potree.js 3.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = global || self, factory(global.Potree = {}));
  5. }(this, (function (exports) { 'use strict';
  6. function mobileVersion(e, t) {
  7. //ios的版本
  8. var i = window.navigator.userAgent,
  9. n = i.match(e);
  10. return (
  11. (n = n ? n[1].split(t) : []),
  12. {
  13. major: parseInt(n[0]) || 0,
  14. minor: parseInt(n[1]) || 0,
  15. patch: parseInt(n[2]) || 0,
  16. }
  17. )
  18. }
  19. var browser = {
  20. isFullscreen: function() {
  21. return (
  22. document.fullscreenElement ||
  23. document.mozFullscreenElement ||
  24. document.mozFullScreenElement ||
  25. document.webkitFullscreenElement ||
  26. document.msFullscreenElement
  27. )
  28. },
  29. supportsFullscreen: function() {
  30. return (
  31. document.fullscreenEnabled ||
  32. document.mozFullscreenEnabled ||
  33. document.mozFullScreenEnabled ||
  34. document.webkitFullscreenEnabled ||
  35. document.msFullscreenEnabled
  36. )
  37. },
  38. isPointerLocked: function() {
  39. return (
  40. document.pointerLockElement ||
  41. document.mozPointerLockElement ||
  42. document.webkitPointerLockElement
  43. )
  44. },
  45. requestFullscreen: function(dom, t) {
  46. dom.requestFullscreen ?
  47. dom.requestFullscreen() :
  48. dom.mozRequestFullScreen ?
  49. dom.mozRequestFullScreen() :
  50. dom.webkitRequestFullscreen ?
  51. dom.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT) :
  52. dom.msRequestFullscreen && dom.msRequestFullscreen(),
  53. t &&
  54. $(document).on(
  55. "fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange",
  56. browser.requestPointerLock
  57. );
  58. },
  59. requestPointerLock: function() {
  60. var e;
  61. if (document.fullscreenElement) e = document.fullscreenElement();
  62. else if (document.mozFullscreenElement) e = document.mozFullscreenElement();
  63. else if (document.mozFullScreenElement) e = document.mozFullScreenElement();
  64. else {
  65. if (!document.webkitFullscreenElement) return
  66. e = document.webkitFullscreenElement();
  67. };
  68. (e.requestPointerLock =
  69. e.requestPointerLock || e.mozRequestPointerLock || e.webkitRequestPointerLock),
  70. e.requestPointerLock(),
  71. $(document).off(
  72. "fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange",
  73. this
  74. );
  75. },
  76. exitPointerLock: function() {
  77. ;
  78. (document.exitPointerLock =
  79. document.exitPointerLock ||
  80. document.mozExitPointerLock ||
  81. document.webkitExitPointerLock),
  82. document.exitPointerLock();
  83. },
  84. exitFullscreen: function() {
  85. document.exitFullscreen ?
  86. document.exitFullscreen() :
  87. document.msExitFullscreen ?
  88. document.msExitFullscreen() :
  89. document.mozCancelFullScreen ?
  90. document.mozCancelFullScreen() :
  91. document.webkitExitFullscreen && document.webkitExitFullscreen();
  92. },
  93. details: function() {
  94. var e = navigator.userAgent.match("(Firefox|Chrome|Safari)/([\\d]+)");
  95. return e ?
  96. {
  97. name: e[1],
  98. version: parseInt(e[2]),
  99. platform: navigator.platform,
  100. } : {}
  101. },
  102. is: function(e) {
  103. return this.details() && this.details().name === e
  104. },
  105. inIframe: function() {
  106. return window.parent !== window
  107. },
  108. aspectRatio: function($elem) {
  109. $elem = $elem || $("#player");
  110. var e = $elem.width() / $elem.height();
  111. return isFinite(e) ? e : 0
  112. },
  113. userAgent: function() {
  114. return window.navigator.userAgent
  115. },
  116. isMobile: function() {
  117. var e = navigator.userAgent || navigator.vendor || window.opera;
  118. return (
  119. /(android|bb\d+|meego).+mobile|android|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(
  120. e
  121. ) ||
  122. /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(
  123. e.substr(0, 4)
  124. )
  125. )
  126. },
  127. isLandscape: function() {
  128. return this.isMobile && this.aspectRatio() > 1
  129. },
  130. isSmallScreen: function() {
  131. var e = screen.width / window.devicePixelRatio;
  132. return e < 240
  133. },
  134. detectIE: function() {
  135. var e = window.navigator.userAgent,
  136. t = e.indexOf("MSIE ");
  137. return t !== -1 || !!navigator.userAgent.match(/Trident.*rv\:11\./)
  138. },
  139. detectSafari: function() {
  140. var e = window.navigator.userAgent,
  141. t = e.indexOf("Safari");
  142. return t !== -1 && !this.detectOpera() && !this.detectChrome() //xzw add detectOpera
  143. },
  144. detectFirefox: function() {
  145. var e = window.navigator.userAgent;
  146. return e.indexOf("Firefox") !== -1
  147. },
  148. detectChrome: function() {
  149. var e = window.navigator.userAgent;
  150. return e.indexOf("Chrome") !== -1 && !this.detectOpera()
  151. },
  152. detectOpera: function() {
  153. var e = window.navigator.userAgent;
  154. return e.indexOf("OPR") !== -1
  155. },
  156. detectIOS: function() {
  157. return this.detectIPhone() || this.detectIPad() || this.detectIPod()
  158. },
  159. detectIPad: function() {
  160. var e = window.navigator.userAgent,
  161. t = /iPad/;
  162. return t.test(e)
  163. },
  164. detectIPod: function() {
  165. var e = window.navigator.userAgent,
  166. t = /iPod/;
  167. return t.test(e)
  168. },
  169. detectIPhone: function() {
  170. var e = window.navigator.userAgent,
  171. t = /iPhone/;
  172. return t.test(e)
  173. },
  174. detectAndroid: function() {
  175. var e = window.navigator.userAgent;
  176. return e.indexOf("Android") !== -1
  177. },
  178. detectAndroidMobile: function() {
  179. var e = window.navigator.userAgent;
  180. return this.detectAndroid() && e.indexOf("Mobile") !== -1
  181. },
  182. detectSamsungNative: function() {
  183. var e = window.navigator.userAgent;
  184. return (
  185. e.indexOf("SM-G900H") !== -1 ||
  186. e.indexOf("GT-I9500") !== -1 ||
  187. e.indexOf("SM-N900") !== -1
  188. )
  189. },
  190. detectSamsungS6: function() {
  191. var e = window.navigator.userAgent;
  192. return e.indexOf("SM-G92") !== -1
  193. },
  194. /************************************************************徐世廷*************************************************************/
  195. detectHUAWEI5X: function() {
  196. return -1 !== window.navigator.userAgent.indexOf("KIW-TL00H")
  197. },
  198. /*******************************************************************************************************************************/
  199. detectWebVR: function() {
  200. return !(!window.navigator.getVRDisplays || !window.VRDisplay)
  201. },
  202. getVRDisplay: function() {
  203. var e = $.Deferred();
  204. return this.detectWebVR() ?
  205. (navigator.getVRDisplays().then(function(t) {
  206. t.length >= 1 && e.resolve(t[0]), e.reject(null);
  207. }),
  208. e) :
  209. e.reject(null)
  210. },
  211. iosVersion: function() {
  212. if (!this.detectIOS()) throw new DeviceMismatchException("Did not detect an iDevice")
  213. var e = /((?:\d+\_?){1,3}) like Mac OS/,
  214. t = "_";
  215. return mobileVersion(e, t)
  216. },
  217. androidVersion: function() {
  218. if (!this.detectAndroid())
  219. throw new DeviceMismatchException("Did not detect an Android based device")
  220. var e = /Android ((?:\d+\.?){1,3})/,
  221. t = ".";
  222. return mobileVersion(e, t)
  223. },
  224. valueFromCookie: function(e, t) {
  225. var i = new RegExp(e + "=([0-9a-f]+)(; ?|$)").exec(document.cookie);
  226. if (!i) return t
  227. var n = i[1];
  228. return "boolean" == typeof t ?
  229. "true" === n || "1" === n :
  230. "number" == typeof t ?
  231. parseFloat(n) :
  232. n
  233. },
  234. valueFromHash: function(e, t) {
  235. var i = new RegExp("[#&?]" + e + "=([^#&?]*)"),
  236. n = i.exec(window.location.href);
  237. if (!n) return t
  238. var r = n[1];
  239. return "boolean" == typeof t ?
  240. "true" === r || "1" === r :
  241. "number" == typeof t ?
  242. parseFloat(r) :
  243. window.decodeURIComponent(r)
  244. },
  245. //-------许钟文:-------------------------------------------------
  246. getProjectNum: function() {
  247. //获取场景projectNum
  248. if (window.__ProjectNum && window.__ProjectNum != "__ProjectNum__") {
  249. return window.__ProjectNum
  250. }
  251. var number = window.location.href.substring(window.location.href.indexOf("=") + 1);
  252. if (number.indexOf("&") != -1) {
  253. number = number.substring(0, number.indexOf("&"));
  254. }
  255. if (number.indexOf("#") != -1) {
  256. number = number.substring(0, number.indexOf("#"));
  257. }
  258. return number
  259. },
  260. urlHasValue: function(key, isGetValue) {
  261. // debugger
  262. // if (getValue) { //得到类似n=1 的 1
  263. // var b = window.location.href.substring(window.location.href.indexOf("?") + 1);
  264. // var a = b.indexOf('&' + t + "=");
  265. // if (a > -1) {
  266. // var s = b.substring(a + ('&' + t + "=").length);
  267. // s.indexOf("&") > -1 && (s = s.substring(0, s.indexOf("&")));
  268. // s.indexOf("#") > -1 && (s = s.substring(0, s.indexOf("#")));
  269. // return s;
  270. // } else return false;
  271. // } else return window.location.search.match("&" + t + "|\\?" + t) != null; //window.location.href.substring(window.location.href.indexOf("?") + 1).indexOf('&' + t) > -1;
  272. //const value = window.location.search.match("&" + t + "|\\?" + t)
  273. if (key === "m" && window.__ProjectNum && window.__ProjectNum != "__ProjectNum__") {
  274. return window.__ProjectNum
  275. }
  276. let querys = window.location.search.substr(1).split("&");
  277. if (isGetValue) {
  278. for (let i = 0; i < querys.length; i++) {
  279. let keypair = querys[i].split("=");
  280. if (keypair.length === 2 && keypair[0] === key) {
  281. return keypair[1]
  282. }
  283. }
  284. return ""
  285. } else {
  286. //return window.location.search.match("&" + key + "|\\?" + key) != null 有bug
  287. for (let i = 0; i < querys.length; i++) {
  288. let keypair = querys[i].split("=");
  289. if (keypair[0] == key) {
  290. return true
  291. }
  292. }
  293. return false
  294. }
  295. },
  296. /**
  297. * 获取查询参数的值
  298. * @param {String} key
  299. * @returns String
  300. */
  301. urlQueryValue(key) {
  302. return this.urlHasValue(key, true) || ""
  303. },
  304. /**
  305. * 获取hash参数的值
  306. * @param {String} key
  307. * @returns String
  308. */
  309. urlHashValue(key) {
  310. let querys = window.location.hash.substr(1).replace('/?', '').split("&");
  311. for (let i = 0; i < querys.length; i++) {
  312. let keypair = querys[i].split("=");
  313. if (keypair.length === 2 && keypair[0] === key) {
  314. return keypair[1]
  315. }
  316. }
  317. return ""
  318. },
  319. /**
  320. * 判断是否存在hash
  321. * @param {String} key
  322. * @returns Boolean
  323. */
  324. urlIsHasHash(key) {
  325. let querys = window.location.hash.substr(1).replace('/?', '').split("&");
  326. return querys.includes(key)
  327. },
  328. islongPhone: function() {
  329. //是否是刘海全面屏幕 仅仅根据比例判断 - -
  330. //screen.height == 812 && screen.width == 375)
  331. var r = screen.height / screen.width; //可能横屏
  332. return this.isMobile() && (r > 1.99 || r < 0.502512) //18/9=2.165 //???
  333. },
  334. detectWeixin: function() {
  335. //微信 包括PC的微信
  336. return window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger"
  337. },
  338. detectWeixinMiniProgram: function() {
  339. return window.navigator.userAgent.match("miniProgram")
  340. },
  341. detectEdge: function() {
  342. return window.navigator.userAgent.indexOf("Edge") > -1
  343. },
  344. detectApp: function() {
  345. return this.urlHasValue("app")
  346. },
  347. /**
  348. * 判断标签页是否切换状态
  349. */
  350. isTabHidden: function() {
  351. var prefixes = ["webkit", "moz", "ms", "o"];
  352. if ("hidden" in document) return document.hidden
  353. for (var i = 0; i < prefixes.length; i++) {
  354. if (prefixes[i] + "Hidden" in document) return document[prefixes[i] + "Hidden"]
  355. }
  356. return false
  357. },
  358. };
  359. //xzw add
  360. const config$1 = {//配置参数 不可修改
  361. displayMode:{
  362. showPointCloud:{
  363. atPano:{
  364. showPoint : true,
  365. showSkybox: false,
  366. pointUsePanoTex : false
  367. },
  368. transition:{
  369. showPoint: true,
  370. showSkybox: false,
  371. pointUsePanoTex: false
  372. },
  373. canLeavePano: true //是否能离开pano位置
  374. },
  375. showPanos:{
  376. atPano:{
  377. showPoint : false,
  378. showSkybox: true,
  379. pointUsePanoTex : false
  380. },
  381. transition:{
  382. //showPoint: true,
  383. showSkybox: true,
  384. //pointUsePanoTex: true //是否使用全景贴图
  385. },
  386. canLeavePano: false
  387. },
  388. showBoth:{
  389. atPano:{
  390. showPoint : true,
  391. showSkybox: true,
  392. pointUsePanoTex : false //?
  393. },
  394. transition:{
  395. showPoint: true,
  396. showSkybox: true,
  397. pointUsePanoTex: true
  398. },
  399. canLeavePano: true //是否能离开pano位置 离开后自动变为showPointCloud
  400. },
  401. //test:
  402. pointUsePanoTex:{ //---静止时调点云
  403. atPano:{
  404. showPoint : true,
  405. showSkybox: false,
  406. pointUsePanoTex : true
  407. },
  408. transition:{
  409. showPoint: true,
  410. showSkybox: true,
  411. pointUsePanoTex: true //是否使用全景贴图
  412. },
  413. canLeavePano: false
  414. },
  415. },
  416. urls:{
  417. //localTextures:'../resources/textures/',
  418. prefix: 'https://laser-oss.4dkankan.com',//oss
  419. prefix2: 'https://testlaser.4dkankan.com',
  420. prefix3: 'https://4dkk.4dage.com',
  421. prefix4: 'https://uat-laser.4dkankan.com/',//test.4dkankan
  422. },
  423. /* transitionsTime:{
  424. flyTime : 1000 // 毫秒/米
  425. panoToPano: 1000,
  426. flyIn:1000,
  427. flyOut:1000,
  428. } */
  429. transitionsTime:{
  430. flyMinTime : 500 /* * 3 */, // 毫秒/米
  431. flytimeDistanceMultiplier: 150/* * 3 */,
  432. panoToPanoMax: 2000/* * 3 */,
  433. flyIn:1000,
  434. flyOut:1000
  435. }
  436. ,
  437. moveSpeedAdujust : 0.5 //越小越慢
  438. ,
  439. view:{
  440. fov:70, //navvis:50
  441. near:0.1,
  442. far: 10000,
  443. },
  444. map:{//mapViewer
  445. mapHeight : -1000,//要比点云低。最低
  446. cameraHeight : 1000, //最高 ,注意(如sitemodel)其他的物体不能超过这个高度
  447. },
  448. pointDensity:{
  449. magnifier:{
  450. maxLevelPercent: 1,
  451. pointBudget : 8*1000*1000,
  452. },
  453. panorama:{//显示全景时的漫游。因为点只能显示1个像素的大小,所以必须很密集,但又要限制点的数量
  454. maxLevelPercent: 0.6,
  455. pointBudget : /* 4*1000*1000// */browser.isMobile() ? 0.1*1000*1000 : 0.4*1000*1000, //点云总最大数
  456. },
  457. fourViewports:{//分四屏时防止卡顿
  458. maxLevelPercent: 0.4,
  459. pointBudget :1*1000*1000, // 只要限制这个就足够 (为什么分屏focus区域不同会闪烁,navvis不会)(navvis:maxLevel:5,pointBudget:1*1000*1000)
  460. },
  461. fourViewportsMain:{//分四屏时防止卡顿
  462. maxLevelPercent: 0.8,
  463. pointBudget :1*1000*1000, // 只要限制这个就足够 (为什么分屏focus区域不同会闪烁,navvis不会)(navvis:maxLevel:5,pointBudget:1*1000*1000)
  464. }
  465. ,
  466. panoEdit:{
  467. maxLevelPercent: 1, //在远处时由于pointBudget限制而展示稀疏,凑近时就变为最高质量了
  468. pointBudget :1*1000*1000, //避免卡顿
  469. },
  470. low:{//highPerformance
  471. maxLevelPercent: 0.4, //最小为0
  472. percentByUser:true, //如果用户定义了percent,使用用户的
  473. pointBudget : 1*1000*1000,
  474. },
  475. middle:{//balanced //不同场景相同级别所产生的numVisibleNodes和numVisiblePoints不同,如果分层比较细,可能要到level8才能看清,那么level5看到的点就很大且很少,如隧道t-e2Kb2iU
  476. maxLevelPercent: 0.7,
  477. percentByUser:true,
  478. pointBudget:browser.isMobile() ? 4*1000*1000 : 2*1000*1000,
  479. },
  480. high:{//highQuality
  481. maxLevelPercent: 1,
  482. percentByUser:true,
  483. pointBudget:browser.isMobile() ? 8*1000*1000 : 4*1000*1000,
  484. }
  485. //browser.isMobile() 时要不要限制下pointBudget,还是让用户自己调低质量?
  486. //minNodeSize?
  487. //数值由testLevelSteps得来,其中nodeMaxLevel为2时,low和middle的都是1,如果真有这么低的点云就单独处理下。
  488. //多个viewport尽量保证pointBudget一样,或者pointBudget不能太低于所需,否则会反复加载了又清除
  489. },
  490. clip:{
  491. color: '#FFC266', //map
  492. },
  493. panoFieldRadius : 10, //当前位置多远范围内可以切全景模式
  494. measure:{
  495. color:'#00C8AF',
  496. default:{
  497. color:"#64C8BB",//"#00c7b2",
  498. opacity:0.7
  499. },
  500. highlight:{
  501. color:'#00C8AF',//"#00c7b2",
  502. opacity:1
  503. },
  504. guide:{
  505. color:'#FFFFFF',
  506. opacity:1
  507. }
  508. ,
  509. backColor:'#333333',
  510. lineWidth: 4,
  511. textColor: "#FFFFFF"
  512. },
  513. material:{//初始化
  514. pointSize: 0.1,
  515. realPointSize : 0.1,//实际上的ui滑动条默认大小(兼容旧的版本)
  516. minSize: 0.1,
  517. maxSize: 10000,
  518. pointSizeType: 'ATTENUATED', //'ADAPTIVE'//'ADAPTIVE' \ FIXED //ADAPTIVE的在小房间里大小会不太匹配,但在远景似乎更好
  519. /*
  520. ATTENUATED : 衰减 真实大小,靠近时感觉是点云一点点变多,缝隙变小
  521. ADAPTIVE: 自适应 大小根据level变化,越高越小。靠近时感觉点云由大慢慢细分成小份。这个感觉更佳但是navvis为何不用这个
  522. */
  523. absolutePanoramaSize: 1.3 ,//全景漫游时的size 是fixed的模式
  524. //sizeAtPanoRtEDL : 2000,
  525. pointColor:'#ffffff',
  526. //sizeAddAtPanoRtEDL : 0.5, //全景模式静止时的size
  527. //ADAPTIVE : 字会失真扭曲
  528. //'ATTENUATED' 往旁边看有缝隙、点在浮动
  529. //navvis的shader在哪里 为什么不会抖动
  530. }
  531. ,
  532. renderLayers:{//渲染层,方便分批渲染管理,替代scene的创建。数字不代表顺序。(数字不能太大)
  533. bg: 20,
  534. bg2: 21,
  535. skybox: 1,
  536. pointcloud: 11,
  537. sceneObjects:0,//default
  538. model : 2,
  539. measure:4,
  540. magnifier:5,
  541. magnifierContent:16,
  542. volume:6,
  543. transformationTool:7,
  544. map:8,
  545. mapObjects:9,//default
  546. bothMapAndScene: 3,
  547. siteModeOnlyMapVisi:12,//只能mapViewer可见
  548. siteModelMapUnvisi:13,//只有mapViewer不可见
  549. siteModeSideVisi:14,//只有侧面可见
  550. },
  551. renderOrders:{ //会影响到绘制、pick时的顺序。
  552. model:10
  553. },
  554. siteModel:{
  555. names:{
  556. 'building': '建筑',
  557. 'floor':'楼层',
  558. 'room':'房间'
  559. },
  560. floorHeightDefault: 5,//一层楼的高度
  561. },
  562. panosEdit:{
  563. },
  564. tiling: {
  565. panoPreRenderRepeatDelay: 2500,
  566. panoPreRenderDelay: 500,
  567. preRenderTourPanos: browser.valueFromHash("tileprerender", 0),
  568. tilingFlagNames: ["usetiles", "tiles"],
  569. maxNavPanoQuality: browser.valueFromHash("maxtileq", null),
  570. maxZoomPanoQuality: browser.valueFromHash("maxztileq", null),
  571. overlayStyle: browser.valueFromHash("tileoverlay", 0),
  572. uploadIntervalDelay: browser.valueFromHash("tileupdelay", 10),
  573. initialIntervalDelay: browser.valueFromHash("itiledelay", 0),
  574. maxNonBaseUploadsPerFrame: browser.valueFromHash("maxnbtpf", 2),
  575. maxBaseUploadsPerFrame: browser.valueFromHash("maxbtpf", 6),
  576. customCompression: browser.valueFromHash("tilecustcomp", 0),
  577. mobileHighQualityOverride: !1,
  578. allowUltraHighResolution: !0
  579. },
  580. navigation: {
  581. panoScores: !1,
  582. mouseDirection: !0,
  583. filterStrictness: .75,
  584. angleFactor: -30,
  585. directionFactor: 10,
  586. distanceFactor: -1,
  587. optionalityFactor: 3
  588. }
  589. ,
  590. axis : { 'x':{color:'#d0021b'/* 'red' */}, 'y':{ color:'#86c542' /* 'green' */}, 'z': {color:'#3399c8' /* 'blue' */}},
  591. highQualityMaxZoom: 2,
  592. ultraHighQualityMaxZoom: 3,
  593. clickMaxDragDis:5,
  594. clickMaxPressTime:500, //ms
  595. doubleClickTime:200,//双击间隔时间
  596. background: '#232323',
  597. mapBG:'#F5F5F5', //地图的clearColor
  598. colors: { //from navvis
  599. red: [213,0,0],
  600. pink: [197,17,98],
  601. purple: [170,0,255],
  602. "deep purple": [98,0,234],
  603. blue: [ 41,98,255],
  604. "light blue": [ 0,145,234],
  605. cyan: [ 0,184,212],
  606. teal: [ 0,191,165],
  607. green: [0,200,83],
  608. "light green": [ 100,221,23],
  609. lime: [ 174,234,0],
  610. yellow: [ 255,214,0],
  611. amber: [ 255,171,0],
  612. orange: [ 255,109,0],
  613. "deep orange": [ 255,61,0],
  614. },
  615. };
  616. config$1.OrthoCameraLimit = {
  617. standard:{
  618. zoom:{min:0.001, max:500}, //如果camera缩太小,地图会因为数字边界问题而扭曲
  619. posBound:{
  620. min: {x:-1e5, y:-1e5,z: config$1.map.cameraHeight},
  621. max: {x:1e5, y:1e5, z:1 / 0 }
  622. }
  623. },
  624. expand:{ //范围再大些,用于编辑空间模型等(但是万一中心点靠近地图边缘的话,就很容易扭曲了)
  625. zoom:{min:0.0004, max:100}, //如果camera缩太小,地图会因为数字边界问题而扭曲
  626. posBound:{
  627. min: {x:-5000000, y:-1000000,z:config$1.map.cameraHeight},
  628. max: {x:5000000, y:1000000, z:1 / 0 }
  629. }//40075017
  630. }
  631. };
  632. /* 显示模式:
  633. 1只显示点云: 滚轮为前进后退,方向键可以行走。进入漫游点时自动变为混合(这样全景可以弥补缝隙),过渡时只显示点云。
  634. 2只显示全景: 不能任意行走。 过渡时显示贴图材质非edl的点云(否则有折痕不贴合)。
  635. 3混合:都显示。 不能任意行走。过渡时显示贴图材质非edl的点云(因为只显示点云的话不太美,点云很碎,不细腻)
  636. */
  637. window.testLevelSteps = function(steps){//[0.4,0.7,1]
  638. if(!steps){
  639. let s = Potree.config.pointDensity;
  640. steps = [s.low.maxLevelPercent, s.middle.maxLevelPercent, s.high.maxLevelPercent, ];
  641. }
  642. let max = 1;
  643. while(++max<=12){
  644. let r1 = steps.map(e=>e * max);
  645. let r2 = steps.map(e=>Math.round(e * max));
  646. console.log(`当nodeMaxLevel为${max}时,每一级的level分别为${r2}, (小数:${r1})`);
  647. }
  648. console.log('请检查每一层的三个level是否有重复');
  649. };
  650. function getPrefix(){
  651. let u = window.location.href.split('//');
  652. let v = u[1].split('/');
  653. return v[0]
  654. }
  655. let settings = {//设置 可修改
  656. editType : '',
  657. number: '', //场景序号
  658. originDatasetId:'',//场景原本的数据集id,应该就是数据集第一个吧
  659. isOfficial:false,
  660. webSite:'testdata',//'data', //不同环境对应的静态文件的地址不同
  661. isLocal:false, //是否本地 局域网版本
  662. libsUrl:'../libs/',
  663. displayMode:'',
  664. isTest :browser.urlHasValue('test'),
  665. prefix: getPrefix(),
  666. pointDensity: '', UserPointDensity:'',//pointDensity会随着进入不同的模块而自动改变,UserPointDensity记录了用户的设置
  667. UserDensityPercent:null,//点云密度百分比
  668. ifShowMarker:true,//显示漫游点
  669. floorplanType:{},//平面图类型 'default' | 'diy' 不同数据集不同{datasetId:...}
  670. floorplanEnable:false,
  671. floorplanEnables:{},
  672. floorplanRequests:{},//开始加载了的
  673. mapEnable:true,//地图区域是否加载地图
  674. cameraFar : config$1.view.far, //相机最远范围 1-300
  675. //limitFar: true, //是否使用setting的cameraFar来限制(如在点云裁剪时为false)
  676. showPanoMesh:false, //显示小球,
  677. dblToFocusPoint:false,//调试时如果需要双击飞向某个点云的点,就打开。此时不在漫游点的话单击将无法漫游。//因和单击漫游冲突
  678. unableNavigate : false,//进入如裁剪界面时 禁止漫游
  679. sizeFitToLevel: false,//当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2
  680. zoom:{
  681. enabled : true,
  682. min:1,
  683. max: config$1.highQualityMaxZoom,
  684. activationThreshold: 1.1,
  685. },
  686. navConstantly:true,
  687. navTileClass: browser.isMobile() ? '1k' : '2k', //默认加载到
  688. tileClass:'4k', //最高可达
  689. /* loadTilesWhenUnfocus:false, //页面unfocus时也仍在加载tiles
  690. loadPointsWhenUnfocus:true, //页面unfocus时也仍在加载点云 */
  691. //initialShowPano:true
  692. drawEntityData: false,
  693. zoomFromPointert:{//定点缩放(包括点云模式、全景模式、地图)
  694. whenPanos:true,
  695. whenPointCloud:true,
  696. map:true,
  697. },
  698. rotAroundPoint:true,//点云模式是否能绕intersectPoint旋转
  699. tourTestCameraMove:false, //测试镜头时,不移动真实的镜头, 只移动frustum
  700. cameraAniSmoothRatio : 20, //镜头动画平滑系数,越高越平滑
  701. urls : $.extend({}, config$1.urls),
  702. useDepthTex: true,//使用深度贴图,但不代表一定有(得到的intersect更快速准确和稳定) SS-t-7DUfWAUZ3V
  703. //matUseDepth:false,
  704. //panoEdit:
  705. datasetsPanos:{},
  706. //mergeModel:
  707. boundAddObjs:false,
  708. intersectOnObjs:false,
  709. intersectWhenHover:true,
  710. };
  711. //JSON.parse(localStorage.getItem('setting'))
  712. settings.isLocalhost = settings.prefix.includes('localhost');
  713. // threejs.org/license
  714. const REVISION = '124';
  715. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  716. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  717. const CullFaceNone = 0;
  718. const CullFaceBack = 1;
  719. const CullFaceFront = 2;
  720. const CullFaceFrontBack = 3;
  721. const BasicShadowMap = 0;
  722. const PCFShadowMap = 1;
  723. const PCFSoftShadowMap = 2;
  724. const VSMShadowMap = 3;
  725. const FrontSide = 0;
  726. const BackSide = 1;
  727. const DoubleSide = 2;
  728. const FlatShading = 1;
  729. const SmoothShading = 2;
  730. const NoBlending = 0;
  731. const NormalBlending = 1;
  732. const AdditiveBlending = 2;
  733. const SubtractiveBlending = 3;
  734. const MultiplyBlending = 4;
  735. const CustomBlending = 5;
  736. const AddEquation = 100;
  737. const SubtractEquation = 101;
  738. const ReverseSubtractEquation = 102;
  739. const MinEquation = 103;
  740. const MaxEquation = 104;
  741. const ZeroFactor = 200;
  742. const OneFactor = 201;
  743. const SrcColorFactor = 202;
  744. const OneMinusSrcColorFactor = 203;
  745. const SrcAlphaFactor = 204;
  746. const OneMinusSrcAlphaFactor = 205;
  747. const DstAlphaFactor = 206;
  748. const OneMinusDstAlphaFactor = 207;
  749. const DstColorFactor = 208;
  750. const OneMinusDstColorFactor = 209;
  751. const SrcAlphaSaturateFactor = 210;
  752. const NeverDepth = 0;
  753. const AlwaysDepth = 1;
  754. const LessDepth = 2;
  755. const LessEqualDepth = 3;
  756. const EqualDepth = 4;
  757. const GreaterEqualDepth = 5;
  758. const GreaterDepth = 6;
  759. const NotEqualDepth = 7;
  760. const MultiplyOperation = 0;
  761. const MixOperation = 1;
  762. const AddOperation = 2;
  763. const NoToneMapping = 0;
  764. const LinearToneMapping = 1;
  765. const ReinhardToneMapping = 2;
  766. const CineonToneMapping = 3;
  767. const ACESFilmicToneMapping = 4;
  768. const CustomToneMapping = 5;
  769. const UVMapping = 300;
  770. const CubeReflectionMapping = 301;
  771. const CubeRefractionMapping = 302;
  772. const EquirectangularReflectionMapping = 303;
  773. const EquirectangularRefractionMapping = 304;
  774. const CubeUVReflectionMapping = 306;
  775. const CubeUVRefractionMapping = 307;
  776. const RepeatWrapping = 1000;
  777. const ClampToEdgeWrapping = 1001;
  778. const MirroredRepeatWrapping = 1002;
  779. const NearestFilter = 1003;
  780. const NearestMipmapNearestFilter = 1004;
  781. const NearestMipMapNearestFilter = 1004;
  782. const NearestMipmapLinearFilter = 1005;
  783. const NearestMipMapLinearFilter = 1005;
  784. const LinearFilter = 1006;
  785. const LinearMipmapNearestFilter = 1007;
  786. const LinearMipMapNearestFilter = 1007;
  787. const LinearMipmapLinearFilter = 1008;
  788. const LinearMipMapLinearFilter = 1008;
  789. const UnsignedByteType = 1009;
  790. const ByteType = 1010;
  791. const ShortType = 1011;
  792. const UnsignedShortType = 1012;
  793. const IntType = 1013;
  794. const UnsignedIntType = 1014;
  795. const FloatType = 1015;
  796. const HalfFloatType = 1016;
  797. const UnsignedShort4444Type = 1017;
  798. const UnsignedShort5551Type = 1018;
  799. const UnsignedShort565Type = 1019;
  800. const UnsignedInt248Type$1 = 1020;
  801. const AlphaFormat = 1021;
  802. const RGBFormat = 1022;
  803. const RGBAFormat = 1023;
  804. const LuminanceFormat = 1024;
  805. const LuminanceAlphaFormat = 1025;
  806. const RGBEFormat = RGBAFormat;
  807. const DepthFormat = 1026;
  808. const DepthStencilFormat = 1027;
  809. const RedFormat = 1028;
  810. const RedIntegerFormat = 1029;
  811. const RGFormat = 1030;
  812. const RGIntegerFormat = 1031;
  813. const RGBIntegerFormat = 1032;
  814. const RGBAIntegerFormat = 1033;
  815. const RGB_S3TC_DXT1_Format = 33776;
  816. const RGBA_S3TC_DXT1_Format$1 = 33777;
  817. const RGBA_S3TC_DXT3_Format = 33778;
  818. const RGBA_S3TC_DXT5_Format$1 = 33779;
  819. const RGB_PVRTC_4BPPV1_Format = 35840;
  820. const RGB_PVRTC_2BPPV1_Format = 35841;
  821. const RGBA_PVRTC_4BPPV1_Format = 35842;
  822. const RGBA_PVRTC_2BPPV1_Format = 35843;
  823. const RGB_ETC1_Format = 36196;
  824. const RGB_ETC2_Format = 37492;
  825. const RGBA_ETC2_EAC_Format = 37496;
  826. const RGBA_ASTC_4x4_Format = 37808;
  827. const RGBA_ASTC_5x4_Format = 37809;
  828. const RGBA_ASTC_5x5_Format = 37810;
  829. const RGBA_ASTC_6x5_Format = 37811;
  830. const RGBA_ASTC_6x6_Format = 37812;
  831. const RGBA_ASTC_8x5_Format = 37813;
  832. const RGBA_ASTC_8x6_Format = 37814;
  833. const RGBA_ASTC_8x8_Format = 37815;
  834. const RGBA_ASTC_10x5_Format = 37816;
  835. const RGBA_ASTC_10x6_Format = 37817;
  836. const RGBA_ASTC_10x8_Format = 37818;
  837. const RGBA_ASTC_10x10_Format = 37819;
  838. const RGBA_ASTC_12x10_Format = 37820;
  839. const RGBA_ASTC_12x12_Format = 37821;
  840. const RGBA_BPTC_Format = 36492;
  841. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  842. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  843. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  844. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  845. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  846. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  847. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  848. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  849. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  850. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  851. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  852. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  853. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  854. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  855. const LoopOnce = 2200;
  856. const LoopRepeat = 2201;
  857. const LoopPingPong = 2202;
  858. const InterpolateDiscrete = 2300;
  859. const InterpolateLinear = 2301;
  860. const InterpolateSmooth = 2302;
  861. const ZeroCurvatureEnding = 2400;
  862. const ZeroSlopeEnding = 2401;
  863. const WrapAroundEnding = 2402;
  864. const NormalAnimationBlendMode = 2500;
  865. const AdditiveAnimationBlendMode = 2501;
  866. const TrianglesDrawMode = 0;
  867. const TriangleStripDrawMode = 1;
  868. const TriangleFanDrawMode = 2;
  869. const LinearEncoding = 3000;
  870. const sRGBEncoding = 3001;
  871. const GammaEncoding = 3007;
  872. const RGBEEncoding = 3002;
  873. const LogLuvEncoding = 3003;
  874. const RGBM7Encoding = 3004;
  875. const RGBM16Encoding = 3005;
  876. const RGBDEncoding = 3006;
  877. const BasicDepthPacking = 3200;
  878. const RGBADepthPacking = 3201;
  879. const TangentSpaceNormalMap = 0;
  880. const ObjectSpaceNormalMap = 1;
  881. const ZeroStencilOp = 0;
  882. const KeepStencilOp = 7680;
  883. const ReplaceStencilOp = 7681;
  884. const IncrementStencilOp = 7682;
  885. const DecrementStencilOp = 7683;
  886. const IncrementWrapStencilOp = 34055;
  887. const DecrementWrapStencilOp = 34056;
  888. const InvertStencilOp = 5386;
  889. const NeverStencilFunc = 512;
  890. const LessStencilFunc = 513;
  891. const EqualStencilFunc = 514;
  892. const LessEqualStencilFunc = 515;
  893. const GreaterStencilFunc = 516;
  894. const NotEqualStencilFunc = 517;
  895. const GreaterEqualStencilFunc = 518;
  896. const AlwaysStencilFunc = 519;
  897. const StaticDrawUsage = 35044;
  898. const DynamicDrawUsage = 35048;
  899. const StreamDrawUsage = 35040;
  900. const StaticReadUsage = 35045;
  901. const DynamicReadUsage = 35049;
  902. const StreamReadUsage = 35041;
  903. const StaticCopyUsage = 35046;
  904. const DynamicCopyUsage = 35050;
  905. const StreamCopyUsage = 35042;
  906. const GLSL1 = '100';
  907. const GLSL3 = '300 es';
  908. /**
  909. * https://github.com/mrdoob/eventdispatcher.js/
  910. */
  911. function EventDispatcher() {}
  912. Object.assign( EventDispatcher.prototype, {
  913. addEventListener: function ( type, listener, importance=0 ) {//add importance
  914. if ( this._listeners === undefined ) this._listeners = {};
  915. const listeners = this._listeners;
  916. if ( listeners[ type ] === undefined ) {
  917. listeners[ type ] = [];
  918. }
  919. if ( !listeners[ type ].some(e=>e.listener == listener ) ) {
  920. //listeners[ type ].push( listener );
  921. listeners[type].push({ listener, importance});
  922. listeners[type] = listeners[type].sort((e,a)=> a.importance - e.importance);//add
  923. }
  924. },
  925. hasEventListener: function ( type, listener ) {
  926. if ( this._listeners === undefined ) return false;
  927. const listeners = this._listeners;
  928. return listeners[ type ] !== undefined && listeners[ type ].some(e=>e.listener == listener )
  929. },
  930. removeEventListener: function ( type, listener ) {
  931. if ( this._listeners === undefined ) return;
  932. const listeners = this._listeners;
  933. const listenerArray = listeners[ type ];
  934. if ( listenerArray !== undefined ) {
  935. /* const index = listenerArray.indexOf( listener );
  936. if ( index !== - 1 ) {
  937. listenerArray.splice( index, 1 );
  938. } */
  939. let item = listenerArray.find(e=>e.listener == listener);
  940. item && listenerArray.splice(listenerArray.indexOf(item), 1);
  941. }
  942. },
  943. removeEventListeners(type){//add
  944. if(this._listeners && this._listeners[type] !== undefined){
  945. delete this._listeners[type];
  946. }
  947. } ,
  948. removeAllListeners(){ //add
  949. this._listeners = {};
  950. },
  951. dispatchEvent: function ( event ) {
  952. if(typeof event == 'string'){//add
  953. event = {type:event};
  954. }
  955. if ( this._listeners === undefined ) return;
  956. const listeners = this._listeners;
  957. const listenerArray = listeners[ event.type ];
  958. if ( listenerArray !== undefined ) {
  959. event.target = this;
  960. // Make a copy, in case listeners are removed while iterating.
  961. for(let {listener} of listenerArray.slice(0)){
  962. let result = listener.call(this, event); //add stopContinue
  963. if(result && result.stopContinue){
  964. break
  965. }
  966. }
  967. }
  968. }
  969. } );
  970. const _lut = [];
  971. for ( let i = 0; i < 256; i ++ ) {
  972. _lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 );
  973. }
  974. let _seed = 1234567;
  975. const MathUtils = {
  976. DEG2RAD: Math.PI / 180,
  977. RAD2DEG: 180 / Math.PI,
  978. generateUUID: function () {
  979. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  980. const d0 = Math.random() * 0xffffffff | 0;
  981. const d1 = Math.random() * 0xffffffff | 0;
  982. const d2 = Math.random() * 0xffffffff | 0;
  983. const d3 = Math.random() * 0xffffffff | 0;
  984. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  985. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  986. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  987. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  988. // .toUpperCase() here flattens concatenated strings to save heap memory space.
  989. return uuid.toUpperCase();
  990. },
  991. clamp: function ( value, min, max ) {
  992. return Math.max( min, Math.min( max, value ) );
  993. },
  994. // compute euclidian modulo of m % n
  995. // https://en.wikipedia.org/wiki/Modulo_operation
  996. euclideanModulo: function ( n, m ) {
  997. return ( ( n % m ) + m ) % m;
  998. },
  999. // Linear mapping from range <a1, a2> to range <b1, b2>
  1000. mapLinear: function ( x, a1, a2, b1, b2 ) {
  1001. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1002. },
  1003. // https://en.wikipedia.org/wiki/Linear_interpolation
  1004. lerp: function ( x, y, t ) {
  1005. return ( 1 - t ) * x + t * y;
  1006. },
  1007. // http://en.wikipedia.org/wiki/Smoothstep
  1008. smoothstep: function ( x, min, max ) {
  1009. if ( x <= min ) return 0;
  1010. if ( x >= max ) return 1;
  1011. x = ( x - min ) / ( max - min );
  1012. return x * x * ( 3 - 2 * x );
  1013. },
  1014. smootherstep: function ( x, min, max ) {
  1015. if ( x <= min ) return 0;
  1016. if ( x >= max ) return 1;
  1017. x = ( x - min ) / ( max - min );
  1018. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1019. },
  1020. // Random integer from <low, high> interval
  1021. randInt: function ( low, high ) {
  1022. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1023. },
  1024. // Random float from <low, high> interval
  1025. randFloat: function ( low, high ) {
  1026. return low + Math.random() * ( high - low );
  1027. },
  1028. // Random float from <-range/2, range/2> interval
  1029. randFloatSpread: function ( range ) {
  1030. return range * ( 0.5 - Math.random() );
  1031. },
  1032. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  1033. seededRandom: function ( s ) {
  1034. if ( s !== undefined ) _seed = s % 2147483647;
  1035. // Park-Miller algorithm
  1036. _seed = _seed * 16807 % 2147483647;
  1037. return ( _seed - 1 ) / 2147483646;
  1038. },
  1039. degToRad: function ( degrees ) {
  1040. return degrees * MathUtils.DEG2RAD;
  1041. },
  1042. radToDeg: function ( radians ) {
  1043. return radians * MathUtils.RAD2DEG;
  1044. },
  1045. isPowerOfTwo: function ( value ) {
  1046. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1047. },
  1048. ceilPowerOfTwo: function ( value ) {
  1049. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1050. },
  1051. floorPowerOfTwo: function ( value ) {
  1052. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1053. },
  1054. setQuaternionFromProperEuler: function ( q, a, b, c, order ) {
  1055. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  1056. // rotations are applied to the axes in the order specified by 'order'
  1057. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  1058. // angles are in radians
  1059. const cos = Math.cos;
  1060. const sin = Math.sin;
  1061. const c2 = cos( b / 2 );
  1062. const s2 = sin( b / 2 );
  1063. const c13 = cos( ( a + c ) / 2 );
  1064. const s13 = sin( ( a + c ) / 2 );
  1065. const c1_3 = cos( ( a - c ) / 2 );
  1066. const s1_3 = sin( ( a - c ) / 2 );
  1067. const c3_1 = cos( ( c - a ) / 2 );
  1068. const s3_1 = sin( ( c - a ) / 2 );
  1069. switch ( order ) {
  1070. case 'XYX':
  1071. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1072. break;
  1073. case 'YZY':
  1074. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1075. break;
  1076. case 'ZXZ':
  1077. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1078. break;
  1079. case 'XZX':
  1080. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1081. break;
  1082. case 'YXY':
  1083. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1084. break;
  1085. case 'ZYZ':
  1086. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1087. break;
  1088. default:
  1089. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  1090. }
  1091. }
  1092. };
  1093. class Vector2$1 {
  1094. constructor( x = 0, y = 0 ) {
  1095. Object.defineProperty( this, 'isVector2', { value: true } );
  1096. this.x = x;
  1097. this.y = y;
  1098. }
  1099. get width() {
  1100. return this.x;
  1101. }
  1102. set width( value ) {
  1103. this.x = value;
  1104. }
  1105. get height() {
  1106. return this.y;
  1107. }
  1108. set height( value ) {
  1109. this.y = value;
  1110. }
  1111. set( x, y ) {
  1112. this.x = x;
  1113. this.y = y;
  1114. return this;
  1115. }
  1116. setScalar( scalar ) {
  1117. this.x = scalar;
  1118. this.y = scalar;
  1119. return this;
  1120. }
  1121. setX( x ) {
  1122. this.x = x;
  1123. return this;
  1124. }
  1125. setY( y ) {
  1126. this.y = y;
  1127. return this;
  1128. }
  1129. setComponent( index, value ) {
  1130. switch ( index ) {
  1131. case 0: this.x = value; break;
  1132. case 1: this.y = value; break;
  1133. default: throw new Error( 'index is out of range: ' + index );
  1134. }
  1135. return this;
  1136. }
  1137. getComponent( index ) {
  1138. switch ( index ) {
  1139. case 0: return this.x;
  1140. case 1: return this.y;
  1141. default: throw new Error( 'index is out of range: ' + index );
  1142. }
  1143. }
  1144. clone() {
  1145. return new this.constructor( this.x, this.y );
  1146. }
  1147. copy( v ) {
  1148. this.x = v.x;
  1149. this.y = v.y;
  1150. return this;
  1151. }
  1152. add( v, w ) {
  1153. if ( w !== undefined ) {
  1154. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1155. return this.addVectors( v, w );
  1156. }
  1157. this.x += v.x;
  1158. this.y += v.y;
  1159. return this;
  1160. }
  1161. addScalar( s ) {
  1162. this.x += s;
  1163. this.y += s;
  1164. return this;
  1165. }
  1166. addVectors( a, b ) {
  1167. this.x = a.x + b.x;
  1168. this.y = a.y + b.y;
  1169. return this;
  1170. }
  1171. addScaledVector( v, s ) {
  1172. this.x += v.x * s;
  1173. this.y += v.y * s;
  1174. return this;
  1175. }
  1176. sub( v, w ) {
  1177. if ( w !== undefined ) {
  1178. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1179. return this.subVectors( v, w );
  1180. }
  1181. this.x -= v.x;
  1182. this.y -= v.y;
  1183. return this;
  1184. }
  1185. subScalar( s ) {
  1186. this.x -= s;
  1187. this.y -= s;
  1188. return this;
  1189. }
  1190. subVectors( a, b ) {
  1191. this.x = a.x - b.x;
  1192. this.y = a.y - b.y;
  1193. return this;
  1194. }
  1195. multiply( v ) {
  1196. this.x *= v.x;
  1197. this.y *= v.y;
  1198. return this;
  1199. }
  1200. multiplyScalar( scalar ) {
  1201. this.x *= scalar;
  1202. this.y *= scalar;
  1203. return this;
  1204. }
  1205. divide( v ) {
  1206. this.x /= v.x;
  1207. this.y /= v.y;
  1208. return this;
  1209. }
  1210. divideScalar( scalar ) {
  1211. return this.multiplyScalar( 1 / scalar );
  1212. }
  1213. applyMatrix3( m ) {
  1214. const x = this.x, y = this.y;
  1215. const e = m.elements;
  1216. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  1217. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  1218. return this;
  1219. }
  1220. min( v ) {
  1221. this.x = Math.min( this.x, v.x );
  1222. this.y = Math.min( this.y, v.y );
  1223. return this;
  1224. }
  1225. max( v ) {
  1226. this.x = Math.max( this.x, v.x );
  1227. this.y = Math.max( this.y, v.y );
  1228. return this;
  1229. }
  1230. clamp( min, max ) {
  1231. // assumes min < max, componentwise
  1232. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1233. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1234. return this;
  1235. }
  1236. clampScalar( minVal, maxVal ) {
  1237. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1238. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1239. return this;
  1240. }
  1241. clampLength( min, max ) {
  1242. const length = this.length();
  1243. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1244. }
  1245. floor() {
  1246. this.x = Math.floor( this.x );
  1247. this.y = Math.floor( this.y );
  1248. return this;
  1249. }
  1250. ceil() {
  1251. this.x = Math.ceil( this.x );
  1252. this.y = Math.ceil( this.y );
  1253. return this;
  1254. }
  1255. round() {
  1256. this.x = Math.round( this.x );
  1257. this.y = Math.round( this.y );
  1258. return this;
  1259. }
  1260. roundToZero() {
  1261. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1262. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1263. return this;
  1264. }
  1265. negate() {
  1266. this.x = - this.x;
  1267. this.y = - this.y;
  1268. return this;
  1269. }
  1270. dot( v ) {
  1271. return this.x * v.x + this.y * v.y;
  1272. }
  1273. cross( v ) {
  1274. return this.x * v.y - this.y * v.x;
  1275. }
  1276. lengthSq() {
  1277. return this.x * this.x + this.y * this.y;
  1278. }
  1279. length() {
  1280. return Math.sqrt( this.x * this.x + this.y * this.y );
  1281. }
  1282. manhattanLength() {
  1283. return Math.abs( this.x ) + Math.abs( this.y );
  1284. }
  1285. normalize() {
  1286. return this.divideScalar( this.length() || 1 );
  1287. }
  1288. angle() {
  1289. // computes the angle in radians with respect to the positive x-axis
  1290. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  1291. return angle;
  1292. }
  1293. distanceTo( v ) {
  1294. return Math.sqrt( this.distanceToSquared( v ) );
  1295. }
  1296. distanceToSquared( v ) {
  1297. const dx = this.x - v.x, dy = this.y - v.y;
  1298. return dx * dx + dy * dy;
  1299. }
  1300. manhattanDistanceTo( v ) {
  1301. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  1302. }
  1303. setLength( length ) {
  1304. return this.normalize().multiplyScalar( length );
  1305. }
  1306. lerp( v, alpha ) {
  1307. this.x += ( v.x - this.x ) * alpha;
  1308. this.y += ( v.y - this.y ) * alpha;
  1309. return this;
  1310. }
  1311. lerpVectors( v1, v2, alpha ) {
  1312. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1313. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1314. return this;
  1315. }
  1316. equals( v ) {
  1317. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  1318. }
  1319. fromArray( array, offset = 0 ) {
  1320. this.x = array[ offset ];
  1321. this.y = array[ offset + 1 ];
  1322. return this;
  1323. }
  1324. toArray( array = [], offset = 0 ) {
  1325. array[ offset ] = this.x;
  1326. array[ offset + 1 ] = this.y;
  1327. return array;
  1328. }
  1329. fromBufferAttribute( attribute, index, offset ) {
  1330. if ( offset !== undefined ) {
  1331. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  1332. }
  1333. this.x = attribute.getX( index );
  1334. this.y = attribute.getY( index );
  1335. return this;
  1336. }
  1337. rotateAround( center, angle ) {
  1338. const c = Math.cos( angle ), s = Math.sin( angle );
  1339. const x = this.x - center.x;
  1340. const y = this.y - center.y;
  1341. this.x = x * c - y * s + center.x;
  1342. this.y = x * s + y * c + center.y;
  1343. return this;
  1344. }
  1345. random() {
  1346. this.x = Math.random();
  1347. this.y = Math.random();
  1348. return this;
  1349. }
  1350. }
  1351. class Matrix3 {
  1352. constructor() {
  1353. Object.defineProperty( this, 'isMatrix3', { value: true } );
  1354. this.elements = [
  1355. 1, 0, 0,
  1356. 0, 1, 0,
  1357. 0, 0, 1
  1358. ];
  1359. if ( arguments.length > 0 ) {
  1360. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  1361. }
  1362. }
  1363. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1364. const te = this.elements;
  1365. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  1366. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  1367. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  1368. return this;
  1369. }
  1370. identity() {
  1371. this.set(
  1372. 1, 0, 0,
  1373. 0, 1, 0,
  1374. 0, 0, 1
  1375. );
  1376. return this;
  1377. }
  1378. clone() {
  1379. return new this.constructor().fromArray( this.elements );
  1380. }
  1381. copy( m ) {
  1382. const te = this.elements;
  1383. const me = m.elements;
  1384. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  1385. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  1386. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  1387. return this;
  1388. }
  1389. extractBasis( xAxis, yAxis, zAxis ) {
  1390. xAxis.setFromMatrix3Column( this, 0 );
  1391. yAxis.setFromMatrix3Column( this, 1 );
  1392. zAxis.setFromMatrix3Column( this, 2 );
  1393. return this;
  1394. }
  1395. setFromMatrix4( m ) {
  1396. const me = m.elements;
  1397. this.set(
  1398. me[ 0 ], me[ 4 ], me[ 8 ],
  1399. me[ 1 ], me[ 5 ], me[ 9 ],
  1400. me[ 2 ], me[ 6 ], me[ 10 ]
  1401. );
  1402. return this;
  1403. }
  1404. multiply( m ) {
  1405. return this.multiplyMatrices( this, m );
  1406. }
  1407. premultiply( m ) {
  1408. return this.multiplyMatrices( m, this );
  1409. }
  1410. multiplyMatrices( a, b ) {
  1411. const ae = a.elements;
  1412. const be = b.elements;
  1413. const te = this.elements;
  1414. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  1415. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  1416. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  1417. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  1418. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  1419. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  1420. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  1421. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  1422. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  1423. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  1424. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  1425. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  1426. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  1427. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  1428. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  1429. return this;
  1430. }
  1431. multiplyScalar( s ) {
  1432. const te = this.elements;
  1433. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  1434. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  1435. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  1436. return this;
  1437. }
  1438. determinant() {
  1439. const te = this.elements;
  1440. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  1441. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  1442. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  1443. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  1444. }
  1445. invert() {
  1446. const te = this.elements,
  1447. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  1448. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  1449. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  1450. t11 = n33 * n22 - n32 * n23,
  1451. t12 = n32 * n13 - n33 * n12,
  1452. t13 = n23 * n12 - n22 * n13,
  1453. det = n11 * t11 + n21 * t12 + n31 * t13;
  1454. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  1455. const detInv = 1 / det;
  1456. te[ 0 ] = t11 * detInv;
  1457. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  1458. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  1459. te[ 3 ] = t12 * detInv;
  1460. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  1461. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  1462. te[ 6 ] = t13 * detInv;
  1463. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  1464. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  1465. return this;
  1466. }
  1467. transpose() {
  1468. let tmp;
  1469. const m = this.elements;
  1470. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  1471. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  1472. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  1473. return this;
  1474. }
  1475. getNormalMatrix( matrix4 ) {
  1476. return this.setFromMatrix4( matrix4 ).copy( this ).invert().transpose();
  1477. }
  1478. transposeIntoArray( r ) {
  1479. const m = this.elements;
  1480. r[ 0 ] = m[ 0 ];
  1481. r[ 1 ] = m[ 3 ];
  1482. r[ 2 ] = m[ 6 ];
  1483. r[ 3 ] = m[ 1 ];
  1484. r[ 4 ] = m[ 4 ];
  1485. r[ 5 ] = m[ 7 ];
  1486. r[ 6 ] = m[ 2 ];
  1487. r[ 7 ] = m[ 5 ];
  1488. r[ 8 ] = m[ 8 ];
  1489. return this;
  1490. }
  1491. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  1492. const c = Math.cos( rotation );
  1493. const s = Math.sin( rotation );
  1494. this.set(
  1495. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  1496. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  1497. 0, 0, 1
  1498. );
  1499. return this;
  1500. }
  1501. scale( sx, sy ) {
  1502. const te = this.elements;
  1503. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  1504. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  1505. return this;
  1506. }
  1507. rotate( theta ) {
  1508. const c = Math.cos( theta );
  1509. const s = Math.sin( theta );
  1510. const te = this.elements;
  1511. const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  1512. const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  1513. te[ 0 ] = c * a11 + s * a21;
  1514. te[ 3 ] = c * a12 + s * a22;
  1515. te[ 6 ] = c * a13 + s * a23;
  1516. te[ 1 ] = - s * a11 + c * a21;
  1517. te[ 4 ] = - s * a12 + c * a22;
  1518. te[ 7 ] = - s * a13 + c * a23;
  1519. return this;
  1520. }
  1521. translate( tx, ty ) {
  1522. const te = this.elements;
  1523. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  1524. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  1525. return this;
  1526. }
  1527. equals( matrix ) {
  1528. const te = this.elements;
  1529. const me = matrix.elements;
  1530. for ( let i = 0; i < 9; i ++ ) {
  1531. if ( te[ i ] !== me[ i ] ) return false;
  1532. }
  1533. return true;
  1534. }
  1535. fromArray( array, offset = 0 ) {
  1536. for ( let i = 0; i < 9; i ++ ) {
  1537. this.elements[ i ] = array[ i + offset ];
  1538. }
  1539. return this;
  1540. }
  1541. toArray( array = [], offset = 0 ) {
  1542. const te = this.elements;
  1543. array[ offset ] = te[ 0 ];
  1544. array[ offset + 1 ] = te[ 1 ];
  1545. array[ offset + 2 ] = te[ 2 ];
  1546. array[ offset + 3 ] = te[ 3 ];
  1547. array[ offset + 4 ] = te[ 4 ];
  1548. array[ offset + 5 ] = te[ 5 ];
  1549. array[ offset + 6 ] = te[ 6 ];
  1550. array[ offset + 7 ] = te[ 7 ];
  1551. array[ offset + 8 ] = te[ 8 ];
  1552. return array;
  1553. }
  1554. }
  1555. let _canvas;
  1556. const ImageUtils = {
  1557. getDataURL: function ( image ) {
  1558. if ( /^data:/i.test( image.src ) ) {
  1559. return image.src;
  1560. }
  1561. if ( typeof HTMLCanvasElement == 'undefined' ) {
  1562. return image.src;
  1563. }
  1564. let canvas;
  1565. if ( image instanceof HTMLCanvasElement ) {
  1566. canvas = image;
  1567. } else {
  1568. if ( _canvas === undefined ) _canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  1569. _canvas.width = image.width;
  1570. _canvas.height = image.height;
  1571. const context = _canvas.getContext( '2d' );
  1572. if ( image instanceof ImageData ) {
  1573. context.putImageData( image, 0, 0 );
  1574. } else {
  1575. context.drawImage( image, 0, 0, image.width, image.height );
  1576. }
  1577. canvas = _canvas;
  1578. }
  1579. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1580. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1581. } else {
  1582. return canvas.toDataURL( 'image/png' );
  1583. }
  1584. }
  1585. };
  1586. let textureId = 0;
  1587. 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 ) {
  1588. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1589. this.uuid = MathUtils.generateUUID();
  1590. this.name = '';
  1591. this.image = image;
  1592. this.mipmaps = [];
  1593. this.mapping = mapping;
  1594. this.wrapS = wrapS;
  1595. this.wrapT = wrapT;
  1596. this.magFilter = magFilter;
  1597. this.minFilter = minFilter;
  1598. this.anisotropy = anisotropy;
  1599. this.format = format;
  1600. this.internalFormat = null;
  1601. this.type = type;
  1602. this.offset = new Vector2$1( 0, 0 );
  1603. this.repeat = new Vector2$1( 1, 1 );
  1604. this.center = new Vector2$1( 0, 0 );
  1605. this.rotation = 0;
  1606. this.matrixAutoUpdate = true;
  1607. this.matrix = new Matrix3();
  1608. this.generateMipmaps = true;
  1609. this.premultiplyAlpha = false;
  1610. this.flipY = true;
  1611. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1612. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1613. //
  1614. // Also changing the encoding after already used by a Material will not automatically make the Material
  1615. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1616. this.encoding = encoding;
  1617. this.version = 0;
  1618. this.onUpdate = null;
  1619. }
  1620. Texture.DEFAULT_IMAGE = undefined;
  1621. Texture.DEFAULT_MAPPING = UVMapping;
  1622. Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  1623. constructor: Texture,
  1624. isTexture: true,
  1625. updateMatrix: function () {
  1626. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1627. },
  1628. clone: function () {
  1629. return new this.constructor().copy( this );
  1630. },
  1631. copy: function ( source ) {
  1632. this.name = source.name;
  1633. this.image = source.image;
  1634. this.mipmaps = source.mipmaps.slice( 0 );
  1635. this.mapping = source.mapping;
  1636. this.wrapS = source.wrapS;
  1637. this.wrapT = source.wrapT;
  1638. this.magFilter = source.magFilter;
  1639. this.minFilter = source.minFilter;
  1640. this.anisotropy = source.anisotropy;
  1641. this.format = source.format;
  1642. this.internalFormat = source.internalFormat;
  1643. this.type = source.type;
  1644. this.offset.copy( source.offset );
  1645. this.repeat.copy( source.repeat );
  1646. this.center.copy( source.center );
  1647. this.rotation = source.rotation;
  1648. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1649. this.matrix.copy( source.matrix );
  1650. this.generateMipmaps = source.generateMipmaps;
  1651. this.premultiplyAlpha = source.premultiplyAlpha;
  1652. this.flipY = source.flipY;
  1653. this.unpackAlignment = source.unpackAlignment;
  1654. this.encoding = source.encoding;
  1655. return this;
  1656. },
  1657. toJSON: function ( meta ) {
  1658. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1659. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1660. return meta.textures[ this.uuid ];
  1661. }
  1662. const output = {
  1663. metadata: {
  1664. version: 4.5,
  1665. type: 'Texture',
  1666. generator: 'Texture.toJSON'
  1667. },
  1668. uuid: this.uuid,
  1669. name: this.name,
  1670. mapping: this.mapping,
  1671. repeat: [ this.repeat.x, this.repeat.y ],
  1672. offset: [ this.offset.x, this.offset.y ],
  1673. center: [ this.center.x, this.center.y ],
  1674. rotation: this.rotation,
  1675. wrap: [ this.wrapS, this.wrapT ],
  1676. format: this.format,
  1677. type: this.type,
  1678. encoding: this.encoding,
  1679. minFilter: this.minFilter,
  1680. magFilter: this.magFilter,
  1681. anisotropy: this.anisotropy,
  1682. flipY: this.flipY,
  1683. premultiplyAlpha: this.premultiplyAlpha,
  1684. unpackAlignment: this.unpackAlignment
  1685. };
  1686. if ( this.image !== undefined ) {
  1687. // TODO: Move to THREE.Image
  1688. const image = this.image;
  1689. if ( image.uuid === undefined ) {
  1690. image.uuid = MathUtils.generateUUID(); // UGH
  1691. }
  1692. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  1693. let url;
  1694. if ( Array.isArray( image ) ) {
  1695. // process array of images e.g. CubeTexture
  1696. url = [];
  1697. for ( let i = 0, l = image.length; i < l; i ++ ) {
  1698. // check cube texture with data textures
  1699. if ( image[ i ].isDataTexture ) {
  1700. url.push( serializeImage( image[ i ].image ) );
  1701. } else {
  1702. url.push( serializeImage( image[ i ] ) );
  1703. }
  1704. }
  1705. } else {
  1706. // process single image
  1707. url = serializeImage( image );
  1708. }
  1709. meta.images[ image.uuid ] = {
  1710. uuid: image.uuid,
  1711. url: url
  1712. };
  1713. }
  1714. output.image = image.uuid;
  1715. }
  1716. if ( ! isRootObject ) {
  1717. meta.textures[ this.uuid ] = output;
  1718. }
  1719. return output;
  1720. },
  1721. dispose: function () {
  1722. this.dispatchEvent( { type: 'dispose' } );
  1723. },
  1724. transformUv: function ( uv ) {
  1725. if ( this.mapping !== UVMapping ) return uv;
  1726. uv.applyMatrix3( this.matrix );
  1727. if ( uv.x < 0 || uv.x > 1 ) {
  1728. switch ( this.wrapS ) {
  1729. case RepeatWrapping:
  1730. uv.x = uv.x - Math.floor( uv.x );
  1731. break;
  1732. case ClampToEdgeWrapping:
  1733. uv.x = uv.x < 0 ? 0 : 1;
  1734. break;
  1735. case MirroredRepeatWrapping:
  1736. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1737. uv.x = Math.ceil( uv.x ) - uv.x;
  1738. } else {
  1739. uv.x = uv.x - Math.floor( uv.x );
  1740. }
  1741. break;
  1742. }
  1743. }
  1744. if ( uv.y < 0 || uv.y > 1 ) {
  1745. switch ( this.wrapT ) {
  1746. case RepeatWrapping:
  1747. uv.y = uv.y - Math.floor( uv.y );
  1748. break;
  1749. case ClampToEdgeWrapping:
  1750. uv.y = uv.y < 0 ? 0 : 1;
  1751. break;
  1752. case MirroredRepeatWrapping:
  1753. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1754. uv.y = Math.ceil( uv.y ) - uv.y;
  1755. } else {
  1756. uv.y = uv.y - Math.floor( uv.y );
  1757. }
  1758. break;
  1759. }
  1760. }
  1761. if ( this.flipY ) {
  1762. uv.y = 1 - uv.y;
  1763. }
  1764. return uv;
  1765. }
  1766. } );
  1767. Object.defineProperty( Texture.prototype, 'needsUpdate', {
  1768. set: function ( value ) {
  1769. if ( value === true ) this.version ++;
  1770. }
  1771. } );
  1772. function serializeImage( image ) {
  1773. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1774. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1775. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1776. // default images
  1777. return ImageUtils.getDataURL( image );
  1778. } else {
  1779. if ( image.data ) {
  1780. // images of DataTexture
  1781. return {
  1782. data: Array.prototype.slice.call( image.data ),
  1783. width: image.width,
  1784. height: image.height,
  1785. type: image.data.constructor.name
  1786. };
  1787. } else {
  1788. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1789. return {};
  1790. }
  1791. }
  1792. }
  1793. class Vector4 {
  1794. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1795. Object.defineProperty( this, 'isVector4', { value: true } );
  1796. this.x = x;
  1797. this.y = y;
  1798. this.z = z;
  1799. this.w = w;
  1800. }
  1801. get width() {
  1802. return this.z;
  1803. }
  1804. set width( value ) {
  1805. this.z = value;
  1806. }
  1807. get height() {
  1808. return this.w;
  1809. }
  1810. set height( value ) {
  1811. this.w = value;
  1812. }
  1813. set( x, y, z, w ) {
  1814. this.x = x;
  1815. this.y = y;
  1816. this.z = z;
  1817. this.w = w;
  1818. return this;
  1819. }
  1820. setScalar( scalar ) {
  1821. this.x = scalar;
  1822. this.y = scalar;
  1823. this.z = scalar;
  1824. this.w = scalar;
  1825. return this;
  1826. }
  1827. setX( x ) {
  1828. this.x = x;
  1829. return this;
  1830. }
  1831. setY( y ) {
  1832. this.y = y;
  1833. return this;
  1834. }
  1835. setZ( z ) {
  1836. this.z = z;
  1837. return this;
  1838. }
  1839. setW( w ) {
  1840. this.w = w;
  1841. return this;
  1842. }
  1843. setComponent( index, value ) {
  1844. switch ( index ) {
  1845. case 0: this.x = value; break;
  1846. case 1: this.y = value; break;
  1847. case 2: this.z = value; break;
  1848. case 3: this.w = value; break;
  1849. default: throw new Error( 'index is out of range: ' + index );
  1850. }
  1851. return this;
  1852. }
  1853. getComponent( index ) {
  1854. switch ( index ) {
  1855. case 0: return this.x;
  1856. case 1: return this.y;
  1857. case 2: return this.z;
  1858. case 3: return this.w;
  1859. default: throw new Error( 'index is out of range: ' + index );
  1860. }
  1861. }
  1862. clone() {
  1863. return new this.constructor( this.x, this.y, this.z, this.w );
  1864. }
  1865. copy( v ) {
  1866. this.x = v.x;
  1867. this.y = v.y;
  1868. this.z = v.z;
  1869. this.w = ( v.w !== undefined ) ? v.w : 1;
  1870. return this;
  1871. }
  1872. add( v, w ) {
  1873. if ( w !== undefined ) {
  1874. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1875. return this.addVectors( v, w );
  1876. }
  1877. this.x += v.x;
  1878. this.y += v.y;
  1879. this.z += v.z;
  1880. this.w += v.w;
  1881. return this;
  1882. }
  1883. addScalar( s ) {
  1884. this.x += s;
  1885. this.y += s;
  1886. this.z += s;
  1887. this.w += s;
  1888. return this;
  1889. }
  1890. addVectors( a, b ) {
  1891. this.x = a.x + b.x;
  1892. this.y = a.y + b.y;
  1893. this.z = a.z + b.z;
  1894. this.w = a.w + b.w;
  1895. return this;
  1896. }
  1897. addScaledVector( v, s ) {
  1898. this.x += v.x * s;
  1899. this.y += v.y * s;
  1900. this.z += v.z * s;
  1901. this.w += v.w * s;
  1902. return this;
  1903. }
  1904. sub( v, w ) {
  1905. if ( w !== undefined ) {
  1906. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1907. return this.subVectors( v, w );
  1908. }
  1909. this.x -= v.x;
  1910. this.y -= v.y;
  1911. this.z -= v.z;
  1912. this.w -= v.w;
  1913. return this;
  1914. }
  1915. subScalar( s ) {
  1916. this.x -= s;
  1917. this.y -= s;
  1918. this.z -= s;
  1919. this.w -= s;
  1920. return this;
  1921. }
  1922. subVectors( a, b ) {
  1923. this.x = a.x - b.x;
  1924. this.y = a.y - b.y;
  1925. this.z = a.z - b.z;
  1926. this.w = a.w - b.w;
  1927. return this;
  1928. }
  1929. multiplyScalar( scalar ) {
  1930. this.x *= scalar;
  1931. this.y *= scalar;
  1932. this.z *= scalar;
  1933. this.w *= scalar;
  1934. return this;
  1935. }
  1936. applyMatrix4( m ) {
  1937. const x = this.x, y = this.y, z = this.z, w = this.w;
  1938. const e = m.elements;
  1939. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1940. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1941. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1942. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1943. return this;
  1944. }
  1945. divideScalar( scalar ) {
  1946. return this.multiplyScalar( 1 / scalar );
  1947. }
  1948. setAxisAngleFromQuaternion( q ) {
  1949. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1950. // q is assumed to be normalized
  1951. this.w = 2 * Math.acos( q.w );
  1952. const s = Math.sqrt( 1 - q.w * q.w );
  1953. if ( s < 0.0001 ) {
  1954. this.x = 1;
  1955. this.y = 0;
  1956. this.z = 0;
  1957. } else {
  1958. this.x = q.x / s;
  1959. this.y = q.y / s;
  1960. this.z = q.z / s;
  1961. }
  1962. return this;
  1963. }
  1964. setAxisAngleFromRotationMatrix( m ) {
  1965. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1966. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1967. let angle, x, y, z; // variables for result
  1968. const epsilon = 0.01, // margin to allow for rounding errors
  1969. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1970. te = m.elements,
  1971. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1972. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1973. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1974. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1975. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1976. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1977. // singularity found
  1978. // first check for identity matrix which must have +1 for all terms
  1979. // in leading diagonal and zero in other terms
  1980. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1981. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1982. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1983. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1984. // this singularity is identity matrix so angle = 0
  1985. this.set( 1, 0, 0, 0 );
  1986. return this; // zero angle, arbitrary axis
  1987. }
  1988. // otherwise this singularity is angle = 180
  1989. angle = Math.PI;
  1990. const xx = ( m11 + 1 ) / 2;
  1991. const yy = ( m22 + 1 ) / 2;
  1992. const zz = ( m33 + 1 ) / 2;
  1993. const xy = ( m12 + m21 ) / 4;
  1994. const xz = ( m13 + m31 ) / 4;
  1995. const yz = ( m23 + m32 ) / 4;
  1996. if ( ( xx > yy ) && ( xx > zz ) ) {
  1997. // m11 is the largest diagonal term
  1998. if ( xx < epsilon ) {
  1999. x = 0;
  2000. y = 0.707106781;
  2001. z = 0.707106781;
  2002. } else {
  2003. x = Math.sqrt( xx );
  2004. y = xy / x;
  2005. z = xz / x;
  2006. }
  2007. } else if ( yy > zz ) {
  2008. // m22 is the largest diagonal term
  2009. if ( yy < epsilon ) {
  2010. x = 0.707106781;
  2011. y = 0;
  2012. z = 0.707106781;
  2013. } else {
  2014. y = Math.sqrt( yy );
  2015. x = xy / y;
  2016. z = yz / y;
  2017. }
  2018. } else {
  2019. // m33 is the largest diagonal term so base result on this
  2020. if ( zz < epsilon ) {
  2021. x = 0.707106781;
  2022. y = 0.707106781;
  2023. z = 0;
  2024. } else {
  2025. z = Math.sqrt( zz );
  2026. x = xz / z;
  2027. y = yz / z;
  2028. }
  2029. }
  2030. this.set( x, y, z, angle );
  2031. return this; // return 180 deg rotation
  2032. }
  2033. // as we have reached here there are no singularities so we can handle normally
  2034. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  2035. ( m13 - m31 ) * ( m13 - m31 ) +
  2036. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  2037. if ( Math.abs( s ) < 0.001 ) s = 1;
  2038. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2039. // caught by singularity test above, but I've left it in just in case
  2040. this.x = ( m32 - m23 ) / s;
  2041. this.y = ( m13 - m31 ) / s;
  2042. this.z = ( m21 - m12 ) / s;
  2043. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  2044. return this;
  2045. }
  2046. min( v ) {
  2047. this.x = Math.min( this.x, v.x );
  2048. this.y = Math.min( this.y, v.y );
  2049. this.z = Math.min( this.z, v.z );
  2050. this.w = Math.min( this.w, v.w );
  2051. return this;
  2052. }
  2053. max( v ) {
  2054. this.x = Math.max( this.x, v.x );
  2055. this.y = Math.max( this.y, v.y );
  2056. this.z = Math.max( this.z, v.z );
  2057. this.w = Math.max( this.w, v.w );
  2058. return this;
  2059. }
  2060. clamp( min, max ) {
  2061. // assumes min < max, componentwise
  2062. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2063. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2064. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2065. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  2066. return this;
  2067. }
  2068. clampScalar( minVal, maxVal ) {
  2069. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2070. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2071. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2072. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  2073. return this;
  2074. }
  2075. clampLength( min, max ) {
  2076. const length = this.length();
  2077. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2078. }
  2079. floor() {
  2080. this.x = Math.floor( this.x );
  2081. this.y = Math.floor( this.y );
  2082. this.z = Math.floor( this.z );
  2083. this.w = Math.floor( this.w );
  2084. return this;
  2085. }
  2086. ceil() {
  2087. this.x = Math.ceil( this.x );
  2088. this.y = Math.ceil( this.y );
  2089. this.z = Math.ceil( this.z );
  2090. this.w = Math.ceil( this.w );
  2091. return this;
  2092. }
  2093. round() {
  2094. this.x = Math.round( this.x );
  2095. this.y = Math.round( this.y );
  2096. this.z = Math.round( this.z );
  2097. this.w = Math.round( this.w );
  2098. return this;
  2099. }
  2100. roundToZero() {
  2101. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2102. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2103. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2104. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  2105. return this;
  2106. }
  2107. negate() {
  2108. this.x = - this.x;
  2109. this.y = - this.y;
  2110. this.z = - this.z;
  2111. this.w = - this.w;
  2112. return this;
  2113. }
  2114. dot( v ) {
  2115. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2116. }
  2117. lengthSq() {
  2118. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2119. }
  2120. length() {
  2121. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2122. }
  2123. manhattanLength() {
  2124. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  2125. }
  2126. normalize() {
  2127. return this.divideScalar( this.length() || 1 );
  2128. }
  2129. setLength( length ) {
  2130. return this.normalize().multiplyScalar( length );
  2131. }
  2132. lerp( v, alpha ) {
  2133. this.x += ( v.x - this.x ) * alpha;
  2134. this.y += ( v.y - this.y ) * alpha;
  2135. this.z += ( v.z - this.z ) * alpha;
  2136. this.w += ( v.w - this.w ) * alpha;
  2137. return this;
  2138. }
  2139. lerpVectors( v1, v2, alpha ) {
  2140. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2141. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2142. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2143. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  2144. return this;
  2145. }
  2146. equals( v ) {
  2147. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  2148. }
  2149. fromArray( array, offset = 0 ) {
  2150. this.x = array[ offset ];
  2151. this.y = array[ offset + 1 ];
  2152. this.z = array[ offset + 2 ];
  2153. this.w = array[ offset + 3 ];
  2154. return this;
  2155. }
  2156. toArray( array = [], offset = 0 ) {
  2157. array[ offset ] = this.x;
  2158. array[ offset + 1 ] = this.y;
  2159. array[ offset + 2 ] = this.z;
  2160. array[ offset + 3 ] = this.w;
  2161. return array;
  2162. }
  2163. fromBufferAttribute( attribute, index, offset ) {
  2164. if ( offset !== undefined ) {
  2165. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  2166. }
  2167. this.x = attribute.getX( index );
  2168. this.y = attribute.getY( index );
  2169. this.z = attribute.getZ( index );
  2170. this.w = attribute.getW( index );
  2171. return this;
  2172. }
  2173. random() {
  2174. this.x = Math.random();
  2175. this.y = Math.random();
  2176. this.z = Math.random();
  2177. this.w = Math.random();
  2178. return this;
  2179. }
  2180. }
  2181. /*
  2182. In options, we can specify:
  2183. * Texture parameters for an auto-generated target texture
  2184. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2185. */
  2186. function WebGLRenderTarget( width, height, options ) {
  2187. this.width = width;
  2188. this.height = height;
  2189. this.scissor = new Vector4( 0, 0, width, height );
  2190. this.scissorTest = false;
  2191. this.viewport = new Vector4( 0, 0, width, height );
  2192. options = options || {};
  2193. this.texture = new Texture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  2194. this.texture.image = {};
  2195. this.texture.image.width = width;
  2196. this.texture.image.height = height;
  2197. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2198. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2199. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2200. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2201. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2202. }
  2203. WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  2204. constructor: WebGLRenderTarget,
  2205. isWebGLRenderTarget: true,
  2206. setSize: function ( width, height ) {
  2207. if ( this.width !== width || this.height !== height ) {
  2208. this.width = width;
  2209. this.height = height;
  2210. this.texture.image.width = width;
  2211. this.texture.image.height = height;
  2212. this.dispose();
  2213. }
  2214. this.viewport.set( 0, 0, width, height );
  2215. this.scissor.set( 0, 0, width, height );
  2216. },
  2217. clone: function () {
  2218. return new this.constructor().copy( this );
  2219. },
  2220. copy: function ( source ) {
  2221. this.width = source.width;
  2222. this.height = source.height;
  2223. this.viewport.copy( source.viewport );
  2224. this.texture = source.texture.clone();
  2225. this.depthBuffer = source.depthBuffer;
  2226. this.stencilBuffer = source.stencilBuffer;
  2227. this.depthTexture = source.depthTexture;
  2228. return this;
  2229. },
  2230. dispose: function () {
  2231. this.dispatchEvent( { type: 'dispose' } );
  2232. }
  2233. } );
  2234. function WebGLMultisampleRenderTarget( width, height, options ) {
  2235. WebGLRenderTarget.call( this, width, height, options );
  2236. this.samples = 4;
  2237. }
  2238. WebGLMultisampleRenderTarget.prototype = Object.assign( Object.create( WebGLRenderTarget.prototype ), {
  2239. constructor: WebGLMultisampleRenderTarget,
  2240. isWebGLMultisampleRenderTarget: true,
  2241. copy: function ( source ) {
  2242. WebGLRenderTarget.prototype.copy.call( this, source );
  2243. this.samples = source.samples;
  2244. return this;
  2245. }
  2246. } );
  2247. class Quaternion {
  2248. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2249. Object.defineProperty( this, 'isQuaternion', { value: true } );
  2250. this._x = x;
  2251. this._y = y;
  2252. this._z = z;
  2253. this._w = w;
  2254. }
  2255. static slerp( qa, qb, qm, t ) {
  2256. return qm.copy( qa ).slerp( qb, t );
  2257. }
  2258. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2259. // fuzz-free, array-based Quaternion SLERP operation
  2260. let x0 = src0[ srcOffset0 + 0 ],
  2261. y0 = src0[ srcOffset0 + 1 ],
  2262. z0 = src0[ srcOffset0 + 2 ],
  2263. w0 = src0[ srcOffset0 + 3 ];
  2264. const x1 = src1[ srcOffset1 + 0 ],
  2265. y1 = src1[ srcOffset1 + 1 ],
  2266. z1 = src1[ srcOffset1 + 2 ],
  2267. w1 = src1[ srcOffset1 + 3 ];
  2268. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2269. let s = 1 - t;
  2270. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2271. dir = ( cos >= 0 ? 1 : - 1 ),
  2272. sqrSin = 1 - cos * cos;
  2273. // Skip the Slerp for tiny steps to avoid numeric problems:
  2274. if ( sqrSin > Number.EPSILON ) {
  2275. const sin = Math.sqrt( sqrSin ),
  2276. len = Math.atan2( sin, cos * dir );
  2277. s = Math.sin( s * len ) / sin;
  2278. t = Math.sin( t * len ) / sin;
  2279. }
  2280. const tDir = t * dir;
  2281. x0 = x0 * s + x1 * tDir;
  2282. y0 = y0 * s + y1 * tDir;
  2283. z0 = z0 * s + z1 * tDir;
  2284. w0 = w0 * s + w1 * tDir;
  2285. // Normalize in case we just did a lerp:
  2286. if ( s === 1 - t ) {
  2287. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2288. x0 *= f;
  2289. y0 *= f;
  2290. z0 *= f;
  2291. w0 *= f;
  2292. }
  2293. }
  2294. dst[ dstOffset ] = x0;
  2295. dst[ dstOffset + 1 ] = y0;
  2296. dst[ dstOffset + 2 ] = z0;
  2297. dst[ dstOffset + 3 ] = w0;
  2298. }
  2299. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2300. const x0 = src0[ srcOffset0 ];
  2301. const y0 = src0[ srcOffset0 + 1 ];
  2302. const z0 = src0[ srcOffset0 + 2 ];
  2303. const w0 = src0[ srcOffset0 + 3 ];
  2304. const x1 = src1[ srcOffset1 ];
  2305. const y1 = src1[ srcOffset1 + 1 ];
  2306. const z1 = src1[ srcOffset1 + 2 ];
  2307. const w1 = src1[ srcOffset1 + 3 ];
  2308. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2309. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2310. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2311. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2312. return dst;
  2313. }
  2314. get x() {
  2315. return this._x;
  2316. }
  2317. set x( value ) {
  2318. this._x = value;
  2319. this._onChangeCallback();
  2320. }
  2321. get y() {
  2322. return this._y;
  2323. }
  2324. set y( value ) {
  2325. this._y = value;
  2326. this._onChangeCallback();
  2327. }
  2328. get z() {
  2329. return this._z;
  2330. }
  2331. set z( value ) {
  2332. this._z = value;
  2333. this._onChangeCallback();
  2334. }
  2335. get w() {
  2336. return this._w;
  2337. }
  2338. set w( value ) {
  2339. this._w = value;
  2340. this._onChangeCallback();
  2341. }
  2342. set( x, y, z, w ) {
  2343. this._x = x;
  2344. this._y = y;
  2345. this._z = z;
  2346. this._w = w;
  2347. this._onChangeCallback();
  2348. return this;
  2349. }
  2350. clone() {
  2351. return new this.constructor( this._x, this._y, this._z, this._w );
  2352. }
  2353. copy( quaternion ) {
  2354. this._x = quaternion.x;
  2355. this._y = quaternion.y;
  2356. this._z = quaternion.z;
  2357. this._w = quaternion.w;
  2358. this._onChangeCallback();
  2359. return this;
  2360. }
  2361. setFromEuler( euler, update ) {
  2362. if ( ! ( euler && euler.isEuler ) ) {
  2363. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2364. }
  2365. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2366. // http://www.mathworks.com/matlabcentral/fileexchange/
  2367. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2368. // content/SpinCalc.m
  2369. const cos = Math.cos;
  2370. const sin = Math.sin;
  2371. const c1 = cos( x / 2 );
  2372. const c2 = cos( y / 2 );
  2373. const c3 = cos( z / 2 );
  2374. const s1 = sin( x / 2 );
  2375. const s2 = sin( y / 2 );
  2376. const s3 = sin( z / 2 );
  2377. switch ( order ) {
  2378. case 'XYZ':
  2379. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2380. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2381. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2382. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2383. break;
  2384. case 'YXZ':
  2385. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2386. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2387. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2388. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2389. break;
  2390. case 'ZXY':
  2391. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2392. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2393. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2394. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2395. break;
  2396. case 'ZYX':
  2397. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2398. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2399. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2400. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2401. break;
  2402. case 'YZX':
  2403. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2404. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2405. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2406. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2407. break;
  2408. case 'XZY':
  2409. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2410. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2411. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2412. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2413. break;
  2414. default:
  2415. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2416. }
  2417. if ( update !== false ) this._onChangeCallback();
  2418. return this;
  2419. }
  2420. setFromAxisAngle( axis, angle ) {
  2421. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2422. // assumes axis is normalized
  2423. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2424. this._x = axis.x * s;
  2425. this._y = axis.y * s;
  2426. this._z = axis.z * s;
  2427. this._w = Math.cos( halfAngle );
  2428. this._onChangeCallback();
  2429. return this;
  2430. }
  2431. setFromRotationMatrix( m ) {
  2432. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2433. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2434. const te = m.elements,
  2435. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2436. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2437. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2438. trace = m11 + m22 + m33;
  2439. if ( trace > 0 ) {
  2440. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2441. this._w = 0.25 / s;
  2442. this._x = ( m32 - m23 ) * s;
  2443. this._y = ( m13 - m31 ) * s;
  2444. this._z = ( m21 - m12 ) * s;
  2445. } else if ( m11 > m22 && m11 > m33 ) {
  2446. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2447. this._w = ( m32 - m23 ) / s;
  2448. this._x = 0.25 * s;
  2449. this._y = ( m12 + m21 ) / s;
  2450. this._z = ( m13 + m31 ) / s;
  2451. } else if ( m22 > m33 ) {
  2452. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2453. this._w = ( m13 - m31 ) / s;
  2454. this._x = ( m12 + m21 ) / s;
  2455. this._y = 0.25 * s;
  2456. this._z = ( m23 + m32 ) / s;
  2457. } else {
  2458. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2459. this._w = ( m21 - m12 ) / s;
  2460. this._x = ( m13 + m31 ) / s;
  2461. this._y = ( m23 + m32 ) / s;
  2462. this._z = 0.25 * s;
  2463. }
  2464. this._onChangeCallback();
  2465. return this;
  2466. }
  2467. setFromUnitVectors( vFrom, vTo ) {
  2468. // assumes direction vectors vFrom and vTo are normalized
  2469. const EPS = 0.000001;
  2470. let r = vFrom.dot( vTo ) + 1;
  2471. if ( r < EPS ) {
  2472. r = 0;
  2473. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2474. this._x = - vFrom.y;
  2475. this._y = vFrom.x;
  2476. this._z = 0;
  2477. this._w = r;
  2478. } else {
  2479. this._x = 0;
  2480. this._y = - vFrom.z;
  2481. this._z = vFrom.y;
  2482. this._w = r;
  2483. }
  2484. } else {
  2485. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2486. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2487. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2488. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2489. this._w = r;
  2490. }
  2491. return this.normalize();
  2492. }
  2493. angleTo( q ) {
  2494. return 2 * Math.acos( Math.abs( MathUtils.clamp( this.dot( q ), - 1, 1 ) ) );
  2495. }
  2496. rotateTowards( q, step ) {
  2497. const angle = this.angleTo( q );
  2498. if ( angle === 0 ) return this;
  2499. const t = Math.min( 1, step / angle );
  2500. this.slerp( q, t );
  2501. return this;
  2502. }
  2503. identity() {
  2504. return this.set( 0, 0, 0, 1 );
  2505. }
  2506. invert() {
  2507. // quaternion is assumed to have unit length
  2508. return this.conjugate();
  2509. }
  2510. conjugate() {
  2511. this._x *= - 1;
  2512. this._y *= - 1;
  2513. this._z *= - 1;
  2514. this._onChangeCallback();
  2515. return this;
  2516. }
  2517. dot( v ) {
  2518. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2519. }
  2520. lengthSq() {
  2521. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2522. }
  2523. length() {
  2524. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2525. }
  2526. normalize() {
  2527. let l = this.length();
  2528. if ( l === 0 ) {
  2529. this._x = 0;
  2530. this._y = 0;
  2531. this._z = 0;
  2532. this._w = 1;
  2533. } else {
  2534. l = 1 / l;
  2535. this._x = this._x * l;
  2536. this._y = this._y * l;
  2537. this._z = this._z * l;
  2538. this._w = this._w * l;
  2539. }
  2540. this._onChangeCallback();
  2541. return this;
  2542. }
  2543. multiply( q, p ) {
  2544. if ( p !== undefined ) {
  2545. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  2546. return this.multiplyQuaternions( q, p );
  2547. }
  2548. return this.multiplyQuaternions( this, q );
  2549. }
  2550. premultiply( q ) {
  2551. return this.multiplyQuaternions( q, this );
  2552. }
  2553. multiplyQuaternions( a, b ) {
  2554. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2555. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2556. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2557. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2558. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2559. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2560. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2561. this._onChangeCallback();
  2562. return this;
  2563. }
  2564. slerp( qb, t ) {
  2565. if ( t === 0 ) return this;
  2566. if ( t === 1 ) return this.copy( qb );
  2567. const x = this._x, y = this._y, z = this._z, w = this._w;
  2568. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2569. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2570. if ( cosHalfTheta < 0 ) {
  2571. this._w = - qb._w;
  2572. this._x = - qb._x;
  2573. this._y = - qb._y;
  2574. this._z = - qb._z;
  2575. cosHalfTheta = - cosHalfTheta;
  2576. } else {
  2577. this.copy( qb );
  2578. }
  2579. if ( cosHalfTheta >= 1.0 ) {
  2580. this._w = w;
  2581. this._x = x;
  2582. this._y = y;
  2583. this._z = z;
  2584. return this;
  2585. }
  2586. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2587. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2588. const s = 1 - t;
  2589. this._w = s * w + t * this._w;
  2590. this._x = s * x + t * this._x;
  2591. this._y = s * y + t * this._y;
  2592. this._z = s * z + t * this._z;
  2593. this.normalize();
  2594. this._onChangeCallback();
  2595. return this;
  2596. }
  2597. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2598. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2599. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2600. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2601. this._w = ( w * ratioA + this._w * ratioB );
  2602. this._x = ( x * ratioA + this._x * ratioB );
  2603. this._y = ( y * ratioA + this._y * ratioB );
  2604. this._z = ( z * ratioA + this._z * ratioB );
  2605. this._onChangeCallback();
  2606. return this;
  2607. }
  2608. equals( quaternion ) {
  2609. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2610. }
  2611. fromArray( array, offset = 0 ) {
  2612. this._x = array[ offset ];
  2613. this._y = array[ offset + 1 ];
  2614. this._z = array[ offset + 2 ];
  2615. this._w = array[ offset + 3 ];
  2616. this._onChangeCallback();
  2617. return this;
  2618. }
  2619. toArray( array = [], offset = 0 ) {
  2620. array[ offset ] = this._x;
  2621. array[ offset + 1 ] = this._y;
  2622. array[ offset + 2 ] = this._z;
  2623. array[ offset + 3 ] = this._w;
  2624. return array;
  2625. }
  2626. fromBufferAttribute( attribute, index ) {
  2627. this._x = attribute.getX( index );
  2628. this._y = attribute.getY( index );
  2629. this._z = attribute.getZ( index );
  2630. this._w = attribute.getW( index );
  2631. return this;
  2632. }
  2633. _onChange( callback ) {
  2634. this._onChangeCallback = callback;
  2635. return this;
  2636. }
  2637. _onChangeCallback() {}
  2638. }
  2639. class Vector3 {
  2640. constructor( x = 0, y = 0, z = 0 ) {
  2641. Object.defineProperty( this, 'isVector3', { value: true } );
  2642. this.x = x;
  2643. this.y = y;
  2644. this.z = z;
  2645. }
  2646. set( x, y, z ) {
  2647. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2648. this.x = x;
  2649. this.y = y;
  2650. this.z = z;
  2651. return this;
  2652. }
  2653. setScalar( scalar ) {
  2654. this.x = scalar;
  2655. this.y = scalar;
  2656. this.z = scalar;
  2657. return this;
  2658. }
  2659. setX( x ) {
  2660. this.x = x;
  2661. return this;
  2662. }
  2663. setY( y ) {
  2664. this.y = y;
  2665. return this;
  2666. }
  2667. setZ( z ) {
  2668. this.z = z;
  2669. return this;
  2670. }
  2671. setComponent( index, value ) {
  2672. switch ( index ) {
  2673. case 0: this.x = value; break;
  2674. case 1: this.y = value; break;
  2675. case 2: this.z = value; break;
  2676. default: throw new Error( 'index is out of range: ' + index );
  2677. }
  2678. return this;
  2679. }
  2680. getComponent( index ) {
  2681. switch ( index ) {
  2682. case 0: return this.x;
  2683. case 1: return this.y;
  2684. case 2: return this.z;
  2685. default: throw new Error( 'index is out of range: ' + index );
  2686. }
  2687. }
  2688. clone() {
  2689. return new this.constructor( this.x, this.y, this.z );
  2690. }
  2691. copy( v ) {
  2692. this.x = v.x;
  2693. this.y = v.y;
  2694. this.z = v.z;
  2695. return this;
  2696. }
  2697. add( v, w ) {
  2698. if ( w !== undefined ) {
  2699. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  2700. return this.addVectors( v, w );
  2701. }
  2702. this.x += v.x;
  2703. this.y += v.y;
  2704. this.z += v.z;
  2705. return this;
  2706. }
  2707. addScalar( s ) {
  2708. this.x += s;
  2709. this.y += s;
  2710. this.z += s;
  2711. return this;
  2712. }
  2713. addVectors( a, b ) {
  2714. this.x = a.x + b.x;
  2715. this.y = a.y + b.y;
  2716. this.z = a.z + b.z;
  2717. return this;
  2718. }
  2719. addScaledVector( v, s ) {
  2720. this.x += v.x * s;
  2721. this.y += v.y * s;
  2722. this.z += v.z * s;
  2723. return this;
  2724. }
  2725. sub( v, w ) {
  2726. if ( w !== undefined ) {
  2727. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  2728. return this.subVectors( v, w );
  2729. }
  2730. this.x -= v.x;
  2731. this.y -= v.y;
  2732. this.z -= v.z;
  2733. return this;
  2734. }
  2735. subScalar( s ) {
  2736. this.x -= s;
  2737. this.y -= s;
  2738. this.z -= s;
  2739. return this;
  2740. }
  2741. subVectors( a, b ) {
  2742. this.x = a.x - b.x;
  2743. this.y = a.y - b.y;
  2744. this.z = a.z - b.z;
  2745. return this;
  2746. }
  2747. multiply( v, w ) {
  2748. if ( w !== undefined ) {
  2749. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  2750. return this.multiplyVectors( v, w );
  2751. }
  2752. this.x *= v.x;
  2753. this.y *= v.y;
  2754. this.z *= v.z;
  2755. return this;
  2756. }
  2757. multiplyScalar( scalar ) {
  2758. this.x *= scalar;
  2759. this.y *= scalar;
  2760. this.z *= scalar;
  2761. return this;
  2762. }
  2763. multiplyVectors( a, b ) {
  2764. this.x = a.x * b.x;
  2765. this.y = a.y * b.y;
  2766. this.z = a.z * b.z;
  2767. return this;
  2768. }
  2769. applyEuler( euler ) {
  2770. if ( ! ( euler && euler.isEuler ) ) {
  2771. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  2772. }
  2773. return this.applyQuaternion( _quaternion.setFromEuler( euler ) );
  2774. }
  2775. applyAxisAngle( axis, angle ) {
  2776. return this.applyQuaternion( _quaternion.setFromAxisAngle( axis, angle ) );
  2777. }
  2778. applyMatrix3( m ) {
  2779. const x = this.x, y = this.y, z = this.z;
  2780. const e = m.elements;
  2781. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2782. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2783. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2784. return this;
  2785. }
  2786. applyNormalMatrix( m ) {
  2787. return this.applyMatrix3( m ).normalize();
  2788. }
  2789. applyMatrix4( m ) {
  2790. const x = this.x, y = this.y, z = this.z;
  2791. const e = m.elements;
  2792. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2793. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2794. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2795. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2796. return this;
  2797. }
  2798. applyQuaternion( q ) {
  2799. const x = this.x, y = this.y, z = this.z;
  2800. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2801. // calculate quat * vector
  2802. const ix = qw * x + qy * z - qz * y;
  2803. const iy = qw * y + qz * x - qx * z;
  2804. const iz = qw * z + qx * y - qy * x;
  2805. const iw = - qx * x - qy * y - qz * z;
  2806. // calculate result * inverse quat
  2807. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2808. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2809. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2810. return this;
  2811. }
  2812. project( camera ) {
  2813. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2814. }
  2815. unproject( camera ) {
  2816. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2817. }
  2818. transformDirection( m ) {
  2819. // input: THREE.Matrix4 affine matrix
  2820. // vector interpreted as a direction
  2821. const x = this.x, y = this.y, z = this.z;
  2822. const e = m.elements;
  2823. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2824. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2825. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2826. return this.normalize();
  2827. }
  2828. divide( v ) {
  2829. this.x /= v.x;
  2830. this.y /= v.y;
  2831. this.z /= v.z;
  2832. return this;
  2833. }
  2834. divideScalar( scalar ) {
  2835. return this.multiplyScalar( 1 / scalar );
  2836. }
  2837. min( v ) {
  2838. this.x = Math.min( this.x, v.x );
  2839. this.y = Math.min( this.y, v.y );
  2840. this.z = Math.min( this.z, v.z );
  2841. return this;
  2842. }
  2843. max( v ) {
  2844. this.x = Math.max( this.x, v.x );
  2845. this.y = Math.max( this.y, v.y );
  2846. this.z = Math.max( this.z, v.z );
  2847. return this;
  2848. }
  2849. clamp( min, max ) {
  2850. // assumes min < max, componentwise
  2851. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2852. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2853. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2854. return this;
  2855. }
  2856. clampScalar( minVal, maxVal ) {
  2857. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2858. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2859. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2860. return this;
  2861. }
  2862. clampLength( min, max ) {
  2863. const length = this.length();
  2864. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2865. }
  2866. floor() {
  2867. this.x = Math.floor( this.x );
  2868. this.y = Math.floor( this.y );
  2869. this.z = Math.floor( this.z );
  2870. return this;
  2871. }
  2872. ceil() {
  2873. this.x = Math.ceil( this.x );
  2874. this.y = Math.ceil( this.y );
  2875. this.z = Math.ceil( this.z );
  2876. return this;
  2877. }
  2878. round() {
  2879. this.x = Math.round( this.x );
  2880. this.y = Math.round( this.y );
  2881. this.z = Math.round( this.z );
  2882. return this;
  2883. }
  2884. roundToZero() {
  2885. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2886. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2887. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2888. return this;
  2889. }
  2890. negate() {
  2891. this.x = - this.x;
  2892. this.y = - this.y;
  2893. this.z = - this.z;
  2894. return this;
  2895. }
  2896. dot( v ) {
  2897. return this.x * v.x + this.y * v.y + this.z * v.z;
  2898. }
  2899. // TODO lengthSquared?
  2900. lengthSq() {
  2901. return this.x * this.x + this.y * this.y + this.z * this.z;
  2902. }
  2903. length() {
  2904. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2905. }
  2906. manhattanLength() {
  2907. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2908. }
  2909. normalize() {
  2910. return this.divideScalar( this.length() || 1 );
  2911. }
  2912. setLength( length ) {
  2913. return this.normalize().multiplyScalar( length );
  2914. }
  2915. lerp( v, alpha ) {
  2916. this.x += ( v.x - this.x ) * alpha;
  2917. this.y += ( v.y - this.y ) * alpha;
  2918. this.z += ( v.z - this.z ) * alpha;
  2919. return this;
  2920. }
  2921. lerpVectors( v1, v2, alpha ) {
  2922. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2923. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2924. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2925. return this;
  2926. }
  2927. cross( v, w ) {
  2928. if ( w !== undefined ) {
  2929. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  2930. return this.crossVectors( v, w );
  2931. }
  2932. return this.crossVectors( this, v );
  2933. }
  2934. crossVectors( a, b ) {
  2935. const ax = a.x, ay = a.y, az = a.z;
  2936. const bx = b.x, by = b.y, bz = b.z;
  2937. this.x = ay * bz - az * by;
  2938. this.y = az * bx - ax * bz;
  2939. this.z = ax * by - ay * bx;
  2940. return this;
  2941. }
  2942. projectOnVector( v ) {
  2943. const denominator = v.lengthSq();
  2944. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2945. const scalar = v.dot( this ) / denominator;
  2946. return this.copy( v ).multiplyScalar( scalar );
  2947. }
  2948. projectOnPlane( planeNormal ) {
  2949. _vector.copy( this ).projectOnVector( planeNormal );
  2950. return this.sub( _vector );
  2951. }
  2952. reflect( normal ) {
  2953. // reflect incident vector off plane orthogonal to normal
  2954. // normal is assumed to have unit length
  2955. return this.sub( _vector.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2956. }
  2957. angleTo( v ) {
  2958. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2959. if ( denominator === 0 ) return Math.PI / 2;
  2960. const theta = this.dot( v ) / denominator;
  2961. // clamp, to handle numerical problems
  2962. return Math.acos( MathUtils.clamp( theta, - 1, 1 ) );
  2963. }
  2964. distanceTo( v ) {
  2965. return Math.sqrt( this.distanceToSquared( v ) );
  2966. }
  2967. distanceToSquared( v ) {
  2968. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2969. return dx * dx + dy * dy + dz * dz;
  2970. }
  2971. manhattanDistanceTo( v ) {
  2972. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2973. }
  2974. setFromSpherical( s ) {
  2975. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2976. }
  2977. setFromSphericalCoords( radius, phi, theta ) {
  2978. const sinPhiRadius = Math.sin( phi ) * radius;
  2979. this.x = sinPhiRadius * Math.sin( theta );
  2980. this.y = Math.cos( phi ) * radius;
  2981. this.z = sinPhiRadius * Math.cos( theta );
  2982. return this;
  2983. }
  2984. setFromCylindrical( c ) {
  2985. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2986. }
  2987. setFromCylindricalCoords( radius, theta, y ) {
  2988. this.x = radius * Math.sin( theta );
  2989. this.y = y;
  2990. this.z = radius * Math.cos( theta );
  2991. return this;
  2992. }
  2993. setFromMatrixPosition( m ) {
  2994. const e = m.elements;
  2995. this.x = e[ 12 ];
  2996. this.y = e[ 13 ];
  2997. this.z = e[ 14 ];
  2998. return this;
  2999. }
  3000. setFromMatrixScale( m ) {
  3001. const sx = this.setFromMatrixColumn( m, 0 ).length();
  3002. const sy = this.setFromMatrixColumn( m, 1 ).length();
  3003. const sz = this.setFromMatrixColumn( m, 2 ).length();
  3004. this.x = sx;
  3005. this.y = sy;
  3006. this.z = sz;
  3007. return this;
  3008. }
  3009. setFromMatrixColumn( m, index ) {
  3010. return this.fromArray( m.elements, index * 4 );
  3011. }
  3012. setFromMatrix3Column( m, index ) {
  3013. return this.fromArray( m.elements, index * 3 );
  3014. }
  3015. equals( v ) {
  3016. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  3017. }
  3018. fromArray( array, offset = 0 ) {
  3019. this.x = array[ offset ];
  3020. this.y = array[ offset + 1 ];
  3021. this.z = array[ offset + 2 ];
  3022. return this;
  3023. }
  3024. toArray( array = [], offset = 0 ) {
  3025. array[ offset ] = this.x;
  3026. array[ offset + 1 ] = this.y;
  3027. array[ offset + 2 ] = this.z;
  3028. return array;
  3029. }
  3030. fromBufferAttribute( attribute, index, offset ) {
  3031. if ( offset !== undefined ) {
  3032. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  3033. }
  3034. this.x = attribute.getX( index );
  3035. this.y = attribute.getY( index );
  3036. this.z = attribute.getZ( index );
  3037. return this;
  3038. }
  3039. random() {
  3040. this.x = Math.random();
  3041. this.y = Math.random();
  3042. this.z = Math.random();
  3043. return this;
  3044. }
  3045. }
  3046. const _vector = /*@__PURE__*/ new Vector3();
  3047. const _quaternion = /*@__PURE__*/ new Quaternion();
  3048. class Box3 {
  3049. constructor( min, max ) {
  3050. Object.defineProperty( this, 'isBox3', { value: true } );
  3051. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  3052. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  3053. }
  3054. set( min, max ) {
  3055. this.min.copy( min );
  3056. this.max.copy( max );
  3057. return this;
  3058. }
  3059. setFromArray( array ) {
  3060. let minX = + Infinity;
  3061. let minY = + Infinity;
  3062. let minZ = + Infinity;
  3063. let maxX = - Infinity;
  3064. let maxY = - Infinity;
  3065. let maxZ = - Infinity;
  3066. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  3067. const x = array[ i ];
  3068. const y = array[ i + 1 ];
  3069. const z = array[ i + 2 ];
  3070. if ( x < minX ) minX = x;
  3071. if ( y < minY ) minY = y;
  3072. if ( z < minZ ) minZ = z;
  3073. if ( x > maxX ) maxX = x;
  3074. if ( y > maxY ) maxY = y;
  3075. if ( z > maxZ ) maxZ = z;
  3076. }
  3077. this.min.set( minX, minY, minZ );
  3078. this.max.set( maxX, maxY, maxZ );
  3079. return this;
  3080. }
  3081. setFromBufferAttribute( attribute ) {
  3082. let minX = + Infinity;
  3083. let minY = + Infinity;
  3084. let minZ = + Infinity;
  3085. let maxX = - Infinity;
  3086. let maxY = - Infinity;
  3087. let maxZ = - Infinity;
  3088. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  3089. const x = attribute.getX( i );
  3090. const y = attribute.getY( i );
  3091. const z = attribute.getZ( i );
  3092. if ( x < minX ) minX = x;
  3093. if ( y < minY ) minY = y;
  3094. if ( z < minZ ) minZ = z;
  3095. if ( x > maxX ) maxX = x;
  3096. if ( y > maxY ) maxY = y;
  3097. if ( z > maxZ ) maxZ = z;
  3098. }
  3099. this.min.set( minX, minY, minZ );
  3100. this.max.set( maxX, maxY, maxZ );
  3101. return this;
  3102. }
  3103. setFromPoints( points ) {
  3104. this.makeEmpty();
  3105. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3106. this.expandByPoint( points[ i ] );
  3107. }
  3108. return this;
  3109. }
  3110. setFromCenterAndSize( center, size ) {
  3111. const halfSize = _vector$1.copy( size ).multiplyScalar( 0.5 );
  3112. this.min.copy( center ).sub( halfSize );
  3113. this.max.copy( center ).add( halfSize );
  3114. return this;
  3115. }
  3116. setFromObject( object ) {
  3117. this.makeEmpty();
  3118. return this.expandByObject( object );
  3119. }
  3120. clone() {
  3121. return new this.constructor().copy( this );
  3122. }
  3123. copy( box ) {
  3124. this.min.copy( box.min );
  3125. this.max.copy( box.max );
  3126. return this;
  3127. }
  3128. makeEmpty() {
  3129. this.min.x = this.min.y = this.min.z = + Infinity;
  3130. this.max.x = this.max.y = this.max.z = - Infinity;
  3131. return this;
  3132. }
  3133. isEmpty() {
  3134. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3135. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  3136. }
  3137. getCenter( target ) {
  3138. if ( target === undefined ) {
  3139. console.warn( 'THREE.Box3: .getCenter() target is now required' );
  3140. target = new Vector3();
  3141. }
  3142. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3143. }
  3144. getSize( target ) {
  3145. if ( target === undefined ) {
  3146. console.warn( 'THREE.Box3: .getSize() target is now required' );
  3147. target = new Vector3();
  3148. }
  3149. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  3150. }
  3151. expandByPoint( point ) {
  3152. this.min.min( point );
  3153. this.max.max( point );
  3154. return this;
  3155. }
  3156. expandByVector( vector ) {
  3157. this.min.sub( vector );
  3158. this.max.add( vector );
  3159. return this;
  3160. }
  3161. expandByScalar( scalar ) {
  3162. this.min.addScalar( - scalar );
  3163. this.max.addScalar( scalar );
  3164. return this;
  3165. }
  3166. expandByObject( object ) {
  3167. // Computes the world-axis-aligned bounding box of an object (including its children),
  3168. // accounting for both the object's, and children's, world transforms
  3169. object.updateWorldMatrix( false, false );
  3170. const geometry = object.geometry;
  3171. if ( geometry !== undefined ) {
  3172. if ( geometry.boundingBox === null ) {
  3173. geometry.computeBoundingBox();
  3174. }
  3175. _box.copy( geometry.boundingBox );
  3176. _box.applyMatrix4( object.matrixWorld );
  3177. this.union( _box );
  3178. }
  3179. const children = object.children;
  3180. for ( let i = 0, l = children.length; i < l; i ++ ) {
  3181. this.expandByObject( children[ i ] );
  3182. }
  3183. return this;
  3184. }
  3185. containsPoint( point ) {
  3186. return point.x < this.min.x || point.x > this.max.x ||
  3187. point.y < this.min.y || point.y > this.max.y ||
  3188. point.z < this.min.z || point.z > this.max.z ? false : true;
  3189. }
  3190. containsBox( box ) {
  3191. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3192. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  3193. this.min.z <= box.min.z && box.max.z <= this.max.z;
  3194. }
  3195. getParameter( point, target ) {
  3196. // This can potentially have a divide by zero if the box
  3197. // has a size dimension of 0.
  3198. if ( target === undefined ) {
  3199. console.warn( 'THREE.Box3: .getParameter() target is now required' );
  3200. target = new Vector3();
  3201. }
  3202. return target.set(
  3203. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3204. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  3205. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  3206. );
  3207. }
  3208. intersectsBox( box ) {
  3209. // using 6 splitting planes to rule out intersections.
  3210. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3211. box.max.y < this.min.y || box.min.y > this.max.y ||
  3212. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  3213. }
  3214. intersectsSphere( sphere ) {
  3215. // Find the point on the AABB closest to the sphere center.
  3216. this.clampPoint( sphere.center, _vector$1 );
  3217. // If that point is inside the sphere, the AABB and sphere intersect.
  3218. return _vector$1.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  3219. }
  3220. intersectsPlane( plane ) {
  3221. // We compute the minimum and maximum dot product values. If those values
  3222. // are on the same side (back or front) of the plane, then there is no intersection.
  3223. let min, max;
  3224. if ( plane.normal.x > 0 ) {
  3225. min = plane.normal.x * this.min.x;
  3226. max = plane.normal.x * this.max.x;
  3227. } else {
  3228. min = plane.normal.x * this.max.x;
  3229. max = plane.normal.x * this.min.x;
  3230. }
  3231. if ( plane.normal.y > 0 ) {
  3232. min += plane.normal.y * this.min.y;
  3233. max += plane.normal.y * this.max.y;
  3234. } else {
  3235. min += plane.normal.y * this.max.y;
  3236. max += plane.normal.y * this.min.y;
  3237. }
  3238. if ( plane.normal.z > 0 ) {
  3239. min += plane.normal.z * this.min.z;
  3240. max += plane.normal.z * this.max.z;
  3241. } else {
  3242. min += plane.normal.z * this.max.z;
  3243. max += plane.normal.z * this.min.z;
  3244. }
  3245. return ( min <= - plane.constant && max >= - plane.constant );
  3246. }
  3247. intersectsTriangle( triangle ) {
  3248. if ( this.isEmpty() ) {
  3249. return false;
  3250. }
  3251. // compute box center and extents
  3252. this.getCenter( _center );
  3253. _extents.subVectors( this.max, _center );
  3254. // translate triangle to aabb origin
  3255. _v0.subVectors( triangle.a, _center );
  3256. _v1.subVectors( triangle.b, _center );
  3257. _v2.subVectors( triangle.c, _center );
  3258. // compute edge vectors for triangle
  3259. _f0.subVectors( _v1, _v0 );
  3260. _f1.subVectors( _v2, _v1 );
  3261. _f2.subVectors( _v0, _v2 );
  3262. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3263. // 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
  3264. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3265. let axes = [
  3266. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3267. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3268. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3269. ];
  3270. if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) {
  3271. return false;
  3272. }
  3273. // test 3 face normals from the aabb
  3274. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3275. if ( ! satForAxes( axes, _v0, _v1, _v2, _extents ) ) {
  3276. return false;
  3277. }
  3278. // finally testing the face normal of the triangle
  3279. // use already existing triangle edge vectors here
  3280. _triangleNormal.crossVectors( _f0, _f1 );
  3281. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3282. return satForAxes( axes, _v0, _v1, _v2, _extents );
  3283. }
  3284. clampPoint( point, target ) {
  3285. if ( target === undefined ) {
  3286. console.warn( 'THREE.Box3: .clampPoint() target is now required' );
  3287. target = new Vector3();
  3288. }
  3289. return target.copy( point ).clamp( this.min, this.max );
  3290. }
  3291. distanceToPoint( point ) {
  3292. const clampedPoint = _vector$1.copy( point ).clamp( this.min, this.max );
  3293. return clampedPoint.sub( point ).length();
  3294. }
  3295. getBoundingSphere( target ) {
  3296. if ( target === undefined ) {
  3297. console.error( 'THREE.Box3: .getBoundingSphere() target is now required' );
  3298. //target = new Sphere(); // removed to avoid cyclic dependency
  3299. }
  3300. this.getCenter( target.center );
  3301. target.radius = this.getSize( _vector$1 ).length() * 0.5;
  3302. return target;
  3303. }
  3304. intersect( box ) {
  3305. this.min.max( box.min );
  3306. this.max.min( box.max );
  3307. // 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.
  3308. if ( this.isEmpty() ) this.makeEmpty();
  3309. return this;
  3310. }
  3311. union( box ) {
  3312. this.min.min( box.min );
  3313. this.max.max( box.max );
  3314. return this;
  3315. }
  3316. applyMatrix4( matrix ) {
  3317. // transform of empty box is an empty box.
  3318. if ( this.isEmpty() ) return this;
  3319. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3320. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3321. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3322. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3323. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3324. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3325. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3326. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3327. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3328. this.setFromPoints( _points );
  3329. return this;
  3330. }
  3331. translate( offset ) {
  3332. this.min.add( offset );
  3333. this.max.add( offset );
  3334. return this;
  3335. }
  3336. equals( box ) {
  3337. return box.min.equals( this.min ) && box.max.equals( this.max );
  3338. }
  3339. }
  3340. function satForAxes( axes, v0, v1, v2, extents ) {
  3341. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3342. _testAxis.fromArray( axes, i );
  3343. // project the aabb onto the seperating axis
  3344. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3345. // project all 3 vertices of the triangle onto the seperating axis
  3346. const p0 = v0.dot( _testAxis );
  3347. const p1 = v1.dot( _testAxis );
  3348. const p2 = v2.dot( _testAxis );
  3349. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3350. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3351. // points of the projected triangle are outside the projected half-length of the aabb
  3352. // the axis is seperating and we can exit
  3353. return false;
  3354. }
  3355. }
  3356. return true;
  3357. }
  3358. const _points = [
  3359. /*@__PURE__*/ new Vector3(),
  3360. /*@__PURE__*/ new Vector3(),
  3361. /*@__PURE__*/ new Vector3(),
  3362. /*@__PURE__*/ new Vector3(),
  3363. /*@__PURE__*/ new Vector3(),
  3364. /*@__PURE__*/ new Vector3(),
  3365. /*@__PURE__*/ new Vector3(),
  3366. /*@__PURE__*/ new Vector3()
  3367. ];
  3368. const _vector$1 = /*@__PURE__*/ new Vector3();
  3369. const _box = /*@__PURE__*/ new Box3();
  3370. // triangle centered vertices
  3371. const _v0 = /*@__PURE__*/ new Vector3();
  3372. const _v1 = /*@__PURE__*/ new Vector3();
  3373. const _v2 = /*@__PURE__*/ new Vector3();
  3374. // triangle edge vectors
  3375. const _f0 = /*@__PURE__*/ new Vector3();
  3376. const _f1 = /*@__PURE__*/ new Vector3();
  3377. const _f2 = /*@__PURE__*/ new Vector3();
  3378. const _center = /*@__PURE__*/ new Vector3();
  3379. const _extents = /*@__PURE__*/ new Vector3();
  3380. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3381. const _testAxis = /*@__PURE__*/ new Vector3();
  3382. const _box$1 = /*@__PURE__*/ new Box3();
  3383. class Sphere {
  3384. constructor( center, radius ) {
  3385. this.center = ( center !== undefined ) ? center : new Vector3();
  3386. this.radius = ( radius !== undefined ) ? radius : - 1;
  3387. }
  3388. set( center, radius ) {
  3389. this.center.copy( center );
  3390. this.radius = radius;
  3391. return this;
  3392. }
  3393. setFromPoints( points, optionalCenter ) {
  3394. const center = this.center;
  3395. if ( optionalCenter !== undefined ) {
  3396. center.copy( optionalCenter );
  3397. } else {
  3398. _box$1.setFromPoints( points ).getCenter( center );
  3399. }
  3400. let maxRadiusSq = 0;
  3401. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3402. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3403. }
  3404. this.radius = Math.sqrt( maxRadiusSq );
  3405. return this;
  3406. }
  3407. clone() {
  3408. return new this.constructor().copy( this );
  3409. }
  3410. copy( sphere ) {
  3411. this.center.copy( sphere.center );
  3412. this.radius = sphere.radius;
  3413. return this;
  3414. }
  3415. isEmpty() {
  3416. return ( this.radius < 0 );
  3417. }
  3418. makeEmpty() {
  3419. this.center.set( 0, 0, 0 );
  3420. this.radius = - 1;
  3421. return this;
  3422. }
  3423. containsPoint( point ) {
  3424. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3425. }
  3426. distanceToPoint( point ) {
  3427. return ( point.distanceTo( this.center ) - this.radius );
  3428. }
  3429. intersectsSphere( sphere ) {
  3430. const radiusSum = this.radius + sphere.radius;
  3431. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3432. }
  3433. intersectsBox( box ) {
  3434. return box.intersectsSphere( this );
  3435. }
  3436. intersectsPlane( plane ) {
  3437. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3438. }
  3439. clampPoint( point, target ) {
  3440. const deltaLengthSq = this.center.distanceToSquared( point );
  3441. if ( target === undefined ) {
  3442. console.warn( 'THREE.Sphere: .clampPoint() target is now required' );
  3443. target = new Vector3();
  3444. }
  3445. target.copy( point );
  3446. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3447. target.sub( this.center ).normalize();
  3448. target.multiplyScalar( this.radius ).add( this.center );
  3449. }
  3450. return target;
  3451. }
  3452. getBoundingBox( target ) {
  3453. if ( target === undefined ) {
  3454. console.warn( 'THREE.Sphere: .getBoundingBox() target is now required' );
  3455. target = new Box3();
  3456. }
  3457. if ( this.isEmpty() ) {
  3458. // Empty sphere produces empty bounding box
  3459. target.makeEmpty();
  3460. return target;
  3461. }
  3462. target.set( this.center, this.center );
  3463. target.expandByScalar( this.radius );
  3464. return target;
  3465. }
  3466. applyMatrix4( matrix ) {
  3467. this.center.applyMatrix4( matrix );
  3468. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3469. return this;
  3470. }
  3471. translate( offset ) {
  3472. this.center.add( offset );
  3473. return this;
  3474. }
  3475. equals( sphere ) {
  3476. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3477. }
  3478. }
  3479. const _vector$2 = /*@__PURE__*/ new Vector3();
  3480. const _segCenter = /*@__PURE__*/ new Vector3();
  3481. const _segDir = /*@__PURE__*/ new Vector3();
  3482. const _diff = /*@__PURE__*/ new Vector3();
  3483. const _edge1 = /*@__PURE__*/ new Vector3();
  3484. const _edge2 = /*@__PURE__*/ new Vector3();
  3485. const _normal = /*@__PURE__*/ new Vector3();
  3486. class Ray {
  3487. constructor( origin, direction ) {
  3488. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  3489. this.direction = ( direction !== undefined ) ? direction : new Vector3( 0, 0, - 1 );
  3490. }
  3491. set( origin, direction ) {
  3492. this.origin.copy( origin );
  3493. this.direction.copy( direction );
  3494. return this;
  3495. }
  3496. clone() {
  3497. return new this.constructor().copy( this );
  3498. }
  3499. copy( ray ) {
  3500. this.origin.copy( ray.origin );
  3501. this.direction.copy( ray.direction );
  3502. return this;
  3503. }
  3504. at( t, target ) {
  3505. if ( target === undefined ) {
  3506. console.warn( 'THREE.Ray: .at() target is now required' );
  3507. target = new Vector3();
  3508. }
  3509. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3510. }
  3511. lookAt( v ) {
  3512. this.direction.copy( v ).sub( this.origin ).normalize();
  3513. return this;
  3514. }
  3515. recast( t ) {
  3516. this.origin.copy( this.at( t, _vector$2 ) );
  3517. return this;
  3518. }
  3519. closestPointToPoint( point, target ) {
  3520. if ( target === undefined ) {
  3521. console.warn( 'THREE.Ray: .closestPointToPoint() target is now required' );
  3522. target = new Vector3();
  3523. }
  3524. target.subVectors( point, this.origin );
  3525. const directionDistance = target.dot( this.direction );
  3526. if ( directionDistance < 0 ) {
  3527. return target.copy( this.origin );
  3528. }
  3529. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3530. }
  3531. distanceToPoint( point ) {
  3532. return Math.sqrt( this.distanceSqToPoint( point ) );
  3533. }
  3534. distanceSqToPoint( point ) {
  3535. const directionDistance = _vector$2.subVectors( point, this.origin ).dot( this.direction );
  3536. // point behind the ray
  3537. if ( directionDistance < 0 ) {
  3538. return this.origin.distanceToSquared( point );
  3539. }
  3540. _vector$2.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3541. return _vector$2.distanceToSquared( point );
  3542. }
  3543. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3544. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3545. // It returns the min distance between the ray and the segment
  3546. // defined by v0 and v1
  3547. // It can also set two optional targets :
  3548. // - The closest point on the ray
  3549. // - The closest point on the segment
  3550. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3551. _segDir.copy( v1 ).sub( v0 ).normalize();
  3552. _diff.copy( this.origin ).sub( _segCenter );
  3553. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3554. const a01 = - this.direction.dot( _segDir );
  3555. const b0 = _diff.dot( this.direction );
  3556. const b1 = - _diff.dot( _segDir );
  3557. const c = _diff.lengthSq();
  3558. const det = Math.abs( 1 - a01 * a01 );
  3559. let s0, s1, sqrDist, extDet;
  3560. if ( det > 0 ) {
  3561. // The ray and segment are not parallel.
  3562. s0 = a01 * b1 - b0;
  3563. s1 = a01 * b0 - b1;
  3564. extDet = segExtent * det;
  3565. if ( s0 >= 0 ) {
  3566. if ( s1 >= - extDet ) {
  3567. if ( s1 <= extDet ) {
  3568. // region 0
  3569. // Minimum at interior points of ray and segment.
  3570. const invDet = 1 / det;
  3571. s0 *= invDet;
  3572. s1 *= invDet;
  3573. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3574. } else {
  3575. // region 1
  3576. s1 = segExtent;
  3577. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3578. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3579. }
  3580. } else {
  3581. // region 5
  3582. s1 = - segExtent;
  3583. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3584. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3585. }
  3586. } else {
  3587. if ( s1 <= - extDet ) {
  3588. // region 4
  3589. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3590. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3591. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3592. } else if ( s1 <= extDet ) {
  3593. // region 3
  3594. s0 = 0;
  3595. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3596. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3597. } else {
  3598. // region 2
  3599. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3600. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3601. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3602. }
  3603. }
  3604. } else {
  3605. // Ray and segment are parallel.
  3606. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3607. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3608. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3609. }
  3610. if ( optionalPointOnRay ) {
  3611. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3612. }
  3613. if ( optionalPointOnSegment ) {
  3614. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  3615. }
  3616. return sqrDist;
  3617. }
  3618. intersectSphere( sphere, target ) {
  3619. _vector$2.subVectors( sphere.center, this.origin );
  3620. const tca = _vector$2.dot( this.direction );
  3621. const d2 = _vector$2.dot( _vector$2 ) - tca * tca;
  3622. const radius2 = sphere.radius * sphere.radius;
  3623. if ( d2 > radius2 ) return null;
  3624. const thc = Math.sqrt( radius2 - d2 );
  3625. // t0 = first intersect point - entrance on front of sphere
  3626. const t0 = tca - thc;
  3627. // t1 = second intersect point - exit point on back of sphere
  3628. const t1 = tca + thc;
  3629. // test to see if both t0 and t1 are behind the ray - if so, return null
  3630. if ( t0 < 0 && t1 < 0 ) return null;
  3631. // test to see if t0 is behind the ray:
  3632. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3633. // in order to always return an intersect point that is in front of the ray.
  3634. if ( t0 < 0 ) return this.at( t1, target );
  3635. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3636. return this.at( t0, target );
  3637. }
  3638. intersectsSphere( sphere ) {
  3639. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3640. }
  3641. distanceToPlane( plane ) {
  3642. const denominator = plane.normal.dot( this.direction );
  3643. if ( denominator === 0 ) {
  3644. // line is coplanar, return origin
  3645. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3646. return 0;
  3647. }
  3648. // Null is preferable to undefined since undefined means.... it is undefined
  3649. return null;
  3650. }
  3651. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3652. // Return if the ray never intersects the plane
  3653. return t >= 0 ? t : null;
  3654. }
  3655. intersectPlane( plane, target ) {
  3656. const t = this.distanceToPlane( plane );
  3657. if ( t === null ) {
  3658. return null;
  3659. }
  3660. return this.at( t, target );
  3661. }
  3662. intersectsPlane( plane ) {
  3663. // check if the ray lies on the plane first
  3664. const distToPoint = plane.distanceToPoint( this.origin );
  3665. if ( distToPoint === 0 ) {
  3666. return true;
  3667. }
  3668. const denominator = plane.normal.dot( this.direction );
  3669. if ( denominator * distToPoint < 0 ) {
  3670. return true;
  3671. }
  3672. // ray origin is behind the plane (and is pointing behind it)
  3673. return false;
  3674. }
  3675. intersectBox( box, target ) {
  3676. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3677. const invdirx = 1 / this.direction.x,
  3678. invdiry = 1 / this.direction.y,
  3679. invdirz = 1 / this.direction.z;
  3680. const origin = this.origin;
  3681. if ( invdirx >= 0 ) {
  3682. tmin = ( box.min.x - origin.x ) * invdirx;
  3683. tmax = ( box.max.x - origin.x ) * invdirx;
  3684. } else {
  3685. tmin = ( box.max.x - origin.x ) * invdirx;
  3686. tmax = ( box.min.x - origin.x ) * invdirx;
  3687. }
  3688. if ( invdiry >= 0 ) {
  3689. tymin = ( box.min.y - origin.y ) * invdiry;
  3690. tymax = ( box.max.y - origin.y ) * invdiry;
  3691. } else {
  3692. tymin = ( box.max.y - origin.y ) * invdiry;
  3693. tymax = ( box.min.y - origin.y ) * invdiry;
  3694. }
  3695. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3696. // These lines also handle the case where tmin or tmax is NaN
  3697. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3698. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3699. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3700. if ( invdirz >= 0 ) {
  3701. tzmin = ( box.min.z - origin.z ) * invdirz;
  3702. tzmax = ( box.max.z - origin.z ) * invdirz;
  3703. } else {
  3704. tzmin = ( box.max.z - origin.z ) * invdirz;
  3705. tzmax = ( box.min.z - origin.z ) * invdirz;
  3706. }
  3707. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3708. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3709. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3710. //return point closest to the ray (positive side)
  3711. if ( tmax < 0 ) return null;
  3712. return this.at( tmin >= 0 ? tmin : tmax, target );
  3713. }
  3714. intersectsBox( box ) {
  3715. return this.intersectBox( box, _vector$2 ) !== null;
  3716. }
  3717. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3718. // Compute the offset origin, edges, and normal.
  3719. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3720. _edge1.subVectors( b, a );
  3721. _edge2.subVectors( c, a );
  3722. _normal.crossVectors( _edge1, _edge2 );
  3723. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3724. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3725. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3726. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3727. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3728. let DdN = this.direction.dot( _normal );
  3729. let sign;
  3730. if ( DdN > 0 ) {
  3731. if ( backfaceCulling ) return null;
  3732. sign = 1;
  3733. } else if ( DdN < 0 ) {
  3734. sign = - 1;
  3735. DdN = - DdN;
  3736. } else {
  3737. return null;
  3738. }
  3739. _diff.subVectors( this.origin, a );
  3740. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3741. // b1 < 0, no intersection
  3742. if ( DdQxE2 < 0 ) {
  3743. return null;
  3744. }
  3745. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3746. // b2 < 0, no intersection
  3747. if ( DdE1xQ < 0 ) {
  3748. return null;
  3749. }
  3750. // b1+b2 > 1, no intersection
  3751. if ( DdQxE2 + DdE1xQ > DdN ) {
  3752. return null;
  3753. }
  3754. // Line intersects triangle, check if ray does.
  3755. const QdN = - sign * _diff.dot( _normal );
  3756. // t < 0, no intersection
  3757. if ( QdN < 0 ) {
  3758. return null;
  3759. }
  3760. // Ray intersects triangle.
  3761. return this.at( QdN / DdN, target );
  3762. }
  3763. applyMatrix4( matrix4 ) {
  3764. this.origin.applyMatrix4( matrix4 );
  3765. this.direction.transformDirection( matrix4 );
  3766. return this;
  3767. }
  3768. equals( ray ) {
  3769. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3770. }
  3771. }
  3772. class Matrix4 {
  3773. constructor() {
  3774. Object.defineProperty( this, 'isMatrix4', { value: true } );
  3775. this.elements = [
  3776. 1, 0, 0, 0,
  3777. 0, 1, 0, 0,
  3778. 0, 0, 1, 0,
  3779. 0, 0, 0, 1
  3780. ];
  3781. if ( arguments.length > 0 ) {
  3782. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  3783. }
  3784. }
  3785. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3786. const te = this.elements;
  3787. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3788. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3789. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3790. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3791. return this;
  3792. }
  3793. identity() {
  3794. this.set(
  3795. 1, 0, 0, 0,
  3796. 0, 1, 0, 0,
  3797. 0, 0, 1, 0,
  3798. 0, 0, 0, 1
  3799. );
  3800. return this;
  3801. }
  3802. clone() {
  3803. return new Matrix4().fromArray( this.elements );
  3804. }
  3805. copy( m ) {
  3806. const te = this.elements;
  3807. const me = m.elements;
  3808. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3809. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3810. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3811. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3812. return this;
  3813. }
  3814. copyPosition( m ) {
  3815. const te = this.elements, me = m.elements;
  3816. te[ 12 ] = me[ 12 ];
  3817. te[ 13 ] = me[ 13 ];
  3818. te[ 14 ] = me[ 14 ];
  3819. return this;
  3820. }
  3821. extractBasis( xAxis, yAxis, zAxis ) {
  3822. xAxis.setFromMatrixColumn( this, 0 );
  3823. yAxis.setFromMatrixColumn( this, 1 );
  3824. zAxis.setFromMatrixColumn( this, 2 );
  3825. return this;
  3826. }
  3827. makeBasis( xAxis, yAxis, zAxis ) {
  3828. this.set(
  3829. xAxis.x, yAxis.x, zAxis.x, 0,
  3830. xAxis.y, yAxis.y, zAxis.y, 0,
  3831. xAxis.z, yAxis.z, zAxis.z, 0,
  3832. 0, 0, 0, 1
  3833. );
  3834. return this;
  3835. }
  3836. extractRotation( m ) {
  3837. // this method does not support reflection matrices
  3838. const te = this.elements;
  3839. const me = m.elements;
  3840. const scaleX = 1 / _v1$1.setFromMatrixColumn( m, 0 ).length();
  3841. const scaleY = 1 / _v1$1.setFromMatrixColumn( m, 1 ).length();
  3842. const scaleZ = 1 / _v1$1.setFromMatrixColumn( m, 2 ).length();
  3843. te[ 0 ] = me[ 0 ] * scaleX;
  3844. te[ 1 ] = me[ 1 ] * scaleX;
  3845. te[ 2 ] = me[ 2 ] * scaleX;
  3846. te[ 3 ] = 0;
  3847. te[ 4 ] = me[ 4 ] * scaleY;
  3848. te[ 5 ] = me[ 5 ] * scaleY;
  3849. te[ 6 ] = me[ 6 ] * scaleY;
  3850. te[ 7 ] = 0;
  3851. te[ 8 ] = me[ 8 ] * scaleZ;
  3852. te[ 9 ] = me[ 9 ] * scaleZ;
  3853. te[ 10 ] = me[ 10 ] * scaleZ;
  3854. te[ 11 ] = 0;
  3855. te[ 12 ] = 0;
  3856. te[ 13 ] = 0;
  3857. te[ 14 ] = 0;
  3858. te[ 15 ] = 1;
  3859. return this;
  3860. }
  3861. makeRotationFromEuler( euler ) {
  3862. if ( ! ( euler && euler.isEuler ) ) {
  3863. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  3864. }
  3865. const te = this.elements;
  3866. const x = euler.x, y = euler.y, z = euler.z;
  3867. const a = Math.cos( x ), b = Math.sin( x );
  3868. const c = Math.cos( y ), d = Math.sin( y );
  3869. const e = Math.cos( z ), f = Math.sin( z );
  3870. if ( euler.order === 'XYZ' ) {
  3871. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3872. te[ 0 ] = c * e;
  3873. te[ 4 ] = - c * f;
  3874. te[ 8 ] = d;
  3875. te[ 1 ] = af + be * d;
  3876. te[ 5 ] = ae - bf * d;
  3877. te[ 9 ] = - b * c;
  3878. te[ 2 ] = bf - ae * d;
  3879. te[ 6 ] = be + af * d;
  3880. te[ 10 ] = a * c;
  3881. } else if ( euler.order === 'YXZ' ) {
  3882. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3883. te[ 0 ] = ce + df * b;
  3884. te[ 4 ] = de * b - cf;
  3885. te[ 8 ] = a * d;
  3886. te[ 1 ] = a * f;
  3887. te[ 5 ] = a * e;
  3888. te[ 9 ] = - b;
  3889. te[ 2 ] = cf * b - de;
  3890. te[ 6 ] = df + ce * b;
  3891. te[ 10 ] = a * c;
  3892. } else if ( euler.order === 'ZXY' ) {
  3893. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3894. te[ 0 ] = ce - df * b;
  3895. te[ 4 ] = - a * f;
  3896. te[ 8 ] = de + cf * b;
  3897. te[ 1 ] = cf + de * b;
  3898. te[ 5 ] = a * e;
  3899. te[ 9 ] = df - ce * b;
  3900. te[ 2 ] = - a * d;
  3901. te[ 6 ] = b;
  3902. te[ 10 ] = a * c;
  3903. } else if ( euler.order === 'ZYX' ) {
  3904. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3905. te[ 0 ] = c * e;
  3906. te[ 4 ] = be * d - af;
  3907. te[ 8 ] = ae * d + bf;
  3908. te[ 1 ] = c * f;
  3909. te[ 5 ] = bf * d + ae;
  3910. te[ 9 ] = af * d - be;
  3911. te[ 2 ] = - d;
  3912. te[ 6 ] = b * c;
  3913. te[ 10 ] = a * c;
  3914. } else if ( euler.order === 'YZX' ) {
  3915. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3916. te[ 0 ] = c * e;
  3917. te[ 4 ] = bd - ac * f;
  3918. te[ 8 ] = bc * f + ad;
  3919. te[ 1 ] = f;
  3920. te[ 5 ] = a * e;
  3921. te[ 9 ] = - b * e;
  3922. te[ 2 ] = - d * e;
  3923. te[ 6 ] = ad * f + bc;
  3924. te[ 10 ] = ac - bd * f;
  3925. } else if ( euler.order === 'XZY' ) {
  3926. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3927. te[ 0 ] = c * e;
  3928. te[ 4 ] = - f;
  3929. te[ 8 ] = d * e;
  3930. te[ 1 ] = ac * f + bd;
  3931. te[ 5 ] = a * e;
  3932. te[ 9 ] = ad * f - bc;
  3933. te[ 2 ] = bc * f - ad;
  3934. te[ 6 ] = b * e;
  3935. te[ 10 ] = bd * f + ac;
  3936. }
  3937. // bottom row
  3938. te[ 3 ] = 0;
  3939. te[ 7 ] = 0;
  3940. te[ 11 ] = 0;
  3941. // last column
  3942. te[ 12 ] = 0;
  3943. te[ 13 ] = 0;
  3944. te[ 14 ] = 0;
  3945. te[ 15 ] = 1;
  3946. return this;
  3947. }
  3948. makeRotationFromQuaternion( q ) {
  3949. return this.compose( _zero, q, _one );
  3950. }
  3951. lookAt( eye, target, up ) {
  3952. const te = this.elements;
  3953. _z.subVectors( eye, target );
  3954. if ( _z.lengthSq() === 0 ) {
  3955. // eye and target are in the same position
  3956. _z.z = 1;
  3957. }
  3958. _z.normalize();
  3959. _x.crossVectors( up, _z );
  3960. if ( _x.lengthSq() === 0 ) {
  3961. // up and z are parallel
  3962. if ( Math.abs( up.z ) === 1 ) {
  3963. _z.x += 0.0001;
  3964. } else {
  3965. _z.z += 0.0001;
  3966. }
  3967. _z.normalize();
  3968. _x.crossVectors( up, _z );
  3969. }
  3970. _x.normalize();
  3971. _y.crossVectors( _z, _x );
  3972. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3973. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3974. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3975. return this;
  3976. }
  3977. multiply( m, n ) {
  3978. if ( n !== undefined ) {
  3979. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  3980. return this.multiplyMatrices( m, n );
  3981. }
  3982. return this.multiplyMatrices( this, m );
  3983. }
  3984. premultiply( m ) {
  3985. return this.multiplyMatrices( m, this );
  3986. }
  3987. multiplyMatrices( a, b ) {
  3988. const ae = a.elements;
  3989. const be = b.elements;
  3990. const te = this.elements;
  3991. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3992. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3993. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3994. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3995. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3996. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3997. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3998. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3999. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4000. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4001. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4002. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4003. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4004. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4005. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4006. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4007. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4008. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4009. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4010. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4011. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4012. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4013. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4014. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4015. return this;
  4016. }
  4017. multiplyScalar( s ) {
  4018. const te = this.elements;
  4019. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  4020. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  4021. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  4022. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  4023. return this;
  4024. }
  4025. determinant() {
  4026. const te = this.elements;
  4027. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  4028. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  4029. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  4030. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  4031. //TODO: make this more efficient
  4032. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4033. return (
  4034. n41 * (
  4035. + n14 * n23 * n32
  4036. - n13 * n24 * n32
  4037. - n14 * n22 * n33
  4038. + n12 * n24 * n33
  4039. + n13 * n22 * n34
  4040. - n12 * n23 * n34
  4041. ) +
  4042. n42 * (
  4043. + n11 * n23 * n34
  4044. - n11 * n24 * n33
  4045. + n14 * n21 * n33
  4046. - n13 * n21 * n34
  4047. + n13 * n24 * n31
  4048. - n14 * n23 * n31
  4049. ) +
  4050. n43 * (
  4051. + n11 * n24 * n32
  4052. - n11 * n22 * n34
  4053. - n14 * n21 * n32
  4054. + n12 * n21 * n34
  4055. + n14 * n22 * n31
  4056. - n12 * n24 * n31
  4057. ) +
  4058. n44 * (
  4059. - n13 * n22 * n31
  4060. - n11 * n23 * n32
  4061. + n11 * n22 * n33
  4062. + n13 * n21 * n32
  4063. - n12 * n21 * n33
  4064. + n12 * n23 * n31
  4065. )
  4066. );
  4067. }
  4068. transpose() {
  4069. const te = this.elements;
  4070. let tmp;
  4071. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  4072. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  4073. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  4074. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  4075. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  4076. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  4077. return this;
  4078. }
  4079. setPosition( x, y, z ) {
  4080. const te = this.elements;
  4081. if ( x.isVector3 ) {
  4082. te[ 12 ] = x.x;
  4083. te[ 13 ] = x.y;
  4084. te[ 14 ] = x.z;
  4085. } else {
  4086. te[ 12 ] = x;
  4087. te[ 13 ] = y;
  4088. te[ 14 ] = z;
  4089. }
  4090. return this;
  4091. }
  4092. invert() {
  4093. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4094. const te = this.elements,
  4095. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  4096. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  4097. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  4098. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  4099. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4100. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4101. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4102. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4103. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4104. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4105. const detInv = 1 / det;
  4106. te[ 0 ] = t11 * detInv;
  4107. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  4108. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  4109. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  4110. te[ 4 ] = t12 * detInv;
  4111. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  4112. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  4113. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  4114. te[ 8 ] = t13 * detInv;
  4115. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  4116. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  4117. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  4118. te[ 12 ] = t14 * detInv;
  4119. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  4120. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  4121. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  4122. return this;
  4123. }
  4124. scale( v ) {
  4125. const te = this.elements;
  4126. const x = v.x, y = v.y, z = v.z;
  4127. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  4128. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  4129. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  4130. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  4131. return this;
  4132. }
  4133. getMaxScaleOnAxis() {
  4134. const te = this.elements;
  4135. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  4136. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  4137. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  4138. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  4139. }
  4140. makeTranslation( x, y, z ) {
  4141. this.set(
  4142. 1, 0, 0, x,
  4143. 0, 1, 0, y,
  4144. 0, 0, 1, z,
  4145. 0, 0, 0, 1
  4146. );
  4147. return this;
  4148. }
  4149. makeRotationX( theta ) {
  4150. const c = Math.cos( theta ), s = Math.sin( theta );
  4151. this.set(
  4152. 1, 0, 0, 0,
  4153. 0, c, - s, 0,
  4154. 0, s, c, 0,
  4155. 0, 0, 0, 1
  4156. );
  4157. return this;
  4158. }
  4159. makeRotationY( theta ) {
  4160. const c = Math.cos( theta ), s = Math.sin( theta );
  4161. this.set(
  4162. c, 0, s, 0,
  4163. 0, 1, 0, 0,
  4164. - s, 0, c, 0,
  4165. 0, 0, 0, 1
  4166. );
  4167. return this;
  4168. }
  4169. makeRotationZ( theta ) {
  4170. const c = Math.cos( theta ), s = Math.sin( theta );
  4171. this.set(
  4172. c, - s, 0, 0,
  4173. s, c, 0, 0,
  4174. 0, 0, 1, 0,
  4175. 0, 0, 0, 1
  4176. );
  4177. return this;
  4178. }
  4179. makeRotationAxis( axis, angle ) {
  4180. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4181. const c = Math.cos( angle );
  4182. const s = Math.sin( angle );
  4183. const t = 1 - c;
  4184. const x = axis.x, y = axis.y, z = axis.z;
  4185. const tx = t * x, ty = t * y;
  4186. this.set(
  4187. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4188. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4189. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4190. 0, 0, 0, 1
  4191. );
  4192. return this;
  4193. }
  4194. makeScale( x, y, z ) {
  4195. this.set(
  4196. x, 0, 0, 0,
  4197. 0, y, 0, 0,
  4198. 0, 0, z, 0,
  4199. 0, 0, 0, 1
  4200. );
  4201. return this;
  4202. }
  4203. makeShear( x, y, z ) {
  4204. this.set(
  4205. 1, y, z, 0,
  4206. x, 1, z, 0,
  4207. x, y, 1, 0,
  4208. 0, 0, 0, 1
  4209. );
  4210. return this;
  4211. }
  4212. compose( position, quaternion, scale ) {
  4213. const te = this.elements;
  4214. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  4215. const x2 = x + x, y2 = y + y, z2 = z + z;
  4216. const xx = x * x2, xy = x * y2, xz = x * z2;
  4217. const yy = y * y2, yz = y * z2, zz = z * z2;
  4218. const wx = w * x2, wy = w * y2, wz = w * z2;
  4219. const sx = scale.x, sy = scale.y, sz = scale.z;
  4220. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  4221. te[ 1 ] = ( xy + wz ) * sx;
  4222. te[ 2 ] = ( xz - wy ) * sx;
  4223. te[ 3 ] = 0;
  4224. te[ 4 ] = ( xy - wz ) * sy;
  4225. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  4226. te[ 6 ] = ( yz + wx ) * sy;
  4227. te[ 7 ] = 0;
  4228. te[ 8 ] = ( xz + wy ) * sz;
  4229. te[ 9 ] = ( yz - wx ) * sz;
  4230. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4231. te[ 11 ] = 0;
  4232. te[ 12 ] = position.x;
  4233. te[ 13 ] = position.y;
  4234. te[ 14 ] = position.z;
  4235. te[ 15 ] = 1;
  4236. return this;
  4237. }
  4238. decompose( position, quaternion, scale ) {
  4239. const te = this.elements;
  4240. let sx = _v1$1.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4241. const sy = _v1$1.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4242. const sz = _v1$1.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4243. // if determine is negative, we need to invert one scale
  4244. const det = this.determinant();
  4245. if ( det < 0 ) sx = - sx;
  4246. position.x = te[ 12 ];
  4247. position.y = te[ 13 ];
  4248. position.z = te[ 14 ];
  4249. // scale the rotation part
  4250. _m1.copy( this );
  4251. const invSX = 1 / sx;
  4252. const invSY = 1 / sy;
  4253. const invSZ = 1 / sz;
  4254. _m1.elements[ 0 ] *= invSX;
  4255. _m1.elements[ 1 ] *= invSX;
  4256. _m1.elements[ 2 ] *= invSX;
  4257. _m1.elements[ 4 ] *= invSY;
  4258. _m1.elements[ 5 ] *= invSY;
  4259. _m1.elements[ 6 ] *= invSY;
  4260. _m1.elements[ 8 ] *= invSZ;
  4261. _m1.elements[ 9 ] *= invSZ;
  4262. _m1.elements[ 10 ] *= invSZ;
  4263. quaternion.setFromRotationMatrix( _m1 );
  4264. scale.x = sx;
  4265. scale.y = sy;
  4266. scale.z = sz;
  4267. return this;
  4268. }
  4269. makePerspective( left, right, top, bottom, near, far ) {
  4270. if ( far === undefined ) {
  4271. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  4272. }
  4273. const te = this.elements;
  4274. const x = 2 * near / ( right - left );
  4275. const y = 2 * near / ( top - bottom );
  4276. const a = ( right + left ) / ( right - left );
  4277. const b = ( top + bottom ) / ( top - bottom );
  4278. const c = - ( far + near ) / ( far - near );
  4279. const d = - 2 * far * near / ( far - near );
  4280. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4281. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4282. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4283. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4284. return this;
  4285. }
  4286. makeOrthographic( left, right, top, bottom, near, far ) {
  4287. const te = this.elements;
  4288. const w = 1.0 / ( right - left );
  4289. const h = 1.0 / ( top - bottom );
  4290. const p = 1.0 / ( far - near );
  4291. const x = ( right + left ) * w;
  4292. const y = ( top + bottom ) * h;
  4293. const z = ( far + near ) * p;
  4294. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4295. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4296. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  4297. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4298. return this;
  4299. }
  4300. equals( matrix ) {
  4301. const te = this.elements;
  4302. const me = matrix.elements;
  4303. for ( let i = 0; i < 16; i ++ ) {
  4304. if ( te[ i ] !== me[ i ] ) return false;
  4305. }
  4306. return true;
  4307. }
  4308. fromArray( array, offset = 0 ) {
  4309. for ( let i = 0; i < 16; i ++ ) {
  4310. this.elements[ i ] = array[ i + offset ];
  4311. }
  4312. return this;
  4313. }
  4314. toArray( array = [], offset = 0 ) {
  4315. const te = this.elements;
  4316. array[ offset ] = te[ 0 ];
  4317. array[ offset + 1 ] = te[ 1 ];
  4318. array[ offset + 2 ] = te[ 2 ];
  4319. array[ offset + 3 ] = te[ 3 ];
  4320. array[ offset + 4 ] = te[ 4 ];
  4321. array[ offset + 5 ] = te[ 5 ];
  4322. array[ offset + 6 ] = te[ 6 ];
  4323. array[ offset + 7 ] = te[ 7 ];
  4324. array[ offset + 8 ] = te[ 8 ];
  4325. array[ offset + 9 ] = te[ 9 ];
  4326. array[ offset + 10 ] = te[ 10 ];
  4327. array[ offset + 11 ] = te[ 11 ];
  4328. array[ offset + 12 ] = te[ 12 ];
  4329. array[ offset + 13 ] = te[ 13 ];
  4330. array[ offset + 14 ] = te[ 14 ];
  4331. array[ offset + 15 ] = te[ 15 ];
  4332. return array;
  4333. }
  4334. }
  4335. const _v1$1 = /*@__PURE__*/ new Vector3();
  4336. const _m1 = /*@__PURE__*/ new Matrix4();
  4337. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4338. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4339. const _x = /*@__PURE__*/ new Vector3();
  4340. const _y = /*@__PURE__*/ new Vector3();
  4341. const _z = /*@__PURE__*/ new Vector3();
  4342. class Euler {
  4343. constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {
  4344. Object.defineProperty( this, 'isEuler', { value: true } );
  4345. this._x = x;
  4346. this._y = y;
  4347. this._z = z;
  4348. this._order = order;
  4349. }
  4350. get x() {
  4351. return this._x;
  4352. }
  4353. set x( value ) {
  4354. this._x = value;
  4355. this._onChangeCallback();
  4356. }
  4357. get y() {
  4358. return this._y;
  4359. }
  4360. set y( value ) {
  4361. this._y = value;
  4362. this._onChangeCallback();
  4363. }
  4364. get z() {
  4365. return this._z;
  4366. }
  4367. set z( value ) {
  4368. this._z = value;
  4369. this._onChangeCallback();
  4370. }
  4371. get order() {
  4372. return this._order;
  4373. }
  4374. set order( value ) {
  4375. this._order = value;
  4376. this._onChangeCallback();
  4377. }
  4378. set( x, y, z, order ) {
  4379. this._x = x;
  4380. this._y = y;
  4381. this._z = z;
  4382. this._order = order || this._order;
  4383. this._onChangeCallback();
  4384. return this;
  4385. }
  4386. clone() {
  4387. return new this.constructor( this._x, this._y, this._z, this._order );
  4388. }
  4389. copy( euler ) {
  4390. this._x = euler._x;
  4391. this._y = euler._y;
  4392. this._z = euler._z;
  4393. this._order = euler._order;
  4394. this._onChangeCallback();
  4395. return this;
  4396. }
  4397. setFromRotationMatrix( m, order, update ) {
  4398. const clamp = MathUtils.clamp;
  4399. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4400. const te = m.elements;
  4401. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4402. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4403. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4404. order = order || this._order;
  4405. switch ( order ) {
  4406. case 'XYZ':
  4407. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4408. if ( Math.abs( m13 ) < 0.9999999 ) {
  4409. this._x = Math.atan2( - m23, m33 );
  4410. this._z = Math.atan2( - m12, m11 );
  4411. } else {
  4412. this._x = Math.atan2( m32, m22 );
  4413. this._z = 0;
  4414. }
  4415. break;
  4416. case 'YXZ':
  4417. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4418. if ( Math.abs( m23 ) < 0.9999999 ) {
  4419. this._y = Math.atan2( m13, m33 );
  4420. this._z = Math.atan2( m21, m22 );
  4421. } else {
  4422. this._y = Math.atan2( - m31, m11 );
  4423. this._z = 0;
  4424. }
  4425. break;
  4426. case 'ZXY':
  4427. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4428. if ( Math.abs( m32 ) < 0.9999999 ) {
  4429. this._y = Math.atan2( - m31, m33 );
  4430. this._z = Math.atan2( - m12, m22 );
  4431. } else {
  4432. this._y = 0;
  4433. this._z = Math.atan2( m21, m11 );
  4434. }
  4435. break;
  4436. case 'ZYX':
  4437. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4438. if ( Math.abs( m31 ) < 0.9999999 ) {
  4439. this._x = Math.atan2( m32, m33 );
  4440. this._z = Math.atan2( m21, m11 );
  4441. } else {
  4442. this._x = 0;
  4443. this._z = Math.atan2( - m12, m22 );
  4444. }
  4445. break;
  4446. case 'YZX':
  4447. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4448. if ( Math.abs( m21 ) < 0.9999999 ) {
  4449. this._x = Math.atan2( - m23, m22 );
  4450. this._y = Math.atan2( - m31, m11 );
  4451. } else {
  4452. this._x = 0;
  4453. this._y = Math.atan2( m13, m33 );
  4454. }
  4455. break;
  4456. case 'XZY':
  4457. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4458. if ( Math.abs( m12 ) < 0.9999999 ) {
  4459. this._x = Math.atan2( m32, m22 );
  4460. this._y = Math.atan2( m13, m11 );
  4461. } else {
  4462. this._x = Math.atan2( - m23, m33 );
  4463. this._y = 0;
  4464. }
  4465. break;
  4466. default:
  4467. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4468. }
  4469. this._order = order;
  4470. if ( update !== false ) this._onChangeCallback();
  4471. return this;
  4472. }
  4473. setFromQuaternion( q, order, update ) {
  4474. _matrix.makeRotationFromQuaternion( q );
  4475. return this.setFromRotationMatrix( _matrix, order, update );
  4476. }
  4477. setFromVector3( v, order ) {
  4478. return this.set( v.x, v.y, v.z, order || this._order );
  4479. }
  4480. reorder( newOrder ) {
  4481. // WARNING: this discards revolution information -bhouston
  4482. _quaternion$1.setFromEuler( this );
  4483. return this.setFromQuaternion( _quaternion$1, newOrder );
  4484. }
  4485. equals( euler ) {
  4486. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4487. }
  4488. fromArray( array ) {
  4489. this._x = array[ 0 ];
  4490. this._y = array[ 1 ];
  4491. this._z = array[ 2 ];
  4492. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4493. this._onChangeCallback();
  4494. return this;
  4495. }
  4496. toArray( array = [], offset = 0 ) {
  4497. array[ offset ] = this._x;
  4498. array[ offset + 1 ] = this._y;
  4499. array[ offset + 2 ] = this._z;
  4500. array[ offset + 3 ] = this._order;
  4501. return array;
  4502. }
  4503. toVector3( optionalResult ) {
  4504. if ( optionalResult ) {
  4505. return optionalResult.set( this._x, this._y, this._z );
  4506. } else {
  4507. return new Vector3( this._x, this._y, this._z );
  4508. }
  4509. }
  4510. _onChange( callback ) {
  4511. this._onChangeCallback = callback;
  4512. return this;
  4513. }
  4514. _onChangeCallback() {}
  4515. }
  4516. Euler.DefaultOrder = 'XYZ';
  4517. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  4518. const _matrix = /*@__PURE__*/ new Matrix4();
  4519. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  4520. class Layers {
  4521. constructor() {
  4522. this.mask = 1 | 0;
  4523. }
  4524. set( channel ) {
  4525. this.mask = 1 << channel | 0;
  4526. }
  4527. enable( channel ) {
  4528. this.mask |= 1 << channel | 0;
  4529. }
  4530. enableAll() {
  4531. this.mask = 0xffffffff | 0;
  4532. }
  4533. toggle( channel ) {
  4534. this.mask ^= 1 << channel | 0;
  4535. }
  4536. disable( channel ) {
  4537. this.mask &= ~ ( 1 << channel | 0 );
  4538. }
  4539. disableAll() {
  4540. this.mask = 0;
  4541. }
  4542. test( layers ) {
  4543. return ( this.mask & layers.mask ) !== 0;
  4544. }
  4545. }
  4546. let _object3DId = 0;
  4547. const _v1$2 = new Vector3();
  4548. const _q1 = new Quaternion();
  4549. const _m1$1 = new Matrix4();
  4550. const _target = new Vector3();
  4551. const _position = new Vector3();
  4552. const _scale = new Vector3();
  4553. const _quaternion$2 = new Quaternion();
  4554. const _xAxis = new Vector3( 1, 0, 0 );
  4555. const _yAxis = new Vector3( 0, 1, 0 );
  4556. const _zAxis = new Vector3( 0, 0, 1 );
  4557. const _addedEvent = { type: 'added' };
  4558. const _removedEvent = { type: 'removed' };
  4559. function Object3D() {
  4560. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4561. this.uuid = MathUtils.generateUUID();
  4562. this.name = '';
  4563. this.type = 'Object3D';
  4564. this.parent = null;
  4565. this.children = [];
  4566. this.up = Object3D.DefaultUp.clone();
  4567. const position = new Vector3();
  4568. const rotation = new Euler();
  4569. const quaternion = new Quaternion();
  4570. const scale = new Vector3( 1, 1, 1 );
  4571. function onRotationChange() {
  4572. quaternion.setFromEuler( rotation, false );
  4573. }
  4574. function onQuaternionChange() {
  4575. rotation.setFromQuaternion( quaternion, undefined, false );
  4576. }
  4577. rotation._onChange( onRotationChange );
  4578. quaternion._onChange( onQuaternionChange );
  4579. Object.defineProperties( this, {
  4580. position: {
  4581. configurable: true,
  4582. enumerable: true,
  4583. value: position
  4584. },
  4585. rotation: {
  4586. configurable: true,
  4587. enumerable: true,
  4588. value: rotation
  4589. },
  4590. quaternion: {
  4591. configurable: true,
  4592. enumerable: true,
  4593. value: quaternion
  4594. },
  4595. scale: {
  4596. configurable: true,
  4597. enumerable: true,
  4598. value: scale
  4599. },
  4600. modelViewMatrix: {
  4601. value: new Matrix4()
  4602. },
  4603. normalMatrix: {
  4604. value: new Matrix3()
  4605. }
  4606. } );
  4607. this.matrix = new Matrix4();
  4608. this.matrixWorld = new Matrix4();
  4609. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4610. this.matrixWorldNeedsUpdate = false;
  4611. this.layers = new Layers();
  4612. this.visible = true;
  4613. this.castShadow = false;
  4614. this.receiveShadow = false;
  4615. this.frustumCulled = true;
  4616. this.renderOrder = 0;
  4617. this.animations = [];
  4618. this.userData = {};
  4619. }
  4620. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  4621. Object3D.DefaultMatrixAutoUpdate = true;
  4622. Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  4623. constructor: Object3D,
  4624. isObject3D: true,
  4625. onBeforeRender: function () {},
  4626. onAfterRender: function () {},
  4627. applyMatrix4: function ( matrix ) {
  4628. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4629. this.matrix.premultiply( matrix );
  4630. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4631. },
  4632. applyQuaternion: function ( q ) {
  4633. this.quaternion.premultiply( q );
  4634. return this;
  4635. },
  4636. setRotationFromAxisAngle: function ( axis, angle ) {
  4637. // assumes axis is normalized
  4638. this.quaternion.setFromAxisAngle( axis, angle );
  4639. },
  4640. setRotationFromEuler: function ( euler ) {
  4641. this.quaternion.setFromEuler( euler, true );
  4642. },
  4643. setRotationFromMatrix: function ( m ) {
  4644. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4645. this.quaternion.setFromRotationMatrix( m );
  4646. },
  4647. setRotationFromQuaternion: function ( q ) {
  4648. // assumes q is normalized
  4649. this.quaternion.copy( q );
  4650. },
  4651. rotateOnAxis: function ( axis, angle ) {
  4652. // rotate object on axis in object space
  4653. // axis is assumed to be normalized
  4654. _q1.setFromAxisAngle( axis, angle );
  4655. this.quaternion.multiply( _q1 );
  4656. return this;
  4657. },
  4658. rotateOnWorldAxis: function ( axis, angle ) {
  4659. // rotate object on axis in world space
  4660. // axis is assumed to be normalized
  4661. // method assumes no rotated parent
  4662. _q1.setFromAxisAngle( axis, angle );
  4663. this.quaternion.premultiply( _q1 );
  4664. return this;
  4665. },
  4666. rotateX: function ( angle ) {
  4667. return this.rotateOnAxis( _xAxis, angle );
  4668. },
  4669. rotateY: function ( angle ) {
  4670. return this.rotateOnAxis( _yAxis, angle );
  4671. },
  4672. rotateZ: function ( angle ) {
  4673. return this.rotateOnAxis( _zAxis, angle );
  4674. },
  4675. translateOnAxis: function ( axis, distance ) {
  4676. // translate object by distance along axis in object space
  4677. // axis is assumed to be normalized
  4678. _v1$2.copy( axis ).applyQuaternion( this.quaternion );
  4679. this.position.add( _v1$2.multiplyScalar( distance ) );
  4680. return this;
  4681. },
  4682. translateX: function ( distance ) {
  4683. return this.translateOnAxis( _xAxis, distance );
  4684. },
  4685. translateY: function ( distance ) {
  4686. return this.translateOnAxis( _yAxis, distance );
  4687. },
  4688. translateZ: function ( distance ) {
  4689. return this.translateOnAxis( _zAxis, distance );
  4690. },
  4691. localToWorld: function ( vector ) {
  4692. return vector.applyMatrix4( this.matrixWorld );
  4693. },
  4694. worldToLocal: function ( vector ) {
  4695. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4696. },
  4697. lookAt: function ( x, y, z ) {
  4698. // This method does not support objects having non-uniformly-scaled parent(s)
  4699. if ( x.isVector3 ) {
  4700. _target.copy( x );
  4701. } else {
  4702. _target.set( x, y, z );
  4703. }
  4704. const parent = this.parent;
  4705. this.updateWorldMatrix( true, false );
  4706. _position.setFromMatrixPosition( this.matrixWorld );
  4707. if ( this.isCamera || this.isLight ) {
  4708. _m1$1.lookAt( _position, _target, this.up );
  4709. } else {
  4710. _m1$1.lookAt( _target, _position, this.up );
  4711. }
  4712. this.quaternion.setFromRotationMatrix( _m1$1 );
  4713. if ( parent ) {
  4714. _m1$1.extractRotation( parent.matrixWorld );
  4715. _q1.setFromRotationMatrix( _m1$1 );
  4716. this.quaternion.premultiply( _q1.invert() );
  4717. }
  4718. },
  4719. add: function ( object ) {
  4720. if ( arguments.length > 1 ) {
  4721. for ( let i = 0; i < arguments.length; i ++ ) {
  4722. this.add( arguments[ i ] );
  4723. }
  4724. return this;
  4725. }
  4726. if ( object === this ) {
  4727. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4728. return this;
  4729. }
  4730. if ( object && object.isObject3D ) {
  4731. if ( object.parent !== null ) {
  4732. object.parent.remove( object );
  4733. }
  4734. object.parent = this;
  4735. this.children.push( object );
  4736. object.dispatchEvent( _addedEvent );
  4737. } else {
  4738. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4739. }
  4740. return this;
  4741. },
  4742. remove: function ( object ) {
  4743. if ( arguments.length > 1 ) {
  4744. for ( let i = 0; i < arguments.length; i ++ ) {
  4745. this.remove( arguments[ i ] );
  4746. }
  4747. return this;
  4748. }
  4749. const index = this.children.indexOf( object );
  4750. if ( index !== - 1 ) {
  4751. object.parent = null;
  4752. this.children.splice( index, 1 );
  4753. object.dispatchEvent( _removedEvent );
  4754. }
  4755. return this;
  4756. },
  4757. clear: function () {
  4758. for ( let i = 0; i < this.children.length; i ++ ) {
  4759. const object = this.children[ i ];
  4760. object.parent = null;
  4761. object.dispatchEvent( _removedEvent );
  4762. }
  4763. this.children.length = 0;
  4764. return this;
  4765. },
  4766. attach: function ( object ) {
  4767. // adds object as a child of this, while maintaining the object's world transform
  4768. this.updateWorldMatrix( true, false );
  4769. _m1$1.copy( this.matrixWorld ).invert();
  4770. if ( object.parent !== null ) {
  4771. object.parent.updateWorldMatrix( true, false );
  4772. _m1$1.multiply( object.parent.matrixWorld );
  4773. }
  4774. object.applyMatrix4( _m1$1 );
  4775. object.updateWorldMatrix( false, false );
  4776. this.add( object );
  4777. return this;
  4778. },
  4779. getObjectById: function ( id ) {
  4780. return this.getObjectByProperty( 'id', id );
  4781. },
  4782. getObjectByName: function ( name ) {
  4783. return this.getObjectByProperty( 'name', name );
  4784. },
  4785. getObjectByProperty: function ( name, value ) {
  4786. if ( this[ name ] === value ) return this;
  4787. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4788. const child = this.children[ i ];
  4789. const object = child.getObjectByProperty( name, value );
  4790. if ( object !== undefined ) {
  4791. return object;
  4792. }
  4793. }
  4794. return undefined;
  4795. },
  4796. getWorldPosition: function ( target ) {
  4797. if ( target === undefined ) {
  4798. console.warn( 'THREE.Object3D: .getWorldPosition() target is now required' );
  4799. target = new Vector3();
  4800. }
  4801. this.updateWorldMatrix( true, false );
  4802. return target.setFromMatrixPosition( this.matrixWorld );
  4803. },
  4804. getWorldQuaternion: function ( target ) {
  4805. if ( target === undefined ) {
  4806. console.warn( 'THREE.Object3D: .getWorldQuaternion() target is now required' );
  4807. target = new Quaternion();
  4808. }
  4809. this.updateWorldMatrix( true, false );
  4810. this.matrixWorld.decompose( _position, target, _scale );
  4811. return target;
  4812. },
  4813. getWorldScale: function ( target ) {
  4814. if ( target === undefined ) {
  4815. console.warn( 'THREE.Object3D: .getWorldScale() target is now required' );
  4816. target = new Vector3();
  4817. }
  4818. this.updateWorldMatrix( true, false );
  4819. this.matrixWorld.decompose( _position, _quaternion$2, target );
  4820. return target;
  4821. },
  4822. getWorldDirection: function ( target ) {
  4823. if ( target === undefined ) {
  4824. console.warn( 'THREE.Object3D: .getWorldDirection() target is now required' );
  4825. target = new Vector3();
  4826. }
  4827. this.updateWorldMatrix( true, false );
  4828. const e = this.matrixWorld.elements;
  4829. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4830. },
  4831. raycast: function () {},
  4832. traverse: function ( callback ) {
  4833. let result = callback( this );
  4834. if(result && result.stopContinue){//xzw add
  4835. return
  4836. }
  4837. const children = this.children;
  4838. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4839. children[ i ].traverse( callback );
  4840. }
  4841. },
  4842. traverseVisible: function ( callback ) {
  4843. if ( this.visible === false ) return;
  4844. callback( this );
  4845. const children = this.children;
  4846. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4847. children[ i ].traverseVisible( callback );
  4848. }
  4849. },
  4850. traverseAncestors: function ( callback ) {
  4851. const parent = this.parent;
  4852. if ( parent !== null ) {
  4853. callback( parent );
  4854. parent.traverseAncestors( callback );
  4855. }
  4856. },
  4857. updateMatrix: function () {
  4858. this.matrix.compose( this.position, this.quaternion, this.scale );
  4859. this.matrixWorldNeedsUpdate = true;
  4860. },
  4861. updateMatrixWorld: function ( force ) {
  4862. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4863. if ( this.matrixWorldNeedsUpdate || force ) {
  4864. if ( this.parent === null ) {
  4865. this.matrixWorld.copy( this.matrix );
  4866. } else {
  4867. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4868. }
  4869. this.matrixWorldNeedsUpdate = false;
  4870. force = true;
  4871. }
  4872. // update children
  4873. const children = this.children;
  4874. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4875. children[ i ].updateMatrixWorld( force );
  4876. }
  4877. },
  4878. updateWorldMatrix: function ( updateParents, updateChildren ) {
  4879. const parent = this.parent;
  4880. if ( updateParents === true && parent !== null ) {
  4881. parent.updateWorldMatrix( true, false );
  4882. }
  4883. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4884. if ( this.parent === null ) {
  4885. this.matrixWorld.copy( this.matrix );
  4886. } else {
  4887. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4888. }
  4889. // update children
  4890. if ( updateChildren === true ) {
  4891. const children = this.children;
  4892. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4893. children[ i ].updateWorldMatrix( false, true );
  4894. }
  4895. }
  4896. },
  4897. toJSON: function ( meta ) {
  4898. // meta is a string when called from JSON.stringify
  4899. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4900. const output = {};
  4901. // meta is a hash used to collect geometries, materials.
  4902. // not providing it implies that this is the root object
  4903. // being serialized.
  4904. if ( isRootObject ) {
  4905. // initialize meta obj
  4906. meta = {
  4907. geometries: {},
  4908. materials: {},
  4909. textures: {},
  4910. images: {},
  4911. shapes: {},
  4912. skeletons: {},
  4913. animations: {}
  4914. };
  4915. output.metadata = {
  4916. version: 4.5,
  4917. type: 'Object',
  4918. generator: 'Object3D.toJSON'
  4919. };
  4920. }
  4921. // standard Object3D serialization
  4922. const object = {};
  4923. object.uuid = this.uuid;
  4924. object.type = this.type;
  4925. if ( this.name !== '' ) object.name = this.name;
  4926. if ( this.castShadow === true ) object.castShadow = true;
  4927. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4928. if ( this.visible === false ) object.visible = false;
  4929. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4930. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4931. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  4932. object.layers = this.layers.mask;
  4933. object.matrix = this.matrix.toArray();
  4934. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4935. // object specific properties
  4936. if ( this.isInstancedMesh ) {
  4937. object.type = 'InstancedMesh';
  4938. object.count = this.count;
  4939. object.instanceMatrix = this.instanceMatrix.toJSON();
  4940. }
  4941. //
  4942. function serialize( library, element ) {
  4943. if ( library[ element.uuid ] === undefined ) {
  4944. library[ element.uuid ] = element.toJSON( meta );
  4945. }
  4946. return element.uuid;
  4947. }
  4948. if ( this.isMesh || this.isLine || this.isPoints ) {
  4949. object.geometry = serialize( meta.geometries, this.geometry );
  4950. const parameters = this.geometry.parameters;
  4951. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4952. const shapes = parameters.shapes;
  4953. if ( Array.isArray( shapes ) ) {
  4954. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4955. const shape = shapes[ i ];
  4956. serialize( meta.shapes, shape );
  4957. }
  4958. } else {
  4959. serialize( meta.shapes, shapes );
  4960. }
  4961. }
  4962. }
  4963. if ( this.isSkinnedMesh ) {
  4964. object.bindMode = this.bindMode;
  4965. object.bindMatrix = this.bindMatrix.toArray();
  4966. if ( this.skeleton !== undefined ) {
  4967. serialize( meta.skeletons, this.skeleton );
  4968. object.skeleton = this.skeleton.uuid;
  4969. }
  4970. }
  4971. if ( this.material !== undefined ) {
  4972. if ( Array.isArray( this.material ) ) {
  4973. const uuids = [];
  4974. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4975. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4976. }
  4977. object.material = uuids;
  4978. } else {
  4979. object.material = serialize( meta.materials, this.material );
  4980. }
  4981. }
  4982. //
  4983. if ( this.children.length > 0 ) {
  4984. object.children = [];
  4985. for ( let i = 0; i < this.children.length; i ++ ) {
  4986. object.children.push( this.children[ i ].toJSON( meta ).object );
  4987. }
  4988. }
  4989. //
  4990. if ( this.animations.length > 0 ) {
  4991. object.animations = [];
  4992. for ( let i = 0; i < this.animations.length; i ++ ) {
  4993. const animation = this.animations[ i ];
  4994. object.animations.push( serialize( meta.animations, animation ) );
  4995. }
  4996. }
  4997. if ( isRootObject ) {
  4998. const geometries = extractFromCache( meta.geometries );
  4999. const materials = extractFromCache( meta.materials );
  5000. const textures = extractFromCache( meta.textures );
  5001. const images = extractFromCache( meta.images );
  5002. const shapes = extractFromCache( meta.shapes );
  5003. const skeletons = extractFromCache( meta.skeletons );
  5004. const animations = extractFromCache( meta.animations );
  5005. if ( geometries.length > 0 ) output.geometries = geometries;
  5006. if ( materials.length > 0 ) output.materials = materials;
  5007. if ( textures.length > 0 ) output.textures = textures;
  5008. if ( images.length > 0 ) output.images = images;
  5009. if ( shapes.length > 0 ) output.shapes = shapes;
  5010. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  5011. if ( animations.length > 0 ) output.animations = animations;
  5012. }
  5013. output.object = object;
  5014. return output;
  5015. // extract data from the cache hash
  5016. // remove metadata on each item
  5017. // and return as array
  5018. function extractFromCache( cache ) {
  5019. const values = [];
  5020. for ( const key in cache ) {
  5021. const data = cache[ key ];
  5022. delete data.metadata;
  5023. values.push( data );
  5024. }
  5025. return values;
  5026. }
  5027. },
  5028. clone: function ( recursive ) {
  5029. return new this.constructor().copy( this, recursive );
  5030. },
  5031. copy: function ( source, recursive = true ) {
  5032. this.name = source.name;
  5033. this.up.copy( source.up );
  5034. this.position.copy( source.position );
  5035. this.rotation.order = source.rotation.order;
  5036. this.quaternion.copy( source.quaternion );
  5037. this.scale.copy( source.scale );
  5038. this.matrix.copy( source.matrix );
  5039. this.matrixWorld.copy( source.matrixWorld );
  5040. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5041. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5042. this.layers.mask = source.layers.mask;
  5043. this.visible = source.visible;
  5044. this.castShadow = source.castShadow;
  5045. this.receiveShadow = source.receiveShadow;
  5046. this.frustumCulled = source.frustumCulled;
  5047. this.renderOrder = source.renderOrder;
  5048. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5049. if ( recursive === true ) {
  5050. for ( let i = 0; i < source.children.length; i ++ ) {
  5051. const child = source.children[ i ];
  5052. this.add( child.clone() );
  5053. }
  5054. }
  5055. return this;
  5056. }
  5057. } );
  5058. const _vector1 = /*@__PURE__*/ new Vector3();
  5059. const _vector2 = /*@__PURE__*/ new Vector3();
  5060. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  5061. class Plane {
  5062. constructor( normal, constant ) {
  5063. Object.defineProperty( this, 'isPlane', { value: true } );
  5064. // normal is assumed to be normalized
  5065. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  5066. this.constant = ( constant !== undefined ) ? constant : 0;
  5067. }
  5068. set( normal, constant ) {
  5069. this.normal.copy( normal );
  5070. this.constant = constant;
  5071. return this;
  5072. }
  5073. setComponents( x, y, z, w ) {
  5074. this.normal.set( x, y, z );
  5075. this.constant = w;
  5076. return this;
  5077. }
  5078. setFromNormalAndCoplanarPoint( normal, point ) {
  5079. this.normal.copy( normal );
  5080. this.constant = - point.dot( this.normal );
  5081. return this;
  5082. }
  5083. setFromCoplanarPoints( a, b, c ) {
  5084. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  5085. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5086. this.setFromNormalAndCoplanarPoint( normal, a );
  5087. return this;
  5088. }
  5089. clone() {
  5090. return new this.constructor().copy( this );
  5091. }
  5092. copy( plane ) {
  5093. this.normal.copy( plane.normal );
  5094. this.constant = plane.constant;
  5095. return this;
  5096. }
  5097. normalize() {
  5098. // Note: will lead to a divide by zero if the plane is invalid.
  5099. const inverseNormalLength = 1.0 / this.normal.length();
  5100. this.normal.multiplyScalar( inverseNormalLength );
  5101. this.constant *= inverseNormalLength;
  5102. return this;
  5103. }
  5104. negate() {
  5105. this.constant *= - 1;
  5106. this.normal.negate();
  5107. return this;
  5108. }
  5109. distanceToPoint( point ) {
  5110. return this.normal.dot( point ) + this.constant;
  5111. }
  5112. distanceToSphere( sphere ) {
  5113. return this.distanceToPoint( sphere.center ) - sphere.radius;
  5114. }
  5115. projectPoint( point, target ) {
  5116. if ( target === undefined ) {
  5117. console.warn( 'THREE.Plane: .projectPoint() target is now required' );
  5118. target = new Vector3();
  5119. }
  5120. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  5121. }
  5122. intersectLine( line, target ) {
  5123. if ( target === undefined ) {
  5124. console.warn( 'THREE.Plane: .intersectLine() target is now required' );
  5125. target = new Vector3();
  5126. }
  5127. const direction = line.delta( _vector1 );
  5128. const denominator = this.normal.dot( direction );
  5129. if ( denominator === 0 ) {
  5130. // line is coplanar, return origin
  5131. if ( this.distanceToPoint( line.start ) === 0 ) {
  5132. return target.copy( line.start );
  5133. }
  5134. // Unsure if this is the correct method to handle this case.
  5135. return undefined;
  5136. }
  5137. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  5138. if ( t < 0 || t > 1 ) {
  5139. return undefined;
  5140. }
  5141. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  5142. }
  5143. intersectsLine( line ) {
  5144. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5145. const startSign = this.distanceToPoint( line.start );
  5146. const endSign = this.distanceToPoint( line.end );
  5147. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  5148. }
  5149. intersectsBox( box ) {
  5150. return box.intersectsPlane( this );
  5151. }
  5152. intersectsSphere( sphere ) {
  5153. return sphere.intersectsPlane( this );
  5154. }
  5155. coplanarPoint( target ) {
  5156. if ( target === undefined ) {
  5157. console.warn( 'THREE.Plane: .coplanarPoint() target is now required' );
  5158. target = new Vector3();
  5159. }
  5160. return target.copy( this.normal ).multiplyScalar( - this.constant );
  5161. }
  5162. applyMatrix4( matrix, optionalNormalMatrix ) {
  5163. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  5164. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  5165. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  5166. this.constant = - referencePoint.dot( normal );
  5167. return this;
  5168. }
  5169. translate( offset ) {
  5170. this.constant -= offset.dot( this.normal );
  5171. return this;
  5172. }
  5173. equals( plane ) {
  5174. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  5175. }
  5176. }
  5177. const _v0$1 = /*@__PURE__*/ new Vector3();
  5178. const _v1$3 = /*@__PURE__*/ new Vector3();
  5179. const _v2$1 = /*@__PURE__*/ new Vector3();
  5180. const _v3 = /*@__PURE__*/ new Vector3();
  5181. const _vab = /*@__PURE__*/ new Vector3();
  5182. const _vac = /*@__PURE__*/ new Vector3();
  5183. const _vbc = /*@__PURE__*/ new Vector3();
  5184. const _vap = /*@__PURE__*/ new Vector3();
  5185. const _vbp = /*@__PURE__*/ new Vector3();
  5186. const _vcp = /*@__PURE__*/ new Vector3();
  5187. class Triangle {
  5188. constructor( a, b, c ) {
  5189. this.a = ( a !== undefined ) ? a : new Vector3();
  5190. this.b = ( b !== undefined ) ? b : new Vector3();
  5191. this.c = ( c !== undefined ) ? c : new Vector3();
  5192. }
  5193. static getNormal( a, b, c, target ) {
  5194. if ( target === undefined ) {
  5195. console.warn( 'THREE.Triangle: .getNormal() target is now required' );
  5196. target = new Vector3();
  5197. }
  5198. target.subVectors( c, b );
  5199. _v0$1.subVectors( a, b );
  5200. target.cross( _v0$1 );
  5201. const targetLengthSq = target.lengthSq();
  5202. if ( targetLengthSq > 0 ) {
  5203. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  5204. }
  5205. return target.set( 0, 0, 0 );
  5206. }
  5207. // static/instance method to calculate barycentric coordinates
  5208. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5209. static getBarycoord( point, a, b, c, target ) {
  5210. _v0$1.subVectors( c, a );
  5211. _v1$3.subVectors( b, a );
  5212. _v2$1.subVectors( point, a );
  5213. const dot00 = _v0$1.dot( _v0$1 );
  5214. const dot01 = _v0$1.dot( _v1$3 );
  5215. const dot02 = _v0$1.dot( _v2$1 );
  5216. const dot11 = _v1$3.dot( _v1$3 );
  5217. const dot12 = _v1$3.dot( _v2$1 );
  5218. const denom = ( dot00 * dot11 - dot01 * dot01 );
  5219. if ( target === undefined ) {
  5220. console.warn( 'THREE.Triangle: .getBarycoord() target is now required' );
  5221. target = new Vector3();
  5222. }
  5223. // collinear or singular triangle
  5224. if ( denom === 0 ) {
  5225. // arbitrary location outside of triangle?
  5226. // not sure if this is the best idea, maybe should be returning undefined
  5227. return target.set( - 2, - 1, - 1 );
  5228. }
  5229. const invDenom = 1 / denom;
  5230. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  5231. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  5232. // barycentric coordinates must always sum to 1
  5233. return target.set( 1 - u - v, v, u );
  5234. }
  5235. static containsPoint( point, a, b, c ) {
  5236. this.getBarycoord( point, a, b, c, _v3 );
  5237. return ( _v3.x >= 0 ) && ( _v3.y >= 0 ) && ( ( _v3.x + _v3.y ) <= 1 );
  5238. }
  5239. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  5240. this.getBarycoord( point, p1, p2, p3, _v3 );
  5241. target.set( 0, 0 );
  5242. target.addScaledVector( uv1, _v3.x );
  5243. target.addScaledVector( uv2, _v3.y );
  5244. target.addScaledVector( uv3, _v3.z );
  5245. return target;
  5246. }
  5247. static isFrontFacing( a, b, c, direction ) {
  5248. _v0$1.subVectors( c, b );
  5249. _v1$3.subVectors( a, b );
  5250. // strictly front facing
  5251. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  5252. }
  5253. set( a, b, c ) {
  5254. this.a.copy( a );
  5255. this.b.copy( b );
  5256. this.c.copy( c );
  5257. return this;
  5258. }
  5259. setFromPointsAndIndices( points, i0, i1, i2 ) {
  5260. this.a.copy( points[ i0 ] );
  5261. this.b.copy( points[ i1 ] );
  5262. this.c.copy( points[ i2 ] );
  5263. return this;
  5264. }
  5265. clone() {
  5266. return new this.constructor().copy( this );
  5267. }
  5268. copy( triangle ) {
  5269. this.a.copy( triangle.a );
  5270. this.b.copy( triangle.b );
  5271. this.c.copy( triangle.c );
  5272. return this;
  5273. }
  5274. getArea() {
  5275. _v0$1.subVectors( this.c, this.b );
  5276. _v1$3.subVectors( this.a, this.b );
  5277. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5278. }
  5279. getMidpoint( target ) {
  5280. if ( target === undefined ) {
  5281. console.warn( 'THREE.Triangle: .getMidpoint() target is now required' );
  5282. target = new Vector3();
  5283. }
  5284. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5285. }
  5286. getNormal( target ) {
  5287. return Triangle.getNormal( this.a, this.b, this.c, target );
  5288. }
  5289. getPlane( target ) {
  5290. if ( target === undefined ) {
  5291. console.warn( 'THREE.Triangle: .getPlane() target is now required' );
  5292. target = new Plane();
  5293. }
  5294. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5295. }
  5296. getBarycoord( point, target ) {
  5297. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5298. }
  5299. getUV( point, uv1, uv2, uv3, target ) {
  5300. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  5301. }
  5302. containsPoint( point ) {
  5303. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5304. }
  5305. isFrontFacing( direction ) {
  5306. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5307. }
  5308. intersectsBox( box ) {
  5309. return box.intersectsTriangle( this );
  5310. }
  5311. closestPointToPoint( p, target ) {
  5312. if ( target === undefined ) {
  5313. console.warn( 'THREE.Triangle: .closestPointToPoint() target is now required' );
  5314. target = new Vector3();
  5315. }
  5316. const a = this.a, b = this.b, c = this.c;
  5317. let v, w;
  5318. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5319. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5320. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5321. // basically, we're distinguishing which of the voronoi regions of the triangle
  5322. // the point lies in with the minimum amount of redundant computation.
  5323. _vab.subVectors( b, a );
  5324. _vac.subVectors( c, a );
  5325. _vap.subVectors( p, a );
  5326. const d1 = _vab.dot( _vap );
  5327. const d2 = _vac.dot( _vap );
  5328. if ( d1 <= 0 && d2 <= 0 ) {
  5329. // vertex region of A; barycentric coords (1, 0, 0)
  5330. return target.copy( a );
  5331. }
  5332. _vbp.subVectors( p, b );
  5333. const d3 = _vab.dot( _vbp );
  5334. const d4 = _vac.dot( _vbp );
  5335. if ( d3 >= 0 && d4 <= d3 ) {
  5336. // vertex region of B; barycentric coords (0, 1, 0)
  5337. return target.copy( b );
  5338. }
  5339. const vc = d1 * d4 - d3 * d2;
  5340. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5341. v = d1 / ( d1 - d3 );
  5342. // edge region of AB; barycentric coords (1-v, v, 0)
  5343. return target.copy( a ).addScaledVector( _vab, v );
  5344. }
  5345. _vcp.subVectors( p, c );
  5346. const d5 = _vab.dot( _vcp );
  5347. const d6 = _vac.dot( _vcp );
  5348. if ( d6 >= 0 && d5 <= d6 ) {
  5349. // vertex region of C; barycentric coords (0, 0, 1)
  5350. return target.copy( c );
  5351. }
  5352. const vb = d5 * d2 - d1 * d6;
  5353. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5354. w = d2 / ( d2 - d6 );
  5355. // edge region of AC; barycentric coords (1-w, 0, w)
  5356. return target.copy( a ).addScaledVector( _vac, w );
  5357. }
  5358. const va = d3 * d6 - d5 * d4;
  5359. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5360. _vbc.subVectors( c, b );
  5361. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5362. // edge region of BC; barycentric coords (0, 1-w, w)
  5363. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5364. }
  5365. // face region
  5366. const denom = 1 / ( va + vb + vc );
  5367. // u = va * denom
  5368. v = vb * denom;
  5369. w = vc * denom;
  5370. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5371. }
  5372. equals( triangle ) {
  5373. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5374. }
  5375. }
  5376. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5377. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5378. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5379. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5380. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5381. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5382. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5383. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5384. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5385. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5386. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5387. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5388. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5389. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5390. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5391. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5392. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5393. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5394. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5395. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5396. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5397. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5398. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5399. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5400. const _hslA = { h: 0, s: 0, l: 0 };
  5401. const _hslB = { h: 0, s: 0, l: 0 };
  5402. function hue2rgb( p, q, t ) {
  5403. if ( t < 0 ) t += 1;
  5404. if ( t > 1 ) t -= 1;
  5405. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5406. if ( t < 1 / 2 ) return q;
  5407. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5408. return p;
  5409. }
  5410. function SRGBToLinear( c ) {
  5411. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5412. }
  5413. function LinearToSRGB( c ) {
  5414. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5415. }
  5416. class Color {
  5417. constructor( r, g, b ) {
  5418. Object.defineProperty( this, 'isColor', { value: true } );
  5419. if ( g === undefined && b === undefined ) {
  5420. // r is THREE.Color, hex or string
  5421. return this.set( r );
  5422. }
  5423. return this.setRGB( r, g, b );
  5424. }
  5425. set( value ) {
  5426. if ( value && value.isColor ) {
  5427. this.copy( value );
  5428. } else if ( typeof value === 'number' ) {
  5429. this.setHex( value );
  5430. } else if ( typeof value === 'string' ) {
  5431. this.setStyle( value );
  5432. }
  5433. return this;
  5434. }
  5435. setScalar( scalar ) {
  5436. this.r = scalar;
  5437. this.g = scalar;
  5438. this.b = scalar;
  5439. return this;
  5440. }
  5441. setHex( hex ) {
  5442. hex = Math.floor( hex );
  5443. this.r = ( hex >> 16 & 255 ) / 255;
  5444. this.g = ( hex >> 8 & 255 ) / 255;
  5445. this.b = ( hex & 255 ) / 255;
  5446. return this;
  5447. }
  5448. setRGB( r, g, b ) {
  5449. this.r = r;
  5450. this.g = g;
  5451. this.b = b;
  5452. return this;
  5453. }
  5454. setHSL( h, s, l ) {
  5455. // h,s,l ranges are in 0.0 - 1.0
  5456. h = MathUtils.euclideanModulo( h, 1 );
  5457. s = MathUtils.clamp( s, 0, 1 );
  5458. l = MathUtils.clamp( l, 0, 1 );
  5459. if ( s === 0 ) {
  5460. this.r = this.g = this.b = l;
  5461. } else {
  5462. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5463. const q = ( 2 * l ) - p;
  5464. this.r = hue2rgb( q, p, h + 1 / 3 );
  5465. this.g = hue2rgb( q, p, h );
  5466. this.b = hue2rgb( q, p, h - 1 / 3 );
  5467. }
  5468. return this;
  5469. }
  5470. setStyle( style ) {
  5471. function handleAlpha( string ) {
  5472. if ( string === undefined ) return;
  5473. if ( parseFloat( string ) < 1 ) {
  5474. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5475. }
  5476. }
  5477. let m;
  5478. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  5479. // rgb / hsl
  5480. let color;
  5481. const name = m[ 1 ];
  5482. const components = m[ 2 ];
  5483. switch ( name ) {
  5484. case 'rgb':
  5485. case 'rgba':
  5486. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5487. // rgb(255,0,0) rgba(255,0,0,0.5)
  5488. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  5489. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  5490. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  5491. handleAlpha( color[ 4 ] );
  5492. return this;
  5493. }
  5494. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5495. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5496. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  5497. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  5498. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  5499. handleAlpha( color[ 4 ] );
  5500. return this;
  5501. }
  5502. break;
  5503. case 'hsl':
  5504. case 'hsla':
  5505. if ( color = /^(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5506. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5507. const h = parseFloat( color[ 1 ] ) / 360;
  5508. const s = parseInt( color[ 2 ], 10 ) / 100;
  5509. const l = parseInt( color[ 3 ], 10 ) / 100;
  5510. handleAlpha( color[ 4 ] );
  5511. return this.setHSL( h, s, l );
  5512. }
  5513. break;
  5514. }
  5515. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5516. // hex color
  5517. const hex = m[ 1 ];
  5518. const size = hex.length;
  5519. if ( size === 3 ) {
  5520. // #ff0
  5521. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  5522. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  5523. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  5524. return this;
  5525. } else if ( size === 6 ) {
  5526. // #ff0000
  5527. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  5528. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  5529. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  5530. return this;
  5531. }
  5532. }
  5533. if ( style && style.length > 0 ) {
  5534. return this.setColorName( style );
  5535. }
  5536. return this;
  5537. }
  5538. setColorName( style ) {
  5539. // color keywords
  5540. const hex = _colorKeywords[ style ];
  5541. if ( hex !== undefined ) {
  5542. // red
  5543. this.setHex( hex );
  5544. } else {
  5545. // unknown color
  5546. console.warn( 'THREE.Color: Unknown color ' + style );
  5547. }
  5548. return this;
  5549. }
  5550. clone() {
  5551. return new this.constructor( this.r, this.g, this.b );
  5552. }
  5553. copy( color ) {
  5554. this.r = color.r;
  5555. this.g = color.g;
  5556. this.b = color.b;
  5557. return this;
  5558. }
  5559. copyGammaToLinear( color, gammaFactor = 2.0 ) {
  5560. this.r = Math.pow( color.r, gammaFactor );
  5561. this.g = Math.pow( color.g, gammaFactor );
  5562. this.b = Math.pow( color.b, gammaFactor );
  5563. return this;
  5564. }
  5565. copyLinearToGamma( color, gammaFactor = 2.0 ) {
  5566. const safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  5567. this.r = Math.pow( color.r, safeInverse );
  5568. this.g = Math.pow( color.g, safeInverse );
  5569. this.b = Math.pow( color.b, safeInverse );
  5570. return this;
  5571. }
  5572. convertGammaToLinear( gammaFactor ) {
  5573. this.copyGammaToLinear( this, gammaFactor );
  5574. return this;
  5575. }
  5576. convertLinearToGamma( gammaFactor ) {
  5577. this.copyLinearToGamma( this, gammaFactor );
  5578. return this;
  5579. }
  5580. copySRGBToLinear( color ) {
  5581. this.r = SRGBToLinear( color.r );
  5582. this.g = SRGBToLinear( color.g );
  5583. this.b = SRGBToLinear( color.b );
  5584. return this;
  5585. }
  5586. copyLinearToSRGB( color ) {
  5587. this.r = LinearToSRGB( color.r );
  5588. this.g = LinearToSRGB( color.g );
  5589. this.b = LinearToSRGB( color.b );
  5590. return this;
  5591. }
  5592. convertSRGBToLinear() {
  5593. this.copySRGBToLinear( this );
  5594. return this;
  5595. }
  5596. convertLinearToSRGB() {
  5597. this.copyLinearToSRGB( this );
  5598. return this;
  5599. }
  5600. getHex() {
  5601. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  5602. }
  5603. getHexString() {
  5604. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  5605. }
  5606. getHSL( target ) {
  5607. // h,s,l ranges are in 0.0 - 1.0
  5608. if ( target === undefined ) {
  5609. console.warn( 'THREE.Color: .getHSL() target is now required' );
  5610. target = { h: 0, s: 0, l: 0 };
  5611. }
  5612. const r = this.r, g = this.g, b = this.b;
  5613. const max = Math.max( r, g, b );
  5614. const min = Math.min( r, g, b );
  5615. let hue, saturation;
  5616. const lightness = ( min + max ) / 2.0;
  5617. if ( min === max ) {
  5618. hue = 0;
  5619. saturation = 0;
  5620. } else {
  5621. const delta = max - min;
  5622. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5623. switch ( max ) {
  5624. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5625. case g: hue = ( b - r ) / delta + 2; break;
  5626. case b: hue = ( r - g ) / delta + 4; break;
  5627. }
  5628. hue /= 6;
  5629. }
  5630. target.h = hue;
  5631. target.s = saturation;
  5632. target.l = lightness;
  5633. return target;
  5634. }
  5635. getStyle() {
  5636. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  5637. }
  5638. offsetHSL( h, s, l ) {
  5639. this.getHSL( _hslA );
  5640. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  5641. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  5642. return this;
  5643. }
  5644. add( color ) {
  5645. this.r += color.r;
  5646. this.g += color.g;
  5647. this.b += color.b;
  5648. return this;
  5649. }
  5650. addColors( color1, color2 ) {
  5651. this.r = color1.r + color2.r;
  5652. this.g = color1.g + color2.g;
  5653. this.b = color1.b + color2.b;
  5654. return this;
  5655. }
  5656. addScalar( s ) {
  5657. this.r += s;
  5658. this.g += s;
  5659. this.b += s;
  5660. return this;
  5661. }
  5662. sub( color ) {
  5663. this.r = Math.max( 0, this.r - color.r );
  5664. this.g = Math.max( 0, this.g - color.g );
  5665. this.b = Math.max( 0, this.b - color.b );
  5666. return this;
  5667. }
  5668. multiply( color ) {
  5669. this.r *= color.r;
  5670. this.g *= color.g;
  5671. this.b *= color.b;
  5672. return this;
  5673. }
  5674. multiplyScalar( s ) {
  5675. this.r *= s;
  5676. this.g *= s;
  5677. this.b *= s;
  5678. return this;
  5679. }
  5680. lerp( color, alpha ) {
  5681. this.r += ( color.r - this.r ) * alpha;
  5682. this.g += ( color.g - this.g ) * alpha;
  5683. this.b += ( color.b - this.b ) * alpha;
  5684. return this;
  5685. }
  5686. lerpHSL( color, alpha ) {
  5687. this.getHSL( _hslA );
  5688. color.getHSL( _hslB );
  5689. const h = MathUtils.lerp( _hslA.h, _hslB.h, alpha );
  5690. const s = MathUtils.lerp( _hslA.s, _hslB.s, alpha );
  5691. const l = MathUtils.lerp( _hslA.l, _hslB.l, alpha );
  5692. this.setHSL( h, s, l );
  5693. return this;
  5694. }
  5695. equals( c ) {
  5696. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5697. }
  5698. fromArray( array, offset = 0 ) {
  5699. this.r = array[ offset ];
  5700. this.g = array[ offset + 1 ];
  5701. this.b = array[ offset + 2 ];
  5702. return this;
  5703. }
  5704. toArray( array = [], offset = 0 ) {
  5705. array[ offset ] = this.r;
  5706. array[ offset + 1 ] = this.g;
  5707. array[ offset + 2 ] = this.b;
  5708. return array;
  5709. }
  5710. fromBufferAttribute( attribute, index ) {
  5711. this.r = attribute.getX( index );
  5712. this.g = attribute.getY( index );
  5713. this.b = attribute.getZ( index );
  5714. if ( attribute.normalized === true ) {
  5715. // assuming Uint8Array
  5716. this.r /= 255;
  5717. this.g /= 255;
  5718. this.b /= 255;
  5719. }
  5720. return this;
  5721. }
  5722. toJSON() {
  5723. return this.getHex();
  5724. }
  5725. }
  5726. Color.NAMES = _colorKeywords;
  5727. Color.prototype.r = 1;
  5728. Color.prototype.g = 1;
  5729. Color.prototype.b = 1;
  5730. class Face3 {
  5731. constructor( a, b, c, normal, color, materialIndex = 0 ) {
  5732. this.a = a;
  5733. this.b = b;
  5734. this.c = c;
  5735. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  5736. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  5737. this.color = ( color && color.isColor ) ? color : new Color();
  5738. this.vertexColors = Array.isArray( color ) ? color : [];
  5739. this.materialIndex = materialIndex;
  5740. }
  5741. clone() {
  5742. return new this.constructor().copy( this );
  5743. }
  5744. copy( source ) {
  5745. this.a = source.a;
  5746. this.b = source.b;
  5747. this.c = source.c;
  5748. this.normal.copy( source.normal );
  5749. this.color.copy( source.color );
  5750. this.materialIndex = source.materialIndex;
  5751. for ( let i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  5752. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  5753. }
  5754. for ( let i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  5755. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  5756. }
  5757. return this;
  5758. }
  5759. }
  5760. let materialId = 0;
  5761. function Material() {
  5762. Object.defineProperty( this, 'id', { value: materialId ++ } );
  5763. this.uuid = MathUtils.generateUUID();
  5764. this.name = '';
  5765. this.type = 'Material';
  5766. this.fog = true;
  5767. this.blending = NormalBlending;
  5768. this.side = FrontSide;
  5769. this.flatShading = false;
  5770. this.vertexColors = false;
  5771. this.opacity = 1;
  5772. this.transparent = false;
  5773. this.blendSrc = SrcAlphaFactor;
  5774. this.blendDst = OneMinusSrcAlphaFactor;
  5775. this.blendEquation = AddEquation;
  5776. this.blendSrcAlpha = null;
  5777. this.blendDstAlpha = null;
  5778. this.blendEquationAlpha = null;
  5779. this.depthFunc = LessEqualDepth;
  5780. this.depthTest = true;
  5781. this.depthWrite = true;
  5782. this.stencilWriteMask = 0xff;
  5783. this.stencilFunc = AlwaysStencilFunc;
  5784. this.stencilRef = 0;
  5785. this.stencilFuncMask = 0xff;
  5786. this.stencilFail = KeepStencilOp;
  5787. this.stencilZFail = KeepStencilOp;
  5788. this.stencilZPass = KeepStencilOp;
  5789. this.stencilWrite = false;
  5790. this.clippingPlanes = null;
  5791. this.clipIntersection = false;
  5792. this.clipShadows = false;
  5793. this.shadowSide = null;
  5794. this.colorWrite = true;
  5795. this.precision = null; // override the renderer's default precision for this material
  5796. this.polygonOffset = false;
  5797. this.polygonOffsetFactor = 0;
  5798. this.polygonOffsetUnits = 0;
  5799. this.dithering = false;
  5800. this.alphaTest = 0;
  5801. this.premultipliedAlpha = false;
  5802. this.visible = true;
  5803. this.toneMapped = true;
  5804. this.userData = {};
  5805. this.version = 0;
  5806. }
  5807. Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  5808. constructor: Material,
  5809. isMaterial: true,
  5810. onBeforeCompile: function ( /* shaderobject, renderer */ ) {},
  5811. customProgramCacheKey: function () {
  5812. return this.onBeforeCompile.toString();
  5813. },
  5814. setValues: function ( values ) {
  5815. if ( values === undefined ) return;
  5816. for ( const key in values ) {
  5817. const newValue = values[ key ];
  5818. if ( newValue === undefined ) {
  5819. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5820. continue;
  5821. }
  5822. // for backward compatability if shading is set in the constructor
  5823. if ( key === 'shading' ) {
  5824. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  5825. this.flatShading = ( newValue === FlatShading ) ? true : false;
  5826. continue;
  5827. }
  5828. const currentValue = this[ key ];
  5829. if ( currentValue === undefined ) {
  5830. //console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  5831. continue;
  5832. }
  5833. if ( currentValue && currentValue.isColor ) {
  5834. currentValue.set( newValue );
  5835. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5836. currentValue.copy( newValue );
  5837. } else {
  5838. this[ key ] = newValue;
  5839. }
  5840. }
  5841. },
  5842. toJSON: function ( meta ) {
  5843. const isRoot = ( meta === undefined || typeof meta === 'string' );
  5844. if ( isRoot ) {
  5845. meta = {
  5846. textures: {},
  5847. images: {}
  5848. };
  5849. }
  5850. const data = {
  5851. metadata: {
  5852. version: 4.5,
  5853. type: 'Material',
  5854. generator: 'Material.toJSON'
  5855. }
  5856. };
  5857. // standard Material serialization
  5858. data.uuid = this.uuid;
  5859. data.type = this.type;
  5860. if ( this.name !== '' ) data.name = this.name;
  5861. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5862. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5863. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5864. if ( this.sheen && this.sheen.isColor ) data.sheen = this.sheen.getHex();
  5865. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5866. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5867. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5868. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5869. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5870. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5871. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5872. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5873. }
  5874. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5875. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5876. }
  5877. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5878. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5879. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5880. }
  5881. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5882. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5883. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5884. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5885. if ( this.aoMap && this.aoMap.isTexture ) {
  5886. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5887. data.aoMapIntensity = this.aoMapIntensity;
  5888. }
  5889. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5890. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5891. data.bumpScale = this.bumpScale;
  5892. }
  5893. if ( this.normalMap && this.normalMap.isTexture ) {
  5894. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5895. data.normalMapType = this.normalMapType;
  5896. data.normalScale = this.normalScale.toArray();
  5897. }
  5898. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5899. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5900. data.displacementScale = this.displacementScale;
  5901. data.displacementBias = this.displacementBias;
  5902. }
  5903. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5904. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5905. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5906. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5907. if ( this.envMap && this.envMap.isTexture ) {
  5908. data.envMap = this.envMap.toJSON( meta ).uuid;
  5909. data.reflectivity = this.reflectivity; // Scale behind envMap
  5910. data.refractionRatio = this.refractionRatio;
  5911. if ( this.combine !== undefined ) data.combine = this.combine;
  5912. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5913. }
  5914. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5915. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5916. }
  5917. if ( this.size !== undefined ) data.size = this.size;
  5918. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5919. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5920. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5921. if ( this.side !== FrontSide ) data.side = this.side;
  5922. if ( this.vertexColors ) data.vertexColors = true;
  5923. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5924. if ( this.transparent === true ) data.transparent = this.transparent;
  5925. data.depthFunc = this.depthFunc;
  5926. data.depthTest = this.depthTest;
  5927. data.depthWrite = this.depthWrite;
  5928. data.stencilWrite = this.stencilWrite;
  5929. data.stencilWriteMask = this.stencilWriteMask;
  5930. data.stencilFunc = this.stencilFunc;
  5931. data.stencilRef = this.stencilRef;
  5932. data.stencilFuncMask = this.stencilFuncMask;
  5933. data.stencilFail = this.stencilFail;
  5934. data.stencilZFail = this.stencilZFail;
  5935. data.stencilZPass = this.stencilZPass;
  5936. // rotation (SpriteMaterial)
  5937. if ( this.rotation && this.rotation !== 0 ) data.rotation = this.rotation;
  5938. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5939. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5940. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5941. if ( this.lineWidth && this.lineWidth !== 1 ) data.lineWidth = this.lineWidth;
  5942. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5943. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5944. if ( this.scale !== undefined ) data.scale = this.scale;
  5945. if ( this.dithering === true ) data.dithering = true;
  5946. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5947. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5948. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5949. if ( this.wireframelineWidth > 1 ) data.wireframelineWidth = this.wireframelineWidth;
  5950. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5951. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5952. if ( this.morphTargets === true ) data.morphTargets = true;
  5953. if ( this.morphNormals === true ) data.morphNormals = true;
  5954. if ( this.skinning === true ) data.skinning = true;
  5955. if ( this.visible === false ) data.visible = false;
  5956. if ( this.toneMapped === false ) data.toneMapped = false;
  5957. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  5958. // TODO: Copied from Object3D.toJSON
  5959. function extractFromCache( cache ) {
  5960. const values = [];
  5961. for ( const key in cache ) {
  5962. const data = cache[ key ];
  5963. delete data.metadata;
  5964. values.push( data );
  5965. }
  5966. return values;
  5967. }
  5968. if ( isRoot ) {
  5969. const textures = extractFromCache( meta.textures );
  5970. const images = extractFromCache( meta.images );
  5971. if ( textures.length > 0 ) data.textures = textures;
  5972. if ( images.length > 0 ) data.images = images;
  5973. }
  5974. return data;
  5975. },
  5976. clone: function () {
  5977. return new this.constructor().copy( this );
  5978. },
  5979. copy: function ( source ) {
  5980. this.name = source.name;
  5981. this.fog = source.fog;
  5982. this.blending = source.blending;
  5983. this.side = source.side;
  5984. this.flatShading = source.flatShading;
  5985. this.vertexColors = source.vertexColors;
  5986. this.opacity = source.opacity;
  5987. this.transparent = source.transparent;
  5988. this.blendSrc = source.blendSrc;
  5989. this.blendDst = source.blendDst;
  5990. this.blendEquation = source.blendEquation;
  5991. this.blendSrcAlpha = source.blendSrcAlpha;
  5992. this.blendDstAlpha = source.blendDstAlpha;
  5993. this.blendEquationAlpha = source.blendEquationAlpha;
  5994. this.depthFunc = source.depthFunc;
  5995. this.depthTest = source.depthTest;
  5996. this.depthWrite = source.depthWrite;
  5997. this.stencilWriteMask = source.stencilWriteMask;
  5998. this.stencilFunc = source.stencilFunc;
  5999. this.stencilRef = source.stencilRef;
  6000. this.stencilFuncMask = source.stencilFuncMask;
  6001. this.stencilFail = source.stencilFail;
  6002. this.stencilZFail = source.stencilZFail;
  6003. this.stencilZPass = source.stencilZPass;
  6004. this.stencilWrite = source.stencilWrite;
  6005. const srcPlanes = source.clippingPlanes;
  6006. let dstPlanes = null;
  6007. if ( srcPlanes !== null ) {
  6008. const n = srcPlanes.length;
  6009. dstPlanes = new Array( n );
  6010. for ( let i = 0; i !== n; ++ i ) {
  6011. dstPlanes[ i ] = srcPlanes[ i ].clone();
  6012. }
  6013. }
  6014. this.clippingPlanes = dstPlanes;
  6015. this.clipIntersection = source.clipIntersection;
  6016. this.clipShadows = source.clipShadows;
  6017. this.shadowSide = source.shadowSide;
  6018. this.colorWrite = source.colorWrite;
  6019. this.precision = source.precision;
  6020. this.polygonOffset = source.polygonOffset;
  6021. this.polygonOffsetFactor = source.polygonOffsetFactor;
  6022. this.polygonOffsetUnits = source.polygonOffsetUnits;
  6023. this.dithering = source.dithering;
  6024. this.alphaTest = source.alphaTest;
  6025. this.premultipliedAlpha = source.premultipliedAlpha;
  6026. this.visible = source.visible;
  6027. this.toneMapped = source.toneMapped;
  6028. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  6029. return this;
  6030. },
  6031. dispose: function () {
  6032. this.dispatchEvent( { type: 'dispose' } );
  6033. }
  6034. } );
  6035. Object.defineProperty( Material.prototype, 'needsUpdate', {
  6036. set: function ( value ) {
  6037. if ( value === true ) this.version ++;
  6038. }
  6039. } );
  6040. /**
  6041. * parameters = {
  6042. * color: <hex>,
  6043. * opacity: <float>,
  6044. * map: new THREE.Texture( <Image> ),
  6045. *
  6046. * lightMap: new THREE.Texture( <Image> ),
  6047. * lightMapIntensity: <float>
  6048. *
  6049. * aoMap: new THREE.Texture( <Image> ),
  6050. * aoMapIntensity: <float>
  6051. *
  6052. * specularMap: new THREE.Texture( <Image> ),
  6053. *
  6054. * alphaMap: new THREE.Texture( <Image> ),
  6055. *
  6056. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  6057. * combine: THREE.Multiply,
  6058. * reflectivity: <float>,
  6059. * refractionRatio: <float>,
  6060. *
  6061. * depthTest: <bool>,
  6062. * depthWrite: <bool>,
  6063. *
  6064. * wireframe: <boolean>,
  6065. * wireframelineWidth: <float>,
  6066. *
  6067. * skinning: <bool>,
  6068. * morphTargets: <bool>
  6069. * }
  6070. */
  6071. function MeshBasicMaterial( parameters ) {
  6072. Material.call( this );
  6073. this.type = 'MeshBasicMaterial';
  6074. this.color = new Color( 0xffffff ); // emissive
  6075. this.map = null;
  6076. this.lightMap = null;
  6077. this.lightMapIntensity = 1.0;
  6078. this.aoMap = null;
  6079. this.aoMapIntensity = 1.0;
  6080. this.specularMap = null;
  6081. this.alphaMap = null;
  6082. this.envMap = null;
  6083. this.combine = MultiplyOperation;
  6084. this.reflectivity = 1;
  6085. this.refractionRatio = 0.98;
  6086. this.wireframe = false;
  6087. this.wireframelineWidth = 1;
  6088. this.wireframeLinecap = 'round';
  6089. this.wireframeLinejoin = 'round';
  6090. this.skinning = false;
  6091. this.morphTargets = false;
  6092. this.setValues( parameters );
  6093. }
  6094. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  6095. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  6096. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  6097. MeshBasicMaterial.prototype.copy = function ( source ) {
  6098. Material.prototype.copy.call( this, source );
  6099. this.color.copy( source.color );
  6100. this.map = source.map;
  6101. this.lightMap = source.lightMap;
  6102. this.lightMapIntensity = source.lightMapIntensity;
  6103. this.aoMap = source.aoMap;
  6104. this.aoMapIntensity = source.aoMapIntensity;
  6105. this.specularMap = source.specularMap;
  6106. this.alphaMap = source.alphaMap;
  6107. this.envMap = source.envMap;
  6108. this.combine = source.combine;
  6109. this.reflectivity = source.reflectivity;
  6110. this.refractionRatio = source.refractionRatio;
  6111. this.wireframe = source.wireframe;
  6112. this.wireframelineWidth = source.wireframelineWidth;
  6113. this.wireframeLinecap = source.wireframeLinecap;
  6114. this.wireframeLinejoin = source.wireframeLinejoin;
  6115. this.skinning = source.skinning;
  6116. this.morphTargets = source.morphTargets;
  6117. return this;
  6118. };
  6119. const _vector$3 = new Vector3();
  6120. const _vector2$1 = new Vector2$1();
  6121. function BufferAttribute( array, itemSize, normalized ) {
  6122. if ( Array.isArray( array ) ) {
  6123. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  6124. }
  6125. this.name = '';
  6126. this.array = array;
  6127. this.itemSize = itemSize;
  6128. this.count = array !== undefined ? array.length / itemSize : 0;
  6129. this.normalized = normalized === true;
  6130. this.usage = StaticDrawUsage;
  6131. this.updateRange = { offset: 0, count: - 1 };
  6132. this.version = 0;
  6133. }
  6134. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  6135. set: function ( value ) {
  6136. if ( value === true ) this.version ++;
  6137. }
  6138. } );
  6139. Object.assign( BufferAttribute.prototype, {
  6140. isBufferAttribute: true,
  6141. onUploadCallback: function () {},
  6142. setUsage: function ( value ) {
  6143. this.usage = value;
  6144. return this;
  6145. },
  6146. copy: function ( source ) {
  6147. this.name = source.name;
  6148. this.array = new source.array.constructor( source.array );
  6149. this.itemSize = source.itemSize;
  6150. this.count = source.count;
  6151. this.normalized = source.normalized;
  6152. this.usage = source.usage;
  6153. return this;
  6154. },
  6155. copyAt: function ( index1, attribute, index2 ) {
  6156. index1 *= this.itemSize;
  6157. index2 *= attribute.itemSize;
  6158. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  6159. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  6160. }
  6161. return this;
  6162. },
  6163. copyArray: function ( array ) {
  6164. this.array.set( array );
  6165. return this;
  6166. },
  6167. copyColorsArray: function ( colors ) {
  6168. const array = this.array;
  6169. let offset = 0;
  6170. for ( let i = 0, l = colors.length; i < l; i ++ ) {
  6171. let color = colors[ i ];
  6172. if ( color === undefined ) {
  6173. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  6174. color = new Color();
  6175. }
  6176. array[ offset ++ ] = color.r;
  6177. array[ offset ++ ] = color.g;
  6178. array[ offset ++ ] = color.b;
  6179. }
  6180. return this;
  6181. },
  6182. copyVector2sArray: function ( vectors ) {
  6183. const array = this.array;
  6184. let offset = 0;
  6185. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  6186. let vector = vectors[ i ];
  6187. if ( vector === undefined ) {
  6188. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  6189. vector = new Vector2$1();
  6190. }
  6191. array[ offset ++ ] = vector.x;
  6192. array[ offset ++ ] = vector.y;
  6193. }
  6194. return this;
  6195. },
  6196. copyVector3sArray: function ( vectors ) {
  6197. const array = this.array;
  6198. let offset = 0;
  6199. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  6200. let vector = vectors[ i ];
  6201. if ( vector === undefined ) {
  6202. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  6203. vector = new Vector3();
  6204. }
  6205. array[ offset ++ ] = vector.x;
  6206. array[ offset ++ ] = vector.y;
  6207. array[ offset ++ ] = vector.z;
  6208. }
  6209. return this;
  6210. },
  6211. copyVector4sArray: function ( vectors ) {
  6212. const array = this.array;
  6213. let offset = 0;
  6214. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  6215. let vector = vectors[ i ];
  6216. if ( vector === undefined ) {
  6217. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  6218. vector = new Vector4();
  6219. }
  6220. array[ offset ++ ] = vector.x;
  6221. array[ offset ++ ] = vector.y;
  6222. array[ offset ++ ] = vector.z;
  6223. array[ offset ++ ] = vector.w;
  6224. }
  6225. return this;
  6226. },
  6227. applyMatrix3: function ( m ) {
  6228. if ( this.itemSize === 2 ) {
  6229. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6230. _vector2$1.fromBufferAttribute( this, i );
  6231. _vector2$1.applyMatrix3( m );
  6232. this.setXY( i, _vector2$1.x, _vector2$1.y );
  6233. }
  6234. } else if ( this.itemSize === 3 ) {
  6235. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6236. _vector$3.fromBufferAttribute( this, i );
  6237. _vector$3.applyMatrix3( m );
  6238. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  6239. }
  6240. }
  6241. return this;
  6242. },
  6243. applyMatrix4: function ( m ) {
  6244. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6245. _vector$3.x = this.getX( i );
  6246. _vector$3.y = this.getY( i );
  6247. _vector$3.z = this.getZ( i );
  6248. _vector$3.applyMatrix4( m );
  6249. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  6250. }
  6251. return this;
  6252. },
  6253. applyNormalMatrix: function ( m ) {
  6254. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6255. _vector$3.x = this.getX( i );
  6256. _vector$3.y = this.getY( i );
  6257. _vector$3.z = this.getZ( i );
  6258. _vector$3.applyNormalMatrix( m );
  6259. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  6260. }
  6261. return this;
  6262. },
  6263. transformDirection: function ( m ) {
  6264. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6265. _vector$3.x = this.getX( i );
  6266. _vector$3.y = this.getY( i );
  6267. _vector$3.z = this.getZ( i );
  6268. _vector$3.transformDirection( m );
  6269. this.setXYZ( i, _vector$3.x, _vector$3.y, _vector$3.z );
  6270. }
  6271. return this;
  6272. },
  6273. set: function ( value, offset = 0 ) {
  6274. this.array.set( value, offset );
  6275. return this;
  6276. },
  6277. getX: function ( index ) {
  6278. return this.array[ index * this.itemSize ];
  6279. },
  6280. setX: function ( index, x ) {
  6281. this.array[ index * this.itemSize ] = x;
  6282. return this;
  6283. },
  6284. getY: function ( index ) {
  6285. return this.array[ index * this.itemSize + 1 ];
  6286. },
  6287. setY: function ( index, y ) {
  6288. this.array[ index * this.itemSize + 1 ] = y;
  6289. return this;
  6290. },
  6291. getZ: function ( index ) {
  6292. return this.array[ index * this.itemSize + 2 ];
  6293. },
  6294. setZ: function ( index, z ) {
  6295. this.array[ index * this.itemSize + 2 ] = z;
  6296. return this;
  6297. },
  6298. getW: function ( index ) {
  6299. return this.array[ index * this.itemSize + 3 ];
  6300. },
  6301. setW: function ( index, w ) {
  6302. this.array[ index * this.itemSize + 3 ] = w;
  6303. return this;
  6304. },
  6305. setXY: function ( index, x, y ) {
  6306. index *= this.itemSize;
  6307. this.array[ index + 0 ] = x;
  6308. this.array[ index + 1 ] = y;
  6309. return this;
  6310. },
  6311. setXYZ: function ( index, x, y, z ) {
  6312. index *= this.itemSize;
  6313. this.array[ index + 0 ] = x;
  6314. this.array[ index + 1 ] = y;
  6315. this.array[ index + 2 ] = z;
  6316. return this;
  6317. },
  6318. setXYZW: function ( index, x, y, z, w ) {
  6319. index *= this.itemSize;
  6320. this.array[ index + 0 ] = x;
  6321. this.array[ index + 1 ] = y;
  6322. this.array[ index + 2 ] = z;
  6323. this.array[ index + 3 ] = w;
  6324. return this;
  6325. },
  6326. onUpload: function ( callback ) {
  6327. this.onUploadCallback = callback;
  6328. return this;
  6329. },
  6330. clone: function () {
  6331. return new this.constructor( this.array, this.itemSize ).copy( this );
  6332. },
  6333. toJSON: function () {
  6334. return {
  6335. itemSize: this.itemSize,
  6336. type: this.array.constructor.name,
  6337. array: Array.prototype.slice.call( this.array ),
  6338. normalized: this.normalized
  6339. };
  6340. }
  6341. } );
  6342. //
  6343. function Int8BufferAttribute( array, itemSize, normalized ) {
  6344. BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );
  6345. }
  6346. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6347. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  6348. function Uint8BufferAttribute( array, itemSize, normalized ) {
  6349. BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );
  6350. }
  6351. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6352. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  6353. function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {
  6354. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );
  6355. }
  6356. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6357. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  6358. function Int16BufferAttribute( array, itemSize, normalized ) {
  6359. BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );
  6360. }
  6361. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6362. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  6363. function Uint16BufferAttribute( array, itemSize, normalized ) {
  6364. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  6365. }
  6366. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6367. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  6368. function Int32BufferAttribute( array, itemSize, normalized ) {
  6369. BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );
  6370. }
  6371. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6372. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  6373. function Uint32BufferAttribute( array, itemSize, normalized ) {
  6374. BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );
  6375. }
  6376. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6377. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  6378. function Float16BufferAttribute( array, itemSize, normalized ) {
  6379. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  6380. }
  6381. Float16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6382. Float16BufferAttribute.prototype.constructor = Float16BufferAttribute;
  6383. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  6384. function Float32BufferAttribute( array, itemSize, normalized ) {
  6385. BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );
  6386. }
  6387. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6388. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  6389. function Float64BufferAttribute( array, itemSize, normalized ) {
  6390. BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );
  6391. }
  6392. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  6393. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  6394. class DirectGeometry {
  6395. constructor() {
  6396. this.vertices = [];
  6397. this.normals = [];
  6398. this.colors = [];
  6399. this.uvs = [];
  6400. this.uvs2 = [];
  6401. this.groups = [];
  6402. this.morphTargets = {};
  6403. this.skinWeights = [];
  6404. this.skinIndices = [];
  6405. // this.lineDistances = [];
  6406. this.boundingBox = null;
  6407. this.boundingSphere = null;
  6408. // update flags
  6409. this.verticesNeedUpdate = false;
  6410. this.normalsNeedUpdate = false;
  6411. this.colorsNeedUpdate = false;
  6412. this.uvsNeedUpdate = false;
  6413. this.groupsNeedUpdate = false;
  6414. }
  6415. computeGroups( geometry ) {
  6416. const groups = [];
  6417. let group, i;
  6418. let materialIndex = undefined;
  6419. const faces = geometry.faces;
  6420. for ( i = 0; i < faces.length; i ++ ) {
  6421. const face = faces[ i ];
  6422. // materials
  6423. if ( face.materialIndex !== materialIndex ) {
  6424. materialIndex = face.materialIndex;
  6425. if ( group !== undefined ) {
  6426. group.count = ( i * 3 ) - group.start;
  6427. groups.push( group );
  6428. }
  6429. group = {
  6430. start: i * 3,
  6431. materialIndex: materialIndex
  6432. };
  6433. }
  6434. }
  6435. if ( group !== undefined ) {
  6436. group.count = ( i * 3 ) - group.start;
  6437. groups.push( group );
  6438. }
  6439. this.groups = groups;
  6440. }
  6441. fromGeometry( geometry ) {
  6442. const faces = geometry.faces;
  6443. const vertices = geometry.vertices;
  6444. const faceVertexUvs = geometry.faceVertexUvs;
  6445. const hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  6446. const hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  6447. // morphs
  6448. const morphTargets = geometry.morphTargets;
  6449. const morphTargetsLength = morphTargets.length;
  6450. let morphTargetsPosition;
  6451. if ( morphTargetsLength > 0 ) {
  6452. morphTargetsPosition = [];
  6453. for ( let i = 0; i < morphTargetsLength; i ++ ) {
  6454. morphTargetsPosition[ i ] = {
  6455. name: morphTargets[ i ].name,
  6456. data: []
  6457. };
  6458. }
  6459. this.morphTargets.position = morphTargetsPosition;
  6460. }
  6461. const morphNormals = geometry.morphNormals;
  6462. const morphNormalsLength = morphNormals.length;
  6463. let morphTargetsNormal;
  6464. if ( morphNormalsLength > 0 ) {
  6465. morphTargetsNormal = [];
  6466. for ( let i = 0; i < morphNormalsLength; i ++ ) {
  6467. morphTargetsNormal[ i ] = {
  6468. name: morphNormals[ i ].name,
  6469. data: []
  6470. };
  6471. }
  6472. this.morphTargets.normal = morphTargetsNormal;
  6473. }
  6474. // skins
  6475. const skinIndices = geometry.skinIndices;
  6476. const skinWeights = geometry.skinWeights;
  6477. const hasSkinIndices = skinIndices.length === vertices.length;
  6478. const hasSkinWeights = skinWeights.length === vertices.length;
  6479. //
  6480. if ( vertices.length > 0 && faces.length === 0 ) {
  6481. console.error( 'THREE.DirectGeometry: Faceless geometries are not supported.' );
  6482. }
  6483. for ( let i = 0; i < faces.length; i ++ ) {
  6484. const face = faces[ i ];
  6485. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  6486. const vertexNormals = face.vertexNormals;
  6487. if ( vertexNormals.length === 3 ) {
  6488. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  6489. } else {
  6490. const normal = face.normal;
  6491. this.normals.push( normal, normal, normal );
  6492. }
  6493. const vertexColors = face.vertexColors;
  6494. if ( vertexColors.length === 3 ) {
  6495. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  6496. } else {
  6497. const color = face.color;
  6498. this.colors.push( color, color, color );
  6499. }
  6500. if ( hasFaceVertexUv === true ) {
  6501. const vertexUvs = faceVertexUvs[ 0 ][ i ];
  6502. if ( vertexUvs !== undefined ) {
  6503. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6504. } else {
  6505. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  6506. this.uvs.push( new Vector2$1(), new Vector2$1(), new Vector2$1() );
  6507. }
  6508. }
  6509. if ( hasFaceVertexUv2 === true ) {
  6510. const vertexUvs = faceVertexUvs[ 1 ][ i ];
  6511. if ( vertexUvs !== undefined ) {
  6512. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6513. } else {
  6514. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  6515. this.uvs2.push( new Vector2$1(), new Vector2$1(), new Vector2$1() );
  6516. }
  6517. }
  6518. // morphs
  6519. for ( let j = 0; j < morphTargetsLength; j ++ ) {
  6520. const morphTarget = morphTargets[ j ].vertices;
  6521. morphTargetsPosition[ j ].data.push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  6522. }
  6523. for ( let j = 0; j < morphNormalsLength; j ++ ) {
  6524. const morphNormal = morphNormals[ j ].vertexNormals[ i ];
  6525. morphTargetsNormal[ j ].data.push( morphNormal.a, morphNormal.b, morphNormal.c );
  6526. }
  6527. // skins
  6528. if ( hasSkinIndices ) {
  6529. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  6530. }
  6531. if ( hasSkinWeights ) {
  6532. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  6533. }
  6534. }
  6535. this.computeGroups( geometry );
  6536. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6537. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6538. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6539. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6540. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6541. if ( geometry.boundingSphere !== null ) {
  6542. this.boundingSphere = geometry.boundingSphere.clone();
  6543. }
  6544. if ( geometry.boundingBox !== null ) {
  6545. this.boundingBox = geometry.boundingBox.clone();
  6546. }
  6547. return this;
  6548. }
  6549. }
  6550. function arrayMax( array ) {
  6551. if ( array.length === 0 ) return - Infinity;
  6552. let max = array[ 0 ];
  6553. for ( let i = 1, l = array.length; i < l; ++ i ) {
  6554. if ( array[ i ] > max ) max = array[ i ];
  6555. }
  6556. return max;
  6557. }
  6558. const TYPED_ARRAYS = {
  6559. Int8Array: Int8Array,
  6560. Uint8Array: Uint8Array,
  6561. // Workaround for IE11 pre KB2929437. See #11440
  6562. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  6563. Int16Array: Int16Array,
  6564. Uint16Array: Uint16Array,
  6565. Int32Array: Int32Array,
  6566. Uint32Array: Uint32Array,
  6567. Float32Array: Float32Array,
  6568. Float64Array: Float64Array
  6569. };
  6570. function getTypedArray( type, buffer ) {
  6571. return new TYPED_ARRAYS[ type ]( buffer );
  6572. }
  6573. let _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  6574. const _m1$2 = new Matrix4();
  6575. const _obj = new Object3D();
  6576. const _offset = new Vector3();
  6577. const _box$2 = new Box3();
  6578. const _boxMorphTargets = new Box3();
  6579. const _vector$4 = new Vector3();
  6580. function BufferGeometry() {
  6581. Object.defineProperty( this, 'id', { value: _bufferGeometryId += 2 } );
  6582. this.uuid = MathUtils.generateUUID();
  6583. this.name = '';
  6584. this.type = 'BufferGeometry';
  6585. this.index = null;
  6586. this.attributes = {};
  6587. this.morphAttributes = {};
  6588. this.morphTargetsRelative = false;
  6589. this.groups = [];
  6590. this.boundingBox = null;
  6591. this.boundingSphere = null;
  6592. this.drawRange = { start: 0, count: Infinity };
  6593. this.userData = {};
  6594. }
  6595. BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  6596. constructor: BufferGeometry,
  6597. isBufferGeometry: true,
  6598. getIndex: function () {
  6599. return this.index;
  6600. },
  6601. setIndex: function ( index ) {
  6602. if ( Array.isArray( index ) ) {
  6603. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6604. } else {
  6605. this.index = index;
  6606. }
  6607. return this;
  6608. },
  6609. getAttribute: function ( name ) {
  6610. return this.attributes[ name ];
  6611. },
  6612. setAttribute: function ( name, attribute ) {
  6613. this.attributes[ name ] = attribute;
  6614. return this;
  6615. },
  6616. deleteAttribute: function ( name ) {
  6617. delete this.attributes[ name ];
  6618. return this;
  6619. },
  6620. hasAttribute: function ( name ) {
  6621. return this.attributes[ name ] !== undefined;
  6622. },
  6623. addGroup: function ( start, count, materialIndex = 0 ) {
  6624. this.groups.push( {
  6625. start: start,
  6626. count: count,
  6627. materialIndex: materialIndex
  6628. } );
  6629. },
  6630. clearGroups: function () {
  6631. this.groups = [];
  6632. },
  6633. setDrawRange: function ( start, count ) {
  6634. this.drawRange.start = start;
  6635. this.drawRange.count = count;
  6636. },
  6637. applyMatrix4: function ( matrix ) {
  6638. const position = this.attributes.position;
  6639. if ( position !== undefined ) {
  6640. position.applyMatrix4( matrix );
  6641. position.needsUpdate = true;
  6642. }
  6643. const normal = this.attributes.normal;
  6644. if ( normal !== undefined ) {
  6645. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6646. normal.applyNormalMatrix( normalMatrix );
  6647. normal.needsUpdate = true;
  6648. }
  6649. const tangent = this.attributes.tangent;
  6650. if ( tangent !== undefined ) {
  6651. tangent.transformDirection( matrix );
  6652. tangent.needsUpdate = true;
  6653. }
  6654. if ( this.boundingBox !== null ) {
  6655. this.computeBoundingBox();
  6656. }
  6657. if ( this.boundingSphere !== null ) {
  6658. this.computeBoundingSphere();
  6659. }
  6660. return this;
  6661. },
  6662. rotateX: function ( angle ) {
  6663. // rotate geometry around world x-axis
  6664. _m1$2.makeRotationX( angle );
  6665. this.applyMatrix4( _m1$2 );
  6666. return this;
  6667. },
  6668. rotateY: function ( angle ) {
  6669. // rotate geometry around world y-axis
  6670. _m1$2.makeRotationY( angle );
  6671. this.applyMatrix4( _m1$2 );
  6672. return this;
  6673. },
  6674. rotateZ: function ( angle ) {
  6675. // rotate geometry around world z-axis
  6676. _m1$2.makeRotationZ( angle );
  6677. this.applyMatrix4( _m1$2 );
  6678. return this;
  6679. },
  6680. translate: function ( x, y, z ) {
  6681. // translate geometry
  6682. _m1$2.makeTranslation( x, y, z );
  6683. this.applyMatrix4( _m1$2 );
  6684. return this;
  6685. },
  6686. scale: function ( x, y, z ) {
  6687. // scale geometry
  6688. _m1$2.makeScale( x, y, z );
  6689. this.applyMatrix4( _m1$2 );
  6690. return this;
  6691. },
  6692. lookAt: function ( vector ) {
  6693. _obj.lookAt( vector );
  6694. _obj.updateMatrix();
  6695. this.applyMatrix4( _obj.matrix );
  6696. return this;
  6697. },
  6698. center: function () {
  6699. this.computeBoundingBox();
  6700. this.boundingBox.getCenter( _offset ).negate();
  6701. this.translate( _offset.x, _offset.y, _offset.z );
  6702. return this;
  6703. },
  6704. setFromObject: function ( object ) {
  6705. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6706. const geometry = object.geometry;
  6707. if ( object.isPoints || object.isLine ) {
  6708. const positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  6709. const colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  6710. this.setAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  6711. this.setAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  6712. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  6713. const lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  6714. this.setAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  6715. }
  6716. if ( geometry.boundingSphere !== null ) {
  6717. this.boundingSphere = geometry.boundingSphere.clone();
  6718. }
  6719. if ( geometry.boundingBox !== null ) {
  6720. this.boundingBox = geometry.boundingBox.clone();
  6721. }
  6722. } else if ( object.isMesh ) {
  6723. if ( geometry && geometry.isGeometry ) {
  6724. this.fromGeometry( geometry );
  6725. }
  6726. }
  6727. return this;
  6728. },
  6729. setFromPoints: function ( points ) {
  6730. const position = [];
  6731. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6732. const point = points[ i ];
  6733. position.push( point.x, point.y, point.z || 0 );
  6734. }
  6735. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6736. return this;
  6737. },
  6738. updateFromObject: function ( object ) {
  6739. let geometry = object.geometry;
  6740. if ( object.isMesh ) {
  6741. let direct = geometry.__directGeometry;
  6742. if ( geometry.elementsNeedUpdate === true ) {
  6743. direct = undefined;
  6744. geometry.elementsNeedUpdate = false;
  6745. }
  6746. if ( direct === undefined ) {
  6747. return this.fromGeometry( geometry );
  6748. }
  6749. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6750. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6751. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6752. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6753. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6754. geometry.verticesNeedUpdate = false;
  6755. geometry.normalsNeedUpdate = false;
  6756. geometry.colorsNeedUpdate = false;
  6757. geometry.uvsNeedUpdate = false;
  6758. geometry.groupsNeedUpdate = false;
  6759. geometry = direct;
  6760. }
  6761. if ( geometry.verticesNeedUpdate === true ) {
  6762. const attribute = this.attributes.position;
  6763. if ( attribute !== undefined ) {
  6764. attribute.copyVector3sArray( geometry.vertices );
  6765. attribute.needsUpdate = true;
  6766. }
  6767. geometry.verticesNeedUpdate = false;
  6768. }
  6769. if ( geometry.normalsNeedUpdate === true ) {
  6770. const attribute = this.attributes.normal;
  6771. if ( attribute !== undefined ) {
  6772. attribute.copyVector3sArray( geometry.normals );
  6773. attribute.needsUpdate = true;
  6774. }
  6775. geometry.normalsNeedUpdate = false;
  6776. }
  6777. if ( geometry.colorsNeedUpdate === true ) {
  6778. const attribute = this.attributes.color;
  6779. if ( attribute !== undefined ) {
  6780. attribute.copyColorsArray( geometry.colors );
  6781. attribute.needsUpdate = true;
  6782. }
  6783. geometry.colorsNeedUpdate = false;
  6784. }
  6785. if ( geometry.uvsNeedUpdate ) {
  6786. const attribute = this.attributes.uv;
  6787. if ( attribute !== undefined ) {
  6788. attribute.copyVector2sArray( geometry.uvs );
  6789. attribute.needsUpdate = true;
  6790. }
  6791. geometry.uvsNeedUpdate = false;
  6792. }
  6793. if ( geometry.lineDistancesNeedUpdate ) {
  6794. const attribute = this.attributes.lineDistance;
  6795. if ( attribute !== undefined ) {
  6796. attribute.copyArray( geometry.lineDistances );
  6797. attribute.needsUpdate = true;
  6798. }
  6799. geometry.lineDistancesNeedUpdate = false;
  6800. }
  6801. if ( geometry.groupsNeedUpdate ) {
  6802. geometry.computeGroups( object.geometry );
  6803. this.groups = geometry.groups;
  6804. geometry.groupsNeedUpdate = false;
  6805. }
  6806. return this;
  6807. },
  6808. fromGeometry: function ( geometry ) {
  6809. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  6810. return this.fromDirectGeometry( geometry.__directGeometry );
  6811. },
  6812. fromDirectGeometry: function ( geometry ) {
  6813. const positions = new Float32Array( geometry.vertices.length * 3 );
  6814. this.setAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  6815. if ( geometry.normals.length > 0 ) {
  6816. const normals = new Float32Array( geometry.normals.length * 3 );
  6817. this.setAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  6818. }
  6819. if ( geometry.colors.length > 0 ) {
  6820. const colors = new Float32Array( geometry.colors.length * 3 );
  6821. this.setAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  6822. }
  6823. if ( geometry.uvs.length > 0 ) {
  6824. const uvs = new Float32Array( geometry.uvs.length * 2 );
  6825. this.setAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  6826. }
  6827. if ( geometry.uvs2.length > 0 ) {
  6828. const uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  6829. this.setAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  6830. }
  6831. // groups
  6832. this.groups = geometry.groups;
  6833. // morphs
  6834. for ( const name in geometry.morphTargets ) {
  6835. const array = [];
  6836. const morphTargets = geometry.morphTargets[ name ];
  6837. for ( let i = 0, l = morphTargets.length; i < l; i ++ ) {
  6838. const morphTarget = morphTargets[ i ];
  6839. const attribute = new Float32BufferAttribute( morphTarget.data.length * 3, 3 );
  6840. attribute.name = morphTarget.name;
  6841. array.push( attribute.copyVector3sArray( morphTarget.data ) );
  6842. }
  6843. this.morphAttributes[ name ] = array;
  6844. }
  6845. // skinning
  6846. if ( geometry.skinIndices.length > 0 ) {
  6847. const skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  6848. this.setAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  6849. }
  6850. if ( geometry.skinWeights.length > 0 ) {
  6851. const skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  6852. this.setAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  6853. }
  6854. //
  6855. if ( geometry.boundingSphere !== null ) {
  6856. this.boundingSphere = geometry.boundingSphere.clone();
  6857. }
  6858. if ( geometry.boundingBox !== null ) {
  6859. this.boundingBox = geometry.boundingBox.clone();
  6860. }
  6861. return this;
  6862. },
  6863. computeBoundingBox: function () {
  6864. if ( this.boundingBox === null ) {
  6865. this.boundingBox = new Box3();
  6866. }
  6867. const position = this.attributes.position;
  6868. const morphAttributesPosition = this.morphAttributes.position;
  6869. if ( position && position.isGLBufferAttribute ) {
  6870. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6871. this.boundingBox.set(
  6872. new Vector3( - Infinity, - Infinity, - Infinity ),
  6873. new Vector3( + Infinity, + Infinity, + Infinity )
  6874. );
  6875. return;
  6876. }
  6877. if ( position !== undefined ) {
  6878. this.boundingBox.setFromBufferAttribute( position );
  6879. // process morph attributes if present
  6880. if ( morphAttributesPosition ) {
  6881. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6882. const morphAttribute = morphAttributesPosition[ i ];
  6883. _box$2.setFromBufferAttribute( morphAttribute );
  6884. if ( this.morphTargetsRelative ) {
  6885. _vector$4.addVectors( this.boundingBox.min, _box$2.min );
  6886. this.boundingBox.expandByPoint( _vector$4 );
  6887. _vector$4.addVectors( this.boundingBox.max, _box$2.max );
  6888. this.boundingBox.expandByPoint( _vector$4 );
  6889. } else {
  6890. this.boundingBox.expandByPoint( _box$2.min );
  6891. this.boundingBox.expandByPoint( _box$2.max );
  6892. }
  6893. }
  6894. }
  6895. } else {
  6896. this.boundingBox.makeEmpty();
  6897. }
  6898. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6899. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6900. }
  6901. },
  6902. computeBoundingSphere: function () {
  6903. if ( this.boundingSphere === null ) {
  6904. this.boundingSphere = new Sphere();
  6905. }
  6906. const position = this.attributes.position;
  6907. const morphAttributesPosition = this.morphAttributes.position;
  6908. if ( position && position.isGLBufferAttribute ) {
  6909. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6910. this.boundingSphere.set( new Vector3(), Infinity );
  6911. return;
  6912. }
  6913. if ( position ) {
  6914. // first, find the center of the bounding sphere
  6915. const center = this.boundingSphere.center;
  6916. _box$2.setFromBufferAttribute( position );
  6917. // process morph attributes if present
  6918. if ( morphAttributesPosition ) {
  6919. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6920. const morphAttribute = morphAttributesPosition[ i ];
  6921. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6922. if ( this.morphTargetsRelative ) {
  6923. _vector$4.addVectors( _box$2.min, _boxMorphTargets.min );
  6924. _box$2.expandByPoint( _vector$4 );
  6925. _vector$4.addVectors( _box$2.max, _boxMorphTargets.max );
  6926. _box$2.expandByPoint( _vector$4 );
  6927. } else {
  6928. _box$2.expandByPoint( _boxMorphTargets.min );
  6929. _box$2.expandByPoint( _boxMorphTargets.max );
  6930. }
  6931. }
  6932. }
  6933. _box$2.getCenter( center );
  6934. // second, try to find a boundingSphere with a radius smaller than the
  6935. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6936. let maxRadiusSq = 0;
  6937. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6938. _vector$4.fromBufferAttribute( position, i );
  6939. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
  6940. }
  6941. // process morph attributes if present
  6942. if ( morphAttributesPosition ) {
  6943. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6944. const morphAttribute = morphAttributesPosition[ i ];
  6945. const morphTargetsRelative = this.morphTargetsRelative;
  6946. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6947. _vector$4.fromBufferAttribute( morphAttribute, j );
  6948. if ( morphTargetsRelative ) {
  6949. _offset.fromBufferAttribute( position, j );
  6950. _vector$4.add( _offset );
  6951. }
  6952. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$4 ) );
  6953. }
  6954. }
  6955. }
  6956. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6957. if ( isNaN( this.boundingSphere.radius ) ) {
  6958. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6959. }
  6960. }
  6961. },
  6962. computeFaceNormals: function () {
  6963. // backwards compatibility
  6964. },
  6965. computeVertexNormals: function () {
  6966. const index = this.index;
  6967. const positionAttribute = this.getAttribute( 'position' );
  6968. if ( positionAttribute !== undefined ) {
  6969. let normalAttribute = this.getAttribute( 'normal' );
  6970. if ( normalAttribute === undefined ) {
  6971. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6972. this.setAttribute( 'normal', normalAttribute );
  6973. } else {
  6974. // reset existing normals to zero
  6975. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6976. normalAttribute.setXYZ( i, 0, 0, 0 );
  6977. }
  6978. }
  6979. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6980. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6981. const cb = new Vector3(), ab = new Vector3();
  6982. // indexed elements
  6983. if ( index ) {
  6984. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6985. const vA = index.getX( i + 0 );
  6986. const vB = index.getX( i + 1 );
  6987. const vC = index.getX( i + 2 );
  6988. pA.fromBufferAttribute( positionAttribute, vA );
  6989. pB.fromBufferAttribute( positionAttribute, vB );
  6990. pC.fromBufferAttribute( positionAttribute, vC );
  6991. cb.subVectors( pC, pB );
  6992. ab.subVectors( pA, pB );
  6993. cb.cross( ab );
  6994. nA.fromBufferAttribute( normalAttribute, vA );
  6995. nB.fromBufferAttribute( normalAttribute, vB );
  6996. nC.fromBufferAttribute( normalAttribute, vC );
  6997. nA.add( cb );
  6998. nB.add( cb );
  6999. nC.add( cb );
  7000. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  7001. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  7002. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  7003. }
  7004. } else {
  7005. // non-indexed elements (unconnected triangle soup)
  7006. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  7007. pA.fromBufferAttribute( positionAttribute, i + 0 );
  7008. pB.fromBufferAttribute( positionAttribute, i + 1 );
  7009. pC.fromBufferAttribute( positionAttribute, i + 2 );
  7010. cb.subVectors( pC, pB );
  7011. ab.subVectors( pA, pB );
  7012. cb.cross( ab );
  7013. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  7014. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  7015. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  7016. }
  7017. }
  7018. this.normalizeNormals();
  7019. normalAttribute.needsUpdate = true;
  7020. }
  7021. },
  7022. merge: function ( geometry, offset ) {
  7023. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  7024. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  7025. return;
  7026. }
  7027. if ( offset === undefined ) {
  7028. offset = 0;
  7029. console.warn(
  7030. 'THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '
  7031. + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.'
  7032. );
  7033. }
  7034. const attributes = this.attributes;
  7035. for ( const key in attributes ) {
  7036. if ( geometry.attributes[ key ] === undefined ) continue;
  7037. const attribute1 = attributes[ key ];
  7038. const attributeArray1 = attribute1.array;
  7039. const attribute2 = geometry.attributes[ key ];
  7040. const attributeArray2 = attribute2.array;
  7041. const attributeOffset = attribute2.itemSize * offset;
  7042. const length = Math.min( attributeArray2.length, attributeArray1.length - attributeOffset );
  7043. for ( let i = 0, j = attributeOffset; i < length; i ++, j ++ ) {
  7044. attributeArray1[ j ] = attributeArray2[ i ];
  7045. }
  7046. }
  7047. return this;
  7048. },
  7049. normalizeNormals: function () {
  7050. const normals = this.attributes.normal;
  7051. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  7052. _vector$4.fromBufferAttribute( normals, i );
  7053. _vector$4.normalize();
  7054. normals.setXYZ( i, _vector$4.x, _vector$4.y, _vector$4.z );
  7055. }
  7056. },
  7057. toNonIndexed: function () {
  7058. function convertBufferAttribute( attribute, indices ) {
  7059. const array = attribute.array;
  7060. const itemSize = attribute.itemSize;
  7061. const normalized = attribute.normalized;
  7062. const array2 = new array.constructor( indices.length * itemSize );
  7063. let index = 0, index2 = 0;
  7064. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  7065. index = indices[ i ] * itemSize;
  7066. for ( let j = 0; j < itemSize; j ++ ) {
  7067. array2[ index2 ++ ] = array[ index ++ ];
  7068. }
  7069. }
  7070. return new BufferAttribute( array2, itemSize, normalized );
  7071. }
  7072. //
  7073. if ( this.index === null ) {
  7074. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  7075. return this;
  7076. }
  7077. const geometry2 = new BufferGeometry();
  7078. const indices = this.index.array;
  7079. const attributes = this.attributes;
  7080. // attributes
  7081. for ( const name in attributes ) {
  7082. const attribute = attributes[ name ];
  7083. const newAttribute = convertBufferAttribute( attribute, indices );
  7084. geometry2.setAttribute( name, newAttribute );
  7085. }
  7086. // morph attributes
  7087. const morphAttributes = this.morphAttributes;
  7088. for ( const name in morphAttributes ) {
  7089. const morphArray = [];
  7090. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  7091. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  7092. const attribute = morphAttribute[ i ];
  7093. const newAttribute = convertBufferAttribute( attribute, indices );
  7094. morphArray.push( newAttribute );
  7095. }
  7096. geometry2.morphAttributes[ name ] = morphArray;
  7097. }
  7098. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  7099. // groups
  7100. const groups = this.groups;
  7101. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  7102. const group = groups[ i ];
  7103. geometry2.addGroup( group.start, group.count, group.materialIndex );
  7104. }
  7105. return geometry2;
  7106. },
  7107. toJSON: function () {
  7108. const data = {
  7109. metadata: {
  7110. version: 4.5,
  7111. type: 'BufferGeometry',
  7112. generator: 'BufferGeometry.toJSON'
  7113. }
  7114. };
  7115. // standard BufferGeometry serialization
  7116. data.uuid = this.uuid;
  7117. data.type = this.type;
  7118. if ( this.name !== '' ) data.name = this.name;
  7119. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  7120. if ( this.parameters !== undefined ) {
  7121. const parameters = this.parameters;
  7122. for ( const key in parameters ) {
  7123. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7124. }
  7125. return data;
  7126. }
  7127. data.data = { attributes: {} };
  7128. const index = this.index;
  7129. if ( index !== null ) {
  7130. data.data.index = {
  7131. type: index.array.constructor.name,
  7132. array: Array.prototype.slice.call( index.array )
  7133. };
  7134. }
  7135. const attributes = this.attributes;
  7136. for ( const key in attributes ) {
  7137. const attribute = attributes[ key ];
  7138. const attributeData = attribute.toJSON( data.data );
  7139. if ( attribute.name !== '' ) attributeData.name = attribute.name;
  7140. data.data.attributes[ key ] = attributeData;
  7141. }
  7142. const morphAttributes = {};
  7143. let hasMorphAttributes = false;
  7144. for ( const key in this.morphAttributes ) {
  7145. const attributeArray = this.morphAttributes[ key ];
  7146. const array = [];
  7147. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  7148. const attribute = attributeArray[ i ];
  7149. const attributeData = attribute.toJSON( data.data );
  7150. if ( attribute.name !== '' ) attributeData.name = attribute.name;
  7151. array.push( attributeData );
  7152. }
  7153. if ( array.length > 0 ) {
  7154. morphAttributes[ key ] = array;
  7155. hasMorphAttributes = true;
  7156. }
  7157. }
  7158. if ( hasMorphAttributes ) {
  7159. data.data.morphAttributes = morphAttributes;
  7160. data.data.morphTargetsRelative = this.morphTargetsRelative;
  7161. }
  7162. const groups = this.groups;
  7163. if ( groups.length > 0 ) {
  7164. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  7165. }
  7166. const boundingSphere = this.boundingSphere;
  7167. if ( boundingSphere !== null ) {
  7168. data.data.boundingSphere = {
  7169. center: boundingSphere.center.toArray(),
  7170. radius: boundingSphere.radius
  7171. };
  7172. }
  7173. return data;
  7174. },
  7175. clone: function () {
  7176. /*
  7177. // Handle primitives
  7178. const parameters = this.parameters;
  7179. if ( parameters !== undefined ) {
  7180. const values = [];
  7181. for ( const key in parameters ) {
  7182. values.push( parameters[ key ] );
  7183. }
  7184. const geometry = Object.create( this.constructor.prototype );
  7185. this.constructor.apply( geometry, values );
  7186. return geometry;
  7187. }
  7188. return new this.constructor().copy( this );
  7189. */
  7190. return new BufferGeometry().copy( this );
  7191. },
  7192. copy: function ( source ) {
  7193. // reset
  7194. this.index = null;
  7195. this.attributes = {};
  7196. this.morphAttributes = {};
  7197. this.groups = [];
  7198. this.boundingBox = null;
  7199. this.boundingSphere = null;
  7200. // used for storing cloned, shared data
  7201. const data = {};
  7202. // name
  7203. this.name = source.name;
  7204. // index
  7205. const index = source.index;
  7206. if ( index !== null ) {
  7207. this.setIndex( index.clone( data ) );
  7208. }
  7209. // attributes
  7210. const attributes = source.attributes;
  7211. for ( const name in attributes ) {
  7212. const attribute = attributes[ name ];
  7213. this.setAttribute( name, attribute.clone( data ) );
  7214. }
  7215. // morph attributes
  7216. const morphAttributes = source.morphAttributes;
  7217. for ( const name in morphAttributes ) {
  7218. const array = [];
  7219. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  7220. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  7221. array.push( morphAttribute[ i ].clone( data ) );
  7222. }
  7223. this.morphAttributes[ name ] = array;
  7224. }
  7225. this.morphTargetsRelative = source.morphTargetsRelative;
  7226. // groups
  7227. const groups = source.groups;
  7228. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  7229. const group = groups[ i ];
  7230. this.addGroup( group.start, group.count, group.materialIndex );
  7231. }
  7232. // bounding box
  7233. const boundingBox = source.boundingBox;
  7234. if ( boundingBox !== null ) {
  7235. this.boundingBox = boundingBox.clone();
  7236. }
  7237. // bounding sphere
  7238. const boundingSphere = source.boundingSphere;
  7239. if ( boundingSphere !== null ) {
  7240. this.boundingSphere = boundingSphere.clone();
  7241. }
  7242. // draw range
  7243. this.drawRange.start = source.drawRange.start;
  7244. this.drawRange.count = source.drawRange.count;
  7245. // user data
  7246. this.userData = source.userData;
  7247. return this;
  7248. },
  7249. dispose: function () {
  7250. this.dispatchEvent( { type: 'dispose' } );
  7251. }
  7252. } );
  7253. const _inverseMatrix = new Matrix4();
  7254. const _ray = new Ray();
  7255. const _sphere = new Sphere();
  7256. const _vA = new Vector3();
  7257. const _vB = new Vector3();
  7258. const _vC = new Vector3();
  7259. const _tempA = new Vector3();
  7260. const _tempB = new Vector3();
  7261. const _tempC = new Vector3();
  7262. const _morphA = new Vector3();
  7263. const _morphB = new Vector3();
  7264. const _morphC = new Vector3();
  7265. const _uvA = new Vector2$1();
  7266. const _uvB = new Vector2$1();
  7267. const _uvC = new Vector2$1();
  7268. const _intersectionPoint = new Vector3();
  7269. const _intersectionPointWorld = new Vector3();
  7270. function Mesh( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  7271. Object3D.call( this );
  7272. this.type = 'Mesh';
  7273. this.geometry = geometry;
  7274. this.material = material;
  7275. this.updateMorphTargets();
  7276. }
  7277. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  7278. constructor: Mesh,
  7279. isMesh: true,
  7280. copy: function ( source ) {
  7281. Object3D.prototype.copy.call( this, source );
  7282. if ( source.morphTargetInfluences !== undefined ) {
  7283. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  7284. }
  7285. if ( source.morphTargetDictionary !== undefined ) {
  7286. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  7287. }
  7288. this.material = source.material;
  7289. this.geometry = source.geometry;
  7290. return this;
  7291. },
  7292. updateMorphTargets: function () {
  7293. const geometry = this.geometry;
  7294. if ( geometry.isBufferGeometry ) {
  7295. const morphAttributes = geometry.morphAttributes;
  7296. const keys = Object.keys( morphAttributes );
  7297. if ( keys.length > 0 ) {
  7298. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  7299. if ( morphAttribute !== undefined ) {
  7300. this.morphTargetInfluences = [];
  7301. this.morphTargetDictionary = {};
  7302. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  7303. const name = morphAttribute[ m ].name || String( m );
  7304. this.morphTargetInfluences.push( 0 );
  7305. this.morphTargetDictionary[ name ] = m;
  7306. }
  7307. }
  7308. }
  7309. } else {
  7310. const morphTargets = geometry.morphTargets;
  7311. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  7312. console.error( 'THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  7313. }
  7314. }
  7315. },
  7316. raycast: function ( raycaster, intersects ) {
  7317. const geometry = this.geometry;
  7318. const material = this.material;
  7319. const matrixWorld = this.matrixWorld;
  7320. if ( material === undefined ) return;
  7321. // Checking boundingSphere distance to ray
  7322. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7323. _sphere.copy( geometry.boundingSphere );
  7324. _sphere.applyMatrix4( matrixWorld );
  7325. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  7326. //
  7327. _inverseMatrix.copy( matrixWorld ).invert();
  7328. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  7329. // Check boundingBox before continuing
  7330. if ( geometry.boundingBox !== null ) {
  7331. if ( _ray.intersectsBox( geometry.boundingBox ) === false ) return;
  7332. }
  7333. let intersection;
  7334. if ( geometry.isBufferGeometry ) {
  7335. const index = geometry.index;
  7336. const position = geometry.attributes.position;
  7337. const morphPosition = geometry.morphAttributes.position;
  7338. const morphTargetsRelative = geometry.morphTargetsRelative;
  7339. const uv = geometry.attributes.uv;
  7340. const uv2 = geometry.attributes.uv2;
  7341. const groups = geometry.groups;
  7342. const drawRange = geometry.drawRange;
  7343. if ( index !== null ) {
  7344. // indexed buffer geometry
  7345. if ( Array.isArray( material ) ) {
  7346. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7347. const group = groups[ i ];
  7348. const groupMaterial = material[ group.materialIndex ];
  7349. const start = Math.max( group.start, drawRange.start );
  7350. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  7351. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7352. const a = index.getX( j );
  7353. const b = index.getX( j + 1 );
  7354. const c = index.getX( j + 2 );
  7355. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7356. if ( intersection ) {
  7357. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  7358. intersection.face.materialIndex = group.materialIndex;
  7359. intersects.push( intersection );
  7360. }
  7361. }
  7362. }
  7363. } else {
  7364. const start = Math.max( 0, drawRange.start );
  7365. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  7366. for ( let i = start, il = end; i < il; i += 3 ) {
  7367. const a = index.getX( i );
  7368. const b = index.getX( i + 1 );
  7369. const c = index.getX( i + 2 );
  7370. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7371. if ( intersection ) {
  7372. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7373. intersects.push( intersection );
  7374. }
  7375. }
  7376. }
  7377. } else if ( position !== undefined ) {
  7378. // non-indexed buffer geometry
  7379. if ( Array.isArray( material ) ) {
  7380. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7381. const group = groups[ i ];
  7382. const groupMaterial = material[ group.materialIndex ];
  7383. const start = Math.max( group.start, drawRange.start );
  7384. const end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) );
  7385. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7386. const a = j;
  7387. const b = j + 1;
  7388. const c = j + 2;
  7389. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7390. if ( intersection ) {
  7391. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7392. intersection.face.materialIndex = group.materialIndex;
  7393. intersects.push( intersection );
  7394. }
  7395. }
  7396. }
  7397. } else {
  7398. const start = Math.max( 0, drawRange.start );
  7399. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7400. for ( let i = start, il = end; i < il; i += 3 ) {
  7401. const a = i;
  7402. const b = i + 1;
  7403. const c = i + 2;
  7404. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  7405. if ( intersection ) {
  7406. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7407. intersects.push( intersection );
  7408. }
  7409. }
  7410. }
  7411. }
  7412. } else if ( geometry.isGeometry ) {
  7413. const isMultiMaterial = Array.isArray( material );
  7414. const vertices = geometry.vertices;
  7415. const faces = geometry.faces;
  7416. let uvs;
  7417. const faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  7418. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  7419. for ( let f = 0, fl = faces.length; f < fl; f ++ ) {
  7420. const face = faces[ f ];
  7421. const faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  7422. if ( faceMaterial === undefined ) continue;
  7423. const fvA = vertices[ face.a ];
  7424. const fvB = vertices[ face.b ];
  7425. const fvC = vertices[ face.c ];
  7426. intersection = checkIntersection( this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint );
  7427. if ( intersection ) {
  7428. if ( uvs && uvs[ f ] ) {
  7429. const uvs_f = uvs[ f ];
  7430. _uvA.copy( uvs_f[ 0 ] );
  7431. _uvB.copy( uvs_f[ 1 ] );
  7432. _uvC.copy( uvs_f[ 2 ] );
  7433. intersection.uv = Triangle.getUV( _intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2$1() );
  7434. }
  7435. intersection.face = face;
  7436. intersection.faceIndex = f;
  7437. intersects.push( intersection );
  7438. }
  7439. }
  7440. }
  7441. }
  7442. } );
  7443. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  7444. let intersect;
  7445. if ( material.side === BackSide ) {
  7446. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7447. } else {
  7448. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  7449. }
  7450. if ( intersect === null ) return null;
  7451. _intersectionPointWorld.copy( point );
  7452. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7453. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7454. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7455. return {
  7456. distance: distance,
  7457. point: _intersectionPointWorld.clone(),
  7458. object: object
  7459. };
  7460. }
  7461. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  7462. _vA.fromBufferAttribute( position, a );
  7463. _vB.fromBufferAttribute( position, b );
  7464. _vC.fromBufferAttribute( position, c );
  7465. const morphInfluences = object.morphTargetInfluences;
  7466. if ( material.morphTargets && morphPosition && morphInfluences ) {
  7467. _morphA.set( 0, 0, 0 );
  7468. _morphB.set( 0, 0, 0 );
  7469. _morphC.set( 0, 0, 0 );
  7470. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  7471. const influence = morphInfluences[ i ];
  7472. const morphAttribute = morphPosition[ i ];
  7473. if ( influence === 0 ) continue;
  7474. _tempA.fromBufferAttribute( morphAttribute, a );
  7475. _tempB.fromBufferAttribute( morphAttribute, b );
  7476. _tempC.fromBufferAttribute( morphAttribute, c );
  7477. if ( morphTargetsRelative ) {
  7478. _morphA.addScaledVector( _tempA, influence );
  7479. _morphB.addScaledVector( _tempB, influence );
  7480. _morphC.addScaledVector( _tempC, influence );
  7481. } else {
  7482. _morphA.addScaledVector( _tempA.sub( _vA ), influence );
  7483. _morphB.addScaledVector( _tempB.sub( _vB ), influence );
  7484. _morphC.addScaledVector( _tempC.sub( _vC ), influence );
  7485. }
  7486. }
  7487. _vA.add( _morphA );
  7488. _vB.add( _morphB );
  7489. _vC.add( _morphC );
  7490. }
  7491. if ( object.isSkinnedMesh ) {
  7492. object.boneTransform( a, _vA );
  7493. object.boneTransform( b, _vB );
  7494. object.boneTransform( c, _vC );
  7495. }
  7496. const intersection = checkIntersection( object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint );
  7497. if ( intersection ) {
  7498. if ( uv ) {
  7499. _uvA.fromBufferAttribute( uv, a );
  7500. _uvB.fromBufferAttribute( uv, b );
  7501. _uvC.fromBufferAttribute( uv, c );
  7502. intersection.uv = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2$1() );
  7503. }
  7504. if ( uv2 ) {
  7505. _uvA.fromBufferAttribute( uv2, a );
  7506. _uvB.fromBufferAttribute( uv2, b );
  7507. _uvC.fromBufferAttribute( uv2, c );
  7508. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2$1() );
  7509. }
  7510. const face = new Face3( a, b, c );
  7511. Triangle.getNormal( _vA, _vB, _vC, face.normal );
  7512. intersection.face = face;
  7513. }
  7514. return intersection;
  7515. }
  7516. class BoxBufferGeometry extends BufferGeometry {
  7517. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7518. super();
  7519. this.type = 'BoxBufferGeometry';
  7520. this.parameters = {
  7521. width: width,
  7522. height: height,
  7523. depth: depth,
  7524. widthSegments: widthSegments,
  7525. heightSegments: heightSegments,
  7526. depthSegments: depthSegments
  7527. };
  7528. const scope = this;
  7529. // segments
  7530. widthSegments = Math.floor( widthSegments );
  7531. heightSegments = Math.floor( heightSegments );
  7532. depthSegments = Math.floor( depthSegments );
  7533. // buffers
  7534. const indices = [];
  7535. const vertices = [];
  7536. const normals = [];
  7537. const uvs = [];
  7538. // helper variables
  7539. let numberOfVertices = 0;
  7540. let groupStart = 0;
  7541. // build each side of the box geometry
  7542. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7543. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7544. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7545. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7546. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7547. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7548. // build geometry
  7549. this.setIndex( indices );
  7550. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7551. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7552. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7553. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7554. const segmentWidth = width / gridX;
  7555. const segmentHeight = height / gridY;
  7556. const widthHalf = width / 2;
  7557. const heightHalf = height / 2;
  7558. const depthHalf = depth / 2;
  7559. const gridX1 = gridX + 1;
  7560. const gridY1 = gridY + 1;
  7561. let vertexCounter = 0;
  7562. let groupCount = 0;
  7563. const vector = new Vector3();
  7564. // generate vertices, normals and uvs
  7565. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7566. const y = iy * segmentHeight - heightHalf;
  7567. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7568. const x = ix * segmentWidth - widthHalf;
  7569. // set values to correct vector component
  7570. vector[ u ] = x * udir;
  7571. vector[ v ] = y * vdir;
  7572. vector[ w ] = depthHalf;
  7573. // now apply vector to vertex buffer
  7574. vertices.push( vector.x, vector.y, vector.z );
  7575. // set values to correct vector component
  7576. vector[ u ] = 0;
  7577. vector[ v ] = 0;
  7578. vector[ w ] = depth > 0 ? 1 : - 1;
  7579. // now apply vector to normal buffer
  7580. normals.push( vector.x, vector.y, vector.z );
  7581. // uvs
  7582. uvs.push( ix / gridX );
  7583. uvs.push( 1 - ( iy / gridY ) );
  7584. // counters
  7585. vertexCounter += 1;
  7586. }
  7587. }
  7588. // indices
  7589. // 1. you need three indices to draw a single face
  7590. // 2. a single segment consists of two faces
  7591. // 3. so we need to generate six (2*3) indices per segment
  7592. for ( let iy = 0; iy < gridY; iy ++ ) {
  7593. for ( let ix = 0; ix < gridX; ix ++ ) {
  7594. const a = numberOfVertices + ix + gridX1 * iy;
  7595. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7596. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7597. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7598. // faces
  7599. indices.push( a, b, d );
  7600. indices.push( b, c, d );
  7601. // increase counter
  7602. groupCount += 6;
  7603. }
  7604. }
  7605. // add a group to the geometry. this will ensure multi material support
  7606. scope.addGroup( groupStart, groupCount, materialIndex );
  7607. // calculate new start value for groups
  7608. groupStart += groupCount;
  7609. // update total number of vertices
  7610. numberOfVertices += vertexCounter;
  7611. }
  7612. }
  7613. }
  7614. /**
  7615. * Uniform Utilities
  7616. */
  7617. function cloneUniforms( src ) {
  7618. const dst = {};
  7619. for ( const u in src ) {
  7620. dst[ u ] = {};
  7621. for ( const p in src[ u ] ) {
  7622. const property = src[ u ][ p ];
  7623. if ( property && ( property.isColor ||
  7624. property.isMatrix3 || property.isMatrix4 ||
  7625. property.isVector2 || property.isVector3 || property.isVector4 ||
  7626. property.isTexture ) ) {
  7627. dst[ u ][ p ] = property.clone();
  7628. } else if ( Array.isArray( property ) ) {
  7629. dst[ u ][ p ] = property.slice();
  7630. } else {
  7631. dst[ u ][ p ] = property;
  7632. }
  7633. }
  7634. }
  7635. return dst;
  7636. }
  7637. function mergeUniforms( uniforms ) {
  7638. const merged = {};
  7639. for ( let u = 0; u < uniforms.length; u ++ ) {
  7640. const tmp = cloneUniforms( uniforms[ u ] );
  7641. for ( const p in tmp ) {
  7642. merged[ p ] = tmp[ p ];
  7643. }
  7644. }
  7645. return merged;
  7646. }
  7647. // Legacy
  7648. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7649. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7650. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7651. /**
  7652. * parameters = {
  7653. * defines: { "label" : "value" },
  7654. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  7655. *
  7656. * fragmentShader: <string>,
  7657. * vertexShader: <string>,
  7658. *
  7659. * wireframe: <boolean>,
  7660. * wireframelineWidth: <float>,
  7661. *
  7662. * lights: <bool>,
  7663. *
  7664. * skinning: <bool>,
  7665. * morphTargets: <bool>,
  7666. * morphNormals: <bool>
  7667. * }
  7668. */
  7669. function ShaderMaterial( parameters ) {
  7670. Material.call( this );
  7671. this.type = 'ShaderMaterial';
  7672. this.defines = {};
  7673. this.uniforms = {};
  7674. this.vertexShader = default_vertex;
  7675. this.fragmentShader = default_fragment;
  7676. this.lineWidth = 1;
  7677. this.wireframe = false;
  7678. this.wireframelineWidth = 1;
  7679. this.fog = false; // set to use scene fog
  7680. this.lights = false; // set to use scene lights
  7681. this.clipping = false; // set to use user-defined clipping planes
  7682. this.skinning = false; // set to use skinning attribute streams
  7683. this.morphTargets = false; // set to use morph targets
  7684. this.morphNormals = false; // set to use morph normals
  7685. this.extensions = {
  7686. derivatives: false, // set to use derivatives
  7687. fragDepth: false, // set to use fragment depth values
  7688. drawBuffers: false, // set to use draw buffers
  7689. shaderTextureLOD: false // set to use shader texture LOD
  7690. };
  7691. // When rendered geometry doesn't include these attributes but the material does,
  7692. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7693. this.defaultAttributeValues = {
  7694. 'color': [ 1, 1, 1 ],
  7695. 'uv': [ 0, 0 ],
  7696. 'uv2': [ 0, 0 ]
  7697. };
  7698. this.index0AttributeName = undefined;
  7699. this.uniformsNeedUpdate = false;
  7700. this.glslVersion = null;
  7701. if ( parameters !== undefined ) {
  7702. if ( parameters.attributes !== undefined ) {
  7703. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  7704. }
  7705. this.setValues( parameters );
  7706. }
  7707. }
  7708. ShaderMaterial.prototype = Object.create( Material.prototype );
  7709. ShaderMaterial.prototype.constructor = ShaderMaterial;
  7710. ShaderMaterial.prototype.isShaderMaterial = true;
  7711. ShaderMaterial.prototype.copy = function ( source ) {
  7712. Material.prototype.copy.call( this, source );
  7713. this.fragmentShader = source.fragmentShader;
  7714. this.vertexShader = source.vertexShader;
  7715. this.uniforms = cloneUniforms( source.uniforms );
  7716. this.defines = Object.assign( {}, source.defines );
  7717. this.wireframe = source.wireframe;
  7718. this.wireframelineWidth = source.wireframelineWidth;
  7719. this.lights = source.lights;
  7720. this.clipping = source.clipping;
  7721. this.skinning = source.skinning;
  7722. this.morphTargets = source.morphTargets;
  7723. this.morphNormals = source.morphNormals;
  7724. this.extensions = Object.assign( {}, source.extensions );
  7725. this.glslVersion = source.glslVersion;
  7726. return this;
  7727. };
  7728. ShaderMaterial.prototype.toJSON = function ( meta ) {
  7729. const data = Material.prototype.toJSON.call( this, meta );
  7730. data.glslVersion = this.glslVersion;
  7731. data.uniforms = {};
  7732. for ( const name in this.uniforms ) {
  7733. const uniform = this.uniforms[ name ];
  7734. const value = uniform.value;
  7735. if ( value && value.isTexture ) {
  7736. data.uniforms[ name ] = {
  7737. type: 't',
  7738. value: value.toJSON( meta ).uuid
  7739. };
  7740. } else if ( value && value.isColor ) {
  7741. data.uniforms[ name ] = {
  7742. type: 'c',
  7743. value: value.getHex()
  7744. };
  7745. } else if ( value && value.isVector2 ) {
  7746. data.uniforms[ name ] = {
  7747. type: 'v2',
  7748. value: value.toArray()
  7749. };
  7750. } else if ( value && value.isVector3 ) {
  7751. data.uniforms[ name ] = {
  7752. type: 'v3',
  7753. value: value.toArray()
  7754. };
  7755. } else if ( value && value.isVector4 ) {
  7756. data.uniforms[ name ] = {
  7757. type: 'v4',
  7758. value: value.toArray()
  7759. };
  7760. } else if ( value && value.isMatrix3 ) {
  7761. data.uniforms[ name ] = {
  7762. type: 'm3',
  7763. value: value.toArray()
  7764. };
  7765. } else if ( value && value.isMatrix4 ) {
  7766. data.uniforms[ name ] = {
  7767. type: 'm4',
  7768. value: value.toArray()
  7769. };
  7770. } else {
  7771. data.uniforms[ name ] = {
  7772. value: value
  7773. };
  7774. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7775. }
  7776. }
  7777. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7778. data.vertexShader = this.vertexShader;
  7779. data.fragmentShader = this.fragmentShader;
  7780. const extensions = {};
  7781. for ( const key in this.extensions ) {
  7782. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7783. }
  7784. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7785. return data;
  7786. };
  7787. function Camera() {
  7788. Object3D.call( this );
  7789. this.type = 'Camera';
  7790. this.matrixWorldInverse = new Matrix4();
  7791. this.projectionMatrix = new Matrix4();
  7792. this.projectionMatrixInverse = new Matrix4();
  7793. }
  7794. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  7795. constructor: Camera,
  7796. isCamera: true,
  7797. copy: function ( source, recursive ) {
  7798. Object3D.prototype.copy.call( this, source, recursive );
  7799. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7800. this.projectionMatrix.copy( source.projectionMatrix );
  7801. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7802. return this;
  7803. },
  7804. getWorldDirection: function ( target ) {
  7805. if ( target === undefined ) {
  7806. console.warn( 'THREE.Camera: .getWorldDirection() target is now required' );
  7807. target = new Vector3();
  7808. }
  7809. this.updateWorldMatrix( true, false );
  7810. const e = this.matrixWorld.elements;
  7811. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  7812. },
  7813. updateMatrixWorld: function ( force ) {
  7814. Object3D.prototype.updateMatrixWorld.call( this, force );
  7815. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7816. },
  7817. updateWorldMatrix: function ( updateParents, updateChildren ) {
  7818. Object3D.prototype.updateWorldMatrix.call( this, updateParents, updateChildren );
  7819. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7820. },
  7821. clone: function () {
  7822. return new this.constructor().copy( this );
  7823. }
  7824. } );
  7825. function PerspectiveCamera( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7826. Camera.call( this );
  7827. this.type = 'PerspectiveCamera';
  7828. this.fov = fov;
  7829. this.zoom = 1;
  7830. this.near = near;
  7831. this.far = far;
  7832. this.focus = 10;
  7833. this.aspect = aspect;
  7834. this.view = null;
  7835. this.filmGauge = 35; // width of the film (default in millimeters)
  7836. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7837. this.updateProjectionMatrix();
  7838. }
  7839. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  7840. constructor: PerspectiveCamera,
  7841. isPerspectiveCamera: true,
  7842. copy: function ( source, recursive ) {
  7843. Camera.prototype.copy.call( this, source, recursive );
  7844. this.fov = source.fov;
  7845. this.zoom = source.zoom;
  7846. this.near = source.near;
  7847. this.far = source.far;
  7848. this.focus = source.focus;
  7849. this.aspect = source.aspect;
  7850. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7851. this.filmGauge = source.filmGauge;
  7852. this.filmOffset = source.filmOffset;
  7853. return this;
  7854. },
  7855. /**
  7856. * Sets the FOV by focal length in respect to the current .filmGauge.
  7857. *
  7858. * The default film gauge is 35, so that the focal length can be specified for
  7859. * a 35mm (full frame) camera.
  7860. *
  7861. * Values for focal length and film gauge must have the same unit.
  7862. */
  7863. setFocalLength: function ( focalLength ) {
  7864. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  7865. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7866. this.fov = MathUtils.RAD2DEG * 2 * Math.atan( vExtentSlope );
  7867. this.updateProjectionMatrix();
  7868. },
  7869. /**
  7870. * Calculates the focal length from the current .fov and .filmGauge.
  7871. */
  7872. getFocalLength: function () {
  7873. const vExtentSlope = Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov );
  7874. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7875. },
  7876. getEffectiveFOV: function () {
  7877. return MathUtils.RAD2DEG * 2 * Math.atan(
  7878. Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7879. },
  7880. getFilmWidth: function () {
  7881. // film not completely covered in portrait format (aspect < 1)
  7882. return this.filmGauge * Math.min( this.aspect, 1 );
  7883. },
  7884. getFilmHeight: function () {
  7885. // film not completely covered in landscape format (aspect > 1)
  7886. return this.filmGauge / Math.max( this.aspect, 1 );
  7887. },
  7888. /**
  7889. * Sets an offset in a larger frustum. This is useful for multi-window or
  7890. * multi-monitor/multi-machine setups.
  7891. *
  7892. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7893. * the monitors are in grid like this
  7894. *
  7895. * +---+---+---+
  7896. * | A | B | C |
  7897. * +---+---+---+
  7898. * | D | E | F |
  7899. * +---+---+---+
  7900. *
  7901. * then for each monitor you would call it like this
  7902. *
  7903. * const w = 1920;
  7904. * const h = 1080;
  7905. * const fullWidth = w * 3;
  7906. * const fullHeight = h * 2;
  7907. *
  7908. * --A--
  7909. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7910. * --B--
  7911. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7912. * --C--
  7913. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7914. * --D--
  7915. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7916. * --E--
  7917. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7918. * --F--
  7919. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7920. *
  7921. * Note there is no reason monitors have to be the same size or in a grid.
  7922. */
  7923. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  7924. this.aspect = fullWidth / fullHeight;
  7925. if ( this.view === null ) {
  7926. this.view = {
  7927. enabled: true,
  7928. fullWidth: 1,
  7929. fullHeight: 1,
  7930. offsetX: 0,
  7931. offsetY: 0,
  7932. width: 1,
  7933. height: 1
  7934. };
  7935. }
  7936. this.view.enabled = true;
  7937. this.view.fullWidth = fullWidth;
  7938. this.view.fullHeight = fullHeight;
  7939. this.view.offsetX = x;
  7940. this.view.offsetY = y;
  7941. this.view.width = width;
  7942. this.view.height = height;
  7943. this.updateProjectionMatrix();
  7944. },
  7945. clearViewOffset: function () {
  7946. if ( this.view !== null ) {
  7947. this.view.enabled = false;
  7948. }
  7949. this.updateProjectionMatrix();
  7950. },
  7951. updateProjectionMatrix: function () {
  7952. const near = this.near;
  7953. let top = near * Math.tan( MathUtils.DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7954. let height = 2 * top;
  7955. let width = this.aspect * height;
  7956. let left = - 0.5 * width;
  7957. const view = this.view;
  7958. if ( this.view !== null && this.view.enabled ) {
  7959. const fullWidth = view.fullWidth,
  7960. fullHeight = view.fullHeight;
  7961. left += view.offsetX * width / fullWidth;
  7962. top -= view.offsetY * height / fullHeight;
  7963. width *= view.width / fullWidth;
  7964. height *= view.height / fullHeight;
  7965. }
  7966. const skew = this.filmOffset;
  7967. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7968. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7969. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7970. },
  7971. toJSON: function ( meta ) {
  7972. const data = Object3D.prototype.toJSON.call( this, meta );
  7973. data.object.fov = this.fov;
  7974. data.object.zoom = this.zoom;
  7975. data.object.near = this.near;
  7976. data.object.far = this.far;
  7977. data.object.focus = this.focus;
  7978. data.object.aspect = this.aspect;
  7979. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7980. data.object.filmGauge = this.filmGauge;
  7981. data.object.filmOffset = this.filmOffset;
  7982. return data;
  7983. }
  7984. } );
  7985. const fov = 90, aspect = 1;
  7986. function CubeCamera( near, far, renderTarget ) {
  7987. Object3D.call( this );
  7988. this.type = 'CubeCamera';
  7989. if ( renderTarget.isWebGLCubeRenderTarget !== true ) {
  7990. console.error( 'THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.' );
  7991. return;
  7992. }
  7993. this.renderTarget = renderTarget;
  7994. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7995. cameraPX.layers = this.layers;
  7996. cameraPX.up.set( 0, - 1, 0 );
  7997. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  7998. this.add( cameraPX );
  7999. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  8000. cameraNX.layers = this.layers;
  8001. cameraNX.up.set( 0, - 1, 0 );
  8002. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  8003. this.add( cameraNX );
  8004. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  8005. cameraPY.layers = this.layers;
  8006. cameraPY.up.set( 0, 0, 1 );
  8007. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  8008. this.add( cameraPY );
  8009. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  8010. cameraNY.layers = this.layers;
  8011. cameraNY.up.set( 0, 0, - 1 );
  8012. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  8013. this.add( cameraNY );
  8014. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  8015. cameraPZ.layers = this.layers;
  8016. cameraPZ.up.set( 0, - 1, 0 );
  8017. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  8018. this.add( cameraPZ );
  8019. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  8020. cameraNZ.layers = this.layers;
  8021. cameraNZ.up.set( 0, - 1, 0 );
  8022. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  8023. this.add( cameraNZ );
  8024. this.update = function ( renderer, scene ) {
  8025. if ( this.parent === null ) this.updateMatrixWorld();
  8026. const currentXrEnabled = renderer.xr.enabled;
  8027. const currentRenderTarget = renderer.getRenderTarget();
  8028. renderer.xr.enabled = false;
  8029. const generateMipmaps = renderTarget.texture.generateMipmaps;
  8030. renderTarget.texture.generateMipmaps = false;
  8031. renderer.setRenderTarget( renderTarget, 0 );
  8032. renderer.render( scene, cameraPX );
  8033. renderer.setRenderTarget( renderTarget, 1 );
  8034. renderer.render( scene, cameraNX );
  8035. renderer.setRenderTarget( renderTarget, 2 );
  8036. renderer.render( scene, cameraPY );
  8037. renderer.setRenderTarget( renderTarget, 3 );
  8038. renderer.render( scene, cameraNY );
  8039. renderer.setRenderTarget( renderTarget, 4 );
  8040. renderer.render( scene, cameraPZ );
  8041. renderTarget.texture.generateMipmaps = generateMipmaps;
  8042. renderer.setRenderTarget( renderTarget, 5 );
  8043. renderer.render( scene, cameraNZ );
  8044. renderer.setRenderTarget( currentRenderTarget );
  8045. renderer.xr.enabled = currentXrEnabled;
  8046. };
  8047. }
  8048. CubeCamera.prototype = Object.create( Object3D.prototype );
  8049. CubeCamera.prototype.constructor = CubeCamera;
  8050. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  8051. images = images !== undefined ? images : [];
  8052. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  8053. format = format !== undefined ? format : RGBFormat;
  8054. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  8055. this.flipY = false;
  8056. // Why CubeTexture._needsFlipEnvMap is necessary:
  8057. //
  8058. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  8059. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  8060. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  8061. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  8062. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  8063. // when using WebGLCubeRenderTarget.texture as a cube texture.
  8064. this._needsFlipEnvMap = true;
  8065. }
  8066. CubeTexture.prototype = Object.create( Texture.prototype );
  8067. CubeTexture.prototype.constructor = CubeTexture;
  8068. CubeTexture.prototype.isCubeTexture = true;
  8069. Object.defineProperty( CubeTexture.prototype, 'images', {
  8070. get: function () {
  8071. return this.image;
  8072. },
  8073. set: function ( value ) {
  8074. this.image = value;
  8075. }
  8076. } );
  8077. function WebGLCubeRenderTarget( size, options, dummy ) {
  8078. if ( Number.isInteger( options ) ) {
  8079. console.warn( 'THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )' );
  8080. options = dummy;
  8081. }
  8082. WebGLRenderTarget.call( this, size, size, options );
  8083. options = options || {};
  8084. this.texture = new CubeTexture( undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  8085. this.texture._needsFlipEnvMap = false;
  8086. }
  8087. WebGLCubeRenderTarget.prototype = Object.create( WebGLRenderTarget.prototype );
  8088. WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;
  8089. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  8090. WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function ( renderer, texture ) {
  8091. this.texture.type = texture.type;
  8092. this.texture.format = RGBAFormat; // see #18859
  8093. this.texture.encoding = texture.encoding;
  8094. this.texture.generateMipmaps = texture.generateMipmaps;
  8095. this.texture.minFilter = texture.minFilter;
  8096. this.texture.magFilter = texture.magFilter;
  8097. const shader = {
  8098. uniforms: {
  8099. tEquirect: { value: null },
  8100. },
  8101. vertexShader: /* glsl */`
  8102. varying vec3 vWorldDirection;
  8103. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  8104. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  8105. }
  8106. void main() {
  8107. vWorldDirection = transformDirection( position, modelMatrix );
  8108. #include <begin_vertex>
  8109. #include <project_vertex>
  8110. }
  8111. `,
  8112. fragmentShader: /* glsl */`
  8113. uniform sampler2D tEquirect;
  8114. varying vec3 vWorldDirection;
  8115. #include <common>
  8116. void main() {
  8117. vec3 direction = normalize( vWorldDirection );
  8118. vec2 sampleUV = equirectUv( direction );
  8119. gl_FragColor = texture2D( tEquirect, sampleUV );
  8120. }
  8121. `
  8122. };
  8123. const geometry = new BoxBufferGeometry( 5, 5, 5 );
  8124. const material = new ShaderMaterial( {
  8125. name: 'CubemapFromEquirect',
  8126. uniforms: cloneUniforms( shader.uniforms ),
  8127. vertexShader: shader.vertexShader,
  8128. fragmentShader: shader.fragmentShader,
  8129. side: BackSide,
  8130. blending: NoBlending
  8131. } );
  8132. material.uniforms.tEquirect.value = texture;
  8133. const mesh = new Mesh( geometry, material );
  8134. const currentMinFilter = texture.minFilter;
  8135. // Avoid blurred poles
  8136. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  8137. const camera = new CubeCamera( 1, 10, this );
  8138. camera.update( renderer, mesh );
  8139. texture.minFilter = currentMinFilter;
  8140. mesh.geometry.dispose();
  8141. mesh.material.dispose();
  8142. return this;
  8143. };
  8144. WebGLCubeRenderTarget.prototype.clear = function ( renderer, color, depth, stencil ) {
  8145. const currentRenderTarget = renderer.getRenderTarget();
  8146. for ( let i = 0; i < 6; i ++ ) {
  8147. renderer.setRenderTarget( this, i );
  8148. renderer.clear( color, depth, stencil );
  8149. }
  8150. renderer.setRenderTarget( currentRenderTarget );
  8151. };
  8152. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  8153. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  8154. this.image = { data: data || null, width: width || 1, height: height || 1 };
  8155. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  8156. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  8157. this.generateMipmaps = false;
  8158. this.flipY = false;
  8159. this.unpackAlignment = 1;
  8160. this.needsUpdate = true;
  8161. }
  8162. DataTexture.prototype = Object.create( Texture.prototype );
  8163. DataTexture.prototype.constructor = DataTexture;
  8164. DataTexture.prototype.isDataTexture = true;
  8165. const _sphere$1 = /*@__PURE__*/ new Sphere();
  8166. const _vector$5 = /*@__PURE__*/ new Vector3();
  8167. class Frustum {
  8168. constructor( p0, p1, p2, p3, p4, p5 ) {
  8169. this.planes = [
  8170. ( p0 !== undefined ) ? p0 : new Plane(),
  8171. ( p1 !== undefined ) ? p1 : new Plane(),
  8172. ( p2 !== undefined ) ? p2 : new Plane(),
  8173. ( p3 !== undefined ) ? p3 : new Plane(),
  8174. ( p4 !== undefined ) ? p4 : new Plane(),
  8175. ( p5 !== undefined ) ? p5 : new Plane()
  8176. ];
  8177. }
  8178. set( p0, p1, p2, p3, p4, p5 ) {
  8179. const planes = this.planes;
  8180. planes[ 0 ].copy( p0 );
  8181. planes[ 1 ].copy( p1 );
  8182. planes[ 2 ].copy( p2 );
  8183. planes[ 3 ].copy( p3 );
  8184. planes[ 4 ].copy( p4 );
  8185. planes[ 5 ].copy( p5 );
  8186. return this;
  8187. }
  8188. clone() {
  8189. return new this.constructor().copy( this );
  8190. }
  8191. copy( frustum ) {
  8192. const planes = this.planes;
  8193. for ( let i = 0; i < 6; i ++ ) {
  8194. planes[ i ].copy( frustum.planes[ i ] );
  8195. }
  8196. return this;
  8197. }
  8198. setFromProjectionMatrix( m ) {
  8199. const planes = this.planes;
  8200. const me = m.elements;
  8201. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  8202. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  8203. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  8204. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  8205. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  8206. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  8207. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  8208. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  8209. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  8210. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  8211. return this;
  8212. }
  8213. intersectsObject( object ) {
  8214. const geometry = object.geometry;
  8215. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8216. _sphere$1.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8217. return this.intersectsSphere( _sphere$1 );
  8218. }
  8219. intersectsSprite( sprite ) {
  8220. _sphere$1.center.set( 0, 0, 0 );
  8221. _sphere$1.radius = 0.7071067811865476;
  8222. _sphere$1.applyMatrix4( sprite.matrixWorld );
  8223. return this.intersectsSphere( _sphere$1 );
  8224. }
  8225. intersectsSphere( sphere ) {
  8226. const planes = this.planes;
  8227. const center = sphere.center;
  8228. const negRadius = - sphere.radius;
  8229. for ( let i = 0; i < 6; i ++ ) {
  8230. const distance = planes[ i ].distanceToPoint( center );
  8231. if ( distance < negRadius ) {
  8232. return false;
  8233. }
  8234. }
  8235. return true;
  8236. }
  8237. intersectsBox( box ) {
  8238. const planes = this.planes;
  8239. for ( let i = 0; i < 6; i ++ ) {
  8240. const plane = planes[ i ];
  8241. // corner at max distance
  8242. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  8243. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  8244. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  8245. if ( plane.distanceToPoint( _vector$5 ) < 0 ) {
  8246. return false;
  8247. }
  8248. }
  8249. return true;
  8250. }
  8251. containsPoint( point ) {
  8252. const planes = this.planes;
  8253. for ( let i = 0; i < 6; i ++ ) {
  8254. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  8255. return false;
  8256. }
  8257. }
  8258. return true;
  8259. }
  8260. }
  8261. function WebGLAnimation() {
  8262. let context = null;
  8263. let isAnimating = false;
  8264. let animationLoop = null;
  8265. let requestId = null;
  8266. function onAnimationFrame( time, frame ) {
  8267. animationLoop( time, frame );
  8268. requestId = context.requestAnimationFrame( onAnimationFrame );
  8269. }
  8270. return {
  8271. start: function () {
  8272. if ( isAnimating === true ) return;
  8273. if ( animationLoop === null ) return;
  8274. requestId = context.requestAnimationFrame( onAnimationFrame );
  8275. isAnimating = true;
  8276. },
  8277. stop: function () {
  8278. context.cancelAnimationFrame( requestId );
  8279. isAnimating = false;
  8280. },
  8281. setAnimationLoop: function ( callback ) {
  8282. animationLoop = callback;
  8283. },
  8284. setContext: function ( value ) {
  8285. context = value;
  8286. }
  8287. };
  8288. }
  8289. function WebGLAttributes( gl, capabilities ) {
  8290. const isWebGL2 = capabilities.isWebGL2;
  8291. const buffers = new WeakMap();
  8292. function createBuffer( attribute, bufferType ) {
  8293. const array = attribute.array;
  8294. const usage = attribute.usage;
  8295. const buffer = gl.createBuffer();
  8296. gl.bindBuffer( bufferType, buffer );
  8297. gl.bufferData( bufferType, array, usage );
  8298. attribute.onUploadCallback();
  8299. let type = 5126;
  8300. if ( array instanceof Float32Array ) {
  8301. type = 5126;
  8302. } else if ( array instanceof Float64Array ) {
  8303. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  8304. } else if ( array instanceof Uint16Array ) {
  8305. if ( attribute.isFloat16BufferAttribute ) {
  8306. if ( isWebGL2 ) {
  8307. type = 5131;
  8308. } else {
  8309. console.warn( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  8310. }
  8311. } else {
  8312. type = 5123;
  8313. }
  8314. } else if ( array instanceof Int16Array ) {
  8315. type = 5122;
  8316. } else if ( array instanceof Uint32Array ) {
  8317. type = 5125;
  8318. } else if ( array instanceof Int32Array ) {
  8319. type = 5124;
  8320. } else if ( array instanceof Int8Array ) {
  8321. type = 5120;
  8322. } else if ( array instanceof Uint8Array ) {
  8323. type = 5121;
  8324. }
  8325. return {
  8326. buffer: buffer,
  8327. type: type,
  8328. bytesPerElement: array.BYTES_PER_ELEMENT,
  8329. version: attribute.version
  8330. };
  8331. }
  8332. function updateBuffer( buffer, attribute, bufferType ) {
  8333. const array = attribute.array;
  8334. const updateRange = attribute.updateRange;
  8335. gl.bindBuffer( bufferType, buffer );
  8336. if ( updateRange.count === - 1 ) {
  8337. // Not using update ranges
  8338. gl.bufferSubData( bufferType, 0, array );
  8339. } else {
  8340. if ( isWebGL2 ) {
  8341. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8342. array, updateRange.offset, updateRange.count );
  8343. } else {
  8344. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8345. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  8346. }
  8347. updateRange.count = - 1; // reset range
  8348. }
  8349. }
  8350. //
  8351. function get( attribute ) {
  8352. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8353. return buffers.get( attribute );
  8354. }
  8355. function remove( attribute ) {
  8356. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8357. const data = buffers.get( attribute );
  8358. if ( data ) {
  8359. gl.deleteBuffer( data.buffer );
  8360. buffers.delete( attribute );
  8361. }
  8362. }
  8363. function update( attribute, bufferType ) {
  8364. if ( attribute.isGLBufferAttribute ) {
  8365. const cached = buffers.get( attribute );
  8366. if ( ! cached || cached.version < attribute.version ) {
  8367. buffers.set( attribute, {
  8368. buffer: attribute.buffer,
  8369. type: attribute.type,
  8370. bytesPerElement: attribute.elementSize,
  8371. version: attribute.version
  8372. } );
  8373. }
  8374. return;
  8375. }
  8376. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8377. const data = buffers.get( attribute );
  8378. if ( data === undefined ) {
  8379. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8380. } else if ( data.version < attribute.version ) {
  8381. updateBuffer( data.buffer, attribute, bufferType );
  8382. data.version = attribute.version;
  8383. }
  8384. }
  8385. return {
  8386. get: get,
  8387. remove: remove,
  8388. update: update
  8389. };
  8390. }
  8391. class PlaneBufferGeometry extends BufferGeometry {
  8392. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  8393. super();
  8394. this.type = 'PlaneBufferGeometry';
  8395. this.parameters = {
  8396. width: width,
  8397. height: height,
  8398. widthSegments: widthSegments,
  8399. heightSegments: heightSegments
  8400. };
  8401. const width_half = width / 2;
  8402. const height_half = height / 2;
  8403. const gridX = Math.floor( widthSegments );
  8404. const gridY = Math.floor( heightSegments );
  8405. const gridX1 = gridX + 1;
  8406. const gridY1 = gridY + 1;
  8407. const segment_width = width / gridX;
  8408. const segment_height = height / gridY;
  8409. //
  8410. const indices = [];
  8411. const vertices = [];
  8412. const normals = [];
  8413. const uvs = [];
  8414. for ( let iy = 0; iy < gridY1; iy ++ ) {
  8415. const y = iy * segment_height - height_half;
  8416. for ( let ix = 0; ix < gridX1; ix ++ ) {
  8417. const x = ix * segment_width - width_half;
  8418. vertices.push( x, - y, 0 );
  8419. normals.push( 0, 0, 1 );
  8420. uvs.push( ix / gridX );
  8421. uvs.push( 1 - ( iy / gridY ) );
  8422. }
  8423. }
  8424. for ( let iy = 0; iy < gridY; iy ++ ) {
  8425. for ( let ix = 0; ix < gridX; ix ++ ) {
  8426. const a = ix + gridX1 * iy;
  8427. const b = ix + gridX1 * ( iy + 1 );
  8428. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8429. const d = ( ix + 1 ) + gridX1 * iy;
  8430. indices.push( a, b, d );
  8431. indices.push( b, c, d );
  8432. }
  8433. }
  8434. this.setIndex( indices );
  8435. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8436. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8437. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8438. }
  8439. }
  8440. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  8441. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8442. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  8443. 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";
  8444. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8445. var begin_vertex = "vec3 transformed = vec3( position );";
  8446. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8447. 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";
  8448. 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";
  8449. 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";
  8450. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8451. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8452. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8453. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8454. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  8455. var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8456. 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";
  8457. 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}";
  8458. 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";
  8459. 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";
  8460. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8461. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  8462. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8463. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8464. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8465. 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}";
  8466. 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";
  8467. 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";
  8468. 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";
  8469. 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";
  8470. 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";
  8471. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  8472. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  8473. 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";
  8474. 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";
  8475. 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}";
  8476. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  8477. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8478. 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";
  8479. 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";
  8480. 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";
  8481. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8482. 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)";
  8483. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8484. 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)";
  8485. 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";
  8486. 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}";
  8487. 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";
  8488. 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";
  8489. 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";
  8490. 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";
  8491. 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";
  8492. 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";
  8493. 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";
  8494. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  8495. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8496. 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";
  8497. 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";
  8498. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8499. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8500. 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";
  8501. 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";
  8502. 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";
  8503. 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;";
  8504. 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";
  8505. 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";
  8506. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8507. 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";
  8508. 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";
  8509. 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}";
  8510. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8511. 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;";
  8512. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8513. 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";
  8514. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8515. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8516. 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";
  8517. 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";
  8518. 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";
  8519. 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}";
  8520. 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";
  8521. 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";
  8522. 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";
  8523. 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";
  8524. 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";
  8525. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8526. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8527. 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; }";
  8528. var transmissionmap_fragment = "#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif";
  8529. var transmissionmap_pars_fragment = "#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif";
  8530. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  8531. 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";
  8532. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  8533. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  8534. 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";
  8535. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  8536. 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";
  8537. 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}";
  8538. 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}";
  8539. 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}";
  8540. 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}";
  8541. 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}";
  8542. 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}";
  8543. 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}";
  8544. 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}";
  8545. 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}";
  8546. 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}";
  8547. 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}";
  8548. 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}";
  8549. 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}";
  8550. 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}";
  8551. 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}";
  8552. 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}";
  8553. 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}";
  8554. 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}";
  8555. 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}";
  8556. 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}";
  8557. 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}";
  8558. 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}";
  8559. 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}";
  8560. 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}";
  8561. 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}";
  8562. 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}";
  8563. 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}";
  8564. 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}";
  8565. 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}";
  8566. 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}";
  8567. 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}";
  8568. 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}";
  8569. const ShaderChunk = {
  8570. alphamap_fragment: alphamap_fragment,
  8571. alphamap_pars_fragment: alphamap_pars_fragment,
  8572. alphatest_fragment: alphatest_fragment,
  8573. aomap_fragment: aomap_fragment,
  8574. aomap_pars_fragment: aomap_pars_fragment,
  8575. begin_vertex: begin_vertex,
  8576. beginnormal_vertex: beginnormal_vertex,
  8577. bsdfs: bsdfs,
  8578. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8579. clipping_planes_fragment: clipping_planes_fragment,
  8580. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8581. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8582. clipping_planes_vertex: clipping_planes_vertex,
  8583. color_fragment: color_fragment,
  8584. color_pars_fragment: color_pars_fragment,
  8585. color_pars_vertex: color_pars_vertex,
  8586. color_vertex: color_vertex,
  8587. common: common,
  8588. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8589. defaultnormal_vertex: defaultnormal_vertex,
  8590. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8591. displacementmap_vertex: displacementmap_vertex,
  8592. emissivemap_fragment: emissivemap_fragment,
  8593. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8594. encodings_fragment: encodings_fragment,
  8595. encodings_pars_fragment: encodings_pars_fragment,
  8596. envmap_fragment: envmap_fragment,
  8597. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8598. envmap_pars_fragment: envmap_pars_fragment,
  8599. envmap_pars_vertex: envmap_pars_vertex,
  8600. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8601. envmap_vertex: envmap_vertex,
  8602. fog_vertex: fog_vertex,
  8603. fog_pars_vertex: fog_pars_vertex,
  8604. fog_fragment: fog_fragment,
  8605. fog_pars_fragment: fog_pars_fragment,
  8606. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8607. lightmap_fragment: lightmap_fragment,
  8608. lightmap_pars_fragment: lightmap_pars_fragment,
  8609. lights_lambert_vertex: lights_lambert_vertex,
  8610. lights_pars_begin: lights_pars_begin,
  8611. lights_toon_fragment: lights_toon_fragment,
  8612. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8613. lights_phong_fragment: lights_phong_fragment,
  8614. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8615. lights_physical_fragment: lights_physical_fragment,
  8616. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8617. lights_fragment_begin: lights_fragment_begin,
  8618. lights_fragment_maps: lights_fragment_maps,
  8619. lights_fragment_end: lights_fragment_end,
  8620. logdepthbuf_fragment: logdepthbuf_fragment,
  8621. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8622. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8623. logdepthbuf_vertex: logdepthbuf_vertex,
  8624. map_fragment: map_fragment,
  8625. map_pars_fragment: map_pars_fragment,
  8626. map_particle_fragment: map_particle_fragment,
  8627. map_particle_pars_fragment: map_particle_pars_fragment,
  8628. metalnessmap_fragment: metalnessmap_fragment,
  8629. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8630. morphnormal_vertex: morphnormal_vertex,
  8631. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8632. morphtarget_vertex: morphtarget_vertex,
  8633. normal_fragment_begin: normal_fragment_begin,
  8634. normal_fragment_maps: normal_fragment_maps,
  8635. normalmap_pars_fragment: normalmap_pars_fragment,
  8636. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8637. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8638. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8639. packing: packing,
  8640. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8641. project_vertex: project_vertex,
  8642. dithering_fragment: dithering_fragment,
  8643. dithering_pars_fragment: dithering_pars_fragment,
  8644. roughnessmap_fragment: roughnessmap_fragment,
  8645. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8646. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8647. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8648. shadowmap_vertex: shadowmap_vertex,
  8649. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8650. skinbase_vertex: skinbase_vertex,
  8651. skinning_pars_vertex: skinning_pars_vertex,
  8652. skinning_vertex: skinning_vertex,
  8653. skinnormal_vertex: skinnormal_vertex,
  8654. specularmap_fragment: specularmap_fragment,
  8655. specularmap_pars_fragment: specularmap_pars_fragment,
  8656. tonemapping_fragment: tonemapping_fragment,
  8657. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8658. transmissionmap_fragment: transmissionmap_fragment,
  8659. transmissionmap_pars_fragment: transmissionmap_pars_fragment,
  8660. uv_pars_fragment: uv_pars_fragment,
  8661. uv_pars_vertex: uv_pars_vertex,
  8662. uv_vertex: uv_vertex,
  8663. uv2_pars_fragment: uv2_pars_fragment,
  8664. uv2_pars_vertex: uv2_pars_vertex,
  8665. uv2_vertex: uv2_vertex,
  8666. worldpos_vertex: worldpos_vertex,
  8667. background_frag: background_frag,
  8668. background_vert: background_vert,
  8669. cube_frag: cube_frag,
  8670. cube_vert: cube_vert,
  8671. depth_frag: depth_frag,
  8672. depth_vert: depth_vert,
  8673. distanceRGBA_frag: distanceRGBA_frag,
  8674. distanceRGBA_vert: distanceRGBA_vert,
  8675. equirect_frag: equirect_frag,
  8676. equirect_vert: equirect_vert,
  8677. linedashed_frag: linedashed_frag,
  8678. linedashed_vert: linedashed_vert,
  8679. meshbasic_frag: meshbasic_frag,
  8680. meshbasic_vert: meshbasic_vert,
  8681. meshlambert_frag: meshlambert_frag,
  8682. meshlambert_vert: meshlambert_vert,
  8683. meshmatcap_frag: meshmatcap_frag,
  8684. meshmatcap_vert: meshmatcap_vert,
  8685. meshtoon_frag: meshtoon_frag,
  8686. meshtoon_vert: meshtoon_vert,
  8687. meshphong_frag: meshphong_frag,
  8688. meshphong_vert: meshphong_vert,
  8689. meshphysical_frag: meshphysical_frag,
  8690. meshphysical_vert: meshphysical_vert,
  8691. normal_frag: normal_frag,
  8692. normal_vert: normal_vert,
  8693. points_frag: points_frag,
  8694. points_vert: points_vert,
  8695. shadow_frag: shadow_frag,
  8696. shadow_vert: shadow_vert,
  8697. sprite_frag: sprite_frag,
  8698. sprite_vert: sprite_vert
  8699. };
  8700. /**
  8701. * Uniforms library for shared webgl shaders
  8702. */
  8703. const UniformsLib = {
  8704. common: {
  8705. diffuse: { value: new Color( 0xeeeeee ) },
  8706. opacity: { value: 1.0 },
  8707. map: { value: null },
  8708. uvTransform: { value: new Matrix3() },
  8709. uv2Transform: { value: new Matrix3() },
  8710. alphaMap: { value: null },
  8711. },
  8712. specularmap: {
  8713. specularMap: { value: null },
  8714. },
  8715. envmap: {
  8716. envMap: { value: null },
  8717. flipEnvMap: { value: - 1 },
  8718. reflectivity: { value: 1.0 },
  8719. refractionRatio: { value: 0.98 },
  8720. maxMipLevel: { value: 0 }
  8721. },
  8722. aomap: {
  8723. aoMap: { value: null },
  8724. aoMapIntensity: { value: 1 }
  8725. },
  8726. lightmap: {
  8727. lightMap: { value: null },
  8728. lightMapIntensity: { value: 1 }
  8729. },
  8730. emissivemap: {
  8731. emissiveMap: { value: null }
  8732. },
  8733. bumpmap: {
  8734. bumpMap: { value: null },
  8735. bumpScale: { value: 1 }
  8736. },
  8737. normalmap: {
  8738. normalMap: { value: null },
  8739. normalScale: { value: new Vector2$1( 1, 1 ) }
  8740. },
  8741. displacementmap: {
  8742. displacementMap: { value: null },
  8743. displacementScale: { value: 1 },
  8744. displacementBias: { value: 0 }
  8745. },
  8746. roughnessmap: {
  8747. roughnessMap: { value: null }
  8748. },
  8749. metalnessmap: {
  8750. metalnessMap: { value: null }
  8751. },
  8752. gradientmap: {
  8753. gradientMap: { value: null }
  8754. },
  8755. fog: {
  8756. fogDensity: { value: 0.00025 },
  8757. fogNear: { value: 1 },
  8758. fogFar: { value: 2000 },
  8759. fogColor: { value: new Color( 0xffffff ) }
  8760. },
  8761. lights: {
  8762. ambientLightColor: { value: [] },
  8763. lightProbe: { value: [] },
  8764. directionalLights: { value: [], properties: {
  8765. direction: {},
  8766. color: {}
  8767. } },
  8768. directionalLightShadows: { value: [], properties: {
  8769. shadowBias: {},
  8770. shadowNormalBias: {},
  8771. shadowRadius: {},
  8772. shadowMapSize: {}
  8773. } },
  8774. directionalShadowMap: { value: [] },
  8775. directionalShadowMatrix: { value: [] },
  8776. spotLights: { value: [], properties: {
  8777. color: {},
  8778. position: {},
  8779. direction: {},
  8780. distance: {},
  8781. coneCos: {},
  8782. penumbraCos: {},
  8783. decay: {}
  8784. } },
  8785. spotLightShadows: { value: [], properties: {
  8786. shadowBias: {},
  8787. shadowNormalBias: {},
  8788. shadowRadius: {},
  8789. shadowMapSize: {}
  8790. } },
  8791. spotShadowMap: { value: [] },
  8792. spotShadowMatrix: { value: [] },
  8793. pointLights: { value: [], properties: {
  8794. color: {},
  8795. position: {},
  8796. decay: {},
  8797. distance: {}
  8798. } },
  8799. pointLightShadows: { value: [], properties: {
  8800. shadowBias: {},
  8801. shadowNormalBias: {},
  8802. shadowRadius: {},
  8803. shadowMapSize: {},
  8804. shadowCameraNear: {},
  8805. shadowCameraFar: {}
  8806. } },
  8807. pointShadowMap: { value: [] },
  8808. pointShadowMatrix: { value: [] },
  8809. hemisphereLights: { value: [], properties: {
  8810. direction: {},
  8811. skyColor: {},
  8812. groundColor: {}
  8813. } },
  8814. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8815. rectAreaLights: { value: [], properties: {
  8816. color: {},
  8817. position: {},
  8818. width: {},
  8819. height: {}
  8820. } },
  8821. ltc_1: { value: null },
  8822. ltc_2: { value: null }
  8823. },
  8824. points: {
  8825. diffuse: { value: new Color( 0xeeeeee ) },
  8826. opacity: { value: 1.0 },
  8827. size: { value: 1.0 },
  8828. scale: { value: 1.0 },
  8829. map: { value: null },
  8830. alphaMap: { value: null },
  8831. uvTransform: { value: new Matrix3() }
  8832. },
  8833. sprite: {
  8834. diffuse: { value: new Color( 0xeeeeee ) },
  8835. opacity: { value: 1.0 },
  8836. center: { value: new Vector2$1( 0.5, 0.5 ) },
  8837. rotation: { value: 0.0 },
  8838. map: { value: null },
  8839. alphaMap: { value: null },
  8840. uvTransform: { value: new Matrix3() }
  8841. }
  8842. };
  8843. const ShaderLib = {
  8844. basic: {
  8845. uniforms: mergeUniforms( [
  8846. UniformsLib.common,
  8847. UniformsLib.specularmap,
  8848. UniformsLib.envmap,
  8849. UniformsLib.aomap,
  8850. UniformsLib.lightmap,
  8851. UniformsLib.fog
  8852. ] ),
  8853. vertexShader: ShaderChunk.meshbasic_vert,
  8854. fragmentShader: ShaderChunk.meshbasic_frag
  8855. },
  8856. lambert: {
  8857. uniforms: mergeUniforms( [
  8858. UniformsLib.common,
  8859. UniformsLib.specularmap,
  8860. UniformsLib.envmap,
  8861. UniformsLib.aomap,
  8862. UniformsLib.lightmap,
  8863. UniformsLib.emissivemap,
  8864. UniformsLib.fog,
  8865. UniformsLib.lights,
  8866. {
  8867. emissive: { value: new Color( 0x000000 ) }
  8868. }
  8869. ] ),
  8870. vertexShader: ShaderChunk.meshlambert_vert,
  8871. fragmentShader: ShaderChunk.meshlambert_frag
  8872. },
  8873. phong: {
  8874. uniforms: mergeUniforms( [
  8875. UniformsLib.common,
  8876. UniformsLib.specularmap,
  8877. UniformsLib.envmap,
  8878. UniformsLib.aomap,
  8879. UniformsLib.lightmap,
  8880. UniformsLib.emissivemap,
  8881. UniformsLib.bumpmap,
  8882. UniformsLib.normalmap,
  8883. UniformsLib.displacementmap,
  8884. UniformsLib.fog,
  8885. UniformsLib.lights,
  8886. {
  8887. emissive: { value: new Color( 0x000000 ) },
  8888. specular: { value: new Color( 0x111111 ) },
  8889. shininess: { value: 30 }
  8890. }
  8891. ] ),
  8892. vertexShader: ShaderChunk.meshphong_vert,
  8893. fragmentShader: ShaderChunk.meshphong_frag
  8894. },
  8895. standard: {
  8896. uniforms: mergeUniforms( [
  8897. UniformsLib.common,
  8898. UniformsLib.envmap,
  8899. UniformsLib.aomap,
  8900. UniformsLib.lightmap,
  8901. UniformsLib.emissivemap,
  8902. UniformsLib.bumpmap,
  8903. UniformsLib.normalmap,
  8904. UniformsLib.displacementmap,
  8905. UniformsLib.roughnessmap,
  8906. UniformsLib.metalnessmap,
  8907. UniformsLib.fog,
  8908. UniformsLib.lights,
  8909. {
  8910. emissive: { value: new Color( 0x000000 ) },
  8911. roughness: { value: 1.0 },
  8912. metalness: { value: 0.0 },
  8913. envMapIntensity: { value: 1 } // temporary
  8914. }
  8915. ] ),
  8916. vertexShader: ShaderChunk.meshphysical_vert,
  8917. fragmentShader: ShaderChunk.meshphysical_frag
  8918. },
  8919. toon: {
  8920. uniforms: mergeUniforms( [
  8921. UniformsLib.common,
  8922. UniformsLib.aomap,
  8923. UniformsLib.lightmap,
  8924. UniformsLib.emissivemap,
  8925. UniformsLib.bumpmap,
  8926. UniformsLib.normalmap,
  8927. UniformsLib.displacementmap,
  8928. UniformsLib.gradientmap,
  8929. UniformsLib.fog,
  8930. UniformsLib.lights,
  8931. {
  8932. emissive: { value: new Color( 0x000000 ) }
  8933. }
  8934. ] ),
  8935. vertexShader: ShaderChunk.meshtoon_vert,
  8936. fragmentShader: ShaderChunk.meshtoon_frag
  8937. },
  8938. matcap: {
  8939. uniforms: mergeUniforms( [
  8940. UniformsLib.common,
  8941. UniformsLib.bumpmap,
  8942. UniformsLib.normalmap,
  8943. UniformsLib.displacementmap,
  8944. UniformsLib.fog,
  8945. {
  8946. matcap: { value: null }
  8947. }
  8948. ] ),
  8949. vertexShader: ShaderChunk.meshmatcap_vert,
  8950. fragmentShader: ShaderChunk.meshmatcap_frag
  8951. },
  8952. points: {
  8953. uniforms: mergeUniforms( [
  8954. UniformsLib.points,
  8955. UniformsLib.fog
  8956. ] ),
  8957. vertexShader: ShaderChunk.points_vert,
  8958. fragmentShader: ShaderChunk.points_frag
  8959. },
  8960. dashed: {
  8961. uniforms: mergeUniforms( [
  8962. UniformsLib.common,
  8963. UniformsLib.fog,
  8964. {
  8965. scale: { value: 1 },
  8966. dashSize: { value: 1 },
  8967. totalSize: { value: 2 }
  8968. }
  8969. ] ),
  8970. vertexShader: ShaderChunk.linedashed_vert,
  8971. fragmentShader: ShaderChunk.linedashed_frag
  8972. },
  8973. depth: {
  8974. uniforms: mergeUniforms( [
  8975. UniformsLib.common,
  8976. UniformsLib.displacementmap
  8977. ] ),
  8978. vertexShader: ShaderChunk.depth_vert,
  8979. fragmentShader: ShaderChunk.depth_frag
  8980. },
  8981. normal: {
  8982. uniforms: mergeUniforms( [
  8983. UniformsLib.common,
  8984. UniformsLib.bumpmap,
  8985. UniformsLib.normalmap,
  8986. UniformsLib.displacementmap,
  8987. {
  8988. opacity: { value: 1.0 }
  8989. }
  8990. ] ),
  8991. vertexShader: ShaderChunk.normal_vert,
  8992. fragmentShader: ShaderChunk.normal_frag
  8993. },
  8994. sprite: {
  8995. uniforms: mergeUniforms( [
  8996. UniformsLib.sprite,
  8997. UniformsLib.fog
  8998. ] ),
  8999. vertexShader: ShaderChunk.sprite_vert,
  9000. fragmentShader: ShaderChunk.sprite_frag
  9001. },
  9002. background: {
  9003. uniforms: {
  9004. uvTransform: { value: new Matrix3() },
  9005. t2D: { value: null },
  9006. },
  9007. vertexShader: ShaderChunk.background_vert,
  9008. fragmentShader: ShaderChunk.background_frag
  9009. },
  9010. /* -------------------------------------------------------------------------
  9011. // Cube map shader
  9012. ------------------------------------------------------------------------- */
  9013. cube: {
  9014. uniforms: mergeUniforms( [
  9015. UniformsLib.envmap,
  9016. {
  9017. opacity: { value: 1.0 }
  9018. }
  9019. ] ),
  9020. vertexShader: ShaderChunk.cube_vert,
  9021. fragmentShader: ShaderChunk.cube_frag
  9022. },
  9023. equirect: {
  9024. uniforms: {
  9025. tEquirect: { value: null },
  9026. },
  9027. vertexShader: ShaderChunk.equirect_vert,
  9028. fragmentShader: ShaderChunk.equirect_frag
  9029. },
  9030. distanceRGBA: {
  9031. uniforms: mergeUniforms( [
  9032. UniformsLib.common,
  9033. UniformsLib.displacementmap,
  9034. {
  9035. referencePosition: { value: new Vector3() },
  9036. nearDistance: { value: 1 },
  9037. farDistance: { value: 1000 }
  9038. }
  9039. ] ),
  9040. vertexShader: ShaderChunk.distanceRGBA_vert,
  9041. fragmentShader: ShaderChunk.distanceRGBA_frag
  9042. },
  9043. shadow: {
  9044. uniforms: mergeUniforms( [
  9045. UniformsLib.lights,
  9046. UniformsLib.fog,
  9047. {
  9048. color: { value: new Color( 0x00000 ) },
  9049. opacity: { value: 1.0 }
  9050. },
  9051. ] ),
  9052. vertexShader: ShaderChunk.shadow_vert,
  9053. fragmentShader: ShaderChunk.shadow_frag
  9054. }
  9055. };
  9056. ShaderLib.physical = {
  9057. uniforms: mergeUniforms( [
  9058. ShaderLib.standard.uniforms,
  9059. {
  9060. clearcoat: { value: 0 },
  9061. clearcoatMap: { value: null },
  9062. clearcoatRoughness: { value: 0 },
  9063. clearcoatRoughnessMap: { value: null },
  9064. clearcoatNormalScale: { value: new Vector2$1( 1, 1 ) },
  9065. clearcoatNormalMap: { value: null },
  9066. sheen: { value: new Color( 0x000000 ) },
  9067. transmission: { value: 0 },
  9068. transmissionMap: { value: null },
  9069. }
  9070. ] ),
  9071. vertexShader: ShaderChunk.meshphysical_vert,
  9072. fragmentShader: ShaderChunk.meshphysical_frag
  9073. };
  9074. function WebGLBackground( renderer, cubemaps, state, objects, premultipliedAlpha ) {
  9075. const clearColor = new Color( 0x000000 );
  9076. let clearAlpha = 0;
  9077. let planeMesh;
  9078. let boxMesh;
  9079. let currentBackground = null;
  9080. let currentBackgroundVersion = 0;
  9081. let currentTonemapping = null;
  9082. function render( renderList, scene, camera, forceClear ) {
  9083. let background = scene.isScene === true ? scene.background : null;
  9084. if ( background && background.isTexture ) {
  9085. background = cubemaps.get( background );
  9086. }
  9087. // Ignore background in AR
  9088. // TODO: Reconsider this.
  9089. const xr = renderer.xr;
  9090. const session = xr.getSession && xr.getSession();
  9091. if ( session && session.environmentBlendMode === 'additive' ) {
  9092. background = null;
  9093. }
  9094. if ( background === null ) {
  9095. setClear( clearColor, clearAlpha );
  9096. } else if ( background && background.isColor ) {
  9097. setClear( background, 1 );
  9098. forceClear = true;
  9099. }
  9100. if ( renderer.autoClear || forceClear ) {
  9101. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  9102. }
  9103. if ( background && ( background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping ) ) {
  9104. if ( boxMesh === undefined ) {
  9105. boxMesh = new Mesh(
  9106. new BoxBufferGeometry( 1, 1, 1 ),
  9107. new ShaderMaterial( {
  9108. name: 'BackgroundCubeMaterial',
  9109. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  9110. vertexShader: ShaderLib.cube.vertexShader,
  9111. fragmentShader: ShaderLib.cube.fragmentShader,
  9112. side: BackSide,
  9113. depthTest: false,
  9114. depthWrite: false,
  9115. fog: false
  9116. } )
  9117. );
  9118. boxMesh.geometry.deleteAttribute( 'normal' );
  9119. boxMesh.geometry.deleteAttribute( 'uv' );
  9120. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  9121. this.matrixWorld.copyPosition( camera.matrixWorld );
  9122. };
  9123. // enable code injection for non-built-in material
  9124. Object.defineProperty( boxMesh.material, 'envMap', {
  9125. get: function () {
  9126. return this.uniforms.envMap.value;
  9127. }
  9128. } );
  9129. objects.update( boxMesh );
  9130. }
  9131. if ( background.isWebGLCubeRenderTarget ) {
  9132. // TODO Deprecate
  9133. background = background.texture;
  9134. }
  9135. boxMesh.material.uniforms.envMap.value = background;
  9136. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background._needsFlipEnvMap ) ? - 1 : 1;
  9137. if ( currentBackground !== background ||
  9138. currentBackgroundVersion !== background.version ||
  9139. currentTonemapping !== renderer.toneMapping ) {
  9140. boxMesh.material.needsUpdate = true;
  9141. currentBackground = background;
  9142. currentBackgroundVersion = background.version;
  9143. currentTonemapping = renderer.toneMapping;
  9144. }
  9145. // push to the pre-sorted opaque render list
  9146. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  9147. } else if ( background && background.isTexture ) {
  9148. if ( planeMesh === undefined ) {
  9149. planeMesh = new Mesh(
  9150. new PlaneBufferGeometry( 2, 2 ),
  9151. new ShaderMaterial( {
  9152. name: 'BackgroundMaterial',
  9153. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  9154. vertexShader: ShaderLib.background.vertexShader,
  9155. fragmentShader: ShaderLib.background.fragmentShader,
  9156. side: FrontSide,
  9157. depthTest: false,
  9158. depthWrite: false,
  9159. fog: false
  9160. } )
  9161. );
  9162. planeMesh.geometry.deleteAttribute( 'normal' );
  9163. // enable code injection for non-built-in material
  9164. Object.defineProperty( planeMesh.material, 'map', {
  9165. get: function () {
  9166. return this.uniforms.t2D.value;
  9167. }
  9168. } );
  9169. objects.update( planeMesh );
  9170. }
  9171. planeMesh.material.uniforms.t2D.value = background;
  9172. if ( background.matrixAutoUpdate === true ) {
  9173. background.updateMatrix();
  9174. }
  9175. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  9176. if ( currentBackground !== background ||
  9177. currentBackgroundVersion !== background.version ||
  9178. currentTonemapping !== renderer.toneMapping ) {
  9179. planeMesh.material.needsUpdate = true;
  9180. currentBackground = background;
  9181. currentBackgroundVersion = background.version;
  9182. currentTonemapping = renderer.toneMapping;
  9183. }
  9184. // push to the pre-sorted opaque render list
  9185. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  9186. }
  9187. }
  9188. function setClear( color, alpha ) {
  9189. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  9190. }
  9191. return {
  9192. getClearColor: function () {
  9193. return clearColor;
  9194. },
  9195. setClearColor: function ( color, alpha = 1 ) {
  9196. clearColor.set( color );
  9197. clearAlpha = alpha;
  9198. setClear( clearColor, clearAlpha );
  9199. },
  9200. getClearAlpha: function () {
  9201. return clearAlpha;
  9202. },
  9203. setClearAlpha: function ( alpha ) {
  9204. clearAlpha = alpha;
  9205. setClear( clearColor, clearAlpha );
  9206. },
  9207. render: render
  9208. };
  9209. }
  9210. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  9211. const maxVertexAttributes = gl.getParameter( 34921 );
  9212. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  9213. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  9214. const bindingStates = {};
  9215. const defaultState = createBindingState( null );
  9216. let currentState = defaultState;
  9217. function setup( object, material, program, geometry, index ) {
  9218. let updateBuffers = false;
  9219. if ( vaoAvailable ) {
  9220. const state = getBindingState( geometry, program, material );
  9221. if ( currentState !== state ) {
  9222. currentState = state;
  9223. bindVertexArrayObject( currentState.object );
  9224. }
  9225. updateBuffers = needsUpdate( geometry, index );
  9226. if ( updateBuffers ) saveCache( geometry, index );
  9227. } else {
  9228. const wireframe = ( material.wireframe === true );
  9229. if ( currentState.geometry !== geometry.id ||
  9230. currentState.program !== program.id ||
  9231. currentState.wireframe !== wireframe ) {
  9232. currentState.geometry = geometry.id;
  9233. currentState.program = program.id;
  9234. currentState.wireframe = wireframe;
  9235. updateBuffers = true;
  9236. }
  9237. }
  9238. if ( object.isInstancedMesh === true ) {
  9239. updateBuffers = true;
  9240. }
  9241. if ( index !== null ) {
  9242. attributes.update( index, 34963 );
  9243. }
  9244. if ( updateBuffers ) {
  9245. setupVertexAttributes( object, material, program, geometry );
  9246. if ( index !== null ) {
  9247. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  9248. }
  9249. }
  9250. }
  9251. function createVertexArrayObject() {
  9252. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  9253. return extension.createVertexArrayOES();
  9254. }
  9255. function bindVertexArrayObject( vao ) {
  9256. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  9257. return extension.bindVertexArrayOES( vao );
  9258. }
  9259. function deleteVertexArrayObject( vao ) {
  9260. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  9261. return extension.deleteVertexArrayOES( vao );
  9262. }
  9263. function getBindingState( geometry, program, material ) {
  9264. const wireframe = ( material.wireframe === true );
  9265. let programMap = bindingStates[ geometry.id ];
  9266. if ( programMap === undefined ) {
  9267. programMap = {};
  9268. bindingStates[ geometry.id ] = programMap;
  9269. }
  9270. let stateMap = programMap[ program.id ];
  9271. if ( stateMap === undefined ) {
  9272. stateMap = {};
  9273. programMap[ program.id ] = stateMap;
  9274. }
  9275. let state = stateMap[ wireframe ];
  9276. if ( state === undefined ) {
  9277. state = createBindingState( createVertexArrayObject() );
  9278. stateMap[ wireframe ] = state;
  9279. }
  9280. return state;
  9281. }
  9282. function createBindingState( vao ) {
  9283. const newAttributes = [];
  9284. const enabledAttributes = [];
  9285. const attributeDivisors = [];
  9286. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  9287. newAttributes[ i ] = 0;
  9288. enabledAttributes[ i ] = 0;
  9289. attributeDivisors[ i ] = 0;
  9290. }
  9291. return {
  9292. // for backward compatibility on non-VAO support browser
  9293. geometry: null,
  9294. program: null,
  9295. wireframe: false,
  9296. newAttributes: newAttributes,
  9297. enabledAttributes: enabledAttributes,
  9298. attributeDivisors: attributeDivisors,
  9299. object: vao,
  9300. attributes: {},
  9301. index: null
  9302. };
  9303. }
  9304. function needsUpdate( geometry, index ) {
  9305. const cachedAttributes = currentState.attributes;
  9306. const geometryAttributes = geometry.attributes;
  9307. let attributesNum = 0;
  9308. for ( const key in geometryAttributes ) {
  9309. const cachedAttribute = cachedAttributes[ key ];
  9310. const geometryAttribute = geometryAttributes[ key ];
  9311. if ( cachedAttribute === undefined ) return true;
  9312. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  9313. if ( cachedAttribute.data !== geometryAttribute.data ) return true;
  9314. attributesNum ++;
  9315. }
  9316. if ( currentState.attributesNum !== attributesNum ) return true;
  9317. if ( currentState.index !== index ) return true;
  9318. return false;
  9319. }
  9320. function saveCache( geometry, index ) {
  9321. const cache = {};
  9322. const attributes = geometry.attributes;
  9323. let attributesNum = 0;
  9324. for ( const key in attributes ) {
  9325. const attribute = attributes[ key ];
  9326. const data = {};
  9327. data.attribute = attribute;
  9328. if ( attribute.data ) {
  9329. data.data = attribute.data;
  9330. }
  9331. cache[ key ] = data;
  9332. attributesNum ++;
  9333. }
  9334. currentState.attributes = cache;
  9335. currentState.attributesNum = attributesNum;
  9336. currentState.index = index;
  9337. }
  9338. function initAttributes() {
  9339. const newAttributes = currentState.newAttributes;
  9340. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  9341. newAttributes[ i ] = 0;
  9342. }
  9343. }
  9344. function enableAttribute( attribute ) {
  9345. enableAttributeAndDivisor( attribute, 0 );
  9346. }
  9347. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  9348. const newAttributes = currentState.newAttributes;
  9349. const enabledAttributes = currentState.enabledAttributes;
  9350. const attributeDivisors = currentState.attributeDivisors;
  9351. newAttributes[ attribute ] = 1;
  9352. if ( enabledAttributes[ attribute ] === 0 ) {
  9353. gl.enableVertexAttribArray( attribute );
  9354. enabledAttributes[ attribute ] = 1;
  9355. }
  9356. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  9357. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  9358. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  9359. attributeDivisors[ attribute ] = meshPerAttribute;
  9360. }
  9361. }
  9362. function disableUnusedAttributes() {
  9363. const newAttributes = currentState.newAttributes;
  9364. const enabledAttributes = currentState.enabledAttributes;
  9365. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  9366. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  9367. gl.disableVertexAttribArray( i );
  9368. enabledAttributes[ i ] = 0;
  9369. }
  9370. }
  9371. }
  9372. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  9373. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  9374. gl.vertexAttribIPointer( index, size, type, stride, offset );
  9375. } else {
  9376. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  9377. }
  9378. }
  9379. function setupVertexAttributes( object, material, program, geometry ) {
  9380. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  9381. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  9382. }
  9383. initAttributes();
  9384. const geometryAttributes = geometry.attributes;
  9385. const programAttributes = program.getAttributes();
  9386. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9387. for ( const name in programAttributes ) {
  9388. const programAttribute = programAttributes[ name ];
  9389. if ( programAttribute >= 0 ) {
  9390. const geometryAttribute = geometryAttributes[ name ];
  9391. if ( geometryAttribute !== undefined ) {
  9392. const normalized = geometryAttribute.normalized;
  9393. const size = geometryAttribute.itemSize;
  9394. const attribute = attributes.get( geometryAttribute );
  9395. // TODO Attribute may not be available on context restore
  9396. if ( attribute === undefined ) continue;
  9397. const buffer = attribute.buffer;
  9398. const type = attribute.type;
  9399. const bytesPerElement = attribute.bytesPerElement;
  9400. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  9401. const data = geometryAttribute.data;
  9402. const stride = data.stride;
  9403. const offset = geometryAttribute.offset;
  9404. if ( data && data.isInstancedInterleavedBuffer ) {
  9405. enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  9406. if ( geometry._maxInstanceCount === undefined ) {
  9407. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9408. }
  9409. } else {
  9410. enableAttribute( programAttribute );
  9411. }
  9412. gl.bindBuffer( 34962, buffer );
  9413. vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement );
  9414. } else {
  9415. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9416. enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  9417. if ( geometry._maxInstanceCount === undefined ) {
  9418. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9419. }
  9420. } else {
  9421. enableAttribute( programAttribute );
  9422. }
  9423. gl.bindBuffer( 34962, buffer );
  9424. vertexAttribPointer( programAttribute, size, type, normalized, 0, 0 );
  9425. }
  9426. } else if ( name === 'instanceMatrix' ) {
  9427. const attribute = attributes.get( object.instanceMatrix );
  9428. // TODO Attribute may not be available on context restore
  9429. if ( attribute === undefined ) continue;
  9430. const buffer = attribute.buffer;
  9431. const type = attribute.type;
  9432. enableAttributeAndDivisor( programAttribute + 0, 1 );
  9433. enableAttributeAndDivisor( programAttribute + 1, 1 );
  9434. enableAttributeAndDivisor( programAttribute + 2, 1 );
  9435. enableAttributeAndDivisor( programAttribute + 3, 1 );
  9436. gl.bindBuffer( 34962, buffer );
  9437. gl.vertexAttribPointer( programAttribute + 0, 4, type, false, 64, 0 );
  9438. gl.vertexAttribPointer( programAttribute + 1, 4, type, false, 64, 16 );
  9439. gl.vertexAttribPointer( programAttribute + 2, 4, type, false, 64, 32 );
  9440. gl.vertexAttribPointer( programAttribute + 3, 4, type, false, 64, 48 );
  9441. } else if ( name === 'instanceColor' ) {
  9442. const attribute = attributes.get( object.instanceColor );
  9443. // TODO Attribute may not be available on context restore
  9444. if ( attribute === undefined ) continue;
  9445. const buffer = attribute.buffer;
  9446. const type = attribute.type;
  9447. enableAttributeAndDivisor( programAttribute, 1 );
  9448. gl.bindBuffer( 34962, buffer );
  9449. gl.vertexAttribPointer( programAttribute, 3, type, false, 12, 0 );
  9450. } else if ( materialDefaultAttributeValues !== undefined ) {
  9451. const value = materialDefaultAttributeValues[ name ];
  9452. if ( value !== undefined ) {
  9453. switch ( value.length ) {
  9454. case 2:
  9455. gl.vertexAttrib2fv( programAttribute, value );
  9456. break;
  9457. case 3:
  9458. gl.vertexAttrib3fv( programAttribute, value );
  9459. break;
  9460. case 4:
  9461. gl.vertexAttrib4fv( programAttribute, value );
  9462. break;
  9463. default:
  9464. gl.vertexAttrib1fv( programAttribute, value );
  9465. }
  9466. }
  9467. }
  9468. }
  9469. }
  9470. disableUnusedAttributes();
  9471. }
  9472. function dispose() {
  9473. reset();
  9474. for ( const geometryId in bindingStates ) {
  9475. const programMap = bindingStates[ geometryId ];
  9476. for ( const programId in programMap ) {
  9477. const stateMap = programMap[ programId ];
  9478. for ( const wireframe in stateMap ) {
  9479. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9480. delete stateMap[ wireframe ];
  9481. }
  9482. delete programMap[ programId ];
  9483. }
  9484. delete bindingStates[ geometryId ];
  9485. }
  9486. }
  9487. function releaseStatesOfGeometry( geometry ) {
  9488. if ( bindingStates[ geometry.id ] === undefined ) return;
  9489. const programMap = bindingStates[ geometry.id ];
  9490. for ( const programId in programMap ) {
  9491. const stateMap = programMap[ programId ];
  9492. for ( const wireframe in stateMap ) {
  9493. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9494. delete stateMap[ wireframe ];
  9495. }
  9496. delete programMap[ programId ];
  9497. }
  9498. delete bindingStates[ geometry.id ];
  9499. }
  9500. function releaseStatesOfProgram( program ) {
  9501. for ( const geometryId in bindingStates ) {
  9502. const programMap = bindingStates[ geometryId ];
  9503. if ( programMap[ program.id ] === undefined ) continue;
  9504. const stateMap = programMap[ program.id ];
  9505. for ( const wireframe in stateMap ) {
  9506. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9507. delete stateMap[ wireframe ];
  9508. }
  9509. delete programMap[ program.id ];
  9510. }
  9511. }
  9512. function reset() {
  9513. resetDefaultState();
  9514. if ( currentState === defaultState ) return;
  9515. currentState = defaultState;
  9516. bindVertexArrayObject( currentState.object );
  9517. }
  9518. // for backward-compatilibity
  9519. function resetDefaultState() {
  9520. defaultState.geometry = null;
  9521. defaultState.program = null;
  9522. defaultState.wireframe = false;
  9523. }
  9524. return {
  9525. setup: setup,
  9526. reset: reset,
  9527. resetDefaultState: resetDefaultState,
  9528. dispose: dispose,
  9529. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9530. releaseStatesOfProgram: releaseStatesOfProgram,
  9531. initAttributes: initAttributes,
  9532. enableAttribute: enableAttribute,
  9533. disableUnusedAttributes: disableUnusedAttributes
  9534. };
  9535. }
  9536. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  9537. const isWebGL2 = capabilities.isWebGL2;
  9538. let mode;
  9539. function setMode( value ) {
  9540. mode = value;
  9541. }
  9542. function render( start, count ) {
  9543. gl.drawArrays( mode, start, count );
  9544. info.update( count, mode, 1 );
  9545. }
  9546. function renderInstances( start, count, primcount ) {
  9547. if ( primcount === 0 ) return;
  9548. let extension, methodName;
  9549. if ( isWebGL2 ) {
  9550. extension = gl;
  9551. methodName = 'drawArraysInstanced';
  9552. } else {
  9553. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9554. methodName = 'drawArraysInstancedANGLE';
  9555. if ( extension === null ) {
  9556. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9557. return;
  9558. }
  9559. }
  9560. extension[ methodName ]( mode, start, count, primcount );
  9561. info.update( count, mode, primcount );
  9562. }
  9563. //
  9564. this.setMode = setMode;
  9565. this.render = render;
  9566. this.renderInstances = renderInstances;
  9567. }
  9568. function WebGLCapabilities( gl, extensions, parameters ) {
  9569. let maxAnisotropy;
  9570. function getMaxAnisotropy() {
  9571. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9572. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9573. if ( extension !== null ) {
  9574. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9575. } else {
  9576. maxAnisotropy = 0;
  9577. }
  9578. return maxAnisotropy;
  9579. }
  9580. function getMaxPrecision( precision ) {
  9581. if ( precision === 'highp' ) {
  9582. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  9583. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  9584. return 'highp';
  9585. }
  9586. precision = 'mediump';
  9587. }
  9588. if ( precision === 'mediump' ) {
  9589. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  9590. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  9591. return 'mediump';
  9592. }
  9593. }
  9594. return 'lowp';
  9595. }
  9596. /* eslint-disable no-undef */
  9597. const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  9598. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  9599. /* eslint-enable no-undef */
  9600. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9601. const maxPrecision = getMaxPrecision( precision );
  9602. if ( maxPrecision !== precision ) {
  9603. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9604. precision = maxPrecision;
  9605. }
  9606. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9607. const maxTextures = gl.getParameter( 34930 );
  9608. const maxVertexTextures = gl.getParameter( 35660 );
  9609. const maxTextureSize = gl.getParameter( 3379 );
  9610. const maxCubemapSize = gl.getParameter( 34076 );
  9611. const maxAttributes = gl.getParameter( 34921 );
  9612. const maxVertexUniforms = gl.getParameter( 36347 );
  9613. const maxVaryings = gl.getParameter( 36348 );
  9614. const maxFragmentUniforms = gl.getParameter( 36349 );
  9615. const vertexTextures = maxVertexTextures > 0;
  9616. const floatFragmentTextures = isWebGL2 || !! extensions.get( 'OES_texture_float' );
  9617. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9618. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  9619. return {
  9620. isWebGL2: isWebGL2,
  9621. getMaxAnisotropy: getMaxAnisotropy,
  9622. getMaxPrecision: getMaxPrecision,
  9623. precision: precision,
  9624. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9625. maxTextures: maxTextures,
  9626. maxVertexTextures: maxVertexTextures,
  9627. maxTextureSize: maxTextureSize,
  9628. maxCubemapSize: maxCubemapSize,
  9629. maxAttributes: maxAttributes,
  9630. maxVertexUniforms: maxVertexUniforms,
  9631. maxVaryings: maxVaryings,
  9632. maxFragmentUniforms: maxFragmentUniforms,
  9633. vertexTextures: vertexTextures,
  9634. floatFragmentTextures: floatFragmentTextures,
  9635. floatVertexTextures: floatVertexTextures,
  9636. maxSamples: maxSamples
  9637. };
  9638. }
  9639. function WebGLClipping( properties ) {
  9640. const scope = this;
  9641. let globalState = null,
  9642. numGlobalPlanes = 0,
  9643. localClippingEnabled = false,
  9644. renderingShadows = false;
  9645. const plane = new Plane(),
  9646. viewNormalMatrix = new Matrix3(),
  9647. uniform = { value: null, needsUpdate: false };
  9648. this.uniform = uniform;
  9649. this.numPlanes = 0;
  9650. this.numIntersection = 0;
  9651. this.init = function ( planes, enableLocalClipping, camera ) {
  9652. const enabled =
  9653. planes.length !== 0 ||
  9654. enableLocalClipping ||
  9655. // enable state of previous frame - the clipping code has to
  9656. // run another frame in order to reset the state:
  9657. numGlobalPlanes !== 0 ||
  9658. localClippingEnabled;
  9659. localClippingEnabled = enableLocalClipping;
  9660. globalState = projectPlanes( planes, camera, 0 );
  9661. numGlobalPlanes = planes.length;
  9662. return enabled;
  9663. };
  9664. this.beginShadows = function () {
  9665. renderingShadows = true;
  9666. projectPlanes( null );
  9667. };
  9668. this.endShadows = function () {
  9669. renderingShadows = false;
  9670. resetGlobalState();
  9671. };
  9672. this.setState = function ( material, camera, useCache ) {
  9673. const planes = material.clippingPlanes,
  9674. clipIntersection = material.clipIntersection,
  9675. clipShadows = material.clipShadows;
  9676. const materialProperties = properties.get( material );
  9677. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9678. // there's no local clipping
  9679. if ( renderingShadows ) {
  9680. // there's no global clipping
  9681. projectPlanes( null );
  9682. } else {
  9683. resetGlobalState();
  9684. }
  9685. } else {
  9686. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9687. lGlobal = nGlobal * 4;
  9688. let dstArray = materialProperties.clippingState || null;
  9689. uniform.value = dstArray; // ensure unique state
  9690. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9691. for ( let i = 0; i !== lGlobal; ++ i ) {
  9692. dstArray[ i ] = globalState[ i ];
  9693. }
  9694. materialProperties.clippingState = dstArray;
  9695. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9696. this.numPlanes += nGlobal;
  9697. }
  9698. };
  9699. function resetGlobalState() {
  9700. if ( uniform.value !== globalState ) {
  9701. uniform.value = globalState;
  9702. uniform.needsUpdate = numGlobalPlanes > 0;
  9703. }
  9704. scope.numPlanes = numGlobalPlanes;
  9705. scope.numIntersection = 0;
  9706. }
  9707. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9708. const nPlanes = planes !== null ? planes.length : 0;
  9709. let dstArray = null;
  9710. if ( nPlanes !== 0 ) {
  9711. dstArray = uniform.value;
  9712. if ( skipTransform !== true || dstArray === null ) {
  9713. const flatSize = dstOffset + nPlanes * 4,
  9714. viewMatrix = camera.matrixWorldInverse;
  9715. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9716. if ( dstArray === null || dstArray.length < flatSize ) {
  9717. dstArray = new Float32Array( flatSize );
  9718. }
  9719. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9720. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9721. plane.normal.toArray( dstArray, i4 );
  9722. dstArray[ i4 + 3 ] = plane.constant;
  9723. }
  9724. }
  9725. uniform.value = dstArray;
  9726. uniform.needsUpdate = true;
  9727. }
  9728. scope.numPlanes = nPlanes;
  9729. scope.numIntersection = 0;
  9730. return dstArray;
  9731. }
  9732. }
  9733. function WebGLCubeMaps( renderer ) {
  9734. let cubemaps = new WeakMap();
  9735. function mapTextureMapping( texture, mapping ) {
  9736. if ( mapping === EquirectangularReflectionMapping ) {
  9737. texture.mapping = CubeReflectionMapping;
  9738. } else if ( mapping === EquirectangularRefractionMapping ) {
  9739. texture.mapping = CubeRefractionMapping;
  9740. }
  9741. return texture;
  9742. }
  9743. function get( texture ) {
  9744. if ( texture && texture.isTexture ) {
  9745. const mapping = texture.mapping;
  9746. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9747. if ( cubemaps.has( texture ) ) {
  9748. const cubemap = cubemaps.get( texture ).texture;
  9749. return mapTextureMapping( cubemap, texture.mapping );
  9750. } else {
  9751. const image = texture.image;
  9752. if ( image && image.height > 0 ) {
  9753. const currentRenderList = renderer.getRenderList();
  9754. const currentRenderTarget = renderer.getRenderTarget();
  9755. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9756. renderTarget.fromEquirectangularTexture( renderer, texture );
  9757. cubemaps.set( texture, renderTarget );
  9758. renderer.setRenderTarget( currentRenderTarget );
  9759. renderer.setRenderList( currentRenderList );
  9760. texture.addEventListener( 'dispose', onTextureDispose );
  9761. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9762. } else {
  9763. // image not yet ready. try the conversion next frame
  9764. return null;
  9765. }
  9766. }
  9767. }
  9768. }
  9769. return texture;
  9770. }
  9771. function onTextureDispose( event ) {
  9772. const texture = event.target;
  9773. texture.removeEventListener( 'dispose', onTextureDispose );
  9774. const cubemap = cubemaps.get( texture );
  9775. if ( cubemap !== undefined ) {
  9776. cubemaps.delete( texture );
  9777. cubemap.dispose();
  9778. }
  9779. }
  9780. function dispose() {
  9781. cubemaps = new WeakMap();
  9782. }
  9783. return {
  9784. get: get,
  9785. dispose: dispose
  9786. };
  9787. }
  9788. function WebGLExtensions( gl ) {
  9789. const extensions = {};
  9790. return {
  9791. has: function ( name ) {
  9792. if ( extensions[ name ] !== undefined ) {
  9793. return extensions[ name ] !== null;
  9794. }
  9795. let extension;
  9796. switch ( name ) {
  9797. case 'WEBGL_depth_texture':
  9798. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9799. break;
  9800. case 'EXT_texture_filter_anisotropic':
  9801. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9802. break;
  9803. case 'WEBGL_compressed_texture_s3tc':
  9804. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9805. break;
  9806. case 'WEBGL_compressed_texture_pvrtc':
  9807. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9808. break;
  9809. default:
  9810. extension = gl.getExtension( name );
  9811. }
  9812. extensions[ name ] = extension;
  9813. return extension !== null;
  9814. },
  9815. get: function ( name ) {
  9816. if ( ! this.has( name ) ) {
  9817. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9818. }
  9819. return extensions[ name ];
  9820. }
  9821. };
  9822. }
  9823. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  9824. const geometries = new WeakMap();
  9825. const wireframeAttributes = new WeakMap();
  9826. function onGeometryDispose( event ) {
  9827. const geometry = event.target;
  9828. const buffergeometry = geometries.get( geometry );
  9829. if ( buffergeometry.index !== null ) {
  9830. attributes.remove( buffergeometry.index );
  9831. }
  9832. for ( const name in buffergeometry.attributes ) {
  9833. attributes.remove( buffergeometry.attributes[ name ] );
  9834. }
  9835. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9836. geometries.delete( geometry );
  9837. const attribute = wireframeAttributes.get( buffergeometry );
  9838. if ( attribute ) {
  9839. attributes.remove( attribute );
  9840. wireframeAttributes.delete( buffergeometry );
  9841. }
  9842. bindingStates.releaseStatesOfGeometry( buffergeometry );
  9843. if ( geometry.isInstancedBufferGeometry === true ) {
  9844. delete geometry._maxInstanceCount;
  9845. }
  9846. //
  9847. info.memory.geometries --;
  9848. }
  9849. function get( object, geometry ) {
  9850. let buffergeometry = geometries.get( geometry );
  9851. if ( buffergeometry ) return buffergeometry;
  9852. geometry.addEventListener( 'dispose', onGeometryDispose );
  9853. if ( geometry.isBufferGeometry ) {
  9854. buffergeometry = geometry;
  9855. } else if ( geometry.isGeometry ) {
  9856. if ( geometry._bufferGeometry === undefined ) {
  9857. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  9858. }
  9859. buffergeometry = geometry._bufferGeometry;
  9860. }
  9861. geometries.set( geometry, buffergeometry );
  9862. info.memory.geometries ++;
  9863. return buffergeometry;
  9864. }
  9865. function update( geometry ) {
  9866. const geometryAttributes = geometry.attributes;
  9867. // Updating index buffer in VAO now. See WebGLBindingStates.
  9868. for ( const name in geometryAttributes ) {
  9869. attributes.update( geometryAttributes[ name ], 34962 );
  9870. }
  9871. // morph targets
  9872. const morphAttributes = geometry.morphAttributes;
  9873. for ( const name in morphAttributes ) {
  9874. const array = morphAttributes[ name ];
  9875. for ( let i = 0, l = array.length; i < l; i ++ ) {
  9876. attributes.update( array[ i ], 34962 );
  9877. }
  9878. }
  9879. }
  9880. function updateWireframeAttribute( geometry ) {
  9881. const indices = [];
  9882. const geometryIndex = geometry.index;
  9883. const geometryPosition = geometry.attributes.position;
  9884. let version = 0;
  9885. if ( geometryIndex !== null ) {
  9886. const array = geometryIndex.array;
  9887. version = geometryIndex.version;
  9888. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9889. const a = array[ i + 0 ];
  9890. const b = array[ i + 1 ];
  9891. const c = array[ i + 2 ];
  9892. indices.push( a, b, b, c, c, a );
  9893. }
  9894. } else {
  9895. const array = geometryPosition.array;
  9896. version = geometryPosition.version;
  9897. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9898. const a = i + 0;
  9899. const b = i + 1;
  9900. const c = i + 2;
  9901. indices.push( a, b, b, c, c, a );
  9902. }
  9903. }
  9904. const attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9905. attribute.version = version;
  9906. // Updating index buffer in VAO now. See WebGLBindingStates
  9907. //
  9908. const previousAttribute = wireframeAttributes.get( geometry );
  9909. if ( previousAttribute ) attributes.remove( previousAttribute );
  9910. //
  9911. wireframeAttributes.set( geometry, attribute );
  9912. }
  9913. function getWireframeAttribute( geometry ) {
  9914. const currentAttribute = wireframeAttributes.get( geometry );
  9915. if ( currentAttribute ) {
  9916. const geometryIndex = geometry.index;
  9917. if ( geometryIndex !== null ) {
  9918. // if the attribute is obsolete, create a new one
  9919. if ( currentAttribute.version < geometryIndex.version ) {
  9920. updateWireframeAttribute( geometry );
  9921. }
  9922. }
  9923. } else {
  9924. updateWireframeAttribute( geometry );
  9925. }
  9926. return wireframeAttributes.get( geometry );
  9927. }
  9928. return {
  9929. get: get,
  9930. update: update,
  9931. getWireframeAttribute: getWireframeAttribute
  9932. };
  9933. }
  9934. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  9935. const isWebGL2 = capabilities.isWebGL2;
  9936. let mode;
  9937. function setMode( value ) {
  9938. mode = value;
  9939. }
  9940. let type, bytesPerElement;
  9941. function setIndex( value ) {
  9942. type = value.type;
  9943. bytesPerElement = value.bytesPerElement;
  9944. }
  9945. function render( start, count ) {
  9946. gl.drawElements( mode, count, type, start * bytesPerElement );
  9947. info.update( count, mode, 1 );
  9948. }
  9949. function renderInstances( start, count, primcount ) {
  9950. if ( primcount === 0 ) return;
  9951. let extension, methodName;
  9952. if ( isWebGL2 ) {
  9953. extension = gl;
  9954. methodName = 'drawElementsInstanced';
  9955. } else {
  9956. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9957. methodName = 'drawElementsInstancedANGLE';
  9958. if ( extension === null ) {
  9959. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9960. return;
  9961. }
  9962. }
  9963. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  9964. info.update( count, mode, primcount );
  9965. }
  9966. //
  9967. this.setMode = setMode;
  9968. this.setIndex = setIndex;
  9969. this.render = render;
  9970. this.renderInstances = renderInstances;
  9971. }
  9972. function WebGLInfo( gl ) {
  9973. const memory = {
  9974. geometries: 0,
  9975. textures: 0
  9976. };
  9977. const render = {
  9978. frame: 0,
  9979. calls: 0,
  9980. triangles: 0,
  9981. points: 0,
  9982. lines: 0
  9983. };
  9984. function update( count, mode, instanceCount ) {
  9985. render.calls ++;
  9986. switch ( mode ) {
  9987. case 4:
  9988. render.triangles += instanceCount * ( count / 3 );
  9989. break;
  9990. case 1:
  9991. render.lines += instanceCount * ( count / 2 );
  9992. break;
  9993. case 3:
  9994. render.lines += instanceCount * ( count - 1 );
  9995. break;
  9996. case 2:
  9997. render.lines += instanceCount * count;
  9998. break;
  9999. case 0:
  10000. render.points += instanceCount * count;
  10001. break;
  10002. default:
  10003. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10004. break;
  10005. }
  10006. }
  10007. function reset() {
  10008. render.frame ++;
  10009. render.calls = 0;
  10010. render.triangles = 0;
  10011. render.points = 0;
  10012. render.lines = 0;
  10013. }
  10014. return {
  10015. memory: memory,
  10016. render: render,
  10017. programs: null,
  10018. autoReset: true,
  10019. reset: reset,
  10020. update: update
  10021. };
  10022. }
  10023. function numericalSort( a, b ) {
  10024. return a[ 0 ] - b[ 0 ];
  10025. }
  10026. function absNumericalSort( a, b ) {
  10027. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10028. }
  10029. function WebGLMorphtargets( gl ) {
  10030. const influencesList = {};
  10031. const morphInfluences = new Float32Array( 8 );
  10032. const workInfluences = [];
  10033. for ( let i = 0; i < 8; i ++ ) {
  10034. workInfluences[ i ] = [ i, 0 ];
  10035. }
  10036. function update( object, geometry, material, program ) {
  10037. const objectInfluences = object.morphTargetInfluences;
  10038. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10039. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10040. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10041. let influences = influencesList[ geometry.id ];
  10042. if ( influences === undefined ) {
  10043. // initialise list
  10044. influences = [];
  10045. for ( let i = 0; i < length; i ++ ) {
  10046. influences[ i ] = [ i, 0 ];
  10047. }
  10048. influencesList[ geometry.id ] = influences;
  10049. }
  10050. // Collect influences
  10051. for ( let i = 0; i < length; i ++ ) {
  10052. const influence = influences[ i ];
  10053. influence[ 0 ] = i;
  10054. influence[ 1 ] = objectInfluences[ i ];
  10055. }
  10056. influences.sort( absNumericalSort );
  10057. for ( let i = 0; i < 8; i ++ ) {
  10058. if ( i < length && influences[ i ][ 1 ] ) {
  10059. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10060. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10061. } else {
  10062. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10063. workInfluences[ i ][ 1 ] = 0;
  10064. }
  10065. }
  10066. workInfluences.sort( numericalSort );
  10067. const morphTargets = material.morphTargets && geometry.morphAttributes.position;
  10068. const morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  10069. let morphInfluencesSum = 0;
  10070. for ( let i = 0; i < 8; i ++ ) {
  10071. const influence = workInfluences[ i ];
  10072. const index = influence[ 0 ];
  10073. const value = influence[ 1 ];
  10074. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10075. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10076. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10077. }
  10078. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10079. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10080. }
  10081. morphInfluences[ i ] = value;
  10082. morphInfluencesSum += value;
  10083. } else {
  10084. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10085. geometry.deleteAttribute( 'morphTarget' + i );
  10086. }
  10087. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10088. geometry.deleteAttribute( 'morphNormal' + i );
  10089. }
  10090. morphInfluences[ i ] = 0;
  10091. }
  10092. }
  10093. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10094. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10095. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10096. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10097. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10098. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10099. }
  10100. return {
  10101. update: update
  10102. };
  10103. }
  10104. function WebGLObjects( gl, geometries, attributes, info ) {
  10105. let updateMap = new WeakMap();
  10106. function update( object ) {
  10107. const frame = info.render.frame;
  10108. const geometry = object.geometry;
  10109. const buffergeometry = geometries.get( object, geometry );
  10110. // Update once per frame
  10111. if ( updateMap.get( buffergeometry ) !== frame ) {
  10112. if ( geometry.isGeometry ) {
  10113. buffergeometry.updateFromObject( object );
  10114. }
  10115. geometries.update( buffergeometry );
  10116. updateMap.set( buffergeometry, frame );
  10117. }
  10118. if ( object.isInstancedMesh ) {
  10119. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10120. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10121. }
  10122. attributes.update( object.instanceMatrix, 34962 );
  10123. if ( object.instanceColor !== null ) {
  10124. attributes.update( object.instanceColor, 34962 );
  10125. }
  10126. }
  10127. return buffergeometry;
  10128. }
  10129. function dispose() {
  10130. updateMap = new WeakMap();
  10131. }
  10132. function onInstancedMeshDispose( event ) {
  10133. const instancedMesh = event.target;
  10134. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10135. attributes.remove( instancedMesh.instanceMatrix );
  10136. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10137. }
  10138. return {
  10139. update: update,
  10140. dispose: dispose
  10141. };
  10142. }
  10143. function DataTexture2DArray( data = null, width = 1, height = 1, depth = 1 ) {
  10144. Texture.call( this, null );
  10145. this.image = { data, width, height, depth };
  10146. this.magFilter = NearestFilter;
  10147. this.minFilter = NearestFilter;
  10148. this.wrapR = ClampToEdgeWrapping;
  10149. this.generateMipmaps = false;
  10150. this.flipY = false;
  10151. this.needsUpdate = true;
  10152. }
  10153. DataTexture2DArray.prototype = Object.create( Texture.prototype );
  10154. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  10155. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10156. function DataTexture3D( data = null, width = 1, height = 1, depth = 1 ) {
  10157. // We're going to add .setXXX() methods for setting properties later.
  10158. // Users can still set in DataTexture3D directly.
  10159. //
  10160. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10161. // texture.anisotropy = 16;
  10162. //
  10163. // See #14839
  10164. Texture.call( this, null );
  10165. this.image = { data, width, height, depth };
  10166. this.magFilter = NearestFilter;
  10167. this.minFilter = NearestFilter;
  10168. this.wrapR = ClampToEdgeWrapping;
  10169. this.generateMipmaps = false;
  10170. this.flipY = false;
  10171. this.needsUpdate = true;
  10172. }
  10173. DataTexture3D.prototype = Object.create( Texture.prototype );
  10174. DataTexture3D.prototype.constructor = DataTexture3D;
  10175. DataTexture3D.prototype.isDataTexture3D = true;
  10176. /**
  10177. * Uniforms of a program.
  10178. * Those form a tree structure with a special top-level container for the root,
  10179. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10180. *
  10181. *
  10182. * Properties of inner nodes including the top-level container:
  10183. *
  10184. * .seq - array of nested uniforms
  10185. * .map - nested uniforms by name
  10186. *
  10187. *
  10188. * Methods of all nodes except the top-level container:
  10189. *
  10190. * .setValue( gl, value, [textures] )
  10191. *
  10192. * uploads a uniform value(s)
  10193. * the 'textures' parameter is needed for sampler uniforms
  10194. *
  10195. *
  10196. * Static methods of the top-level container (textures factorizations):
  10197. *
  10198. * .upload( gl, seq, values, textures )
  10199. *
  10200. * sets uniforms in 'seq' to 'values[id].value'
  10201. *
  10202. * .seqWithValue( seq, values ) : filteredSeq
  10203. *
  10204. * filters 'seq' entries with corresponding entry in values
  10205. *
  10206. *
  10207. * Methods of the top-level container (textures factorizations):
  10208. *
  10209. * .setValue( gl, name, value, textures )
  10210. *
  10211. * sets uniform with name 'name' to 'value'
  10212. *
  10213. * .setOptional( gl, obj, prop )
  10214. *
  10215. * like .set for an optional property of the object
  10216. *
  10217. */
  10218. const emptyTexture = new Texture();
  10219. const emptyTexture2dArray = new DataTexture2DArray();
  10220. const emptyTexture3d = new DataTexture3D();
  10221. const emptyCubeTexture = new CubeTexture();
  10222. // --- Utilities ---
  10223. // Array Caches (provide typed arrays for temporary by size)
  10224. const arrayCacheF32 = [];
  10225. const arrayCacheI32 = [];
  10226. // Float32Array caches used for uploading Matrix uniforms
  10227. const mat4array = new Float32Array( 16 );
  10228. const mat3array = new Float32Array( 9 );
  10229. const mat2array = new Float32Array( 4 );
  10230. // Flattening for arrays of vectors and matrices
  10231. function flatten( array, nBlocks, blockSize ) {
  10232. const firstElem = array[ 0 ];
  10233. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10234. // unoptimized: ! isNaN( firstElem )
  10235. // see http://jacksondunstan.com/articles/983
  10236. const n = nBlocks * blockSize;
  10237. let r = arrayCacheF32[ n ];
  10238. if ( r === undefined ) {
  10239. r = new Float32Array( n );
  10240. arrayCacheF32[ n ] = r;
  10241. }
  10242. if ( nBlocks !== 0 ) {
  10243. firstElem.toArray( r, 0 );
  10244. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10245. offset += blockSize;
  10246. array[ i ].toArray( r, offset );
  10247. }
  10248. }
  10249. return r;
  10250. }
  10251. function arraysEqual( a, b ) {
  10252. if ( a.length !== b.length ) return false;
  10253. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10254. if ( a[ i ] !== b[ i ] ) return false;
  10255. }
  10256. return true;
  10257. }
  10258. function copyArray( a, b ) {
  10259. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10260. a[ i ] = b[ i ];
  10261. }
  10262. }
  10263. // Texture unit allocation
  10264. function allocTexUnits( textures, n ) {
  10265. let r = arrayCacheI32[ n ];
  10266. if ( r === undefined ) {
  10267. r = new Int32Array( n );
  10268. arrayCacheI32[ n ] = r;
  10269. }
  10270. for ( let i = 0; i !== n; ++ i ) {
  10271. r[ i ] = textures.allocateTextureUnit();
  10272. }
  10273. return r;
  10274. }
  10275. // --- Setters ---
  10276. // Note: Defining these methods externally, because they come in a bunch
  10277. // and this way their names minify.
  10278. // Single scalar
  10279. function setValueV1f( gl, v ) {
  10280. const cache = this.cache;
  10281. if ( cache[ 0 ] === v ) return;
  10282. gl.uniform1f( this.addr, v );
  10283. cache[ 0 ] = v;
  10284. }
  10285. // Single float vector (from flat array or THREE.VectorN)
  10286. function setValueV2f( gl, v ) {
  10287. const cache = this.cache;
  10288. if ( v.x !== undefined ) {
  10289. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10290. gl.uniform2f( this.addr, v.x, v.y );
  10291. cache[ 0 ] = v.x;
  10292. cache[ 1 ] = v.y;
  10293. }
  10294. } else {
  10295. if ( arraysEqual( cache, v ) ) return;
  10296. gl.uniform2fv( this.addr, v );
  10297. copyArray( cache, v );
  10298. }
  10299. }
  10300. function setValueV3f( gl, v ) {
  10301. const cache = this.cache;
  10302. if ( v.x !== undefined ) {
  10303. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10304. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10305. cache[ 0 ] = v.x;
  10306. cache[ 1 ] = v.y;
  10307. cache[ 2 ] = v.z;
  10308. }
  10309. } else if ( v.r !== undefined ) {
  10310. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10311. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10312. cache[ 0 ] = v.r;
  10313. cache[ 1 ] = v.g;
  10314. cache[ 2 ] = v.b;
  10315. }
  10316. } else {
  10317. if ( arraysEqual( cache, v ) ) return;
  10318. gl.uniform3fv( this.addr, v );
  10319. copyArray( cache, v );
  10320. }
  10321. }
  10322. function setValueV4f( gl, v ) {
  10323. const cache = this.cache;
  10324. if ( v.x !== undefined ) {
  10325. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10326. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10327. cache[ 0 ] = v.x;
  10328. cache[ 1 ] = v.y;
  10329. cache[ 2 ] = v.z;
  10330. cache[ 3 ] = v.w;
  10331. }
  10332. } else {
  10333. if ( arraysEqual( cache, v ) ) return;
  10334. gl.uniform4fv( this.addr, v );
  10335. copyArray( cache, v );
  10336. }
  10337. }
  10338. // Single matrix (from flat array or MatrixN)
  10339. function setValueM2( gl, v ) {
  10340. const cache = this.cache;
  10341. const elements = v.elements;
  10342. if ( elements === undefined ) {
  10343. if ( arraysEqual( cache, v ) ) return;
  10344. gl.uniformMatrix2fv( this.addr, false, v );
  10345. copyArray( cache, v );
  10346. } else {
  10347. if ( arraysEqual( cache, elements ) ) return;
  10348. mat2array.set( elements );
  10349. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10350. copyArray( cache, elements );
  10351. }
  10352. }
  10353. function setValueM3( gl, v ) {
  10354. const cache = this.cache;
  10355. const elements = v.elements;
  10356. if ( elements === undefined ) {
  10357. if ( arraysEqual( cache, v ) ) return;
  10358. gl.uniformMatrix3fv( this.addr, false, v );
  10359. copyArray( cache, v );
  10360. } else {
  10361. if ( arraysEqual( cache, elements ) ) return;
  10362. mat3array.set( elements );
  10363. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10364. copyArray( cache, elements );
  10365. }
  10366. }
  10367. function setValueM4( gl, v ) {
  10368. const cache = this.cache;
  10369. const elements = v.elements;
  10370. if ( elements === undefined ) {
  10371. if ( arraysEqual( cache, v ) ) return;
  10372. gl.uniformMatrix4fv( this.addr, false, v );
  10373. copyArray( cache, v );
  10374. } else {
  10375. if ( arraysEqual( cache, elements ) ) return;
  10376. mat4array.set( elements );
  10377. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10378. copyArray( cache, elements );
  10379. }
  10380. }
  10381. // Single texture (2D / Cube)
  10382. function setValueT1( gl, v, textures ) {
  10383. const cache = this.cache;
  10384. const unit = textures.allocateTextureUnit();
  10385. if ( cache[ 0 ] !== unit ) {
  10386. gl.uniform1i( this.addr, unit );
  10387. cache[ 0 ] = unit;
  10388. }
  10389. textures.safeSetTexture2D( v || emptyTexture, unit );
  10390. }
  10391. function setValueT2DArray1( gl, v, textures ) {
  10392. const cache = this.cache;
  10393. const unit = textures.allocateTextureUnit();
  10394. if ( cache[ 0 ] !== unit ) {
  10395. gl.uniform1i( this.addr, unit );
  10396. cache[ 0 ] = unit;
  10397. }
  10398. textures.setTexture2DArray( v || emptyTexture2dArray, unit );
  10399. }
  10400. function setValueT3D1( gl, v, textures ) {
  10401. const cache = this.cache;
  10402. const unit = textures.allocateTextureUnit();
  10403. if ( cache[ 0 ] !== unit ) {
  10404. gl.uniform1i( this.addr, unit );
  10405. cache[ 0 ] = unit;
  10406. }
  10407. textures.setTexture3D( v || emptyTexture3d, unit );
  10408. }
  10409. function setValueT6( gl, v, textures ) {
  10410. const cache = this.cache;
  10411. const unit = textures.allocateTextureUnit();
  10412. if ( cache[ 0 ] !== unit ) {
  10413. gl.uniform1i( this.addr, unit );
  10414. cache[ 0 ] = unit;
  10415. }
  10416. textures.safeSetTextureCube( v || emptyCubeTexture, unit );
  10417. }
  10418. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10419. function setValueV1i( gl, v ) {
  10420. const cache = this.cache;
  10421. if ( cache[ 0 ] === v ) return;
  10422. gl.uniform1i( this.addr, v );
  10423. cache[ 0 ] = v;
  10424. }
  10425. function setValueV2i( gl, v ) {
  10426. const cache = this.cache;
  10427. if ( arraysEqual( cache, v ) ) return;
  10428. gl.uniform2iv( this.addr, v );
  10429. copyArray( cache, v );
  10430. }
  10431. function setValueV3i( gl, v ) {
  10432. const cache = this.cache;
  10433. if ( arraysEqual( cache, v ) ) return;
  10434. gl.uniform3iv( this.addr, v );
  10435. copyArray( cache, v );
  10436. }
  10437. function setValueV4i( gl, v ) {
  10438. const cache = this.cache;
  10439. if ( arraysEqual( cache, v ) ) return;
  10440. gl.uniform4iv( this.addr, v );
  10441. copyArray( cache, v );
  10442. }
  10443. // uint
  10444. function setValueV1ui( gl, v ) {
  10445. const cache = this.cache;
  10446. if ( cache[ 0 ] === v ) return;
  10447. gl.uniform1ui( this.addr, v );
  10448. cache[ 0 ] = v;
  10449. }
  10450. // Helper to pick the right setter for the singular case
  10451. function getSingularSetter( type ) {
  10452. switch ( type ) {
  10453. case 0x1406: return setValueV1f; // FLOAT
  10454. case 0x8b50: return setValueV2f; // _VEC2
  10455. case 0x8b51: return setValueV3f; // _VEC3
  10456. case 0x8b52: return setValueV4f; // _VEC4
  10457. case 0x8b5a: return setValueM2; // _MAT2
  10458. case 0x8b5b: return setValueM3; // _MAT3
  10459. case 0x8b5c: return setValueM4; // _MAT4
  10460. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10461. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10462. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10463. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10464. case 0x1405: return setValueV1ui; // UINT
  10465. case 0x8b5e: // SAMPLER_2D
  10466. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10467. case 0x8dca: // INT_SAMPLER_2D
  10468. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10469. case 0x8b62: // SAMPLER_2D_SHADOW
  10470. return setValueT1;
  10471. case 0x8b5f: // SAMPLER_3D
  10472. case 0x8dcb: // INT_SAMPLER_3D
  10473. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10474. return setValueT3D1;
  10475. case 0x8b60: // SAMPLER_CUBE
  10476. case 0x8dcc: // INT_SAMPLER_CUBE
  10477. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10478. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10479. return setValueT6;
  10480. case 0x8dc1: // SAMPLER_2D_ARRAY
  10481. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10482. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10483. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10484. return setValueT2DArray1;
  10485. }
  10486. }
  10487. // Array of scalars
  10488. function setValueV1fArray( gl, v ) {
  10489. gl.uniform1fv( this.addr, v );
  10490. }
  10491. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10492. function setValueV1iArray( gl, v ) {
  10493. gl.uniform1iv( this.addr, v );
  10494. }
  10495. function setValueV2iArray( gl, v ) {
  10496. gl.uniform2iv( this.addr, v );
  10497. }
  10498. function setValueV3iArray( gl, v ) {
  10499. gl.uniform3iv( this.addr, v );
  10500. }
  10501. function setValueV4iArray( gl, v ) {
  10502. gl.uniform4iv( this.addr, v );
  10503. }
  10504. // Array of vectors (flat or from THREE classes)
  10505. function setValueV2fArray( gl, v ) {
  10506. const data = flatten( v, this.size, 2 );
  10507. gl.uniform2fv( this.addr, data );
  10508. }
  10509. function setValueV3fArray( gl, v ) {
  10510. const data = flatten( v, this.size, 3 );
  10511. gl.uniform3fv( this.addr, data );
  10512. }
  10513. function setValueV4fArray( gl, v ) {
  10514. const data = flatten( v, this.size, 4 );
  10515. gl.uniform4fv( this.addr, data );
  10516. }
  10517. // Array of matrices (flat or from THREE clases)
  10518. function setValueM2Array( gl, v ) {
  10519. const data = flatten( v, this.size, 4 );
  10520. gl.uniformMatrix2fv( this.addr, false, data );
  10521. }
  10522. function setValueM3Array( gl, v ) {
  10523. const data = flatten( v, this.size, 9 );
  10524. gl.uniformMatrix3fv( this.addr, false, data );
  10525. }
  10526. function setValueM4Array( gl, v ) {
  10527. const data = flatten( v, this.size, 16 );
  10528. gl.uniformMatrix4fv( this.addr, false, data );
  10529. }
  10530. // Array of textures (2D / Cube)
  10531. function setValueT1Array( gl, v, textures ) {
  10532. const n = v.length;
  10533. const units = allocTexUnits( textures, n );
  10534. gl.uniform1iv( this.addr, units );
  10535. for ( let i = 0; i !== n; ++ i ) {
  10536. textures.safeSetTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10537. }
  10538. }
  10539. function setValueT6Array( 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.safeSetTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10545. }
  10546. }
  10547. // Helper to pick the right setter for a pure (bottom-level) array
  10548. function getPureArraySetter( type ) {
  10549. switch ( type ) {
  10550. case 0x1406: return setValueV1fArray; // FLOAT
  10551. case 0x8b50: return setValueV2fArray; // _VEC2
  10552. case 0x8b51: return setValueV3fArray; // _VEC3
  10553. case 0x8b52: return setValueV4fArray; // _VEC4
  10554. case 0x8b5a: return setValueM2Array; // _MAT2
  10555. case 0x8b5b: return setValueM3Array; // _MAT3
  10556. case 0x8b5c: return setValueM4Array; // _MAT4
  10557. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10558. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10559. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10560. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10561. case 0x8b5e: // SAMPLER_2D
  10562. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10563. case 0x8dca: // INT_SAMPLER_2D
  10564. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10565. case 0x8b62: // SAMPLER_2D_SHADOW
  10566. return setValueT1Array;
  10567. case 0x8b60: // SAMPLER_CUBE
  10568. case 0x8dcc: // INT_SAMPLER_CUBE
  10569. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10570. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10571. return setValueT6Array;
  10572. }
  10573. }
  10574. // --- Uniform Classes ---
  10575. function SingleUniform( id, activeInfo, addr ) {
  10576. this.id = id;
  10577. this.addr = addr;
  10578. this.cache = [];
  10579. this.setValue = getSingularSetter( activeInfo.type );
  10580. // this.path = activeInfo.name; // DEBUG
  10581. }
  10582. function PureArrayUniform( id, activeInfo, addr ) {
  10583. this.id = id;
  10584. this.addr = addr;
  10585. this.cache = [];
  10586. this.size = activeInfo.size;
  10587. this.setValue = getPureArraySetter( activeInfo.type );
  10588. // this.path = activeInfo.name; // DEBUG
  10589. }
  10590. PureArrayUniform.prototype.updateCache = function ( data ) {
  10591. const cache = this.cache;
  10592. if ( data instanceof Float32Array && cache.length !== data.length ) {
  10593. this.cache = new Float32Array( data.length );
  10594. }
  10595. copyArray( cache, data );
  10596. };
  10597. function StructuredUniform( id ) {
  10598. this.id = id;
  10599. this.seq = [];
  10600. this.map = {};
  10601. }
  10602. StructuredUniform.prototype.setValue = function ( gl, value, textures ) {
  10603. const seq = this.seq;
  10604. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10605. const u = seq[ i ];
  10606. u.setValue( gl, value[ u.id ], textures );
  10607. }
  10608. };
  10609. // --- Top-level ---
  10610. // Parser - builds up the property tree from the path strings
  10611. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  10612. // extracts
  10613. // - the identifier (member name or array index)
  10614. // - followed by an optional right bracket (found when array index)
  10615. // - followed by an optional left bracket or dot (type of subscript)
  10616. //
  10617. // Note: These portions can be read in a non-overlapping fashion and
  10618. // allow straightforward parsing of the hierarchy that WebGL encodes
  10619. // in the uniform names.
  10620. function addUniform( container, uniformObject ) {
  10621. container.seq.push( uniformObject );
  10622. container.map[ uniformObject.id ] = uniformObject;
  10623. }
  10624. function parseUniform( activeInfo, addr, container ) {
  10625. const path = activeInfo.name,
  10626. pathLength = path.length;
  10627. // reset RegExp object, because of the early exit of a previous run
  10628. RePathPart.lastIndex = 0;
  10629. while ( true ) {
  10630. const match = RePathPart.exec( path ),
  10631. matchEnd = RePathPart.lastIndex;
  10632. let id = match[ 1 ];
  10633. const idIsIndex = match[ 2 ] === ']',
  10634. subscript = match[ 3 ];
  10635. if ( idIsIndex ) id = id | 0; // convert to integer
  10636. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  10637. // bare name or "pure" bottom-level array "[0]" suffix
  10638. addUniform( container, subscript === undefined ?
  10639. new SingleUniform( id, activeInfo, addr ) :
  10640. new PureArrayUniform( id, activeInfo, addr ) );
  10641. break;
  10642. } else {
  10643. // step into inner node / create it in case it doesn't exist
  10644. const map = container.map;
  10645. let next = map[ id ];
  10646. if ( next === undefined ) {
  10647. next = new StructuredUniform( id );
  10648. addUniform( container, next );
  10649. }
  10650. container = next;
  10651. }
  10652. }
  10653. }
  10654. // Root Container
  10655. function WebGLUniforms( gl, program ) {
  10656. this.seq = [];
  10657. this.map = {};
  10658. const n = gl.getProgramParameter( program, 35718 );
  10659. for ( let i = 0; i < n; ++ i ) {
  10660. const info = gl.getActiveUniform( program, i ),
  10661. addr = gl.getUniformLocation( program, info.name );
  10662. parseUniform( info, addr, this );
  10663. }
  10664. }
  10665. WebGLUniforms.prototype.setValue = function ( gl, name, value, textures ) {
  10666. const u = this.map[ name ];
  10667. if ( u !== undefined ) u.setValue( gl, value, textures );
  10668. };
  10669. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  10670. const v = object[ name ];
  10671. if ( v !== undefined ) this.setValue( gl, name, v );
  10672. };
  10673. // Static interface
  10674. WebGLUniforms.upload = function ( gl, seq, values, textures ) {
  10675. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10676. const u = seq[ i ],
  10677. v = values[ u.id ];
  10678. if ( v.needsUpdate !== false ) {
  10679. // note: always updating when .needsUpdate is undefined
  10680. u.setValue( gl, v.value, textures );
  10681. }
  10682. }
  10683. };
  10684. WebGLUniforms.seqWithValue = function ( seq, values ) {
  10685. const r = [];
  10686. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10687. const u = seq[ i ];
  10688. if ( u.id in values ) r.push( u );
  10689. }
  10690. return r;
  10691. };
  10692. function WebGLShader( gl, type, string ) {
  10693. const shader = gl.createShader( type );
  10694. gl.shaderSource( shader, string );
  10695. gl.compileShader( shader );
  10696. return shader;
  10697. }
  10698. let programIdCount = 0;
  10699. function addLineNumbers( string ) {
  10700. const lines = string.split( '\n' );
  10701. for ( let i = 0; i < lines.length; i ++ ) {
  10702. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  10703. }
  10704. return lines.join( '\n' );
  10705. }
  10706. function getEncodingComponents( encoding ) {
  10707. switch ( encoding ) {
  10708. case LinearEncoding:
  10709. return [ 'Linear', '( value )' ];
  10710. case sRGBEncoding:
  10711. return [ 'sRGB', '( value )' ];
  10712. case RGBEEncoding:
  10713. return [ 'RGBE', '( value )' ];
  10714. case RGBM7Encoding:
  10715. return [ 'RGBM', '( value, 7.0 )' ];
  10716. case RGBM16Encoding:
  10717. return [ 'RGBM', '( value, 16.0 )' ];
  10718. case RGBDEncoding:
  10719. return [ 'RGBD', '( value, 256.0 )' ];
  10720. case GammaEncoding:
  10721. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  10722. case LogLuvEncoding:
  10723. return [ 'LogLuv', '( value )' ];
  10724. default:
  10725. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  10726. return [ 'Linear', '( value )' ];
  10727. }
  10728. }
  10729. function getShaderErrors( gl, shader, type ) {
  10730. const status = gl.getShaderParameter( shader, 35713 );
  10731. const log = gl.getShaderInfoLog( shader ).trim();
  10732. if ( status && log === '' ) return '';
  10733. // --enable-privileged-webgl-extension
  10734. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10735. const source = gl.getShaderSource( shader );
  10736. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers( source );
  10737. }
  10738. function getTexelDecodingFunction( functionName, encoding ) {
  10739. const components = getEncodingComponents( encoding );
  10740. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  10741. }
  10742. function getTexelEncodingFunction( functionName, encoding ) {
  10743. const components = getEncodingComponents( encoding );
  10744. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  10745. }
  10746. function getToneMappingFunction( functionName, toneMapping ) {
  10747. let toneMappingName;
  10748. switch ( toneMapping ) {
  10749. case LinearToneMapping:
  10750. toneMappingName = 'Linear';
  10751. break;
  10752. case ReinhardToneMapping:
  10753. toneMappingName = 'Reinhard';
  10754. break;
  10755. case CineonToneMapping:
  10756. toneMappingName = 'OptimizedCineon';
  10757. break;
  10758. case ACESFilmicToneMapping:
  10759. toneMappingName = 'ACESFilmic';
  10760. break;
  10761. case CustomToneMapping:
  10762. toneMappingName = 'Custom';
  10763. break;
  10764. default:
  10765. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  10766. toneMappingName = 'Linear';
  10767. }
  10768. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10769. }
  10770. function generateExtensions( parameters ) {
  10771. const chunks = [
  10772. ( parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10773. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  10774. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10775. ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10776. ];
  10777. return chunks.filter( filterEmptyLine ).join( '\n' );
  10778. }
  10779. function generateDefines( defines ) {
  10780. const chunks = [];
  10781. for ( const name in defines ) {
  10782. const value = defines[ name ];
  10783. if ( value === false ) continue;
  10784. chunks.push( '#define ' + name + ' ' + value );
  10785. }
  10786. return chunks.join( '\n' );
  10787. }
  10788. function fetchAttributeLocations( gl, program ) {
  10789. const attributes = {};
  10790. const n = gl.getProgramParameter( program, 35721 );
  10791. for ( let i = 0; i < n; i ++ ) {
  10792. const info = gl.getActiveAttrib( program, i );
  10793. const name = info.name;
  10794. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10795. attributes[ name ] = gl.getAttribLocation( program, name );
  10796. }
  10797. return attributes;
  10798. }
  10799. function filterEmptyLine( string ) {
  10800. return string !== '';
  10801. }
  10802. function replaceLightNums( string, parameters ) {
  10803. return string
  10804. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10805. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10806. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10807. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10808. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  10809. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  10810. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  10811. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  10812. }
  10813. function replaceClippingPlaneNums( string, parameters ) {
  10814. return string
  10815. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  10816. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  10817. }
  10818. // Resolve Includes
  10819. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10820. function resolveIncludes( string ) {
  10821. return string.replace( includePattern, includeReplacer );
  10822. }
  10823. function includeReplacer( match, include ) {
  10824. const string = ShaderChunk[ include ];
  10825. if ( string === undefined ) {
  10826. throw new Error( 'Can not resolve #include <' + include + '>' );
  10827. }
  10828. return resolveIncludes( string );
  10829. }
  10830. // Unroll Loops
  10831. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  10832. 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;
  10833. function unrollLoops( string ) {
  10834. return string
  10835. .replace( unrollLoopPattern, loopReplacer )
  10836. .replace( deprecatedUnrollLoopPattern, deprecatedLoopReplacer );
  10837. }
  10838. function deprecatedLoopReplacer( match, start, end, snippet ) {
  10839. console.warn( 'WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.' );
  10840. return loopReplacer( match, start, end, snippet );
  10841. }
  10842. function loopReplacer( match, start, end, snippet ) {
  10843. let string = '';
  10844. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10845. string += snippet
  10846. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  10847. .replace( /UNROLLED_LOOP_INDEX/g, i );
  10848. }
  10849. return string;
  10850. }
  10851. //
  10852. function generatePrecision( parameters ) {
  10853. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  10854. if ( parameters.precision === 'highp' ) {
  10855. precisionstring += '\n#define HIGH_PRECISION';
  10856. } else if ( parameters.precision === 'mediump' ) {
  10857. precisionstring += '\n#define MEDIUM_PRECISION';
  10858. } else if ( parameters.precision === 'lowp' ) {
  10859. precisionstring += '\n#define LOW_PRECISION';
  10860. }
  10861. return precisionstring;
  10862. }
  10863. function generateShadowMapTypeDefine( parameters ) {
  10864. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10865. if ( parameters.shadowMapType === PCFShadowMap ) {
  10866. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10867. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10868. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10869. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  10870. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  10871. }
  10872. return shadowMapTypeDefine;
  10873. }
  10874. function generateEnvMapTypeDefine( parameters ) {
  10875. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10876. if ( parameters.envMap ) {
  10877. switch ( parameters.envMapMode ) {
  10878. case CubeReflectionMapping:
  10879. case CubeRefractionMapping:
  10880. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10881. break;
  10882. case CubeUVReflectionMapping:
  10883. case CubeUVRefractionMapping:
  10884. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10885. break;
  10886. }
  10887. }
  10888. return envMapTypeDefine;
  10889. }
  10890. function generateEnvMapModeDefine( parameters ) {
  10891. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10892. if ( parameters.envMap ) {
  10893. switch ( parameters.envMapMode ) {
  10894. case CubeRefractionMapping:
  10895. case CubeUVRefractionMapping:
  10896. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10897. break;
  10898. }
  10899. }
  10900. return envMapModeDefine;
  10901. }
  10902. function generateEnvMapBlendingDefine( parameters ) {
  10903. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  10904. if ( parameters.envMap ) {
  10905. switch ( parameters.combine ) {
  10906. case MultiplyOperation:
  10907. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  10908. break;
  10909. case MixOperation:
  10910. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  10911. break;
  10912. case AddOperation:
  10913. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  10914. break;
  10915. }
  10916. }
  10917. return envMapBlendingDefine;
  10918. }
  10919. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  10920. const gl = renderer.getContext();
  10921. const defines = parameters.defines;
  10922. let vertexShader = parameters.vertexShader;
  10923. let fragmentShader = parameters.fragmentShader;
  10924. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  10925. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  10926. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  10927. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  10928. const gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  10929. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  10930. const customDefines = generateDefines( defines );
  10931. const program = gl.createProgram();
  10932. let prefixVertex, prefixFragment;
  10933. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  10934. if ( parameters.isRawShaderMaterial ) {
  10935. prefixVertex = [
  10936. customDefines
  10937. ].filter( filterEmptyLine ).join( '\n' );
  10938. if ( prefixVertex.length > 0 ) {
  10939. prefixVertex += '\n';
  10940. }
  10941. prefixFragment = [
  10942. customExtensions,
  10943. customDefines
  10944. ].filter( filterEmptyLine ).join( '\n' );
  10945. if ( prefixFragment.length > 0 ) {
  10946. prefixFragment += '\n';
  10947. }
  10948. } else {
  10949. prefixVertex = [
  10950. generatePrecision( parameters ),
  10951. '#define SHADER_NAME ' + parameters.shaderName,
  10952. customDefines,
  10953. parameters.instancing ? '#define USE_INSTANCING' : '',
  10954. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  10955. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  10956. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  10957. '#define MAX_BONES ' + parameters.maxBones,
  10958. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  10959. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  10960. parameters.map ? '#define USE_MAP' : '',
  10961. parameters.envMap ? '#define USE_ENVMAP' : '',
  10962. parameters.envMap ? '#define ' + envMapModeDefine : '',
  10963. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  10964. parameters.aoMap ? '#define USE_AOMAP' : '',
  10965. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  10966. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  10967. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  10968. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  10969. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  10970. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  10971. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  10972. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  10973. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  10974. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  10975. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  10976. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  10977. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  10978. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  10979. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  10980. parameters.vertexColors ? '#define USE_COLOR' : '',
  10981. parameters.vertexUvs ? '#define USE_UV' : '',
  10982. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  10983. parameters.flatShading ? '#define FLAT_SHADED' : '',
  10984. parameters.skinning ? '#define USE_SKINNING' : '',
  10985. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  10986. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  10987. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  10988. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  10989. parameters.flipSided ? '#define FLIP_SIDED' : '',
  10990. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  10991. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  10992. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  10993. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  10994. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  10995. 'uniform mat4 modelMatrix;',
  10996. 'uniform mat4 modelViewMatrix;',
  10997. 'uniform mat4 projectionMatrix;',
  10998. 'uniform mat4 viewMatrix;',
  10999. 'uniform mat3 normalMatrix;',
  11000. 'uniform vec3 cameraPosition;',
  11001. 'uniform bool isOrthographic;',
  11002. '#ifdef USE_INSTANCING',
  11003. ' attribute mat4 instanceMatrix;',
  11004. '#endif',
  11005. '#ifdef USE_INSTANCING_COLOR',
  11006. ' attribute vec3 instanceColor;',
  11007. '#endif',
  11008. 'attribute vec3 position;',
  11009. 'attribute vec3 normal;',
  11010. 'attribute vec2 uv;',
  11011. '#ifdef USE_TANGENT',
  11012. ' attribute vec4 tangent;',
  11013. '#endif',
  11014. '#ifdef USE_COLOR',
  11015. ' attribute vec3 color;',
  11016. '#endif',
  11017. '#ifdef USE_MORPHTARGETS',
  11018. ' attribute vec3 morphTarget0;',
  11019. ' attribute vec3 morphTarget1;',
  11020. ' attribute vec3 morphTarget2;',
  11021. ' attribute vec3 morphTarget3;',
  11022. ' #ifdef USE_MORPHNORMALS',
  11023. ' attribute vec3 morphNormal0;',
  11024. ' attribute vec3 morphNormal1;',
  11025. ' attribute vec3 morphNormal2;',
  11026. ' attribute vec3 morphNormal3;',
  11027. ' #else',
  11028. ' attribute vec3 morphTarget4;',
  11029. ' attribute vec3 morphTarget5;',
  11030. ' attribute vec3 morphTarget6;',
  11031. ' attribute vec3 morphTarget7;',
  11032. ' #endif',
  11033. '#endif',
  11034. '#ifdef USE_SKINNING',
  11035. ' attribute vec4 skinIndex;',
  11036. ' attribute vec4 skinWeight;',
  11037. '#endif',
  11038. '\n'
  11039. ].filter( filterEmptyLine ).join( '\n' );
  11040. prefixFragment = [
  11041. customExtensions,
  11042. generatePrecision( parameters ),
  11043. '#define SHADER_NAME ' + parameters.shaderName,
  11044. customDefines,
  11045. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + ( parameters.alphaTest % 1 ? '' : '.0' ) : '', // add '.0' if integer
  11046. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  11047. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11048. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11049. parameters.map ? '#define USE_MAP' : '',
  11050. parameters.matcap ? '#define USE_MATCAP' : '',
  11051. parameters.envMap ? '#define USE_ENVMAP' : '',
  11052. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11053. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11054. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11055. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11056. parameters.aoMap ? '#define USE_AOMAP' : '',
  11057. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11058. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11059. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11060. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11061. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11062. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11063. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11064. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11065. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11066. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11067. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11068. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11069. parameters.sheen ? '#define USE_SHEEN' : '',
  11070. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11071. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11072. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11073. parameters.vertexUvs ? '#define USE_UV' : '',
  11074. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11075. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11076. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11077. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11078. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11079. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11080. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11081. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11082. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  11083. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11084. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11085. ( ( parameters.extensionShaderTextureLOD || parameters.envMap ) && parameters.rendererExtensionShaderTextureLod ) ? '#define TEXTURE_LOD_EXT' : '',
  11086. 'uniform mat4 viewMatrix;',
  11087. 'uniform vec3 cameraPosition;',
  11088. 'uniform bool isOrthographic;',
  11089. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11090. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11091. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11092. parameters.dithering ? '#define DITHERING' : '',
  11093. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11094. parameters.map ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  11095. parameters.matcap ? getTexelDecodingFunction( 'matcapTexelToLinear', parameters.matcapEncoding ) : '',
  11096. parameters.envMap ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  11097. parameters.emissiveMap ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  11098. parameters.lightMap ? getTexelDecodingFunction( 'lightMapTexelToLinear', parameters.lightMapEncoding ) : '',
  11099. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11100. parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11101. '\n'
  11102. ].filter( filterEmptyLine ).join( '\n' );
  11103. }
  11104. vertexShader = resolveIncludes( vertexShader );
  11105. vertexShader = replaceLightNums( vertexShader, parameters );
  11106. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11107. fragmentShader = resolveIncludes( fragmentShader );
  11108. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11109. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11110. vertexShader = unrollLoops( vertexShader );
  11111. fragmentShader = unrollLoops( fragmentShader );
  11112. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11113. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11114. versionString = '#version 300 es\n';
  11115. prefixVertex = [
  11116. '#define attribute in',
  11117. '#define varying out',
  11118. '#define texture2D texture'
  11119. ].join( '\n' ) + '\n' + prefixVertex;
  11120. prefixFragment = [
  11121. '#define varying in',
  11122. ( parameters.glslVersion === GLSL3 ) ? '' : 'out highp vec4 pc_fragColor;',
  11123. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11124. '#define gl_FragDepthEXT gl_FragDepth',
  11125. '#define texture2D texture',
  11126. '#define textureCube texture',
  11127. '#define texture2DProj textureProj',
  11128. '#define texture2DLodEXT textureLod',
  11129. '#define texture2DProjLodEXT textureProjLod',
  11130. '#define textureCubeLodEXT textureLod',
  11131. '#define texture2DGradEXT textureGrad',
  11132. '#define texture2DProjGradEXT textureProjGrad',
  11133. '#define textureCubeGradEXT textureGrad'
  11134. ].join( '\n' ) + '\n' + prefixFragment;
  11135. }
  11136. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11137. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11138. // console.log( '*VERTEX*', vertexGlsl );
  11139. // console.log( '*FRAGMENT*', fragmentGlsl );
  11140. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  11141. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  11142. gl.attachShader( program, glVertexShader );
  11143. gl.attachShader( program, glFragmentShader );
  11144. // Force a particular attribute to index 0.
  11145. if ( parameters.index0AttributeName !== undefined ) {
  11146. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11147. } else if ( parameters.morphTargets === true ) {
  11148. // programs with morphTargets displace position out of attribute 0
  11149. gl.bindAttribLocation( program, 0, 'position' );
  11150. }
  11151. gl.linkProgram( program );
  11152. // check for link errors
  11153. if ( renderer.debug.checkShaderErrors ) {
  11154. const programLog = gl.getProgramInfoLog( program ).trim();
  11155. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11156. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11157. let runnable = true;
  11158. let haveDiagnostics = true;
  11159. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  11160. runnable = false;
  11161. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11162. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11163. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter( program, 35715 ), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors );
  11164. //add:
  11165. if(fragmentErrors){
  11166. console.log(fragmentGlsl.split("\n").map((a, i) => `${i + 1}`.padEnd(5) + a).join("\n") );
  11167. }else {
  11168. console.log(vertexGlsl.split("\n").map((a, i) => `${i + 1}`.padEnd(5) + a).join("\n") );
  11169. }
  11170. } else if ( programLog !== '' ) {
  11171. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  11172. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11173. haveDiagnostics = false;
  11174. }
  11175. if ( haveDiagnostics ) {
  11176. this.diagnostics = {
  11177. runnable: runnable,
  11178. programLog: programLog,
  11179. vertexShader: {
  11180. log: vertexLog,
  11181. prefix: prefixVertex
  11182. },
  11183. fragmentShader: {
  11184. log: fragmentLog,
  11185. prefix: prefixFragment
  11186. }
  11187. };
  11188. }
  11189. }
  11190. // Clean up
  11191. // Crashes in iOS9 and iOS10. #18402
  11192. // gl.detachShader( program, glVertexShader );
  11193. // gl.detachShader( program, glFragmentShader );
  11194. gl.deleteShader( glVertexShader );
  11195. gl.deleteShader( glFragmentShader );
  11196. // set up caching for uniform locations
  11197. let cachedUniforms;
  11198. this.getUniforms = function () {
  11199. if ( cachedUniforms === undefined ) {
  11200. cachedUniforms = new WebGLUniforms( gl, program );
  11201. }
  11202. return cachedUniforms;
  11203. };
  11204. // set up caching for attribute locations
  11205. let cachedAttributes;
  11206. this.getAttributes = function () {
  11207. if ( cachedAttributes === undefined ) {
  11208. cachedAttributes = fetchAttributeLocations( gl, program );
  11209. }
  11210. return cachedAttributes;
  11211. };
  11212. // free resource
  11213. this.destroy = function () {
  11214. bindingStates.releaseStatesOfProgram( this );
  11215. gl.deleteProgram( program );
  11216. this.program = undefined;
  11217. };
  11218. //
  11219. this.name = parameters.shaderName;
  11220. this.id = programIdCount ++;
  11221. this.cacheKey = cacheKey;
  11222. this.usedTimes = 1;
  11223. this.program = program;
  11224. this.vertexShader = glVertexShader;
  11225. this.fragmentShader = glFragmentShader;
  11226. return this;
  11227. }
  11228. function WebGLPrograms( renderer, cubemaps, extensions, capabilities, bindingStates, clipping ) {
  11229. const programs = [];
  11230. const isWebGL2 = capabilities.isWebGL2;
  11231. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11232. const floatVertexTextures = capabilities.floatVertexTextures;
  11233. const maxVertexUniforms = capabilities.maxVertexUniforms;
  11234. const vertexTextures = capabilities.vertexTextures;
  11235. let precision = capabilities.precision;
  11236. const shaderIDs = {
  11237. MeshDepthMaterial: 'depth',
  11238. MeshDistanceMaterial: 'distanceRGBA',
  11239. MeshNormalMaterial: 'normal',
  11240. MeshBasicMaterial: 'basic',
  11241. MeshLambertMaterial: 'lambert',
  11242. MeshPhongMaterial: 'phong',
  11243. MeshToonMaterial: 'toon',
  11244. MeshStandardMaterial: 'physical',
  11245. MeshPhysicalMaterial: 'physical',
  11246. MeshMatcapMaterial: 'matcap',
  11247. LineBasicMaterial: 'basic',
  11248. LineDashedMaterial: 'dashed',
  11249. PointsMaterial: 'points',
  11250. ShadowMaterial: 'shadow',
  11251. SpriteMaterial: 'sprite'
  11252. };
  11253. const parameterNames = [
  11254. 'precision', 'isWebGL2', 'supportsVertexTextures', 'outputEncoding', 'instancing', 'instancingColor',
  11255. 'map', 'mapEncoding', 'matcap', 'matcapEncoding', 'envMap', 'envMapMode', 'envMapEncoding', 'envMapCubeUV',
  11256. 'lightMap', 'lightMapEncoding', 'aoMap', 'emissiveMap', 'emissiveMapEncoding', 'bumpMap', 'normalMap', 'objectSpaceNormalMap', 'tangentSpaceNormalMap', 'clearcoatMap', 'clearcoatRoughnessMap', 'clearcoatNormalMap', 'displacementMap', 'specularMap',
  11257. 'roughnessMap', 'metalnessMap', 'gradientMap',
  11258. 'alphaMap', 'combine', 'vertexColors', 'vertexTangents', 'vertexUvs', 'uvsVertexOnly', 'fog', 'useFog', 'fogExp2',
  11259. 'flatShading', 'sizeAttenuation', 'logarithmicDepthBuffer', 'skinning',
  11260. 'maxBones', 'useVertexTexture', 'morphTargets', 'morphNormals',
  11261. 'maxMorphTargets', 'maxMorphNormals', 'premultipliedAlpha',
  11262. 'numDirLights', 'numPointLights', 'numSpotLights', 'numHemiLights', 'numRectAreaLights',
  11263. 'numDirLightShadows', 'numPointLightShadows', 'numSpotLightShadows',
  11264. 'shadowMapEnabled', 'shadowMapType', 'toneMapping', 'physicallyCorrectLights',
  11265. 'alphaTest', 'doubleSided', 'flipSided', 'numClippingPlanes', 'numClipIntersection', 'depthPacking', 'dithering',
  11266. 'sheen', 'transmissionMap'
  11267. ];
  11268. function getMaxBones( object ) {
  11269. const skeleton = object.skeleton;
  11270. const bones = skeleton.bones;
  11271. if ( floatVertexTextures ) {
  11272. return 1024;
  11273. } else {
  11274. // default for when object is not specified
  11275. // ( for example when prebuilding shader to be used with multiple objects )
  11276. //
  11277. // - leave some extra space for other uniforms
  11278. // - limit here is ANGLE's 254 max uniform vectors
  11279. // (up to 54 should be safe)
  11280. const nVertexUniforms = maxVertexUniforms;
  11281. const nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  11282. const maxBones = Math.min( nVertexMatrices, bones.length );
  11283. if ( maxBones < bones.length ) {
  11284. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  11285. return 0;
  11286. }
  11287. return maxBones;
  11288. }
  11289. }
  11290. function getTextureEncodingFromMap( map ) {
  11291. let encoding;
  11292. if ( map && map.isTexture ) {
  11293. encoding = map.encoding;
  11294. } else if ( map && map.isWebGLRenderTarget ) {
  11295. console.warn( 'THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.' );
  11296. encoding = map.texture.encoding;
  11297. } else {
  11298. encoding = LinearEncoding;
  11299. }
  11300. return encoding;
  11301. }
  11302. function getParameters( material, lights, shadows, scene, object ) {
  11303. const fog = scene.fog;
  11304. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11305. const envMap = cubemaps.get( material.envMap || environment );
  11306. const shaderID = shaderIDs[ material.type ];
  11307. // heuristics to create shader parameters according to lights in the scene
  11308. // (not to blow over maxLights budget)
  11309. const maxBones = object.isSkinnedMesh ? getMaxBones( object ) : 0;
  11310. if ( material.precision !== null ) {
  11311. precision = capabilities.getMaxPrecision( material.precision );
  11312. if ( precision !== material.precision ) {
  11313. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11314. }
  11315. }
  11316. let vertexShader, fragmentShader;
  11317. if ( shaderID ) {
  11318. const shader = ShaderLib[ shaderID ];
  11319. vertexShader = shader.vertexShader;
  11320. fragmentShader = shader.fragmentShader;
  11321. } else {
  11322. vertexShader = material.vertexShader;
  11323. fragmentShader = material.fragmentShader;
  11324. }
  11325. const currentRenderTarget = renderer.getRenderTarget();
  11326. const parameters = {
  11327. isWebGL2: isWebGL2,
  11328. shaderID: shaderID,
  11329. shaderName: material.type,
  11330. vertexShader: vertexShader,
  11331. fragmentShader: fragmentShader,
  11332. defines: material.defines,
  11333. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11334. glslVersion: material.glslVersion,
  11335. precision: precision,
  11336. instancing: object.isInstancedMesh === true,
  11337. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11338. supportsVertexTextures: vertexTextures,
  11339. outputEncoding: ( currentRenderTarget !== null ) ? getTextureEncodingFromMap( currentRenderTarget.texture ) : renderer.outputEncoding,
  11340. map: !! material.map,
  11341. mapEncoding: getTextureEncodingFromMap( material.map ),
  11342. matcap: !! material.matcap,
  11343. matcapEncoding: getTextureEncodingFromMap( material.matcap ),
  11344. envMap: !! envMap,
  11345. envMapMode: envMap && envMap.mapping,
  11346. envMapEncoding: getTextureEncodingFromMap( envMap ),
  11347. envMapCubeUV: ( !! envMap ) && ( ( envMap.mapping === CubeUVReflectionMapping ) || ( envMap.mapping === CubeUVRefractionMapping ) ),
  11348. lightMap: !! material.lightMap,
  11349. lightMapEncoding: getTextureEncodingFromMap( material.lightMap ),
  11350. aoMap: !! material.aoMap,
  11351. emissiveMap: !! material.emissiveMap,
  11352. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap ),
  11353. bumpMap: !! material.bumpMap,
  11354. normalMap: !! material.normalMap,
  11355. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11356. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11357. clearcoatMap: !! material.clearcoatMap,
  11358. clearcoatRoughnessMap: !! material.clearcoatRoughnessMap,
  11359. clearcoatNormalMap: !! material.clearcoatNormalMap,
  11360. displacementMap: !! material.displacementMap,
  11361. roughnessMap: !! material.roughnessMap,
  11362. metalnessMap: !! material.metalnessMap,
  11363. specularMap: !! material.specularMap,
  11364. alphaMap: !! material.alphaMap,
  11365. gradientMap: !! material.gradientMap,
  11366. sheen: !! material.sheen,
  11367. transmissionMap: !! material.transmissionMap,
  11368. combine: material.combine,
  11369. vertexTangents: ( material.normalMap && material.vertexTangents ),
  11370. vertexColors: material.vertexColors,
  11371. 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,
  11372. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.transmissionMap ) && !! material.displacementMap,
  11373. fog: !! fog,
  11374. useFog: material.fog,
  11375. fogExp2: ( fog && fog.isFogExp2 ),
  11376. flatShading: material.flatShading,
  11377. sizeAttenuation: material.sizeAttenuation,
  11378. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11379. skinning: material.skinning && maxBones > 0,
  11380. maxBones: maxBones,
  11381. useVertexTexture: floatVertexTextures,
  11382. morphTargets: material.morphTargets,
  11383. morphNormals: material.morphNormals,
  11384. maxMorphTargets: renderer.maxMorphTargets,
  11385. maxMorphNormals: renderer.maxMorphNormals,
  11386. numDirLights: lights.directional.length,
  11387. numPointLights: lights.point.length,
  11388. numSpotLights: lights.spot.length,
  11389. numRectAreaLights: lights.rectArea.length,
  11390. numHemiLights: lights.hemi.length,
  11391. numDirLightShadows: lights.directionalShadowMap.length,
  11392. numPointLightShadows: lights.pointShadowMap.length,
  11393. numSpotLightShadows: lights.spotShadowMap.length,
  11394. numClippingPlanes: clipping.numPlanes,
  11395. numClipIntersection: clipping.numIntersection,
  11396. dithering: material.dithering,
  11397. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11398. shadowMapType: renderer.shadowMap.type,
  11399. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11400. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11401. premultipliedAlpha: material.premultipliedAlpha,
  11402. alphaTest: material.alphaTest,
  11403. doubleSided: material.side === DoubleSide,
  11404. flipSided: material.side === BackSide,
  11405. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false,
  11406. index0AttributeName: material.index0AttributeName,
  11407. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11408. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11409. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11410. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11411. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11412. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11413. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11414. customProgramCacheKey: material.customProgramCacheKey()
  11415. };
  11416. return parameters;
  11417. }
  11418. function getProgramCacheKey( parameters ) {
  11419. const array = [];
  11420. if ( parameters.shaderID ) {
  11421. array.push( parameters.shaderID );
  11422. } else {
  11423. array.push( parameters.fragmentShader );
  11424. array.push( parameters.vertexShader );
  11425. }
  11426. if ( parameters.defines !== undefined ) {
  11427. for ( const name in parameters.defines ) {
  11428. array.push( name );
  11429. array.push( parameters.defines[ name ] );
  11430. }
  11431. }
  11432. if ( parameters.isRawShaderMaterial === false ) {
  11433. for ( let i = 0; i < parameterNames.length; i ++ ) {
  11434. array.push( parameters[ parameterNames[ i ] ] );
  11435. }
  11436. array.push( renderer.outputEncoding );
  11437. array.push( renderer.gammaFactor );
  11438. }
  11439. array.push( parameters.customProgramCacheKey );
  11440. return array.join();
  11441. }
  11442. function getUniforms( material ) {
  11443. const shaderID = shaderIDs[ material.type ];
  11444. let uniforms;
  11445. if ( shaderID ) {
  11446. const shader = ShaderLib[ shaderID ];
  11447. uniforms = UniformsUtils.clone( shader.uniforms );
  11448. } else {
  11449. uniforms = material.uniforms;
  11450. }
  11451. return uniforms;
  11452. }
  11453. function acquireProgram( parameters, cacheKey ) {
  11454. let program;
  11455. // Check if code has been already compiled
  11456. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  11457. const preexistingProgram = programs[ p ];
  11458. if ( preexistingProgram.cacheKey === cacheKey ) {
  11459. program = preexistingProgram;
  11460. ++ program.usedTimes;
  11461. break;
  11462. }
  11463. }
  11464. if ( program === undefined ) {
  11465. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  11466. programs.push( program );
  11467. }
  11468. return program;
  11469. }
  11470. function releaseProgram( program ) {
  11471. if ( -- program.usedTimes === 0 ) {
  11472. // Remove from unordered set
  11473. const i = programs.indexOf( program );
  11474. programs[ i ] = programs[ programs.length - 1 ];
  11475. programs.pop();
  11476. // Free WebGL resources
  11477. program.destroy();
  11478. }
  11479. }
  11480. return {
  11481. getParameters: getParameters,
  11482. getProgramCacheKey: getProgramCacheKey,
  11483. getUniforms: getUniforms,
  11484. acquireProgram: acquireProgram,
  11485. releaseProgram: releaseProgram,
  11486. // Exposed for resource monitoring & error feedback via renderer.info:
  11487. programs: programs
  11488. };
  11489. }
  11490. function WebGLProperties() {
  11491. let properties = new WeakMap();
  11492. function get( object ) {
  11493. let map = properties.get( object );
  11494. if ( map === undefined ) {
  11495. map = {};
  11496. properties.set( object, map );
  11497. }
  11498. return map;
  11499. }
  11500. function remove( object ) {
  11501. properties.delete( object );
  11502. }
  11503. function update( object, key, value ) {
  11504. properties.get( object )[ key ] = value;
  11505. }
  11506. function dispose() {
  11507. properties = new WeakMap();
  11508. }
  11509. return {
  11510. get: get,
  11511. remove: remove,
  11512. update: update,
  11513. dispose: dispose
  11514. };
  11515. }
  11516. function painterSortStable( a, b ) {
  11517. if ( a.groupOrder !== b.groupOrder ) {
  11518. return a.groupOrder - b.groupOrder;
  11519. } else if ( a.renderOrder !== b.renderOrder ) {
  11520. return a.renderOrder - b.renderOrder;
  11521. } else if ( a.program !== b.program ) {
  11522. return a.program.id - b.program.id;
  11523. } else if ( a.material.id !== b.material.id ) {
  11524. return a.material.id - b.material.id;
  11525. } else if ( a.z !== b.z ) {
  11526. return a.z - b.z;
  11527. } else {
  11528. return a.id - b.id;
  11529. }
  11530. }
  11531. function reversePainterSortStable( a, b ) {
  11532. if ( a.groupOrder !== b.groupOrder ) {
  11533. return a.groupOrder - b.groupOrder;
  11534. } else if ( a.renderOrder !== b.renderOrder ) {
  11535. return a.renderOrder - b.renderOrder;
  11536. } else if ( a.z !== b.z ) {
  11537. return b.z - a.z;
  11538. } else {
  11539. return a.id - b.id;
  11540. }
  11541. }
  11542. function WebGLRenderList( properties ) {
  11543. const renderItems = [];
  11544. let renderItemsIndex = 0;
  11545. const opaque = [];
  11546. const transparent = [];
  11547. const defaultProgram = { id: - 1 };
  11548. function init() {
  11549. renderItemsIndex = 0;
  11550. opaque.length = 0;
  11551. transparent.length = 0;
  11552. }
  11553. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  11554. let renderItem = renderItems[ renderItemsIndex ];
  11555. const materialProperties = properties.get( material );
  11556. if ( renderItem === undefined ) {
  11557. renderItem = {
  11558. id: object.id,
  11559. object: object,
  11560. geometry: geometry,
  11561. material: material,
  11562. program: materialProperties.program || defaultProgram,
  11563. groupOrder: groupOrder,
  11564. renderOrder: object.renderOrder,
  11565. z: z,
  11566. group: group
  11567. };
  11568. renderItems[ renderItemsIndex ] = renderItem;
  11569. } else {
  11570. renderItem.id = object.id;
  11571. renderItem.object = object;
  11572. renderItem.geometry = geometry;
  11573. renderItem.material = material;
  11574. renderItem.program = materialProperties.program || defaultProgram;
  11575. renderItem.groupOrder = groupOrder;
  11576. renderItem.renderOrder = object.renderOrder;
  11577. renderItem.z = z;
  11578. renderItem.group = group;
  11579. }
  11580. renderItemsIndex ++;
  11581. return renderItem;
  11582. }
  11583. function push( object, geometry, material, groupOrder, z, group ) {
  11584. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11585. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  11586. }
  11587. function unshift( object, geometry, material, groupOrder, z, group ) {
  11588. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11589. ( material.transparent === true ? transparent : opaque ).unshift( renderItem );
  11590. }
  11591. function sort( customOpaqueSort, customTransparentSort ) {
  11592. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  11593. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  11594. }
  11595. function finish() {
  11596. // Clear references from inactive renderItems in the list
  11597. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  11598. const renderItem = renderItems[ i ];
  11599. if ( renderItem.id === null ) break;
  11600. renderItem.id = null;
  11601. renderItem.object = null;
  11602. renderItem.geometry = null;
  11603. renderItem.material = null;
  11604. renderItem.program = null;
  11605. renderItem.group = null;
  11606. }
  11607. }
  11608. return {
  11609. opaque: opaque,
  11610. transparent: transparent,
  11611. init: init,
  11612. push: push,
  11613. unshift: unshift,
  11614. finish: finish,
  11615. sort: sort
  11616. };
  11617. }
  11618. function WebGLRenderLists( properties ) {
  11619. let lists = new WeakMap();
  11620. function get( scene, camera ) {
  11621. const cameras = lists.get( scene );
  11622. let list;
  11623. if ( cameras === undefined ) {
  11624. list = new WebGLRenderList( properties );
  11625. lists.set( scene, new WeakMap() );
  11626. lists.get( scene ).set( camera, list );
  11627. } else {
  11628. list = cameras.get( camera );
  11629. if ( list === undefined ) {
  11630. list = new WebGLRenderList( properties );
  11631. cameras.set( camera, list );
  11632. }
  11633. }
  11634. return list;
  11635. }
  11636. function dispose() {
  11637. lists = new WeakMap();
  11638. }
  11639. return {
  11640. get: get,
  11641. dispose: dispose
  11642. };
  11643. }
  11644. function UniformsCache() {
  11645. const lights = {};
  11646. return {
  11647. get: function ( light ) {
  11648. if ( lights[ light.id ] !== undefined ) {
  11649. return lights[ light.id ];
  11650. }
  11651. let uniforms;
  11652. switch ( light.type ) {
  11653. case 'DirectionalLight':
  11654. uniforms = {
  11655. direction: new Vector3(),
  11656. color: new Color()
  11657. };
  11658. break;
  11659. case 'SpotLight':
  11660. uniforms = {
  11661. position: new Vector3(),
  11662. direction: new Vector3(),
  11663. color: new Color(),
  11664. distance: 0,
  11665. coneCos: 0,
  11666. penumbraCos: 0,
  11667. decay: 0
  11668. };
  11669. break;
  11670. case 'PointLight':
  11671. uniforms = {
  11672. position: new Vector3(),
  11673. color: new Color(),
  11674. distance: 0,
  11675. decay: 0
  11676. };
  11677. break;
  11678. case 'HemisphereLight':
  11679. uniforms = {
  11680. direction: new Vector3(),
  11681. skyColor: new Color(),
  11682. groundColor: new Color()
  11683. };
  11684. break;
  11685. case 'RectAreaLight':
  11686. uniforms = {
  11687. color: new Color(),
  11688. position: new Vector3(),
  11689. halfWidth: new Vector3(),
  11690. halfHeight: new Vector3()
  11691. };
  11692. break;
  11693. }
  11694. lights[ light.id ] = uniforms;
  11695. return uniforms;
  11696. }
  11697. };
  11698. }
  11699. function ShadowUniformsCache() {
  11700. const lights = {};
  11701. return {
  11702. get: function ( light ) {
  11703. if ( lights[ light.id ] !== undefined ) {
  11704. return lights[ light.id ];
  11705. }
  11706. let uniforms;
  11707. switch ( light.type ) {
  11708. case 'DirectionalLight':
  11709. uniforms = {
  11710. shadowBias: 0,
  11711. shadowNormalBias: 0,
  11712. shadowRadius: 1,
  11713. shadowMapSize: new Vector2$1()
  11714. };
  11715. break;
  11716. case 'SpotLight':
  11717. uniforms = {
  11718. shadowBias: 0,
  11719. shadowNormalBias: 0,
  11720. shadowRadius: 1,
  11721. shadowMapSize: new Vector2$1()
  11722. };
  11723. break;
  11724. case 'PointLight':
  11725. uniforms = {
  11726. shadowBias: 0,
  11727. shadowNormalBias: 0,
  11728. shadowRadius: 1,
  11729. shadowMapSize: new Vector2$1(),
  11730. shadowCameraNear: 1,
  11731. shadowCameraFar: 1000
  11732. };
  11733. break;
  11734. // TODO (abelnation): set RectAreaLight shadow uniforms
  11735. }
  11736. lights[ light.id ] = uniforms;
  11737. return uniforms;
  11738. }
  11739. };
  11740. }
  11741. let nextVersion = 0;
  11742. function shadowCastingLightsFirst( lightA, lightB ) {
  11743. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  11744. }
  11745. function WebGLLights( extensions, capabilities ) {
  11746. const cache = new UniformsCache();
  11747. const shadowCache = ShadowUniformsCache();
  11748. const state = {
  11749. version: 0,
  11750. hash: {
  11751. directionalLength: - 1,
  11752. pointLength: - 1,
  11753. spotLength: - 1,
  11754. rectAreaLength: - 1,
  11755. hemiLength: - 1,
  11756. numDirectionalShadows: - 1,
  11757. numPointShadows: - 1,
  11758. numSpotShadows: - 1
  11759. },
  11760. ambient: [ 0, 0, 0 ],
  11761. probe: [],
  11762. directional: [],
  11763. directionalShadow: [],
  11764. directionalShadowMap: [],
  11765. directionalShadowMatrix: [],
  11766. spot: [],
  11767. spotShadow: [],
  11768. spotShadowMap: [],
  11769. spotShadowMatrix: [],
  11770. rectArea: [],
  11771. rectAreaLTC1: null,
  11772. rectAreaLTC2: null,
  11773. point: [],
  11774. pointShadow: [],
  11775. pointShadowMap: [],
  11776. pointShadowMatrix: [],
  11777. hemi: []
  11778. };
  11779. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  11780. const vector3 = new Vector3();
  11781. const matrix4 = new Matrix4();
  11782. const matrix42 = new Matrix4();
  11783. function setup( lights ) {
  11784. let r = 0, g = 0, b = 0;
  11785. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  11786. let directionalLength = 0;
  11787. let pointLength = 0;
  11788. let spotLength = 0;
  11789. let rectAreaLength = 0;
  11790. let hemiLength = 0;
  11791. let numDirectionalShadows = 0;
  11792. let numPointShadows = 0;
  11793. let numSpotShadows = 0;
  11794. lights.sort( shadowCastingLightsFirst );
  11795. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  11796. const light = lights[ i ];
  11797. const color = light.color;
  11798. const intensity = light.intensity;
  11799. const distance = light.distance;
  11800. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  11801. if ( light.isAmbientLight ) {
  11802. r += color.r * intensity;
  11803. g += color.g * intensity;
  11804. b += color.b * intensity;
  11805. } else if ( light.isLightProbe ) {
  11806. for ( let j = 0; j < 9; j ++ ) {
  11807. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  11808. }
  11809. } else if ( light.isDirectionalLight ) {
  11810. const uniforms = cache.get( light );
  11811. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  11812. if ( light.castShadow ) {
  11813. const shadow = light.shadow;
  11814. const shadowUniforms = shadowCache.get( light );
  11815. shadowUniforms.shadowBias = shadow.bias;
  11816. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11817. shadowUniforms.shadowRadius = shadow.radius;
  11818. shadowUniforms.shadowMapSize = shadow.mapSize;
  11819. state.directionalShadow[ directionalLength ] = shadowUniforms;
  11820. state.directionalShadowMap[ directionalLength ] = shadowMap;
  11821. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  11822. numDirectionalShadows ++;
  11823. }
  11824. state.directional[ directionalLength ] = uniforms;
  11825. directionalLength ++;
  11826. } else if ( light.isSpotLight ) {
  11827. const uniforms = cache.get( light );
  11828. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11829. uniforms.color.copy( color ).multiplyScalar( intensity );
  11830. uniforms.distance = distance;
  11831. uniforms.coneCos = Math.cos( light.angle );
  11832. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  11833. uniforms.decay = light.decay;
  11834. if ( light.castShadow ) {
  11835. const shadow = light.shadow;
  11836. const shadowUniforms = shadowCache.get( light );
  11837. shadowUniforms.shadowBias = shadow.bias;
  11838. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11839. shadowUniforms.shadowRadius = shadow.radius;
  11840. shadowUniforms.shadowMapSize = shadow.mapSize;
  11841. state.spotShadow[ spotLength ] = shadowUniforms;
  11842. state.spotShadowMap[ spotLength ] = shadowMap;
  11843. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  11844. numSpotShadows ++;
  11845. }
  11846. state.spot[ spotLength ] = uniforms;
  11847. spotLength ++;
  11848. } else if ( light.isRectAreaLight ) {
  11849. const uniforms = cache.get( light );
  11850. // (a) intensity is the total visible light emitted
  11851. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  11852. // (b) intensity is the brightness of the light
  11853. uniforms.color.copy( color ).multiplyScalar( intensity );
  11854. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  11855. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  11856. state.rectArea[ rectAreaLength ] = uniforms;
  11857. rectAreaLength ++;
  11858. } else if ( light.isPointLight ) {
  11859. const uniforms = cache.get( light );
  11860. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  11861. uniforms.distance = light.distance;
  11862. uniforms.decay = light.decay;
  11863. if ( light.castShadow ) {
  11864. const shadow = light.shadow;
  11865. const shadowUniforms = shadowCache.get( light );
  11866. shadowUniforms.shadowBias = shadow.bias;
  11867. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11868. shadowUniforms.shadowRadius = shadow.radius;
  11869. shadowUniforms.shadowMapSize = shadow.mapSize;
  11870. shadowUniforms.shadowCameraNear = shadow.camera.near;
  11871. shadowUniforms.shadowCameraFar = shadow.camera.far;
  11872. state.pointShadow[ pointLength ] = shadowUniforms;
  11873. state.pointShadowMap[ pointLength ] = shadowMap;
  11874. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  11875. numPointShadows ++;
  11876. }
  11877. state.point[ pointLength ] = uniforms;
  11878. pointLength ++;
  11879. } else if ( light.isHemisphereLight ) {
  11880. const uniforms = cache.get( light );
  11881. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  11882. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  11883. state.hemi[ hemiLength ] = uniforms;
  11884. hemiLength ++;
  11885. }
  11886. }
  11887. if ( rectAreaLength > 0 ) {
  11888. if ( capabilities.isWebGL2 ) {
  11889. // WebGL 2
  11890. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11891. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11892. } else {
  11893. // WebGL 1
  11894. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  11895. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11896. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11897. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  11898. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  11899. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  11900. } else {
  11901. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  11902. }
  11903. }
  11904. }
  11905. state.ambient[ 0 ] = r;
  11906. state.ambient[ 1 ] = g;
  11907. state.ambient[ 2 ] = b;
  11908. const hash = state.hash;
  11909. if ( hash.directionalLength !== directionalLength ||
  11910. hash.pointLength !== pointLength ||
  11911. hash.spotLength !== spotLength ||
  11912. hash.rectAreaLength !== rectAreaLength ||
  11913. hash.hemiLength !== hemiLength ||
  11914. hash.numDirectionalShadows !== numDirectionalShadows ||
  11915. hash.numPointShadows !== numPointShadows ||
  11916. hash.numSpotShadows !== numSpotShadows ) {
  11917. state.directional.length = directionalLength;
  11918. state.spot.length = spotLength;
  11919. state.rectArea.length = rectAreaLength;
  11920. state.point.length = pointLength;
  11921. state.hemi.length = hemiLength;
  11922. state.directionalShadow.length = numDirectionalShadows;
  11923. state.directionalShadowMap.length = numDirectionalShadows;
  11924. state.pointShadow.length = numPointShadows;
  11925. state.pointShadowMap.length = numPointShadows;
  11926. state.spotShadow.length = numSpotShadows;
  11927. state.spotShadowMap.length = numSpotShadows;
  11928. state.directionalShadowMatrix.length = numDirectionalShadows;
  11929. state.pointShadowMatrix.length = numPointShadows;
  11930. state.spotShadowMatrix.length = numSpotShadows;
  11931. hash.directionalLength = directionalLength;
  11932. hash.pointLength = pointLength;
  11933. hash.spotLength = spotLength;
  11934. hash.rectAreaLength = rectAreaLength;
  11935. hash.hemiLength = hemiLength;
  11936. hash.numDirectionalShadows = numDirectionalShadows;
  11937. hash.numPointShadows = numPointShadows;
  11938. hash.numSpotShadows = numSpotShadows;
  11939. state.version = nextVersion ++;
  11940. }
  11941. }
  11942. function setupView( lights, camera ) {
  11943. let directionalLength = 0;
  11944. let pointLength = 0;
  11945. let spotLength = 0;
  11946. let rectAreaLength = 0;
  11947. let hemiLength = 0;
  11948. const viewMatrix = camera.matrixWorldInverse;
  11949. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  11950. const light = lights[ i ];
  11951. if ( light.isDirectionalLight ) {
  11952. const uniforms = state.directional[ directionalLength ];
  11953. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11954. vector3.setFromMatrixPosition( light.target.matrixWorld );
  11955. uniforms.direction.sub( vector3 );
  11956. uniforms.direction.transformDirection( viewMatrix );
  11957. directionalLength ++;
  11958. } else if ( light.isSpotLight ) {
  11959. const uniforms = state.spot[ spotLength ];
  11960. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11961. uniforms.position.applyMatrix4( viewMatrix );
  11962. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11963. vector3.setFromMatrixPosition( light.target.matrixWorld );
  11964. uniforms.direction.sub( vector3 );
  11965. uniforms.direction.transformDirection( viewMatrix );
  11966. spotLength ++;
  11967. } else if ( light.isRectAreaLight ) {
  11968. const uniforms = state.rectArea[ rectAreaLength ];
  11969. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11970. uniforms.position.applyMatrix4( viewMatrix );
  11971. // extract local rotation of light to derive width/height half vectors
  11972. matrix42.identity();
  11973. matrix4.copy( light.matrixWorld );
  11974. matrix4.premultiply( viewMatrix );
  11975. matrix42.extractRotation( matrix4 );
  11976. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  11977. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  11978. uniforms.halfWidth.applyMatrix4( matrix42 );
  11979. uniforms.halfHeight.applyMatrix4( matrix42 );
  11980. rectAreaLength ++;
  11981. } else if ( light.isPointLight ) {
  11982. const uniforms = state.point[ pointLength ];
  11983. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  11984. uniforms.position.applyMatrix4( viewMatrix );
  11985. pointLength ++;
  11986. } else if ( light.isHemisphereLight ) {
  11987. const uniforms = state.hemi[ hemiLength ];
  11988. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  11989. uniforms.direction.transformDirection( viewMatrix );
  11990. uniforms.direction.normalize();
  11991. hemiLength ++;
  11992. }
  11993. }
  11994. }
  11995. return {
  11996. setup: setup,
  11997. setupView: setupView,
  11998. state: state
  11999. };
  12000. }
  12001. function WebGLRenderState( extensions, capabilities ) {
  12002. const lights = new WebGLLights( extensions, capabilities );
  12003. const lightsArray = [];
  12004. const shadowsArray = [];
  12005. function init() {
  12006. lightsArray.length = 0;
  12007. shadowsArray.length = 0;
  12008. }
  12009. function pushLight( light ) {
  12010. lightsArray.push( light );
  12011. }
  12012. function pushShadow( shadowLight ) {
  12013. shadowsArray.push( shadowLight );
  12014. }
  12015. function setupLights() {
  12016. lights.setup( lightsArray );
  12017. }
  12018. function setupLightsView( camera ) {
  12019. lights.setupView( lightsArray, camera );
  12020. }
  12021. const state = {
  12022. lightsArray: lightsArray,
  12023. shadowsArray: shadowsArray,
  12024. lights: lights
  12025. };
  12026. return {
  12027. init: init,
  12028. state: state,
  12029. setupLights: setupLights,
  12030. setupLightsView: setupLightsView,
  12031. pushLight: pushLight,
  12032. pushShadow: pushShadow
  12033. };
  12034. }
  12035. function WebGLRenderStates( extensions, capabilities ) {
  12036. let renderStates = new WeakMap();
  12037. function get( scene, renderCallDepth = 0 ) {
  12038. let renderState;
  12039. if ( renderStates.has( scene ) === false ) {
  12040. renderState = new WebGLRenderState( extensions, capabilities );
  12041. renderStates.set( scene, [] );
  12042. renderStates.get( scene ).push( renderState );
  12043. } else {
  12044. if ( renderCallDepth >= renderStates.get( scene ).length ) {
  12045. renderState = new WebGLRenderState( extensions, capabilities );
  12046. renderStates.get( scene ).push( renderState );
  12047. } else {
  12048. renderState = renderStates.get( scene )[ renderCallDepth ];
  12049. }
  12050. }
  12051. return renderState;
  12052. }
  12053. function dispose() {
  12054. renderStates = new WeakMap();
  12055. }
  12056. return {
  12057. get: get,
  12058. dispose: dispose
  12059. };
  12060. }
  12061. /**
  12062. * parameters = {
  12063. *
  12064. * opacity: <float>,
  12065. *
  12066. * map: new THREE.Texture( <Image> ),
  12067. *
  12068. * alphaMap: new THREE.Texture( <Image> ),
  12069. *
  12070. * displacementMap: new THREE.Texture( <Image> ),
  12071. * displacementScale: <float>,
  12072. * displacementBias: <float>,
  12073. *
  12074. * wireframe: <boolean>,
  12075. * wireframelineWidth: <float>
  12076. * }
  12077. */
  12078. function MeshDepthMaterial( parameters ) {
  12079. Material.call( this );
  12080. this.type = 'MeshDepthMaterial';
  12081. this.depthPacking = BasicDepthPacking;
  12082. this.skinning = false;
  12083. this.morphTargets = false;
  12084. this.map = null;
  12085. this.alphaMap = null;
  12086. this.displacementMap = null;
  12087. this.displacementScale = 1;
  12088. this.displacementBias = 0;
  12089. this.wireframe = false;
  12090. this.wireframelineWidth = 1;
  12091. this.fog = false;
  12092. this.setValues( parameters );
  12093. }
  12094. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  12095. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  12096. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12097. MeshDepthMaterial.prototype.copy = function ( source ) {
  12098. Material.prototype.copy.call( this, source );
  12099. this.depthPacking = source.depthPacking;
  12100. this.skinning = source.skinning;
  12101. this.morphTargets = source.morphTargets;
  12102. this.map = source.map;
  12103. this.alphaMap = source.alphaMap;
  12104. this.displacementMap = source.displacementMap;
  12105. this.displacementScale = source.displacementScale;
  12106. this.displacementBias = source.displacementBias;
  12107. this.wireframe = source.wireframe;
  12108. this.wireframelineWidth = source.wireframelineWidth;
  12109. return this;
  12110. };
  12111. /**
  12112. * parameters = {
  12113. *
  12114. * referencePosition: <float>,
  12115. * nearDistance: <float>,
  12116. * farDistance: <float>,
  12117. *
  12118. * skinning: <bool>,
  12119. * morphTargets: <bool>,
  12120. *
  12121. * map: new THREE.Texture( <Image> ),
  12122. *
  12123. * alphaMap: new THREE.Texture( <Image> ),
  12124. *
  12125. * displacementMap: new THREE.Texture( <Image> ),
  12126. * displacementScale: <float>,
  12127. * displacementBias: <float>
  12128. *
  12129. * }
  12130. */
  12131. function MeshDistanceMaterial( parameters ) {
  12132. Material.call( this );
  12133. this.type = 'MeshDistanceMaterial';
  12134. this.referencePosition = new Vector3();
  12135. this.nearDistance = 1;
  12136. this.farDistance = 1000;
  12137. this.skinning = false;
  12138. this.morphTargets = false;
  12139. this.map = null;
  12140. this.alphaMap = null;
  12141. this.displacementMap = null;
  12142. this.displacementScale = 1;
  12143. this.displacementBias = 0;
  12144. this.fog = false;
  12145. this.setValues( parameters );
  12146. }
  12147. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  12148. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  12149. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12150. MeshDistanceMaterial.prototype.copy = function ( source ) {
  12151. Material.prototype.copy.call( this, source );
  12152. this.referencePosition.copy( source.referencePosition );
  12153. this.nearDistance = source.nearDistance;
  12154. this.farDistance = source.farDistance;
  12155. this.skinning = source.skinning;
  12156. this.morphTargets = source.morphTargets;
  12157. this.map = source.map;
  12158. this.alphaMap = source.alphaMap;
  12159. this.displacementMap = source.displacementMap;
  12160. this.displacementScale = source.displacementScale;
  12161. this.displacementBias = source.displacementBias;
  12162. return this;
  12163. };
  12164. 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}";
  12165. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12166. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  12167. let _frustum = new Frustum();
  12168. const _shadowMapSize = new Vector2$1(),
  12169. _viewportSize = new Vector2$1(),
  12170. _viewport = new Vector4(),
  12171. _depthMaterials = [],
  12172. _distanceMaterials = [],
  12173. _materialCache = {};
  12174. const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  12175. const shadowMaterialVertical = new ShaderMaterial( {
  12176. defines: {
  12177. SAMPLE_RATE: 2.0 / 8.0,
  12178. HALF_SAMPLE_RATE: 1.0 / 8.0
  12179. },
  12180. uniforms: {
  12181. shadow_pass: { value: null },
  12182. resolution: { value: new Vector2$1() },
  12183. radius: { value: 4.0 }
  12184. },
  12185. vertexShader: vsm_vert,
  12186. fragmentShader: vsm_frag
  12187. } );
  12188. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12189. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12190. const fullScreenTri = new BufferGeometry();
  12191. fullScreenTri.setAttribute(
  12192. 'position',
  12193. new BufferAttribute(
  12194. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12195. 3
  12196. )
  12197. );
  12198. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12199. const scope = this;
  12200. this.enabled = false;
  12201. this.autoUpdate = true;
  12202. this.needsUpdate = false;
  12203. this.type = PCFShadowMap;
  12204. this.render = function ( lights, scene, camera ) {
  12205. if ( scope.enabled === false ) return;
  12206. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12207. if ( lights.length === 0 ) return;
  12208. const currentRenderTarget = _renderer.getRenderTarget();
  12209. const activeCubeFace = _renderer.getActiveCubeFace();
  12210. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12211. const _state = _renderer.state;
  12212. // Set GL state for depth map.
  12213. _state.setBlending( NoBlending );
  12214. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12215. _state.buffers.depth.setTest( true );
  12216. _state.setScissorTest( false );
  12217. // render depth map
  12218. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12219. const light = lights[ i ];
  12220. const shadow = light.shadow;
  12221. if ( shadow === undefined ) {
  12222. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12223. continue;
  12224. }
  12225. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12226. _shadowMapSize.copy( shadow.mapSize );
  12227. const shadowFrameExtents = shadow.getFrameExtents();
  12228. _shadowMapSize.multiply( shadowFrameExtents );
  12229. _viewportSize.copy( shadow.mapSize );
  12230. if ( _shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize ) {
  12231. if ( _shadowMapSize.x > maxTextureSize ) {
  12232. _viewportSize.x = Math.floor( maxTextureSize / shadowFrameExtents.x );
  12233. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12234. shadow.mapSize.x = _viewportSize.x;
  12235. }
  12236. if ( _shadowMapSize.y > maxTextureSize ) {
  12237. _viewportSize.y = Math.floor( maxTextureSize / shadowFrameExtents.y );
  12238. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12239. shadow.mapSize.y = _viewportSize.y;
  12240. }
  12241. }
  12242. if ( shadow.map === null && ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  12243. const pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  12244. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12245. shadow.map.texture.name = light.name + '.shadowMap';
  12246. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12247. shadow.camera.updateProjectionMatrix();
  12248. }
  12249. if ( shadow.map === null ) {
  12250. const pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  12251. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12252. shadow.map.texture.name = light.name + '.shadowMap';
  12253. shadow.camera.updateProjectionMatrix();
  12254. }
  12255. _renderer.setRenderTarget( shadow.map );
  12256. _renderer.clear();
  12257. const viewportCount = shadow.getViewportCount();
  12258. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12259. const viewport = shadow.getViewport( vp );
  12260. _viewport.set(
  12261. _viewportSize.x * viewport.x,
  12262. _viewportSize.y * viewport.y,
  12263. _viewportSize.x * viewport.z,
  12264. _viewportSize.y * viewport.w
  12265. );
  12266. _state.viewport( _viewport );
  12267. shadow.updateMatrices( light, vp );
  12268. _frustum = shadow.getFrustum();
  12269. renderObject( scene, camera, shadow.camera, light, this.type );
  12270. }
  12271. // do blur pass for VSM
  12272. if ( ! shadow.isPointLightShadow && this.type === VSMShadowMap ) {
  12273. VSMPass( shadow, camera );
  12274. }
  12275. shadow.needsUpdate = false;
  12276. }
  12277. scope.needsUpdate = false;
  12278. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12279. };
  12280. function VSMPass( shadow, camera ) {
  12281. const geometry = _objects.update( fullScreenMesh );
  12282. // vertical pass
  12283. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12284. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12285. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12286. _renderer.setRenderTarget( shadow.mapPass );
  12287. _renderer.clear();
  12288. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12289. // horizontal pass
  12290. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12291. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12292. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12293. _renderer.setRenderTarget( shadow.map );
  12294. _renderer.clear();
  12295. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  12296. }
  12297. function getDepthMaterialVariant( useMorphing, useSkinning, useInstancing ) {
  12298. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12299. let material = _depthMaterials[ index ];
  12300. if ( material === undefined ) {
  12301. material = new MeshDepthMaterial( {
  12302. depthPacking: RGBADepthPacking,
  12303. morphTargets: useMorphing,
  12304. skinning: useSkinning
  12305. } );
  12306. _depthMaterials[ index ] = material;
  12307. }
  12308. return material;
  12309. }
  12310. function getDistanceMaterialVariant( useMorphing, useSkinning, useInstancing ) {
  12311. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12312. let material = _distanceMaterials[ index ];
  12313. if ( material === undefined ) {
  12314. material = new MeshDistanceMaterial( {
  12315. morphTargets: useMorphing,
  12316. skinning: useSkinning
  12317. } );
  12318. _distanceMaterials[ index ] = material;
  12319. }
  12320. return material;
  12321. }
  12322. function getDepthMaterial( object, geometry, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12323. let result = null;
  12324. let getMaterialVariant = getDepthMaterialVariant;
  12325. let customMaterial = object.customDepthMaterial;
  12326. if ( light.isPointLight === true ) {
  12327. getMaterialVariant = getDistanceMaterialVariant;
  12328. customMaterial = object.customDistanceMaterial;
  12329. }
  12330. if ( customMaterial === undefined ) {
  12331. let useMorphing = false;
  12332. if ( material.morphTargets === true ) {
  12333. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  12334. }
  12335. let useSkinning = false;
  12336. if ( object.isSkinnedMesh === true ) {
  12337. if ( material.skinning === true ) {
  12338. useSkinning = true;
  12339. } else {
  12340. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  12341. }
  12342. }
  12343. const useInstancing = object.isInstancedMesh === true;
  12344. result = getMaterialVariant( useMorphing, useSkinning, useInstancing );
  12345. } else {
  12346. result = customMaterial;
  12347. }
  12348. if ( _renderer.localClippingEnabled &&
  12349. material.clipShadows === true &&
  12350. material.clippingPlanes.length !== 0 ) {
  12351. // in this case we need a unique material instance reflecting the
  12352. // appropriate state
  12353. const keyA = result.uuid, keyB = material.uuid;
  12354. let materialsForVariant = _materialCache[ keyA ];
  12355. if ( materialsForVariant === undefined ) {
  12356. materialsForVariant = {};
  12357. _materialCache[ keyA ] = materialsForVariant;
  12358. }
  12359. let cachedMaterial = materialsForVariant[ keyB ];
  12360. if ( cachedMaterial === undefined ) {
  12361. cachedMaterial = result.clone();
  12362. materialsForVariant[ keyB ] = cachedMaterial;
  12363. }
  12364. result = cachedMaterial;
  12365. }
  12366. result.visible = material.visible;
  12367. result.wireframe = material.wireframe;
  12368. if ( type === VSMShadowMap ) {
  12369. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12370. } else {
  12371. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12372. }
  12373. result.clipShadows = material.clipShadows;
  12374. result.clippingPlanes = material.clippingPlanes;
  12375. result.clipIntersection = material.clipIntersection;
  12376. result.wireframelineWidth = material.wireframelineWidth;
  12377. result.lineWidth = material.lineWidth;
  12378. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12379. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12380. result.nearDistance = shadowCameraNear;
  12381. result.farDistance = shadowCameraFar;
  12382. }
  12383. return result;
  12384. }
  12385. function renderObject( object, camera, shadowCamera, light, type ) {
  12386. if ( object.visible === false ) return;
  12387. const visible = object.layers.test( camera.layers );
  12388. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  12389. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  12390. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  12391. const geometry = _objects.update( object );
  12392. const material = object.material;
  12393. if ( Array.isArray( material ) ) {
  12394. const groups = geometry.groups;
  12395. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  12396. const group = groups[ k ];
  12397. const groupMaterial = material[ group.materialIndex ];
  12398. if ( groupMaterial && groupMaterial.visible ) {
  12399. const depthMaterial = getDepthMaterial( object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  12400. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  12401. }
  12402. }
  12403. } else if ( material.visible ) {
  12404. const depthMaterial = getDepthMaterial( object, geometry, material, light, shadowCamera.near, shadowCamera.far, type );
  12405. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  12406. }
  12407. }
  12408. }
  12409. const children = object.children;
  12410. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12411. renderObject( children[ i ], camera, shadowCamera, light, type );
  12412. }
  12413. }
  12414. }
  12415. function WebGLState( gl, extensions, capabilities ) {
  12416. const isWebGL2 = capabilities.isWebGL2;
  12417. function ColorBuffer() {
  12418. let locked = false;
  12419. const color = new Vector4();
  12420. let currentColorMask = null;
  12421. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  12422. return {
  12423. setMask: function ( colorMask ) {
  12424. if ( currentColorMask !== colorMask && ! locked ) {
  12425. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  12426. currentColorMask = colorMask;
  12427. }
  12428. },
  12429. setLocked: function ( lock ) {
  12430. locked = lock;
  12431. },
  12432. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  12433. if ( premultipliedAlpha === true ) {
  12434. r *= a; g *= a; b *= a;
  12435. }
  12436. color.set( r, g, b, a );
  12437. if ( currentColorClear.equals( color ) === false ) {
  12438. gl.clearColor( r, g, b, a );
  12439. currentColorClear.copy( color );
  12440. }
  12441. },
  12442. reset: function () {
  12443. locked = false;
  12444. currentColorMask = null;
  12445. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  12446. }
  12447. };
  12448. }
  12449. function DepthBuffer() {
  12450. let locked = false;
  12451. let currentDepthMask = null;
  12452. let currentDepthFunc = null;
  12453. let currentDepthClear = null;
  12454. return {
  12455. setTest: function ( depthTest ) {
  12456. if ( depthTest ) {
  12457. enable( 2929 );
  12458. } else {
  12459. disable( 2929 );
  12460. }
  12461. },
  12462. setMask: function ( depthMask ) {
  12463. if ( currentDepthMask !== depthMask && ! locked ) {
  12464. gl.depthMask( depthMask );
  12465. currentDepthMask = depthMask;
  12466. }
  12467. },
  12468. setFunc: function ( depthFunc ) {
  12469. if ( currentDepthFunc !== depthFunc ) {
  12470. if ( depthFunc ) {
  12471. switch ( depthFunc ) {
  12472. case NeverDepth:
  12473. gl.depthFunc( 512 );
  12474. break;
  12475. case AlwaysDepth:
  12476. gl.depthFunc( 519 );
  12477. break;
  12478. case LessDepth:
  12479. gl.depthFunc( 513 );
  12480. break;
  12481. case LessEqualDepth:
  12482. gl.depthFunc( 515 );
  12483. break;
  12484. case EqualDepth:
  12485. gl.depthFunc( 514 );
  12486. break;
  12487. case GreaterEqualDepth:
  12488. gl.depthFunc( 518 );
  12489. break;
  12490. case GreaterDepth:
  12491. gl.depthFunc( 516 );
  12492. break;
  12493. case NotEqualDepth:
  12494. gl.depthFunc( 517 );
  12495. break;
  12496. default:
  12497. gl.depthFunc( 515 );
  12498. }
  12499. } else {
  12500. gl.depthFunc( 515 );
  12501. }
  12502. currentDepthFunc = depthFunc;
  12503. }
  12504. },
  12505. setLocked: function ( lock ) {
  12506. locked = lock;
  12507. },
  12508. setClear: function ( depth ) {
  12509. if ( currentDepthClear !== depth ) {
  12510. gl.clearDepth( depth );
  12511. currentDepthClear = depth;
  12512. }
  12513. },
  12514. reset: function () {
  12515. locked = false;
  12516. currentDepthMask = null;
  12517. currentDepthFunc = null;
  12518. currentDepthClear = null;
  12519. }
  12520. };
  12521. }
  12522. function StencilBuffer() {
  12523. let locked = false;
  12524. let currentStencilMask = null;
  12525. let currentStencilFunc = null;
  12526. let currentStencilRef = null;
  12527. let currentStencilFuncMask = null;
  12528. let currentStencilFail = null;
  12529. let currentStencilZFail = null;
  12530. let currentStencilZPass = null;
  12531. let currentStencilClear = null;
  12532. return {
  12533. setTest: function ( stencilTest ) {
  12534. if ( ! locked ) {
  12535. if ( stencilTest ) {
  12536. enable( 2960 );
  12537. } else {
  12538. disable( 2960 );
  12539. }
  12540. }
  12541. },
  12542. setMask: function ( stencilMask ) {
  12543. if ( currentStencilMask !== stencilMask && ! locked ) {
  12544. gl.stencilMask( stencilMask );
  12545. currentStencilMask = stencilMask;
  12546. }
  12547. },
  12548. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  12549. if ( currentStencilFunc !== stencilFunc ||
  12550. currentStencilRef !== stencilRef ||
  12551. currentStencilFuncMask !== stencilMask ) {
  12552. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  12553. currentStencilFunc = stencilFunc;
  12554. currentStencilRef = stencilRef;
  12555. currentStencilFuncMask = stencilMask;
  12556. }
  12557. },
  12558. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  12559. if ( currentStencilFail !== stencilFail ||
  12560. currentStencilZFail !== stencilZFail ||
  12561. currentStencilZPass !== stencilZPass ) {
  12562. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  12563. currentStencilFail = stencilFail;
  12564. currentStencilZFail = stencilZFail;
  12565. currentStencilZPass = stencilZPass;
  12566. }
  12567. },
  12568. setLocked: function ( lock ) {
  12569. locked = lock;
  12570. },
  12571. setClear: function ( stencil ) {
  12572. if ( currentStencilClear !== stencil ) {
  12573. gl.clearStencil( stencil );
  12574. currentStencilClear = stencil;
  12575. }
  12576. },
  12577. reset: function () {
  12578. locked = false;
  12579. currentStencilMask = null;
  12580. currentStencilFunc = null;
  12581. currentStencilRef = null;
  12582. currentStencilFuncMask = null;
  12583. currentStencilFail = null;
  12584. currentStencilZFail = null;
  12585. currentStencilZPass = null;
  12586. currentStencilClear = null;
  12587. }
  12588. };
  12589. }
  12590. //
  12591. const colorBuffer = new ColorBuffer();
  12592. const depthBuffer = new DepthBuffer();
  12593. const stencilBuffer = new StencilBuffer();
  12594. let enabledCapabilities = {};
  12595. let currentProgram = null;
  12596. let currentBlendingEnabled = null;
  12597. let currentBlending = null;
  12598. let currentBlendEquation = null;
  12599. let currentBlendSrc = null;
  12600. let currentBlendDst = null;
  12601. let currentBlendEquationAlpha = null;
  12602. let currentBlendSrcAlpha = null;
  12603. let currentBlendDstAlpha = null;
  12604. let currentPremultipledAlpha = false;
  12605. let currentFlipSided = null;
  12606. let currentCullFace = null;
  12607. let currentlineWidth = null;
  12608. let currentPolygonOffsetFactor = null;
  12609. let currentPolygonOffsetUnits = null;
  12610. const maxTextures = gl.getParameter( 35661 );
  12611. let lineWidthAvailable = false;
  12612. let version = 0;
  12613. const glVersion = gl.getParameter( 7938 );
  12614. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  12615. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  12616. lineWidthAvailable = ( version >= 1.0 );
  12617. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  12618. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  12619. lineWidthAvailable = ( version >= 2.0 );
  12620. }
  12621. let currentTextureSlot = null;
  12622. let currentBoundTextures = {};
  12623. const currentScissor = new Vector4();
  12624. const currentViewport = new Vector4();
  12625. function createTexture( type, target, count ) {
  12626. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  12627. const texture = gl.createTexture();
  12628. gl.bindTexture( type, texture );
  12629. gl.texParameteri( type, 10241, 9728 );
  12630. gl.texParameteri( type, 10240, 9728 );
  12631. for ( let i = 0; i < count; i ++ ) {
  12632. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  12633. }
  12634. return texture;
  12635. }
  12636. const emptyTextures = {};
  12637. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  12638. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  12639. // init
  12640. colorBuffer.setClear( 0, 0, 0, 1 );
  12641. depthBuffer.setClear( 1 );
  12642. stencilBuffer.setClear( 0 );
  12643. enable( 2929 );
  12644. depthBuffer.setFunc( LessEqualDepth );
  12645. setFlipSided( false );
  12646. setCullFace( CullFaceBack );
  12647. enable( 2884 );
  12648. setBlending( NoBlending );
  12649. //
  12650. function enable( id ) {
  12651. if ( enabledCapabilities[ id ] !== true ) {
  12652. gl.enable( id );
  12653. enabledCapabilities[ id ] = true;
  12654. }
  12655. }
  12656. function disable( id ) {
  12657. if ( enabledCapabilities[ id ] !== false ) {
  12658. gl.disable( id );
  12659. enabledCapabilities[ id ] = false;
  12660. }
  12661. }
  12662. function useProgram( program ) {
  12663. if ( currentProgram !== program ) {
  12664. gl.useProgram( program );
  12665. currentProgram = program;
  12666. return true;
  12667. }
  12668. return false;
  12669. }
  12670. const equationToGL = {
  12671. [ AddEquation ]: 32774,
  12672. [ SubtractEquation ]: 32778,
  12673. [ ReverseSubtractEquation ]: 32779
  12674. };
  12675. if ( isWebGL2 ) {
  12676. equationToGL[ MinEquation ] = 32775;
  12677. equationToGL[ MaxEquation ] = 32776;
  12678. } else {
  12679. const extension = extensions.get( 'EXT_blend_minmax' );
  12680. if ( extension !== null ) {
  12681. equationToGL[ MinEquation ] = extension.MIN_EXT;
  12682. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  12683. }
  12684. }
  12685. const factorToGL = {
  12686. [ ZeroFactor ]: 0,
  12687. [ OneFactor ]: 1,
  12688. [ SrcColorFactor ]: 768,
  12689. [ SrcAlphaFactor ]: 770,
  12690. [ SrcAlphaSaturateFactor ]: 776,
  12691. [ DstColorFactor ]: 774,
  12692. [ DstAlphaFactor ]: 772,
  12693. [ OneMinusSrcColorFactor ]: 769,
  12694. [ OneMinusSrcAlphaFactor ]: 771,
  12695. [ OneMinusDstColorFactor ]: 775,
  12696. [ OneMinusDstAlphaFactor ]: 773
  12697. };
  12698. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  12699. if ( blending === NoBlending ) {
  12700. if ( currentBlendingEnabled ) {
  12701. disable( 3042 );
  12702. currentBlendingEnabled = false;
  12703. }
  12704. return;
  12705. }
  12706. if ( ! currentBlendingEnabled ) {
  12707. enable( 3042 );
  12708. currentBlendingEnabled = true;
  12709. }
  12710. if ( blending !== CustomBlending ) {
  12711. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  12712. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  12713. gl.blendEquation( 32774 );
  12714. currentBlendEquation = AddEquation;
  12715. currentBlendEquationAlpha = AddEquation;
  12716. }
  12717. if ( premultipliedAlpha ) {
  12718. switch ( blending ) {
  12719. case NormalBlending:
  12720. gl.blendFuncSeparate( 1, 771, 1, 771 );
  12721. break;
  12722. case AdditiveBlending:
  12723. gl.blendFunc( 1, 1 );
  12724. break;
  12725. case SubtractiveBlending:
  12726. gl.blendFuncSeparate( 0, 0, 769, 771 );
  12727. break;
  12728. case MultiplyBlending:
  12729. gl.blendFuncSeparate( 0, 768, 0, 770 );
  12730. break;
  12731. default:
  12732. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  12733. break;
  12734. }
  12735. } else {
  12736. switch ( blending ) {
  12737. case NormalBlending:
  12738. gl.blendFuncSeparate( 770, 771, 1, 771 );
  12739. break;
  12740. case AdditiveBlending:
  12741. gl.blendFunc( 770, 1 );
  12742. break;
  12743. case SubtractiveBlending:
  12744. gl.blendFunc( 0, 769 );
  12745. break;
  12746. case MultiplyBlending:
  12747. gl.blendFunc( 0, 768 );
  12748. break;
  12749. default:
  12750. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  12751. break;
  12752. }
  12753. }
  12754. currentBlendSrc = null;
  12755. currentBlendDst = null;
  12756. currentBlendSrcAlpha = null;
  12757. currentBlendDstAlpha = null;
  12758. currentBlending = blending;
  12759. currentPremultipledAlpha = premultipliedAlpha;
  12760. }
  12761. return;
  12762. }
  12763. // custom blending
  12764. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12765. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12766. blendDstAlpha = blendDstAlpha || blendDst;
  12767. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  12768. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  12769. currentBlendEquation = blendEquation;
  12770. currentBlendEquationAlpha = blendEquationAlpha;
  12771. }
  12772. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  12773. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  12774. currentBlendSrc = blendSrc;
  12775. currentBlendDst = blendDst;
  12776. currentBlendSrcAlpha = blendSrcAlpha;
  12777. currentBlendDstAlpha = blendDstAlpha;
  12778. }
  12779. currentBlending = blending;
  12780. currentPremultipledAlpha = null;
  12781. }
  12782. function setMaterial( material, frontFaceCW ) {
  12783. material.side === DoubleSide
  12784. ? disable( 2884 )
  12785. : enable( 2884 );
  12786. let flipSided = ( material.side === BackSide );
  12787. if ( frontFaceCW ) flipSided = ! flipSided;
  12788. setFlipSided( flipSided );
  12789. ( material.blending === NormalBlending && material.transparent === false )
  12790. ? setBlending( NoBlending )
  12791. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  12792. depthBuffer.setFunc( material.depthFunc );
  12793. depthBuffer.setTest( material.depthTest );
  12794. depthBuffer.setMask( material.depthWrite );
  12795. colorBuffer.setMask( material.colorWrite );
  12796. const stencilWrite = material.stencilWrite;
  12797. stencilBuffer.setTest( stencilWrite );
  12798. if ( stencilWrite ) {
  12799. stencilBuffer.setMask( material.stencilWriteMask );
  12800. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  12801. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  12802. }
  12803. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12804. }
  12805. //
  12806. function setFlipSided( flipSided ) {
  12807. if ( currentFlipSided !== flipSided ) {
  12808. if ( flipSided ) {
  12809. gl.frontFace( 2304 );
  12810. } else {
  12811. gl.frontFace( 2305 );
  12812. }
  12813. currentFlipSided = flipSided;
  12814. }
  12815. }
  12816. function setCullFace( cullFace ) {
  12817. if ( cullFace !== CullFaceNone ) {
  12818. enable( 2884 );
  12819. if ( cullFace !== currentCullFace ) {
  12820. if ( cullFace === CullFaceBack ) {
  12821. gl.cullFace( 1029 );
  12822. } else if ( cullFace === CullFaceFront ) {
  12823. gl.cullFace( 1028 );
  12824. } else {
  12825. gl.cullFace( 1032 );
  12826. }
  12827. }
  12828. } else {
  12829. disable( 2884 );
  12830. }
  12831. currentCullFace = cullFace;
  12832. }
  12833. function setlineWidth( width ) {
  12834. if ( width !== currentlineWidth ) {
  12835. if ( lineWidthAvailable ) gl.lineWidth( width );
  12836. currentlineWidth = width;
  12837. }
  12838. }
  12839. function setPolygonOffset( polygonOffset, factor, units ) {
  12840. if ( polygonOffset ) {
  12841. enable( 32823 );
  12842. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  12843. gl.polygonOffset( factor, units );
  12844. currentPolygonOffsetFactor = factor;
  12845. currentPolygonOffsetUnits = units;
  12846. }
  12847. } else {
  12848. disable( 32823 );
  12849. }
  12850. }
  12851. function setScissorTest( scissorTest ) {
  12852. if ( scissorTest ) {
  12853. enable( 3089 );
  12854. } else {
  12855. disable( 3089 );
  12856. }
  12857. }
  12858. // texture
  12859. function activeTexture( webglSlot ) {
  12860. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  12861. if ( currentTextureSlot !== webglSlot ) {
  12862. gl.activeTexture( webglSlot );
  12863. currentTextureSlot = webglSlot;
  12864. }
  12865. }
  12866. function bindTexture( webglType, webglTexture ) {
  12867. if ( currentTextureSlot === null ) {
  12868. activeTexture();
  12869. }
  12870. let boundTexture = currentBoundTextures[ currentTextureSlot ];
  12871. if ( boundTexture === undefined ) {
  12872. boundTexture = { type: undefined, texture: undefined };
  12873. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  12874. }
  12875. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  12876. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  12877. boundTexture.type = webglType;
  12878. boundTexture.texture = webglTexture;
  12879. }
  12880. }
  12881. function unbindTexture() {
  12882. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  12883. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  12884. gl.bindTexture( boundTexture.type, null );
  12885. boundTexture.type = undefined;
  12886. boundTexture.texture = undefined;
  12887. }
  12888. }
  12889. function compressedTexImage2D() {
  12890. try {
  12891. gl.compressedTexImage2D.apply( gl, arguments );
  12892. } catch ( error ) {
  12893. console.error( 'THREE.WebGLState:', error );
  12894. }
  12895. }
  12896. function texImage2D() {
  12897. try {
  12898. gl.texImage2D.apply( gl, arguments );
  12899. } catch ( error ) {
  12900. console.error( 'THREE.WebGLState:', error );
  12901. }
  12902. }
  12903. function texImage3D() {
  12904. try {
  12905. gl.texImage3D.apply( gl, arguments );
  12906. } catch ( error ) {
  12907. console.error( 'THREE.WebGLState:', error );
  12908. }
  12909. }
  12910. //
  12911. function scissor( scissor ) {
  12912. if ( currentScissor.equals( scissor ) === false ) {
  12913. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  12914. currentScissor.copy( scissor );
  12915. }
  12916. }
  12917. function viewport( viewport ) {
  12918. if ( currentViewport.equals( viewport ) === false ) {
  12919. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  12920. currentViewport.copy( viewport );
  12921. }
  12922. }
  12923. //
  12924. function reset() {
  12925. enabledCapabilities = {};
  12926. currentTextureSlot = null;
  12927. currentBoundTextures = {};
  12928. currentProgram = null;
  12929. currentBlendingEnabled = null;
  12930. currentBlending = null;
  12931. currentBlendEquation = null;
  12932. currentBlendSrc = null;
  12933. currentBlendDst = null;
  12934. currentBlendEquationAlpha = null;
  12935. currentBlendSrcAlpha = null;
  12936. currentBlendDstAlpha = null;
  12937. currentPremultipledAlpha = false;
  12938. currentFlipSided = null;
  12939. currentCullFace = null;
  12940. currentlineWidth = null;
  12941. currentPolygonOffsetFactor = null;
  12942. currentPolygonOffsetUnits = null;
  12943. colorBuffer.reset();
  12944. depthBuffer.reset();
  12945. stencilBuffer.reset();
  12946. }
  12947. return {
  12948. buffers: {
  12949. color: colorBuffer,
  12950. depth: depthBuffer,
  12951. stencil: stencilBuffer
  12952. },
  12953. enable: enable,
  12954. disable: disable,
  12955. useProgram: useProgram,
  12956. setBlending: setBlending,
  12957. setMaterial: setMaterial,
  12958. setFlipSided: setFlipSided,
  12959. setCullFace: setCullFace,
  12960. setlineWidth: setlineWidth,
  12961. setPolygonOffset: setPolygonOffset,
  12962. setScissorTest: setScissorTest,
  12963. activeTexture: activeTexture,
  12964. bindTexture: bindTexture,
  12965. unbindTexture: unbindTexture,
  12966. compressedTexImage2D: compressedTexImage2D,
  12967. texImage2D: texImage2D,
  12968. texImage3D: texImage3D,
  12969. scissor: scissor,
  12970. viewport: viewport,
  12971. reset: reset
  12972. };
  12973. }
  12974. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  12975. const isWebGL2 = capabilities.isWebGL2;
  12976. const maxTextures = capabilities.maxTextures;
  12977. const maxCubemapSize = capabilities.maxCubemapSize;
  12978. const maxTextureSize = capabilities.maxTextureSize;
  12979. const maxSamples = capabilities.maxSamples;
  12980. const _videoTextures = new WeakMap();
  12981. let _canvas;
  12982. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12983. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  12984. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  12985. let useOffscreenCanvas = false;
  12986. try {
  12987. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  12988. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  12989. } catch ( err ) {
  12990. // Ignore any errors
  12991. }
  12992. function createCanvas( width, height ) {
  12993. // Use OffscreenCanvas when available. Specially needed in web workers
  12994. return useOffscreenCanvas ?
  12995. new OffscreenCanvas( width, height ) :
  12996. document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  12997. }
  12998. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  12999. let scale = 1;
  13000. // handle case if texture exceeds max size
  13001. if ( image.width > maxSize || image.height > maxSize ) {
  13002. scale = maxSize / Math.max( image.width, image.height );
  13003. }
  13004. // only perform resize if necessary
  13005. if ( scale < 1 || needsPowerOfTwo === true ) {
  13006. // only perform resize for certain image types
  13007. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13008. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13009. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13010. const floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
  13011. const width = floor( scale * image.width );
  13012. const height = floor( scale * image.height );
  13013. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13014. // cube textures can't reuse the same canvas
  13015. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13016. canvas.width = width;
  13017. canvas.height = height;
  13018. const context = canvas.getContext( '2d' );
  13019. context.drawImage( image, 0, 0, width, height );
  13020. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13021. return canvas;
  13022. } else {
  13023. if ( 'data' in image ) {
  13024. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13025. }
  13026. return image;
  13027. }
  13028. }
  13029. return image;
  13030. }
  13031. function isPowerOfTwo( image ) {
  13032. return MathUtils.isPowerOfTwo( image.width ) && MathUtils.isPowerOfTwo( image.height );
  13033. }
  13034. function textureNeedsPowerOfTwo( texture ) {
  13035. if ( isWebGL2 ) return false;
  13036. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13037. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13038. }
  13039. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13040. return texture.generateMipmaps && supportsMips &&
  13041. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13042. }
  13043. function generateMipmap( target, texture, width, height ) {
  13044. _gl.generateMipmap( target );
  13045. const textureProperties = properties.get( texture );
  13046. // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  13047. textureProperties.__maxMipLevel = Math.log( Math.max( width, height ) ) * Math.LOG2E;
  13048. }
  13049. function getInternalFormat( internalFormatName, glFormat, glType ) {
  13050. if ( isWebGL2 === false ) return glFormat;
  13051. if ( internalFormatName !== null ) {
  13052. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13053. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13054. }
  13055. let internalFormat = glFormat;
  13056. if ( glFormat === 6403 ) {
  13057. if ( glType === 5126 ) internalFormat = 33326;
  13058. if ( glType === 5131 ) internalFormat = 33325;
  13059. if ( glType === 5121 ) internalFormat = 33321;
  13060. }
  13061. if ( glFormat === 6407 ) {
  13062. if ( glType === 5126 ) internalFormat = 34837;
  13063. if ( glType === 5131 ) internalFormat = 34843;
  13064. if ( glType === 5121 ) internalFormat = 32849;
  13065. }
  13066. if ( glFormat === 6408 ) {
  13067. if ( glType === 5126 ) internalFormat = 34836;
  13068. if ( glType === 5131 ) internalFormat = 34842;
  13069. if ( glType === 5121 ) internalFormat = 32856;
  13070. }
  13071. if ( internalFormat === 33325 || internalFormat === 33326 ||
  13072. internalFormat === 34842 || internalFormat === 34836 ) {
  13073. extensions.get( 'EXT_color_buffer_float' );
  13074. }
  13075. return internalFormat;
  13076. }
  13077. // Fallback filters for non-power-of-2 textures
  13078. function filterFallback( f ) {
  13079. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13080. return 9728;
  13081. }
  13082. return 9729;
  13083. }
  13084. //
  13085. function onTextureDispose( event ) {
  13086. const texture = event.target;
  13087. texture.removeEventListener( 'dispose', onTextureDispose );
  13088. deallocateTexture( texture );
  13089. if ( texture.isVideoTexture ) {
  13090. _videoTextures.delete( texture );
  13091. }
  13092. info.memory.textures --;
  13093. }
  13094. function onRenderTargetDispose( event ) {
  13095. const renderTarget = event.target;
  13096. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13097. deallocateRenderTarget( renderTarget );
  13098. info.memory.textures --;
  13099. }
  13100. //
  13101. function deallocateTexture( texture ) {
  13102. const textureProperties = properties.get( texture );
  13103. if ( textureProperties.__webglInit === undefined ) return;
  13104. _gl.deleteTexture( textureProperties.__webglTexture );
  13105. properties.remove( texture );
  13106. }
  13107. function deallocateRenderTarget( renderTarget ) {
  13108. const renderTargetProperties = properties.get( renderTarget );
  13109. const textureProperties = properties.get( renderTarget.texture );
  13110. if ( ! renderTarget ) return;
  13111. if ( textureProperties.__webglTexture !== undefined ) {
  13112. _gl.deleteTexture( textureProperties.__webglTexture );
  13113. }
  13114. if ( renderTarget.depthTexture ) {
  13115. renderTarget.depthTexture.dispose();
  13116. }
  13117. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13118. for ( let i = 0; i < 6; i ++ ) {
  13119. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13120. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13121. }
  13122. } else {
  13123. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13124. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13125. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13126. if ( renderTargetProperties.__webglColorRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer );
  13127. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13128. }
  13129. properties.remove( renderTarget.texture );
  13130. properties.remove( renderTarget );
  13131. }
  13132. //
  13133. let textureUnits = 0;
  13134. function resetTextureUnits() {
  13135. textureUnits = 0;
  13136. }
  13137. function allocateTextureUnit() {
  13138. const textureUnit = textureUnits;
  13139. if ( textureUnit >= maxTextures ) {
  13140. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13141. }
  13142. textureUnits += 1;
  13143. return textureUnit;
  13144. }
  13145. //
  13146. function setTexture2D( texture, slot ) {
  13147. const textureProperties = properties.get( texture );
  13148. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  13149. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13150. const image = texture.image;
  13151. if ( image === undefined ) {
  13152. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined' );
  13153. } else if ( image.complete === false ) {
  13154. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  13155. } else {
  13156. uploadTexture( textureProperties, texture, slot );
  13157. return;
  13158. }
  13159. }
  13160. state.activeTexture( 33984 + slot );
  13161. state.bindTexture( 3553, textureProperties.__webglTexture );
  13162. }
  13163. function setTexture2DArray( texture, slot ) {
  13164. const textureProperties = properties.get( texture );
  13165. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13166. uploadTexture( textureProperties, texture, slot );
  13167. return;
  13168. }
  13169. state.activeTexture( 33984 + slot );
  13170. state.bindTexture( 35866, textureProperties.__webglTexture );
  13171. }
  13172. function setTexture3D( texture, slot ) {
  13173. const textureProperties = properties.get( texture );
  13174. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13175. uploadTexture( textureProperties, texture, slot );
  13176. return;
  13177. }
  13178. state.activeTexture( 33984 + slot );
  13179. state.bindTexture( 32879, textureProperties.__webglTexture );
  13180. }
  13181. function setTextureCube( texture, slot ) {
  13182. const textureProperties = properties.get( texture );
  13183. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13184. uploadCubeTexture( textureProperties, texture, slot );
  13185. return;
  13186. }
  13187. state.activeTexture( 33984 + slot );
  13188. state.bindTexture( 34067, textureProperties.__webglTexture );
  13189. }
  13190. const wrappingToGL = {
  13191. [ RepeatWrapping ]: 10497,
  13192. [ ClampToEdgeWrapping ]: 33071,
  13193. [ MirroredRepeatWrapping ]: 33648
  13194. };
  13195. const filterToGL = {
  13196. [ NearestFilter ]: 9728,
  13197. [ NearestMipmapNearestFilter ]: 9984,
  13198. [ NearestMipmapLinearFilter ]: 9986,
  13199. [ LinearFilter ]: 9729,
  13200. [ LinearMipmapNearestFilter ]: 9985,
  13201. [ LinearMipmapLinearFilter ]: 9987
  13202. };
  13203. function setTextureParameters( textureType, texture, supportsMips ) {
  13204. if ( supportsMips ) {
  13205. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  13206. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  13207. if ( textureType === 32879 || textureType === 35866 ) {
  13208. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  13209. }
  13210. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  13211. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  13212. } else {
  13213. _gl.texParameteri( textureType, 10242, 33071 );
  13214. _gl.texParameteri( textureType, 10243, 33071 );
  13215. if ( textureType === 32879 || textureType === 35866 ) {
  13216. _gl.texParameteri( textureType, 32882, 33071 );
  13217. }
  13218. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  13219. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  13220. }
  13221. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  13222. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  13223. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  13224. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  13225. }
  13226. }
  13227. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13228. if ( extension ) {
  13229. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  13230. if ( texture.type === HalfFloatType && ( isWebGL2 || extensions.get( 'OES_texture_half_float_linear' ) ) === null ) return;
  13231. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  13232. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  13233. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  13234. }
  13235. }
  13236. }
  13237. function initTexture( textureProperties, texture ) {
  13238. if ( textureProperties.__webglInit === undefined ) {
  13239. textureProperties.__webglInit = true;
  13240. texture.addEventListener( 'dispose', onTextureDispose );
  13241. textureProperties.__webglTexture = _gl.createTexture();
  13242. info.memory.textures ++;
  13243. }
  13244. }
  13245. function uploadTexture( textureProperties, texture, slot ) {
  13246. let textureType = 3553;
  13247. if ( texture.isDataTexture2DArray ) textureType = 35866;
  13248. if ( texture.isDataTexture3D ) textureType = 32879;
  13249. initTexture( textureProperties, texture );
  13250. state.activeTexture( 33984 + slot );
  13251. state.bindTexture( textureType, textureProperties.__webglTexture );
  13252. _gl.pixelStorei( 37440, texture.flipY );
  13253. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  13254. _gl.pixelStorei( 3317, texture.unpackAlignment );
  13255. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( texture.image ) === false;
  13256. const image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  13257. const supportsMips = isPowerOfTwo( image ) || isWebGL2,
  13258. glFormat = utils.convert( texture.format );
  13259. let glType = utils.convert( texture.type ),
  13260. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  13261. setTextureParameters( textureType, texture, supportsMips );
  13262. let mipmap;
  13263. const mipmaps = texture.mipmaps;
  13264. if ( texture.isDepthTexture ) {
  13265. // populate depth texture with dummy data
  13266. glInternalFormat = 6402;
  13267. if ( isWebGL2 ) {
  13268. if ( texture.type === FloatType ) {
  13269. glInternalFormat = 36012;
  13270. } else if ( texture.type === UnsignedIntType ) {
  13271. glInternalFormat = 33190;
  13272. } else if ( texture.type === UnsignedInt248Type$1 ) {
  13273. glInternalFormat = 35056;
  13274. } else {
  13275. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  13276. }
  13277. } else {
  13278. if ( texture.type === FloatType ) {
  13279. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  13280. }
  13281. }
  13282. // validation checks for WebGL 1
  13283. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  13284. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13285. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13286. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13287. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  13288. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  13289. texture.type = UnsignedShortType;
  13290. glType = utils.convert( texture.type );
  13291. }
  13292. }
  13293. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  13294. // Depth stencil textures need the DEPTH_STENCIL internal format
  13295. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13296. glInternalFormat = 34041;
  13297. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13298. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13299. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13300. if ( texture.type !== UnsignedInt248Type$1 ) {
  13301. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  13302. texture.type = UnsignedInt248Type$1;
  13303. glType = utils.convert( texture.type );
  13304. }
  13305. }
  13306. //
  13307. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  13308. } else if ( texture.isDataTexture ) {
  13309. // use manually created mipmaps if available
  13310. // if there are no manual mipmaps
  13311. // set 0 level mipmap and then use GL to generate other mipmap levels
  13312. if ( mipmaps.length > 0 && supportsMips ) {
  13313. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13314. mipmap = mipmaps[ i ];
  13315. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13316. }
  13317. texture.generateMipmaps = false;
  13318. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13319. } else {
  13320. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13321. textureProperties.__maxMipLevel = 0;
  13322. }
  13323. } else if ( texture.isCompressedTexture ) {
  13324. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13325. mipmap = mipmaps[ i ];
  13326. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  13327. if ( glFormat !== null ) {
  13328. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13329. } else {
  13330. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  13331. }
  13332. } else {
  13333. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13334. }
  13335. }
  13336. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13337. } else if ( texture.isDataTexture2DArray ) {
  13338. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13339. textureProperties.__maxMipLevel = 0;
  13340. } else if ( texture.isDataTexture3D ) {
  13341. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13342. textureProperties.__maxMipLevel = 0;
  13343. } else {
  13344. // regular Texture (image, video, canvas)
  13345. // use manually created mipmaps if available
  13346. // if there are no manual mipmaps
  13347. // set 0 level mipmap and then use GL to generate other mipmap levels
  13348. if ( mipmaps.length > 0 && supportsMips ) {
  13349. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13350. mipmap = mipmaps[ i ];
  13351. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  13352. }
  13353. texture.generateMipmaps = false;
  13354. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13355. } else {
  13356. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  13357. textureProperties.__maxMipLevel = 0;
  13358. }
  13359. }
  13360. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13361. generateMipmap( textureType, texture, image.width, image.height );
  13362. }
  13363. textureProperties.__version = texture.version;
  13364. if ( texture.onUpdate ) texture.onUpdate( texture );
  13365. }
  13366. function uploadCubeTexture( textureProperties, texture, slot ) {
  13367. if ( texture.image.length !== 6 ) return;
  13368. initTexture( textureProperties, texture );
  13369. state.activeTexture( 33984 + slot );
  13370. state.bindTexture( 34067, textureProperties.__webglTexture );
  13371. _gl.pixelStorei( 37440, texture.flipY );
  13372. const isCompressed = ( texture && ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture ) );
  13373. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  13374. const cubeImage = [];
  13375. for ( let i = 0; i < 6; i ++ ) {
  13376. if ( ! isCompressed && ! isDataTexture ) {
  13377. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  13378. } else {
  13379. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  13380. }
  13381. }
  13382. const image = cubeImage[ 0 ],
  13383. supportsMips = isPowerOfTwo( image ) || isWebGL2,
  13384. glFormat = utils.convert( texture.format ),
  13385. glType = utils.convert( texture.type ),
  13386. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType );
  13387. setTextureParameters( 34067, texture, supportsMips );
  13388. let mipmaps;
  13389. if ( isCompressed ) {
  13390. for ( let i = 0; i < 6; i ++ ) {
  13391. mipmaps = cubeImage[ i ].mipmaps;
  13392. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13393. const mipmap = mipmaps[ j ];
  13394. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  13395. if ( glFormat !== null ) {
  13396. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13397. } else {
  13398. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  13399. }
  13400. } else {
  13401. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13402. }
  13403. }
  13404. }
  13405. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13406. } else {
  13407. mipmaps = texture.mipmaps;
  13408. for ( let i = 0; i < 6; i ++ ) {
  13409. if ( isDataTexture ) {
  13410. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  13411. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13412. const mipmap = mipmaps[ j ];
  13413. const mipmapImage = mipmap.image[ i ].image;
  13414. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  13415. }
  13416. } else {
  13417. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  13418. for ( let j = 0; j < mipmaps.length; j ++ ) {
  13419. const mipmap = mipmaps[ j ];
  13420. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  13421. }
  13422. }
  13423. }
  13424. textureProperties.__maxMipLevel = mipmaps.length;
  13425. }
  13426. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13427. // We assume images for cube map have the same size.
  13428. generateMipmap( 34067, texture, image.width, image.height );
  13429. }
  13430. textureProperties.__version = texture.version;
  13431. if ( texture.onUpdate ) texture.onUpdate( texture );
  13432. }
  13433. // Render targets
  13434. // Setup storage for target texture and bind it to correct framebuffer
  13435. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  13436. const glFormat = utils.convert( renderTarget.texture.format );
  13437. const glType = utils.convert( renderTarget.texture.type );
  13438. const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  13439. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13440. _gl.bindFramebuffer( 36160, framebuffer );
  13441. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  13442. _gl.bindFramebuffer( 36160, null );
  13443. }
  13444. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13445. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  13446. _gl.bindRenderbuffer( 36161, renderbuffer );
  13447. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13448. let glInternalFormat = 33189;
  13449. if ( isMultisample ) {
  13450. const depthTexture = renderTarget.depthTexture;
  13451. if ( depthTexture && depthTexture.isDepthTexture ) {
  13452. if ( depthTexture.type === FloatType ) {
  13453. glInternalFormat = 36012;
  13454. } else if ( depthTexture.type === UnsignedIntType ) {
  13455. glInternalFormat = 33190;
  13456. }
  13457. }
  13458. const samples = getRenderTargetSamples( renderTarget );
  13459. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13460. } else {
  13461. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  13462. }
  13463. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  13464. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13465. if ( isMultisample ) {
  13466. const samples = getRenderTargetSamples( renderTarget );
  13467. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  13468. } else {
  13469. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  13470. }
  13471. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  13472. } else {
  13473. const glFormat = utils.convert( renderTarget.texture.format );
  13474. const glType = utils.convert( renderTarget.texture.type );
  13475. const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  13476. if ( isMultisample ) {
  13477. const samples = getRenderTargetSamples( renderTarget );
  13478. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13479. } else {
  13480. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  13481. }
  13482. }
  13483. _gl.bindRenderbuffer( 36161, null );
  13484. }
  13485. // Setup resources for a Depth Texture for a FBO (needs an extension)
  13486. function setupDepthTexture( framebuffer, renderTarget ) {
  13487. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  13488. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  13489. _gl.bindFramebuffer( 36160, framebuffer );
  13490. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  13491. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  13492. }
  13493. // upload an empty depth texture with framebuffer size
  13494. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  13495. renderTarget.depthTexture.image.width !== renderTarget.width ||
  13496. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  13497. renderTarget.depthTexture.image.width = renderTarget.width;
  13498. renderTarget.depthTexture.image.height = renderTarget.height;
  13499. renderTarget.depthTexture.needsUpdate = true;
  13500. }
  13501. setTexture2D( renderTarget.depthTexture, 0 );
  13502. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  13503. if ( renderTarget.depthTexture.format === DepthFormat ) {
  13504. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  13505. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  13506. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  13507. } else {
  13508. throw new Error( 'Unknown depthTexture format' );
  13509. }
  13510. }
  13511. // Setup GL resources for a non-texture depth buffer
  13512. function setupDepthRenderbuffer( renderTarget ) {
  13513. const renderTargetProperties = properties.get( renderTarget );
  13514. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  13515. if ( renderTarget.depthTexture ) {
  13516. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  13517. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  13518. } else {
  13519. if ( isCube ) {
  13520. renderTargetProperties.__webglDepthbuffer = [];
  13521. for ( let i = 0; i < 6; i ++ ) {
  13522. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  13523. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  13524. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  13525. }
  13526. } else {
  13527. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  13528. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13529. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  13530. }
  13531. }
  13532. _gl.bindFramebuffer( 36160, null );
  13533. }
  13534. // Set up GL resources for the render target
  13535. function setupRenderTarget( renderTarget ) {
  13536. const renderTargetProperties = properties.get( renderTarget );
  13537. const textureProperties = properties.get( renderTarget.texture );
  13538. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  13539. textureProperties.__webglTexture = _gl.createTexture();
  13540. info.memory.textures ++;
  13541. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  13542. const isMultisample = ( renderTarget.isWebGLMultisampleRenderTarget === true );
  13543. const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
  13544. // Handles WebGL2 RGBFormat fallback - #18858
  13545. if ( isWebGL2 && renderTarget.texture.format === RGBFormat && ( renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType ) ) {
  13546. renderTarget.texture.format = RGBAFormat;
  13547. console.warn( 'THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.' );
  13548. }
  13549. // Setup framebuffer
  13550. if ( isCube ) {
  13551. renderTargetProperties.__webglFramebuffer = [];
  13552. for ( let i = 0; i < 6; i ++ ) {
  13553. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13554. }
  13555. } else {
  13556. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13557. if ( isMultisample ) {
  13558. if ( isWebGL2 ) {
  13559. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13560. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13561. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer );
  13562. const glFormat = utils.convert( renderTarget.texture.format );
  13563. const glType = utils.convert( renderTarget.texture.type );
  13564. const glInternalFormat = getInternalFormat( renderTarget.texture.internalFormat, glFormat, glType );
  13565. const samples = getRenderTargetSamples( renderTarget );
  13566. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  13567. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  13568. _gl.framebufferRenderbuffer( 36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer );
  13569. _gl.bindRenderbuffer( 36161, null );
  13570. if ( renderTarget.depthBuffer ) {
  13571. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13572. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  13573. }
  13574. _gl.bindFramebuffer( 36160, null );
  13575. } else {
  13576. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  13577. }
  13578. }
  13579. }
  13580. // Setup color buffer
  13581. if ( isCube ) {
  13582. state.bindTexture( 34067, textureProperties.__webglTexture );
  13583. setTextureParameters( 34067, renderTarget.texture, supportsMips );
  13584. for ( let i = 0; i < 6; i ++ ) {
  13585. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, 36064, 34069 + i );
  13586. }
  13587. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  13588. generateMipmap( 34067, renderTarget.texture, renderTarget.width, renderTarget.height );
  13589. }
  13590. state.bindTexture( 34067, null );
  13591. } else {
  13592. state.bindTexture( 3553, textureProperties.__webglTexture );
  13593. setTextureParameters( 3553, renderTarget.texture, supportsMips );
  13594. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553 );
  13595. if ( textureNeedsGenerateMipmaps( renderTarget.texture, supportsMips ) ) {
  13596. generateMipmap( 3553, renderTarget.texture, renderTarget.width, renderTarget.height );
  13597. }
  13598. state.bindTexture( 3553, null );
  13599. }
  13600. // Setup depth and stencil buffers
  13601. if ( renderTarget.depthBuffer ) {
  13602. setupDepthRenderbuffer( renderTarget );
  13603. }
  13604. }
  13605. function updateRenderTargetMipmap( renderTarget ) {
  13606. const texture = renderTarget.texture;
  13607. const supportsMips = isPowerOfTwo( renderTarget ) || isWebGL2;
  13608. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13609. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  13610. const webglTexture = properties.get( texture ).__webglTexture;
  13611. state.bindTexture( target, webglTexture );
  13612. generateMipmap( target, texture, renderTarget.width, renderTarget.height );
  13613. state.bindTexture( target, null );
  13614. }
  13615. }
  13616. function updateMultisampleRenderTarget( renderTarget ) {
  13617. if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  13618. if ( isWebGL2 ) {
  13619. const renderTargetProperties = properties.get( renderTarget );
  13620. _gl.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  13621. _gl.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  13622. const width = renderTarget.width;
  13623. const height = renderTarget.height;
  13624. let mask = 16384;
  13625. if ( renderTarget.depthBuffer ) mask |= 256;
  13626. if ( renderTarget.stencilBuffer ) mask |= 1024;
  13627. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  13628. _gl.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer ); // see #18905
  13629. } else {
  13630. console.warn( 'THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.' );
  13631. }
  13632. }
  13633. }
  13634. function getRenderTargetSamples( renderTarget ) {
  13635. return ( isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ) ?
  13636. Math.min( maxSamples, renderTarget.samples ) : 0;
  13637. }
  13638. function updateVideoTexture( texture ) {
  13639. const frame = info.render.frame;
  13640. // Check the last frame we updated the VideoTexture
  13641. if ( _videoTextures.get( texture ) !== frame ) {
  13642. _videoTextures.set( texture, frame );
  13643. texture.update();
  13644. }
  13645. }
  13646. // backwards compatibility
  13647. let warnedTexture2D = false;
  13648. let warnedTextureCube = false;
  13649. function safeSetTexture2D( texture, slot ) {
  13650. if ( texture && texture.isWebGLRenderTarget ) {
  13651. if ( warnedTexture2D === false ) {
  13652. console.warn( 'THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.' );
  13653. warnedTexture2D = true;
  13654. }
  13655. texture = texture.texture;
  13656. }
  13657. setTexture2D( texture, slot );
  13658. }
  13659. function safeSetTextureCube( texture, slot ) {
  13660. if ( texture && texture.isWebGLCubeRenderTarget ) {
  13661. if ( warnedTextureCube === false ) {
  13662. console.warn( 'THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.' );
  13663. warnedTextureCube = true;
  13664. }
  13665. texture = texture.texture;
  13666. }
  13667. setTextureCube( texture, slot );
  13668. }
  13669. //
  13670. this.allocateTextureUnit = allocateTextureUnit;
  13671. this.resetTextureUnits = resetTextureUnits;
  13672. this.setTexture2D = setTexture2D;
  13673. this.setTexture2DArray = setTexture2DArray;
  13674. this.setTexture3D = setTexture3D;
  13675. this.setTextureCube = setTextureCube;
  13676. this.setupRenderTarget = setupRenderTarget;
  13677. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13678. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13679. this.safeSetTexture2D = safeSetTexture2D;
  13680. this.safeSetTextureCube = safeSetTextureCube;
  13681. }
  13682. function WebGLUtils( gl, extensions, capabilities ) {
  13683. const isWebGL2 = capabilities.isWebGL2;
  13684. function convert( p ) {
  13685. let extension;
  13686. if ( p === UnsignedByteType ) return 5121;
  13687. if ( p === UnsignedShort4444Type ) return 32819;
  13688. if ( p === UnsignedShort5551Type ) return 32820;
  13689. if ( p === UnsignedShort565Type ) return 33635;
  13690. if ( p === ByteType ) return 5120;
  13691. if ( p === ShortType ) return 5122;
  13692. if ( p === UnsignedShortType ) return 5123;
  13693. if ( p === IntType ) return 5124;
  13694. if ( p === UnsignedIntType ) return 5125;
  13695. if ( p === FloatType ) return 5126;
  13696. if ( p === HalfFloatType ) {
  13697. if ( isWebGL2 ) return 5131;
  13698. extension = extensions.get( 'OES_texture_half_float' );
  13699. if ( extension !== null ) {
  13700. return extension.HALF_FLOAT_OES;
  13701. } else {
  13702. return null;
  13703. }
  13704. }
  13705. if ( p === AlphaFormat ) return 6406;
  13706. if ( p === RGBFormat ) return 6407;
  13707. if ( p === RGBAFormat ) return 6408;
  13708. if ( p === LuminanceFormat ) return 6409;
  13709. if ( p === LuminanceAlphaFormat ) return 6410;
  13710. if ( p === DepthFormat ) return 6402;
  13711. if ( p === DepthStencilFormat ) return 34041;
  13712. if ( p === RedFormat ) return 6403;
  13713. // WebGL2 formats.
  13714. if ( p === RedIntegerFormat ) return 36244;
  13715. if ( p === RGFormat ) return 33319;
  13716. if ( p === RGIntegerFormat ) return 33320;
  13717. if ( p === RGBIntegerFormat ) return 36248;
  13718. if ( p === RGBAIntegerFormat ) return 36249;
  13719. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format$1 ||
  13720. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format$1 ) {
  13721. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13722. if ( extension !== null ) {
  13723. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13724. if ( p === RGBA_S3TC_DXT1_Format$1 ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13725. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13726. if ( p === RGBA_S3TC_DXT5_Format$1 ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13727. } else {
  13728. return null;
  13729. }
  13730. }
  13731. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  13732. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  13733. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13734. if ( extension !== null ) {
  13735. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13736. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13737. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13738. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13739. } else {
  13740. return null;
  13741. }
  13742. }
  13743. if ( p === RGB_ETC1_Format ) {
  13744. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  13745. if ( extension !== null ) {
  13746. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13747. } else {
  13748. return null;
  13749. }
  13750. }
  13751. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  13752. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  13753. if ( extension !== null ) {
  13754. if ( p === RGB_ETC2_Format ) return extension.COMPRESSED_RGB8_ETC2;
  13755. if ( p === RGBA_ETC2_EAC_Format ) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13756. }
  13757. }
  13758. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  13759. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  13760. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  13761. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  13762. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ||
  13763. p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format ||
  13764. p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format ||
  13765. p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format ||
  13766. p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format ||
  13767. p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format ) {
  13768. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  13769. if ( extension !== null ) {
  13770. // TODO Complete?
  13771. return p;
  13772. } else {
  13773. return null;
  13774. }
  13775. }
  13776. if ( p === RGBA_BPTC_Format ) {
  13777. extension = extensions.get( 'EXT_texture_compression_bptc' );
  13778. if ( extension !== null ) {
  13779. // TODO Complete?
  13780. return p;
  13781. } else {
  13782. return null;
  13783. }
  13784. }
  13785. if ( p === UnsignedInt248Type$1 ) {
  13786. if ( isWebGL2 ) return 34042;
  13787. extension = extensions.get( 'WEBGL_depth_texture' );
  13788. if ( extension !== null ) {
  13789. return extension.UNSIGNED_INT_24_8_WEBGL;
  13790. } else {
  13791. return null;
  13792. }
  13793. }
  13794. }
  13795. return { convert: convert };
  13796. }
  13797. function ArrayCamera( array = [] ) {
  13798. PerspectiveCamera.call( this );
  13799. this.cameras = array;
  13800. }
  13801. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  13802. constructor: ArrayCamera,
  13803. isArrayCamera: true
  13804. } );
  13805. function Group() {
  13806. Object3D.call( this );
  13807. this.type = 'Group';
  13808. }
  13809. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13810. constructor: Group,
  13811. isGroup: true
  13812. } );
  13813. function WebXRController() {
  13814. this._targetRay = null;
  13815. this._grip = null;
  13816. this._hand = null;
  13817. }
  13818. Object.assign( WebXRController.prototype, {
  13819. constructor: WebXRController,
  13820. getHandSpace: function () {
  13821. if ( this._hand === null ) {
  13822. this._hand = new Group();
  13823. this._hand.matrixAutoUpdate = false;
  13824. this._hand.visible = false;
  13825. this._hand.joints = [];
  13826. this._hand.inputState = { pinching: false };
  13827. if ( window.XRHand ) {
  13828. for ( let i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i ++ ) {
  13829. // The transform of this joint will be updated with the joint pose on each frame
  13830. const joint = new Group();
  13831. joint.matrixAutoUpdate = false;
  13832. joint.visible = false;
  13833. this._hand.joints.push( joint );
  13834. // ??
  13835. this._hand.add( joint );
  13836. }
  13837. }
  13838. }
  13839. return this._hand;
  13840. },
  13841. getTargetRaySpace: function () {
  13842. if ( this._targetRay === null ) {
  13843. this._targetRay = new Group();
  13844. this._targetRay.matrixAutoUpdate = false;
  13845. this._targetRay.visible = false;
  13846. }
  13847. return this._targetRay;
  13848. },
  13849. getGripSpace: function () {
  13850. if ( this._grip === null ) {
  13851. this._grip = new Group();
  13852. this._grip.matrixAutoUpdate = false;
  13853. this._grip.visible = false;
  13854. }
  13855. return this._grip;
  13856. },
  13857. dispatchEvent: function ( event ) {
  13858. if ( this._targetRay !== null ) {
  13859. this._targetRay.dispatchEvent( event );
  13860. }
  13861. if ( this._grip !== null ) {
  13862. this._grip.dispatchEvent( event );
  13863. }
  13864. if ( this._hand !== null ) {
  13865. this._hand.dispatchEvent( event );
  13866. }
  13867. return this;
  13868. },
  13869. disconnect: function ( inputSource ) {
  13870. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  13871. if ( this._targetRay !== null ) {
  13872. this._targetRay.visible = false;
  13873. }
  13874. if ( this._grip !== null ) {
  13875. this._grip.visible = false;
  13876. }
  13877. if ( this._hand !== null ) {
  13878. this._hand.visible = false;
  13879. }
  13880. return this;
  13881. },
  13882. update: function ( inputSource, frame, referenceSpace ) {
  13883. let inputPose = null;
  13884. let gripPose = null;
  13885. let handPose = null;
  13886. const targetRay = this._targetRay;
  13887. const grip = this._grip;
  13888. const hand = this._hand;
  13889. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  13890. if ( hand && inputSource.hand ) {
  13891. handPose = true;
  13892. for ( let i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i ++ ) {
  13893. if ( inputSource.hand[ i ] ) {
  13894. // Update the joints groups with the XRJoint poses
  13895. const jointPose = frame.getJointPose( inputSource.hand[ i ], referenceSpace );
  13896. const joint = hand.joints[ i ];
  13897. if ( jointPose !== null ) {
  13898. joint.matrix.fromArray( jointPose.transform.matrix );
  13899. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  13900. joint.jointRadius = jointPose.radius;
  13901. }
  13902. joint.visible = jointPose !== null;
  13903. // Custom events
  13904. // Check pinch
  13905. const indexTip = hand.joints[ window.XRHand.INDEX_PHALANX_TIP ];
  13906. const thumbTip = hand.joints[ window.XRHand.THUMB_PHALANX_TIP ];
  13907. const distance = indexTip.position.distanceTo( thumbTip.position );
  13908. const distanceToPinch = 0.02;
  13909. const threshold = 0.005;
  13910. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  13911. hand.inputState.pinching = false;
  13912. this.dispatchEvent( {
  13913. type: 'pinchend',
  13914. handedness: inputSource.handedness,
  13915. target: this
  13916. } );
  13917. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  13918. hand.inputState.pinching = true;
  13919. this.dispatchEvent( {
  13920. type: 'pinchstart',
  13921. handedness: inputSource.handedness,
  13922. target: this
  13923. } );
  13924. }
  13925. }
  13926. }
  13927. } else {
  13928. if ( targetRay !== null ) {
  13929. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  13930. if ( inputPose !== null ) {
  13931. targetRay.matrix.fromArray( inputPose.transform.matrix );
  13932. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  13933. }
  13934. }
  13935. if ( grip !== null && inputSource.gripSpace ) {
  13936. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  13937. if ( gripPose !== null ) {
  13938. grip.matrix.fromArray( gripPose.transform.matrix );
  13939. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  13940. }
  13941. }
  13942. }
  13943. }
  13944. if ( targetRay !== null ) {
  13945. targetRay.visible = ( inputPose !== null );
  13946. }
  13947. if ( grip !== null ) {
  13948. grip.visible = ( gripPose !== null );
  13949. }
  13950. if ( hand !== null ) {
  13951. hand.visible = ( handPose !== null );
  13952. }
  13953. return this;
  13954. }
  13955. } );
  13956. function WebXRManager( renderer, gl ) {
  13957. const scope = this;
  13958. let session = null;
  13959. let framebufferScaleFactor = 1.0;
  13960. let referenceSpace = null;
  13961. let referenceSpaceType = 'local-floor';
  13962. let pose = null;
  13963. const controllers = [];
  13964. const inputSourcesMap = new Map();
  13965. //
  13966. const cameraL = new PerspectiveCamera();
  13967. cameraL.layers.enable( 1 );
  13968. cameraL.viewport = new Vector4();
  13969. const cameraR = new PerspectiveCamera();
  13970. cameraR.layers.enable( 2 );
  13971. cameraR.viewport = new Vector4();
  13972. const cameras = [ cameraL, cameraR ];
  13973. const cameraVR = new ArrayCamera();
  13974. cameraVR.layers.enable( 1 );
  13975. cameraVR.layers.enable( 2 );
  13976. let _currentDepthNear = null;
  13977. let _currentDepthFar = null;
  13978. //
  13979. this.enabled = false;
  13980. this.isPresenting = false;
  13981. this.getController = function ( index ) {
  13982. let controller = controllers[ index ];
  13983. if ( controller === undefined ) {
  13984. controller = new WebXRController();
  13985. controllers[ index ] = controller;
  13986. }
  13987. return controller.getTargetRaySpace();
  13988. };
  13989. this.getControllerGrip = function ( index ) {
  13990. let controller = controllers[ index ];
  13991. if ( controller === undefined ) {
  13992. controller = new WebXRController();
  13993. controllers[ index ] = controller;
  13994. }
  13995. return controller.getGripSpace();
  13996. };
  13997. this.getHand = function ( index ) {
  13998. let controller = controllers[ index ];
  13999. if ( controller === undefined ) {
  14000. controller = new WebXRController();
  14001. controllers[ index ] = controller;
  14002. }
  14003. return controller.getHandSpace();
  14004. };
  14005. //
  14006. function onSessionEvent( event ) {
  14007. const controller = inputSourcesMap.get( event.inputSource );
  14008. if ( controller ) {
  14009. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  14010. }
  14011. }
  14012. function onSessionEnd() {
  14013. inputSourcesMap.forEach( function ( controller, inputSource ) {
  14014. controller.disconnect( inputSource );
  14015. } );
  14016. inputSourcesMap.clear();
  14017. //
  14018. renderer.setFramebuffer( null );
  14019. renderer.setRenderTarget( renderer.getRenderTarget() ); // Hack #15830
  14020. animation.stop();
  14021. scope.isPresenting = false;
  14022. scope.dispatchEvent( { type: 'sessionend' } );
  14023. }
  14024. function onRequestReferenceSpace( value ) {
  14025. referenceSpace = value;
  14026. animation.setContext( session );
  14027. animation.start();
  14028. scope.isPresenting = true;
  14029. scope.dispatchEvent( { type: 'sessionstart' } );
  14030. }
  14031. this.setFramebufferScaleFactor = function ( value ) {
  14032. framebufferScaleFactor = value;
  14033. if ( scope.isPresenting === true ) {
  14034. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  14035. }
  14036. };
  14037. this.setReferenceSpaceType = function ( value ) {
  14038. referenceSpaceType = value;
  14039. if ( scope.isPresenting === true ) {
  14040. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  14041. }
  14042. };
  14043. this.getReferenceSpace = function () {
  14044. return referenceSpace;
  14045. };
  14046. this.getSession = function () {
  14047. return session;
  14048. };
  14049. this.setSession = function ( value ) {
  14050. session = value;
  14051. if ( session !== null ) {
  14052. session.addEventListener( 'select', onSessionEvent );
  14053. session.addEventListener( 'selectstart', onSessionEvent );
  14054. session.addEventListener( 'selectend', onSessionEvent );
  14055. session.addEventListener( 'squeeze', onSessionEvent );
  14056. session.addEventListener( 'squeezestart', onSessionEvent );
  14057. session.addEventListener( 'squeezeend', onSessionEvent );
  14058. session.addEventListener( 'end', onSessionEnd );
  14059. const attributes = gl.getContextAttributes();
  14060. if ( attributes.xrCompatible !== true ) {
  14061. gl.makeXRCompatible();
  14062. }
  14063. const layerInit = {
  14064. antialias: attributes.antialias,
  14065. alpha: attributes.alpha,
  14066. depth: attributes.depth,
  14067. stencil: attributes.stencil,
  14068. framebufferScaleFactor: framebufferScaleFactor
  14069. };
  14070. // eslint-disable-next-line no-undef
  14071. const baseLayer = new XRWebGLLayer( session, gl, layerInit );
  14072. session.updateRenderState( { baseLayer: baseLayer } );
  14073. session.requestReferenceSpace( referenceSpaceType ).then( onRequestReferenceSpace );
  14074. //
  14075. session.addEventListener( 'inputsourceschange', updateInputSources );
  14076. }
  14077. };
  14078. function updateInputSources( event ) {
  14079. const inputSources = session.inputSources;
  14080. // Assign inputSources to available controllers
  14081. for ( let i = 0; i < controllers.length; i ++ ) {
  14082. inputSourcesMap.set( inputSources[ i ], controllers[ i ] );
  14083. }
  14084. // Notify disconnected
  14085. for ( let i = 0; i < event.removed.length; i ++ ) {
  14086. const inputSource = event.removed[ i ];
  14087. const controller = inputSourcesMap.get( inputSource );
  14088. if ( controller ) {
  14089. controller.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14090. inputSourcesMap.delete( inputSource );
  14091. }
  14092. }
  14093. // Notify connected
  14094. for ( let i = 0; i < event.added.length; i ++ ) {
  14095. const inputSource = event.added[ i ];
  14096. const controller = inputSourcesMap.get( inputSource );
  14097. if ( controller ) {
  14098. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  14099. }
  14100. }
  14101. }
  14102. //
  14103. const cameraLPos = new Vector3();
  14104. const cameraRPos = new Vector3();
  14105. /**
  14106. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14107. * the cameras' projection and world matrices have already been set.
  14108. * And that near and far planes are identical for both cameras.
  14109. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14110. */
  14111. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  14112. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  14113. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  14114. const ipd = cameraLPos.distanceTo( cameraRPos );
  14115. const projL = cameraL.projectionMatrix.elements;
  14116. const projR = cameraR.projectionMatrix.elements;
  14117. // VR systems will have identical far and near planes, and
  14118. // most likely identical top and bottom frustum extents.
  14119. // Use the left camera for these values.
  14120. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  14121. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  14122. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  14123. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  14124. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  14125. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  14126. const left = near * leftFov;
  14127. const right = near * rightFov;
  14128. // Calculate the new camera's position offset from the
  14129. // left camera. xOffset should be roughly half `ipd`.
  14130. const zOffset = ipd / ( - leftFov + rightFov );
  14131. const xOffset = zOffset * - leftFov;
  14132. // TODO: Better way to apply this offset?
  14133. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  14134. camera.translateX( xOffset );
  14135. camera.translateZ( zOffset );
  14136. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  14137. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  14138. // Find the union of the frustum values of the cameras and scale
  14139. // the values so that the near plane's position does not change in world space,
  14140. // although must now be relative to the new union camera.
  14141. const near2 = near + zOffset;
  14142. const far2 = far + zOffset;
  14143. const left2 = left - xOffset;
  14144. const right2 = right + ( ipd - xOffset );
  14145. const top2 = topFov * far / far2 * near2;
  14146. const bottom2 = bottomFov * far / far2 * near2;
  14147. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  14148. }
  14149. function updateCamera( camera, parent ) {
  14150. if ( parent === null ) {
  14151. camera.matrixWorld.copy( camera.matrix );
  14152. } else {
  14153. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  14154. }
  14155. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  14156. }
  14157. this.getCamera = function ( camera ) {
  14158. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14159. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14160. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  14161. // Note that the new renderState won't apply until the next frame. See #18320
  14162. session.updateRenderState( {
  14163. depthNear: cameraVR.near,
  14164. depthFar: cameraVR.far
  14165. } );
  14166. _currentDepthNear = cameraVR.near;
  14167. _currentDepthFar = cameraVR.far;
  14168. }
  14169. const parent = camera.parent;
  14170. const cameras = cameraVR.cameras;
  14171. updateCamera( cameraVR, parent );
  14172. for ( let i = 0; i < cameras.length; i ++ ) {
  14173. updateCamera( cameras[ i ], parent );
  14174. }
  14175. // update camera and its children
  14176. camera.matrixWorld.copy( cameraVR.matrixWorld );
  14177. const children = camera.children;
  14178. for ( let i = 0, l = children.length; i < l; i ++ ) {
  14179. children[ i ].updateMatrixWorld( true );
  14180. }
  14181. // update projection matrix for proper view frustum culling
  14182. if ( cameras.length === 2 ) {
  14183. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  14184. } else {
  14185. // assume single camera setup (AR)
  14186. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  14187. }
  14188. return cameraVR;
  14189. };
  14190. // Animation Loop
  14191. let onAnimationFrameCallback = null;
  14192. function onAnimationFrame( time, frame ) {
  14193. pose = frame.getViewerPose( referenceSpace );
  14194. if ( pose !== null ) {
  14195. const views = pose.views;
  14196. const baseLayer = session.renderState.baseLayer;
  14197. renderer.setFramebuffer( baseLayer.framebuffer );
  14198. let cameraVRNeedsUpdate = false;
  14199. // check if it's necessary to rebuild cameraVR's camera list
  14200. if ( views.length !== cameraVR.cameras.length ) {
  14201. cameraVR.cameras.length = 0;
  14202. cameraVRNeedsUpdate = true;
  14203. }
  14204. for ( let i = 0; i < views.length; i ++ ) {
  14205. const view = views[ i ];
  14206. const viewport = baseLayer.getViewport( view );
  14207. const camera = cameras[ i ];
  14208. camera.matrix.fromArray( view.transform.matrix );
  14209. camera.projectionMatrix.fromArray( view.projectionMatrix );
  14210. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  14211. if ( i === 0 ) {
  14212. cameraVR.matrix.copy( camera.matrix );
  14213. }
  14214. if ( cameraVRNeedsUpdate === true ) {
  14215. cameraVR.cameras.push( camera );
  14216. }
  14217. }
  14218. }
  14219. //
  14220. const inputSources = session.inputSources;
  14221. for ( let i = 0; i < controllers.length; i ++ ) {
  14222. const controller = controllers[ i ];
  14223. const inputSource = inputSources[ i ];
  14224. controller.update( inputSource, frame, referenceSpace );
  14225. }
  14226. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  14227. }
  14228. const animation = new WebGLAnimation();
  14229. animation.setAnimationLoop( onAnimationFrame );
  14230. this.setAnimationLoop = function ( callback ) {
  14231. onAnimationFrameCallback = callback;
  14232. };
  14233. this.dispose = function () {};
  14234. }
  14235. Object.assign( WebXRManager.prototype, EventDispatcher.prototype );
  14236. function WebGLMaterials( properties ) {
  14237. function refreshFogUniforms( uniforms, fog ) {
  14238. uniforms.fogColor.value.copy( fog.color );
  14239. if ( fog.isFog ) {
  14240. uniforms.fogNear.value = fog.near;
  14241. uniforms.fogFar.value = fog.far;
  14242. } else if ( fog.isFogExp2 ) {
  14243. uniforms.fogDensity.value = fog.density;
  14244. }
  14245. }
  14246. function refreshMaterialUniforms( uniforms, material, pixelRatio, height ) {
  14247. if ( material.isMeshBasicMaterial ) {
  14248. refreshUniformsCommon( uniforms, material );
  14249. } else if ( material.isMeshLambertMaterial ) {
  14250. refreshUniformsCommon( uniforms, material );
  14251. refreshUniformsLambert( uniforms, material );
  14252. } else if ( material.isMeshToonMaterial ) {
  14253. refreshUniformsCommon( uniforms, material );
  14254. refreshUniformsToon( uniforms, material );
  14255. } else if ( material.isMeshPhongMaterial ) {
  14256. refreshUniformsCommon( uniforms, material );
  14257. refreshUniformsPhong( uniforms, material );
  14258. } else if ( material.isMeshStandardMaterial ) {
  14259. refreshUniformsCommon( uniforms, material );
  14260. if ( material.isMeshPhysicalMaterial ) {
  14261. refreshUniformsPhysical( uniforms, material );
  14262. } else {
  14263. refreshUniformsStandard( uniforms, material );
  14264. }
  14265. } else if ( material.isMeshMatcapMaterial ) {
  14266. refreshUniformsCommon( uniforms, material );
  14267. refreshUniformsMatcap( uniforms, material );
  14268. } else if ( material.isMeshDepthMaterial ) {
  14269. refreshUniformsCommon( uniforms, material );
  14270. refreshUniformsDepth( uniforms, material );
  14271. } else if ( material.isMeshDistanceMaterial ) {
  14272. refreshUniformsCommon( uniforms, material );
  14273. refreshUniformsDistance( uniforms, material );
  14274. } else if ( material.isMeshNormalMaterial ) {
  14275. refreshUniformsCommon( uniforms, material );
  14276. refreshUniformsNormal( uniforms, material );
  14277. } else if ( material.isLineBasicMaterial ) {
  14278. refreshUniformsLine( uniforms, material );
  14279. if ( material.isLineDashedMaterial ) {
  14280. refreshUniformsDash( uniforms, material );
  14281. }
  14282. } else if ( material.isPointsMaterial ) {
  14283. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  14284. } else if ( material.isSpriteMaterial ) {
  14285. refreshUniformsSprites( uniforms, material );
  14286. } else if ( material.isShadowMaterial ) {
  14287. uniforms.color.value.copy( material.color );
  14288. uniforms.opacity.value = material.opacity;
  14289. } else if ( material.isShaderMaterial ) {
  14290. material.uniformsNeedUpdate = false; // #15581
  14291. }
  14292. }
  14293. function refreshUniformsCommon( uniforms, material ) {
  14294. uniforms.opacity.value = material.opacity;
  14295. if ( material.color ) {
  14296. uniforms.diffuse.value.copy( material.color );
  14297. }
  14298. if ( material.emissive ) {
  14299. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  14300. }
  14301. if ( material.map ) {
  14302. uniforms.map.value = material.map;
  14303. }
  14304. if ( material.alphaMap ) {
  14305. uniforms.alphaMap.value = material.alphaMap;
  14306. }
  14307. if ( material.specularMap ) {
  14308. uniforms.specularMap.value = material.specularMap;
  14309. }
  14310. const envMap = properties.get( material ).envMap;
  14311. if ( envMap ) {
  14312. uniforms.envMap.value = envMap;
  14313. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap._needsFlipEnvMap ) ? - 1 : 1;
  14314. uniforms.reflectivity.value = material.reflectivity;
  14315. uniforms.refractionRatio.value = material.refractionRatio;
  14316. const maxMipLevel = properties.get( envMap ).__maxMipLevel;
  14317. if ( maxMipLevel !== undefined ) {
  14318. uniforms.maxMipLevel.value = maxMipLevel;
  14319. }
  14320. }
  14321. if ( material.lightMap ) {
  14322. uniforms.lightMap.value = material.lightMap;
  14323. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  14324. }
  14325. if ( material.aoMap ) {
  14326. uniforms.aoMap.value = material.aoMap;
  14327. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  14328. }
  14329. // uv repeat and offset setting priorities
  14330. // 1. color map
  14331. // 2. specular map
  14332. // 3. displacementMap map
  14333. // 4. normal map
  14334. // 5. bump map
  14335. // 6. roughnessMap map
  14336. // 7. metalnessMap map
  14337. // 8. alphaMap map
  14338. // 9. emissiveMap map
  14339. // 10. clearcoat map
  14340. // 11. clearcoat normal map
  14341. // 12. clearcoat roughnessMap map
  14342. let uvScaleMap;
  14343. if ( material.map ) {
  14344. uvScaleMap = material.map;
  14345. } else if ( material.specularMap ) {
  14346. uvScaleMap = material.specularMap;
  14347. } else if ( material.displacementMap ) {
  14348. uvScaleMap = material.displacementMap;
  14349. } else if ( material.normalMap ) {
  14350. uvScaleMap = material.normalMap;
  14351. } else if ( material.bumpMap ) {
  14352. uvScaleMap = material.bumpMap;
  14353. } else if ( material.roughnessMap ) {
  14354. uvScaleMap = material.roughnessMap;
  14355. } else if ( material.metalnessMap ) {
  14356. uvScaleMap = material.metalnessMap;
  14357. } else if ( material.alphaMap ) {
  14358. uvScaleMap = material.alphaMap;
  14359. } else if ( material.emissiveMap ) {
  14360. uvScaleMap = material.emissiveMap;
  14361. } else if ( material.clearcoatMap ) {
  14362. uvScaleMap = material.clearcoatMap;
  14363. } else if ( material.clearcoatNormalMap ) {
  14364. uvScaleMap = material.clearcoatNormalMap;
  14365. } else if ( material.clearcoatRoughnessMap ) {
  14366. uvScaleMap = material.clearcoatRoughnessMap;
  14367. }
  14368. if ( uvScaleMap !== undefined ) {
  14369. // backwards compatibility
  14370. if ( uvScaleMap.isWebGLRenderTarget ) {
  14371. uvScaleMap = uvScaleMap.texture;
  14372. }
  14373. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14374. uvScaleMap.updateMatrix();
  14375. }
  14376. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14377. }
  14378. // uv repeat and offset setting priorities for uv2
  14379. // 1. ao map
  14380. // 2. light map
  14381. let uv2ScaleMap;
  14382. if ( material.aoMap ) {
  14383. uv2ScaleMap = material.aoMap;
  14384. } else if ( material.lightMap ) {
  14385. uv2ScaleMap = material.lightMap;
  14386. }
  14387. if ( uv2ScaleMap !== undefined ) {
  14388. // backwards compatibility
  14389. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  14390. uv2ScaleMap = uv2ScaleMap.texture;
  14391. }
  14392. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  14393. uv2ScaleMap.updateMatrix();
  14394. }
  14395. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  14396. }
  14397. }
  14398. function refreshUniformsLine( uniforms, material ) {
  14399. uniforms.diffuse.value.copy( material.color );
  14400. uniforms.opacity.value = material.opacity;
  14401. }
  14402. function refreshUniformsDash( uniforms, material ) {
  14403. uniforms.dashSize.value = material.dashSize;
  14404. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14405. uniforms.scale.value = material.scale;
  14406. }
  14407. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  14408. uniforms.diffuse.value.copy( material.color );
  14409. uniforms.opacity.value = material.opacity;
  14410. uniforms.size.value = material.size * pixelRatio;
  14411. uniforms.scale.value = height * 0.5;
  14412. if ( material.map ) {
  14413. uniforms.map.value = material.map;
  14414. }
  14415. if ( material.alphaMap ) {
  14416. uniforms.alphaMap.value = material.alphaMap;
  14417. }
  14418. // uv repeat and offset setting priorities
  14419. // 1. color map
  14420. // 2. alpha map
  14421. let uvScaleMap;
  14422. if ( material.map ) {
  14423. uvScaleMap = material.map;
  14424. } else if ( material.alphaMap ) {
  14425. uvScaleMap = material.alphaMap;
  14426. }
  14427. if ( uvScaleMap !== undefined ) {
  14428. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14429. uvScaleMap.updateMatrix();
  14430. }
  14431. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14432. }
  14433. }
  14434. function refreshUniformsSprites( uniforms, material ) {
  14435. uniforms.diffuse.value.copy( material.color );
  14436. uniforms.opacity.value = material.opacity;
  14437. uniforms.rotation.value = material.rotation;
  14438. if ( material.map ) {
  14439. uniforms.map.value = material.map;
  14440. }
  14441. if ( material.alphaMap ) {
  14442. uniforms.alphaMap.value = material.alphaMap;
  14443. }
  14444. // uv repeat and offset setting priorities
  14445. // 1. color map
  14446. // 2. alpha map
  14447. let uvScaleMap;
  14448. if ( material.map ) {
  14449. uvScaleMap = material.map;
  14450. } else if ( material.alphaMap ) {
  14451. uvScaleMap = material.alphaMap;
  14452. }
  14453. if ( uvScaleMap !== undefined ) {
  14454. if ( uvScaleMap.matrixAutoUpdate === true ) {
  14455. uvScaleMap.updateMatrix();
  14456. }
  14457. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  14458. }
  14459. }
  14460. function refreshUniformsLambert( uniforms, material ) {
  14461. if ( material.emissiveMap ) {
  14462. uniforms.emissiveMap.value = material.emissiveMap;
  14463. }
  14464. }
  14465. function refreshUniformsPhong( uniforms, material ) {
  14466. uniforms.specular.value.copy( material.specular );
  14467. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  14468. if ( material.emissiveMap ) {
  14469. uniforms.emissiveMap.value = material.emissiveMap;
  14470. }
  14471. if ( material.bumpMap ) {
  14472. uniforms.bumpMap.value = material.bumpMap;
  14473. uniforms.bumpScale.value = material.bumpScale;
  14474. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14475. }
  14476. if ( material.normalMap ) {
  14477. uniforms.normalMap.value = material.normalMap;
  14478. uniforms.normalScale.value.copy( material.normalScale );
  14479. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14480. }
  14481. if ( material.displacementMap ) {
  14482. uniforms.displacementMap.value = material.displacementMap;
  14483. uniforms.displacementScale.value = material.displacementScale;
  14484. uniforms.displacementBias.value = material.displacementBias;
  14485. }
  14486. }
  14487. function refreshUniformsToon( uniforms, material ) {
  14488. if ( material.gradientMap ) {
  14489. uniforms.gradientMap.value = material.gradientMap;
  14490. }
  14491. if ( material.emissiveMap ) {
  14492. uniforms.emissiveMap.value = material.emissiveMap;
  14493. }
  14494. if ( material.bumpMap ) {
  14495. uniforms.bumpMap.value = material.bumpMap;
  14496. uniforms.bumpScale.value = material.bumpScale;
  14497. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14498. }
  14499. if ( material.normalMap ) {
  14500. uniforms.normalMap.value = material.normalMap;
  14501. uniforms.normalScale.value.copy( material.normalScale );
  14502. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14503. }
  14504. if ( material.displacementMap ) {
  14505. uniforms.displacementMap.value = material.displacementMap;
  14506. uniforms.displacementScale.value = material.displacementScale;
  14507. uniforms.displacementBias.value = material.displacementBias;
  14508. }
  14509. }
  14510. function refreshUniformsStandard( uniforms, material ) {
  14511. uniforms.roughness.value = material.roughness;
  14512. uniforms.metalness.value = material.metalness;
  14513. if ( material.roughnessMap ) {
  14514. uniforms.roughnessMap.value = material.roughnessMap;
  14515. }
  14516. if ( material.metalnessMap ) {
  14517. uniforms.metalnessMap.value = material.metalnessMap;
  14518. }
  14519. if ( material.emissiveMap ) {
  14520. uniforms.emissiveMap.value = material.emissiveMap;
  14521. }
  14522. if ( material.bumpMap ) {
  14523. uniforms.bumpMap.value = material.bumpMap;
  14524. uniforms.bumpScale.value = material.bumpScale;
  14525. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14526. }
  14527. if ( material.normalMap ) {
  14528. uniforms.normalMap.value = material.normalMap;
  14529. uniforms.normalScale.value.copy( material.normalScale );
  14530. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14531. }
  14532. if ( material.displacementMap ) {
  14533. uniforms.displacementMap.value = material.displacementMap;
  14534. uniforms.displacementScale.value = material.displacementScale;
  14535. uniforms.displacementBias.value = material.displacementBias;
  14536. }
  14537. const envMap = properties.get( material ).envMap;
  14538. if ( envMap ) {
  14539. //uniforms.envMap.value = material.envMap; // part of uniforms common
  14540. uniforms.envMapIntensity.value = material.envMapIntensity;
  14541. }
  14542. }
  14543. function refreshUniformsPhysical( uniforms, material ) {
  14544. refreshUniformsStandard( uniforms, material );
  14545. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  14546. uniforms.clearcoat.value = material.clearcoat;
  14547. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  14548. if ( material.sheen ) uniforms.sheen.value.copy( material.sheen );
  14549. if ( material.clearcoatMap ) {
  14550. uniforms.clearcoatMap.value = material.clearcoatMap;
  14551. }
  14552. if ( material.clearcoatRoughnessMap ) {
  14553. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  14554. }
  14555. if ( material.clearcoatNormalMap ) {
  14556. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  14557. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  14558. if ( material.side === BackSide ) {
  14559. uniforms.clearcoatNormalScale.value.negate();
  14560. }
  14561. }
  14562. uniforms.transmission.value = material.transmission;
  14563. if ( material.transmissionMap ) {
  14564. uniforms.transmissionMap.value = material.transmissionMap;
  14565. }
  14566. }
  14567. function refreshUniformsMatcap( uniforms, material ) {
  14568. if ( material.matcap ) {
  14569. uniforms.matcap.value = material.matcap;
  14570. }
  14571. if ( material.bumpMap ) {
  14572. uniforms.bumpMap.value = material.bumpMap;
  14573. uniforms.bumpScale.value = material.bumpScale;
  14574. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14575. }
  14576. if ( material.normalMap ) {
  14577. uniforms.normalMap.value = material.normalMap;
  14578. uniforms.normalScale.value.copy( material.normalScale );
  14579. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14580. }
  14581. if ( material.displacementMap ) {
  14582. uniforms.displacementMap.value = material.displacementMap;
  14583. uniforms.displacementScale.value = material.displacementScale;
  14584. uniforms.displacementBias.value = material.displacementBias;
  14585. }
  14586. }
  14587. function refreshUniformsDepth( uniforms, material ) {
  14588. if ( material.displacementMap ) {
  14589. uniforms.displacementMap.value = material.displacementMap;
  14590. uniforms.displacementScale.value = material.displacementScale;
  14591. uniforms.displacementBias.value = material.displacementBias;
  14592. }
  14593. }
  14594. function refreshUniformsDistance( uniforms, material ) {
  14595. if ( material.displacementMap ) {
  14596. uniforms.displacementMap.value = material.displacementMap;
  14597. uniforms.displacementScale.value = material.displacementScale;
  14598. uniforms.displacementBias.value = material.displacementBias;
  14599. }
  14600. uniforms.referencePosition.value.copy( material.referencePosition );
  14601. uniforms.nearDistance.value = material.nearDistance;
  14602. uniforms.farDistance.value = material.farDistance;
  14603. }
  14604. function refreshUniformsNormal( uniforms, material ) {
  14605. if ( material.bumpMap ) {
  14606. uniforms.bumpMap.value = material.bumpMap;
  14607. uniforms.bumpScale.value = material.bumpScale;
  14608. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  14609. }
  14610. if ( material.normalMap ) {
  14611. uniforms.normalMap.value = material.normalMap;
  14612. uniforms.normalScale.value.copy( material.normalScale );
  14613. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  14614. }
  14615. if ( material.displacementMap ) {
  14616. uniforms.displacementMap.value = material.displacementMap;
  14617. uniforms.displacementScale.value = material.displacementScale;
  14618. uniforms.displacementBias.value = material.displacementBias;
  14619. }
  14620. }
  14621. return {
  14622. refreshFogUniforms: refreshFogUniforms,
  14623. refreshMaterialUniforms: refreshMaterialUniforms
  14624. };
  14625. }
  14626. function createCanvasElement() {
  14627. const canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  14628. canvas.style.display = 'block';
  14629. return canvas;
  14630. }
  14631. function WebGLRenderer( parameters ) {
  14632. parameters = parameters || {};
  14633. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  14634. _context = parameters.context !== undefined ? parameters.context : null,
  14635. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14636. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14637. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14638. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14639. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14640. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14641. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14642. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14643. let currentRenderList = null;
  14644. let currentRenderState = null;
  14645. // render() can be called from within a callback triggered by another render.
  14646. // We track this so that the nested render call gets its state isolated from the parent render call.
  14647. const renderStateStack = [];
  14648. // public properties
  14649. this.domElement = _canvas;
  14650. // Debug configuration container
  14651. this.debug = {
  14652. /**
  14653. * Enables error checking and reporting when shader programs are being compiled
  14654. * @type {boolean}
  14655. */
  14656. checkShaderErrors: true
  14657. };
  14658. // clearing
  14659. this.autoClear = true;
  14660. this.autoClearColor = true;
  14661. this.autoClearDepth = true;
  14662. this.autoClearStencil = true;
  14663. // scene graph
  14664. this.sortObjects = true;
  14665. // user-defined clipping
  14666. this.clippingPlanes = [];
  14667. this.localClippingEnabled = false;
  14668. // physically based shading
  14669. this.gammaFactor = 2.0; // for backwards compatibility
  14670. this.outputEncoding = LinearEncoding;
  14671. // physical lights
  14672. this.physicallyCorrectLights = false;
  14673. // tone mapping
  14674. this.toneMapping = NoToneMapping;
  14675. this.toneMappingExposure = 1.0;
  14676. // morphs
  14677. this.maxMorphTargets = 8;
  14678. this.maxMorphNormals = 4;
  14679. // internal properties
  14680. const _this = this;
  14681. let _isContextLost = false;
  14682. // internal state cache
  14683. let _framebuffer = null;
  14684. let _currentActiveCubeFace = 0;
  14685. let _currentActiveMipmapLevel = 0;
  14686. let _currentRenderTarget = null;
  14687. let _currentFramebuffer = null;
  14688. let _currentMaterialId = - 1;
  14689. let _currentCamera = null;
  14690. const _currentViewport = new Vector4();
  14691. const _currentScissor = new Vector4();
  14692. let _currentScissorTest = null;
  14693. //
  14694. let _width = _canvas.width;
  14695. let _height = _canvas.height;
  14696. let _pixelRatio = 1;
  14697. let _opaqueSort = null;
  14698. let _transparentSort = null;
  14699. const _viewport = new Vector4( 0, 0, _width, _height );
  14700. const _scissor = new Vector4( 0, 0, _width, _height );
  14701. let _scissorTest = false;
  14702. // frustum
  14703. const _frustum = new Frustum();
  14704. // clipping
  14705. let _clippingEnabled = false;
  14706. let _localClippingEnabled = false;
  14707. // camera matrices cache
  14708. const _projScreenMatrix = new Matrix4();
  14709. const _vector3 = new Vector3();
  14710. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  14711. function getTargetPixelRatio() {
  14712. return _currentRenderTarget === null ? _pixelRatio : 1;
  14713. }
  14714. // initialize
  14715. let _gl = _context;
  14716. function getContext( contextNames, contextAttributes ) {
  14717. for ( let i = 0; i < contextNames.length; i ++ ) {
  14718. const contextName = contextNames[ i ];
  14719. const context = _canvas.getContext( contextName, contextAttributes );
  14720. if ( context !== null ) return context;
  14721. }
  14722. return null;
  14723. }
  14724. try {
  14725. const contextAttributes = {
  14726. alpha: _alpha,
  14727. depth: _depth,
  14728. stencil: _stencil,
  14729. antialias: _antialias,
  14730. premultipliedAlpha: _premultipliedAlpha,
  14731. preserveDrawingBuffer: _preserveDrawingBuffer,
  14732. powerPreference: _powerPreference,
  14733. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  14734. };
  14735. // event listeners must be registered before WebGL context is created, see #12753
  14736. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  14737. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  14738. if ( _gl === null ) {
  14739. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  14740. if ( _this.isWebGL1Renderer === true ) {
  14741. contextNames.shift();
  14742. }
  14743. _gl = getContext( contextNames, contextAttributes );
  14744. if ( _gl === null ) {
  14745. if ( getContext( contextNames ) ) {
  14746. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  14747. } else {
  14748. throw new Error( 'Error creating WebGL context.' );
  14749. }
  14750. }
  14751. }
  14752. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14753. if ( _gl.getShaderPrecisionFormat === undefined ) {
  14754. _gl.getShaderPrecisionFormat = function () {
  14755. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  14756. };
  14757. }
  14758. } catch ( error ) {
  14759. console.error( 'THREE.WebGLRenderer: ' + error.message );
  14760. throw error;
  14761. }
  14762. let extensions, capabilities, state, info;
  14763. let properties, textures, cubemaps, attributes, geometries, objects;
  14764. let programCache, materials, renderLists, renderStates, clipping;
  14765. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14766. let utils, bindingStates;
  14767. function initGLContext() {
  14768. extensions = new WebGLExtensions( _gl );
  14769. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  14770. if ( capabilities.isWebGL2 === false ) {
  14771. extensions.get( 'WEBGL_depth_texture' );
  14772. extensions.get( 'OES_texture_float' );
  14773. extensions.get( 'OES_texture_half_float' );
  14774. extensions.get( 'OES_texture_half_float_linear' );
  14775. extensions.get( 'OES_standard_derivatives' );
  14776. extensions.get( 'OES_element_index_uint' );
  14777. extensions.get( 'OES_vertex_array_object' );
  14778. extensions.get( 'ANGLE_instanced_arrays' );
  14779. }
  14780. extensions.get( 'OES_texture_float_linear' );
  14781. utils = new WebGLUtils( _gl, extensions, capabilities );
  14782. state = new WebGLState( _gl, extensions, capabilities );
  14783. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  14784. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  14785. info = new WebGLInfo( _gl );
  14786. properties = new WebGLProperties();
  14787. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  14788. cubemaps = new WebGLCubeMaps( _this );
  14789. attributes = new WebGLAttributes( _gl, capabilities );
  14790. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  14791. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  14792. objects = new WebGLObjects( _gl, geometries, attributes, info );
  14793. morphtargets = new WebGLMorphtargets( _gl );
  14794. clipping = new WebGLClipping( properties );
  14795. programCache = new WebGLPrograms( _this, cubemaps, extensions, capabilities, bindingStates, clipping );
  14796. materials = new WebGLMaterials( properties );
  14797. renderLists = new WebGLRenderLists( properties );
  14798. renderStates = new WebGLRenderStates( extensions, capabilities );
  14799. background = new WebGLBackground( _this, cubemaps, state, objects, _premultipliedAlpha );
  14800. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  14801. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  14802. info.programs = programCache.programs;
  14803. _this.capabilities = capabilities;
  14804. _this.extensions = extensions;
  14805. _this.properties = properties;
  14806. _this.renderLists = renderLists;
  14807. _this.state = state;
  14808. _this.info = info;
  14809. _this._textures = textures;//add
  14810. }
  14811. initGLContext();
  14812. // xr
  14813. const xr = new WebXRManager( _this, _gl );
  14814. this.xr = xr;
  14815. // shadow map
  14816. const shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  14817. this.shadowMap = shadowMap;
  14818. // API
  14819. this.getContext = function () {
  14820. return _gl;
  14821. };
  14822. this.getContextAttributes = function () {
  14823. return _gl.getContextAttributes();
  14824. };
  14825. this.forceContextLoss = function () {
  14826. const extension = extensions.get( 'WEBGL_lose_context' );
  14827. if ( extension ) extension.loseContext();
  14828. };
  14829. this.forceContextRestore = function () {
  14830. const extension = extensions.get( 'WEBGL_lose_context' );
  14831. if ( extension ) extension.restoreContext();
  14832. };
  14833. this.getPixelRatio = function () {
  14834. return _pixelRatio;
  14835. };
  14836. this.setPixelRatio = function ( value ) {
  14837. if ( value === undefined ) return;
  14838. _pixelRatio = value;
  14839. this.setSize( _width, _height, false );
  14840. };
  14841. this.getSize = function ( target ) {
  14842. if ( target === undefined ) {
  14843. console.warn( 'WebGLRenderer: .getsize() now requires a Vector2 as an argument' );
  14844. target = new Vector2$1();
  14845. }
  14846. return target.set( _width, _height );
  14847. };
  14848. this.setSize = function ( width, height, updateStyle, devicePixelRatio ) {//改
  14849. if (devicePixelRatio != void 0) _pixelRatio = devicePixelRatio; //add
  14850. if ( xr.isPresenting ) {
  14851. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  14852. return;
  14853. }
  14854. _width = width;
  14855. _height = height;
  14856. //if(!window.unableSetSize){
  14857. _canvas.width = Math.floor( width * _pixelRatio );
  14858. _canvas.height = Math.floor( height * _pixelRatio );
  14859. if ( updateStyle !== false ) {
  14860. _canvas.style.width = width + 'px';
  14861. _canvas.style.height = height + 'px';
  14862. }
  14863. this.setViewport( 0, 0, width, height );
  14864. //}
  14865. };
  14866. this.getDrawingBufferSize = function ( target ) {
  14867. if ( target === undefined ) {
  14868. console.warn( 'WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument' );
  14869. target = new Vector2$1();
  14870. }
  14871. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  14872. };
  14873. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  14874. _width = width;
  14875. _height = height;
  14876. _pixelRatio = pixelRatio;
  14877. _canvas.width = Math.floor( width * pixelRatio );
  14878. _canvas.height = Math.floor( height * pixelRatio );
  14879. this.setViewport( 0, 0, width, height );
  14880. };
  14881. this.getCurrentViewport = function ( target ) {
  14882. if ( target === undefined ) {
  14883. console.warn( 'WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument' );
  14884. target = new Vector4();
  14885. }
  14886. return target.copy( _currentViewport );
  14887. };
  14888. this.getViewport = function ( target ) {
  14889. return target.copy( _viewport );
  14890. };
  14891. this.setViewport = function ( x, y, width, height ) {
  14892. if ( x.isVector4 ) {
  14893. _viewport.set( x.x, x.y, x.z, x.w );
  14894. } else {
  14895. _viewport.set( x, y, width, height );
  14896. }
  14897. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  14898. };
  14899. this.getScissor = function ( target ) {
  14900. return target.copy( _scissor );
  14901. };
  14902. this.setScissor = function ( x, y, width, height ) {
  14903. if ( x.isVector4 ) {
  14904. _scissor.set( x.x, x.y, x.z, x.w );
  14905. } else {
  14906. _scissor.set( x, y, width, height );
  14907. }
  14908. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  14909. };
  14910. this.getScissorTest = function () {
  14911. return _scissorTest;
  14912. };
  14913. this.setScissorTest = function ( boolean ) {
  14914. state.setScissorTest( _scissorTest = boolean );
  14915. };
  14916. this.setOpaqueSort = function ( method ) {
  14917. _opaqueSort = method;
  14918. };
  14919. this.setTransparentSort = function ( method ) {
  14920. _transparentSort = method;
  14921. };
  14922. // Clearing
  14923. this.getClearColor = function ( target ) {
  14924. if ( target === undefined ) {
  14925. console.warn( 'WebGLRenderer: .getClearColor() now requires a Color as an argument' );
  14926. target = new Color();
  14927. }
  14928. return target.copy( background.getClearColor() );
  14929. };
  14930. this.setClearColor = function () {
  14931. background.setClearColor.apply( background, arguments );
  14932. };
  14933. this.getClearAlpha = function () {
  14934. return background.getClearAlpha();
  14935. };
  14936. this.setClearAlpha = function () {
  14937. background.setClearAlpha.apply( background, arguments );
  14938. };
  14939. this.clear = function ( color, depth, stencil ) {
  14940. let bits = 0;
  14941. if ( color === undefined || color ) bits |= 16384;
  14942. if ( depth === undefined || depth ) bits |= 256;
  14943. if ( stencil === undefined || stencil ) bits |= 1024;
  14944. _gl.clear( bits );
  14945. };
  14946. this.clearColor = function () {
  14947. this.clear( true, false, false );
  14948. };
  14949. this.clearDepth = function () {
  14950. this.clear( false, true, false );
  14951. };
  14952. this.clearStencil = function () {
  14953. this.clear( false, false, true );
  14954. };
  14955. //
  14956. this.dispose = function () {
  14957. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  14958. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  14959. renderLists.dispose();
  14960. renderStates.dispose();
  14961. properties.dispose();
  14962. cubemaps.dispose();
  14963. objects.dispose();
  14964. bindingStates.dispose();
  14965. xr.dispose();
  14966. animation.stop();
  14967. };
  14968. // Events
  14969. function onContextLost( event ) {
  14970. event.preventDefault();
  14971. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  14972. _isContextLost = true;
  14973. }
  14974. function onContextRestore( /* event */ ) {
  14975. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  14976. _isContextLost = false;
  14977. initGLContext();
  14978. }
  14979. function onMaterialDispose( event ) {
  14980. const material = event.target;
  14981. material.removeEventListener( 'dispose', onMaterialDispose );
  14982. deallocateMaterial( material );
  14983. }
  14984. // Buffer deallocation
  14985. function deallocateMaterial( material ) {
  14986. releaseMaterialProgramReference( material );
  14987. properties.remove( material );
  14988. }
  14989. function releaseMaterialProgramReference( material ) {
  14990. const programInfo = properties.get( material ).program;
  14991. if ( programInfo !== undefined ) {
  14992. programCache.releaseProgram( programInfo );
  14993. }
  14994. }
  14995. // Buffer rendering
  14996. function renderObjectImmediate( object, program ) {
  14997. object.render( function ( object ) {
  14998. _this.renderBufferImmediate( object, program );
  14999. } );
  15000. }
  15001. this.renderBufferImmediate = function ( object, program ) {
  15002. bindingStates.initAttributes();
  15003. const buffers = properties.get( object );
  15004. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  15005. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  15006. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  15007. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  15008. const programAttributes = program.getAttributes();
  15009. if ( object.hasPositions ) {
  15010. _gl.bindBuffer( 34962, buffers.position );
  15011. _gl.bufferData( 34962, object.positionArray, 35048 );
  15012. bindingStates.enableAttribute( programAttributes.position );
  15013. _gl.vertexAttribPointer( programAttributes.position, 3, 5126, false, 0, 0 );
  15014. }
  15015. if ( object.hasNormals ) {
  15016. _gl.bindBuffer( 34962, buffers.normal );
  15017. _gl.bufferData( 34962, object.normalArray, 35048 );
  15018. bindingStates.enableAttribute( programAttributes.normal );
  15019. _gl.vertexAttribPointer( programAttributes.normal, 3, 5126, false, 0, 0 );
  15020. }
  15021. if ( object.hasUvs ) {
  15022. _gl.bindBuffer( 34962, buffers.uv );
  15023. _gl.bufferData( 34962, object.uvArray, 35048 );
  15024. bindingStates.enableAttribute( programAttributes.uv );
  15025. _gl.vertexAttribPointer( programAttributes.uv, 2, 5126, false, 0, 0 );
  15026. }
  15027. if ( object.hasColors ) {
  15028. _gl.bindBuffer( 34962, buffers.color );
  15029. _gl.bufferData( 34962, object.colorArray, 35048 );
  15030. bindingStates.enableAttribute( programAttributes.color );
  15031. _gl.vertexAttribPointer( programAttributes.color, 3, 5126, false, 0, 0 );
  15032. }
  15033. bindingStates.disableUnusedAttributes();
  15034. _gl.drawArrays( 4, 0, object.count );
  15035. object.count = 0;
  15036. };
  15037. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  15038. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  15039. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  15040. const program = setProgram( camera, scene, material, object );
  15041. state.setMaterial( material, frontFaceCW );
  15042. //
  15043. let index = geometry.index;
  15044. const position = geometry.attributes.position;
  15045. //
  15046. if ( index === null ) {
  15047. if ( position === undefined || position.count === 0 ) return;
  15048. } else if ( index.count === 0 ) {
  15049. return;
  15050. }
  15051. //
  15052. let rangeFactor = 1;
  15053. if ( material.wireframe === true ) {
  15054. index = geometries.getWireframeAttribute( geometry );
  15055. rangeFactor = 2;
  15056. }
  15057. if ( material.morphTargets || material.morphNormals ) {
  15058. morphtargets.update( object, geometry, material, program );
  15059. }
  15060. bindingStates.setup( object, material, program, geometry, index );
  15061. let attribute;
  15062. let renderer = bufferRenderer;
  15063. if ( index !== null ) {
  15064. attribute = attributes.get( index );
  15065. renderer = indexedBufferRenderer;
  15066. renderer.setIndex( attribute );
  15067. }
  15068. //
  15069. const dataCount = ( index !== null ) ? index.count : position.count;
  15070. const rangeStart = geometry.drawRange.start * rangeFactor;
  15071. const rangeCount = geometry.drawRange.count * rangeFactor;
  15072. const groupStart = group !== null ? group.start * rangeFactor : 0;
  15073. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  15074. const drawStart = Math.max( rangeStart, groupStart );
  15075. const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  15076. const drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  15077. if ( drawCount === 0 ) return;
  15078. //
  15079. if ( object.isMesh ) {
  15080. if ( material.wireframe === true ) {
  15081. state.setlineWidth( material.wireframelineWidth * getTargetPixelRatio() );
  15082. renderer.setMode( 1 );
  15083. } else {
  15084. renderer.setMode( 4 );
  15085. }
  15086. } else if ( object.isLine ) {
  15087. let lineWidth = material.lineWidth;
  15088. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  15089. state.setlineWidth( lineWidth * getTargetPixelRatio() );
  15090. if ( object.isLineSegments ) {
  15091. renderer.setMode( 1 );
  15092. } else if ( object.isLineLoop ) {
  15093. renderer.setMode( 2 );
  15094. } else {
  15095. renderer.setMode( 3 );
  15096. }
  15097. } else if ( object.isPoints ) {
  15098. renderer.setMode( 0 );
  15099. } else if ( object.isSprite ) {
  15100. renderer.setMode( 4 );
  15101. }
  15102. if ( object.isInstancedMesh ) {
  15103. renderer.renderInstances( drawStart, drawCount, object.count );
  15104. } else if ( geometry.isInstancedBufferGeometry ) {
  15105. const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  15106. renderer.renderInstances( drawStart, drawCount, instanceCount );
  15107. } else {
  15108. renderer.render( drawStart, drawCount );
  15109. }
  15110. };
  15111. // Compile
  15112. this.compile = function ( scene, camera ) {
  15113. currentRenderState = renderStates.get( scene );
  15114. currentRenderState.init();
  15115. scene.traverseVisible( function ( object ) {
  15116. if ( object.isLight && object.layers.test( camera.layers ) ) {
  15117. currentRenderState.pushLight( object );
  15118. if ( object.castShadow ) {
  15119. currentRenderState.pushShadow( object );
  15120. }
  15121. }
  15122. } );
  15123. currentRenderState.setupLights();
  15124. const compiled = new WeakMap();
  15125. scene.traverse( function ( object ) {
  15126. const material = object.material;
  15127. if ( material ) {
  15128. if ( Array.isArray( material ) ) {
  15129. for ( let i = 0; i < material.length; i ++ ) {
  15130. const material2 = material[ i ];
  15131. if ( compiled.has( material2 ) === false ) {
  15132. initMaterial( material2, scene, object );
  15133. compiled.set( material2 );
  15134. }
  15135. }
  15136. } else if ( compiled.has( material ) === false ) {
  15137. initMaterial( material, scene, object );
  15138. compiled.set( material );
  15139. }
  15140. }
  15141. } );
  15142. };
  15143. // Animation Loop
  15144. let onAnimationFrameCallback = null;
  15145. function onAnimationFrame( time ) {
  15146. if ( xr.isPresenting ) return;
  15147. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  15148. }
  15149. const animation = new WebGLAnimation();
  15150. animation.setAnimationLoop( onAnimationFrame );
  15151. if ( typeof window !== 'undefined' ) animation.setContext( window );
  15152. this.setAnimationLoop = function ( callback ) {
  15153. onAnimationFrameCallback = callback;
  15154. xr.setAnimationLoop( callback );
  15155. ( callback === null ) ? animation.stop() : animation.start();
  15156. };
  15157. // Rendering
  15158. this.render = function ( scene, camera ) {
  15159. let renderTarget, forceClear;
  15160. if ( arguments[ 2 ] !== undefined ) {
  15161. console.warn( 'THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.' );
  15162. renderTarget = arguments[ 2 ];
  15163. }
  15164. if ( arguments[ 3 ] !== undefined ) {
  15165. console.warn( 'THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.' );
  15166. forceClear = arguments[ 3 ];
  15167. }
  15168. if ( camera !== undefined && camera.isCamera !== true ) {
  15169. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  15170. return;
  15171. }
  15172. if ( _isContextLost === true ) return;
  15173. // reset caching for this frame
  15174. bindingStates.resetDefaultState();
  15175. _currentMaterialId = - 1;
  15176. _currentCamera = null;
  15177. // update scene graph
  15178. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  15179. // update camera matrices and frustum
  15180. if ( camera.parent === null ) camera.updateMatrixWorld();
  15181. if ( xr.enabled === true && xr.isPresenting === true ) {
  15182. camera = xr.getCamera( camera );
  15183. }
  15184. //
  15185. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, renderTarget || _currentRenderTarget );
  15186. currentRenderState = renderStates.get( scene, renderStateStack.length );
  15187. currentRenderState.init();
  15188. renderStateStack.push( currentRenderState );
  15189. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  15190. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  15191. _localClippingEnabled = this.localClippingEnabled;
  15192. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  15193. currentRenderList = renderLists.get( scene, camera );
  15194. currentRenderList.init();
  15195. projectObject( scene, camera, 0, _this.sortObjects );
  15196. currentRenderList.finish();
  15197. if ( _this.sortObjects === true ) {
  15198. currentRenderList.sort( _opaqueSort, _transparentSort );
  15199. }
  15200. //
  15201. if ( _clippingEnabled === true ) clipping.beginShadows();
  15202. const shadowsArray = currentRenderState.state.shadowsArray;
  15203. shadowMap.render( shadowsArray, scene, camera );
  15204. currentRenderState.setupLights();
  15205. currentRenderState.setupLightsView( camera );
  15206. if ( _clippingEnabled === true ) clipping.endShadows();
  15207. //
  15208. if ( this.info.autoReset === true ) this.info.reset();
  15209. if ( renderTarget !== undefined ) {
  15210. this.setRenderTarget( renderTarget );
  15211. }
  15212. //
  15213. background.render( currentRenderList, scene, camera, forceClear );
  15214. // render scene
  15215. const opaqueObjects = currentRenderList.opaque;
  15216. const transparentObjects = currentRenderList.transparent;
  15217. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  15218. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  15219. //
  15220. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  15221. //
  15222. if ( _currentRenderTarget !== null ) {
  15223. // Generate mipmap if we're using any kind of mipmap filtering
  15224. textures.updateRenderTargetMipmap( _currentRenderTarget );
  15225. // resolve multisample renderbuffers to a single-sample texture if necessary
  15226. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  15227. }
  15228. // Ensure depth buffer writing is enabled so it can be cleared on next render
  15229. state.buffers.depth.setTest( true );
  15230. state.buffers.depth.setMask( true );
  15231. state.buffers.color.setMask( true );
  15232. state.setPolygonOffset( false );
  15233. // _gl.finish();
  15234. renderStateStack.pop();
  15235. if ( renderStateStack.length > 0 ) {
  15236. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  15237. } else {
  15238. currentRenderState = null;
  15239. }
  15240. currentRenderList = null;
  15241. };
  15242. function projectObject( object, camera, groupOrder, sortObjects ) {
  15243. if ( object.visible === false ) return;
  15244. const visible = object.layers.test( camera.layers );
  15245. if ( visible ) {
  15246. if ( object.isGroup ) {
  15247. groupOrder = object.renderOrder;
  15248. } else if ( object.isLOD ) {
  15249. if ( object.autoUpdate === true ) object.update( camera );
  15250. } else if ( object.isLight ) {
  15251. currentRenderState.pushLight( object );
  15252. if ( object.castShadow ) {
  15253. currentRenderState.pushShadow( object );
  15254. }
  15255. } else if ( object.isSprite ) {
  15256. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  15257. if ( sortObjects ) {
  15258. _vector3.setFromMatrixPosition( object.matrixWorld )
  15259. .applyMatrix4( _projScreenMatrix );
  15260. }
  15261. const geometry = objects.update( object );
  15262. const material = object.material;
  15263. if ( material.visible ) {
  15264. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  15265. }
  15266. }
  15267. } else if ( object.isImmediateRenderObject ) {
  15268. if ( sortObjects ) {
  15269. _vector3.setFromMatrixPosition( object.matrixWorld )
  15270. .applyMatrix4( _projScreenMatrix );
  15271. }
  15272. currentRenderList.push( object, null, object.material, groupOrder, _vector3.z, null );
  15273. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  15274. if ( object.isSkinnedMesh ) {
  15275. // update skeleton only once in a frame
  15276. if ( object.skeleton.frame !== info.render.frame ) {
  15277. object.skeleton.update();
  15278. object.skeleton.frame = info.render.frame;
  15279. }
  15280. }
  15281. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  15282. if ( sortObjects ) {
  15283. _vector3.setFromMatrixPosition( object.matrixWorld )
  15284. .applyMatrix4( _projScreenMatrix );
  15285. }
  15286. const geometry = objects.update( object );
  15287. const material = object.material;
  15288. if ( Array.isArray( material ) ) {
  15289. const groups = geometry.groups;
  15290. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15291. const group = groups[ i ];
  15292. const groupMaterial = material[ group.materialIndex ];
  15293. if ( groupMaterial && groupMaterial.visible ) {
  15294. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  15295. }
  15296. }
  15297. } else if ( material.visible ) {
  15298. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  15299. }
  15300. }
  15301. }
  15302. }
  15303. const children = object.children;
  15304. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15305. projectObject( children[ i ], camera, groupOrder, sortObjects );
  15306. }
  15307. }
  15308. function renderObjects( renderList, scene, camera ) {
  15309. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  15310. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  15311. const renderItem = renderList[ i ];
  15312. const object = renderItem.object;
  15313. const geometry = renderItem.geometry;
  15314. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  15315. const group = renderItem.group;
  15316. if ( camera.isArrayCamera ) {
  15317. const cameras = camera.cameras;
  15318. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  15319. const camera2 = cameras[ j ];
  15320. if ( object.layers.test( camera2.layers ) ) {
  15321. state.viewport( _currentViewport.copy( camera2.viewport ) );
  15322. currentRenderState.setupLightsView( camera2 );
  15323. renderObject( object, scene, camera2, geometry, material, group );
  15324. }
  15325. }
  15326. } else {
  15327. renderObject( object, scene, camera, geometry, material, group );
  15328. }
  15329. }
  15330. }
  15331. function renderObject( object, scene, camera, geometry, material, group ) {
  15332. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  15333. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  15334. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  15335. if ( object.isImmediateRenderObject ) {
  15336. const program = setProgram( camera, scene, material, object );
  15337. state.setMaterial( material );
  15338. bindingStates.reset();
  15339. renderObjectImmediate( object, program );
  15340. } else {
  15341. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  15342. }
  15343. object.onAfterRender( _this, scene, camera, geometry, material, group );
  15344. }
  15345. function initMaterial( material, scene, object ) {
  15346. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15347. const materialProperties = properties.get( material );
  15348. const lights = currentRenderState.state.lights;
  15349. const shadowsArray = currentRenderState.state.shadowsArray;
  15350. const lightsStateVersion = lights.state.version;
  15351. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  15352. const programCacheKey = programCache.getProgramCacheKey( parameters );
  15353. let program = materialProperties.program;
  15354. let programChange = true;
  15355. if ( program === undefined ) {
  15356. // new material
  15357. material.addEventListener( 'dispose', onMaterialDispose );
  15358. } else if ( program.cacheKey !== programCacheKey ) {
  15359. // changed glsl or parameters
  15360. releaseMaterialProgramReference( material );
  15361. } else if ( materialProperties.lightsStateVersion !== lightsStateVersion ) {
  15362. programChange = false;
  15363. } else if ( parameters.shaderID !== undefined ) {
  15364. // same glsl and uniform list, envMap still needs the update here to avoid a frame-late effect
  15365. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15366. materialProperties.envMap = cubemaps.get( material.envMap || environment );
  15367. return;
  15368. } else {
  15369. // only rebuild uniform list
  15370. programChange = false;
  15371. }
  15372. if ( programChange ) {
  15373. parameters.uniforms = programCache.getUniforms( material );
  15374. material.onBeforeCompile( parameters, _this );
  15375. program = programCache.acquireProgram( parameters, programCacheKey );
  15376. materialProperties.program = program;
  15377. materialProperties.uniforms = parameters.uniforms;
  15378. materialProperties.outputEncoding = parameters.outputEncoding;
  15379. }
  15380. const uniforms = materialProperties.uniforms;
  15381. if ( ! material.isShaderMaterial &&
  15382. ! material.isRawShaderMaterial ||
  15383. material.clipping === true ) {
  15384. materialProperties.numClippingPlanes = clipping.numPlanes;
  15385. materialProperties.numIntersection = clipping.numIntersection;
  15386. uniforms.clippingPlanes = clipping.uniform;
  15387. }
  15388. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  15389. materialProperties.fog = scene.fog;
  15390. materialProperties.envMap = cubemaps.get( material.envMap || materialProperties.environment );
  15391. // store the light setup it was created for
  15392. materialProperties.needsLights = materialNeedsLights( material );
  15393. materialProperties.lightsStateVersion = lightsStateVersion;
  15394. if ( materialProperties.needsLights ) {
  15395. // wire up the material to this renderer's lighting state
  15396. uniforms.ambientLightColor.value = lights.state.ambient;
  15397. uniforms.lightProbe.value = lights.state.probe;
  15398. uniforms.directionalLights.value = lights.state.directional;
  15399. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  15400. uniforms.spotLights.value = lights.state.spot;
  15401. uniforms.spotLightShadows.value = lights.state.spotShadow;
  15402. uniforms.rectAreaLights.value = lights.state.rectArea;
  15403. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  15404. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  15405. uniforms.pointLights.value = lights.state.point;
  15406. uniforms.pointLightShadows.value = lights.state.pointShadow;
  15407. uniforms.hemisphereLights.value = lights.state.hemi;
  15408. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15409. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15410. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15411. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15412. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15413. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  15414. // TODO (abelnation): add area lights shadow info to uniforms
  15415. }
  15416. const progUniforms = materialProperties.program.getUniforms();
  15417. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  15418. materialProperties.uniformsList = uniformsList;
  15419. }
  15420. function setProgram( camera, scene, material, object ) {
  15421. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15422. textures.resetTextureUnits();
  15423. const fog = scene.fog;
  15424. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15425. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  15426. const envMap = cubemaps.get( material.envMap || environment );
  15427. const materialProperties = properties.get( material );
  15428. const lights = currentRenderState.state.lights;
  15429. if ( _clippingEnabled === true ) {
  15430. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  15431. const useCache =
  15432. camera === _currentCamera &&
  15433. material.id === _currentMaterialId;
  15434. // we might want to call this function with some ClippingGroup
  15435. // object instead of the material, once it becomes feasible
  15436. // (#8465, #8379)
  15437. clipping.setState( material, camera, useCache );
  15438. }
  15439. }
  15440. if ( material.version === materialProperties.__version ) {
  15441. if ( material.fog && materialProperties.fog !== fog ) {
  15442. initMaterial( material, scene, object );
  15443. } else if ( materialProperties.environment !== environment ) {
  15444. initMaterial( material, scene, object );
  15445. } else if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  15446. initMaterial( material, scene, object );
  15447. } else if ( materialProperties.numClippingPlanes !== undefined &&
  15448. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  15449. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  15450. initMaterial( material, scene, object );
  15451. } else if ( materialProperties.outputEncoding !== encoding ) {
  15452. initMaterial( material, scene, object );
  15453. } else if ( materialProperties.envMap !== envMap ) {
  15454. initMaterial( material, scene, object );
  15455. }
  15456. } else {
  15457. initMaterial( material, scene, object );
  15458. materialProperties.__version = material.version;
  15459. }
  15460. let refreshProgram = false;
  15461. let refreshMaterial = false;
  15462. let refreshLights = false;
  15463. const program = materialProperties.program,
  15464. p_uniforms = program.getUniforms(),
  15465. m_uniforms = materialProperties.uniforms;
  15466. if ( state.useProgram( program.program ) ) {
  15467. refreshProgram = true;
  15468. refreshMaterial = true;
  15469. refreshLights = true;
  15470. }
  15471. if ( material.id !== _currentMaterialId ) {
  15472. _currentMaterialId = material.id;
  15473. refreshMaterial = true;
  15474. }
  15475. if ( refreshProgram || _currentCamera !== camera ) {
  15476. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  15477. if ( capabilities.logarithmicDepthBuffer ) {
  15478. p_uniforms.setValue( _gl, 'logDepthBufFC',
  15479. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  15480. }
  15481. if ( _currentCamera !== camera ) {
  15482. _currentCamera = camera;
  15483. // lighting uniforms depend on the camera so enforce an update
  15484. // now, in case this material supports lights - or later, when
  15485. // the next material that does gets activated:
  15486. refreshMaterial = true; // set to true on material change
  15487. refreshLights = true; // remains set until update done
  15488. }
  15489. // load material specific uniforms
  15490. // (shader material also gets them for the sake of genericity)
  15491. if ( material.isShaderMaterial ||
  15492. material.isMeshPhongMaterial ||
  15493. material.isMeshToonMaterial ||
  15494. material.isMeshStandardMaterial ||
  15495. material.envMap ) {
  15496. const uCamPos = p_uniforms.map.cameraPosition;
  15497. if ( uCamPos !== undefined ) {
  15498. uCamPos.setValue( _gl,
  15499. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  15500. }
  15501. }
  15502. if ( material.isMeshPhongMaterial ||
  15503. material.isMeshToonMaterial ||
  15504. material.isMeshLambertMaterial ||
  15505. material.isMeshBasicMaterial ||
  15506. material.isMeshStandardMaterial ||
  15507. material.isShaderMaterial ) {
  15508. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  15509. }
  15510. if ( material.isMeshPhongMaterial ||
  15511. material.isMeshToonMaterial ||
  15512. material.isMeshLambertMaterial ||
  15513. material.isMeshBasicMaterial ||
  15514. material.isMeshStandardMaterial ||
  15515. material.isShaderMaterial ||
  15516. material.isShadowMaterial ||
  15517. material.skinning ) {
  15518. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  15519. }
  15520. }
  15521. // skinning uniforms must be set even if material didn't change
  15522. // auto-setting of texture unit for bone texture must go before other textures
  15523. // otherwise textures used for skinning can take over texture units reserved for other material textures
  15524. if ( material.skinning ) {
  15525. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  15526. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  15527. const skeleton = object.skeleton;
  15528. if ( skeleton ) {
  15529. const bones = skeleton.bones;
  15530. if ( capabilities.floatVertexTextures ) {
  15531. if ( skeleton.boneTexture === null ) {
  15532. // layout (1 matrix = 4 pixels)
  15533. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  15534. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  15535. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  15536. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  15537. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  15538. let size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  15539. size = MathUtils.ceilPowerOfTwo( size );
  15540. size = Math.max( size, 4 );
  15541. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  15542. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  15543. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  15544. skeleton.boneMatrices = boneMatrices;
  15545. skeleton.boneTexture = boneTexture;
  15546. skeleton.boneTextureSize = size;
  15547. }
  15548. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  15549. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  15550. } else {
  15551. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  15552. }
  15553. }
  15554. }
  15555. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  15556. materialProperties.receiveShadow = object.receiveShadow;
  15557. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  15558. }
  15559. if ( refreshMaterial ) {
  15560. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  15561. if ( materialProperties.needsLights ) {
  15562. // the current material requires lighting info
  15563. // note: all lighting uniforms are always set correctly
  15564. // they simply reference the renderer's state for their
  15565. // values
  15566. //
  15567. // use the current material's .needsUpdate flags to set
  15568. // the GL state when required
  15569. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  15570. }
  15571. // refresh uniforms common to several materials
  15572. if ( fog && material.fog ) {
  15573. materials.refreshFogUniforms( m_uniforms, fog );
  15574. }
  15575. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height );
  15576. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  15577. }
  15578. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  15579. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  15580. material.uniformsNeedUpdate = false;
  15581. }
  15582. if ( material.isSpriteMaterial ) {
  15583. p_uniforms.setValue( _gl, 'center', object.center );
  15584. }
  15585. // common matrices
  15586. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  15587. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  15588. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  15589. return program;
  15590. }
  15591. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15592. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  15593. uniforms.ambientLightColor.needsUpdate = value;
  15594. uniforms.lightProbe.needsUpdate = value;
  15595. uniforms.directionalLights.needsUpdate = value;
  15596. uniforms.directionalLightShadows.needsUpdate = value;
  15597. uniforms.pointLights.needsUpdate = value;
  15598. uniforms.pointLightShadows.needsUpdate = value;
  15599. uniforms.spotLights.needsUpdate = value;
  15600. uniforms.spotLightShadows.needsUpdate = value;
  15601. uniforms.rectAreaLights.needsUpdate = value;
  15602. uniforms.hemisphereLights.needsUpdate = value;
  15603. }
  15604. function materialNeedsLights( material ) {
  15605. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  15606. material.isMeshStandardMaterial || material.isShadowMaterial ||
  15607. ( material.isShaderMaterial && material.lights === true );
  15608. }
  15609. //
  15610. this.setFramebuffer = function ( value ) {
  15611. if ( _framebuffer !== value && _currentRenderTarget === null ) _gl.bindFramebuffer( 36160, value );
  15612. _framebuffer = value;
  15613. };
  15614. this.getActiveCubeFace = function () {
  15615. return _currentActiveCubeFace;
  15616. };
  15617. this.getActiveMipmapLevel = function () {
  15618. return _currentActiveMipmapLevel;
  15619. };
  15620. this.getRenderList = function () {
  15621. return currentRenderList;
  15622. };
  15623. this.setRenderList = function ( renderList ) {
  15624. currentRenderList = renderList;
  15625. };
  15626. this.getRenderTarget = function () {
  15627. return _currentRenderTarget;
  15628. };
  15629. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  15630. _currentRenderTarget = renderTarget;
  15631. _currentActiveCubeFace = activeCubeFace;
  15632. _currentActiveMipmapLevel = activeMipmapLevel;
  15633. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  15634. textures.setupRenderTarget( renderTarget );
  15635. }
  15636. let framebuffer = _framebuffer;
  15637. let isCube = false;
  15638. if ( renderTarget ) {
  15639. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  15640. if ( renderTarget.isWebGLCubeRenderTarget ) {
  15641. framebuffer = __webglFramebuffer[ activeCubeFace ];
  15642. isCube = true;
  15643. } else if ( renderTarget.isWebGLMultisampleRenderTarget ) {
  15644. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  15645. } else {
  15646. framebuffer = __webglFramebuffer;
  15647. }
  15648. _currentViewport.copy( renderTarget.viewport );
  15649. _currentScissor.copy( renderTarget.scissor );
  15650. _currentScissorTest = renderTarget.scissorTest;
  15651. } else {
  15652. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  15653. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  15654. _currentScissorTest = _scissorTest;
  15655. }
  15656. if ( _currentFramebuffer !== framebuffer ) {
  15657. _gl.bindFramebuffer( 36160, framebuffer );
  15658. _currentFramebuffer = framebuffer;
  15659. }
  15660. state.viewport( _currentViewport );
  15661. state.scissor( _currentScissor );
  15662. state.setScissorTest( _currentScissorTest );
  15663. if ( isCube ) {
  15664. const textureProperties = properties.get( renderTarget.texture );
  15665. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  15666. }
  15667. };
  15668. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  15669. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  15670. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  15671. return;
  15672. }
  15673. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  15674. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  15675. framebuffer = framebuffer[ activeCubeFaceIndex ];
  15676. }
  15677. if ( framebuffer ) {
  15678. let restore = false;
  15679. if ( framebuffer !== _currentFramebuffer ) {
  15680. _gl.bindFramebuffer( 36160, framebuffer );
  15681. restore = true;
  15682. }
  15683. try {
  15684. const texture = renderTarget.texture;
  15685. const textureFormat = texture.format;
  15686. const textureType = texture.type;
  15687. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  15688. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  15689. return;
  15690. }
  15691. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  15692. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  15693. ! ( textureType === HalfFloatType && ( capabilities.isWebGL2 ? extensions.get( 'EXT_color_buffer_float' ) : extensions.get( 'EXT_color_buffer_half_float' ) ) ) ) {
  15694. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  15695. return;
  15696. }
  15697. if ( _gl.checkFramebufferStatus( 36160 ) === 36053 ) {
  15698. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  15699. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  15700. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  15701. }
  15702. } else {
  15703. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  15704. }
  15705. } finally {
  15706. if ( restore ) {
  15707. _gl.bindFramebuffer( 36160, _currentFramebuffer );
  15708. }
  15709. }
  15710. }
  15711. };
  15712. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  15713. const levelScale = Math.pow( 2, - level );
  15714. const width = Math.floor( texture.image.width * levelScale );
  15715. const height = Math.floor( texture.image.height * levelScale );
  15716. const glFormat = utils.convert( texture.format );
  15717. textures.setTexture2D( texture, 0 );
  15718. _gl.copyTexImage2D( 3553, level, glFormat, position.x, position.y, width, height, 0 );
  15719. state.unbindTexture();
  15720. };
  15721. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  15722. const width = srcTexture.image.width;
  15723. const height = srcTexture.image.height;
  15724. const glFormat = utils.convert( dstTexture.format );
  15725. const glType = utils.convert( dstTexture.type );
  15726. textures.setTexture2D( dstTexture, 0 );
  15727. // As another texture upload may have changed pixelStorei
  15728. // parameters, make sure they are correct for the dstTexture
  15729. _gl.pixelStorei( 37440, dstTexture.flipY );
  15730. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  15731. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  15732. if ( srcTexture.isDataTexture ) {
  15733. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  15734. } else {
  15735. if ( srcTexture.isCompressedTexture ) {
  15736. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  15737. } else {
  15738. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  15739. }
  15740. }
  15741. // Generate mipmaps only when copying level 0
  15742. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  15743. state.unbindTexture();
  15744. };
  15745. this.initTexture = function ( texture ) {
  15746. textures.setTexture2D( texture, 0 );
  15747. state.unbindTexture();
  15748. };
  15749. this.resetState = function () {
  15750. state.reset();
  15751. bindingStates.reset();
  15752. };
  15753. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  15754. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  15755. }
  15756. }
  15757. function WebGL1Renderer( parameters ) {
  15758. WebGLRenderer.call( this, parameters );
  15759. }
  15760. WebGL1Renderer.prototype = Object.assign( Object.create( WebGLRenderer.prototype ), {
  15761. constructor: WebGL1Renderer,
  15762. isWebGL1Renderer: true
  15763. } );
  15764. class FogExp2 {
  15765. constructor( color, density ) {
  15766. Object.defineProperty( this, 'isFogExp2', { value: true } );
  15767. this.name = '';
  15768. this.color = new Color( color );
  15769. this.density = ( density !== undefined ) ? density : 0.00025;
  15770. }
  15771. clone() {
  15772. return new FogExp2( this.color, this.density );
  15773. }
  15774. toJSON( /* meta */ ) {
  15775. return {
  15776. type: 'FogExp2',
  15777. color: this.color.getHex(),
  15778. density: this.density
  15779. };
  15780. }
  15781. }
  15782. class Fog {
  15783. constructor( color, near, far ) {
  15784. Object.defineProperty( this, 'isFog', { value: true } );
  15785. this.name = '';
  15786. this.color = new Color( color );
  15787. this.near = ( near !== undefined ) ? near : 1;
  15788. this.far = ( far !== undefined ) ? far : 1000;
  15789. }
  15790. clone() {
  15791. return new Fog( this.color, this.near, this.far );
  15792. }
  15793. toJSON( /* meta */ ) {
  15794. return {
  15795. type: 'Fog',
  15796. color: this.color.getHex(),
  15797. near: this.near,
  15798. far: this.far
  15799. };
  15800. }
  15801. }
  15802. class Scene extends Object3D {
  15803. constructor() {
  15804. super();
  15805. Object.defineProperty( this, 'isScene', { value: true } );
  15806. this.type = 'Scene';
  15807. this.background = null;
  15808. this.environment = null;
  15809. this.fog = null;
  15810. this.overrideMaterial = null;
  15811. this.autoUpdate = true; // checked by the renderer
  15812. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  15813. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) ); // eslint-disable-line no-undef
  15814. }
  15815. }
  15816. copy( source, recursive ) {
  15817. super.copy( source, recursive );
  15818. if ( source.background !== null ) this.background = source.background.clone();
  15819. if ( source.environment !== null ) this.environment = source.environment.clone();
  15820. if ( source.fog !== null ) this.fog = source.fog.clone();
  15821. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  15822. this.autoUpdate = source.autoUpdate;
  15823. this.matrixAutoUpdate = source.matrixAutoUpdate;
  15824. return this;
  15825. }
  15826. toJSON( meta ) {
  15827. const data = super.toJSON( meta );
  15828. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  15829. if ( this.environment !== null ) data.object.environment = this.environment.toJSON( meta );
  15830. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  15831. return data;
  15832. }
  15833. }
  15834. function InterleavedBuffer( array, stride ) {
  15835. this.array = array;
  15836. this.stride = stride;
  15837. this.count = array !== undefined ? array.length / stride : 0;
  15838. this.usage = StaticDrawUsage;
  15839. this.updateRange = { offset: 0, count: - 1 };
  15840. this.version = 0;
  15841. this.uuid = MathUtils.generateUUID();
  15842. }
  15843. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  15844. set: function ( value ) {
  15845. if ( value === true ) this.version ++;
  15846. }
  15847. } );
  15848. Object.assign( InterleavedBuffer.prototype, {
  15849. isInterleavedBuffer: true,
  15850. onUploadCallback: function () {},
  15851. setUsage: function ( value ) {
  15852. this.usage = value;
  15853. return this;
  15854. },
  15855. copy: function ( source ) {
  15856. this.array = new source.array.constructor( source.array );
  15857. this.count = source.count;
  15858. this.stride = source.stride;
  15859. this.usage = source.usage;
  15860. return this;
  15861. },
  15862. copyAt: function ( index1, attribute, index2 ) {
  15863. index1 *= this.stride;
  15864. index2 *= attribute.stride;
  15865. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  15866. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  15867. }
  15868. return this;
  15869. },
  15870. set: function ( value, offset = 0 ) {
  15871. this.array.set( value, offset );
  15872. return this;
  15873. },
  15874. clone: function ( data ) {
  15875. if ( data.arrayBuffers === undefined ) {
  15876. data.arrayBuffers = {};
  15877. }
  15878. if ( this.array.buffer._uuid === undefined ) {
  15879. this.array.buffer._uuid = MathUtils.generateUUID();
  15880. }
  15881. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  15882. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  15883. }
  15884. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  15885. const ib = new InterleavedBuffer( array, this.stride );
  15886. ib.setUsage( this.usage );
  15887. return ib;
  15888. },
  15889. onUpload: function ( callback ) {
  15890. this.onUploadCallback = callback;
  15891. return this;
  15892. },
  15893. toJSON: function ( data ) {
  15894. if ( data.arrayBuffers === undefined ) {
  15895. data.arrayBuffers = {};
  15896. }
  15897. // generate UUID for array buffer if necessary
  15898. if ( this.array.buffer._uuid === undefined ) {
  15899. this.array.buffer._uuid = MathUtils.generateUUID();
  15900. }
  15901. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  15902. data.arrayBuffers[ this.array.buffer._uuid ] = Array.prototype.slice.call( new Uint32Array( this.array.buffer ) );
  15903. }
  15904. //
  15905. return {
  15906. uuid: this.uuid,
  15907. buffer: this.array.buffer._uuid,
  15908. type: this.array.constructor.name,
  15909. stride: this.stride
  15910. };
  15911. }
  15912. } );
  15913. const _vector$6 = new Vector3();
  15914. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  15915. this.name = '';
  15916. this.data = interleavedBuffer;
  15917. this.itemSize = itemSize;
  15918. this.offset = offset;
  15919. this.normalized = normalized === true;
  15920. }
  15921. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  15922. count: {
  15923. get: function () {
  15924. return this.data.count;
  15925. }
  15926. },
  15927. array: {
  15928. get: function () {
  15929. return this.data.array;
  15930. }
  15931. },
  15932. needsUpdate: {
  15933. set: function ( value ) {
  15934. this.data.needsUpdate = value;
  15935. }
  15936. }
  15937. } );
  15938. Object.assign( InterleavedBufferAttribute.prototype, {
  15939. isInterleavedBufferAttribute: true,
  15940. applyMatrix4: function ( m ) {
  15941. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  15942. _vector$6.x = this.getX( i );
  15943. _vector$6.y = this.getY( i );
  15944. _vector$6.z = this.getZ( i );
  15945. _vector$6.applyMatrix4( m );
  15946. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  15947. }
  15948. return this;
  15949. },
  15950. setX: function ( index, x ) {
  15951. this.data.array[ index * this.data.stride + this.offset ] = x;
  15952. return this;
  15953. },
  15954. setY: function ( index, y ) {
  15955. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  15956. return this;
  15957. },
  15958. setZ: function ( index, z ) {
  15959. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  15960. return this;
  15961. },
  15962. setW: function ( index, w ) {
  15963. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  15964. return this;
  15965. },
  15966. getX: function ( index ) {
  15967. return this.data.array[ index * this.data.stride + this.offset ];
  15968. },
  15969. getY: function ( index ) {
  15970. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  15971. },
  15972. getZ: function ( index ) {
  15973. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  15974. },
  15975. getW: function ( index ) {
  15976. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  15977. },
  15978. setXY: function ( index, x, y ) {
  15979. index = index * this.data.stride + this.offset;
  15980. this.data.array[ index + 0 ] = x;
  15981. this.data.array[ index + 1 ] = y;
  15982. return this;
  15983. },
  15984. setXYZ: function ( index, x, y, z ) {
  15985. index = index * this.data.stride + this.offset;
  15986. this.data.array[ index + 0 ] = x;
  15987. this.data.array[ index + 1 ] = y;
  15988. this.data.array[ index + 2 ] = z;
  15989. return this;
  15990. },
  15991. setXYZW: function ( index, x, y, z, w ) {
  15992. index = index * this.data.stride + this.offset;
  15993. this.data.array[ index + 0 ] = x;
  15994. this.data.array[ index + 1 ] = y;
  15995. this.data.array[ index + 2 ] = z;
  15996. this.data.array[ index + 3 ] = w;
  15997. return this;
  15998. },
  15999. clone: function ( data ) {
  16000. if ( data === undefined ) {
  16001. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.' );
  16002. const array = [];
  16003. for ( let i = 0; i < this.count; i ++ ) {
  16004. const index = i * this.data.stride + this.offset;
  16005. for ( let j = 0; j < this.itemSize; j ++ ) {
  16006. array.push( this.data.array[ index + j ] );
  16007. }
  16008. }
  16009. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  16010. } else {
  16011. if ( data.interleavedBuffers === undefined ) {
  16012. data.interleavedBuffers = {};
  16013. }
  16014. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  16015. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  16016. }
  16017. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  16018. }
  16019. },
  16020. toJSON: function ( data ) {
  16021. if ( data === undefined ) {
  16022. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.' );
  16023. const array = [];
  16024. for ( let i = 0; i < this.count; i ++ ) {
  16025. const index = i * this.data.stride + this.offset;
  16026. for ( let j = 0; j < this.itemSize; j ++ ) {
  16027. array.push( this.data.array[ index + j ] );
  16028. }
  16029. }
  16030. // deinterleave data and save it as an ordinary buffer attribute for now
  16031. return {
  16032. itemSize: this.itemSize,
  16033. type: this.array.constructor.name,
  16034. array: array,
  16035. normalized: this.normalized
  16036. };
  16037. } else {
  16038. // save as true interlaved attribtue
  16039. if ( data.interleavedBuffers === undefined ) {
  16040. data.interleavedBuffers = {};
  16041. }
  16042. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  16043. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  16044. }
  16045. return {
  16046. isInterleavedBufferAttribute: true,
  16047. itemSize: this.itemSize,
  16048. data: this.data.uuid,
  16049. offset: this.offset,
  16050. normalized: this.normalized
  16051. };
  16052. }
  16053. }
  16054. } );
  16055. /**
  16056. * parameters = {
  16057. * color: <hex>,
  16058. * map: new THREE.Texture( <Image> ),
  16059. * alphaMap: new THREE.Texture( <Image> ),
  16060. * rotation: <float>,
  16061. * sizeAttenuation: <bool>
  16062. * }
  16063. */
  16064. function SpriteMaterial( parameters ) {
  16065. Material.call( this );
  16066. this.type = 'SpriteMaterial';
  16067. this.color = new Color( 0xffffff );
  16068. this.map = null;
  16069. this.alphaMap = null;
  16070. this.rotation = 0;
  16071. this.sizeAttenuation = true;
  16072. this.transparent = true;
  16073. this.setValues( parameters );
  16074. }
  16075. SpriteMaterial.prototype = Object.create( Material.prototype );
  16076. SpriteMaterial.prototype.constructor = SpriteMaterial;
  16077. SpriteMaterial.prototype.isSpriteMaterial = true;
  16078. SpriteMaterial.prototype.copy = function ( source ) {
  16079. Material.prototype.copy.call( this, source );
  16080. this.color.copy( source.color );
  16081. this.map = source.map;
  16082. this.alphaMap = source.alphaMap;
  16083. this.rotation = source.rotation;
  16084. this.sizeAttenuation = source.sizeAttenuation;
  16085. return this;
  16086. };
  16087. let _geometry;
  16088. const _intersectPoint = new Vector3();
  16089. const _worldScale = new Vector3();
  16090. const _mvPosition = new Vector3();
  16091. const _alignedPosition = new Vector2$1();
  16092. const _rotatedPosition = new Vector2$1();
  16093. const _viewWorldMatrix = new Matrix4();
  16094. const _vA$1 = new Vector3();
  16095. const _vB$1 = new Vector3();
  16096. const _vC$1 = new Vector3();
  16097. const _uvA$1 = new Vector2$1();
  16098. const _uvB$1 = new Vector2$1();
  16099. const _uvC$1 = new Vector2$1();
  16100. function Sprite( material ) {
  16101. Object3D.call( this );
  16102. this.type = 'Sprite';
  16103. if ( _geometry === undefined ) {
  16104. _geometry = new BufferGeometry();
  16105. const float32Array = new Float32Array( [
  16106. - 0.5, - 0.5, 0, 0, 0,
  16107. 0.5, - 0.5, 0, 1, 0,
  16108. 0.5, 0.5, 0, 1, 1,
  16109. - 0.5, 0.5, 0, 0, 1
  16110. ] );
  16111. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  16112. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  16113. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  16114. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  16115. }
  16116. this.geometry = _geometry;
  16117. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  16118. this.center = new Vector2$1( 0.5, 0.5 );
  16119. }
  16120. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16121. constructor: Sprite,
  16122. isSprite: true,
  16123. raycast: function ( raycaster, intersects ) {
  16124. if ( raycaster.camera === null ) {
  16125. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  16126. }
  16127. _worldScale.setFromMatrixScale( this.matrixWorld );
  16128. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  16129. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  16130. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  16131. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  16132. _worldScale.multiplyScalar( - _mvPosition.z );
  16133. }
  16134. const rotation = this.material.rotation;
  16135. let sin, cos;
  16136. if ( rotation !== 0 ) {
  16137. cos = Math.cos( rotation );
  16138. sin = Math.sin( rotation );
  16139. }
  16140. const center = this.center;
  16141. transformVertex( _vA$1.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16142. transformVertex( _vB$1.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16143. transformVertex( _vC$1.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16144. _uvA$1.set( 0, 0 );
  16145. _uvB$1.set( 1, 0 );
  16146. _uvC$1.set( 1, 1 );
  16147. // check first triangle
  16148. let intersect = raycaster.ray.intersectTriangle( _vA$1, _vB$1, _vC$1, false, _intersectPoint );
  16149. if ( intersect === null ) {
  16150. // check second triangle
  16151. transformVertex( _vB$1.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  16152. _uvB$1.set( 0, 1 );
  16153. intersect = raycaster.ray.intersectTriangle( _vA$1, _vC$1, _vB$1, false, _intersectPoint );
  16154. if ( intersect === null ) {
  16155. return;
  16156. }
  16157. }
  16158. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  16159. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16160. intersects.push( {
  16161. distance: distance,
  16162. point: _intersectPoint.clone(),
  16163. uv: Triangle.getUV( _intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2$1() ),
  16164. face: null,
  16165. object: this
  16166. } );
  16167. },
  16168. copy: function ( source ) {
  16169. Object3D.prototype.copy.call( this, source );
  16170. if ( source.center !== undefined ) this.center.copy( source.center );
  16171. this.material = source.material;
  16172. return this;
  16173. }
  16174. } );
  16175. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  16176. // compute position in camera space
  16177. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  16178. // to check if rotation is not zero
  16179. if ( sin !== undefined ) {
  16180. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  16181. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  16182. } else {
  16183. _rotatedPosition.copy( _alignedPosition );
  16184. }
  16185. vertexPosition.copy( mvPosition );
  16186. vertexPosition.x += _rotatedPosition.x;
  16187. vertexPosition.y += _rotatedPosition.y;
  16188. // transform to world space
  16189. vertexPosition.applyMatrix4( _viewWorldMatrix );
  16190. }
  16191. const _v1$4 = new Vector3();
  16192. const _v2$2 = new Vector3();
  16193. function LOD() {
  16194. Object3D.call( this );
  16195. this._currentLevel = 0;
  16196. this.type = 'LOD';
  16197. Object.defineProperties( this, {
  16198. levels: {
  16199. enumerable: true,
  16200. value: []
  16201. }
  16202. } );
  16203. this.autoUpdate = true;
  16204. }
  16205. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16206. constructor: LOD,
  16207. isLOD: true,
  16208. copy: function ( source ) {
  16209. Object3D.prototype.copy.call( this, source, false );
  16210. const levels = source.levels;
  16211. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16212. const level = levels[ i ];
  16213. this.addLevel( level.object.clone(), level.distance );
  16214. }
  16215. this.autoUpdate = source.autoUpdate;
  16216. return this;
  16217. },
  16218. addLevel: function ( object, distance = 0 ) {
  16219. distance = Math.abs( distance );
  16220. const levels = this.levels;
  16221. let l;
  16222. for ( l = 0; l < levels.length; l ++ ) {
  16223. if ( distance < levels[ l ].distance ) {
  16224. break;
  16225. }
  16226. }
  16227. levels.splice( l, 0, { distance: distance, object: object } );
  16228. this.add( object );
  16229. return this;
  16230. },
  16231. getCurrentLevel: function () {
  16232. return this._currentLevel;
  16233. },
  16234. getObjectForDistance: function ( distance ) {
  16235. const levels = this.levels;
  16236. if ( levels.length > 0 ) {
  16237. let i, l;
  16238. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16239. if ( distance < levels[ i ].distance ) {
  16240. break;
  16241. }
  16242. }
  16243. return levels[ i - 1 ].object;
  16244. }
  16245. return null;
  16246. },
  16247. raycast: function ( raycaster, intersects ) {
  16248. const levels = this.levels;
  16249. if ( levels.length > 0 ) {
  16250. _v1$4.setFromMatrixPosition( this.matrixWorld );
  16251. const distance = raycaster.ray.origin.distanceTo( _v1$4 );
  16252. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  16253. }
  16254. },
  16255. update: function ( camera ) {
  16256. const levels = this.levels;
  16257. if ( levels.length > 1 ) {
  16258. _v1$4.setFromMatrixPosition( camera.matrixWorld );
  16259. _v2$2.setFromMatrixPosition( this.matrixWorld );
  16260. const distance = _v1$4.distanceTo( _v2$2 ) / camera.zoom;
  16261. levels[ 0 ].object.visible = true;
  16262. let i, l;
  16263. for ( i = 1, l = levels.length; i < l; i ++ ) {
  16264. if ( distance >= levels[ i ].distance ) {
  16265. levels[ i - 1 ].object.visible = false;
  16266. levels[ i ].object.visible = true;
  16267. } else {
  16268. break;
  16269. }
  16270. }
  16271. this._currentLevel = i - 1;
  16272. for ( ; i < l; i ++ ) {
  16273. levels[ i ].object.visible = false;
  16274. }
  16275. }
  16276. },
  16277. toJSON: function ( meta ) {
  16278. const data = Object3D.prototype.toJSON.call( this, meta );
  16279. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  16280. data.object.levels = [];
  16281. const levels = this.levels;
  16282. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  16283. const level = levels[ i ];
  16284. data.object.levels.push( {
  16285. object: level.object.uuid,
  16286. distance: level.distance
  16287. } );
  16288. }
  16289. return data;
  16290. }
  16291. } );
  16292. const _basePosition = new Vector3();
  16293. const _skinIndex = new Vector4();
  16294. const _skinWeight = new Vector4();
  16295. const _vector$7 = new Vector3();
  16296. const _matrix$1 = new Matrix4();
  16297. function SkinnedMesh( geometry, material ) {
  16298. if ( geometry && geometry.isGeometry ) {
  16299. console.error( 'THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16300. }
  16301. Mesh.call( this, geometry, material );
  16302. this.type = 'SkinnedMesh';
  16303. this.bindMode = 'attached';
  16304. this.bindMatrix = new Matrix4();
  16305. this.bindMatrixInverse = new Matrix4();
  16306. }
  16307. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  16308. constructor: SkinnedMesh,
  16309. isSkinnedMesh: true,
  16310. copy: function ( source ) {
  16311. Mesh.prototype.copy.call( this, source );
  16312. this.bindMode = source.bindMode;
  16313. this.bindMatrix.copy( source.bindMatrix );
  16314. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  16315. this.skeleton = source.skeleton;
  16316. return this;
  16317. },
  16318. bind: function ( skeleton, bindMatrix ) {
  16319. this.skeleton = skeleton;
  16320. if ( bindMatrix === undefined ) {
  16321. this.updateMatrixWorld( true );
  16322. this.skeleton.calculateInverses();
  16323. bindMatrix = this.matrixWorld;
  16324. }
  16325. this.bindMatrix.copy( bindMatrix );
  16326. this.bindMatrixInverse.copy( bindMatrix ).invert();
  16327. },
  16328. pose: function () {
  16329. this.skeleton.pose();
  16330. },
  16331. normalizeSkinWeights: function () {
  16332. const vector = new Vector4();
  16333. const skinWeight = this.geometry.attributes.skinWeight;
  16334. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  16335. vector.x = skinWeight.getX( i );
  16336. vector.y = skinWeight.getY( i );
  16337. vector.z = skinWeight.getZ( i );
  16338. vector.w = skinWeight.getW( i );
  16339. const scale = 1.0 / vector.manhattanLength();
  16340. if ( scale !== Infinity ) {
  16341. vector.multiplyScalar( scale );
  16342. } else {
  16343. vector.set( 1, 0, 0, 0 ); // do something reasonable
  16344. }
  16345. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  16346. }
  16347. },
  16348. updateMatrixWorld: function ( force ) {
  16349. Mesh.prototype.updateMatrixWorld.call( this, force );
  16350. if ( this.bindMode === 'attached' ) {
  16351. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  16352. } else if ( this.bindMode === 'detached' ) {
  16353. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  16354. } else {
  16355. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  16356. }
  16357. },
  16358. boneTransform: function ( index, target ) {
  16359. const skeleton = this.skeleton;
  16360. const geometry = this.geometry;
  16361. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  16362. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  16363. _basePosition.fromBufferAttribute( geometry.attributes.position, index ).applyMatrix4( this.bindMatrix );
  16364. target.set( 0, 0, 0 );
  16365. for ( let i = 0; i < 4; i ++ ) {
  16366. const weight = _skinWeight.getComponent( i );
  16367. if ( weight !== 0 ) {
  16368. const boneIndex = _skinIndex.getComponent( i );
  16369. _matrix$1.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  16370. target.addScaledVector( _vector$7.copy( _basePosition ).applyMatrix4( _matrix$1 ), weight );
  16371. }
  16372. }
  16373. return target.applyMatrix4( this.bindMatrixInverse );
  16374. }
  16375. } );
  16376. function Bone() {
  16377. Object3D.call( this );
  16378. this.type = 'Bone';
  16379. }
  16380. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16381. constructor: Bone,
  16382. isBone: true
  16383. } );
  16384. const _offsetMatrix = new Matrix4();
  16385. const _identityMatrix = new Matrix4();
  16386. function Skeleton( bones = [], boneInverses = [] ) {
  16387. this.uuid = MathUtils.generateUUID();
  16388. this.bones = bones.slice( 0 );
  16389. this.boneInverses = boneInverses;
  16390. this.boneMatrices = null;
  16391. this.boneTexture = null;
  16392. this.boneTextureSize = 0;
  16393. this.frame = - 1;
  16394. this.init();
  16395. }
  16396. Object.assign( Skeleton.prototype, {
  16397. init: function () {
  16398. const bones = this.bones;
  16399. const boneInverses = this.boneInverses;
  16400. this.boneMatrices = new Float32Array( bones.length * 16 );
  16401. // calculate inverse bone matrices if necessary
  16402. if ( boneInverses.length === 0 ) {
  16403. this.calculateInverses();
  16404. } else {
  16405. // handle special case
  16406. if ( bones.length !== boneInverses.length ) {
  16407. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  16408. this.boneInverses = [];
  16409. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16410. this.boneInverses.push( new Matrix4() );
  16411. }
  16412. }
  16413. }
  16414. },
  16415. calculateInverses: function () {
  16416. this.boneInverses.length = 0;
  16417. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16418. const inverse = new Matrix4();
  16419. if ( this.bones[ i ] ) {
  16420. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  16421. }
  16422. this.boneInverses.push( inverse );
  16423. }
  16424. },
  16425. pose: function () {
  16426. // recover the bind-time world matrices
  16427. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16428. const bone = this.bones[ i ];
  16429. if ( bone ) {
  16430. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  16431. }
  16432. }
  16433. // compute the local matrices, positions, rotations and scales
  16434. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16435. const bone = this.bones[ i ];
  16436. if ( bone ) {
  16437. if ( bone.parent && bone.parent.isBone ) {
  16438. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  16439. bone.matrix.multiply( bone.matrixWorld );
  16440. } else {
  16441. bone.matrix.copy( bone.matrixWorld );
  16442. }
  16443. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  16444. }
  16445. }
  16446. },
  16447. update: function () {
  16448. const bones = this.bones;
  16449. const boneInverses = this.boneInverses;
  16450. const boneMatrices = this.boneMatrices;
  16451. const boneTexture = this.boneTexture;
  16452. // flatten bone matrices to array
  16453. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  16454. // compute the offset between the current and the original transform
  16455. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  16456. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  16457. _offsetMatrix.toArray( boneMatrices, i * 16 );
  16458. }
  16459. if ( boneTexture !== null ) {
  16460. boneTexture.needsUpdate = true;
  16461. }
  16462. },
  16463. clone: function () {
  16464. return new Skeleton( this.bones, this.boneInverses );
  16465. },
  16466. getBoneByName: function ( name ) {
  16467. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  16468. const bone = this.bones[ i ];
  16469. if ( bone.name === name ) {
  16470. return bone;
  16471. }
  16472. }
  16473. return undefined;
  16474. },
  16475. dispose: function ( ) {
  16476. if ( this.boneTexture !== null ) {
  16477. this.boneTexture.dispose();
  16478. this.boneTexture = null;
  16479. }
  16480. },
  16481. fromJSON: function ( json, bones ) {
  16482. this.uuid = json.uuid;
  16483. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  16484. const uuid = json.bones[ i ];
  16485. let bone = bones[ uuid ];
  16486. if ( bone === undefined ) {
  16487. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  16488. bone = new Bone();
  16489. }
  16490. this.bones.push( bone );
  16491. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  16492. }
  16493. this.init();
  16494. return this;
  16495. },
  16496. toJSON: function () {
  16497. const data = {
  16498. metadata: {
  16499. version: 4.5,
  16500. type: 'Skeleton',
  16501. generator: 'Skeleton.toJSON'
  16502. },
  16503. bones: [],
  16504. boneInverses: []
  16505. };
  16506. data.uuid = this.uuid;
  16507. const bones = this.bones;
  16508. const boneInverses = this.boneInverses;
  16509. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  16510. const bone = bones[ i ];
  16511. data.bones.push( bone.uuid );
  16512. const boneInverse = boneInverses[ i ];
  16513. data.boneInverses.push( boneInverse.toArray() );
  16514. }
  16515. return data;
  16516. }
  16517. } );
  16518. const _instanceLocalMatrix = new Matrix4();
  16519. const _instanceWorldMatrix = new Matrix4();
  16520. const _instanceIntersects = [];
  16521. const _mesh = new Mesh();
  16522. function InstancedMesh( geometry, material, count ) {
  16523. Mesh.call( this, geometry, material );
  16524. this.instanceMatrix = new BufferAttribute( new Float32Array( count * 16 ), 16 );
  16525. this.instanceColor = null;
  16526. this.count = count;
  16527. this.frustumCulled = false;
  16528. }
  16529. InstancedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  16530. constructor: InstancedMesh,
  16531. isInstancedMesh: true,
  16532. copy: function ( source ) {
  16533. Mesh.prototype.copy.call( this, source );
  16534. this.instanceMatrix.copy( source.instanceMatrix );
  16535. this.count = source.count;
  16536. return this;
  16537. },
  16538. getColorAt: function ( index, color ) {
  16539. color.fromArray( this.instanceColor.array, index * 3 );
  16540. },
  16541. getMatrixAt: function ( index, matrix ) {
  16542. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  16543. },
  16544. raycast: function ( raycaster, intersects ) {
  16545. const matrixWorld = this.matrixWorld;
  16546. const raycastTimes = this.count;
  16547. _mesh.geometry = this.geometry;
  16548. _mesh.material = this.material;
  16549. if ( _mesh.material === undefined ) return;
  16550. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  16551. // calculate the world matrix for each instance
  16552. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  16553. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  16554. // the mesh represents this single instance
  16555. _mesh.matrixWorld = _instanceWorldMatrix;
  16556. _mesh.raycast( raycaster, _instanceIntersects );
  16557. // process the result of raycast
  16558. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  16559. const intersect = _instanceIntersects[ i ];
  16560. intersect.instanceId = instanceId;
  16561. intersect.object = this;
  16562. intersects.push( intersect );
  16563. }
  16564. _instanceIntersects.length = 0;
  16565. }
  16566. },
  16567. setColorAt: function ( index, color ) {
  16568. if ( this.instanceColor === null ) {
  16569. this.instanceColor = new BufferAttribute( new Float32Array( this.count * 3 ), 3 );
  16570. }
  16571. color.toArray( this.instanceColor.array, index * 3 );
  16572. },
  16573. setMatrixAt: function ( index, matrix ) {
  16574. matrix.toArray( this.instanceMatrix.array, index * 16 );
  16575. },
  16576. updateMorphTargets: function () {
  16577. },
  16578. dispose: function () {
  16579. this.dispatchEvent( { type: 'dispose' } );
  16580. }
  16581. } );
  16582. /**
  16583. * parameters = {
  16584. * color: <hex>,
  16585. * opacity: <float>,
  16586. *
  16587. * lineWidth: <float>,
  16588. * linecap: "round",
  16589. * linejoin: "round"
  16590. * }
  16591. */
  16592. function LineBasicMaterial( parameters ) {
  16593. Material.call( this );
  16594. this.type = 'LineBasicMaterial';
  16595. this.color = new Color( 0xffffff );
  16596. this.lineWidth = 1;
  16597. this.linecap = 'round';
  16598. this.linejoin = 'round';
  16599. this.morphTargets = false;
  16600. this.setValues( parameters );
  16601. }
  16602. LineBasicMaterial.prototype = Object.create( Material.prototype );
  16603. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  16604. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16605. LineBasicMaterial.prototype.copy = function ( source ) {
  16606. Material.prototype.copy.call( this, source );
  16607. this.color.copy( source.color );
  16608. this.lineWidth = source.lineWidth;
  16609. this.linecap = source.linecap;
  16610. this.linejoin = source.linejoin;
  16611. this.morphTargets = source.morphTargets;
  16612. return this;
  16613. };
  16614. const _start = new Vector3();
  16615. const _end = new Vector3();
  16616. const _inverseMatrix$1 = new Matrix4();
  16617. const _ray$1 = new Ray();
  16618. const _sphere$2 = new Sphere();
  16619. function Line( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  16620. Object3D.call( this );
  16621. this.type = 'Line';
  16622. this.geometry = geometry;
  16623. this.material = material;
  16624. this.updateMorphTargets();
  16625. }
  16626. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16627. constructor: Line,
  16628. isLine: true,
  16629. copy: function ( source ) {
  16630. Object3D.prototype.copy.call( this, source );
  16631. this.material = source.material;
  16632. this.geometry = source.geometry;
  16633. return this;
  16634. },
  16635. computeLineDistances: function () {
  16636. const geometry = this.geometry;
  16637. if ( geometry.isBufferGeometry ) {
  16638. // we assume non-indexed geometry
  16639. if ( geometry.index === null ) {
  16640. const positionAttribute = geometry.attributes.position;
  16641. const lineDistances = [ 0 ];
  16642. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  16643. _start.fromBufferAttribute( positionAttribute, i - 1 );
  16644. _end.fromBufferAttribute( positionAttribute, i );
  16645. lineDistances[ i ] = lineDistances[ i - 1 ];
  16646. lineDistances[ i ] += _start.distanceTo( _end );
  16647. }
  16648. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  16649. } else {
  16650. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  16651. }
  16652. } else if ( geometry.isGeometry ) {
  16653. const vertices = geometry.vertices;
  16654. const lineDistances = geometry.lineDistances;
  16655. lineDistances[ 0 ] = 0;
  16656. for ( let i = 1, l = vertices.length; i < l; i ++ ) {
  16657. lineDistances[ i ] = lineDistances[ i - 1 ];
  16658. lineDistances[ i ] += vertices[ i - 1 ].distanceTo( vertices[ i ] );
  16659. }
  16660. }
  16661. return this;
  16662. },
  16663. raycast: function ( raycaster, intersects ) {
  16664. const geometry = this.geometry;
  16665. const matrixWorld = this.matrixWorld;
  16666. const threshold = raycaster.params.Line.threshold;
  16667. // Checking boundingSphere distance to ray
  16668. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  16669. _sphere$2.copy( geometry.boundingSphere );
  16670. _sphere$2.applyMatrix4( matrixWorld );
  16671. _sphere$2.radius += threshold;
  16672. if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return;
  16673. //
  16674. _inverseMatrix$1.copy( matrixWorld ).invert();
  16675. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  16676. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  16677. const localThresholdSq = localThreshold * localThreshold;
  16678. const vStart = new Vector3();
  16679. const vEnd = new Vector3();
  16680. const interSegment = new Vector3();
  16681. const interRay = new Vector3();
  16682. const step = this.isLineSegments ? 2 : 1;
  16683. if ( geometry.isBufferGeometry ) {
  16684. const index = geometry.index;
  16685. const attributes = geometry.attributes;
  16686. const positionAttribute = attributes.position;
  16687. if ( index !== null ) {
  16688. const indices = index.array;
  16689. for ( let i = 0, l = indices.length - 1; i < l; i += step ) {
  16690. const a = indices[ i ];
  16691. const b = indices[ i + 1 ];
  16692. vStart.fromBufferAttribute( positionAttribute, a );
  16693. vEnd.fromBufferAttribute( positionAttribute, b );
  16694. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  16695. if ( distSq > localThresholdSq ) continue;
  16696. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  16697. const distance = raycaster.ray.origin.distanceTo( interRay );
  16698. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  16699. intersects.push( {
  16700. distance: distance,
  16701. // What do we want? intersection point on the ray or on the segment??
  16702. // point: raycaster.ray.at( distance ),
  16703. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  16704. index: i,
  16705. face: null,
  16706. faceIndex: null,
  16707. object: this
  16708. } );
  16709. }
  16710. } else {
  16711. for ( let i = 0, l = positionAttribute.count - 1; i < l; i += step ) {
  16712. vStart.fromBufferAttribute( positionAttribute, i );
  16713. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  16714. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  16715. if ( distSq > localThresholdSq ) continue;
  16716. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  16717. const distance = raycaster.ray.origin.distanceTo( interRay );
  16718. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  16719. intersects.push( {
  16720. distance: distance,
  16721. // What do we want? intersection point on the ray or on the segment??
  16722. // point: raycaster.ray.at( distance ),
  16723. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  16724. index: i,
  16725. face: null,
  16726. faceIndex: null,
  16727. object: this
  16728. } );
  16729. }
  16730. }
  16731. } else if ( geometry.isGeometry ) {
  16732. const vertices = geometry.vertices;
  16733. const nbVertices = vertices.length;
  16734. for ( let i = 0; i < nbVertices - 1; i += step ) {
  16735. const distSq = _ray$1.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  16736. if ( distSq > localThresholdSq ) continue;
  16737. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  16738. const distance = raycaster.ray.origin.distanceTo( interRay );
  16739. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  16740. intersects.push( {
  16741. distance: distance,
  16742. // What do we want? intersection point on the ray or on the segment??
  16743. // point: raycaster.ray.at( distance ),
  16744. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  16745. index: i,
  16746. face: null,
  16747. faceIndex: null,
  16748. object: this
  16749. } );
  16750. }
  16751. }
  16752. },
  16753. updateMorphTargets: function () {
  16754. const geometry = this.geometry;
  16755. if ( geometry.isBufferGeometry ) {
  16756. const morphAttributes = geometry.morphAttributes;
  16757. const keys = Object.keys( morphAttributes );
  16758. if ( keys.length > 0 ) {
  16759. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  16760. if ( morphAttribute !== undefined ) {
  16761. this.morphTargetInfluences = [];
  16762. this.morphTargetDictionary = {};
  16763. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  16764. const name = morphAttribute[ m ].name || String( m );
  16765. this.morphTargetInfluences.push( 0 );
  16766. this.morphTargetDictionary[ name ] = m;
  16767. }
  16768. }
  16769. }
  16770. } else {
  16771. const morphTargets = geometry.morphTargets;
  16772. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  16773. console.error( 'THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16774. }
  16775. }
  16776. }
  16777. } );
  16778. const _start$1 = new Vector3();
  16779. const _end$1 = new Vector3();
  16780. function LineSegments( geometry, material ) {
  16781. Line.call( this, geometry, material );
  16782. this.type = 'LineSegments';
  16783. }
  16784. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  16785. constructor: LineSegments,
  16786. isLineSegments: true,
  16787. computeLineDistances: function () {
  16788. const geometry = this.geometry;
  16789. if ( geometry.isBufferGeometry ) {
  16790. // we assume non-indexed geometry
  16791. if ( geometry.index === null ) {
  16792. const positionAttribute = geometry.attributes.position;
  16793. const lineDistances = [];
  16794. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  16795. _start$1.fromBufferAttribute( positionAttribute, i );
  16796. _end$1.fromBufferAttribute( positionAttribute, i + 1 );
  16797. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  16798. lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );
  16799. }
  16800. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  16801. } else {
  16802. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  16803. }
  16804. } else if ( geometry.isGeometry ) {
  16805. const vertices = geometry.vertices;
  16806. const lineDistances = geometry.lineDistances;
  16807. for ( let i = 0, l = vertices.length; i < l; i += 2 ) {
  16808. _start$1.copy( vertices[ i ] );
  16809. _end$1.copy( vertices[ i + 1 ] );
  16810. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  16811. lineDistances[ i + 1 ] = lineDistances[ i ] + _start$1.distanceTo( _end$1 );
  16812. }
  16813. }
  16814. return this;
  16815. }
  16816. } );
  16817. function LineLoop( geometry, material ) {
  16818. Line.call( this, geometry, material );
  16819. this.type = 'LineLoop';
  16820. }
  16821. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  16822. constructor: LineLoop,
  16823. isLineLoop: true,
  16824. } );
  16825. /**
  16826. * parameters = {
  16827. * color: <hex>,
  16828. * opacity: <float>,
  16829. * map: new THREE.Texture( <Image> ),
  16830. * alphaMap: new THREE.Texture( <Image> ),
  16831. *
  16832. * size: <float>,
  16833. * sizeAttenuation: <bool>
  16834. *
  16835. * morphTargets: <bool>
  16836. * }
  16837. */
  16838. function PointsMaterial( parameters ) {
  16839. Material.call( this );
  16840. this.type = 'PointsMaterial';
  16841. this.color = new Color( 0xffffff );
  16842. this.map = null;
  16843. this.alphaMap = null;
  16844. this.size = 1;
  16845. this.sizeAttenuation = true;
  16846. this.morphTargets = false;
  16847. this.setValues( parameters );
  16848. }
  16849. PointsMaterial.prototype = Object.create( Material.prototype );
  16850. PointsMaterial.prototype.constructor = PointsMaterial;
  16851. PointsMaterial.prototype.isPointsMaterial = true;
  16852. PointsMaterial.prototype.copy = function ( source ) {
  16853. Material.prototype.copy.call( this, source );
  16854. this.color.copy( source.color );
  16855. this.map = source.map;
  16856. this.alphaMap = source.alphaMap;
  16857. this.size = source.size;
  16858. this.sizeAttenuation = source.sizeAttenuation;
  16859. this.morphTargets = source.morphTargets;
  16860. return this;
  16861. };
  16862. const _inverseMatrix$2 = new Matrix4();
  16863. const _ray$2 = new Ray();
  16864. const _sphere$3 = new Sphere();
  16865. const _position$1 = new Vector3();
  16866. function Points( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  16867. Object3D.call( this );
  16868. this.type = 'Points';
  16869. this.geometry = geometry;
  16870. this.material = material;
  16871. this.updateMorphTargets();
  16872. }
  16873. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  16874. constructor: Points,
  16875. isPoints: true,
  16876. copy: function ( source ) {
  16877. Object3D.prototype.copy.call( this, source );
  16878. this.material = source.material;
  16879. this.geometry = source.geometry;
  16880. return this;
  16881. },
  16882. raycast: function ( raycaster, intersects ) {
  16883. const geometry = this.geometry;
  16884. const matrixWorld = this.matrixWorld;
  16885. const threshold = raycaster.params.Points.threshold;
  16886. // Checking boundingSphere distance to ray
  16887. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  16888. _sphere$3.copy( geometry.boundingSphere );
  16889. _sphere$3.applyMatrix4( matrixWorld );
  16890. _sphere$3.radius += threshold;
  16891. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  16892. //
  16893. _inverseMatrix$2.copy( matrixWorld ).invert();
  16894. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  16895. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  16896. const localThresholdSq = localThreshold * localThreshold;
  16897. if ( geometry.isBufferGeometry ) {
  16898. const index = geometry.index;
  16899. const attributes = geometry.attributes;
  16900. const positionAttribute = attributes.position;
  16901. if ( index !== null ) {
  16902. const indices = index.array;
  16903. for ( let i = 0, il = indices.length; i < il; i ++ ) {
  16904. const a = indices[ i ];
  16905. _position$1.fromBufferAttribute( positionAttribute, a );
  16906. testPoint( _position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16907. }
  16908. } else {
  16909. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  16910. _position$1.fromBufferAttribute( positionAttribute, i );
  16911. testPoint( _position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16912. }
  16913. }
  16914. } else {
  16915. const vertices = geometry.vertices;
  16916. for ( let i = 0, l = vertices.length; i < l; i ++ ) {
  16917. testPoint( vertices[ i ], i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  16918. }
  16919. }
  16920. },
  16921. updateMorphTargets: function () {
  16922. const geometry = this.geometry;
  16923. if ( geometry.isBufferGeometry ) {
  16924. const morphAttributes = geometry.morphAttributes;
  16925. const keys = Object.keys( morphAttributes );
  16926. if ( keys.length > 0 ) {
  16927. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  16928. if ( morphAttribute !== undefined ) {
  16929. this.morphTargetInfluences = [];
  16930. this.morphTargetDictionary = {};
  16931. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  16932. const name = morphAttribute[ m ].name || String( m );
  16933. this.morphTargetInfluences.push( 0 );
  16934. this.morphTargetDictionary[ name ] = m;
  16935. }
  16936. }
  16937. }
  16938. } else {
  16939. const morphTargets = geometry.morphTargets;
  16940. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  16941. console.error( 'THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.' );
  16942. }
  16943. }
  16944. }
  16945. } );
  16946. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  16947. const rayPointDistanceSq = _ray$2.distanceSqToPoint( point );
  16948. if ( rayPointDistanceSq < localThresholdSq ) {
  16949. const intersectPoint = new Vector3();
  16950. _ray$2.closestPointToPoint( point, intersectPoint );
  16951. intersectPoint.applyMatrix4( matrixWorld );
  16952. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  16953. if ( distance < raycaster.near || distance > raycaster.far ) return;
  16954. intersects.push( {
  16955. distance: distance,
  16956. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  16957. point: intersectPoint,
  16958. index: index,
  16959. face: null,
  16960. object: object
  16961. } );
  16962. }
  16963. }
  16964. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  16965. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  16966. this.format = format !== undefined ? format : RGBFormat;
  16967. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16968. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16969. this.generateMipmaps = false;
  16970. const scope = this;
  16971. function updateVideo() {
  16972. scope.needsUpdate = true;
  16973. video.requestVideoFrameCallback( updateVideo );
  16974. }
  16975. if ( 'requestVideoFrameCallback' in video ) {
  16976. video.requestVideoFrameCallback( updateVideo );
  16977. }
  16978. }
  16979. VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), {
  16980. constructor: VideoTexture,
  16981. clone: function () {
  16982. return new this.constructor( this.image ).copy( this );
  16983. },
  16984. isVideoTexture: true,
  16985. update: function () {
  16986. const video = this.image;
  16987. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  16988. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  16989. this.needsUpdate = true;
  16990. }
  16991. }
  16992. } );
  16993. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  16994. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  16995. this.image = { width: width, height: height };
  16996. this.mipmaps = mipmaps;
  16997. // no flipping for cube textures
  16998. // (also flipping doesn't work for compressed textures )
  16999. this.flipY = false;
  17000. // can't generate mipmaps for compressed textures
  17001. // mips must be embedded in DDS files
  17002. this.generateMipmaps = false;
  17003. }
  17004. CompressedTexture.prototype = Object.create( Texture.prototype );
  17005. CompressedTexture.prototype.constructor = CompressedTexture;
  17006. CompressedTexture.prototype.isCompressedTexture = true;
  17007. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  17008. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17009. this.needsUpdate = true;
  17010. }
  17011. CanvasTexture.prototype = Object.create( Texture.prototype );
  17012. CanvasTexture.prototype.constructor = CanvasTexture;
  17013. CanvasTexture.prototype.isCanvasTexture = true;
  17014. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  17015. format = format !== undefined ? format : DepthFormat;
  17016. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  17017. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  17018. }
  17019. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  17020. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type$1;
  17021. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  17022. this.image = { width: width, height: height };
  17023. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  17024. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  17025. this.flipY = false;
  17026. this.generateMipmaps = false;
  17027. }
  17028. DepthTexture.prototype = Object.create( Texture.prototype );
  17029. DepthTexture.prototype.constructor = DepthTexture;
  17030. DepthTexture.prototype.isDepthTexture = true;
  17031. let _geometryId = 0; // Geometry uses even numbers as Id
  17032. const _m1$3 = new Matrix4();
  17033. const _obj$1 = new Object3D();
  17034. const _offset$1 = new Vector3();
  17035. function Geometry() {
  17036. Object.defineProperty( this, 'id', { value: _geometryId += 2 } );
  17037. this.uuid = MathUtils.generateUUID();
  17038. this.name = '';
  17039. this.type = 'Geometry';
  17040. this.vertices = [];
  17041. this.colors = [];
  17042. this.faces = [];
  17043. this.faceVertexUvs = [[]];
  17044. this.morphTargets = [];
  17045. this.morphNormals = [];
  17046. this.skinWeights = [];
  17047. this.skinIndices = [];
  17048. this.lineDistances = [];
  17049. this.boundingBox = null;
  17050. this.boundingSphere = null;
  17051. // update flags
  17052. this.elementsNeedUpdate = false;
  17053. this.verticesNeedUpdate = false;
  17054. this.uvsNeedUpdate = false;
  17055. this.normalsNeedUpdate = false;
  17056. this.colorsNeedUpdate = false;
  17057. this.lineDistancesNeedUpdate = false;
  17058. this.groupsNeedUpdate = false;
  17059. }
  17060. Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  17061. constructor: Geometry,
  17062. isGeometry: true,
  17063. applyMatrix4: function ( matrix ) {
  17064. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  17065. for ( let i = 0, il = this.vertices.length; i < il; i ++ ) {
  17066. const vertex = this.vertices[ i ];
  17067. vertex.applyMatrix4( matrix );
  17068. }
  17069. for ( let i = 0, il = this.faces.length; i < il; i ++ ) {
  17070. const face = this.faces[ i ];
  17071. face.normal.applyMatrix3( normalMatrix ).normalize();
  17072. for ( let j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  17073. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  17074. }
  17075. }
  17076. if ( this.boundingBox !== null ) {
  17077. this.computeBoundingBox();
  17078. }
  17079. if ( this.boundingSphere !== null ) {
  17080. this.computeBoundingSphere();
  17081. }
  17082. this.verticesNeedUpdate = true;
  17083. this.normalsNeedUpdate = true;
  17084. return this;
  17085. },
  17086. rotateX: function ( angle ) {
  17087. // rotate geometry around world x-axis
  17088. _m1$3.makeRotationX( angle );
  17089. this.applyMatrix4( _m1$3 );
  17090. return this;
  17091. },
  17092. rotateY: function ( angle ) {
  17093. // rotate geometry around world y-axis
  17094. _m1$3.makeRotationY( angle );
  17095. this.applyMatrix4( _m1$3 );
  17096. return this;
  17097. },
  17098. rotateZ: function ( angle ) {
  17099. // rotate geometry around world z-axis
  17100. _m1$3.makeRotationZ( angle );
  17101. this.applyMatrix4( _m1$3 );
  17102. return this;
  17103. },
  17104. translate: function ( x, y, z ) {
  17105. // translate geometry
  17106. _m1$3.makeTranslation( x, y, z );
  17107. this.applyMatrix4( _m1$3 );
  17108. return this;
  17109. },
  17110. scale: function ( x, y, z ) {
  17111. // scale geometry
  17112. _m1$3.makeScale( x, y, z );
  17113. this.applyMatrix4( _m1$3 );
  17114. return this;
  17115. },
  17116. lookAt: function ( vector ) {
  17117. _obj$1.lookAt( vector );
  17118. _obj$1.updateMatrix();
  17119. this.applyMatrix4( _obj$1.matrix );
  17120. return this;
  17121. },
  17122. fromBufferGeometry: function ( geometry ) {
  17123. const scope = this;
  17124. const index = geometry.index !== null ? geometry.index : undefined;
  17125. const attributes = geometry.attributes;
  17126. if ( attributes.position === undefined ) {
  17127. console.error( 'THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.' );
  17128. return this;
  17129. }
  17130. const position = attributes.position;
  17131. const normal = attributes.normal;
  17132. const color = attributes.color;
  17133. const uv = attributes.uv;
  17134. const uv2 = attributes.uv2;
  17135. if ( uv2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  17136. for ( let i = 0; i < position.count; i ++ ) {
  17137. scope.vertices.push( new Vector3().fromBufferAttribute( position, i ) );
  17138. if ( color !== undefined ) {
  17139. scope.colors.push( new Color().fromBufferAttribute( color, i ) );
  17140. }
  17141. }
  17142. function addFace( a, b, c, materialIndex ) {
  17143. const vertexColors = ( color === undefined ) ? [] : [
  17144. scope.colors[ a ].clone(),
  17145. scope.colors[ b ].clone(),
  17146. scope.colors[ c ].clone()
  17147. ];
  17148. const vertexNormals = ( normal === undefined ) ? [] : [
  17149. new Vector3().fromBufferAttribute( normal, a ),
  17150. new Vector3().fromBufferAttribute( normal, b ),
  17151. new Vector3().fromBufferAttribute( normal, c )
  17152. ];
  17153. const face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  17154. scope.faces.push( face );
  17155. if ( uv !== undefined ) {
  17156. scope.faceVertexUvs[ 0 ].push( [
  17157. new Vector2$1().fromBufferAttribute( uv, a ),
  17158. new Vector2$1().fromBufferAttribute( uv, b ),
  17159. new Vector2$1().fromBufferAttribute( uv, c )
  17160. ] );
  17161. }
  17162. if ( uv2 !== undefined ) {
  17163. scope.faceVertexUvs[ 1 ].push( [
  17164. new Vector2$1().fromBufferAttribute( uv2, a ),
  17165. new Vector2$1().fromBufferAttribute( uv2, b ),
  17166. new Vector2$1().fromBufferAttribute( uv2, c )
  17167. ] );
  17168. }
  17169. }
  17170. const groups = geometry.groups;
  17171. if ( groups.length > 0 ) {
  17172. for ( let i = 0; i < groups.length; i ++ ) {
  17173. const group = groups[ i ];
  17174. const start = group.start;
  17175. const count = group.count;
  17176. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  17177. if ( index !== undefined ) {
  17178. addFace( index.getX( j ), index.getX( j + 1 ), index.getX( j + 2 ), group.materialIndex );
  17179. } else {
  17180. addFace( j, j + 1, j + 2, group.materialIndex );
  17181. }
  17182. }
  17183. }
  17184. } else {
  17185. if ( index !== undefined ) {
  17186. for ( let i = 0; i < index.count; i += 3 ) {
  17187. addFace( index.getX( i ), index.getX( i + 1 ), index.getX( i + 2 ) );
  17188. }
  17189. } else {
  17190. for ( let i = 0; i < position.count; i += 3 ) {
  17191. addFace( i, i + 1, i + 2 );
  17192. }
  17193. }
  17194. }
  17195. this.computeFaceNormals();
  17196. if ( geometry.boundingBox !== null ) {
  17197. this.boundingBox = geometry.boundingBox.clone();
  17198. }
  17199. if ( geometry.boundingSphere !== null ) {
  17200. this.boundingSphere = geometry.boundingSphere.clone();
  17201. }
  17202. return this;
  17203. },
  17204. center: function () {
  17205. this.computeBoundingBox();
  17206. this.boundingBox.getCenter( _offset$1 ).negate();
  17207. this.translate( _offset$1.x, _offset$1.y, _offset$1.z );
  17208. return this;
  17209. },
  17210. normalize: function () {
  17211. this.computeBoundingSphere();
  17212. const center = this.boundingSphere.center;
  17213. const radius = this.boundingSphere.radius;
  17214. const s = radius === 0 ? 1 : 1.0 / radius;
  17215. const matrix = new Matrix4();
  17216. matrix.set(
  17217. s, 0, 0, - s * center.x,
  17218. 0, s, 0, - s * center.y,
  17219. 0, 0, s, - s * center.z,
  17220. 0, 0, 0, 1
  17221. );
  17222. this.applyMatrix4( matrix );
  17223. return this;
  17224. },
  17225. computeFaceNormals: function () {
  17226. const cb = new Vector3(), ab = new Vector3();
  17227. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17228. const face = this.faces[ f ];
  17229. const vA = this.vertices[ face.a ];
  17230. const vB = this.vertices[ face.b ];
  17231. const vC = this.vertices[ face.c ];
  17232. cb.subVectors( vC, vB );
  17233. ab.subVectors( vA, vB );
  17234. cb.cross( ab );
  17235. cb.normalize();
  17236. face.normal.copy( cb );
  17237. }
  17238. },
  17239. computeVertexNormals: function ( areaWeighted = true ) {
  17240. const vertices = new Array( this.vertices.length );
  17241. for ( let v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  17242. vertices[ v ] = new Vector3();
  17243. }
  17244. if ( areaWeighted ) {
  17245. // vertex normals weighted by triangle areas
  17246. // http://www.iquilezles.org/www/articles/normals/normals.htm
  17247. const cb = new Vector3(), ab = new Vector3();
  17248. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17249. const face = this.faces[ f ];
  17250. const vA = this.vertices[ face.a ];
  17251. const vB = this.vertices[ face.b ];
  17252. const vC = this.vertices[ face.c ];
  17253. cb.subVectors( vC, vB );
  17254. ab.subVectors( vA, vB );
  17255. cb.cross( ab );
  17256. vertices[ face.a ].add( cb );
  17257. vertices[ face.b ].add( cb );
  17258. vertices[ face.c ].add( cb );
  17259. }
  17260. } else {
  17261. this.computeFaceNormals();
  17262. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17263. const face = this.faces[ f ];
  17264. vertices[ face.a ].add( face.normal );
  17265. vertices[ face.b ].add( face.normal );
  17266. vertices[ face.c ].add( face.normal );
  17267. }
  17268. }
  17269. for ( let v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  17270. vertices[ v ].normalize();
  17271. }
  17272. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17273. const face = this.faces[ f ];
  17274. const vertexNormals = face.vertexNormals;
  17275. if ( vertexNormals.length === 3 ) {
  17276. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  17277. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  17278. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  17279. } else {
  17280. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  17281. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  17282. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  17283. }
  17284. }
  17285. if ( this.faces.length > 0 ) {
  17286. this.normalsNeedUpdate = true;
  17287. }
  17288. },
  17289. computeFlatVertexNormals: function () {
  17290. this.computeFaceNormals();
  17291. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17292. const face = this.faces[ f ];
  17293. const vertexNormals = face.vertexNormals;
  17294. if ( vertexNormals.length === 3 ) {
  17295. vertexNormals[ 0 ].copy( face.normal );
  17296. vertexNormals[ 1 ].copy( face.normal );
  17297. vertexNormals[ 2 ].copy( face.normal );
  17298. } else {
  17299. vertexNormals[ 0 ] = face.normal.clone();
  17300. vertexNormals[ 1 ] = face.normal.clone();
  17301. vertexNormals[ 2 ] = face.normal.clone();
  17302. }
  17303. }
  17304. if ( this.faces.length > 0 ) {
  17305. this.normalsNeedUpdate = true;
  17306. }
  17307. },
  17308. computeMorphNormals: function () {
  17309. // save original normals
  17310. // - create temp variables on first access
  17311. // otherwise just copy (for faster repeated calls)
  17312. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17313. const face = this.faces[ f ];
  17314. if ( ! face.__originalFaceNormal ) {
  17315. face.__originalFaceNormal = face.normal.clone();
  17316. } else {
  17317. face.__originalFaceNormal.copy( face.normal );
  17318. }
  17319. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  17320. for ( let i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  17321. if ( ! face.__originalVertexNormals[ i ] ) {
  17322. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  17323. } else {
  17324. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  17325. }
  17326. }
  17327. }
  17328. // use temp geometry to compute face and vertex normals for each morph
  17329. const tmpGeo = new Geometry();
  17330. tmpGeo.faces = this.faces;
  17331. for ( let i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  17332. // create on first access
  17333. if ( ! this.morphNormals[ i ] ) {
  17334. this.morphNormals[ i ] = {};
  17335. this.morphNormals[ i ].faceNormals = [];
  17336. this.morphNormals[ i ].vertexNormals = [];
  17337. const dstNormalsFace = this.morphNormals[ i ].faceNormals;
  17338. const dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  17339. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17340. const faceNormal = new Vector3();
  17341. const vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  17342. dstNormalsFace.push( faceNormal );
  17343. dstNormalsVertex.push( vertexNormals );
  17344. }
  17345. }
  17346. const morphNormals = this.morphNormals[ i ];
  17347. // set vertices to morph target
  17348. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  17349. // compute morph normals
  17350. tmpGeo.computeFaceNormals();
  17351. tmpGeo.computeVertexNormals();
  17352. // store morph normals
  17353. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17354. const face = this.faces[ f ];
  17355. const faceNormal = morphNormals.faceNormals[ f ];
  17356. const vertexNormals = morphNormals.vertexNormals[ f ];
  17357. faceNormal.copy( face.normal );
  17358. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  17359. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  17360. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  17361. }
  17362. }
  17363. // restore original normals
  17364. for ( let f = 0, fl = this.faces.length; f < fl; f ++ ) {
  17365. const face = this.faces[ f ];
  17366. face.normal = face.__originalFaceNormal;
  17367. face.vertexNormals = face.__originalVertexNormals;
  17368. }
  17369. },
  17370. computeBoundingBox: function () {
  17371. if ( this.boundingBox === null ) {
  17372. this.boundingBox = new Box3();
  17373. }
  17374. this.boundingBox.setFromPoints( this.vertices );
  17375. },
  17376. computeBoundingSphere: function () {
  17377. if ( this.boundingSphere === null ) {
  17378. this.boundingSphere = new Sphere();
  17379. }
  17380. this.boundingSphere.setFromPoints( this.vertices );
  17381. },
  17382. merge: function ( geometry, matrix, materialIndexOffset = 0 ) {
  17383. if ( ! ( geometry && geometry.isGeometry ) ) {
  17384. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  17385. return;
  17386. }
  17387. let normalMatrix;
  17388. const vertexOffset = this.vertices.length,
  17389. vertices1 = this.vertices,
  17390. vertices2 = geometry.vertices,
  17391. faces1 = this.faces,
  17392. faces2 = geometry.faces,
  17393. colors1 = this.colors,
  17394. colors2 = geometry.colors;
  17395. if ( matrix !== undefined ) {
  17396. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  17397. }
  17398. // vertices
  17399. for ( let i = 0, il = vertices2.length; i < il; i ++ ) {
  17400. const vertex = vertices2[ i ];
  17401. const vertexCopy = vertex.clone();
  17402. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  17403. vertices1.push( vertexCopy );
  17404. }
  17405. // colors
  17406. for ( let i = 0, il = colors2.length; i < il; i ++ ) {
  17407. colors1.push( colors2[ i ].clone() );
  17408. }
  17409. // faces
  17410. for ( let i = 0, il = faces2.length; i < il; i ++ ) {
  17411. const face = faces2[ i ];
  17412. let normal, color;
  17413. const faceVertexNormals = face.vertexNormals,
  17414. faceVertexColors = face.vertexColors;
  17415. const faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  17416. faceCopy.normal.copy( face.normal );
  17417. if ( normalMatrix !== undefined ) {
  17418. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  17419. }
  17420. for ( let j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  17421. normal = faceVertexNormals[ j ].clone();
  17422. if ( normalMatrix !== undefined ) {
  17423. normal.applyMatrix3( normalMatrix ).normalize();
  17424. }
  17425. faceCopy.vertexNormals.push( normal );
  17426. }
  17427. faceCopy.color.copy( face.color );
  17428. for ( let j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  17429. color = faceVertexColors[ j ];
  17430. faceCopy.vertexColors.push( color.clone() );
  17431. }
  17432. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  17433. faces1.push( faceCopy );
  17434. }
  17435. // uvs
  17436. for ( let i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  17437. const faceVertexUvs2 = geometry.faceVertexUvs[ i ];
  17438. if ( this.faceVertexUvs[ i ] === undefined ) this.faceVertexUvs[ i ] = [];
  17439. for ( let j = 0, jl = faceVertexUvs2.length; j < jl; j ++ ) {
  17440. const uvs2 = faceVertexUvs2[ j ], uvsCopy = [];
  17441. for ( let k = 0, kl = uvs2.length; k < kl; k ++ ) {
  17442. uvsCopy.push( uvs2[ k ].clone() );
  17443. }
  17444. this.faceVertexUvs[ i ].push( uvsCopy );
  17445. }
  17446. }
  17447. },
  17448. mergeMesh: function ( mesh ) {
  17449. if ( ! ( mesh && mesh.isMesh ) ) {
  17450. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  17451. return;
  17452. }
  17453. if ( mesh.matrixAutoUpdate ) mesh.updateMatrix();
  17454. this.merge( mesh.geometry, mesh.matrix );
  17455. },
  17456. /*
  17457. * Checks for duplicate vertices with hashmap.
  17458. * Duplicated vertices are removed
  17459. * and faces' vertices are updated.
  17460. */
  17461. mergeVertices: function ( precisionPoints = 4 ) {
  17462. const verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  17463. const unique = [], changes = [];
  17464. const precision = Math.pow( 10, precisionPoints );
  17465. for ( let i = 0, il = this.vertices.length; i < il; i ++ ) {
  17466. const v = this.vertices[ i ];
  17467. const key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  17468. if ( verticesMap[ key ] === undefined ) {
  17469. verticesMap[ key ] = i;
  17470. unique.push( this.vertices[ i ] );
  17471. changes[ i ] = unique.length - 1;
  17472. } else {
  17473. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  17474. changes[ i ] = changes[ verticesMap[ key ] ];
  17475. }
  17476. }
  17477. // if faces are completely degenerate after merging vertices, we
  17478. // have to remove them from the geometry.
  17479. const faceIndicesToRemove = [];
  17480. for ( let i = 0, il = this.faces.length; i < il; i ++ ) {
  17481. const face = this.faces[ i ];
  17482. face.a = changes[ face.a ];
  17483. face.b = changes[ face.b ];
  17484. face.c = changes[ face.c ];
  17485. const indices = [ face.a, face.b, face.c ];
  17486. // if any duplicate vertices are found in a Face3
  17487. // we have to remove the face as nothing can be saved
  17488. for ( let n = 0; n < 3; n ++ ) {
  17489. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  17490. faceIndicesToRemove.push( i );
  17491. break;
  17492. }
  17493. }
  17494. }
  17495. for ( let i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  17496. const idx = faceIndicesToRemove[ i ];
  17497. this.faces.splice( idx, 1 );
  17498. for ( let j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  17499. this.faceVertexUvs[ j ].splice( idx, 1 );
  17500. }
  17501. }
  17502. // Use unique set of vertices
  17503. const diff = this.vertices.length - unique.length;
  17504. this.vertices = unique;
  17505. return diff;
  17506. },
  17507. setFromPoints: function ( points ) {
  17508. this.vertices = [];
  17509. for ( let i = 0, l = points.length; i < l; i ++ ) {
  17510. const point = points[ i ];
  17511. this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  17512. }
  17513. return this;
  17514. },
  17515. sortFacesByMaterialIndex: function () {
  17516. const faces = this.faces;
  17517. const length = faces.length;
  17518. // tag faces
  17519. for ( let i = 0; i < length; i ++ ) {
  17520. faces[ i ]._id = i;
  17521. }
  17522. // sort faces
  17523. function materialIndexSort( a, b ) {
  17524. return a.materialIndex - b.materialIndex;
  17525. }
  17526. faces.sort( materialIndexSort );
  17527. // sort uvs
  17528. const uvs1 = this.faceVertexUvs[ 0 ];
  17529. const uvs2 = this.faceVertexUvs[ 1 ];
  17530. let newUvs1, newUvs2;
  17531. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  17532. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  17533. for ( let i = 0; i < length; i ++ ) {
  17534. const id = faces[ i ]._id;
  17535. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  17536. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  17537. }
  17538. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  17539. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  17540. },
  17541. toJSON: function () {
  17542. const data = {
  17543. metadata: {
  17544. version: 4.5,
  17545. type: 'Geometry',
  17546. generator: 'Geometry.toJSON'
  17547. }
  17548. };
  17549. // standard Geometry serialization
  17550. data.uuid = this.uuid;
  17551. data.type = this.type;
  17552. if ( this.name !== '' ) data.name = this.name;
  17553. if ( this.parameters !== undefined ) {
  17554. const parameters = this.parameters;
  17555. for ( const key in parameters ) {
  17556. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  17557. }
  17558. return data;
  17559. }
  17560. const vertices = [];
  17561. for ( let i = 0; i < this.vertices.length; i ++ ) {
  17562. const vertex = this.vertices[ i ];
  17563. vertices.push( vertex.x, vertex.y, vertex.z );
  17564. }
  17565. const faces = [];
  17566. const normals = [];
  17567. const normalsHash = {};
  17568. const colors = [];
  17569. const colorsHash = {};
  17570. const uvs = [];
  17571. const uvsHash = {};
  17572. for ( let i = 0; i < this.faces.length; i ++ ) {
  17573. const face = this.faces[ i ];
  17574. const hasMaterial = true;
  17575. const hasFaceUv = false; // deprecated
  17576. const hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  17577. const hasFaceNormal = face.normal.length() > 0;
  17578. const hasFaceVertexNormal = face.vertexNormals.length > 0;
  17579. const hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  17580. const hasFaceVertexColor = face.vertexColors.length > 0;
  17581. let faceType = 0;
  17582. faceType = setBit( faceType, 0, 0 ); // isQuad
  17583. faceType = setBit( faceType, 1, hasMaterial );
  17584. faceType = setBit( faceType, 2, hasFaceUv );
  17585. faceType = setBit( faceType, 3, hasFaceVertexUv );
  17586. faceType = setBit( faceType, 4, hasFaceNormal );
  17587. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  17588. faceType = setBit( faceType, 6, hasFaceColor );
  17589. faceType = setBit( faceType, 7, hasFaceVertexColor );
  17590. faces.push( faceType );
  17591. faces.push( face.a, face.b, face.c );
  17592. faces.push( face.materialIndex );
  17593. if ( hasFaceVertexUv ) {
  17594. const faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  17595. faces.push(
  17596. getUvIndex( faceVertexUvs[ 0 ] ),
  17597. getUvIndex( faceVertexUvs[ 1 ] ),
  17598. getUvIndex( faceVertexUvs[ 2 ] )
  17599. );
  17600. }
  17601. if ( hasFaceNormal ) {
  17602. faces.push( getNormalIndex( face.normal ) );
  17603. }
  17604. if ( hasFaceVertexNormal ) {
  17605. const vertexNormals = face.vertexNormals;
  17606. faces.push(
  17607. getNormalIndex( vertexNormals[ 0 ] ),
  17608. getNormalIndex( vertexNormals[ 1 ] ),
  17609. getNormalIndex( vertexNormals[ 2 ] )
  17610. );
  17611. }
  17612. if ( hasFaceColor ) {
  17613. faces.push( getColorIndex( face.color ) );
  17614. }
  17615. if ( hasFaceVertexColor ) {
  17616. const vertexColors = face.vertexColors;
  17617. faces.push(
  17618. getColorIndex( vertexColors[ 0 ] ),
  17619. getColorIndex( vertexColors[ 1 ] ),
  17620. getColorIndex( vertexColors[ 2 ] )
  17621. );
  17622. }
  17623. }
  17624. function setBit( value, position, enabled ) {
  17625. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  17626. }
  17627. function getNormalIndex( normal ) {
  17628. const hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  17629. if ( normalsHash[ hash ] !== undefined ) {
  17630. return normalsHash[ hash ];
  17631. }
  17632. normalsHash[ hash ] = normals.length / 3;
  17633. normals.push( normal.x, normal.y, normal.z );
  17634. return normalsHash[ hash ];
  17635. }
  17636. function getColorIndex( color ) {
  17637. const hash = color.r.toString() + color.g.toString() + color.b.toString();
  17638. if ( colorsHash[ hash ] !== undefined ) {
  17639. return colorsHash[ hash ];
  17640. }
  17641. colorsHash[ hash ] = colors.length;
  17642. colors.push( color.getHex() );
  17643. return colorsHash[ hash ];
  17644. }
  17645. function getUvIndex( uv ) {
  17646. const hash = uv.x.toString() + uv.y.toString();
  17647. if ( uvsHash[ hash ] !== undefined ) {
  17648. return uvsHash[ hash ];
  17649. }
  17650. uvsHash[ hash ] = uvs.length / 2;
  17651. uvs.push( uv.x, uv.y );
  17652. return uvsHash[ hash ];
  17653. }
  17654. data.data = {};
  17655. data.data.vertices = vertices;
  17656. data.data.normals = normals;
  17657. if ( colors.length > 0 ) data.data.colors = colors;
  17658. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  17659. data.data.faces = faces;
  17660. return data;
  17661. },
  17662. clone: function () {
  17663. /*
  17664. // Handle primitives
  17665. const parameters = this.parameters;
  17666. if ( parameters !== undefined ) {
  17667. const values = [];
  17668. for ( const key in parameters ) {
  17669. values.push( parameters[ key ] );
  17670. }
  17671. const geometry = Object.create( this.constructor.prototype );
  17672. this.constructor.apply( geometry, values );
  17673. return geometry;
  17674. }
  17675. return new this.constructor().copy( this );
  17676. */
  17677. return new Geometry().copy( this );
  17678. },
  17679. copy: function ( source ) {
  17680. // reset
  17681. this.vertices = [];
  17682. this.colors = [];
  17683. this.faces = [];
  17684. this.faceVertexUvs = [[]];
  17685. this.morphTargets = [];
  17686. this.morphNormals = [];
  17687. this.skinWeights = [];
  17688. this.skinIndices = [];
  17689. this.lineDistances = [];
  17690. this.boundingBox = null;
  17691. this.boundingSphere = null;
  17692. // name
  17693. this.name = source.name;
  17694. // vertices
  17695. const vertices = source.vertices;
  17696. for ( let i = 0, il = vertices.length; i < il; i ++ ) {
  17697. this.vertices.push( vertices[ i ].clone() );
  17698. }
  17699. // colors
  17700. const colors = source.colors;
  17701. for ( let i = 0, il = colors.length; i < il; i ++ ) {
  17702. this.colors.push( colors[ i ].clone() );
  17703. }
  17704. // faces
  17705. const faces = source.faces;
  17706. for ( let i = 0, il = faces.length; i < il; i ++ ) {
  17707. this.faces.push( faces[ i ].clone() );
  17708. }
  17709. // face vertex uvs
  17710. for ( let i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  17711. const faceVertexUvs = source.faceVertexUvs[ i ];
  17712. if ( this.faceVertexUvs[ i ] === undefined ) {
  17713. this.faceVertexUvs[ i ] = [];
  17714. }
  17715. for ( let j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  17716. const uvs = faceVertexUvs[ j ], uvsCopy = [];
  17717. for ( let k = 0, kl = uvs.length; k < kl; k ++ ) {
  17718. const uv = uvs[ k ];
  17719. uvsCopy.push( uv.clone() );
  17720. }
  17721. this.faceVertexUvs[ i ].push( uvsCopy );
  17722. }
  17723. }
  17724. // morph targets
  17725. const morphTargets = source.morphTargets;
  17726. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  17727. const morphTarget = {};
  17728. morphTarget.name = morphTargets[ i ].name;
  17729. // vertices
  17730. if ( morphTargets[ i ].vertices !== undefined ) {
  17731. morphTarget.vertices = [];
  17732. for ( let j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  17733. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  17734. }
  17735. }
  17736. // normals
  17737. if ( morphTargets[ i ].normals !== undefined ) {
  17738. morphTarget.normals = [];
  17739. for ( let j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  17740. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  17741. }
  17742. }
  17743. this.morphTargets.push( morphTarget );
  17744. }
  17745. // morph normals
  17746. const morphNormals = source.morphNormals;
  17747. for ( let i = 0, il = morphNormals.length; i < il; i ++ ) {
  17748. const morphNormal = {};
  17749. // vertex normals
  17750. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  17751. morphNormal.vertexNormals = [];
  17752. for ( let j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  17753. const srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  17754. const destVertexNormal = {};
  17755. destVertexNormal.a = srcVertexNormal.a.clone();
  17756. destVertexNormal.b = srcVertexNormal.b.clone();
  17757. destVertexNormal.c = srcVertexNormal.c.clone();
  17758. morphNormal.vertexNormals.push( destVertexNormal );
  17759. }
  17760. }
  17761. // face normals
  17762. if ( morphNormals[ i ].faceNormals !== undefined ) {
  17763. morphNormal.faceNormals = [];
  17764. for ( let j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  17765. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  17766. }
  17767. }
  17768. this.morphNormals.push( morphNormal );
  17769. }
  17770. // skin weights
  17771. const skinWeights = source.skinWeights;
  17772. for ( let i = 0, il = skinWeights.length; i < il; i ++ ) {
  17773. this.skinWeights.push( skinWeights[ i ].clone() );
  17774. }
  17775. // skin indices
  17776. const skinIndices = source.skinIndices;
  17777. for ( let i = 0, il = skinIndices.length; i < il; i ++ ) {
  17778. this.skinIndices.push( skinIndices[ i ].clone() );
  17779. }
  17780. // line distances
  17781. const lineDistances = source.lineDistances;
  17782. for ( let i = 0, il = lineDistances.length; i < il; i ++ ) {
  17783. this.lineDistances.push( lineDistances[ i ] );
  17784. }
  17785. // bounding box
  17786. const boundingBox = source.boundingBox;
  17787. if ( boundingBox !== null ) {
  17788. this.boundingBox = boundingBox.clone();
  17789. }
  17790. // bounding sphere
  17791. const boundingSphere = source.boundingSphere;
  17792. if ( boundingSphere !== null ) {
  17793. this.boundingSphere = boundingSphere.clone();
  17794. }
  17795. // update flags
  17796. this.elementsNeedUpdate = source.elementsNeedUpdate;
  17797. this.verticesNeedUpdate = source.verticesNeedUpdate;
  17798. this.uvsNeedUpdate = source.uvsNeedUpdate;
  17799. this.normalsNeedUpdate = source.normalsNeedUpdate;
  17800. this.colorsNeedUpdate = source.colorsNeedUpdate;
  17801. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  17802. this.groupsNeedUpdate = source.groupsNeedUpdate;
  17803. return this;
  17804. },
  17805. dispose: function () {
  17806. this.dispatchEvent( { type: 'dispose' } );
  17807. }
  17808. } );
  17809. class BoxGeometry extends Geometry {
  17810. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  17811. super();
  17812. this.type = 'BoxGeometry';
  17813. this.parameters = {
  17814. width: width,
  17815. height: height,
  17816. depth: depth,
  17817. widthSegments: widthSegments,
  17818. heightSegments: heightSegments,
  17819. depthSegments: depthSegments
  17820. };
  17821. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  17822. this.mergeVertices();
  17823. }
  17824. }
  17825. class CircleBufferGeometry extends BufferGeometry {
  17826. constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17827. super();
  17828. this.type = 'CircleBufferGeometry';
  17829. this.parameters = {
  17830. radius: radius,
  17831. segments: segments,
  17832. thetaStart: thetaStart,
  17833. thetaLength: thetaLength
  17834. };
  17835. segments = Math.max( 3, segments );
  17836. // buffers
  17837. const indices = [];
  17838. const vertices = [];
  17839. const normals = [];
  17840. const uvs = [];
  17841. // helper variables
  17842. const vertex = new Vector3();
  17843. const uv = new Vector2$1();
  17844. // center point
  17845. vertices.push( 0, 0, 0 );
  17846. normals.push( 0, 0, 1 );
  17847. uvs.push( 0.5, 0.5 );
  17848. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  17849. const segment = thetaStart + s / segments * thetaLength;
  17850. // vertex
  17851. vertex.x = radius * Math.cos( segment );
  17852. vertex.y = radius * Math.sin( segment );
  17853. vertices.push( vertex.x, vertex.y, vertex.z );
  17854. // normal
  17855. normals.push( 0, 0, 1 );
  17856. // uvs
  17857. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  17858. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  17859. uvs.push( uv.x, uv.y );
  17860. }
  17861. // indices
  17862. for ( let i = 1; i <= segments; i ++ ) {
  17863. indices.push( i, i + 1, 0 );
  17864. }
  17865. // build geometry
  17866. this.setIndex( indices );
  17867. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17868. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17869. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17870. }
  17871. }
  17872. class CircleGeometry extends Geometry {
  17873. constructor( radius, segments, thetaStart, thetaLength ) {
  17874. super();
  17875. this.type = 'CircleGeometry';
  17876. this.parameters = {
  17877. radius: radius,
  17878. segments: segments,
  17879. thetaStart: thetaStart,
  17880. thetaLength: thetaLength
  17881. };
  17882. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  17883. this.mergeVertices();
  17884. }
  17885. }
  17886. class CylinderBufferGeometry extends BufferGeometry {
  17887. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  17888. super();
  17889. this.type = 'CylinderBufferGeometry';
  17890. this.parameters = {
  17891. radiusTop: radiusTop,
  17892. radiusBottom: radiusBottom,
  17893. height: height,
  17894. radialSegments: radialSegments,
  17895. heightSegments: heightSegments,
  17896. openEnded: openEnded,
  17897. thetaStart: thetaStart,
  17898. thetaLength: thetaLength
  17899. };
  17900. const scope = this;
  17901. radialSegments = Math.floor( radialSegments );
  17902. heightSegments = Math.floor( heightSegments );
  17903. // buffers
  17904. const indices = [];
  17905. const vertices = [];
  17906. const normals = [];
  17907. const uvs = [];
  17908. // helper variables
  17909. let index = 0;
  17910. const indexArray = [];
  17911. const halfHeight = height / 2;
  17912. let groupStart = 0;
  17913. // generate geometry
  17914. generateTorso();
  17915. if ( openEnded === false ) {
  17916. if ( radiusTop > 0 ) generateCap( true );
  17917. if ( radiusBottom > 0 ) generateCap( false );
  17918. }
  17919. // build geometry
  17920. this.setIndex( indices );
  17921. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  17922. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  17923. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  17924. function generateTorso() {
  17925. const normal = new Vector3();
  17926. const vertex = new Vector3();
  17927. let groupCount = 0;
  17928. // this will be used to calculate the normal
  17929. const slope = ( radiusBottom - radiusTop ) / height;
  17930. // generate vertices, normals and uvs
  17931. for ( let y = 0; y <= heightSegments; y ++ ) {
  17932. const indexRow = [];
  17933. const v = y / heightSegments;
  17934. // calculate the radius of the current row
  17935. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17936. for ( let x = 0; x <= radialSegments; x ++ ) {
  17937. const u = x / radialSegments;
  17938. const theta = u * thetaLength + thetaStart;
  17939. const sinTheta = Math.sin( theta );
  17940. const cosTheta = Math.cos( theta );
  17941. // vertex
  17942. vertex.x = radius * sinTheta;
  17943. vertex.y = - v * height + halfHeight;
  17944. vertex.z = radius * cosTheta;
  17945. vertices.push( vertex.x, vertex.y, vertex.z );
  17946. // normal
  17947. normal.set( sinTheta, slope, cosTheta ).normalize();
  17948. normals.push( normal.x, normal.y, normal.z );
  17949. // uv
  17950. uvs.push( u, 1 - v );
  17951. // save index of vertex in respective row
  17952. indexRow.push( index ++ );
  17953. }
  17954. // now save vertices of the row in our index array
  17955. indexArray.push( indexRow );
  17956. }
  17957. // generate indices
  17958. for ( let x = 0; x < radialSegments; x ++ ) {
  17959. for ( let y = 0; y < heightSegments; y ++ ) {
  17960. // we use the index array to access the correct indices
  17961. const a = indexArray[ y ][ x ];
  17962. const b = indexArray[ y + 1 ][ x ];
  17963. const c = indexArray[ y + 1 ][ x + 1 ];
  17964. const d = indexArray[ y ][ x + 1 ];
  17965. // faces
  17966. indices.push( a, b, d );
  17967. indices.push( b, c, d );
  17968. // update group counter
  17969. groupCount += 6;
  17970. }
  17971. }
  17972. // add a group to the geometry. this will ensure multi material support
  17973. scope.addGroup( groupStart, groupCount, 0 );
  17974. // calculate new start value for groups
  17975. groupStart += groupCount;
  17976. }
  17977. function generateCap( top ) {
  17978. // save the index of the first center vertex
  17979. const centerIndexStart = index;
  17980. const uv = new Vector2$1();
  17981. const vertex = new Vector3();
  17982. let groupCount = 0;
  17983. const radius = ( top === true ) ? radiusTop : radiusBottom;
  17984. const sign = ( top === true ) ? 1 : - 1;
  17985. // first we generate the center vertex data of the cap.
  17986. // because the geometry needs one set of uvs per face,
  17987. // we must generate a center vertex per face/segment
  17988. for ( let x = 1; x <= radialSegments; x ++ ) {
  17989. // vertex
  17990. vertices.push( 0, halfHeight * sign, 0 );
  17991. // normal
  17992. normals.push( 0, sign, 0 );
  17993. // uv
  17994. uvs.push( 0.5, 0.5 );
  17995. // increase index
  17996. index ++;
  17997. }
  17998. // save the index of the last center vertex
  17999. const centerIndexEnd = index;
  18000. // now we generate the surrounding vertices, normals and uvs
  18001. for ( let x = 0; x <= radialSegments; x ++ ) {
  18002. const u = x / radialSegments;
  18003. const theta = u * thetaLength + thetaStart;
  18004. const cosTheta = Math.cos( theta );
  18005. const sinTheta = Math.sin( theta );
  18006. // vertex
  18007. vertex.x = radius * sinTheta;
  18008. vertex.y = halfHeight * sign;
  18009. vertex.z = radius * cosTheta;
  18010. vertices.push( vertex.x, vertex.y, vertex.z );
  18011. // normal
  18012. normals.push( 0, sign, 0 );
  18013. // uv
  18014. uv.x = ( cosTheta * 0.5 ) + 0.5;
  18015. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  18016. uvs.push( uv.x, uv.y );
  18017. // increase index
  18018. index ++;
  18019. }
  18020. // generate indices
  18021. for ( let x = 0; x < radialSegments; x ++ ) {
  18022. const c = centerIndexStart + x;
  18023. const i = centerIndexEnd + x;
  18024. if ( top === true ) {
  18025. // face top
  18026. indices.push( i, i + 1, c );
  18027. } else {
  18028. // face bottom
  18029. indices.push( i + 1, i, c );
  18030. }
  18031. groupCount += 3;
  18032. }
  18033. // add a group to the geometry. this will ensure multi material support
  18034. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  18035. // calculate new start value for groups
  18036. groupStart += groupCount;
  18037. }
  18038. }
  18039. }
  18040. class CylinderGeometry extends Geometry {
  18041. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  18042. super();
  18043. this.type = 'CylinderGeometry';
  18044. this.parameters = {
  18045. radiusTop: radiusTop,
  18046. radiusBottom: radiusBottom,
  18047. height: height,
  18048. radialSegments: radialSegments,
  18049. heightSegments: heightSegments,
  18050. openEnded: openEnded,
  18051. thetaStart: thetaStart,
  18052. thetaLength: thetaLength
  18053. };
  18054. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  18055. this.mergeVertices();
  18056. }
  18057. }
  18058. class ConeGeometry extends CylinderGeometry {
  18059. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  18060. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  18061. this.type = 'ConeGeometry';
  18062. this.parameters = {
  18063. radius: radius,
  18064. height: height,
  18065. radialSegments: radialSegments,
  18066. heightSegments: heightSegments,
  18067. openEnded: openEnded,
  18068. thetaStart: thetaStart,
  18069. thetaLength: thetaLength
  18070. };
  18071. }
  18072. }
  18073. class ConeBufferGeometry extends CylinderBufferGeometry {
  18074. constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  18075. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  18076. this.type = 'ConeBufferGeometry';
  18077. this.parameters = {
  18078. radius: radius,
  18079. height: height,
  18080. radialSegments: radialSegments,
  18081. heightSegments: heightSegments,
  18082. openEnded: openEnded,
  18083. thetaStart: thetaStart,
  18084. thetaLength: thetaLength
  18085. };
  18086. }
  18087. }
  18088. class PolyhedronBufferGeometry extends BufferGeometry {
  18089. constructor( vertices, indices, radius = 1, detail = 0 ) {
  18090. super();
  18091. this.type = 'PolyhedronBufferGeometry';
  18092. this.parameters = {
  18093. vertices: vertices,
  18094. indices: indices,
  18095. radius: radius,
  18096. detail: detail
  18097. };
  18098. // default buffer data
  18099. const vertexBuffer = [];
  18100. const uvBuffer = [];
  18101. // the subdivision creates the vertex buffer data
  18102. subdivide( detail );
  18103. // all vertices should lie on a conceptual sphere with a given radius
  18104. applyRadius( radius );
  18105. // finally, create the uv data
  18106. generateUVs();
  18107. // build non-indexed geometry
  18108. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  18109. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  18110. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  18111. if ( detail === 0 ) {
  18112. this.computeVertexNormals(); // flat normals
  18113. } else {
  18114. this.normalizeNormals(); // smooth normals
  18115. }
  18116. // helper functions
  18117. function subdivide( detail ) {
  18118. const a = new Vector3();
  18119. const b = new Vector3();
  18120. const c = new Vector3();
  18121. // iterate over all faces and apply a subdivison with the given detail value
  18122. for ( let i = 0; i < indices.length; i += 3 ) {
  18123. // get the vertices of the face
  18124. getVertexByIndex( indices[ i + 0 ], a );
  18125. getVertexByIndex( indices[ i + 1 ], b );
  18126. getVertexByIndex( indices[ i + 2 ], c );
  18127. // perform subdivision
  18128. subdivideFace( a, b, c, detail );
  18129. }
  18130. }
  18131. function subdivideFace( a, b, c, detail ) {
  18132. const cols = detail + 1;
  18133. // we use this multidimensional array as a data structure for creating the subdivision
  18134. const v = [];
  18135. // construct all of the vertices for this subdivision
  18136. for ( let i = 0; i <= cols; i ++ ) {
  18137. v[ i ] = [];
  18138. const aj = a.clone().lerp( c, i / cols );
  18139. const bj = b.clone().lerp( c, i / cols );
  18140. const rows = cols - i;
  18141. for ( let j = 0; j <= rows; j ++ ) {
  18142. if ( j === 0 && i === cols ) {
  18143. v[ i ][ j ] = aj;
  18144. } else {
  18145. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  18146. }
  18147. }
  18148. }
  18149. // construct all of the faces
  18150. for ( let i = 0; i < cols; i ++ ) {
  18151. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  18152. const k = Math.floor( j / 2 );
  18153. if ( j % 2 === 0 ) {
  18154. pushVertex( v[ i ][ k + 1 ] );
  18155. pushVertex( v[ i + 1 ][ k ] );
  18156. pushVertex( v[ i ][ k ] );
  18157. } else {
  18158. pushVertex( v[ i ][ k + 1 ] );
  18159. pushVertex( v[ i + 1 ][ k + 1 ] );
  18160. pushVertex( v[ i + 1 ][ k ] );
  18161. }
  18162. }
  18163. }
  18164. }
  18165. function applyRadius( radius ) {
  18166. const vertex = new Vector3();
  18167. // iterate over the entire buffer and apply the radius to each vertex
  18168. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  18169. vertex.x = vertexBuffer[ i + 0 ];
  18170. vertex.y = vertexBuffer[ i + 1 ];
  18171. vertex.z = vertexBuffer[ i + 2 ];
  18172. vertex.normalize().multiplyScalar( radius );
  18173. vertexBuffer[ i + 0 ] = vertex.x;
  18174. vertexBuffer[ i + 1 ] = vertex.y;
  18175. vertexBuffer[ i + 2 ] = vertex.z;
  18176. }
  18177. }
  18178. function generateUVs() {
  18179. const vertex = new Vector3();
  18180. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  18181. vertex.x = vertexBuffer[ i + 0 ];
  18182. vertex.y = vertexBuffer[ i + 1 ];
  18183. vertex.z = vertexBuffer[ i + 2 ];
  18184. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  18185. const v = inclination( vertex ) / Math.PI + 0.5;
  18186. uvBuffer.push( u, 1 - v );
  18187. }
  18188. correctUVs();
  18189. correctSeam();
  18190. }
  18191. function correctSeam() {
  18192. // handle case when face straddles the seam, see #3269
  18193. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  18194. // uv data of a single face
  18195. const x0 = uvBuffer[ i + 0 ];
  18196. const x1 = uvBuffer[ i + 2 ];
  18197. const x2 = uvBuffer[ i + 4 ];
  18198. const max = Math.max( x0, x1, x2 );
  18199. const min = Math.min( x0, x1, x2 );
  18200. // 0.9 is somewhat arbitrary
  18201. if ( max > 0.9 && min < 0.1 ) {
  18202. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  18203. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  18204. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  18205. }
  18206. }
  18207. }
  18208. function pushVertex( vertex ) {
  18209. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  18210. }
  18211. function getVertexByIndex( index, vertex ) {
  18212. const stride = index * 3;
  18213. vertex.x = vertices[ stride + 0 ];
  18214. vertex.y = vertices[ stride + 1 ];
  18215. vertex.z = vertices[ stride + 2 ];
  18216. }
  18217. function correctUVs() {
  18218. const a = new Vector3();
  18219. const b = new Vector3();
  18220. const c = new Vector3();
  18221. const centroid = new Vector3();
  18222. const uvA = new Vector2$1();
  18223. const uvB = new Vector2$1();
  18224. const uvC = new Vector2$1();
  18225. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  18226. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  18227. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  18228. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  18229. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  18230. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  18231. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  18232. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  18233. const azi = azimuth( centroid );
  18234. correctUV( uvA, j + 0, a, azi );
  18235. correctUV( uvB, j + 2, b, azi );
  18236. correctUV( uvC, j + 4, c, azi );
  18237. }
  18238. }
  18239. function correctUV( uv, stride, vector, azimuth ) {
  18240. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  18241. uvBuffer[ stride ] = uv.x - 1;
  18242. }
  18243. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  18244. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  18245. }
  18246. }
  18247. // Angle around the Y axis, counter-clockwise when looking from above.
  18248. function azimuth( vector ) {
  18249. return Math.atan2( vector.z, - vector.x );
  18250. }
  18251. // Angle above the XZ plane.
  18252. function inclination( vector ) {
  18253. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  18254. }
  18255. }
  18256. }
  18257. class DodecahedronBufferGeometry extends PolyhedronBufferGeometry {
  18258. constructor( radius = 1, detail = 0 ) {
  18259. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  18260. const r = 1 / t;
  18261. const vertices = [
  18262. // (±1, ±1, ±1)
  18263. - 1, - 1, - 1, - 1, - 1, 1,
  18264. - 1, 1, - 1, - 1, 1, 1,
  18265. 1, - 1, - 1, 1, - 1, 1,
  18266. 1, 1, - 1, 1, 1, 1,
  18267. // (0, ±1/φ, ±φ)
  18268. 0, - r, - t, 0, - r, t,
  18269. 0, r, - t, 0, r, t,
  18270. // (±1/φ, ±φ, 0)
  18271. - r, - t, 0, - r, t, 0,
  18272. r, - t, 0, r, t, 0,
  18273. // (±φ, 0, ±1/φ)
  18274. - t, 0, - r, t, 0, - r,
  18275. - t, 0, r, t, 0, r
  18276. ];
  18277. const indices = [
  18278. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  18279. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  18280. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  18281. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  18282. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  18283. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  18284. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  18285. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  18286. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  18287. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  18288. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  18289. 1, 12, 14, 1, 14, 5, 1, 5, 9
  18290. ];
  18291. super( vertices, indices, radius, detail );
  18292. this.type = 'DodecahedronBufferGeometry';
  18293. this.parameters = {
  18294. radius: radius,
  18295. detail: detail
  18296. };
  18297. }
  18298. }
  18299. class DodecahedronGeometry extends Geometry {
  18300. constructor( radius, detail ) {
  18301. super();
  18302. this.type = 'DodecahedronGeometry';
  18303. this.parameters = {
  18304. radius: radius,
  18305. detail: detail
  18306. };
  18307. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  18308. this.mergeVertices();
  18309. }
  18310. }
  18311. const _v0$2 = new Vector3();
  18312. const _v1$5 = new Vector3();
  18313. const _normal$1 = new Vector3();
  18314. const _triangle = new Triangle();
  18315. class EdgesGeometry extends BufferGeometry {
  18316. constructor( geometry, thresholdAngle ) {
  18317. super();
  18318. this.type = 'EdgesGeometry';
  18319. this.parameters = {
  18320. thresholdAngle: thresholdAngle
  18321. };
  18322. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  18323. if ( geometry.isGeometry ) {
  18324. geometry = new BufferGeometry().fromGeometry( geometry );
  18325. }
  18326. const precisionPoints = 4;
  18327. const precision = Math.pow( 10, precisionPoints );
  18328. const thresholdDot = Math.cos( MathUtils.DEG2RAD * thresholdAngle );
  18329. const indexAttr = geometry.getIndex();
  18330. const positionAttr = geometry.getAttribute( 'position' );
  18331. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  18332. const indexArr = [ 0, 0, 0 ];
  18333. const vertKeys = [ 'a', 'b', 'c' ];
  18334. const hashes = new Array( 3 );
  18335. const edgeData = {};
  18336. const vertices = [];
  18337. for ( let i = 0; i < indexCount; i += 3 ) {
  18338. if ( indexAttr ) {
  18339. indexArr[ 0 ] = indexAttr.getX( i );
  18340. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  18341. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  18342. } else {
  18343. indexArr[ 0 ] = i;
  18344. indexArr[ 1 ] = i + 1;
  18345. indexArr[ 2 ] = i + 2;
  18346. }
  18347. const { a, b, c } = _triangle;
  18348. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  18349. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  18350. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  18351. _triangle.getNormal( _normal$1 );
  18352. // create hashes for the edge from the vertices
  18353. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  18354. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  18355. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  18356. // skip degenerate triangles
  18357. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  18358. continue;
  18359. }
  18360. // iterate over every edge
  18361. for ( let j = 0; j < 3; j ++ ) {
  18362. // get the first and next vertex making up the edge
  18363. const jNext = ( j + 1 ) % 3;
  18364. const vecHash0 = hashes[ j ];
  18365. const vecHash1 = hashes[ jNext ];
  18366. const v0 = _triangle[ vertKeys[ j ] ];
  18367. const v1 = _triangle[ vertKeys[ jNext ] ];
  18368. const hash = `${ vecHash0 }_${ vecHash1 }`;
  18369. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  18370. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  18371. // if we found a sibling edge add it into the vertex array if
  18372. // it meets the angle threshold and delete the edge from the map.
  18373. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  18374. vertices.push( v0.x, v0.y, v0.z );
  18375. vertices.push( v1.x, v1.y, v1.z );
  18376. }
  18377. edgeData[ reverseHash ] = null;
  18378. } else if ( ! ( hash in edgeData ) ) {
  18379. // if we've already got an edge here then skip adding a new one
  18380. edgeData[ hash ] = {
  18381. index0: indexArr[ j ],
  18382. index1: indexArr[ jNext ],
  18383. normal: _normal$1.clone(),
  18384. };
  18385. }
  18386. }
  18387. }
  18388. // iterate over all remaining, unmatched edges and add them to the vertex array
  18389. for ( const key in edgeData ) {
  18390. if ( edgeData[ key ] ) {
  18391. const { index0, index1 } = edgeData[ key ];
  18392. _v0$2.fromBufferAttribute( positionAttr, index0 );
  18393. _v1$5.fromBufferAttribute( positionAttr, index1 );
  18394. vertices.push( _v0$2.x, _v0$2.y, _v0$2.z );
  18395. vertices.push( _v1$5.x, _v1$5.y, _v1$5.z );
  18396. }
  18397. }
  18398. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18399. }
  18400. }
  18401. /**
  18402. * Port from https://github.com/mapbox/earcut (v2.2.2)
  18403. */
  18404. const Earcut = {
  18405. triangulate: function ( data, holeIndices, dim ) {
  18406. dim = dim || 2;
  18407. const hasHoles = holeIndices && holeIndices.length;
  18408. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  18409. let outerNode = linkedList( data, 0, outerLen, dim, true );
  18410. const triangles = [];
  18411. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  18412. let minX, minY, maxX, maxY, x, y, invSize;
  18413. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  18414. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  18415. if ( data.length > 80 * dim ) {
  18416. minX = maxX = data[ 0 ];
  18417. minY = maxY = data[ 1 ];
  18418. for ( let i = dim; i < outerLen; i += dim ) {
  18419. x = data[ i ];
  18420. y = data[ i + 1 ];
  18421. if ( x < minX ) minX = x;
  18422. if ( y < minY ) minY = y;
  18423. if ( x > maxX ) maxX = x;
  18424. if ( y > maxY ) maxY = y;
  18425. }
  18426. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  18427. invSize = Math.max( maxX - minX, maxY - minY );
  18428. invSize = invSize !== 0 ? 1 / invSize : 0;
  18429. }
  18430. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  18431. return triangles;
  18432. }
  18433. };
  18434. // create a circular doubly linked list from polygon points in the specified winding order
  18435. function linkedList( data, start, end, dim, clockwise ) {
  18436. let i, last;
  18437. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  18438. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  18439. } else {
  18440. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  18441. }
  18442. if ( last && equals( last, last.next ) ) {
  18443. removeNode( last );
  18444. last = last.next;
  18445. }
  18446. return last;
  18447. }
  18448. // eliminate colinear or duplicate points
  18449. function filterPoints( start, end ) {
  18450. if ( ! start ) return start;
  18451. if ( ! end ) end = start;
  18452. let p = start,
  18453. again;
  18454. do {
  18455. again = false;
  18456. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  18457. removeNode( p );
  18458. p = end = p.prev;
  18459. if ( p === p.next ) break;
  18460. again = true;
  18461. } else {
  18462. p = p.next;
  18463. }
  18464. } while ( again || p !== end );
  18465. return end;
  18466. }
  18467. // main ear slicing loop which triangulates a polygon (given as a linked list)
  18468. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  18469. if ( ! ear ) return;
  18470. // interlink polygon nodes in z-order
  18471. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  18472. let stop = ear,
  18473. prev, next;
  18474. // iterate through ears, slicing them one by one
  18475. while ( ear.prev !== ear.next ) {
  18476. prev = ear.prev;
  18477. next = ear.next;
  18478. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  18479. // cut off the triangle
  18480. triangles.push( prev.i / dim );
  18481. triangles.push( ear.i / dim );
  18482. triangles.push( next.i / dim );
  18483. removeNode( ear );
  18484. // skipping the next vertex leads to less sliver triangles
  18485. ear = next.next;
  18486. stop = next.next;
  18487. continue;
  18488. }
  18489. ear = next;
  18490. // if we looped through the whole remaining polygon and can't find any more ears
  18491. if ( ear === stop ) {
  18492. // try filtering points and slicing again
  18493. if ( ! pass ) {
  18494. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  18495. // if this didn't work, try curing all small self-intersections locally
  18496. } else if ( pass === 1 ) {
  18497. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  18498. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  18499. // as a last resort, try splitting the remaining polygon into two
  18500. } else if ( pass === 2 ) {
  18501. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  18502. }
  18503. break;
  18504. }
  18505. }
  18506. }
  18507. // check whether a polygon node forms a valid ear with adjacent nodes
  18508. function isEar( ear ) {
  18509. const a = ear.prev,
  18510. b = ear,
  18511. c = ear.next;
  18512. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  18513. // now make sure we don't have other points inside the potential ear
  18514. let p = ear.next.next;
  18515. while ( p !== ear.prev ) {
  18516. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  18517. area( p.prev, p, p.next ) >= 0 ) return false;
  18518. p = p.next;
  18519. }
  18520. return true;
  18521. }
  18522. function isEarHashed( ear, minX, minY, invSize ) {
  18523. const a = ear.prev,
  18524. b = ear,
  18525. c = ear.next;
  18526. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  18527. // triangle bbox; min & max are calculated like this for speed
  18528. const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  18529. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  18530. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  18531. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  18532. // z-order range for the current triangle bbox;
  18533. const minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  18534. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  18535. let p = ear.prevZ,
  18536. n = ear.nextZ;
  18537. // look for points inside the triangle in both directions
  18538. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  18539. if ( p !== ear.prev && p !== ear.next &&
  18540. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  18541. area( p.prev, p, p.next ) >= 0 ) return false;
  18542. p = p.prevZ;
  18543. if ( n !== ear.prev && n !== ear.next &&
  18544. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  18545. area( n.prev, n, n.next ) >= 0 ) return false;
  18546. n = n.nextZ;
  18547. }
  18548. // look for remaining points in decreasing z-order
  18549. while ( p && p.z >= minZ ) {
  18550. if ( p !== ear.prev && p !== ear.next &&
  18551. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  18552. area( p.prev, p, p.next ) >= 0 ) return false;
  18553. p = p.prevZ;
  18554. }
  18555. // look for remaining points in increasing z-order
  18556. while ( n && n.z <= maxZ ) {
  18557. if ( n !== ear.prev && n !== ear.next &&
  18558. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  18559. area( n.prev, n, n.next ) >= 0 ) return false;
  18560. n = n.nextZ;
  18561. }
  18562. return true;
  18563. }
  18564. // go through all polygon nodes and cure small local self-intersections
  18565. function cureLocalIntersections( start, triangles, dim ) {
  18566. let p = start;
  18567. do {
  18568. const a = p.prev,
  18569. b = p.next.next;
  18570. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  18571. triangles.push( a.i / dim );
  18572. triangles.push( p.i / dim );
  18573. triangles.push( b.i / dim );
  18574. // remove two nodes involved
  18575. removeNode( p );
  18576. removeNode( p.next );
  18577. p = start = b;
  18578. }
  18579. p = p.next;
  18580. } while ( p !== start );
  18581. return filterPoints( p );
  18582. }
  18583. // try splitting polygon into two and triangulate them independently
  18584. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  18585. // look for a valid diagonal that divides the polygon into two
  18586. let a = start;
  18587. do {
  18588. let b = a.next.next;
  18589. while ( b !== a.prev ) {
  18590. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  18591. // split the polygon in two by the diagonal
  18592. let c = splitPolygon( a, b );
  18593. // filter colinear points around the cuts
  18594. a = filterPoints( a, a.next );
  18595. c = filterPoints( c, c.next );
  18596. // run earcut on each half
  18597. earcutLinked( a, triangles, dim, minX, minY, invSize );
  18598. earcutLinked( c, triangles, dim, minX, minY, invSize );
  18599. return;
  18600. }
  18601. b = b.next;
  18602. }
  18603. a = a.next;
  18604. } while ( a !== start );
  18605. }
  18606. // link every hole into the outer loop, producing a single-ring polygon without holes
  18607. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  18608. const queue = [];
  18609. let i, len, start, end, list;
  18610. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  18611. start = holeIndices[ i ] * dim;
  18612. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  18613. list = linkedList( data, start, end, dim, false );
  18614. if ( list === list.next ) list.steiner = true;
  18615. queue.push( getLeftmost( list ) );
  18616. }
  18617. queue.sort( compareX );
  18618. // process holes from left to right
  18619. for ( i = 0; i < queue.length; i ++ ) {
  18620. eliminateHole( queue[ i ], outerNode );
  18621. outerNode = filterPoints( outerNode, outerNode.next );
  18622. }
  18623. return outerNode;
  18624. }
  18625. function compareX( a, b ) {
  18626. return a.x - b.x;
  18627. }
  18628. // find a bridge between vertices that connects hole with an outer ring and and link it
  18629. function eliminateHole( hole, outerNode ) {
  18630. outerNode = findHoleBridge( hole, outerNode );
  18631. if ( outerNode ) {
  18632. const b = splitPolygon( outerNode, hole );
  18633. // filter collinear points around the cuts
  18634. filterPoints( outerNode, outerNode.next );
  18635. filterPoints( b, b.next );
  18636. }
  18637. }
  18638. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  18639. function findHoleBridge( hole, outerNode ) {
  18640. let p = outerNode;
  18641. const hx = hole.x;
  18642. const hy = hole.y;
  18643. let qx = - Infinity, m;
  18644. // find a segment intersected by a ray from the hole's leftmost point to the left;
  18645. // segment's endpoint with lesser x will be potential connection point
  18646. do {
  18647. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  18648. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  18649. if ( x <= hx && x > qx ) {
  18650. qx = x;
  18651. if ( x === hx ) {
  18652. if ( hy === p.y ) return p;
  18653. if ( hy === p.next.y ) return p.next;
  18654. }
  18655. m = p.x < p.next.x ? p : p.next;
  18656. }
  18657. }
  18658. p = p.next;
  18659. } while ( p !== outerNode );
  18660. if ( ! m ) return null;
  18661. if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
  18662. // look for points inside the triangle of hole point, segment intersection and endpoint;
  18663. // if there are no points found, we have a valid connection;
  18664. // otherwise choose the point of the minimum angle with the ray as connection point
  18665. const stop = m,
  18666. mx = m.x,
  18667. my = m.y;
  18668. let tanMin = Infinity, tan;
  18669. p = m;
  18670. do {
  18671. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  18672. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  18673. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  18674. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  18675. m = p;
  18676. tanMin = tan;
  18677. }
  18678. }
  18679. p = p.next;
  18680. } while ( p !== stop );
  18681. return m;
  18682. }
  18683. // whether sector in vertex m contains sector in vertex p in the same coordinates
  18684. function sectorContainsSector( m, p ) {
  18685. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  18686. }
  18687. // interlink polygon nodes in z-order
  18688. function indexCurve( start, minX, minY, invSize ) {
  18689. let p = start;
  18690. do {
  18691. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  18692. p.prevZ = p.prev;
  18693. p.nextZ = p.next;
  18694. p = p.next;
  18695. } while ( p !== start );
  18696. p.prevZ.nextZ = null;
  18697. p.prevZ = null;
  18698. sortLinked( p );
  18699. }
  18700. // Simon Tatham's linked list merge sort algorithm
  18701. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  18702. function sortLinked( list ) {
  18703. let i, p, q, e, tail, numMerges, pSize, qSize,
  18704. inSize = 1;
  18705. do {
  18706. p = list;
  18707. list = null;
  18708. tail = null;
  18709. numMerges = 0;
  18710. while ( p ) {
  18711. numMerges ++;
  18712. q = p;
  18713. pSize = 0;
  18714. for ( i = 0; i < inSize; i ++ ) {
  18715. pSize ++;
  18716. q = q.nextZ;
  18717. if ( ! q ) break;
  18718. }
  18719. qSize = inSize;
  18720. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  18721. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  18722. e = p;
  18723. p = p.nextZ;
  18724. pSize --;
  18725. } else {
  18726. e = q;
  18727. q = q.nextZ;
  18728. qSize --;
  18729. }
  18730. if ( tail ) tail.nextZ = e;
  18731. else list = e;
  18732. e.prevZ = tail;
  18733. tail = e;
  18734. }
  18735. p = q;
  18736. }
  18737. tail.nextZ = null;
  18738. inSize *= 2;
  18739. } while ( numMerges > 1 );
  18740. return list;
  18741. }
  18742. // z-order of a point given coords and inverse of the longer side of data bbox
  18743. function zOrder( x, y, minX, minY, invSize ) {
  18744. // coords are transformed into non-negative 15-bit integer range
  18745. x = 32767 * ( x - minX ) * invSize;
  18746. y = 32767 * ( y - minY ) * invSize;
  18747. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  18748. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  18749. x = ( x | ( x << 2 ) ) & 0x33333333;
  18750. x = ( x | ( x << 1 ) ) & 0x55555555;
  18751. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  18752. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  18753. y = ( y | ( y << 2 ) ) & 0x33333333;
  18754. y = ( y | ( y << 1 ) ) & 0x55555555;
  18755. return x | ( y << 1 );
  18756. }
  18757. // find the leftmost node of a polygon ring
  18758. function getLeftmost( start ) {
  18759. let p = start,
  18760. leftmost = start;
  18761. do {
  18762. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  18763. p = p.next;
  18764. } while ( p !== start );
  18765. return leftmost;
  18766. }
  18767. // check if a point lies within a convex triangle
  18768. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  18769. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  18770. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  18771. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  18772. }
  18773. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  18774. function isValidDiagonal( a, b ) {
  18775. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  18776. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  18777. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  18778. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  18779. }
  18780. // signed area of a triangle
  18781. function area( p, q, r ) {
  18782. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  18783. }
  18784. // check if two points are equal
  18785. function equals( p1, p2 ) {
  18786. return p1.x === p2.x && p1.y === p2.y;
  18787. }
  18788. // check if two segments intersect
  18789. function intersects( p1, q1, p2, q2 ) {
  18790. const o1 = sign( area( p1, q1, p2 ) );
  18791. const o2 = sign( area( p1, q1, q2 ) );
  18792. const o3 = sign( area( p2, q2, p1 ) );
  18793. const o4 = sign( area( p2, q2, q1 ) );
  18794. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  18795. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  18796. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  18797. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  18798. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  18799. return false;
  18800. }
  18801. // for collinear points p, q, r, check if point q lies on segment pr
  18802. function onSegment( p, q, r ) {
  18803. 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 );
  18804. }
  18805. function sign( num ) {
  18806. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  18807. }
  18808. // check if a polygon diagonal intersects any polygon segments
  18809. function intersectsPolygon( a, b ) {
  18810. let p = a;
  18811. do {
  18812. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  18813. intersects( p, p.next, a, b ) ) return true;
  18814. p = p.next;
  18815. } while ( p !== a );
  18816. return false;
  18817. }
  18818. // check if a polygon diagonal is locally inside the polygon
  18819. function locallyInside( a, b ) {
  18820. return area( a.prev, a, a.next ) < 0 ?
  18821. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  18822. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  18823. }
  18824. // check if the middle point of a polygon diagonal is inside the polygon
  18825. function middleInside( a, b ) {
  18826. let p = a,
  18827. inside = false;
  18828. const px = ( a.x + b.x ) / 2,
  18829. py = ( a.y + b.y ) / 2;
  18830. do {
  18831. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  18832. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  18833. inside = ! inside;
  18834. p = p.next;
  18835. } while ( p !== a );
  18836. return inside;
  18837. }
  18838. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  18839. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  18840. function splitPolygon( a, b ) {
  18841. const a2 = new Node( a.i, a.x, a.y ),
  18842. b2 = new Node( b.i, b.x, b.y ),
  18843. an = a.next,
  18844. bp = b.prev;
  18845. a.next = b;
  18846. b.prev = a;
  18847. a2.next = an;
  18848. an.prev = a2;
  18849. b2.next = a2;
  18850. a2.prev = b2;
  18851. bp.next = b2;
  18852. b2.prev = bp;
  18853. return b2;
  18854. }
  18855. // create a node and optionally link it with previous one (in a circular doubly linked list)
  18856. function insertNode( i, x, y, last ) {
  18857. const p = new Node( i, x, y );
  18858. if ( ! last ) {
  18859. p.prev = p;
  18860. p.next = p;
  18861. } else {
  18862. p.next = last.next;
  18863. p.prev = last;
  18864. last.next.prev = p;
  18865. last.next = p;
  18866. }
  18867. return p;
  18868. }
  18869. function removeNode( p ) {
  18870. p.next.prev = p.prev;
  18871. p.prev.next = p.next;
  18872. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  18873. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  18874. }
  18875. function Node( i, x, y ) {
  18876. // vertex index in coordinates array
  18877. this.i = i;
  18878. // vertex coordinates
  18879. this.x = x;
  18880. this.y = y;
  18881. // previous and next vertex nodes in a polygon ring
  18882. this.prev = null;
  18883. this.next = null;
  18884. // z-order curve value
  18885. this.z = null;
  18886. // previous and next nodes in z-order
  18887. this.prevZ = null;
  18888. this.nextZ = null;
  18889. // indicates whether this is a steiner point
  18890. this.steiner = false;
  18891. }
  18892. function signedArea( data, start, end, dim ) {
  18893. let sum = 0;
  18894. for ( let i = start, j = end - dim; i < end; i += dim ) {
  18895. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  18896. j = i;
  18897. }
  18898. return sum;
  18899. }
  18900. const ShapeUtils = {
  18901. // calculate area of the contour polygon
  18902. area: function ( contour ) {
  18903. const n = contour.length;
  18904. let a = 0.0;
  18905. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  18906. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  18907. }
  18908. return a * 0.5;
  18909. },
  18910. isClockWise: function ( pts ) {
  18911. return ShapeUtils.area( pts ) < 0;
  18912. },
  18913. triangulateShape: function ( contour, holes ) {
  18914. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  18915. const holeIndices = []; // array of hole indices
  18916. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  18917. removeDupEndPts( contour );
  18918. addContour( vertices, contour );
  18919. //
  18920. let holeIndex = contour.length;
  18921. holes.forEach( removeDupEndPts );
  18922. for ( let i = 0; i < holes.length; i ++ ) {
  18923. holeIndices.push( holeIndex );
  18924. holeIndex += holes[ i ].length;
  18925. addContour( vertices, holes[ i ] );
  18926. }
  18927. //
  18928. const triangles = Earcut.triangulate( vertices, holeIndices );
  18929. //
  18930. for ( let i = 0; i < triangles.length; i += 3 ) {
  18931. faces.push( triangles.slice( i, i + 3 ) );
  18932. }
  18933. return faces;
  18934. }
  18935. };
  18936. function removeDupEndPts( points ) {
  18937. const l = points.length;
  18938. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  18939. points.pop();
  18940. }
  18941. }
  18942. function addContour( vertices, contour ) {
  18943. for ( let i = 0; i < contour.length; i ++ ) {
  18944. vertices.push( contour[ i ].x );
  18945. vertices.push( contour[ i ].y );
  18946. }
  18947. }
  18948. /**
  18949. * Creates extruded geometry from a path shape.
  18950. *
  18951. * parameters = {
  18952. *
  18953. * curveSegments: <int>, // number of points on the curves
  18954. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18955. * depth: <float>, // Depth to extrude the shape
  18956. *
  18957. * bevelEnabled: <bool>, // turn on bevel
  18958. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18959. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  18960. * bevelOffset: <float>, // how far from shape outline does bevel start
  18961. * bevelSegments: <int>, // number of bevel layers
  18962. *
  18963. * extrudePath: <THREE.Curve> // curve to extrude shape along
  18964. *
  18965. * UVGenerator: <Object> // object that provides UV generator functions
  18966. *
  18967. * }
  18968. */
  18969. class ExtrudeBufferGeometry extends BufferGeometry {
  18970. constructor( shapes, options ) {
  18971. super();
  18972. this.type = 'ExtrudeBufferGeometry';
  18973. this.parameters = {
  18974. shapes: shapes,
  18975. options: options
  18976. };
  18977. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  18978. const scope = this;
  18979. const verticesArray = [];
  18980. const uvArray = [];
  18981. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  18982. const shape = shapes[ i ];
  18983. addShape( shape );
  18984. }
  18985. // build geometry
  18986. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  18987. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  18988. this.computeVertexNormals();
  18989. // functions
  18990. function addShape( shape ) {
  18991. const placeholder = [];
  18992. // options
  18993. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18994. const steps = options.steps !== undefined ? options.steps : 1;
  18995. let depth = options.depth !== undefined ? options.depth : 100;
  18996. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  18997. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  18998. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  18999. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  19000. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19001. const extrudePath = options.extrudePath;
  19002. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  19003. // deprecated options
  19004. if ( options.amount !== undefined ) {
  19005. console.warn( 'THREE.ExtrudeBufferGeometry: amount has been renamed to depth.' );
  19006. depth = options.amount;
  19007. }
  19008. //
  19009. let extrudePts, extrudeByPath = false;
  19010. let splineTube, binormal, normal, position2;
  19011. if ( extrudePath ) {
  19012. extrudePts = extrudePath.getSpacedPoints( steps );
  19013. extrudeByPath = true;
  19014. bevelEnabled = false; // bevels not supported for path extrusion
  19015. // SETUP TNB variables
  19016. // TODO1 - have a .isClosed in spline?
  19017. splineTube = extrudePath.computeFrenetFrames( steps, false );
  19018. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19019. binormal = new Vector3();
  19020. normal = new Vector3();
  19021. position2 = new Vector3();
  19022. }
  19023. // Safeguards if bevels are not enabled
  19024. if ( ! bevelEnabled ) {
  19025. bevelSegments = 0;
  19026. bevelThickness = 0;
  19027. bevelSize = 0;
  19028. bevelOffset = 0;
  19029. }
  19030. // Variables initialization
  19031. const shapePoints = shape.extractPoints( curveSegments );
  19032. let vertices = shapePoints.shape;
  19033. const holes = shapePoints.holes;
  19034. const reverse = ! ShapeUtils.isClockWise( vertices );
  19035. if ( reverse ) {
  19036. vertices = vertices.reverse();
  19037. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19038. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19039. const ahole = holes[ h ];
  19040. if ( ShapeUtils.isClockWise( ahole ) ) {
  19041. holes[ h ] = ahole.reverse();
  19042. }
  19043. }
  19044. }
  19045. const faces = ShapeUtils.triangulateShape( vertices, holes );
  19046. /* Vertices */
  19047. const contour = vertices; // vertices has all points but contour has only points of circumference
  19048. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19049. const ahole = holes[ h ];
  19050. vertices = vertices.concat( ahole );
  19051. }
  19052. function scalePt2( pt, vec, size ) {
  19053. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  19054. return vec.clone().multiplyScalar( size ).add( pt );
  19055. }
  19056. const vlen = vertices.length, flen = faces.length;
  19057. // Find directions for point movement
  19058. function getBevelVec( inPt, inPrev, inNext ) {
  19059. // computes for inPt the corresponding point inPt' on a new contour
  19060. // shifted by 1 unit (length of normalized vector) to the left
  19061. // if we walk along contour clockwise, this new contour is outside the old one
  19062. //
  19063. // inPt' is the intersection of the two lines parallel to the two
  19064. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19065. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  19066. // good reading for geometry algorithms (here: line-line intersection)
  19067. // http://geomalgorithms.com/a05-_intersect-1.html
  19068. const v_prev_x = inPt.x - inPrev.x,
  19069. v_prev_y = inPt.y - inPrev.y;
  19070. const v_next_x = inNext.x - inPt.x,
  19071. v_next_y = inNext.y - inPt.y;
  19072. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19073. // check for collinear edges
  19074. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19075. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  19076. // not collinear
  19077. // length of vectors for normalizing
  19078. const v_prev_len = Math.sqrt( v_prev_lensq );
  19079. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19080. // shift adjacent points by unit vectors to the left
  19081. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19082. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19083. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19084. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19085. // scaling factor for v_prev to intersection point
  19086. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19087. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19088. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19089. // vector from inPt to intersection point
  19090. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19091. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19092. // Don't normalize!, otherwise sharp corners become ugly
  19093. // but prevent crazy spikes
  19094. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  19095. if ( v_trans_lensq <= 2 ) {
  19096. return new Vector2$1( v_trans_x, v_trans_y );
  19097. } else {
  19098. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19099. }
  19100. } else {
  19101. // handle special case of collinear edges
  19102. let direction_eq = false; // assumes: opposite
  19103. if ( v_prev_x > Number.EPSILON ) {
  19104. if ( v_next_x > Number.EPSILON ) {
  19105. direction_eq = true;
  19106. }
  19107. } else {
  19108. if ( v_prev_x < - Number.EPSILON ) {
  19109. if ( v_next_x < - Number.EPSILON ) {
  19110. direction_eq = true;
  19111. }
  19112. } else {
  19113. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  19114. direction_eq = true;
  19115. }
  19116. }
  19117. }
  19118. if ( direction_eq ) {
  19119. // console.log("Warning: lines are a straight sequence");
  19120. v_trans_x = - v_prev_y;
  19121. v_trans_y = v_prev_x;
  19122. shrink_by = Math.sqrt( v_prev_lensq );
  19123. } else {
  19124. // console.log("Warning: lines are a straight spike");
  19125. v_trans_x = v_prev_x;
  19126. v_trans_y = v_prev_y;
  19127. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  19128. }
  19129. }
  19130. return new Vector2$1( v_trans_x / shrink_by, v_trans_y / shrink_by );
  19131. }
  19132. const contourMovements = [];
  19133. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19134. if ( j === il ) j = 0;
  19135. if ( k === il ) k = 0;
  19136. // (j)---(i)---(k)
  19137. // console.log('i,j,k', i, j , k)
  19138. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19139. }
  19140. const holesMovements = [];
  19141. let oneHoleMovements, verticesMovements = contourMovements.concat();
  19142. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19143. const ahole = holes[ h ];
  19144. oneHoleMovements = [];
  19145. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19146. if ( j === il ) j = 0;
  19147. if ( k === il ) k = 0;
  19148. // (j)---(i)---(k)
  19149. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19150. }
  19151. holesMovements.push( oneHoleMovements );
  19152. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19153. }
  19154. // Loop bevelSegments, 1 for the front, 1 for the back
  19155. for ( let b = 0; b < bevelSegments; b ++ ) {
  19156. //for ( b = bevelSegments; b > 0; b -- ) {
  19157. const t = b / bevelSegments;
  19158. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  19159. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  19160. // contract shape
  19161. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  19162. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19163. v( vert.x, vert.y, - z );
  19164. }
  19165. // expand holes
  19166. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19167. const ahole = holes[ h ];
  19168. oneHoleMovements = holesMovements[ h ];
  19169. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  19170. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19171. v( vert.x, vert.y, - z );
  19172. }
  19173. }
  19174. }
  19175. const bs = bevelSize + bevelOffset;
  19176. // Back facing vertices
  19177. for ( let i = 0; i < vlen; i ++ ) {
  19178. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19179. if ( ! extrudeByPath ) {
  19180. v( vert.x, vert.y, 0 );
  19181. } else {
  19182. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19183. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  19184. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  19185. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  19186. v( position2.x, position2.y, position2.z );
  19187. }
  19188. }
  19189. // Add stepped vertices...
  19190. // Including front facing vertices
  19191. for ( let s = 1; s <= steps; s ++ ) {
  19192. for ( let i = 0; i < vlen; i ++ ) {
  19193. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19194. if ( ! extrudeByPath ) {
  19195. v( vert.x, vert.y, depth / steps * s );
  19196. } else {
  19197. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19198. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  19199. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  19200. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  19201. v( position2.x, position2.y, position2.z );
  19202. }
  19203. }
  19204. }
  19205. // Add bevel segments planes
  19206. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19207. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  19208. const t = b / bevelSegments;
  19209. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  19210. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  19211. // contract shape
  19212. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  19213. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19214. v( vert.x, vert.y, depth + z );
  19215. }
  19216. // expand holes
  19217. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19218. const ahole = holes[ h ];
  19219. oneHoleMovements = holesMovements[ h ];
  19220. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  19221. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19222. if ( ! extrudeByPath ) {
  19223. v( vert.x, vert.y, depth + z );
  19224. } else {
  19225. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19226. }
  19227. }
  19228. }
  19229. }
  19230. /* Faces */
  19231. // Top and bottom faces
  19232. buildLidFaces();
  19233. // Sides faces
  19234. buildSideFaces();
  19235. ///// Internal functions
  19236. function buildLidFaces() {
  19237. const start = verticesArray.length / 3;
  19238. if ( bevelEnabled ) {
  19239. let layer = 0; // steps + 1
  19240. let offset = vlen * layer;
  19241. // Bottom faces
  19242. for ( let i = 0; i < flen; i ++ ) {
  19243. const face = faces[ i ];
  19244. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  19245. }
  19246. layer = steps + bevelSegments * 2;
  19247. offset = vlen * layer;
  19248. // Top faces
  19249. for ( let i = 0; i < flen; i ++ ) {
  19250. const face = faces[ i ];
  19251. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  19252. }
  19253. } else {
  19254. // Bottom faces
  19255. for ( let i = 0; i < flen; i ++ ) {
  19256. const face = faces[ i ];
  19257. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  19258. }
  19259. // Top faces
  19260. for ( let i = 0; i < flen; i ++ ) {
  19261. const face = faces[ i ];
  19262. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  19263. }
  19264. }
  19265. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  19266. }
  19267. // Create faces for the z-sides of the shape
  19268. function buildSideFaces() {
  19269. const start = verticesArray.length / 3;
  19270. let layeroffset = 0;
  19271. sidewalls( contour, layeroffset );
  19272. layeroffset += contour.length;
  19273. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  19274. const ahole = holes[ h ];
  19275. sidewalls( ahole, layeroffset );
  19276. //, true
  19277. layeroffset += ahole.length;
  19278. }
  19279. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  19280. }
  19281. function sidewalls( contour, layeroffset ) {
  19282. let i = contour.length;
  19283. while ( -- i >= 0 ) {
  19284. const j = i;
  19285. let k = i - 1;
  19286. if ( k < 0 ) k = contour.length - 1;
  19287. //console.log('b', i,j, i-1, k,vertices.length);
  19288. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  19289. const slen1 = vlen * s;
  19290. const slen2 = vlen * ( s + 1 );
  19291. const a = layeroffset + j + slen1,
  19292. b = layeroffset + k + slen1,
  19293. c = layeroffset + k + slen2,
  19294. d = layeroffset + j + slen2;
  19295. f4( a, b, c, d );
  19296. }
  19297. }
  19298. }
  19299. function v( x, y, z ) {
  19300. placeholder.push( x );
  19301. placeholder.push( y );
  19302. placeholder.push( z );
  19303. }
  19304. function f3( a, b, c ) {
  19305. addVertex( a );
  19306. addVertex( b );
  19307. addVertex( c );
  19308. const nextIndex = verticesArray.length / 3;
  19309. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  19310. addUV( uvs[ 0 ] );
  19311. addUV( uvs[ 1 ] );
  19312. addUV( uvs[ 2 ] );
  19313. }
  19314. function f4( a, b, c, d ) {
  19315. addVertex( a );
  19316. addVertex( b );
  19317. addVertex( d );
  19318. addVertex( b );
  19319. addVertex( c );
  19320. addVertex( d );
  19321. const nextIndex = verticesArray.length / 3;
  19322. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  19323. addUV( uvs[ 0 ] );
  19324. addUV( uvs[ 1 ] );
  19325. addUV( uvs[ 3 ] );
  19326. addUV( uvs[ 1 ] );
  19327. addUV( uvs[ 2 ] );
  19328. addUV( uvs[ 3 ] );
  19329. }
  19330. function addVertex( index ) {
  19331. verticesArray.push( placeholder[ index * 3 + 0 ] );
  19332. verticesArray.push( placeholder[ index * 3 + 1 ] );
  19333. verticesArray.push( placeholder[ index * 3 + 2 ] );
  19334. }
  19335. function addUV( vector2 ) {
  19336. uvArray.push( vector2.x );
  19337. uvArray.push( vector2.y );
  19338. }
  19339. }
  19340. }
  19341. toJSON() {
  19342. const data = BufferGeometry.prototype.toJSON.call( this );
  19343. const shapes = this.parameters.shapes;
  19344. const options = this.parameters.options;
  19345. return toJSON( shapes, options, data );
  19346. }
  19347. }
  19348. const WorldUVGenerator = {
  19349. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  19350. const a_x = vertices[ indexA * 3 ];
  19351. const a_y = vertices[ indexA * 3 + 1 ];
  19352. const b_x = vertices[ indexB * 3 ];
  19353. const b_y = vertices[ indexB * 3 + 1 ];
  19354. const c_x = vertices[ indexC * 3 ];
  19355. const c_y = vertices[ indexC * 3 + 1 ];
  19356. return [
  19357. new Vector2$1( a_x, a_y ),
  19358. new Vector2$1( b_x, b_y ),
  19359. new Vector2$1( c_x, c_y )
  19360. ];
  19361. },
  19362. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  19363. const a_x = vertices[ indexA * 3 ];
  19364. const a_y = vertices[ indexA * 3 + 1 ];
  19365. const a_z = vertices[ indexA * 3 + 2 ];
  19366. const b_x = vertices[ indexB * 3 ];
  19367. const b_y = vertices[ indexB * 3 + 1 ];
  19368. const b_z = vertices[ indexB * 3 + 2 ];
  19369. const c_x = vertices[ indexC * 3 ];
  19370. const c_y = vertices[ indexC * 3 + 1 ];
  19371. const c_z = vertices[ indexC * 3 + 2 ];
  19372. const d_x = vertices[ indexD * 3 ];
  19373. const d_y = vertices[ indexD * 3 + 1 ];
  19374. const d_z = vertices[ indexD * 3 + 2 ];
  19375. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  19376. return [
  19377. new Vector2$1( a_x, 1 - a_z ),
  19378. new Vector2$1( b_x, 1 - b_z ),
  19379. new Vector2$1( c_x, 1 - c_z ),
  19380. new Vector2$1( d_x, 1 - d_z )
  19381. ];
  19382. } else {
  19383. return [
  19384. new Vector2$1( a_y, 1 - a_z ),
  19385. new Vector2$1( b_y, 1 - b_z ),
  19386. new Vector2$1( c_y, 1 - c_z ),
  19387. new Vector2$1( d_y, 1 - d_z )
  19388. ];
  19389. }
  19390. }
  19391. };
  19392. function toJSON( shapes, options, data ) {
  19393. data.shapes = [];
  19394. if ( Array.isArray( shapes ) ) {
  19395. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19396. const shape = shapes[ i ];
  19397. data.shapes.push( shape.uuid );
  19398. }
  19399. } else {
  19400. data.shapes.push( shapes.uuid );
  19401. }
  19402. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  19403. return data;
  19404. }
  19405. /**
  19406. * Creates extruded geometry from a path shape.
  19407. *
  19408. * parameters = {
  19409. *
  19410. * curveSegments: <int>, // number of points on the curves
  19411. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19412. * depth: <float>, // Depth to extrude the shape
  19413. *
  19414. * bevelEnabled: <bool>, // turn on bevel
  19415. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19416. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19417. * bevelOffset: <float>, // how far from shape outline does bevel start
  19418. * bevelSegments: <int>, // number of bevel layers
  19419. *
  19420. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19421. *
  19422. * UVGenerator: <Object> // object that provides UV generator functions
  19423. *
  19424. * }
  19425. */
  19426. class ExtrudeGeometry extends Geometry {
  19427. constructor( shapes, options ) {
  19428. super();
  19429. this.type = 'ExtrudeGeometry';
  19430. this.parameters = {
  19431. shapes: shapes,
  19432. options: options
  19433. };
  19434. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  19435. this.mergeVertices();
  19436. }
  19437. toJSON() {
  19438. const data = super.toJSON();
  19439. const shapes = this.parameters.shapes;
  19440. const options = this.parameters.options;
  19441. return toJSON$1( shapes, options, data );
  19442. }
  19443. }
  19444. function toJSON$1( shapes, options, data ) {
  19445. data.shapes = [];
  19446. if ( Array.isArray( shapes ) ) {
  19447. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19448. const shape = shapes[ i ];
  19449. data.shapes.push( shape.uuid );
  19450. }
  19451. } else {
  19452. data.shapes.push( shapes.uuid );
  19453. }
  19454. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  19455. return data;
  19456. }
  19457. class IcosahedronBufferGeometry extends PolyhedronBufferGeometry {
  19458. constructor( radius = 1, detail = 0 ) {
  19459. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19460. const vertices = [
  19461. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  19462. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  19463. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  19464. ];
  19465. const indices = [
  19466. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  19467. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  19468. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  19469. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  19470. ];
  19471. super( vertices, indices, radius, detail );
  19472. this.type = 'IcosahedronBufferGeometry';
  19473. this.parameters = {
  19474. radius: radius,
  19475. detail: detail
  19476. };
  19477. }
  19478. }
  19479. class IcosahedronGeometry extends Geometry {
  19480. constructor( radius, detail ) {
  19481. super();
  19482. this.type = 'IcosahedronGeometry';
  19483. this.parameters = {
  19484. radius: radius,
  19485. detail: detail
  19486. };
  19487. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  19488. this.mergeVertices();
  19489. }
  19490. }
  19491. class LatheBufferGeometry extends BufferGeometry {
  19492. constructor( points, segments = 12, phiStart = 0, phiLength = Math.PI * 2 ) {
  19493. super();
  19494. this.type = 'LatheBufferGeometry';
  19495. this.parameters = {
  19496. points: points,
  19497. segments: segments,
  19498. phiStart: phiStart,
  19499. phiLength: phiLength
  19500. };
  19501. segments = Math.floor( segments );
  19502. // clamp phiLength so it's in range of [ 0, 2PI ]
  19503. phiLength = MathUtils.clamp( phiLength, 0, Math.PI * 2 );
  19504. // buffers
  19505. const indices = [];
  19506. const vertices = [];
  19507. const uvs = [];
  19508. // helper variables
  19509. const inverseSegments = 1.0 / segments;
  19510. const vertex = new Vector3();
  19511. const uv = new Vector2$1();
  19512. // generate vertices and uvs
  19513. for ( let i = 0; i <= segments; i ++ ) {
  19514. const phi = phiStart + i * inverseSegments * phiLength;
  19515. const sin = Math.sin( phi );
  19516. const cos = Math.cos( phi );
  19517. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19518. // vertex
  19519. vertex.x = points[ j ].x * sin;
  19520. vertex.y = points[ j ].y;
  19521. vertex.z = points[ j ].x * cos;
  19522. vertices.push( vertex.x, vertex.y, vertex.z );
  19523. // uv
  19524. uv.x = i / segments;
  19525. uv.y = j / ( points.length - 1 );
  19526. uvs.push( uv.x, uv.y );
  19527. }
  19528. }
  19529. // indices
  19530. for ( let i = 0; i < segments; i ++ ) {
  19531. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  19532. const base = j + i * points.length;
  19533. const a = base;
  19534. const b = base + points.length;
  19535. const c = base + points.length + 1;
  19536. const d = base + 1;
  19537. // faces
  19538. indices.push( a, b, d );
  19539. indices.push( b, c, d );
  19540. }
  19541. }
  19542. // build geometry
  19543. this.setIndex( indices );
  19544. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19545. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19546. // generate normals
  19547. this.computeVertexNormals();
  19548. // if the geometry is closed, we need to average the normals along the seam.
  19549. // because the corresponding vertices are identical (but still have different UVs).
  19550. if ( phiLength === Math.PI * 2 ) {
  19551. const normals = this.attributes.normal.array;
  19552. const n1 = new Vector3();
  19553. const n2 = new Vector3();
  19554. const n = new Vector3();
  19555. // this is the buffer offset for the last line of vertices
  19556. const base = segments * points.length * 3;
  19557. for ( let i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  19558. // select the normal of the vertex in the first line
  19559. n1.x = normals[ j + 0 ];
  19560. n1.y = normals[ j + 1 ];
  19561. n1.z = normals[ j + 2 ];
  19562. // select the normal of the vertex in the last line
  19563. n2.x = normals[ base + j + 0 ];
  19564. n2.y = normals[ base + j + 1 ];
  19565. n2.z = normals[ base + j + 2 ];
  19566. // average normals
  19567. n.addVectors( n1, n2 ).normalize();
  19568. // assign the new values to both normals
  19569. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  19570. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  19571. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  19572. }
  19573. }
  19574. }
  19575. }
  19576. class LatheGeometry extends Geometry {
  19577. constructor( points, segments, phiStart, phiLength ) {
  19578. super();
  19579. this.type = 'LatheGeometry';
  19580. this.parameters = {
  19581. points: points,
  19582. segments: segments,
  19583. phiStart: phiStart,
  19584. phiLength: phiLength
  19585. };
  19586. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  19587. this.mergeVertices();
  19588. }
  19589. }
  19590. class OctahedronBufferGeometry extends PolyhedronBufferGeometry {
  19591. constructor( radius = 1, detail = 0 ) {
  19592. const vertices = [
  19593. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  19594. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  19595. ];
  19596. const indices = [
  19597. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  19598. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  19599. 1, 3, 4, 1, 4, 2
  19600. ];
  19601. super( vertices, indices, radius, detail );
  19602. this.type = 'OctahedronBufferGeometry';
  19603. this.parameters = {
  19604. radius: radius,
  19605. detail: detail
  19606. };
  19607. }
  19608. }
  19609. class OctahedronGeometry extends Geometry {
  19610. constructor( radius, detail ) {
  19611. super();
  19612. this.type = 'OctahedronGeometry';
  19613. this.parameters = {
  19614. radius: radius,
  19615. detail: detail
  19616. };
  19617. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  19618. this.mergeVertices();
  19619. }
  19620. }
  19621. /**
  19622. * Parametric Surfaces Geometry
  19623. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  19624. */
  19625. function ParametricBufferGeometry( func, slices, stacks ) {
  19626. BufferGeometry.call( this );
  19627. this.type = 'ParametricBufferGeometry';
  19628. this.parameters = {
  19629. func: func,
  19630. slices: slices,
  19631. stacks: stacks
  19632. };
  19633. // buffers
  19634. const indices = [];
  19635. const vertices = [];
  19636. const normals = [];
  19637. const uvs = [];
  19638. const EPS = 0.00001;
  19639. const normal = new Vector3();
  19640. const p0 = new Vector3(), p1 = new Vector3();
  19641. const pu = new Vector3(), pv = new Vector3();
  19642. if ( func.length < 3 ) {
  19643. console.error( 'THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.' );
  19644. }
  19645. // generate vertices, normals and uvs
  19646. const sliceCount = slices + 1;
  19647. for ( let i = 0; i <= stacks; i ++ ) {
  19648. const v = i / stacks;
  19649. for ( let j = 0; j <= slices; j ++ ) {
  19650. const u = j / slices;
  19651. // vertex
  19652. func( u, v, p0 );
  19653. vertices.push( p0.x, p0.y, p0.z );
  19654. // normal
  19655. // approximate tangent vectors via finite differences
  19656. if ( u - EPS >= 0 ) {
  19657. func( u - EPS, v, p1 );
  19658. pu.subVectors( p0, p1 );
  19659. } else {
  19660. func( u + EPS, v, p1 );
  19661. pu.subVectors( p1, p0 );
  19662. }
  19663. if ( v - EPS >= 0 ) {
  19664. func( u, v - EPS, p1 );
  19665. pv.subVectors( p0, p1 );
  19666. } else {
  19667. func( u, v + EPS, p1 );
  19668. pv.subVectors( p1, p0 );
  19669. }
  19670. // cross product of tangent vectors returns surface normal
  19671. normal.crossVectors( pu, pv ).normalize();
  19672. normals.push( normal.x, normal.y, normal.z );
  19673. // uv
  19674. uvs.push( u, v );
  19675. }
  19676. }
  19677. // generate indices
  19678. for ( let i = 0; i < stacks; i ++ ) {
  19679. for ( let j = 0; j < slices; j ++ ) {
  19680. const a = i * sliceCount + j;
  19681. const b = i * sliceCount + j + 1;
  19682. const c = ( i + 1 ) * sliceCount + j + 1;
  19683. const d = ( i + 1 ) * sliceCount + j;
  19684. // faces one and two
  19685. indices.push( a, b, d );
  19686. indices.push( b, c, d );
  19687. }
  19688. }
  19689. // build geometry
  19690. this.setIndex( indices );
  19691. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19692. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19693. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19694. }
  19695. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19696. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  19697. /**
  19698. * Parametric Surfaces Geometry
  19699. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  19700. */
  19701. function ParametricGeometry( func, slices, stacks ) {
  19702. Geometry.call( this );
  19703. this.type = 'ParametricGeometry';
  19704. this.parameters = {
  19705. func: func,
  19706. slices: slices,
  19707. stacks: stacks
  19708. };
  19709. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  19710. this.mergeVertices();
  19711. }
  19712. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  19713. ParametricGeometry.prototype.constructor = ParametricGeometry;
  19714. class PlaneGeometry extends Geometry {
  19715. constructor( width, height, widthSegments, heightSegments ) {
  19716. super();
  19717. this.type = 'PlaneGeometry';
  19718. this.parameters = {
  19719. width: width,
  19720. height: height,
  19721. widthSegments: widthSegments,
  19722. heightSegments: heightSegments
  19723. };
  19724. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  19725. this.mergeVertices();
  19726. }
  19727. }
  19728. class PolyhedronGeometry extends Geometry {
  19729. constructor( vertices, indices, radius, detail ) {
  19730. super();
  19731. this.type = 'PolyhedronGeometry';
  19732. this.parameters = {
  19733. vertices: vertices,
  19734. indices: indices,
  19735. radius: radius,
  19736. detail: detail
  19737. };
  19738. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  19739. this.mergeVertices();
  19740. }
  19741. }
  19742. class RingBufferGeometry extends BufferGeometry {
  19743. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19744. super();
  19745. this.type = 'RingBufferGeometry';
  19746. this.parameters = {
  19747. innerRadius: innerRadius,
  19748. outerRadius: outerRadius,
  19749. thetaSegments: thetaSegments,
  19750. phiSegments: phiSegments,
  19751. thetaStart: thetaStart,
  19752. thetaLength: thetaLength
  19753. };
  19754. thetaSegments = Math.max( 3, thetaSegments );
  19755. phiSegments = Math.max( 1, phiSegments );
  19756. // buffers
  19757. const indices = [];
  19758. const vertices = [];
  19759. const normals = [];
  19760. const uvs = [];
  19761. // some helper variables
  19762. let radius = innerRadius;
  19763. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19764. const vertex = new Vector3();
  19765. const uv = new Vector2$1();
  19766. // generate vertices, normals and uvs
  19767. for ( let j = 0; j <= phiSegments; j ++ ) {
  19768. for ( let i = 0; i <= thetaSegments; i ++ ) {
  19769. // values are generate from the inside of the ring to the outside
  19770. const segment = thetaStart + i / thetaSegments * thetaLength;
  19771. // vertex
  19772. vertex.x = radius * Math.cos( segment );
  19773. vertex.y = radius * Math.sin( segment );
  19774. vertices.push( vertex.x, vertex.y, vertex.z );
  19775. // normal
  19776. normals.push( 0, 0, 1 );
  19777. // uv
  19778. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  19779. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  19780. uvs.push( uv.x, uv.y );
  19781. }
  19782. // increase the radius for next row of vertices
  19783. radius += radiusStep;
  19784. }
  19785. // indices
  19786. for ( let j = 0; j < phiSegments; j ++ ) {
  19787. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  19788. for ( let i = 0; i < thetaSegments; i ++ ) {
  19789. const segment = i + thetaSegmentLevel;
  19790. const a = segment;
  19791. const b = segment + thetaSegments + 1;
  19792. const c = segment + thetaSegments + 2;
  19793. const d = segment + 1;
  19794. // faces
  19795. indices.push( a, b, d );
  19796. indices.push( b, c, d );
  19797. }
  19798. }
  19799. // build geometry
  19800. this.setIndex( indices );
  19801. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19802. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19803. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19804. }
  19805. }
  19806. class RingGeometry extends Geometry {
  19807. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19808. super();
  19809. this.type = 'RingGeometry';
  19810. this.parameters = {
  19811. innerRadius: innerRadius,
  19812. outerRadius: outerRadius,
  19813. thetaSegments: thetaSegments,
  19814. phiSegments: phiSegments,
  19815. thetaStart: thetaStart,
  19816. thetaLength: thetaLength
  19817. };
  19818. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  19819. this.mergeVertices();
  19820. }
  19821. }
  19822. class ShapeBufferGeometry extends BufferGeometry {
  19823. constructor( shapes, curveSegments = 12 ) {
  19824. super();
  19825. this.type = 'ShapeBufferGeometry';
  19826. this.parameters = {
  19827. shapes: shapes,
  19828. curveSegments: curveSegments
  19829. };
  19830. // buffers
  19831. const indices = [];
  19832. const vertices = [];
  19833. const normals = [];
  19834. const uvs = [];
  19835. // helper variables
  19836. let groupStart = 0;
  19837. let groupCount = 0;
  19838. // allow single and array values for "shapes" parameter
  19839. if ( Array.isArray( shapes ) === false ) {
  19840. addShape( shapes );
  19841. } else {
  19842. for ( let i = 0; i < shapes.length; i ++ ) {
  19843. addShape( shapes[ i ] );
  19844. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  19845. groupStart += groupCount;
  19846. groupCount = 0;
  19847. }
  19848. }
  19849. // build geometry
  19850. this.setIndex( indices );
  19851. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19852. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19853. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19854. // helper functions
  19855. function addShape( shape ) {
  19856. const indexOffset = vertices.length / 3;
  19857. const points = shape.extractPoints( curveSegments );
  19858. let shapeVertices = points.shape;
  19859. const shapeHoles = points.holes;
  19860. // check direction of vertices
  19861. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  19862. shapeVertices = shapeVertices.reverse();
  19863. }
  19864. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  19865. const shapeHole = shapeHoles[ i ];
  19866. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  19867. shapeHoles[ i ] = shapeHole.reverse();
  19868. }
  19869. }
  19870. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  19871. // join vertices of inner and outer paths to a single array
  19872. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  19873. const shapeHole = shapeHoles[ i ];
  19874. shapeVertices = shapeVertices.concat( shapeHole );
  19875. }
  19876. // vertices, normals, uvs
  19877. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  19878. const vertex = shapeVertices[ i ];
  19879. vertices.push( vertex.x, vertex.y, 0 );
  19880. normals.push( 0, 0, 1 );
  19881. uvs.push( vertex.x, vertex.y ); // world uvs
  19882. }
  19883. // incides
  19884. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  19885. const face = faces[ i ];
  19886. const a = face[ 0 ] + indexOffset;
  19887. const b = face[ 1 ] + indexOffset;
  19888. const c = face[ 2 ] + indexOffset;
  19889. indices.push( a, b, c );
  19890. groupCount += 3;
  19891. }
  19892. }
  19893. }
  19894. toJSON() {
  19895. const data = BufferGeometry.prototype.toJSON.call( this );
  19896. const shapes = this.parameters.shapes;
  19897. return toJSON$2( shapes, data );
  19898. }
  19899. }
  19900. function toJSON$2( shapes, data ) {
  19901. data.shapes = [];
  19902. if ( Array.isArray( shapes ) ) {
  19903. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19904. const shape = shapes[ i ];
  19905. data.shapes.push( shape.uuid );
  19906. }
  19907. } else {
  19908. data.shapes.push( shapes.uuid );
  19909. }
  19910. return data;
  19911. }
  19912. class ShapeGeometry extends Geometry {
  19913. constructor( shapes, curveSegments ) {
  19914. super();
  19915. this.type = 'ShapeGeometry';
  19916. if ( typeof curveSegments === 'object' ) {
  19917. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  19918. curveSegments = curveSegments.curveSegments;
  19919. }
  19920. this.parameters = {
  19921. shapes: shapes,
  19922. curveSegments: curveSegments
  19923. };
  19924. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  19925. this.mergeVertices();
  19926. }
  19927. toJSON() {
  19928. const data = Geometry.prototype.toJSON.call( this );
  19929. const shapes = this.parameters.shapes;
  19930. return toJSON$3( shapes, data );
  19931. }
  19932. }
  19933. function toJSON$3( shapes, data ) {
  19934. data.shapes = [];
  19935. if ( Array.isArray( shapes ) ) {
  19936. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  19937. const shape = shapes[ i ];
  19938. data.shapes.push( shape.uuid );
  19939. }
  19940. } else {
  19941. data.shapes.push( shapes.uuid );
  19942. }
  19943. return data;
  19944. }
  19945. class SphereBufferGeometry extends BufferGeometry {
  19946. constructor( radius = 1, widthSegments = 8, heightSegments = 6, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  19947. super();
  19948. this.type = 'SphereBufferGeometry';
  19949. this.parameters = {
  19950. radius: radius,
  19951. widthSegments: widthSegments,
  19952. heightSegments: heightSegments,
  19953. phiStart: phiStart,
  19954. phiLength: phiLength,
  19955. thetaStart: thetaStart,
  19956. thetaLength: thetaLength
  19957. };
  19958. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  19959. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  19960. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  19961. let index = 0;
  19962. const grid = [];
  19963. const vertex = new Vector3();
  19964. const normal = new Vector3();
  19965. // buffers
  19966. const indices = [];
  19967. const vertices = [];
  19968. const normals = [];
  19969. const uvs = [];
  19970. // generate vertices, normals and uvs
  19971. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  19972. const verticesRow = [];
  19973. const v = iy / heightSegments;
  19974. // special case for the poles
  19975. let uOffset = 0;
  19976. if ( iy == 0 && thetaStart == 0 ) {
  19977. uOffset = 0.5 / widthSegments;
  19978. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  19979. uOffset = - 0.5 / widthSegments;
  19980. }
  19981. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  19982. const u = ix / widthSegments;
  19983. // vertex
  19984. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19985. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19986. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19987. vertices.push( vertex.x, vertex.y, vertex.z );
  19988. // normal
  19989. normal.copy( vertex ).normalize();
  19990. normals.push( normal.x, normal.y, normal.z );
  19991. // uv
  19992. uvs.push( u + uOffset, 1 - v );
  19993. verticesRow.push( index ++ );
  19994. }
  19995. grid.push( verticesRow );
  19996. }
  19997. // indices
  19998. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  19999. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  20000. const a = grid[ iy ][ ix + 1 ];
  20001. const b = grid[ iy ][ ix ];
  20002. const c = grid[ iy + 1 ][ ix ];
  20003. const d = grid[ iy + 1 ][ ix + 1 ];
  20004. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  20005. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  20006. }
  20007. }
  20008. // build geometry
  20009. this.setIndex( indices );
  20010. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20011. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20012. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20013. }
  20014. }
  20015. class SphereGeometry extends Geometry {
  20016. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  20017. super();
  20018. this.type = 'SphereGeometry';
  20019. this.parameters = {
  20020. radius: radius,
  20021. widthSegments: widthSegments,
  20022. heightSegments: heightSegments,
  20023. phiStart: phiStart,
  20024. phiLength: phiLength,
  20025. thetaStart: thetaStart,
  20026. thetaLength: thetaLength
  20027. };
  20028. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  20029. this.mergeVertices();
  20030. }
  20031. }
  20032. class TetrahedronBufferGeometry extends PolyhedronBufferGeometry {
  20033. constructor( radius = 1, detail = 0 ) {
  20034. const vertices = [
  20035. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  20036. ];
  20037. const indices = [
  20038. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  20039. ];
  20040. super( vertices, indices, radius, detail );
  20041. this.type = 'TetrahedronBufferGeometry';
  20042. this.parameters = {
  20043. radius: radius,
  20044. detail: detail
  20045. };
  20046. }
  20047. }
  20048. class TetrahedronGeometry extends Geometry {
  20049. constructor( radius, detail ) {
  20050. super();
  20051. this.type = 'TetrahedronGeometry';
  20052. this.parameters = {
  20053. radius: radius,
  20054. detail: detail
  20055. };
  20056. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  20057. this.mergeVertices();
  20058. }
  20059. }
  20060. /**
  20061. * Text = 3D Text
  20062. *
  20063. * parameters = {
  20064. * font: <THREE.Font>, // font
  20065. *
  20066. * size: <float>, // size of the text
  20067. * height: <float>, // thickness to extrude text
  20068. * curveSegments: <int>, // number of points on the curves
  20069. *
  20070. * bevelEnabled: <bool>, // turn on bevel
  20071. * bevelThickness: <float>, // how deep into text bevel goes
  20072. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  20073. * bevelOffset: <float> // how far from text outline does bevel start
  20074. * }
  20075. */
  20076. class TextBufferGeometry extends ExtrudeBufferGeometry {
  20077. constructor( text, parameters = {} ) {
  20078. const font = parameters.font;
  20079. if ( ! ( font && font.isFont ) ) {
  20080. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  20081. return new BufferGeometry();
  20082. }
  20083. const shapes = font.generateShapes( text, parameters.size );
  20084. // translate parameters to ExtrudeGeometry API
  20085. parameters.depth = parameters.height !== undefined ? parameters.height : 50;
  20086. // defaults
  20087. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  20088. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  20089. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  20090. super( shapes, parameters );
  20091. this.type = 'TextBufferGeometry';
  20092. }
  20093. }
  20094. /**
  20095. * Text = 3D Text
  20096. *
  20097. * parameters = {
  20098. * font: <THREE.Font>, // font
  20099. *
  20100. * size: <float>, // size of the text
  20101. * height: <float>, // thickness to extrude text
  20102. * curveSegments: <int>, // number of points on the curves
  20103. *
  20104. * bevelEnabled: <bool>, // turn on bevel
  20105. * bevelThickness: <float>, // how deep into text bevel goes
  20106. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  20107. * bevelOffset: <float> // how far from text outline does bevel start
  20108. * }
  20109. */
  20110. class TextGeometry extends Geometry {
  20111. constructor( text, parameters ) {
  20112. super();
  20113. this.type = 'TextGeometry';
  20114. this.parameters = {
  20115. text: text,
  20116. parameters: parameters
  20117. };
  20118. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  20119. this.mergeVertices();
  20120. }
  20121. }
  20122. class TorusBufferGeometry extends BufferGeometry {
  20123. constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) {
  20124. super();
  20125. this.type = 'TorusBufferGeometry';
  20126. this.parameters = {
  20127. radius: radius,
  20128. tube: tube,
  20129. radialSegments: radialSegments,
  20130. tubularSegments: tubularSegments,
  20131. arc: arc
  20132. };
  20133. radialSegments = Math.floor( radialSegments );
  20134. tubularSegments = Math.floor( tubularSegments );
  20135. // buffers
  20136. const indices = [];
  20137. const vertices = [];
  20138. const normals = [];
  20139. const uvs = [];
  20140. // helper variables
  20141. const center = new Vector3();
  20142. const vertex = new Vector3();
  20143. const normal = new Vector3();
  20144. // generate vertices, normals and uvs
  20145. for ( let j = 0; j <= radialSegments; j ++ ) {
  20146. for ( let i = 0; i <= tubularSegments; i ++ ) {
  20147. const u = i / tubularSegments * arc;
  20148. const v = j / radialSegments * Math.PI * 2;
  20149. // vertex
  20150. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  20151. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  20152. vertex.z = tube * Math.sin( v );
  20153. vertices.push( vertex.x, vertex.y, vertex.z );
  20154. // normal
  20155. center.x = radius * Math.cos( u );
  20156. center.y = radius * Math.sin( u );
  20157. normal.subVectors( vertex, center ).normalize();
  20158. normals.push( normal.x, normal.y, normal.z );
  20159. // uv
  20160. uvs.push( i / tubularSegments );
  20161. uvs.push( j / radialSegments );
  20162. }
  20163. }
  20164. // generate indices
  20165. for ( let j = 1; j <= radialSegments; j ++ ) {
  20166. for ( let i = 1; i <= tubularSegments; i ++ ) {
  20167. // indices
  20168. const a = ( tubularSegments + 1 ) * j + i - 1;
  20169. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20170. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  20171. const d = ( tubularSegments + 1 ) * j + i;
  20172. // faces
  20173. indices.push( a, b, d );
  20174. indices.push( b, c, d );
  20175. }
  20176. }
  20177. // build geometry
  20178. this.setIndex( indices );
  20179. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20180. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20181. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20182. }
  20183. }
  20184. class TorusGeometry extends Geometry {
  20185. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  20186. super();
  20187. this.type = 'TorusGeometry';
  20188. this.parameters = {
  20189. radius: radius,
  20190. tube: tube,
  20191. radialSegments: radialSegments,
  20192. tubularSegments: tubularSegments,
  20193. arc: arc
  20194. };
  20195. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  20196. this.mergeVertices();
  20197. }
  20198. }
  20199. class TorusKnotBufferGeometry extends BufferGeometry {
  20200. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  20201. super();
  20202. this.type = 'TorusKnotBufferGeometry';
  20203. this.parameters = {
  20204. radius: radius,
  20205. tube: tube,
  20206. tubularSegments: tubularSegments,
  20207. radialSegments: radialSegments,
  20208. p: p,
  20209. q: q
  20210. };
  20211. tubularSegments = Math.floor( tubularSegments );
  20212. radialSegments = Math.floor( radialSegments );
  20213. // buffers
  20214. const indices = [];
  20215. const vertices = [];
  20216. const normals = [];
  20217. const uvs = [];
  20218. // helper variables
  20219. const vertex = new Vector3();
  20220. const normal = new Vector3();
  20221. const P1 = new Vector3();
  20222. const P2 = new Vector3();
  20223. const B = new Vector3();
  20224. const T = new Vector3();
  20225. const N = new Vector3();
  20226. // generate vertices, normals and uvs
  20227. for ( let i = 0; i <= tubularSegments; ++ i ) {
  20228. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  20229. const u = i / tubularSegments * p * Math.PI * 2;
  20230. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  20231. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20232. calculatePositionOnCurve( u, p, q, radius, P1 );
  20233. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  20234. // calculate orthonormal basis
  20235. T.subVectors( P2, P1 );
  20236. N.addVectors( P2, P1 );
  20237. B.crossVectors( T, N );
  20238. N.crossVectors( B, T );
  20239. // normalize B, N. T can be ignored, we don't use it
  20240. B.normalize();
  20241. N.normalize();
  20242. for ( let j = 0; j <= radialSegments; ++ j ) {
  20243. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20244. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20245. const v = j / radialSegments * Math.PI * 2;
  20246. const cx = - tube * Math.cos( v );
  20247. const cy = tube * Math.sin( v );
  20248. // now calculate the final vertex position.
  20249. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  20250. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  20251. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  20252. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  20253. vertices.push( vertex.x, vertex.y, vertex.z );
  20254. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  20255. normal.subVectors( vertex, P1 ).normalize();
  20256. normals.push( normal.x, normal.y, normal.z );
  20257. // uv
  20258. uvs.push( i / tubularSegments );
  20259. uvs.push( j / radialSegments );
  20260. }
  20261. }
  20262. // generate indices
  20263. for ( let j = 1; j <= tubularSegments; j ++ ) {
  20264. for ( let i = 1; i <= radialSegments; i ++ ) {
  20265. // indices
  20266. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20267. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  20268. const c = ( radialSegments + 1 ) * j + i;
  20269. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20270. // faces
  20271. indices.push( a, b, d );
  20272. indices.push( b, c, d );
  20273. }
  20274. }
  20275. // build geometry
  20276. this.setIndex( indices );
  20277. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20278. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20279. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20280. // this function calculates the current position on the torus curve
  20281. function calculatePositionOnCurve( u, p, q, radius, position ) {
  20282. const cu = Math.cos( u );
  20283. const su = Math.sin( u );
  20284. const quOverP = q / p * u;
  20285. const cs = Math.cos( quOverP );
  20286. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  20287. position.y = radius * ( 2 + cs ) * su * 0.5;
  20288. position.z = radius * Math.sin( quOverP ) * 0.5;
  20289. }
  20290. }
  20291. }
  20292. class TorusKnotGeometry extends Geometry {
  20293. constructor( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  20294. super();
  20295. this.type = 'TorusKnotGeometry';
  20296. this.parameters = {
  20297. radius: radius,
  20298. tube: tube,
  20299. tubularSegments: tubularSegments,
  20300. radialSegments: radialSegments,
  20301. p: p,
  20302. q: q
  20303. };
  20304. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  20305. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  20306. this.mergeVertices();
  20307. }
  20308. }
  20309. class TubeBufferGeometry extends BufferGeometry {
  20310. constructor( path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false ) {
  20311. super();
  20312. this.type = 'TubeBufferGeometry';
  20313. this.parameters = {
  20314. path: path,
  20315. tubularSegments: tubularSegments,
  20316. radius: radius,
  20317. radialSegments: radialSegments,
  20318. closed: closed
  20319. };
  20320. const frames = path.computeFrenetFrames( tubularSegments, closed );
  20321. // expose internals
  20322. this.tangents = frames.tangents;
  20323. this.normals = frames.normals;
  20324. this.binormals = frames.binormals;
  20325. // helper variables
  20326. const vertex = new Vector3();
  20327. const normal = new Vector3();
  20328. const uv = new Vector2$1();
  20329. let P = new Vector3();
  20330. // buffer
  20331. const vertices = [];
  20332. const normals = [];
  20333. const uvs = [];
  20334. const indices = [];
  20335. // create buffer data
  20336. generateBufferData();
  20337. // build geometry
  20338. this.setIndex( indices );
  20339. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20340. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20341. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20342. // functions
  20343. function generateBufferData() {
  20344. for ( let i = 0; i < tubularSegments; i ++ ) {
  20345. generateSegment( i );
  20346. }
  20347. // if the geometry is not closed, generate the last row of vertices and normals
  20348. // at the regular position on the given path
  20349. //
  20350. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  20351. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  20352. // uvs are generated in a separate function.
  20353. // this makes it easy compute correct values for closed geometries
  20354. generateUVs();
  20355. // finally create faces
  20356. generateIndices();
  20357. }
  20358. function generateSegment( i ) {
  20359. // we use getPointAt to sample evenly distributed points from the given path
  20360. P = path.getPointAt( i / tubularSegments, P );
  20361. // retrieve corresponding normal and binormal
  20362. const N = frames.normals[ i ];
  20363. const B = frames.binormals[ i ];
  20364. // generate normals and vertices for the current segment
  20365. for ( let j = 0; j <= radialSegments; j ++ ) {
  20366. const v = j / radialSegments * Math.PI * 2;
  20367. const sin = Math.sin( v );
  20368. const cos = - Math.cos( v );
  20369. // normal
  20370. normal.x = ( cos * N.x + sin * B.x );
  20371. normal.y = ( cos * N.y + sin * B.y );
  20372. normal.z = ( cos * N.z + sin * B.z );
  20373. normal.normalize();
  20374. normals.push( normal.x, normal.y, normal.z );
  20375. // vertex
  20376. vertex.x = P.x + radius * normal.x;
  20377. vertex.y = P.y + radius * normal.y;
  20378. vertex.z = P.z + radius * normal.z;
  20379. vertices.push( vertex.x, vertex.y, vertex.z );
  20380. }
  20381. }
  20382. function generateIndices() {
  20383. for ( let j = 1; j <= tubularSegments; j ++ ) {
  20384. for ( let i = 1; i <= radialSegments; i ++ ) {
  20385. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20386. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  20387. const c = ( radialSegments + 1 ) * j + i;
  20388. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20389. // faces
  20390. indices.push( a, b, d );
  20391. indices.push( b, c, d );
  20392. }
  20393. }
  20394. }
  20395. function generateUVs() {
  20396. for ( let i = 0; i <= tubularSegments; i ++ ) {
  20397. for ( let j = 0; j <= radialSegments; j ++ ) {
  20398. uv.x = i / tubularSegments;
  20399. uv.y = j / radialSegments;
  20400. uvs.push( uv.x, uv.y );
  20401. }
  20402. }
  20403. }
  20404. }
  20405. toJSON() {
  20406. const data = BufferGeometry.prototype.toJSON.call( this );
  20407. data.path = this.parameters.path.toJSON();
  20408. return data;
  20409. }
  20410. }
  20411. class TubeGeometry extends Geometry {
  20412. constructor( path, tubularSegments, radius, radialSegments, closed, taper ) {
  20413. super();
  20414. this.type = 'TubeGeometry';
  20415. this.parameters = {
  20416. path: path,
  20417. tubularSegments: tubularSegments,
  20418. radius: radius,
  20419. radialSegments: radialSegments,
  20420. closed: closed
  20421. };
  20422. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  20423. const bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  20424. // expose internals
  20425. this.tangents = bufferGeometry.tangents;
  20426. this.normals = bufferGeometry.normals;
  20427. this.binormals = bufferGeometry.binormals;
  20428. // create geometry
  20429. this.fromBufferGeometry( bufferGeometry );
  20430. this.mergeVertices();
  20431. }
  20432. }
  20433. class WireframeGeometry extends BufferGeometry {
  20434. constructor( geometry ) {
  20435. super();
  20436. this.type = 'WireframeGeometry';
  20437. // buffer
  20438. const vertices = [];
  20439. // helper variables
  20440. const edge = [ 0, 0 ], edges = {};
  20441. const keys = [ 'a', 'b', 'c' ];
  20442. // different logic for Geometry and BufferGeometry
  20443. if ( geometry && geometry.isGeometry ) {
  20444. // create a data structure that contains all edges without duplicates
  20445. const faces = geometry.faces;
  20446. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  20447. const face = faces[ i ];
  20448. for ( let j = 0; j < 3; j ++ ) {
  20449. const edge1 = face[ keys[ j ] ];
  20450. const edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  20451. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  20452. edge[ 1 ] = Math.max( edge1, edge2 );
  20453. const key = edge[ 0 ] + ',' + edge[ 1 ];
  20454. if ( edges[ key ] === undefined ) {
  20455. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  20456. }
  20457. }
  20458. }
  20459. // generate vertices
  20460. for ( const key in edges ) {
  20461. const e = edges[ key ];
  20462. let vertex = geometry.vertices[ e.index1 ];
  20463. vertices.push( vertex.x, vertex.y, vertex.z );
  20464. vertex = geometry.vertices[ e.index2 ];
  20465. vertices.push( vertex.x, vertex.y, vertex.z );
  20466. }
  20467. } else if ( geometry && geometry.isBufferGeometry ) {
  20468. const vertex = new Vector3();
  20469. if ( geometry.index !== null ) {
  20470. // indexed BufferGeometry
  20471. const position = geometry.attributes.position;
  20472. const indices = geometry.index;
  20473. let groups = geometry.groups;
  20474. if ( groups.length === 0 ) {
  20475. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  20476. }
  20477. // create a data structure that contains all eges without duplicates
  20478. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  20479. const group = groups[ o ];
  20480. const start = group.start;
  20481. const count = group.count;
  20482. for ( let i = start, l = ( start + count ); i < l; i += 3 ) {
  20483. for ( let j = 0; j < 3; j ++ ) {
  20484. const edge1 = indices.getX( i + j );
  20485. const edge2 = indices.getX( i + ( j + 1 ) % 3 );
  20486. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  20487. edge[ 1 ] = Math.max( edge1, edge2 );
  20488. const key = edge[ 0 ] + ',' + edge[ 1 ];
  20489. if ( edges[ key ] === undefined ) {
  20490. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  20491. }
  20492. }
  20493. }
  20494. }
  20495. // generate vertices
  20496. for ( const key in edges ) {
  20497. const e = edges[ key ];
  20498. vertex.fromBufferAttribute( position, e.index1 );
  20499. vertices.push( vertex.x, vertex.y, vertex.z );
  20500. vertex.fromBufferAttribute( position, e.index2 );
  20501. vertices.push( vertex.x, vertex.y, vertex.z );
  20502. }
  20503. } else {
  20504. // non-indexed BufferGeometry
  20505. const position = geometry.attributes.position;
  20506. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  20507. for ( let j = 0; j < 3; j ++ ) {
  20508. // three edges per triangle, an edge is represented as (index1, index2)
  20509. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  20510. const index1 = 3 * i + j;
  20511. vertex.fromBufferAttribute( position, index1 );
  20512. vertices.push( vertex.x, vertex.y, vertex.z );
  20513. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  20514. vertex.fromBufferAttribute( position, index2 );
  20515. vertices.push( vertex.x, vertex.y, vertex.z );
  20516. }
  20517. }
  20518. }
  20519. }
  20520. // build geometry
  20521. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20522. }
  20523. }
  20524. var Geometries = /*#__PURE__*/Object.freeze({
  20525. __proto__: null,
  20526. BoxGeometry: BoxGeometry,
  20527. BoxBufferGeometry: BoxBufferGeometry,
  20528. CircleGeometry: CircleGeometry,
  20529. CircleBufferGeometry: CircleBufferGeometry,
  20530. ConeGeometry: ConeGeometry,
  20531. ConeBufferGeometry: ConeBufferGeometry,
  20532. CylinderGeometry: CylinderGeometry,
  20533. CylinderBufferGeometry: CylinderBufferGeometry,
  20534. DodecahedronGeometry: DodecahedronGeometry,
  20535. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  20536. EdgesGeometry: EdgesGeometry,
  20537. ExtrudeGeometry: ExtrudeGeometry,
  20538. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  20539. IcosahedronGeometry: IcosahedronGeometry,
  20540. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  20541. LatheGeometry: LatheGeometry,
  20542. LatheBufferGeometry: LatheBufferGeometry,
  20543. OctahedronGeometry: OctahedronGeometry,
  20544. OctahedronBufferGeometry: OctahedronBufferGeometry,
  20545. ParametricGeometry: ParametricGeometry,
  20546. ParametricBufferGeometry: ParametricBufferGeometry,
  20547. PlaneGeometry: PlaneGeometry,
  20548. PlaneBufferGeometry: PlaneBufferGeometry,
  20549. PolyhedronGeometry: PolyhedronGeometry,
  20550. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  20551. RingGeometry: RingGeometry,
  20552. RingBufferGeometry: RingBufferGeometry,
  20553. ShapeGeometry: ShapeGeometry,
  20554. ShapeBufferGeometry: ShapeBufferGeometry,
  20555. SphereGeometry: SphereGeometry,
  20556. SphereBufferGeometry: SphereBufferGeometry,
  20557. TetrahedronGeometry: TetrahedronGeometry,
  20558. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  20559. TextGeometry: TextGeometry,
  20560. TextBufferGeometry: TextBufferGeometry,
  20561. TorusGeometry: TorusGeometry,
  20562. TorusBufferGeometry: TorusBufferGeometry,
  20563. TorusKnotGeometry: TorusKnotGeometry,
  20564. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  20565. TubeGeometry: TubeGeometry,
  20566. TubeBufferGeometry: TubeBufferGeometry,
  20567. WireframeGeometry: WireframeGeometry
  20568. });
  20569. /**
  20570. * parameters = {
  20571. * color: <THREE.Color>
  20572. * }
  20573. */
  20574. function ShadowMaterial( parameters ) {
  20575. Material.call( this );
  20576. this.type = 'ShadowMaterial';
  20577. this.color = new Color( 0x000000 );
  20578. this.transparent = true;
  20579. this.setValues( parameters );
  20580. }
  20581. ShadowMaterial.prototype = Object.create( Material.prototype );
  20582. ShadowMaterial.prototype.constructor = ShadowMaterial;
  20583. ShadowMaterial.prototype.isShadowMaterial = true;
  20584. ShadowMaterial.prototype.copy = function ( source ) {
  20585. Material.prototype.copy.call( this, source );
  20586. this.color.copy( source.color );
  20587. return this;
  20588. };
  20589. function RawShaderMaterial( parameters ) {
  20590. ShaderMaterial.call( this, parameters );
  20591. this.type = 'RawShaderMaterial';
  20592. }
  20593. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  20594. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  20595. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  20596. /**
  20597. * parameters = {
  20598. * color: <hex>,
  20599. * roughness: <float>,
  20600. * metalness: <float>,
  20601. * opacity: <float>,
  20602. *
  20603. * map: new THREE.Texture( <Image> ),
  20604. *
  20605. * lightMap: new THREE.Texture( <Image> ),
  20606. * lightMapIntensity: <float>
  20607. *
  20608. * aoMap: new THREE.Texture( <Image> ),
  20609. * aoMapIntensity: <float>
  20610. *
  20611. * emissive: <hex>,
  20612. * emissiveIntensity: <float>
  20613. * emissiveMap: new THREE.Texture( <Image> ),
  20614. *
  20615. * bumpMap: new THREE.Texture( <Image> ),
  20616. * bumpScale: <float>,
  20617. *
  20618. * normalMap: new THREE.Texture( <Image> ),
  20619. * normalMapType: THREE.TangentSpaceNormalMap,
  20620. * normalScale: <Vector2>,
  20621. *
  20622. * displacementMap: new THREE.Texture( <Image> ),
  20623. * displacementScale: <float>,
  20624. * displacementBias: <float>,
  20625. *
  20626. * roughnessMap: new THREE.Texture( <Image> ),
  20627. *
  20628. * metalnessMap: new THREE.Texture( <Image> ),
  20629. *
  20630. * alphaMap: new THREE.Texture( <Image> ),
  20631. *
  20632. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20633. * envMapIntensity: <float>
  20634. *
  20635. * refractionRatio: <float>,
  20636. *
  20637. * wireframe: <boolean>,
  20638. * wireframelineWidth: <float>,
  20639. *
  20640. * skinning: <bool>,
  20641. * morphTargets: <bool>,
  20642. * morphNormals: <bool>
  20643. * }
  20644. */
  20645. function MeshStandardMaterial( parameters ) {
  20646. Material.call( this );
  20647. this.defines = { 'STANDARD': '' };
  20648. this.type = 'MeshStandardMaterial';
  20649. this.color = new Color( 0xffffff ); // diffuse
  20650. this.roughness = 1.0;
  20651. this.metalness = 0.0;
  20652. this.map = null;
  20653. this.lightMap = null;
  20654. this.lightMapIntensity = 1.0;
  20655. this.aoMap = null;
  20656. this.aoMapIntensity = 1.0;
  20657. this.emissive = new Color( 0x000000 );
  20658. this.emissiveIntensity = 1.0;
  20659. this.emissiveMap = null;
  20660. this.bumpMap = null;
  20661. this.bumpScale = 1;
  20662. this.normalMap = null;
  20663. this.normalMapType = TangentSpaceNormalMap;
  20664. this.normalScale = new Vector2$1( 1, 1 );
  20665. this.displacementMap = null;
  20666. this.displacementScale = 1;
  20667. this.displacementBias = 0;
  20668. this.roughnessMap = null;
  20669. this.metalnessMap = null;
  20670. this.alphaMap = null;
  20671. this.envMap = null;
  20672. this.envMapIntensity = 1.0;
  20673. this.refractionRatio = 0.98;
  20674. this.wireframe = false;
  20675. this.wireframelineWidth = 1;
  20676. this.wireframeLinecap = 'round';
  20677. this.wireframeLinejoin = 'round';
  20678. this.skinning = false;
  20679. this.morphTargets = false;
  20680. this.morphNormals = false;
  20681. this.vertexTangents = false;
  20682. this.setValues( parameters );
  20683. }
  20684. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  20685. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  20686. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  20687. MeshStandardMaterial.prototype.copy = function ( source ) {
  20688. Material.prototype.copy.call( this, source );
  20689. this.defines = { 'STANDARD': '' };
  20690. this.color.copy( source.color );
  20691. this.roughness = source.roughness;
  20692. this.metalness = source.metalness;
  20693. this.map = source.map;
  20694. this.lightMap = source.lightMap;
  20695. this.lightMapIntensity = source.lightMapIntensity;
  20696. this.aoMap = source.aoMap;
  20697. this.aoMapIntensity = source.aoMapIntensity;
  20698. this.emissive.copy( source.emissive );
  20699. this.emissiveMap = source.emissiveMap;
  20700. this.emissiveIntensity = source.emissiveIntensity;
  20701. this.bumpMap = source.bumpMap;
  20702. this.bumpScale = source.bumpScale;
  20703. this.normalMap = source.normalMap;
  20704. this.normalMapType = source.normalMapType;
  20705. this.normalScale.copy( source.normalScale );
  20706. this.displacementMap = source.displacementMap;
  20707. this.displacementScale = source.displacementScale;
  20708. this.displacementBias = source.displacementBias;
  20709. this.roughnessMap = source.roughnessMap;
  20710. this.metalnessMap = source.metalnessMap;
  20711. this.alphaMap = source.alphaMap;
  20712. this.envMap = source.envMap;
  20713. this.envMapIntensity = source.envMapIntensity;
  20714. this.refractionRatio = source.refractionRatio;
  20715. this.wireframe = source.wireframe;
  20716. this.wireframelineWidth = source.wireframelineWidth;
  20717. this.wireframeLinecap = source.wireframeLinecap;
  20718. this.wireframeLinejoin = source.wireframeLinejoin;
  20719. this.skinning = source.skinning;
  20720. this.morphTargets = source.morphTargets;
  20721. this.morphNormals = source.morphNormals;
  20722. this.vertexTangents = source.vertexTangents;
  20723. return this;
  20724. };
  20725. /**
  20726. * parameters = {
  20727. * clearcoat: <float>,
  20728. * clearcoatMap: new THREE.Texture( <Image> ),
  20729. * clearcoatRoughness: <float>,
  20730. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  20731. * clearcoatNormalScale: <Vector2>,
  20732. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  20733. *
  20734. * reflectivity: <float>,
  20735. * ior: <float>,
  20736. *
  20737. * sheen: <Color>,
  20738. *
  20739. * transmission: <float>,
  20740. * transmissionMap: new THREE.Texture( <Image> )
  20741. * }
  20742. */
  20743. function MeshPhysicalMaterial( parameters ) {
  20744. MeshStandardMaterial.call( this );
  20745. this.defines = {
  20746. 'STANDARD': '',
  20747. 'PHYSICAL': ''
  20748. };
  20749. this.type = 'MeshPhysicalMaterial';
  20750. this.clearcoat = 0.0;
  20751. this.clearcoatMap = null;
  20752. this.clearcoatRoughness = 0.0;
  20753. this.clearcoatRoughnessMap = null;
  20754. this.clearcoatNormalScale = new Vector2$1( 1, 1 );
  20755. this.clearcoatNormalMap = null;
  20756. this.reflectivity = 0.5; // maps to F0 = 0.04
  20757. Object.defineProperty( this, 'ior', {
  20758. get: function () {
  20759. return ( 1 + 0.4 * this.reflectivity ) / ( 1 - 0.4 * this.reflectivity );
  20760. },
  20761. set: function ( ior ) {
  20762. this.reflectivity = MathUtils.clamp( 2.5 * ( ior - 1 ) / ( ior + 1 ), 0, 1 );
  20763. }
  20764. } );
  20765. this.sheen = null; // null will disable sheen bsdf
  20766. this.transmission = 0.0;
  20767. this.transmissionMap = null;
  20768. this.setValues( parameters );
  20769. }
  20770. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  20771. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  20772. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  20773. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  20774. MeshStandardMaterial.prototype.copy.call( this, source );
  20775. this.defines = {
  20776. 'STANDARD': '',
  20777. 'PHYSICAL': ''
  20778. };
  20779. this.clearcoat = source.clearcoat;
  20780. this.clearcoatMap = source.clearcoatMap;
  20781. this.clearcoatRoughness = source.clearcoatRoughness;
  20782. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  20783. this.clearcoatNormalMap = source.clearcoatNormalMap;
  20784. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  20785. this.reflectivity = source.reflectivity;
  20786. if ( source.sheen ) {
  20787. this.sheen = ( this.sheen || new Color() ).copy( source.sheen );
  20788. } else {
  20789. this.sheen = null;
  20790. }
  20791. this.transmission = source.transmission;
  20792. this.transmissionMap = source.transmissionMap;
  20793. return this;
  20794. };
  20795. /**
  20796. * parameters = {
  20797. * color: <hex>,
  20798. * specular: <hex>,
  20799. * shininess: <float>,
  20800. * opacity: <float>,
  20801. *
  20802. * map: new THREE.Texture( <Image> ),
  20803. *
  20804. * lightMap: new THREE.Texture( <Image> ),
  20805. * lightMapIntensity: <float>
  20806. *
  20807. * aoMap: new THREE.Texture( <Image> ),
  20808. * aoMapIntensity: <float>
  20809. *
  20810. * emissive: <hex>,
  20811. * emissiveIntensity: <float>
  20812. * emissiveMap: new THREE.Texture( <Image> ),
  20813. *
  20814. * bumpMap: new THREE.Texture( <Image> ),
  20815. * bumpScale: <float>,
  20816. *
  20817. * normalMap: new THREE.Texture( <Image> ),
  20818. * normalMapType: THREE.TangentSpaceNormalMap,
  20819. * normalScale: <Vector2>,
  20820. *
  20821. * displacementMap: new THREE.Texture( <Image> ),
  20822. * displacementScale: <float>,
  20823. * displacementBias: <float>,
  20824. *
  20825. * specularMap: new THREE.Texture( <Image> ),
  20826. *
  20827. * alphaMap: new THREE.Texture( <Image> ),
  20828. *
  20829. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20830. * combine: THREE.MultiplyOperation,
  20831. * reflectivity: <float>,
  20832. * refractionRatio: <float>,
  20833. *
  20834. * wireframe: <boolean>,
  20835. * wireframelineWidth: <float>,
  20836. *
  20837. * skinning: <bool>,
  20838. * morphTargets: <bool>,
  20839. * morphNormals: <bool>
  20840. * }
  20841. */
  20842. function MeshPhongMaterial( parameters ) {
  20843. Material.call( this );
  20844. this.type = 'MeshPhongMaterial';
  20845. this.color = new Color( 0xffffff ); // diffuse
  20846. this.specular = new Color( 0x111111 );
  20847. this.shininess = 30;
  20848. this.map = null;
  20849. this.lightMap = null;
  20850. this.lightMapIntensity = 1.0;
  20851. this.aoMap = null;
  20852. this.aoMapIntensity = 1.0;
  20853. this.emissive = new Color( 0x000000 );
  20854. this.emissiveIntensity = 1.0;
  20855. this.emissiveMap = null;
  20856. this.bumpMap = null;
  20857. this.bumpScale = 1;
  20858. this.normalMap = null;
  20859. this.normalMapType = TangentSpaceNormalMap;
  20860. this.normalScale = new Vector2$1( 1, 1 );
  20861. this.displacementMap = null;
  20862. this.displacementScale = 1;
  20863. this.displacementBias = 0;
  20864. this.specularMap = null;
  20865. this.alphaMap = null;
  20866. this.envMap = null;
  20867. this.combine = MultiplyOperation;
  20868. this.reflectivity = 1;
  20869. this.refractionRatio = 0.98;
  20870. this.wireframe = false;
  20871. this.wireframelineWidth = 1;
  20872. this.wireframeLinecap = 'round';
  20873. this.wireframeLinejoin = 'round';
  20874. this.skinning = false;
  20875. this.morphTargets = false;
  20876. this.morphNormals = false;
  20877. this.setValues( parameters );
  20878. }
  20879. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  20880. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  20881. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  20882. MeshPhongMaterial.prototype.copy = function ( source ) {
  20883. Material.prototype.copy.call( this, source );
  20884. this.color.copy( source.color );
  20885. this.specular.copy( source.specular );
  20886. this.shininess = source.shininess;
  20887. this.map = source.map;
  20888. this.lightMap = source.lightMap;
  20889. this.lightMapIntensity = source.lightMapIntensity;
  20890. this.aoMap = source.aoMap;
  20891. this.aoMapIntensity = source.aoMapIntensity;
  20892. this.emissive.copy( source.emissive );
  20893. this.emissiveMap = source.emissiveMap;
  20894. this.emissiveIntensity = source.emissiveIntensity;
  20895. this.bumpMap = source.bumpMap;
  20896. this.bumpScale = source.bumpScale;
  20897. this.normalMap = source.normalMap;
  20898. this.normalMapType = source.normalMapType;
  20899. this.normalScale.copy( source.normalScale );
  20900. this.displacementMap = source.displacementMap;
  20901. this.displacementScale = source.displacementScale;
  20902. this.displacementBias = source.displacementBias;
  20903. this.specularMap = source.specularMap;
  20904. this.alphaMap = source.alphaMap;
  20905. this.envMap = source.envMap;
  20906. this.combine = source.combine;
  20907. this.reflectivity = source.reflectivity;
  20908. this.refractionRatio = source.refractionRatio;
  20909. this.wireframe = source.wireframe;
  20910. this.wireframelineWidth = source.wireframelineWidth;
  20911. this.wireframeLinecap = source.wireframeLinecap;
  20912. this.wireframeLinejoin = source.wireframeLinejoin;
  20913. this.skinning = source.skinning;
  20914. this.morphTargets = source.morphTargets;
  20915. this.morphNormals = source.morphNormals;
  20916. return this;
  20917. };
  20918. /**
  20919. * parameters = {
  20920. * color: <hex>,
  20921. *
  20922. * map: new THREE.Texture( <Image> ),
  20923. * gradientMap: new THREE.Texture( <Image> ),
  20924. *
  20925. * lightMap: new THREE.Texture( <Image> ),
  20926. * lightMapIntensity: <float>
  20927. *
  20928. * aoMap: new THREE.Texture( <Image> ),
  20929. * aoMapIntensity: <float>
  20930. *
  20931. * emissive: <hex>,
  20932. * emissiveIntensity: <float>
  20933. * emissiveMap: new THREE.Texture( <Image> ),
  20934. *
  20935. * bumpMap: new THREE.Texture( <Image> ),
  20936. * bumpScale: <float>,
  20937. *
  20938. * normalMap: new THREE.Texture( <Image> ),
  20939. * normalMapType: THREE.TangentSpaceNormalMap,
  20940. * normalScale: <Vector2>,
  20941. *
  20942. * displacementMap: new THREE.Texture( <Image> ),
  20943. * displacementScale: <float>,
  20944. * displacementBias: <float>,
  20945. *
  20946. * alphaMap: new THREE.Texture( <Image> ),
  20947. *
  20948. * wireframe: <boolean>,
  20949. * wireframelineWidth: <float>,
  20950. *
  20951. * skinning: <bool>,
  20952. * morphTargets: <bool>,
  20953. * morphNormals: <bool>
  20954. * }
  20955. */
  20956. function MeshToonMaterial( parameters ) {
  20957. Material.call( this );
  20958. this.defines = { 'TOON': '' };
  20959. this.type = 'MeshToonMaterial';
  20960. this.color = new Color( 0xffffff );
  20961. this.map = null;
  20962. this.gradientMap = null;
  20963. this.lightMap = null;
  20964. this.lightMapIntensity = 1.0;
  20965. this.aoMap = null;
  20966. this.aoMapIntensity = 1.0;
  20967. this.emissive = new Color( 0x000000 );
  20968. this.emissiveIntensity = 1.0;
  20969. this.emissiveMap = null;
  20970. this.bumpMap = null;
  20971. this.bumpScale = 1;
  20972. this.normalMap = null;
  20973. this.normalMapType = TangentSpaceNormalMap;
  20974. this.normalScale = new Vector2$1( 1, 1 );
  20975. this.displacementMap = null;
  20976. this.displacementScale = 1;
  20977. this.displacementBias = 0;
  20978. this.alphaMap = null;
  20979. this.wireframe = false;
  20980. this.wireframelineWidth = 1;
  20981. this.wireframeLinecap = 'round';
  20982. this.wireframeLinejoin = 'round';
  20983. this.skinning = false;
  20984. this.morphTargets = false;
  20985. this.morphNormals = false;
  20986. this.setValues( parameters );
  20987. }
  20988. MeshToonMaterial.prototype = Object.create( Material.prototype );
  20989. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  20990. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20991. MeshToonMaterial.prototype.copy = function ( source ) {
  20992. Material.prototype.copy.call( this, source );
  20993. this.color.copy( source.color );
  20994. this.map = source.map;
  20995. this.gradientMap = source.gradientMap;
  20996. this.lightMap = source.lightMap;
  20997. this.lightMapIntensity = source.lightMapIntensity;
  20998. this.aoMap = source.aoMap;
  20999. this.aoMapIntensity = source.aoMapIntensity;
  21000. this.emissive.copy( source.emissive );
  21001. this.emissiveMap = source.emissiveMap;
  21002. this.emissiveIntensity = source.emissiveIntensity;
  21003. this.bumpMap = source.bumpMap;
  21004. this.bumpScale = source.bumpScale;
  21005. this.normalMap = source.normalMap;
  21006. this.normalMapType = source.normalMapType;
  21007. this.normalScale.copy( source.normalScale );
  21008. this.displacementMap = source.displacementMap;
  21009. this.displacementScale = source.displacementScale;
  21010. this.displacementBias = source.displacementBias;
  21011. this.alphaMap = source.alphaMap;
  21012. this.wireframe = source.wireframe;
  21013. this.wireframelineWidth = source.wireframelineWidth;
  21014. this.wireframeLinecap = source.wireframeLinecap;
  21015. this.wireframeLinejoin = source.wireframeLinejoin;
  21016. this.skinning = source.skinning;
  21017. this.morphTargets = source.morphTargets;
  21018. this.morphNormals = source.morphNormals;
  21019. return this;
  21020. };
  21021. /**
  21022. * parameters = {
  21023. * opacity: <float>,
  21024. *
  21025. * bumpMap: new THREE.Texture( <Image> ),
  21026. * bumpScale: <float>,
  21027. *
  21028. * normalMap: new THREE.Texture( <Image> ),
  21029. * normalMapType: THREE.TangentSpaceNormalMap,
  21030. * normalScale: <Vector2>,
  21031. *
  21032. * displacementMap: new THREE.Texture( <Image> ),
  21033. * displacementScale: <float>,
  21034. * displacementBias: <float>,
  21035. *
  21036. * wireframe: <boolean>,
  21037. * wireframelineWidth: <float>
  21038. *
  21039. * skinning: <bool>,
  21040. * morphTargets: <bool>,
  21041. * morphNormals: <bool>
  21042. * }
  21043. */
  21044. function MeshNormalMaterial( parameters ) {
  21045. Material.call( this );
  21046. this.type = 'MeshNormalMaterial';
  21047. this.bumpMap = null;
  21048. this.bumpScale = 1;
  21049. this.normalMap = null;
  21050. this.normalMapType = TangentSpaceNormalMap;
  21051. this.normalScale = new Vector2$1( 1, 1 );
  21052. this.displacementMap = null;
  21053. this.displacementScale = 1;
  21054. this.displacementBias = 0;
  21055. this.wireframe = false;
  21056. this.wireframelineWidth = 1;
  21057. this.fog = false;
  21058. this.skinning = false;
  21059. this.morphTargets = false;
  21060. this.morphNormals = false;
  21061. this.setValues( parameters );
  21062. }
  21063. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  21064. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  21065. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  21066. MeshNormalMaterial.prototype.copy = function ( source ) {
  21067. Material.prototype.copy.call( this, source );
  21068. this.bumpMap = source.bumpMap;
  21069. this.bumpScale = source.bumpScale;
  21070. this.normalMap = source.normalMap;
  21071. this.normalMapType = source.normalMapType;
  21072. this.normalScale.copy( source.normalScale );
  21073. this.displacementMap = source.displacementMap;
  21074. this.displacementScale = source.displacementScale;
  21075. this.displacementBias = source.displacementBias;
  21076. this.wireframe = source.wireframe;
  21077. this.wireframelineWidth = source.wireframelineWidth;
  21078. this.skinning = source.skinning;
  21079. this.morphTargets = source.morphTargets;
  21080. this.morphNormals = source.morphNormals;
  21081. return this;
  21082. };
  21083. /**
  21084. * parameters = {
  21085. * color: <hex>,
  21086. * opacity: <float>,
  21087. *
  21088. * map: new THREE.Texture( <Image> ),
  21089. *
  21090. * lightMap: new THREE.Texture( <Image> ),
  21091. * lightMapIntensity: <float>
  21092. *
  21093. * aoMap: new THREE.Texture( <Image> ),
  21094. * aoMapIntensity: <float>
  21095. *
  21096. * emissive: <hex>,
  21097. * emissiveIntensity: <float>
  21098. * emissiveMap: new THREE.Texture( <Image> ),
  21099. *
  21100. * specularMap: new THREE.Texture( <Image> ),
  21101. *
  21102. * alphaMap: new THREE.Texture( <Image> ),
  21103. *
  21104. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21105. * combine: THREE.Multiply,
  21106. * reflectivity: <float>,
  21107. * refractionRatio: <float>,
  21108. *
  21109. * wireframe: <boolean>,
  21110. * wireframelineWidth: <float>,
  21111. *
  21112. * skinning: <bool>,
  21113. * morphTargets: <bool>,
  21114. * morphNormals: <bool>
  21115. * }
  21116. */
  21117. function MeshLambertMaterial( parameters ) {
  21118. Material.call( this );
  21119. this.type = 'MeshLambertMaterial';
  21120. this.color = new Color( 0xffffff ); // diffuse
  21121. this.map = null;
  21122. this.lightMap = null;
  21123. this.lightMapIntensity = 1.0;
  21124. this.aoMap = null;
  21125. this.aoMapIntensity = 1.0;
  21126. this.emissive = new Color( 0x000000 );
  21127. this.emissiveIntensity = 1.0;
  21128. this.emissiveMap = null;
  21129. this.specularMap = null;
  21130. this.alphaMap = null;
  21131. this.envMap = null;
  21132. this.combine = MultiplyOperation;
  21133. this.reflectivity = 1;
  21134. this.refractionRatio = 0.98;
  21135. this.wireframe = false;
  21136. this.wireframelineWidth = 1;
  21137. this.wireframeLinecap = 'round';
  21138. this.wireframeLinejoin = 'round';
  21139. this.skinning = false;
  21140. this.morphTargets = false;
  21141. this.morphNormals = false;
  21142. this.setValues( parameters );
  21143. }
  21144. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  21145. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  21146. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21147. MeshLambertMaterial.prototype.copy = function ( source ) {
  21148. Material.prototype.copy.call( this, source );
  21149. this.color.copy( source.color );
  21150. this.map = source.map;
  21151. this.lightMap = source.lightMap;
  21152. this.lightMapIntensity = source.lightMapIntensity;
  21153. this.aoMap = source.aoMap;
  21154. this.aoMapIntensity = source.aoMapIntensity;
  21155. this.emissive.copy( source.emissive );
  21156. this.emissiveMap = source.emissiveMap;
  21157. this.emissiveIntensity = source.emissiveIntensity;
  21158. this.specularMap = source.specularMap;
  21159. this.alphaMap = source.alphaMap;
  21160. this.envMap = source.envMap;
  21161. this.combine = source.combine;
  21162. this.reflectivity = source.reflectivity;
  21163. this.refractionRatio = source.refractionRatio;
  21164. this.wireframe = source.wireframe;
  21165. this.wireframelineWidth = source.wireframelineWidth;
  21166. this.wireframeLinecap = source.wireframeLinecap;
  21167. this.wireframeLinejoin = source.wireframeLinejoin;
  21168. this.skinning = source.skinning;
  21169. this.morphTargets = source.morphTargets;
  21170. this.morphNormals = source.morphNormals;
  21171. return this;
  21172. };
  21173. /**
  21174. * parameters = {
  21175. * color: <hex>,
  21176. * opacity: <float>,
  21177. *
  21178. * matcap: new THREE.Texture( <Image> ),
  21179. *
  21180. * map: new THREE.Texture( <Image> ),
  21181. *
  21182. * bumpMap: new THREE.Texture( <Image> ),
  21183. * bumpScale: <float>,
  21184. *
  21185. * normalMap: new THREE.Texture( <Image> ),
  21186. * normalMapType: THREE.TangentSpaceNormalMap,
  21187. * normalScale: <Vector2>,
  21188. *
  21189. * displacementMap: new THREE.Texture( <Image> ),
  21190. * displacementScale: <float>,
  21191. * displacementBias: <float>,
  21192. *
  21193. * alphaMap: new THREE.Texture( <Image> ),
  21194. *
  21195. * skinning: <bool>,
  21196. * morphTargets: <bool>,
  21197. * morphNormals: <bool>
  21198. * }
  21199. */
  21200. function MeshMatcapMaterial( parameters ) {
  21201. Material.call( this );
  21202. this.defines = { 'MATCAP': '' };
  21203. this.type = 'MeshMatcapMaterial';
  21204. this.color = new Color( 0xffffff ); // diffuse
  21205. this.matcap = null;
  21206. this.map = null;
  21207. this.bumpMap = null;
  21208. this.bumpScale = 1;
  21209. this.normalMap = null;
  21210. this.normalMapType = TangentSpaceNormalMap;
  21211. this.normalScale = new Vector2$1( 1, 1 );
  21212. this.displacementMap = null;
  21213. this.displacementScale = 1;
  21214. this.displacementBias = 0;
  21215. this.alphaMap = null;
  21216. this.skinning = false;
  21217. this.morphTargets = false;
  21218. this.morphNormals = false;
  21219. this.setValues( parameters );
  21220. }
  21221. MeshMatcapMaterial.prototype = Object.create( Material.prototype );
  21222. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  21223. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  21224. MeshMatcapMaterial.prototype.copy = function ( source ) {
  21225. Material.prototype.copy.call( this, source );
  21226. this.defines = { 'MATCAP': '' };
  21227. this.color.copy( source.color );
  21228. this.matcap = source.matcap;
  21229. this.map = source.map;
  21230. this.bumpMap = source.bumpMap;
  21231. this.bumpScale = source.bumpScale;
  21232. this.normalMap = source.normalMap;
  21233. this.normalMapType = source.normalMapType;
  21234. this.normalScale.copy( source.normalScale );
  21235. this.displacementMap = source.displacementMap;
  21236. this.displacementScale = source.displacementScale;
  21237. this.displacementBias = source.displacementBias;
  21238. this.alphaMap = source.alphaMap;
  21239. this.skinning = source.skinning;
  21240. this.morphTargets = source.morphTargets;
  21241. this.morphNormals = source.morphNormals;
  21242. return this;
  21243. };
  21244. /**
  21245. * parameters = {
  21246. * color: <hex>,
  21247. * opacity: <float>,
  21248. *
  21249. * lineWidth: <float>,
  21250. *
  21251. * scale: <float>,
  21252. * dashSize: <float>,
  21253. * gapSize: <float>
  21254. * }
  21255. */
  21256. function LineDashedMaterial( parameters ) {
  21257. LineBasicMaterial.call( this );
  21258. this.type = 'LineDashedMaterial';
  21259. this.scale = 1;
  21260. this.dashSize = 3;
  21261. this.gapSize = 1;
  21262. this.setValues( parameters );
  21263. }
  21264. LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
  21265. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  21266. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21267. LineDashedMaterial.prototype.copy = function ( source ) {
  21268. LineBasicMaterial.prototype.copy.call( this, source );
  21269. this.scale = source.scale;
  21270. this.dashSize = source.dashSize;
  21271. this.gapSize = source.gapSize;
  21272. return this;
  21273. };
  21274. var Materials = /*#__PURE__*/Object.freeze({
  21275. __proto__: null,
  21276. ShadowMaterial: ShadowMaterial,
  21277. SpriteMaterial: SpriteMaterial,
  21278. RawShaderMaterial: RawShaderMaterial,
  21279. ShaderMaterial: ShaderMaterial,
  21280. PointsMaterial: PointsMaterial,
  21281. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21282. MeshStandardMaterial: MeshStandardMaterial,
  21283. MeshPhongMaterial: MeshPhongMaterial,
  21284. MeshToonMaterial: MeshToonMaterial,
  21285. MeshNormalMaterial: MeshNormalMaterial,
  21286. MeshLambertMaterial: MeshLambertMaterial,
  21287. MeshDepthMaterial: MeshDepthMaterial,
  21288. MeshDistanceMaterial: MeshDistanceMaterial,
  21289. MeshBasicMaterial: MeshBasicMaterial,
  21290. MeshMatcapMaterial: MeshMatcapMaterial,
  21291. LineDashedMaterial: LineDashedMaterial,
  21292. LineBasicMaterial: LineBasicMaterial,
  21293. Material: Material
  21294. });
  21295. const AnimationUtils = {
  21296. // same as Array.prototype.slice, but also works on typed arrays
  21297. arraySlice: function ( array, from, to ) {
  21298. if ( AnimationUtils.isTypedArray( array ) ) {
  21299. // in ios9 array.subarray(from, undefined) will return empty array
  21300. // but array.subarray(from) or array.subarray(from, len) is correct
  21301. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  21302. }
  21303. return array.slice( from, to );
  21304. },
  21305. // converts an array to a specific type
  21306. convertArray: function ( array, type, forceClone ) {
  21307. if ( ! array || // let 'undefined' and 'null' pass
  21308. ! forceClone && array.constructor === type ) return array;
  21309. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  21310. return new type( array ); // create typed array
  21311. }
  21312. return Array.prototype.slice.call( array ); // create Array
  21313. },
  21314. isTypedArray: function ( object ) {
  21315. return ArrayBuffer.isView( object ) &&
  21316. ! ( object instanceof DataView );
  21317. },
  21318. // returns an array by which times and values can be sorted
  21319. getKeyframeOrder: function ( times ) {
  21320. function compareTime( i, j ) {
  21321. return times[ i ] - times[ j ];
  21322. }
  21323. const n = times.length;
  21324. const result = new Array( n );
  21325. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  21326. result.sort( compareTime );
  21327. return result;
  21328. },
  21329. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21330. sortedArray: function ( values, stride, order ) {
  21331. const nValues = values.length;
  21332. const result = new values.constructor( nValues );
  21333. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  21334. const srcOffset = order[ i ] * stride;
  21335. for ( let j = 0; j !== stride; ++ j ) {
  21336. result[ dstOffset ++ ] = values[ srcOffset + j ];
  21337. }
  21338. }
  21339. return result;
  21340. },
  21341. // function for parsing AOS keyframe formats
  21342. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  21343. let i = 1, key = jsonKeys[ 0 ];
  21344. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  21345. key = jsonKeys[ i ++ ];
  21346. }
  21347. if ( key === undefined ) return; // no data
  21348. let value = key[ valuePropertyName ];
  21349. if ( value === undefined ) return; // no data
  21350. if ( Array.isArray( value ) ) {
  21351. do {
  21352. value = key[ valuePropertyName ];
  21353. if ( value !== undefined ) {
  21354. times.push( key.time );
  21355. values.push.apply( values, value ); // push all elements
  21356. }
  21357. key = jsonKeys[ i ++ ];
  21358. } while ( key !== undefined );
  21359. } else if ( value.toArray !== undefined ) {
  21360. // ...assume THREE.Math-ish
  21361. do {
  21362. value = key[ valuePropertyName ];
  21363. if ( value !== undefined ) {
  21364. times.push( key.time );
  21365. value.toArray( values, values.length );
  21366. }
  21367. key = jsonKeys[ i ++ ];
  21368. } while ( key !== undefined );
  21369. } else {
  21370. // otherwise push as-is
  21371. do {
  21372. value = key[ valuePropertyName ];
  21373. if ( value !== undefined ) {
  21374. times.push( key.time );
  21375. values.push( value );
  21376. }
  21377. key = jsonKeys[ i ++ ];
  21378. } while ( key !== undefined );
  21379. }
  21380. },
  21381. subclip: function ( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  21382. const clip = sourceClip.clone();
  21383. clip.name = name;
  21384. const tracks = [];
  21385. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21386. const track = clip.tracks[ i ];
  21387. const valueSize = track.getValueSize();
  21388. const times = [];
  21389. const values = [];
  21390. for ( let j = 0; j < track.times.length; ++ j ) {
  21391. const frame = track.times[ j ] * fps;
  21392. if ( frame < startFrame || frame >= endFrame ) continue;
  21393. times.push( track.times[ j ] );
  21394. for ( let k = 0; k < valueSize; ++ k ) {
  21395. values.push( track.values[ j * valueSize + k ] );
  21396. }
  21397. }
  21398. if ( times.length === 0 ) continue;
  21399. track.times = AnimationUtils.convertArray( times, track.times.constructor );
  21400. track.values = AnimationUtils.convertArray( values, track.values.constructor );
  21401. tracks.push( track );
  21402. }
  21403. clip.tracks = tracks;
  21404. // find minimum .times value across all tracks in the trimmed clip
  21405. let minStartTime = Infinity;
  21406. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21407. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  21408. minStartTime = clip.tracks[ i ].times[ 0 ];
  21409. }
  21410. }
  21411. // shift all tracks such that clip begins at t=0
  21412. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  21413. clip.tracks[ i ].shift( - 1 * minStartTime );
  21414. }
  21415. clip.resetDuration();
  21416. return clip;
  21417. },
  21418. makeClipAdditive: function ( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  21419. if ( fps <= 0 ) fps = 30;
  21420. const numTracks = referenceClip.tracks.length;
  21421. const referenceTime = referenceFrame / fps;
  21422. // Make each track's values relative to the values at the reference frame
  21423. for ( let i = 0; i < numTracks; ++ i ) {
  21424. const referenceTrack = referenceClip.tracks[ i ];
  21425. const referenceTrackType = referenceTrack.ValueTypeName;
  21426. // Skip this track if it's non-numeric
  21427. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  21428. // Find the track in the target clip whose name and type matches the reference track
  21429. const targetTrack = targetClip.tracks.find( function ( track ) {
  21430. return track.name === referenceTrack.name
  21431. && track.ValueTypeName === referenceTrackType;
  21432. } );
  21433. if ( targetTrack === undefined ) continue;
  21434. let referenceOffset = 0;
  21435. const referenceValueSize = referenceTrack.getValueSize();
  21436. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  21437. referenceOffset = referenceValueSize / 3;
  21438. }
  21439. let targetOffset = 0;
  21440. const targetValueSize = targetTrack.getValueSize();
  21441. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  21442. targetOffset = targetValueSize / 3;
  21443. }
  21444. const lastIndex = referenceTrack.times.length - 1;
  21445. let referenceValue;
  21446. // Find the value to subtract out of the track
  21447. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  21448. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  21449. const startIndex = referenceOffset;
  21450. const endIndex = referenceValueSize - referenceOffset;
  21451. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  21452. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  21453. // Reference frame is after the last keyframe, so just use the last keyframe
  21454. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  21455. const endIndex = startIndex + referenceValueSize - referenceOffset;
  21456. referenceValue = AnimationUtils.arraySlice( referenceTrack.values, startIndex, endIndex );
  21457. } else {
  21458. // Interpolate to the reference value
  21459. const interpolant = referenceTrack.createInterpolant();
  21460. const startIndex = referenceOffset;
  21461. const endIndex = referenceValueSize - referenceOffset;
  21462. interpolant.evaluate( referenceTime );
  21463. referenceValue = AnimationUtils.arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  21464. }
  21465. // Conjugate the quaternion
  21466. if ( referenceTrackType === 'quaternion' ) {
  21467. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  21468. referenceQuat.toArray( referenceValue );
  21469. }
  21470. // Subtract the reference value from all of the track values
  21471. const numTimes = targetTrack.times.length;
  21472. for ( let j = 0; j < numTimes; ++ j ) {
  21473. const valueStart = j * targetValueSize + targetOffset;
  21474. if ( referenceTrackType === 'quaternion' ) {
  21475. // Multiply the conjugate for quaternion track types
  21476. Quaternion.multiplyQuaternionsFlat(
  21477. targetTrack.values,
  21478. valueStart,
  21479. referenceValue,
  21480. 0,
  21481. targetTrack.values,
  21482. valueStart
  21483. );
  21484. } else {
  21485. const valueEnd = targetValueSize - targetOffset * 2;
  21486. // Subtract each value for all other numeric track types
  21487. for ( let k = 0; k < valueEnd; ++ k ) {
  21488. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  21489. }
  21490. }
  21491. }
  21492. }
  21493. targetClip.blendMode = AdditiveAnimationBlendMode;
  21494. return targetClip;
  21495. }
  21496. };
  21497. /**
  21498. * Abstract base class of interpolants over parametric samples.
  21499. *
  21500. * The parameter domain is one dimensional, typically the time or a path
  21501. * along a curve defined by the data.
  21502. *
  21503. * The sample values can have any dimensionality and derived classes may
  21504. * apply special interpretations to the data.
  21505. *
  21506. * This class provides the interval seek in a Template Method, deferring
  21507. * the actual interpolation to derived classes.
  21508. *
  21509. * Time complexity is O(1) for linear access crossing at most two points
  21510. * and O(log N) for random access, where N is the number of positions.
  21511. *
  21512. * References:
  21513. *
  21514. * http://www.oodesign.com/template-method-pattern.html
  21515. *
  21516. */
  21517. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21518. this.parameterPositions = parameterPositions;
  21519. this._cachedIndex = 0;
  21520. this.resultBuffer = resultBuffer !== undefined ?
  21521. resultBuffer : new sampleValues.constructor( sampleSize );
  21522. this.sampleValues = sampleValues;
  21523. this.valueSize = sampleSize;
  21524. }
  21525. Object.assign( Interpolant.prototype, {
  21526. evaluate: function ( t ) {
  21527. const pp = this.parameterPositions;
  21528. let i1 = this._cachedIndex,
  21529. t1 = pp[ i1 ],
  21530. t0 = pp[ i1 - 1 ];
  21531. validate_interval: {
  21532. seek: {
  21533. let right;
  21534. linear_scan: {
  21535. //- See http://jsperf.com/comparison-to-undefined/3
  21536. //- slower code:
  21537. //-
  21538. //- if ( t >= t1 || t1 === undefined ) {
  21539. forward_scan: if ( ! ( t < t1 ) ) {
  21540. for ( let giveUpAt = i1 + 2; ; ) {
  21541. if ( t1 === undefined ) {
  21542. if ( t < t0 ) break forward_scan;
  21543. // after end
  21544. i1 = pp.length;
  21545. this._cachedIndex = i1;
  21546. return this.afterEnd_( i1 - 1, t, t0 );
  21547. }
  21548. if ( i1 === giveUpAt ) break; // this loop
  21549. t0 = t1;
  21550. t1 = pp[ ++ i1 ];
  21551. if ( t < t1 ) {
  21552. // we have arrived at the sought interval
  21553. break seek;
  21554. }
  21555. }
  21556. // prepare binary search on the right side of the index
  21557. right = pp.length;
  21558. break linear_scan;
  21559. }
  21560. //- slower code:
  21561. //- if ( t < t0 || t0 === undefined ) {
  21562. if ( ! ( t >= t0 ) ) {
  21563. // looping?
  21564. const t1global = pp[ 1 ];
  21565. if ( t < t1global ) {
  21566. i1 = 2; // + 1, using the scan for the details
  21567. t0 = t1global;
  21568. }
  21569. // linear reverse scan
  21570. for ( let giveUpAt = i1 - 2; ; ) {
  21571. if ( t0 === undefined ) {
  21572. // before start
  21573. this._cachedIndex = 0;
  21574. return this.beforeStart_( 0, t, t1 );
  21575. }
  21576. if ( i1 === giveUpAt ) break; // this loop
  21577. t1 = t0;
  21578. t0 = pp[ -- i1 - 1 ];
  21579. if ( t >= t0 ) {
  21580. // we have arrived at the sought interval
  21581. break seek;
  21582. }
  21583. }
  21584. // prepare binary search on the left side of the index
  21585. right = i1;
  21586. i1 = 0;
  21587. break linear_scan;
  21588. }
  21589. // the interval is valid
  21590. break validate_interval;
  21591. } // linear scan
  21592. // binary search
  21593. while ( i1 < right ) {
  21594. const mid = ( i1 + right ) >>> 1;
  21595. if ( t < pp[ mid ] ) {
  21596. right = mid;
  21597. } else {
  21598. i1 = mid + 1;
  21599. }
  21600. }
  21601. t1 = pp[ i1 ];
  21602. t0 = pp[ i1 - 1 ];
  21603. // check boundary cases, again
  21604. if ( t0 === undefined ) {
  21605. this._cachedIndex = 0;
  21606. return this.beforeStart_( 0, t, t1 );
  21607. }
  21608. if ( t1 === undefined ) {
  21609. i1 = pp.length;
  21610. this._cachedIndex = i1;
  21611. return this.afterEnd_( i1 - 1, t0, t );
  21612. }
  21613. } // seek
  21614. this._cachedIndex = i1;
  21615. this.intervalChanged_( i1, t0, t1 );
  21616. } // validate_interval
  21617. return this.interpolate_( i1, t0, t, t1 );
  21618. },
  21619. settings: null, // optional, subclass-specific settings structure
  21620. // Note: The indirection allows central control of many interpolants.
  21621. // --- Protected interface
  21622. DefaultSettings_: {},
  21623. getSettings_: function () {
  21624. return this.settings || this.DefaultSettings_;
  21625. },
  21626. copySampleValue_: function ( index ) {
  21627. // copies a sample value to the result buffer
  21628. const result = this.resultBuffer,
  21629. values = this.sampleValues,
  21630. stride = this.valueSize,
  21631. offset = index * stride;
  21632. for ( let i = 0; i !== stride; ++ i ) {
  21633. result[ i ] = values[ offset + i ];
  21634. }
  21635. return result;
  21636. },
  21637. // Template methods for derived classes:
  21638. interpolate_: function ( /* i1, t0, t, t1 */ ) {
  21639. throw new Error( 'call to abstract method' );
  21640. // implementations shall return this.resultBuffer
  21641. },
  21642. intervalChanged_: function ( /* i1, t0, t1 */ ) {
  21643. // empty
  21644. }
  21645. } );
  21646. // DECLARE ALIAS AFTER assign prototype
  21647. Object.assign( Interpolant.prototype, {
  21648. //( 0, t, t0 ), returns this.resultBuffer
  21649. beforeStart_: Interpolant.prototype.copySampleValue_,
  21650. //( N-1, tN-1, t ), returns this.resultBuffer
  21651. afterEnd_: Interpolant.prototype.copySampleValue_,
  21652. } );
  21653. /**
  21654. * Fast and simple cubic spline interpolant.
  21655. *
  21656. * It was derived from a Hermitian construction setting the first derivative
  21657. * at each sample position to the linear slope between neighboring positions
  21658. * over their parameter interval.
  21659. */
  21660. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21661. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  21662. this._weightPrev = - 0;
  21663. this._offsetPrev = - 0;
  21664. this._weightNext = - 0;
  21665. this._offsetNext = - 0;
  21666. }
  21667. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  21668. constructor: CubicInterpolant,
  21669. DefaultSettings_: {
  21670. endingStart: ZeroCurvatureEnding,
  21671. endingEnd: ZeroCurvatureEnding
  21672. },
  21673. intervalChanged_: function ( i1, t0, t1 ) {
  21674. const pp = this.parameterPositions;
  21675. let iPrev = i1 - 2,
  21676. iNext = i1 + 1,
  21677. tPrev = pp[ iPrev ],
  21678. tNext = pp[ iNext ];
  21679. if ( tPrev === undefined ) {
  21680. switch ( this.getSettings_().endingStart ) {
  21681. case ZeroSlopeEnding:
  21682. // f'(t0) = 0
  21683. iPrev = i1;
  21684. tPrev = 2 * t0 - t1;
  21685. break;
  21686. case WrapAroundEnding:
  21687. // use the other end of the curve
  21688. iPrev = pp.length - 2;
  21689. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  21690. break;
  21691. default: // ZeroCurvatureEnding
  21692. // f''(t0) = 0 a.k.a. Natural Spline
  21693. iPrev = i1;
  21694. tPrev = t1;
  21695. }
  21696. }
  21697. if ( tNext === undefined ) {
  21698. switch ( this.getSettings_().endingEnd ) {
  21699. case ZeroSlopeEnding:
  21700. // f'(tN) = 0
  21701. iNext = i1;
  21702. tNext = 2 * t1 - t0;
  21703. break;
  21704. case WrapAroundEnding:
  21705. // use the other end of the curve
  21706. iNext = 1;
  21707. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  21708. break;
  21709. default: // ZeroCurvatureEnding
  21710. // f''(tN) = 0, a.k.a. Natural Spline
  21711. iNext = i1 - 1;
  21712. tNext = t0;
  21713. }
  21714. }
  21715. const halfDt = ( t1 - t0 ) * 0.5,
  21716. stride = this.valueSize;
  21717. this._weightPrev = halfDt / ( t0 - tPrev );
  21718. this._weightNext = halfDt / ( tNext - t1 );
  21719. this._offsetPrev = iPrev * stride;
  21720. this._offsetNext = iNext * stride;
  21721. },
  21722. interpolate_: function ( i1, t0, t, t1 ) {
  21723. const result = this.resultBuffer,
  21724. values = this.sampleValues,
  21725. stride = this.valueSize,
  21726. o1 = i1 * stride, o0 = o1 - stride,
  21727. oP = this._offsetPrev, oN = this._offsetNext,
  21728. wP = this._weightPrev, wN = this._weightNext,
  21729. p = ( t - t0 ) / ( t1 - t0 ),
  21730. pp = p * p,
  21731. ppp = pp * p;
  21732. // evaluate polynomials
  21733. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  21734. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  21735. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  21736. const sN = wN * ppp - wN * pp;
  21737. // combine data linearly
  21738. for ( let i = 0; i !== stride; ++ i ) {
  21739. result[ i ] =
  21740. sP * values[ oP + i ] +
  21741. s0 * values[ o0 + i ] +
  21742. s1 * values[ o1 + i ] +
  21743. sN * values[ oN + i ];
  21744. }
  21745. return result;
  21746. }
  21747. } );
  21748. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21749. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  21750. }
  21751. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  21752. constructor: LinearInterpolant,
  21753. interpolate_: function ( i1, t0, t, t1 ) {
  21754. const result = this.resultBuffer,
  21755. values = this.sampleValues,
  21756. stride = this.valueSize,
  21757. offset1 = i1 * stride,
  21758. offset0 = offset1 - stride,
  21759. weight1 = ( t - t0 ) / ( t1 - t0 ),
  21760. weight0 = 1 - weight1;
  21761. for ( let i = 0; i !== stride; ++ i ) {
  21762. result[ i ] =
  21763. values[ offset0 + i ] * weight0 +
  21764. values[ offset1 + i ] * weight1;
  21765. }
  21766. return result;
  21767. }
  21768. } );
  21769. /**
  21770. *
  21771. * Interpolant that evaluates to the sample value at the position preceeding
  21772. * the parameter.
  21773. */
  21774. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  21775. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  21776. }
  21777. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  21778. constructor: DiscreteInterpolant,
  21779. interpolate_: function ( i1 /*, t0, t, t1 */ ) {
  21780. return this.copySampleValue_( i1 - 1 );
  21781. }
  21782. } );
  21783. function KeyframeTrack( name, times, values, interpolation ) {
  21784. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  21785. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  21786. this.name = name;
  21787. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  21788. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  21789. this.setInterpolation( interpolation || this.DefaultInterpolation );
  21790. }
  21791. // Static methods
  21792. Object.assign( KeyframeTrack, {
  21793. // Serialization (in static context, because of constructor invocation
  21794. // and automatic invocation of .toJSON):
  21795. toJSON: function ( track ) {
  21796. const trackType = track.constructor;
  21797. let json;
  21798. // derived classes can define a static toJSON method
  21799. if ( trackType.toJSON !== undefined ) {
  21800. json = trackType.toJSON( track );
  21801. } else {
  21802. // by default, we assume the data can be serialized as-is
  21803. json = {
  21804. 'name': track.name,
  21805. 'times': AnimationUtils.convertArray( track.times, Array ),
  21806. 'values': AnimationUtils.convertArray( track.values, Array )
  21807. };
  21808. const interpolation = track.getInterpolation();
  21809. if ( interpolation !== track.DefaultInterpolation ) {
  21810. json.interpolation = interpolation;
  21811. }
  21812. }
  21813. json.type = track.ValueTypeName; // mandatory
  21814. return json;
  21815. }
  21816. } );
  21817. Object.assign( KeyframeTrack.prototype, {
  21818. constructor: KeyframeTrack,
  21819. TimeBufferType: Float32Array,
  21820. ValueBufferType: Float32Array,
  21821. DefaultInterpolation: InterpolateLinear,
  21822. InterpolantFactoryMethodDiscrete: function ( result ) {
  21823. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  21824. },
  21825. InterpolantFactoryMethodLinear: function ( result ) {
  21826. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  21827. },
  21828. InterpolantFactoryMethodSmooth: function ( result ) {
  21829. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  21830. },
  21831. setInterpolation: function ( interpolation ) {
  21832. let factoryMethod;
  21833. switch ( interpolation ) {
  21834. case InterpolateDiscrete:
  21835. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  21836. break;
  21837. case InterpolateLinear:
  21838. factoryMethod = this.InterpolantFactoryMethodLinear;
  21839. break;
  21840. case InterpolateSmooth:
  21841. factoryMethod = this.InterpolantFactoryMethodSmooth;
  21842. break;
  21843. }
  21844. if ( factoryMethod === undefined ) {
  21845. const message = 'unsupported interpolation for ' +
  21846. this.ValueTypeName + ' keyframe track named ' + this.name;
  21847. if ( this.createInterpolant === undefined ) {
  21848. // fall back to default, unless the default itself is messed up
  21849. if ( interpolation !== this.DefaultInterpolation ) {
  21850. this.setInterpolation( this.DefaultInterpolation );
  21851. } else {
  21852. throw new Error( message ); // fatal, in this case
  21853. }
  21854. }
  21855. console.warn( 'THREE.KeyframeTrack:', message );
  21856. return this;
  21857. }
  21858. this.createInterpolant = factoryMethod;
  21859. return this;
  21860. },
  21861. getInterpolation: function () {
  21862. switch ( this.createInterpolant ) {
  21863. case this.InterpolantFactoryMethodDiscrete:
  21864. return InterpolateDiscrete;
  21865. case this.InterpolantFactoryMethodLinear:
  21866. return InterpolateLinear;
  21867. case this.InterpolantFactoryMethodSmooth:
  21868. return InterpolateSmooth;
  21869. }
  21870. },
  21871. getValueSize: function () {
  21872. return this.values.length / this.times.length;
  21873. },
  21874. // move all keyframes either forwards or backwards in time
  21875. shift: function ( timeOffset ) {
  21876. if ( timeOffset !== 0.0 ) {
  21877. const times = this.times;
  21878. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  21879. times[ i ] += timeOffset;
  21880. }
  21881. }
  21882. return this;
  21883. },
  21884. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  21885. scale: function ( timeScale ) {
  21886. if ( timeScale !== 1.0 ) {
  21887. const times = this.times;
  21888. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  21889. times[ i ] *= timeScale;
  21890. }
  21891. }
  21892. return this;
  21893. },
  21894. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  21895. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  21896. trim: function ( startTime, endTime ) {
  21897. const times = this.times,
  21898. nKeys = times.length;
  21899. let from = 0,
  21900. to = nKeys - 1;
  21901. while ( from !== nKeys && times[ from ] < startTime ) {
  21902. ++ from;
  21903. }
  21904. while ( to !== - 1 && times[ to ] > endTime ) {
  21905. -- to;
  21906. }
  21907. ++ to; // inclusive -> exclusive bound
  21908. if ( from !== 0 || to !== nKeys ) {
  21909. // empty tracks are forbidden, so keep at least one keyframe
  21910. if ( from >= to ) {
  21911. to = Math.max( to, 1 );
  21912. from = to - 1;
  21913. }
  21914. const stride = this.getValueSize();
  21915. this.times = AnimationUtils.arraySlice( times, from, to );
  21916. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  21917. }
  21918. return this;
  21919. },
  21920. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  21921. validate: function () {
  21922. let valid = true;
  21923. const valueSize = this.getValueSize();
  21924. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  21925. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  21926. valid = false;
  21927. }
  21928. const times = this.times,
  21929. values = this.values,
  21930. nKeys = times.length;
  21931. if ( nKeys === 0 ) {
  21932. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  21933. valid = false;
  21934. }
  21935. let prevTime = null;
  21936. for ( let i = 0; i !== nKeys; i ++ ) {
  21937. const currTime = times[ i ];
  21938. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  21939. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  21940. valid = false;
  21941. break;
  21942. }
  21943. if ( prevTime !== null && prevTime > currTime ) {
  21944. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  21945. valid = false;
  21946. break;
  21947. }
  21948. prevTime = currTime;
  21949. }
  21950. if ( values !== undefined ) {
  21951. if ( AnimationUtils.isTypedArray( values ) ) {
  21952. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  21953. const value = values[ i ];
  21954. if ( isNaN( value ) ) {
  21955. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  21956. valid = false;
  21957. break;
  21958. }
  21959. }
  21960. }
  21961. }
  21962. return valid;
  21963. },
  21964. // removes equivalent sequential keys as common in morph target sequences
  21965. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21966. optimize: function () {
  21967. // times or values may be shared with other tracks, so overwriting is unsafe
  21968. const times = AnimationUtils.arraySlice( this.times ),
  21969. values = AnimationUtils.arraySlice( this.values ),
  21970. stride = this.getValueSize(),
  21971. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21972. lastIndex = times.length - 1;
  21973. let writeIndex = 1;
  21974. for ( let i = 1; i < lastIndex; ++ i ) {
  21975. let keep = false;
  21976. const time = times[ i ];
  21977. const timeNext = times[ i + 1 ];
  21978. // remove adjacent keyframes scheduled at the same time
  21979. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  21980. if ( ! smoothInterpolation ) {
  21981. // remove unnecessary keyframes same as their neighbors
  21982. const offset = i * stride,
  21983. offsetP = offset - stride,
  21984. offsetN = offset + stride;
  21985. for ( let j = 0; j !== stride; ++ j ) {
  21986. const value = values[ offset + j ];
  21987. if ( value !== values[ offsetP + j ] ||
  21988. value !== values[ offsetN + j ] ) {
  21989. keep = true;
  21990. break;
  21991. }
  21992. }
  21993. } else {
  21994. keep = true;
  21995. }
  21996. }
  21997. // in-place compaction
  21998. if ( keep ) {
  21999. if ( i !== writeIndex ) {
  22000. times[ writeIndex ] = times[ i ];
  22001. const readOffset = i * stride,
  22002. writeOffset = writeIndex * stride;
  22003. for ( let j = 0; j !== stride; ++ j ) {
  22004. values[ writeOffset + j ] = values[ readOffset + j ];
  22005. }
  22006. }
  22007. ++ writeIndex;
  22008. }
  22009. }
  22010. // flush last keyframe (compaction looks ahead)
  22011. if ( lastIndex > 0 ) {
  22012. times[ writeIndex ] = times[ lastIndex ];
  22013. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  22014. values[ writeOffset + j ] = values[ readOffset + j ];
  22015. }
  22016. ++ writeIndex;
  22017. }
  22018. if ( writeIndex !== times.length ) {
  22019. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  22020. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  22021. } else {
  22022. this.times = times;
  22023. this.values = values;
  22024. }
  22025. return this;
  22026. },
  22027. clone: function () {
  22028. const times = AnimationUtils.arraySlice( this.times, 0 );
  22029. const values = AnimationUtils.arraySlice( this.values, 0 );
  22030. const TypedKeyframeTrack = this.constructor;
  22031. const track = new TypedKeyframeTrack( this.name, times, values );
  22032. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22033. track.createInterpolant = this.createInterpolant;
  22034. return track;
  22035. }
  22036. } );
  22037. /**
  22038. * A Track of Boolean keyframe values.
  22039. */
  22040. function BooleanKeyframeTrack( name, times, values ) {
  22041. KeyframeTrack.call( this, name, times, values );
  22042. }
  22043. BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  22044. constructor: BooleanKeyframeTrack,
  22045. ValueTypeName: 'bool',
  22046. ValueBufferType: Array,
  22047. DefaultInterpolation: InterpolateDiscrete,
  22048. InterpolantFactoryMethodLinear: undefined,
  22049. InterpolantFactoryMethodSmooth: undefined
  22050. // Note: Actually this track could have a optimized / compressed
  22051. // representation of a single value and a custom interpolant that
  22052. // computes "firstValue ^ isOdd( index )".
  22053. } );
  22054. /**
  22055. * A Track of keyframe values that represent color.
  22056. */
  22057. function ColorKeyframeTrack( name, times, values, interpolation ) {
  22058. KeyframeTrack.call( this, name, times, values, interpolation );
  22059. }
  22060. ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  22061. constructor: ColorKeyframeTrack,
  22062. ValueTypeName: 'color'
  22063. // ValueBufferType is inherited
  22064. // DefaultInterpolation is inherited
  22065. // Note: Very basic implementation and nothing special yet.
  22066. // However, this is the place for color space parameterization.
  22067. } );
  22068. /**
  22069. * A Track of numeric keyframe values.
  22070. */
  22071. function NumberKeyframeTrack( name, times, values, interpolation ) {
  22072. KeyframeTrack.call( this, name, times, values, interpolation );
  22073. }
  22074. NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  22075. constructor: NumberKeyframeTrack,
  22076. ValueTypeName: 'number'
  22077. // ValueBufferType is inherited
  22078. // DefaultInterpolation is inherited
  22079. } );
  22080. /**
  22081. * Spherical linear unit quaternion interpolant.
  22082. */
  22083. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22084. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  22085. }
  22086. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  22087. constructor: QuaternionLinearInterpolant,
  22088. interpolate_: function ( i1, t0, t, t1 ) {
  22089. const result = this.resultBuffer,
  22090. values = this.sampleValues,
  22091. stride = this.valueSize,
  22092. alpha = ( t - t0 ) / ( t1 - t0 );
  22093. let offset = i1 * stride;
  22094. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  22095. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  22096. }
  22097. return result;
  22098. }
  22099. } );
  22100. /**
  22101. * A Track of quaternion keyframe values.
  22102. */
  22103. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  22104. KeyframeTrack.call( this, name, times, values, interpolation );
  22105. }
  22106. QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  22107. constructor: QuaternionKeyframeTrack,
  22108. ValueTypeName: 'quaternion',
  22109. // ValueBufferType is inherited
  22110. DefaultInterpolation: InterpolateLinear,
  22111. InterpolantFactoryMethodLinear: function ( result ) {
  22112. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  22113. },
  22114. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  22115. } );
  22116. /**
  22117. * A Track that interpolates Strings
  22118. */
  22119. function StringKeyframeTrack( name, times, values, interpolation ) {
  22120. KeyframeTrack.call( this, name, times, values, interpolation );
  22121. }
  22122. StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  22123. constructor: StringKeyframeTrack,
  22124. ValueTypeName: 'string',
  22125. ValueBufferType: Array,
  22126. DefaultInterpolation: InterpolateDiscrete,
  22127. InterpolantFactoryMethodLinear: undefined,
  22128. InterpolantFactoryMethodSmooth: undefined
  22129. } );
  22130. /**
  22131. * A Track of vectored keyframe values.
  22132. */
  22133. function VectorKeyframeTrack( name, times, values, interpolation ) {
  22134. KeyframeTrack.call( this, name, times, values, interpolation );
  22135. }
  22136. VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  22137. constructor: VectorKeyframeTrack,
  22138. ValueTypeName: 'vector'
  22139. // ValueBufferType is inherited
  22140. // DefaultInterpolation is inherited
  22141. } );
  22142. function AnimationClip( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  22143. this.name = name;
  22144. this.tracks = tracks;
  22145. this.duration = duration;
  22146. this.blendMode = blendMode;
  22147. this.uuid = MathUtils.generateUUID();
  22148. // this means it should figure out its duration by scanning the tracks
  22149. if ( this.duration < 0 ) {
  22150. this.resetDuration();
  22151. }
  22152. }
  22153. function getTrackTypeForValueTypeName( typeName ) {
  22154. switch ( typeName.toLowerCase() ) {
  22155. case 'scalar':
  22156. case 'double':
  22157. case 'float':
  22158. case 'number':
  22159. case 'integer':
  22160. return NumberKeyframeTrack;
  22161. case 'vector':
  22162. case 'vector2':
  22163. case 'vector3':
  22164. case 'vector4':
  22165. return VectorKeyframeTrack;
  22166. case 'color':
  22167. return ColorKeyframeTrack;
  22168. case 'quaternion':
  22169. return QuaternionKeyframeTrack;
  22170. case 'bool':
  22171. case 'boolean':
  22172. return BooleanKeyframeTrack;
  22173. case 'string':
  22174. return StringKeyframeTrack;
  22175. }
  22176. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  22177. }
  22178. function parseKeyframeTrack( json ) {
  22179. if ( json.type === undefined ) {
  22180. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  22181. }
  22182. const trackType = getTrackTypeForValueTypeName( json.type );
  22183. if ( json.times === undefined ) {
  22184. const times = [], values = [];
  22185. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  22186. json.times = times;
  22187. json.values = values;
  22188. }
  22189. // derived classes can define a static parse method
  22190. if ( trackType.parse !== undefined ) {
  22191. return trackType.parse( json );
  22192. } else {
  22193. // by default, we assume a constructor compatible with the base
  22194. return new trackType( json.name, json.times, json.values, json.interpolation );
  22195. }
  22196. }
  22197. Object.assign( AnimationClip, {
  22198. parse: function ( json ) {
  22199. const tracks = [],
  22200. jsonTracks = json.tracks,
  22201. frameTime = 1.0 / ( json.fps || 1.0 );
  22202. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  22203. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  22204. }
  22205. const clip = new AnimationClip( json.name, json.duration, tracks, json.blendMode );
  22206. clip.uuid = json.uuid;
  22207. return clip;
  22208. },
  22209. toJSON: function ( clip ) {
  22210. const tracks = [],
  22211. clipTracks = clip.tracks;
  22212. const json = {
  22213. 'name': clip.name,
  22214. 'duration': clip.duration,
  22215. 'tracks': tracks,
  22216. 'uuid': clip.uuid,
  22217. 'blendMode': clip.blendMode
  22218. };
  22219. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  22220. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  22221. }
  22222. return json;
  22223. },
  22224. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  22225. const numMorphTargets = morphTargetSequence.length;
  22226. const tracks = [];
  22227. for ( let i = 0; i < numMorphTargets; i ++ ) {
  22228. let times = [];
  22229. let values = [];
  22230. times.push(
  22231. ( i + numMorphTargets - 1 ) % numMorphTargets,
  22232. i,
  22233. ( i + 1 ) % numMorphTargets );
  22234. values.push( 0, 1, 0 );
  22235. const order = AnimationUtils.getKeyframeOrder( times );
  22236. times = AnimationUtils.sortedArray( times, 1, order );
  22237. values = AnimationUtils.sortedArray( values, 1, order );
  22238. // if there is a key at the first frame, duplicate it as the
  22239. // last frame as well for perfect loop.
  22240. if ( ! noLoop && times[ 0 ] === 0 ) {
  22241. times.push( numMorphTargets );
  22242. values.push( values[ 0 ] );
  22243. }
  22244. tracks.push(
  22245. new NumberKeyframeTrack(
  22246. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  22247. times, values
  22248. ).scale( 1.0 / fps ) );
  22249. }
  22250. return new AnimationClip( name, - 1, tracks );
  22251. },
  22252. findByName: function ( objectOrClipArray, name ) {
  22253. let clipArray = objectOrClipArray;
  22254. if ( ! Array.isArray( objectOrClipArray ) ) {
  22255. const o = objectOrClipArray;
  22256. clipArray = o.geometry && o.geometry.animations || o.animations;
  22257. }
  22258. for ( let i = 0; i < clipArray.length; i ++ ) {
  22259. if ( clipArray[ i ].name === name ) {
  22260. return clipArray[ i ];
  22261. }
  22262. }
  22263. return null;
  22264. },
  22265. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  22266. const animationToMorphTargets = {};
  22267. // tested with https://regex101.com/ on trick sequences
  22268. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22269. const pattern = /^([\w-]*?)([\d]+)$/;
  22270. // sort morph target names into animation groups based
  22271. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22272. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  22273. const morphTarget = morphTargets[ i ];
  22274. const parts = morphTarget.name.match( pattern );
  22275. if ( parts && parts.length > 1 ) {
  22276. const name = parts[ 1 ];
  22277. let animationMorphTargets = animationToMorphTargets[ name ];
  22278. if ( ! animationMorphTargets ) {
  22279. animationToMorphTargets[ name ] = animationMorphTargets = [];
  22280. }
  22281. animationMorphTargets.push( morphTarget );
  22282. }
  22283. }
  22284. const clips = [];
  22285. for ( const name in animationToMorphTargets ) {
  22286. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  22287. }
  22288. return clips;
  22289. },
  22290. // parse the animation.hierarchy format
  22291. parseAnimation: function ( animation, bones ) {
  22292. if ( ! animation ) {
  22293. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  22294. return null;
  22295. }
  22296. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  22297. // only return track if there are actually keys.
  22298. if ( animationKeys.length !== 0 ) {
  22299. const times = [];
  22300. const values = [];
  22301. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  22302. // empty keys are filtered out, so check again
  22303. if ( times.length !== 0 ) {
  22304. destTracks.push( new trackType( trackName, times, values ) );
  22305. }
  22306. }
  22307. };
  22308. const tracks = [];
  22309. const clipName = animation.name || 'default';
  22310. const fps = animation.fps || 30;
  22311. const blendMode = animation.blendMode;
  22312. // automatic length determination in AnimationClip.
  22313. let duration = animation.length || - 1;
  22314. const hierarchyTracks = animation.hierarchy || [];
  22315. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  22316. const animationKeys = hierarchyTracks[ h ].keys;
  22317. // skip empty tracks
  22318. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  22319. // process morph targets
  22320. if ( animationKeys[ 0 ].morphTargets ) {
  22321. // figure out all morph targets used in this track
  22322. const morphTargetNames = {};
  22323. let k;
  22324. for ( k = 0; k < animationKeys.length; k ++ ) {
  22325. if ( animationKeys[ k ].morphTargets ) {
  22326. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  22327. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  22328. }
  22329. }
  22330. }
  22331. // create a track for each morph target with all zero
  22332. // morphTargetInfluences except for the keys in which
  22333. // the morphTarget is named.
  22334. for ( const morphTargetName in morphTargetNames ) {
  22335. const times = [];
  22336. const values = [];
  22337. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  22338. const animationKey = animationKeys[ k ];
  22339. times.push( animationKey.time );
  22340. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  22341. }
  22342. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  22343. }
  22344. duration = morphTargetNames.length * ( fps || 1.0 );
  22345. } else {
  22346. // ...assume skeletal animation
  22347. const boneName = '.bones[' + bones[ h ].name + ']';
  22348. addNonemptyTrack(
  22349. VectorKeyframeTrack, boneName + '.position',
  22350. animationKeys, 'pos', tracks );
  22351. addNonemptyTrack(
  22352. QuaternionKeyframeTrack, boneName + '.quaternion',
  22353. animationKeys, 'rot', tracks );
  22354. addNonemptyTrack(
  22355. VectorKeyframeTrack, boneName + '.scale',
  22356. animationKeys, 'scl', tracks );
  22357. }
  22358. }
  22359. if ( tracks.length === 0 ) {
  22360. return null;
  22361. }
  22362. const clip = new AnimationClip( clipName, duration, tracks, blendMode );
  22363. return clip;
  22364. }
  22365. } );
  22366. Object.assign( AnimationClip.prototype, {
  22367. resetDuration: function () {
  22368. const tracks = this.tracks;
  22369. let duration = 0;
  22370. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  22371. const track = this.tracks[ i ];
  22372. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  22373. }
  22374. this.duration = duration;
  22375. return this;
  22376. },
  22377. trim: function () {
  22378. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22379. this.tracks[ i ].trim( 0, this.duration );
  22380. }
  22381. return this;
  22382. },
  22383. validate: function () {
  22384. let valid = true;
  22385. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22386. valid = valid && this.tracks[ i ].validate();
  22387. }
  22388. return valid;
  22389. },
  22390. optimize: function () {
  22391. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22392. this.tracks[ i ].optimize();
  22393. }
  22394. return this;
  22395. },
  22396. clone: function () {
  22397. const tracks = [];
  22398. for ( let i = 0; i < this.tracks.length; i ++ ) {
  22399. tracks.push( this.tracks[ i ].clone() );
  22400. }
  22401. return new AnimationClip( this.name, this.duration, tracks, this.blendMode );
  22402. },
  22403. toJSON: function () {
  22404. return AnimationClip.toJSON( this );
  22405. }
  22406. } );
  22407. const Cache = {
  22408. enabled: false,
  22409. files: {},
  22410. add: function ( key, file ) {
  22411. if ( this.enabled === false ) return;
  22412. // console.log( 'THREE.Cache', 'Adding key:', key );
  22413. this.files[ key ] = file;
  22414. },
  22415. get: function ( key ) {
  22416. if ( this.enabled === false ) return;
  22417. // console.log( 'THREE.Cache', 'Checking key:', key );
  22418. return this.files[ key ];
  22419. },
  22420. remove: function ( key ) {
  22421. delete this.files[ key ];
  22422. },
  22423. clear: function () {
  22424. this.files = {};
  22425. }
  22426. };
  22427. function LoadingManager( onLoad, onProgress, onError ) {
  22428. const scope = this;
  22429. let isLoading = false;
  22430. let itemsLoaded = 0;
  22431. let itemsTotal = 0;
  22432. let urlModifier = undefined;
  22433. const handlers = [];
  22434. // Refer to #5689 for the reason why we don't set .onStart
  22435. // in the constructor
  22436. this.onStart = undefined;
  22437. this.onLoad = onLoad;
  22438. this.onProgress = onProgress;
  22439. this.onError = onError;
  22440. this.itemStart = function ( url ) {
  22441. itemsTotal ++;
  22442. if ( isLoading === false ) {
  22443. if ( scope.onStart !== undefined ) {
  22444. scope.onStart( url, itemsLoaded, itemsTotal );
  22445. }
  22446. }
  22447. isLoading = true;
  22448. };
  22449. this.itemEnd = function ( url ) {
  22450. itemsLoaded ++;
  22451. if ( scope.onProgress !== undefined ) {
  22452. scope.onProgress( url, itemsLoaded, itemsTotal );
  22453. }
  22454. if ( itemsLoaded === itemsTotal ) {
  22455. isLoading = false;
  22456. if ( scope.onLoad !== undefined ) {
  22457. scope.onLoad();
  22458. }
  22459. }
  22460. };
  22461. this.itemError = function ( url ) {
  22462. if ( scope.onError !== undefined ) {
  22463. scope.onError( url );
  22464. }
  22465. };
  22466. this.resolveURL = function ( url ) {
  22467. if ( urlModifier ) {
  22468. return urlModifier( url );
  22469. }
  22470. return url;
  22471. };
  22472. this.setURLModifier = function ( transform ) {
  22473. urlModifier = transform;
  22474. return this;
  22475. };
  22476. this.addHandler = function ( regex, loader ) {
  22477. handlers.push( regex, loader );
  22478. return this;
  22479. };
  22480. this.removeHandler = function ( regex ) {
  22481. const index = handlers.indexOf( regex );
  22482. if ( index !== - 1 ) {
  22483. handlers.splice( index, 2 );
  22484. }
  22485. return this;
  22486. };
  22487. this.getHandler = function ( file ) {
  22488. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  22489. const regex = handlers[ i ];
  22490. const loader = handlers[ i + 1 ];
  22491. if ( regex.global ) regex.lastIndex = 0; // see #17920
  22492. if ( regex.test( file ) ) {
  22493. return loader;
  22494. }
  22495. }
  22496. return null;
  22497. };
  22498. }
  22499. const DefaultLoadingManager = new LoadingManager();
  22500. function Loader( manager ) {
  22501. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22502. this.crossOrigin = 'anonymous';
  22503. this.withCredentials = false;
  22504. this.path = '';
  22505. this.resourcePath = '';
  22506. this.requestHeader = {};
  22507. }
  22508. Object.assign( Loader.prototype, {
  22509. load: function ( /* url, onLoad, onProgress, onError */ ) {},
  22510. loadAsync: function ( url, onProgress ) {
  22511. const scope = this;
  22512. return new Promise( function ( resolve, reject ) {
  22513. scope.load( url, resolve, onProgress, reject );
  22514. } );
  22515. },
  22516. parse: function ( /* data */ ) {},
  22517. setCrossOrigin: function ( crossOrigin ) {
  22518. this.crossOrigin = crossOrigin;
  22519. return this;
  22520. },
  22521. setWithCredentials: function ( value ) {
  22522. this.withCredentials = value;
  22523. return this;
  22524. },
  22525. setPath: function ( path ) {
  22526. this.path = path;
  22527. return this;
  22528. },
  22529. setResourcePath: function ( resourcePath ) {
  22530. this.resourcePath = resourcePath;
  22531. return this;
  22532. },
  22533. setRequestHeader: function ( requestHeader ) {
  22534. this.requestHeader = requestHeader;
  22535. return this;
  22536. }
  22537. } );
  22538. const loading = {};
  22539. function FileLoader( manager ) {
  22540. Loader.call( this, manager );
  22541. }
  22542. FileLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22543. constructor: FileLoader,
  22544. load: function ( url, onLoad, onProgress, onError ) {
  22545. if ( url === undefined ) url = '';
  22546. if ( this.path !== undefined ) url = this.path + url;
  22547. url = this.manager.resolveURL( url );
  22548. const scope = this;
  22549. const cached = Cache.get( url );
  22550. if ( cached !== undefined ) {
  22551. scope.manager.itemStart( url );
  22552. setTimeout( function () {
  22553. if ( onLoad ) onLoad( cached );
  22554. scope.manager.itemEnd( url );
  22555. }, 0 );
  22556. return cached;
  22557. }
  22558. // Check if request is duplicate
  22559. if ( loading[ url ] !== undefined ) {
  22560. loading[ url ].push( {
  22561. onLoad: onLoad,
  22562. onProgress: onProgress,
  22563. onError: onError
  22564. } );
  22565. return;
  22566. }
  22567. // Check for data: URI
  22568. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22569. const dataUriRegexResult = url.match( dataUriRegex );
  22570. let request;
  22571. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22572. if ( dataUriRegexResult ) {
  22573. const mimeType = dataUriRegexResult[ 1 ];
  22574. const isBase64 = !! dataUriRegexResult[ 2 ];
  22575. let data = dataUriRegexResult[ 3 ];
  22576. data = decodeURIComponent( data );
  22577. if ( isBase64 ) data = atob( data );
  22578. try {
  22579. let response;
  22580. const responseType = ( this.responseType || '' ).toLowerCase();
  22581. switch ( responseType ) {
  22582. case 'arraybuffer':
  22583. case 'blob':
  22584. const view = new Uint8Array( data.length );
  22585. for ( let i = 0; i < data.length; i ++ ) {
  22586. view[ i ] = data.charCodeAt( i );
  22587. }
  22588. if ( responseType === 'blob' ) {
  22589. response = new Blob( [ view.buffer ], { type: mimeType } );
  22590. } else {
  22591. response = view.buffer;
  22592. }
  22593. break;
  22594. case 'document':
  22595. const parser = new DOMParser();
  22596. response = parser.parseFromString( data, mimeType );
  22597. break;
  22598. case 'json':
  22599. response = JSON.parse( data );
  22600. break;
  22601. default: // 'text' or other
  22602. response = data;
  22603. break;
  22604. }
  22605. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22606. setTimeout( function () {
  22607. if ( onLoad ) onLoad( response );
  22608. scope.manager.itemEnd( url );
  22609. }, 0 );
  22610. } catch ( error ) {
  22611. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22612. setTimeout( function () {
  22613. if ( onError ) onError( error );
  22614. scope.manager.itemError( url );
  22615. scope.manager.itemEnd( url );
  22616. }, 0 );
  22617. }
  22618. } else {
  22619. // Initialise array for duplicate requests
  22620. loading[ url ] = [];
  22621. loading[ url ].push( {
  22622. onLoad: onLoad,
  22623. onProgress: onProgress,
  22624. onError: onError
  22625. } );
  22626. request = new XMLHttpRequest();
  22627. request.open( 'GET', url, true );
  22628. request.addEventListener( 'load', function ( event ) {
  22629. const response = this.response;
  22630. const callbacks = loading[ url ];
  22631. delete loading[ url ];
  22632. if ( this.status === 200 || this.status === 0 ) {
  22633. // Some browsers return HTTP Status 0 when using non-http protocol
  22634. // e.g. 'file://' or 'data://'. Handle as success.
  22635. if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  22636. // Add to cache only on HTTP success, so that we do not cache
  22637. // error response bodies as proper responses to requests.
  22638. Cache.add( url, response );
  22639. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22640. const callback = callbacks[ i ];
  22641. if ( callback.onLoad ) callback.onLoad( response, event.total); //xzw add event.total
  22642. }
  22643. scope.manager.itemEnd( url );
  22644. } else {
  22645. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22646. const callback = callbacks[ i ];
  22647. if ( callback.onError ) callback.onError( event );
  22648. }
  22649. scope.manager.itemError( url );
  22650. scope.manager.itemEnd( url );
  22651. }
  22652. }, false );
  22653. request.addEventListener( 'progress', function ( event ) {
  22654. const callbacks = loading[ url ];
  22655. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22656. const callback = callbacks[ i ];
  22657. if ( callback.onProgress ) callback.onProgress( event );
  22658. }
  22659. }, false );
  22660. request.addEventListener( 'error', function ( event ) {
  22661. const callbacks = loading[ url ];
  22662. delete loading[ url ];
  22663. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22664. const callback = callbacks[ i ];
  22665. if ( callback.onError ) callback.onError( event );
  22666. }
  22667. scope.manager.itemError( url );
  22668. scope.manager.itemEnd( url );
  22669. }, false );
  22670. request.addEventListener( 'abort', function ( event ) {
  22671. const callbacks = loading[ url ];
  22672. delete loading[ url ];
  22673. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  22674. const callback = callbacks[ i ];
  22675. if ( callback.onError ) callback.onError( event );
  22676. }
  22677. scope.manager.itemError( url );
  22678. scope.manager.itemEnd( url );
  22679. }, false );
  22680. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  22681. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  22682. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  22683. for ( const header in this.requestHeader ) {
  22684. request.setRequestHeader( header, this.requestHeader[ header ] );
  22685. }
  22686. request.send( null );
  22687. }
  22688. scope.manager.itemStart( url );
  22689. return request;
  22690. },
  22691. setResponseType: function ( value ) {
  22692. this.responseType = value;
  22693. return this;
  22694. },
  22695. setMimeType: function ( value ) {
  22696. this.mimeType = value;
  22697. return this;
  22698. }
  22699. } );
  22700. function AnimationLoader( manager ) {
  22701. Loader.call( this, manager );
  22702. }
  22703. AnimationLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22704. constructor: AnimationLoader,
  22705. load: function ( url, onLoad, onProgress, onError ) {
  22706. const scope = this;
  22707. const loader = new FileLoader( scope.manager );
  22708. loader.setPath( scope.path );
  22709. loader.setRequestHeader( scope.requestHeader );
  22710. loader.setWithCredentials( scope.withCredentials );
  22711. loader.load( url, function ( text ) {
  22712. try {
  22713. onLoad( scope.parse( JSON.parse( text ) ) );
  22714. } catch ( e ) {
  22715. if ( onError ) {
  22716. onError( e );
  22717. } else {
  22718. console.error( e );
  22719. }
  22720. scope.manager.itemError( url );
  22721. }
  22722. }, onProgress, onError );
  22723. },
  22724. parse: function ( json ) {
  22725. const animations = [];
  22726. for ( let i = 0; i < json.length; i ++ ) {
  22727. const clip = AnimationClip.parse( json[ i ] );
  22728. animations.push( clip );
  22729. }
  22730. return animations;
  22731. }
  22732. } );
  22733. /**
  22734. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22735. *
  22736. * Sub classes have to implement the parse() method which will be used in load().
  22737. */
  22738. function CompressedTextureLoader( manager ) {
  22739. Loader.call( this, manager );
  22740. }
  22741. CompressedTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22742. constructor: CompressedTextureLoader,
  22743. load: function ( url, onLoad, onProgress, onError ) {
  22744. const scope = this;
  22745. const images = [];
  22746. const texture = new CompressedTexture();
  22747. const loader = new FileLoader( this.manager );
  22748. loader.setPath( this.path );
  22749. loader.setResponseType( 'arraybuffer' );
  22750. loader.setRequestHeader( this.requestHeader );
  22751. loader.setWithCredentials( scope.withCredentials );
  22752. let loaded = 0;
  22753. function loadTexture( i ) {
  22754. loader.load( url[ i ], function ( buffer ) {
  22755. const texDatas = scope.parse( buffer, true );
  22756. images[ i ] = {
  22757. width: texDatas.width,
  22758. height: texDatas.height,
  22759. format: texDatas.format,
  22760. mipmaps: texDatas.mipmaps
  22761. };
  22762. loaded += 1;
  22763. if ( loaded === 6 ) {
  22764. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  22765. texture.image = images;
  22766. texture.format = texDatas.format;
  22767. texture.needsUpdate = true;
  22768. if ( onLoad ) onLoad( texture );
  22769. }
  22770. }, onProgress, onError );
  22771. }
  22772. if ( Array.isArray( url ) ) {
  22773. for ( let i = 0, il = url.length; i < il; ++ i ) {
  22774. loadTexture( i );
  22775. }
  22776. } else {
  22777. // compressed cubemap texture stored in a single DDS file
  22778. loader.load( url, function ( buffer ) {
  22779. const texDatas = scope.parse( buffer, true );
  22780. if ( texDatas.isCubemap ) {
  22781. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22782. for ( let f = 0; f < faces; f ++ ) {
  22783. images[ f ] = { mipmaps: [] };
  22784. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  22785. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  22786. images[ f ].format = texDatas.format;
  22787. images[ f ].width = texDatas.width;
  22788. images[ f ].height = texDatas.height;
  22789. }
  22790. }
  22791. texture.image = images;
  22792. } else {
  22793. texture.image.width = texDatas.width;
  22794. texture.image.height = texDatas.height;
  22795. texture.mipmaps = texDatas.mipmaps;
  22796. }
  22797. if ( texDatas.mipmapCount === 1 ) {
  22798. texture.minFilter = LinearFilter;
  22799. }
  22800. texture.format = texDatas.format;
  22801. texture.needsUpdate = true;
  22802. if ( onLoad ) onLoad( texture );
  22803. }, onProgress, onError );
  22804. }
  22805. return texture;
  22806. }
  22807. } );
  22808. function ImageLoader( manager ) {
  22809. Loader.call( this, manager );
  22810. }
  22811. ImageLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22812. constructor: ImageLoader,
  22813. load: function ( url, onLoad, onProgress, onError ) {
  22814. if ( this.path !== undefined ) url = this.path + url;
  22815. url = this.manager.resolveURL( url );
  22816. const scope = this;
  22817. const cached = Cache.get( url );
  22818. if ( cached !== undefined ) {
  22819. scope.manager.itemStart( url );
  22820. setTimeout( function () {
  22821. if ( onLoad ) onLoad( cached );
  22822. scope.manager.itemEnd( url );
  22823. }, 0 );
  22824. return cached;
  22825. }
  22826. const image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  22827. function onImageLoad() {
  22828. image.removeEventListener( 'load', onImageLoad, false );
  22829. image.removeEventListener( 'error', onImageError, false );
  22830. Cache.add( url, this );
  22831. if ( onLoad ) onLoad( this );
  22832. scope.manager.itemEnd( url );
  22833. }
  22834. function onImageError( event ) {
  22835. image.removeEventListener( 'load', onImageLoad, false );
  22836. image.removeEventListener( 'error', onImageError, false );
  22837. if ( onError ) onError( event );
  22838. scope.manager.itemError( url );
  22839. scope.manager.itemEnd( url );
  22840. }
  22841. image.addEventListener( 'load', onImageLoad, false );
  22842. image.addEventListener( 'error', onImageError, false );
  22843. if ( url.substr( 0, 5 ) !== 'data:' ) {
  22844. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  22845. }
  22846. scope.manager.itemStart( url );
  22847. image.src = url;
  22848. return image;
  22849. }
  22850. } );
  22851. function CubeTextureLoader( manager ) {
  22852. Loader.call( this, manager );
  22853. }
  22854. CubeTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22855. constructor: CubeTextureLoader,
  22856. load: function ( urls, onLoad, onProgress, onError ) {
  22857. const texture = new CubeTexture();
  22858. const loader = new ImageLoader( this.manager );
  22859. loader.setCrossOrigin( this.crossOrigin );
  22860. loader.setPath( this.path );
  22861. let loaded = 0;
  22862. function loadTexture( i ) {
  22863. loader.load( urls[ i ], function ( image ) {
  22864. texture.images[ i ] = image;
  22865. loaded ++;
  22866. if ( loaded === 6 ) {
  22867. texture.needsUpdate = true;
  22868. if ( onLoad ) onLoad( texture );
  22869. }
  22870. }, undefined, onError );
  22871. }
  22872. for ( let i = 0; i < urls.length; ++ i ) {
  22873. loadTexture( i );
  22874. }
  22875. return texture;
  22876. }
  22877. } );
  22878. /**
  22879. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22880. *
  22881. * Sub classes have to implement the parse() method which will be used in load().
  22882. */
  22883. function DataTextureLoader( manager ) {
  22884. Loader.call( this, manager );
  22885. }
  22886. DataTextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22887. constructor: DataTextureLoader,
  22888. load: function ( url, onLoad, onProgress, onError ) {
  22889. const scope = this;
  22890. const texture = new DataTexture();
  22891. const loader = new FileLoader( this.manager );
  22892. loader.setResponseType( 'arraybuffer' );
  22893. loader.setRequestHeader( this.requestHeader );
  22894. loader.setPath( this.path );
  22895. loader.setWithCredentials( scope.withCredentials );
  22896. loader.load( url, function ( buffer ) {
  22897. const texData = scope.parse( buffer );
  22898. if ( ! texData ) return;
  22899. if ( texData.image !== undefined ) {
  22900. texture.image = texData.image;
  22901. } else if ( texData.data !== undefined ) {
  22902. texture.image.width = texData.width;
  22903. texture.image.height = texData.height;
  22904. texture.image.data = texData.data;
  22905. }
  22906. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  22907. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  22908. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  22909. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  22910. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  22911. if ( texData.format !== undefined ) {
  22912. texture.format = texData.format;
  22913. }
  22914. if ( texData.type !== undefined ) {
  22915. texture.type = texData.type;
  22916. }
  22917. if ( texData.mipmaps !== undefined ) {
  22918. texture.mipmaps = texData.mipmaps;
  22919. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  22920. }
  22921. if ( texData.mipmapCount === 1 ) {
  22922. texture.minFilter = LinearFilter;
  22923. }
  22924. texture.needsUpdate = true;
  22925. if ( onLoad ) onLoad( texture, texData );
  22926. }, onProgress, onError );
  22927. return texture;
  22928. }
  22929. } );
  22930. function TextureLoader( manager ) {
  22931. Loader.call( this, manager );
  22932. }
  22933. TextureLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  22934. constructor: TextureLoader,
  22935. load: function ( url, onLoad, onProgress, onError ) {
  22936. const texture = new Texture();
  22937. const loader = new ImageLoader( this.manager );
  22938. loader.setCrossOrigin( this.crossOrigin );
  22939. loader.setPath( this.path );
  22940. loader.load( url, function ( image ) {
  22941. texture.image = image;
  22942. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22943. const isJPEG = url.search( /\.jpe?g($|\?)/i ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  22944. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22945. texture.needsUpdate = true;
  22946. if ( onLoad !== undefined ) {
  22947. onLoad( texture );
  22948. }
  22949. }, onProgress, onError );
  22950. return texture;
  22951. }
  22952. } );
  22953. /**
  22954. * Extensible curve object.
  22955. *
  22956. * Some common of curve methods:
  22957. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  22958. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  22959. * .getPoints(), .getSpacedPoints()
  22960. * .getLength()
  22961. * .updateArcLengths()
  22962. *
  22963. * This following curves inherit from THREE.Curve:
  22964. *
  22965. * -- 2D curves --
  22966. * THREE.ArcCurve
  22967. * THREE.CubicBezierCurve
  22968. * THREE.EllipseCurve
  22969. * THREE.LineCurve
  22970. * THREE.QuadraticBezierCurve
  22971. * THREE.SplineCurve
  22972. *
  22973. * -- 3D curves --
  22974. * THREE.CatmullRomCurve3
  22975. * THREE.CubicBezierCurve3
  22976. * THREE.LineCurve3
  22977. * THREE.QuadraticBezierCurve3
  22978. *
  22979. * A series of curves can be represented as a THREE.CurvePath.
  22980. *
  22981. **/
  22982. function Curve() {
  22983. this.type = 'Curve';
  22984. this.arcLengthDivisions = 200;
  22985. }
  22986. Object.assign( Curve.prototype, {
  22987. // Virtual base class method to overwrite and implement in subclasses
  22988. // - t [0 .. 1]
  22989. getPoint: function ( /* t, optionalTarget */ ) {
  22990. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  22991. return null;
  22992. },
  22993. // Get point at relative position in curve according to arc length
  22994. // - u [0 .. 1]
  22995. getPointAt: function ( u, optionalTarget ) {
  22996. const t = this.getUtoTmapping( u );
  22997. return this.getPoint( t, optionalTarget );
  22998. },
  22999. // Get sequence of points using getPoint( t )
  23000. getPoints: function ( divisions = 5 ) {
  23001. const points = [];
  23002. for ( let d = 0; d <= divisions; d ++ ) {
  23003. points.push( this.getPoint( d / divisions ) );
  23004. }
  23005. return points;
  23006. },
  23007. // Get sequence of points using getPointAt( u )
  23008. getSpacedPoints: function ( divisions = 5 ) {
  23009. const points = [];
  23010. for ( let d = 0; d <= divisions; d ++ ) {
  23011. points.push( this.getPointAt( d / divisions ) );
  23012. }
  23013. return points;
  23014. },
  23015. // Get total curve arc length
  23016. getLength: function () {
  23017. const lengths = this.getLengths();
  23018. return lengths[ lengths.length - 1 ];
  23019. },
  23020. // Get list of cumulative segment lengths
  23021. getLengths: function ( divisions ) {
  23022. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  23023. if ( this.cacheArcLengths &&
  23024. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23025. ! this.needsUpdate ) {
  23026. return this.cacheArcLengths;
  23027. }
  23028. this.needsUpdate = false;
  23029. const cache = [];
  23030. let current, last = this.getPoint( 0 );
  23031. let sum = 0;
  23032. cache.push( 0 );
  23033. for ( let p = 1; p <= divisions; p ++ ) {
  23034. current = this.getPoint( p / divisions );
  23035. sum += current.distanceTo( last );
  23036. cache.push( sum );
  23037. last = current;
  23038. }
  23039. this.cacheArcLengths = cache;
  23040. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23041. },
  23042. updateArcLengths: function () {
  23043. this.needsUpdate = true;
  23044. this.getLengths();
  23045. },
  23046. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  23047. getUtoTmapping: function ( u, distance ) {
  23048. const arcLengths = this.getLengths();
  23049. let i = 0;
  23050. const il = arcLengths.length;
  23051. let targetArcLength; // The targeted u distance value to get
  23052. if ( distance ) {
  23053. targetArcLength = distance;
  23054. } else {
  23055. targetArcLength = u * arcLengths[ il - 1 ];
  23056. }
  23057. // binary search for the index with largest value smaller than target u distance
  23058. let low = 0, high = il - 1, comparison;
  23059. while ( low <= high ) {
  23060. 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
  23061. comparison = arcLengths[ i ] - targetArcLength;
  23062. if ( comparison < 0 ) {
  23063. low = i + 1;
  23064. } else if ( comparison > 0 ) {
  23065. high = i - 1;
  23066. } else {
  23067. high = i;
  23068. break;
  23069. // DONE
  23070. }
  23071. }
  23072. i = high;
  23073. if ( arcLengths[ i ] === targetArcLength ) {
  23074. return i / ( il - 1 );
  23075. }
  23076. // we could get finer grain at lengths, or use simple interpolation between two points
  23077. const lengthBefore = arcLengths[ i ];
  23078. const lengthAfter = arcLengths[ i + 1 ];
  23079. const segmentLength = lengthAfter - lengthBefore;
  23080. // determine where we are between the 'before' and 'after' points
  23081. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23082. // add that fractional amount to t
  23083. const t = ( i + segmentFraction ) / ( il - 1 );
  23084. return t;
  23085. },
  23086. // Returns a unit vector tangent at t
  23087. // In case any sub curve does not implement its tangent derivation,
  23088. // 2 points a small delta apart will be used to find its gradient
  23089. // which seems to give a reasonable approximation
  23090. getTangent: function ( t, optionalTarget ) {
  23091. const delta = 0.0001;
  23092. let t1 = t - delta;
  23093. let t2 = t + delta;
  23094. // Capping in case of danger
  23095. if ( t1 < 0 ) t1 = 0;
  23096. if ( t2 > 1 ) t2 = 1;
  23097. const pt1 = this.getPoint( t1 );
  23098. const pt2 = this.getPoint( t2 );
  23099. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2$1() : new Vector3() );
  23100. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23101. return tangent;
  23102. },
  23103. getTangentAt: function ( u, optionalTarget ) {
  23104. const t = this.getUtoTmapping( u );
  23105. return this.getTangent( t, optionalTarget );
  23106. },
  23107. computeFrenetFrames: function ( segments, closed ) {
  23108. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23109. const normal = new Vector3();
  23110. const tangents = [];
  23111. const normals = [];
  23112. const binormals = [];
  23113. const vec = new Vector3();
  23114. const mat = new Matrix4();
  23115. // compute the tangent vectors for each segment on the curve
  23116. for ( let i = 0; i <= segments; i ++ ) {
  23117. const u = i / segments;
  23118. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23119. tangents[ i ].normalize();
  23120. }
  23121. // select an initial normal vector perpendicular to the first tangent vector,
  23122. // and in the direction of the minimum tangent xyz component
  23123. normals[ 0 ] = new Vector3();
  23124. binormals[ 0 ] = new Vector3();
  23125. let min = Number.MAX_VALUE;
  23126. const tx = Math.abs( tangents[ 0 ].x );
  23127. const ty = Math.abs( tangents[ 0 ].y );
  23128. const tz = Math.abs( tangents[ 0 ].z );
  23129. if ( tx <= min ) {
  23130. min = tx;
  23131. normal.set( 1, 0, 0 );
  23132. }
  23133. if ( ty <= min ) {
  23134. min = ty;
  23135. normal.set( 0, 1, 0 );
  23136. }
  23137. if ( tz <= min ) {
  23138. normal.set( 0, 0, 1 );
  23139. }
  23140. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23141. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23142. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23143. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23144. for ( let i = 1; i <= segments; i ++ ) {
  23145. normals[ i ] = normals[ i - 1 ].clone();
  23146. binormals[ i ] = binormals[ i - 1 ].clone();
  23147. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23148. if ( vec.length() > Number.EPSILON ) {
  23149. vec.normalize();
  23150. const theta = Math.acos( MathUtils.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  23151. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23152. }
  23153. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23154. }
  23155. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23156. if ( closed === true ) {
  23157. let theta = Math.acos( MathUtils.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  23158. theta /= segments;
  23159. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23160. theta = - theta;
  23161. }
  23162. for ( let i = 1; i <= segments; i ++ ) {
  23163. // twist a little...
  23164. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23165. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23166. }
  23167. }
  23168. return {
  23169. tangents: tangents,
  23170. normals: normals,
  23171. binormals: binormals
  23172. };
  23173. },
  23174. clone: function () {
  23175. return new this.constructor().copy( this );
  23176. },
  23177. copy: function ( source ) {
  23178. this.arcLengthDivisions = source.arcLengthDivisions;
  23179. return this;
  23180. },
  23181. toJSON: function () {
  23182. const data = {
  23183. metadata: {
  23184. version: 4.5,
  23185. type: 'Curve',
  23186. generator: 'Curve.toJSON'
  23187. }
  23188. };
  23189. data.arcLengthDivisions = this.arcLengthDivisions;
  23190. data.type = this.type;
  23191. return data;
  23192. },
  23193. fromJSON: function ( json ) {
  23194. this.arcLengthDivisions = json.arcLengthDivisions;
  23195. return this;
  23196. }
  23197. } );
  23198. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  23199. Curve.call( this );
  23200. this.type = 'EllipseCurve';
  23201. this.aX = aX || 0;
  23202. this.aY = aY || 0;
  23203. this.xRadius = xRadius || 1;
  23204. this.yRadius = yRadius || 1;
  23205. this.aStartAngle = aStartAngle || 0;
  23206. this.aEndAngle = aEndAngle || 2 * Math.PI;
  23207. this.aClockwise = aClockwise || false;
  23208. this.aRotation = aRotation || 0;
  23209. }
  23210. EllipseCurve.prototype = Object.create( Curve.prototype );
  23211. EllipseCurve.prototype.constructor = EllipseCurve;
  23212. EllipseCurve.prototype.isEllipseCurve = true;
  23213. EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) {
  23214. const point = optionalTarget || new Vector2$1();
  23215. const twoPi = Math.PI * 2;
  23216. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23217. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23218. // ensures that deltaAngle is 0 .. 2 PI
  23219. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23220. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23221. if ( deltaAngle < Number.EPSILON ) {
  23222. if ( samePoints ) {
  23223. deltaAngle = 0;
  23224. } else {
  23225. deltaAngle = twoPi;
  23226. }
  23227. }
  23228. if ( this.aClockwise === true && ! samePoints ) {
  23229. if ( deltaAngle === twoPi ) {
  23230. deltaAngle = - twoPi;
  23231. } else {
  23232. deltaAngle = deltaAngle - twoPi;
  23233. }
  23234. }
  23235. const angle = this.aStartAngle + t * deltaAngle;
  23236. let x = this.aX + this.xRadius * Math.cos( angle );
  23237. let y = this.aY + this.yRadius * Math.sin( angle );
  23238. if ( this.aRotation !== 0 ) {
  23239. const cos = Math.cos( this.aRotation );
  23240. const sin = Math.sin( this.aRotation );
  23241. const tx = x - this.aX;
  23242. const ty = y - this.aY;
  23243. // Rotate the point about the center of the ellipse.
  23244. x = tx * cos - ty * sin + this.aX;
  23245. y = tx * sin + ty * cos + this.aY;
  23246. }
  23247. return point.set( x, y );
  23248. };
  23249. EllipseCurve.prototype.copy = function ( source ) {
  23250. Curve.prototype.copy.call( this, source );
  23251. this.aX = source.aX;
  23252. this.aY = source.aY;
  23253. this.xRadius = source.xRadius;
  23254. this.yRadius = source.yRadius;
  23255. this.aStartAngle = source.aStartAngle;
  23256. this.aEndAngle = source.aEndAngle;
  23257. this.aClockwise = source.aClockwise;
  23258. this.aRotation = source.aRotation;
  23259. return this;
  23260. };
  23261. EllipseCurve.prototype.toJSON = function () {
  23262. const data = Curve.prototype.toJSON.call( this );
  23263. data.aX = this.aX;
  23264. data.aY = this.aY;
  23265. data.xRadius = this.xRadius;
  23266. data.yRadius = this.yRadius;
  23267. data.aStartAngle = this.aStartAngle;
  23268. data.aEndAngle = this.aEndAngle;
  23269. data.aClockwise = this.aClockwise;
  23270. data.aRotation = this.aRotation;
  23271. return data;
  23272. };
  23273. EllipseCurve.prototype.fromJSON = function ( json ) {
  23274. Curve.prototype.fromJSON.call( this, json );
  23275. this.aX = json.aX;
  23276. this.aY = json.aY;
  23277. this.xRadius = json.xRadius;
  23278. this.yRadius = json.yRadius;
  23279. this.aStartAngle = json.aStartAngle;
  23280. this.aEndAngle = json.aEndAngle;
  23281. this.aClockwise = json.aClockwise;
  23282. this.aRotation = json.aRotation;
  23283. return this;
  23284. };
  23285. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23286. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23287. this.type = 'ArcCurve';
  23288. }
  23289. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  23290. ArcCurve.prototype.constructor = ArcCurve;
  23291. ArcCurve.prototype.isArcCurve = true;
  23292. /**
  23293. * Centripetal CatmullRom Curve - which is useful for avoiding
  23294. * cusps and self-intersections in non-uniform catmull rom curves.
  23295. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23296. *
  23297. * curve.type accepts centripetal(default), chordal and catmullrom
  23298. * curve.tension is used for catmullrom which defaults to 0.5
  23299. */
  23300. /*
  23301. Based on an optimized c++ solution in
  23302. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23303. - http://ideone.com/NoEbVM
  23304. This CubicPoly class could be used for reusing some variables and calculations,
  23305. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23306. which can be placed in CurveUtils.
  23307. */
  23308. function CubicPoly() {
  23309. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23310. /*
  23311. * Compute coefficients for a cubic polynomial
  23312. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23313. * such that
  23314. * p(0) = x0, p(1) = x1
  23315. * and
  23316. * p'(0) = t0, p'(1) = t1.
  23317. */
  23318. function init( x0, x1, t0, t1 ) {
  23319. c0 = x0;
  23320. c1 = t0;
  23321. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  23322. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23323. }
  23324. return {
  23325. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23326. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23327. },
  23328. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23329. // compute tangents when parameterized in [t1,t2]
  23330. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23331. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23332. // rescale tangents for parametrization in [0,1]
  23333. t1 *= dt1;
  23334. t2 *= dt1;
  23335. init( x1, x2, t1, t2 );
  23336. },
  23337. calc: function ( t ) {
  23338. const t2 = t * t;
  23339. const t3 = t2 * t;
  23340. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23341. }
  23342. };
  23343. }
  23344. //
  23345. const tmp = new Vector3();
  23346. const px = new CubicPoly(), py = new CubicPoly(), pz = new CubicPoly();
  23347. function CatmullRomCurve3( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23348. Curve.call( this );
  23349. this.type = 'CatmullRomCurve3';
  23350. this.points = points;
  23351. this.closed = closed;
  23352. this.curveType = curveType;
  23353. this.tension = tension;
  23354. }
  23355. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  23356. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  23357. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  23358. CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget = new Vector3() ) {
  23359. const point = optionalTarget;
  23360. const points = this.points;
  23361. const l = points.length;
  23362. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23363. let intPoint = Math.floor( p );
  23364. let weight = p - intPoint;
  23365. if ( this.closed ) {
  23366. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23367. } else if ( weight === 0 && intPoint === l - 1 ) {
  23368. intPoint = l - 2;
  23369. weight = 1;
  23370. }
  23371. let p0, p3; // 4 points (p1 & p2 defined below)
  23372. if ( this.closed || intPoint > 0 ) {
  23373. p0 = points[ ( intPoint - 1 ) % l ];
  23374. } else {
  23375. // extrapolate first point
  23376. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23377. p0 = tmp;
  23378. }
  23379. const p1 = points[ intPoint % l ];
  23380. const p2 = points[ ( intPoint + 1 ) % l ];
  23381. if ( this.closed || intPoint + 2 < l ) {
  23382. p3 = points[ ( intPoint + 2 ) % l ];
  23383. } else {
  23384. // extrapolate last point
  23385. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23386. p3 = tmp;
  23387. }
  23388. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23389. // init Centripetal / Chordal Catmull-Rom
  23390. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23391. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23392. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23393. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23394. // safety check for repeated points
  23395. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23396. if ( dt0 < 1e-4 ) dt0 = dt1;
  23397. if ( dt2 < 1e-4 ) dt2 = dt1;
  23398. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23399. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23400. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23401. } else if ( this.curveType === 'catmullrom' ) {
  23402. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23403. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23404. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23405. }
  23406. point.set(
  23407. px.calc( weight ),
  23408. py.calc( weight ),
  23409. pz.calc( weight )
  23410. );
  23411. return point;
  23412. };
  23413. CatmullRomCurve3.prototype.copy = function ( source ) {
  23414. Curve.prototype.copy.call( this, source );
  23415. this.points = [];
  23416. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23417. const point = source.points[ i ];
  23418. this.points.push( point.clone() );
  23419. }
  23420. this.closed = source.closed;
  23421. this.curveType = source.curveType;
  23422. this.tension = source.tension;
  23423. return this;
  23424. };
  23425. CatmullRomCurve3.prototype.toJSON = function () {
  23426. const data = Curve.prototype.toJSON.call( this );
  23427. data.points = [];
  23428. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23429. const point = this.points[ i ];
  23430. data.points.push( point.toArray() );
  23431. }
  23432. data.closed = this.closed;
  23433. data.curveType = this.curveType;
  23434. data.tension = this.tension;
  23435. return data;
  23436. };
  23437. CatmullRomCurve3.prototype.fromJSON = function ( json ) {
  23438. Curve.prototype.fromJSON.call( this, json );
  23439. this.points = [];
  23440. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23441. const point = json.points[ i ];
  23442. this.points.push( new Vector3().fromArray( point ) );
  23443. }
  23444. this.closed = json.closed;
  23445. this.curveType = json.curveType;
  23446. this.tension = json.tension;
  23447. return this;
  23448. };
  23449. /**
  23450. * Bezier Curves formulas obtained from
  23451. * http://en.wikipedia.org/wiki/Bézier_curve
  23452. */
  23453. function CatmullRom( t, p0, p1, p2, p3 ) {
  23454. const v0 = ( p2 - p0 ) * 0.5;
  23455. const v1 = ( p3 - p1 ) * 0.5;
  23456. const t2 = t * t;
  23457. const t3 = t * t2;
  23458. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23459. }
  23460. //
  23461. function QuadraticBezierP0( t, p ) {
  23462. const k = 1 - t;
  23463. return k * k * p;
  23464. }
  23465. function QuadraticBezierP1( t, p ) {
  23466. return 2 * ( 1 - t ) * t * p;
  23467. }
  23468. function QuadraticBezierP2( t, p ) {
  23469. return t * t * p;
  23470. }
  23471. function QuadraticBezier( t, p0, p1, p2 ) {
  23472. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23473. QuadraticBezierP2( t, p2 );
  23474. }
  23475. //
  23476. function CubicBezierP0( t, p ) {
  23477. const k = 1 - t;
  23478. return k * k * k * p;
  23479. }
  23480. function CubicBezierP1( t, p ) {
  23481. const k = 1 - t;
  23482. return 3 * k * k * t * p;
  23483. }
  23484. function CubicBezierP2( t, p ) {
  23485. return 3 * ( 1 - t ) * t * t * p;
  23486. }
  23487. function CubicBezierP3( t, p ) {
  23488. return t * t * t * p;
  23489. }
  23490. function CubicBezier( t, p0, p1, p2, p3 ) {
  23491. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23492. CubicBezierP3( t, p3 );
  23493. }
  23494. function CubicBezierCurve( v0 = new Vector2$1(), v1 = new Vector2$1(), v2 = new Vector2$1(), v3 = new Vector2$1() ) {
  23495. Curve.call( this );
  23496. this.type = 'CubicBezierCurve';
  23497. this.v0 = v0;
  23498. this.v1 = v1;
  23499. this.v2 = v2;
  23500. this.v3 = v3;
  23501. }
  23502. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  23503. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  23504. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  23505. CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget = new Vector2$1() ) {
  23506. const point = optionalTarget;
  23507. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23508. point.set(
  23509. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23510. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23511. );
  23512. return point;
  23513. };
  23514. CubicBezierCurve.prototype.copy = function ( source ) {
  23515. Curve.prototype.copy.call( this, source );
  23516. this.v0.copy( source.v0 );
  23517. this.v1.copy( source.v1 );
  23518. this.v2.copy( source.v2 );
  23519. this.v3.copy( source.v3 );
  23520. return this;
  23521. };
  23522. CubicBezierCurve.prototype.toJSON = function () {
  23523. const data = Curve.prototype.toJSON.call( this );
  23524. data.v0 = this.v0.toArray();
  23525. data.v1 = this.v1.toArray();
  23526. data.v2 = this.v2.toArray();
  23527. data.v3 = this.v3.toArray();
  23528. return data;
  23529. };
  23530. CubicBezierCurve.prototype.fromJSON = function ( json ) {
  23531. Curve.prototype.fromJSON.call( this, json );
  23532. this.v0.fromArray( json.v0 );
  23533. this.v1.fromArray( json.v1 );
  23534. this.v2.fromArray( json.v2 );
  23535. this.v3.fromArray( json.v3 );
  23536. return this;
  23537. };
  23538. function CubicBezierCurve3( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  23539. Curve.call( this );
  23540. this.type = 'CubicBezierCurve3';
  23541. this.v0 = v0;
  23542. this.v1 = v1;
  23543. this.v2 = v2;
  23544. this.v3 = v3;
  23545. }
  23546. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  23547. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  23548. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  23549. CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget = new Vector3() ) {
  23550. const point = optionalTarget;
  23551. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23552. point.set(
  23553. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23554. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  23555. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  23556. );
  23557. return point;
  23558. };
  23559. CubicBezierCurve3.prototype.copy = function ( source ) {
  23560. Curve.prototype.copy.call( this, source );
  23561. this.v0.copy( source.v0 );
  23562. this.v1.copy( source.v1 );
  23563. this.v2.copy( source.v2 );
  23564. this.v3.copy( source.v3 );
  23565. return this;
  23566. };
  23567. CubicBezierCurve3.prototype.toJSON = function () {
  23568. const data = Curve.prototype.toJSON.call( this );
  23569. data.v0 = this.v0.toArray();
  23570. data.v1 = this.v1.toArray();
  23571. data.v2 = this.v2.toArray();
  23572. data.v3 = this.v3.toArray();
  23573. return data;
  23574. };
  23575. CubicBezierCurve3.prototype.fromJSON = function ( json ) {
  23576. Curve.prototype.fromJSON.call( this, json );
  23577. this.v0.fromArray( json.v0 );
  23578. this.v1.fromArray( json.v1 );
  23579. this.v2.fromArray( json.v2 );
  23580. this.v3.fromArray( json.v3 );
  23581. return this;
  23582. };
  23583. function LineCurve( v1 = new Vector2$1(), v2 = new Vector2$1() ) {
  23584. Curve.call( this );
  23585. this.type = 'LineCurve';
  23586. this.v1 = v1;
  23587. this.v2 = v2;
  23588. }
  23589. LineCurve.prototype = Object.create( Curve.prototype );
  23590. LineCurve.prototype.constructor = LineCurve;
  23591. LineCurve.prototype.isLineCurve = true;
  23592. LineCurve.prototype.getPoint = function ( t, optionalTarget = new Vector2$1() ) {
  23593. const point = optionalTarget;
  23594. if ( t === 1 ) {
  23595. point.copy( this.v2 );
  23596. } else {
  23597. point.copy( this.v2 ).sub( this.v1 );
  23598. point.multiplyScalar( t ).add( this.v1 );
  23599. }
  23600. return point;
  23601. };
  23602. // Line curve is linear, so we can overwrite default getPointAt
  23603. LineCurve.prototype.getPointAt = function ( u, optionalTarget ) {
  23604. return this.getPoint( u, optionalTarget );
  23605. };
  23606. LineCurve.prototype.getTangent = function ( t, optionalTarget ) {
  23607. const tangent = optionalTarget || new Vector2$1();
  23608. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  23609. return tangent;
  23610. };
  23611. LineCurve.prototype.copy = function ( source ) {
  23612. Curve.prototype.copy.call( this, source );
  23613. this.v1.copy( source.v1 );
  23614. this.v2.copy( source.v2 );
  23615. return this;
  23616. };
  23617. LineCurve.prototype.toJSON = function () {
  23618. const data = Curve.prototype.toJSON.call( this );
  23619. data.v1 = this.v1.toArray();
  23620. data.v2 = this.v2.toArray();
  23621. return data;
  23622. };
  23623. LineCurve.prototype.fromJSON = function ( json ) {
  23624. Curve.prototype.fromJSON.call( this, json );
  23625. this.v1.fromArray( json.v1 );
  23626. this.v2.fromArray( json.v2 );
  23627. return this;
  23628. };
  23629. function LineCurve3( v1 = new Vector3(), v2 = new Vector3() ) {
  23630. Curve.call( this );
  23631. this.type = 'LineCurve3';
  23632. this.v1 = v1;
  23633. this.v2 = v2;
  23634. }
  23635. LineCurve3.prototype = Object.create( Curve.prototype );
  23636. LineCurve3.prototype.constructor = LineCurve3;
  23637. LineCurve3.prototype.isLineCurve3 = true;
  23638. LineCurve3.prototype.getPoint = function ( t, optionalTarget = new Vector3() ) {
  23639. const point = optionalTarget;
  23640. if ( t === 1 ) {
  23641. point.copy( this.v2 );
  23642. } else {
  23643. point.copy( this.v2 ).sub( this.v1 );
  23644. point.multiplyScalar( t ).add( this.v1 );
  23645. }
  23646. return point;
  23647. };
  23648. // Line curve is linear, so we can overwrite default getPointAt
  23649. LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) {
  23650. return this.getPoint( u, optionalTarget );
  23651. };
  23652. LineCurve3.prototype.copy = function ( source ) {
  23653. Curve.prototype.copy.call( this, source );
  23654. this.v1.copy( source.v1 );
  23655. this.v2.copy( source.v2 );
  23656. return this;
  23657. };
  23658. LineCurve3.prototype.toJSON = function () {
  23659. const data = Curve.prototype.toJSON.call( this );
  23660. data.v1 = this.v1.toArray();
  23661. data.v2 = this.v2.toArray();
  23662. return data;
  23663. };
  23664. LineCurve3.prototype.fromJSON = function ( json ) {
  23665. Curve.prototype.fromJSON.call( this, json );
  23666. this.v1.fromArray( json.v1 );
  23667. this.v2.fromArray( json.v2 );
  23668. return this;
  23669. };
  23670. function QuadraticBezierCurve( v0 = new Vector2$1(), v1 = new Vector2$1(), v2 = new Vector2$1() ) {
  23671. Curve.call( this );
  23672. this.type = 'QuadraticBezierCurve';
  23673. this.v0 = v0;
  23674. this.v1 = v1;
  23675. this.v2 = v2;
  23676. }
  23677. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  23678. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  23679. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  23680. QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget = new Vector2$1() ) {
  23681. const point = optionalTarget;
  23682. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23683. point.set(
  23684. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23685. QuadraticBezier( t, v0.y, v1.y, v2.y )
  23686. );
  23687. return point;
  23688. };
  23689. QuadraticBezierCurve.prototype.copy = function ( source ) {
  23690. Curve.prototype.copy.call( this, source );
  23691. this.v0.copy( source.v0 );
  23692. this.v1.copy( source.v1 );
  23693. this.v2.copy( source.v2 );
  23694. return this;
  23695. };
  23696. QuadraticBezierCurve.prototype.toJSON = function () {
  23697. const data = Curve.prototype.toJSON.call( this );
  23698. data.v0 = this.v0.toArray();
  23699. data.v1 = this.v1.toArray();
  23700. data.v2 = this.v2.toArray();
  23701. return data;
  23702. };
  23703. QuadraticBezierCurve.prototype.fromJSON = function ( json ) {
  23704. Curve.prototype.fromJSON.call( this, json );
  23705. this.v0.fromArray( json.v0 );
  23706. this.v1.fromArray( json.v1 );
  23707. this.v2.fromArray( json.v2 );
  23708. return this;
  23709. };
  23710. function QuadraticBezierCurve3( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  23711. Curve.call( this );
  23712. this.type = 'QuadraticBezierCurve3';
  23713. this.v0 = v0;
  23714. this.v1 = v1;
  23715. this.v2 = v2;
  23716. }
  23717. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  23718. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  23719. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  23720. QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget = new Vector3() ) {
  23721. const point = optionalTarget;
  23722. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23723. point.set(
  23724. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23725. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  23726. QuadraticBezier( t, v0.z, v1.z, v2.z )
  23727. );
  23728. return point;
  23729. };
  23730. QuadraticBezierCurve3.prototype.copy = function ( source ) {
  23731. Curve.prototype.copy.call( this, source );
  23732. this.v0.copy( source.v0 );
  23733. this.v1.copy( source.v1 );
  23734. this.v2.copy( source.v2 );
  23735. return this;
  23736. };
  23737. QuadraticBezierCurve3.prototype.toJSON = function () {
  23738. const data = Curve.prototype.toJSON.call( this );
  23739. data.v0 = this.v0.toArray();
  23740. data.v1 = this.v1.toArray();
  23741. data.v2 = this.v2.toArray();
  23742. return data;
  23743. };
  23744. QuadraticBezierCurve3.prototype.fromJSON = function ( json ) {
  23745. Curve.prototype.fromJSON.call( this, json );
  23746. this.v0.fromArray( json.v0 );
  23747. this.v1.fromArray( json.v1 );
  23748. this.v2.fromArray( json.v2 );
  23749. return this;
  23750. };
  23751. function SplineCurve( points = [] ) {
  23752. Curve.call( this );
  23753. this.type = 'SplineCurve';
  23754. this.points = points;
  23755. }
  23756. SplineCurve.prototype = Object.create( Curve.prototype );
  23757. SplineCurve.prototype.constructor = SplineCurve;
  23758. SplineCurve.prototype.isSplineCurve = true;
  23759. SplineCurve.prototype.getPoint = function ( t, optionalTarget = new Vector2$1() ) {
  23760. const point = optionalTarget;
  23761. const points = this.points;
  23762. const p = ( points.length - 1 ) * t;
  23763. const intPoint = Math.floor( p );
  23764. const weight = p - intPoint;
  23765. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  23766. const p1 = points[ intPoint ];
  23767. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  23768. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  23769. point.set(
  23770. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  23771. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  23772. );
  23773. return point;
  23774. };
  23775. SplineCurve.prototype.copy = function ( source ) {
  23776. Curve.prototype.copy.call( this, source );
  23777. this.points = [];
  23778. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23779. const point = source.points[ i ];
  23780. this.points.push( point.clone() );
  23781. }
  23782. return this;
  23783. };
  23784. SplineCurve.prototype.toJSON = function () {
  23785. const data = Curve.prototype.toJSON.call( this );
  23786. data.points = [];
  23787. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23788. const point = this.points[ i ];
  23789. data.points.push( point.toArray() );
  23790. }
  23791. return data;
  23792. };
  23793. SplineCurve.prototype.fromJSON = function ( json ) {
  23794. Curve.prototype.fromJSON.call( this, json );
  23795. this.points = [];
  23796. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23797. const point = json.points[ i ];
  23798. this.points.push( new Vector2$1().fromArray( point ) );
  23799. }
  23800. return this;
  23801. };
  23802. var Curves = /*#__PURE__*/Object.freeze({
  23803. __proto__: null,
  23804. ArcCurve: ArcCurve,
  23805. CatmullRomCurve3: CatmullRomCurve3,
  23806. CubicBezierCurve: CubicBezierCurve,
  23807. CubicBezierCurve3: CubicBezierCurve3,
  23808. EllipseCurve: EllipseCurve,
  23809. LineCurve: LineCurve,
  23810. LineCurve3: LineCurve3,
  23811. QuadraticBezierCurve: QuadraticBezierCurve,
  23812. QuadraticBezierCurve3: QuadraticBezierCurve3,
  23813. SplineCurve: SplineCurve
  23814. });
  23815. /**************************************************************
  23816. * Curved Path - a curve path is simply a array of connected
  23817. * curves, but retains the api of a curve
  23818. **************************************************************/
  23819. function CurvePath() {
  23820. Curve.call( this );
  23821. this.type = 'CurvePath';
  23822. this.curves = [];
  23823. this.autoClose = false; // Automatically closes the path
  23824. }
  23825. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  23826. constructor: CurvePath,
  23827. add: function ( curve ) {
  23828. this.curves.push( curve );
  23829. },
  23830. closePath: function () {
  23831. // Add a line curve if start and end of lines are not connected
  23832. const startPoint = this.curves[ 0 ].getPoint( 0 );
  23833. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  23834. if ( ! startPoint.equals( endPoint ) ) {
  23835. this.curves.push( new LineCurve( endPoint, startPoint ) );
  23836. }
  23837. },
  23838. // To get accurate point with reference to
  23839. // entire path distance at time t,
  23840. // following has to be done:
  23841. // 1. Length of each sub path have to be known
  23842. // 2. Locate and identify type of curve
  23843. // 3. Get t for the curve
  23844. // 4. Return curve.getPointAt(t')
  23845. getPoint: function ( t ) {
  23846. const d = t * this.getLength();
  23847. const curveLengths = this.getCurveLengths();
  23848. let i = 0;
  23849. // To think about boundaries points.
  23850. while ( i < curveLengths.length ) {
  23851. if ( curveLengths[ i ] >= d ) {
  23852. const diff = curveLengths[ i ] - d;
  23853. const curve = this.curves[ i ];
  23854. const segmentLength = curve.getLength();
  23855. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  23856. return curve.getPointAt( u );
  23857. }
  23858. i ++;
  23859. }
  23860. return null;
  23861. // loop where sum != 0, sum > d , sum+1 <d
  23862. },
  23863. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  23864. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  23865. // getPoint() depends on getLength
  23866. getLength: function () {
  23867. const lens = this.getCurveLengths();
  23868. return lens[ lens.length - 1 ];
  23869. },
  23870. // cacheLengths must be recalculated.
  23871. updateArcLengths: function () {
  23872. this.needsUpdate = true;
  23873. this.cacheLengths = null;
  23874. this.getCurveLengths();
  23875. },
  23876. // Compute lengths and cache them
  23877. // We cannot overwrite getLengths() because UtoT mapping uses it.
  23878. getCurveLengths: function () {
  23879. // We use cache values if curves and cache array are same length
  23880. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  23881. return this.cacheLengths;
  23882. }
  23883. // Get length of sub-curve
  23884. // Push sums into cached array
  23885. const lengths = [];
  23886. let sums = 0;
  23887. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  23888. sums += this.curves[ i ].getLength();
  23889. lengths.push( sums );
  23890. }
  23891. this.cacheLengths = lengths;
  23892. return lengths;
  23893. },
  23894. getSpacedPoints: function ( divisions = 40 ) {
  23895. const points = [];
  23896. for ( let i = 0; i <= divisions; i ++ ) {
  23897. points.push( this.getPoint( i / divisions ) );
  23898. }
  23899. if ( this.autoClose ) {
  23900. points.push( points[ 0 ] );
  23901. }
  23902. return points;
  23903. },
  23904. getPoints: function ( divisions = 12 ) {
  23905. const points = [];
  23906. let last;
  23907. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  23908. const curve = curves[ i ];
  23909. const resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  23910. : ( curve && ( curve.isLineCurve || curve.isLineCurve3 ) ) ? 1
  23911. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  23912. : divisions;
  23913. const pts = curve.getPoints( resolution );
  23914. for ( let j = 0; j < pts.length; j ++ ) {
  23915. const point = pts[ j ];
  23916. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  23917. points.push( point );
  23918. last = point;
  23919. }
  23920. }
  23921. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  23922. points.push( points[ 0 ] );
  23923. }
  23924. return points;
  23925. },
  23926. copy: function ( source ) {
  23927. Curve.prototype.copy.call( this, source );
  23928. this.curves = [];
  23929. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  23930. const curve = source.curves[ i ];
  23931. this.curves.push( curve.clone() );
  23932. }
  23933. this.autoClose = source.autoClose;
  23934. return this;
  23935. },
  23936. toJSON: function () {
  23937. const data = Curve.prototype.toJSON.call( this );
  23938. data.autoClose = this.autoClose;
  23939. data.curves = [];
  23940. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  23941. const curve = this.curves[ i ];
  23942. data.curves.push( curve.toJSON() );
  23943. }
  23944. return data;
  23945. },
  23946. fromJSON: function ( json ) {
  23947. Curve.prototype.fromJSON.call( this, json );
  23948. this.autoClose = json.autoClose;
  23949. this.curves = [];
  23950. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  23951. const curve = json.curves[ i ];
  23952. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  23953. }
  23954. return this;
  23955. }
  23956. } );
  23957. function Path( points ) {
  23958. CurvePath.call( this );
  23959. this.type = 'Path';
  23960. this.currentPoint = new Vector2$1();
  23961. if ( points ) {
  23962. this.setFromPoints( points );
  23963. }
  23964. }
  23965. Path.prototype = Object.assign( Object.create( CurvePath.prototype ), {
  23966. constructor: Path,
  23967. setFromPoints: function ( points ) {
  23968. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  23969. for ( let i = 1, l = points.length; i < l; i ++ ) {
  23970. this.lineTo( points[ i ].x, points[ i ].y );
  23971. }
  23972. return this;
  23973. },
  23974. moveTo: function ( x, y ) {
  23975. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  23976. return this;
  23977. },
  23978. lineTo: function ( x, y ) {
  23979. const curve = new LineCurve( this.currentPoint.clone(), new Vector2$1( x, y ) );
  23980. this.curves.push( curve );
  23981. this.currentPoint.set( x, y );
  23982. return this;
  23983. },
  23984. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  23985. const curve = new QuadraticBezierCurve(
  23986. this.currentPoint.clone(),
  23987. new Vector2$1( aCPx, aCPy ),
  23988. new Vector2$1( aX, aY )
  23989. );
  23990. this.curves.push( curve );
  23991. this.currentPoint.set( aX, aY );
  23992. return this;
  23993. },
  23994. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  23995. const curve = new CubicBezierCurve(
  23996. this.currentPoint.clone(),
  23997. new Vector2$1( aCP1x, aCP1y ),
  23998. new Vector2$1( aCP2x, aCP2y ),
  23999. new Vector2$1( aX, aY )
  24000. );
  24001. this.curves.push( curve );
  24002. this.currentPoint.set( aX, aY );
  24003. return this;
  24004. },
  24005. splineThru: function ( pts /*Array of Vector*/ ) {
  24006. const npts = [ this.currentPoint.clone() ].concat( pts );
  24007. const curve = new SplineCurve( npts );
  24008. this.curves.push( curve );
  24009. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24010. return this;
  24011. },
  24012. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24013. const x0 = this.currentPoint.x;
  24014. const y0 = this.currentPoint.y;
  24015. this.absarc( aX + x0, aY + y0, aRadius,
  24016. aStartAngle, aEndAngle, aClockwise );
  24017. return this;
  24018. },
  24019. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24020. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24021. return this;
  24022. },
  24023. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24024. const x0 = this.currentPoint.x;
  24025. const y0 = this.currentPoint.y;
  24026. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24027. return this;
  24028. },
  24029. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24030. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24031. if ( this.curves.length > 0 ) {
  24032. // if a previous curve is present, attempt to join
  24033. const firstPoint = curve.getPoint( 0 );
  24034. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24035. this.lineTo( firstPoint.x, firstPoint.y );
  24036. }
  24037. }
  24038. this.curves.push( curve );
  24039. const lastPoint = curve.getPoint( 1 );
  24040. this.currentPoint.copy( lastPoint );
  24041. return this;
  24042. },
  24043. copy: function ( source ) {
  24044. CurvePath.prototype.copy.call( this, source );
  24045. this.currentPoint.copy( source.currentPoint );
  24046. return this;
  24047. },
  24048. toJSON: function () {
  24049. const data = CurvePath.prototype.toJSON.call( this );
  24050. data.currentPoint = this.currentPoint.toArray();
  24051. return data;
  24052. },
  24053. fromJSON: function ( json ) {
  24054. CurvePath.prototype.fromJSON.call( this, json );
  24055. this.currentPoint.fromArray( json.currentPoint );
  24056. return this;
  24057. }
  24058. } );
  24059. function Shape( points ) {
  24060. Path.call( this, points );
  24061. this.uuid = MathUtils.generateUUID();
  24062. this.type = 'Shape';
  24063. this.holes = [];
  24064. }
  24065. Shape.prototype = Object.assign( Object.create( Path.prototype ), {
  24066. constructor: Shape,
  24067. getPointsHoles: function ( divisions ) {
  24068. const holesPts = [];
  24069. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24070. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24071. }
  24072. return holesPts;
  24073. },
  24074. // get points of shape and holes (keypoints based on segments parameter)
  24075. extractPoints: function ( divisions ) {
  24076. return {
  24077. shape: this.getPoints( divisions ),
  24078. holes: this.getPointsHoles( divisions )
  24079. };
  24080. },
  24081. copy: function ( source ) {
  24082. Path.prototype.copy.call( this, source );
  24083. this.holes = [];
  24084. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  24085. const hole = source.holes[ i ];
  24086. this.holes.push( hole.clone() );
  24087. }
  24088. return this;
  24089. },
  24090. toJSON: function () {
  24091. const data = Path.prototype.toJSON.call( this );
  24092. data.uuid = this.uuid;
  24093. data.holes = [];
  24094. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  24095. const hole = this.holes[ i ];
  24096. data.holes.push( hole.toJSON() );
  24097. }
  24098. return data;
  24099. },
  24100. fromJSON: function ( json ) {
  24101. Path.prototype.fromJSON.call( this, json );
  24102. this.uuid = json.uuid;
  24103. this.holes = [];
  24104. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  24105. const hole = json.holes[ i ];
  24106. this.holes.push( new Path().fromJSON( hole ) );
  24107. }
  24108. return this;
  24109. }
  24110. } );
  24111. function Light( color, intensity = 1 ) {
  24112. Object3D.call( this );
  24113. this.type = 'Light';
  24114. this.color = new Color( color );
  24115. this.intensity = intensity;
  24116. }
  24117. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  24118. constructor: Light,
  24119. isLight: true,
  24120. copy: function ( source ) {
  24121. Object3D.prototype.copy.call( this, source );
  24122. this.color.copy( source.color );
  24123. this.intensity = source.intensity;
  24124. return this;
  24125. },
  24126. toJSON: function ( meta ) {
  24127. const data = Object3D.prototype.toJSON.call( this, meta );
  24128. data.object.color = this.color.getHex();
  24129. data.object.intensity = this.intensity;
  24130. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24131. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24132. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24133. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24134. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24135. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24136. return data;
  24137. }
  24138. } );
  24139. function HemisphereLight( skyColor, groundColor, intensity ) {
  24140. Light.call( this, skyColor, intensity );
  24141. this.type = 'HemisphereLight';
  24142. this.position.copy( Object3D.DefaultUp );
  24143. this.updateMatrix();
  24144. this.groundColor = new Color( groundColor );
  24145. }
  24146. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24147. constructor: HemisphereLight,
  24148. isHemisphereLight: true,
  24149. copy: function ( source ) {
  24150. Light.prototype.copy.call( this, source );
  24151. this.groundColor.copy( source.groundColor );
  24152. return this;
  24153. }
  24154. } );
  24155. function LightShadow( camera ) {
  24156. this.camera = camera;
  24157. this.bias = 0;
  24158. this.normalBias = 0;
  24159. this.radius = 1;
  24160. this.mapSize = new Vector2$1( 512, 512 );
  24161. this.map = null;
  24162. this.mapPass = null;
  24163. this.matrix = new Matrix4();
  24164. this.autoUpdate = true;
  24165. this.needsUpdate = false;
  24166. this._frustum = new Frustum();
  24167. this._frameExtents = new Vector2$1( 1, 1 );
  24168. this._viewportCount = 1;
  24169. this._viewports = [
  24170. new Vector4( 0, 0, 1, 1 )
  24171. ];
  24172. }
  24173. Object.assign( LightShadow.prototype, {
  24174. _projScreenMatrix: new Matrix4(),
  24175. _lightPositionWorld: new Vector3(),
  24176. _lookTarget: new Vector3(),
  24177. getViewportCount: function () {
  24178. return this._viewportCount;
  24179. },
  24180. getFrustum: function () {
  24181. return this._frustum;
  24182. },
  24183. updateMatrices: function ( light ) {
  24184. const shadowCamera = this.camera,
  24185. shadowMatrix = this.matrix,
  24186. projScreenMatrix = this._projScreenMatrix,
  24187. lookTarget = this._lookTarget,
  24188. lightPositionWorld = this._lightPositionWorld;
  24189. lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24190. shadowCamera.position.copy( lightPositionWorld );
  24191. lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  24192. shadowCamera.lookAt( lookTarget );
  24193. shadowCamera.updateMatrixWorld();
  24194. projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  24195. this._frustum.setFromProjectionMatrix( projScreenMatrix );
  24196. shadowMatrix.set(
  24197. 0.5, 0.0, 0.0, 0.5,
  24198. 0.0, 0.5, 0.0, 0.5,
  24199. 0.0, 0.0, 0.5, 0.5,
  24200. 0.0, 0.0, 0.0, 1.0
  24201. );
  24202. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  24203. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  24204. },
  24205. getViewport: function ( viewportIndex ) {
  24206. return this._viewports[ viewportIndex ];
  24207. },
  24208. getFrameExtents: function () {
  24209. return this._frameExtents;
  24210. },
  24211. copy: function ( source ) {
  24212. this.camera = source.camera.clone();
  24213. this.bias = source.bias;
  24214. this.radius = source.radius;
  24215. this.mapSize.copy( source.mapSize );
  24216. return this;
  24217. },
  24218. clone: function () {
  24219. return new this.constructor().copy( this );
  24220. },
  24221. toJSON: function () {
  24222. const object = {};
  24223. if ( this.bias !== 0 ) object.bias = this.bias;
  24224. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  24225. if ( this.radius !== 1 ) object.radius = this.radius;
  24226. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24227. object.camera = this.camera.toJSON( false ).object;
  24228. delete object.camera.matrix;
  24229. return object;
  24230. }
  24231. } );
  24232. function SpotLightShadow() {
  24233. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24234. this.focus = 1;
  24235. }
  24236. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  24237. constructor: SpotLightShadow,
  24238. isSpotLightShadow: true,
  24239. updateMatrices: function ( light ) {
  24240. const camera = this.camera;
  24241. const fov = MathUtils.RAD2DEG * 2 * light.angle * this.focus;
  24242. const aspect = this.mapSize.width / this.mapSize.height;
  24243. const far = light.distance || camera.far;
  24244. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24245. camera.fov = fov;
  24246. camera.aspect = aspect;
  24247. camera.far = far;
  24248. camera.updateProjectionMatrix();
  24249. }
  24250. LightShadow.prototype.updateMatrices.call( this, light );
  24251. }
  24252. } );
  24253. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  24254. Light.call( this, color, intensity );
  24255. this.type = 'SpotLight';
  24256. this.position.copy( Object3D.DefaultUp );
  24257. this.updateMatrix();
  24258. this.target = new Object3D();
  24259. Object.defineProperty( this, 'power', {
  24260. get: function () {
  24261. // intensity = power per solid angle.
  24262. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24263. return this.intensity * Math.PI;
  24264. },
  24265. set: function ( power ) {
  24266. // intensity = power per solid angle.
  24267. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24268. this.intensity = power / Math.PI;
  24269. }
  24270. } );
  24271. this.distance = ( distance !== undefined ) ? distance : 0;
  24272. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  24273. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  24274. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  24275. this.shadow = new SpotLightShadow();
  24276. }
  24277. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24278. constructor: SpotLight,
  24279. isSpotLight: true,
  24280. copy: function ( source ) {
  24281. Light.prototype.copy.call( this, source );
  24282. this.distance = source.distance;
  24283. this.angle = source.angle;
  24284. this.penumbra = source.penumbra;
  24285. this.decay = source.decay;
  24286. this.target = source.target.clone();
  24287. this.shadow = source.shadow.clone();
  24288. return this;
  24289. }
  24290. } );
  24291. function PointLightShadow() {
  24292. LightShadow.call( this, new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24293. this._frameExtents = new Vector2$1( 4, 2 );
  24294. this._viewportCount = 6;
  24295. this._viewports = [
  24296. // These viewports map a cube-map onto a 2D texture with the
  24297. // following orientation:
  24298. //
  24299. // xzXZ
  24300. // y Y
  24301. //
  24302. // X - Positive x direction
  24303. // x - Negative x direction
  24304. // Y - Positive y direction
  24305. // y - Negative y direction
  24306. // Z - Positive z direction
  24307. // z - Negative z direction
  24308. // positive X
  24309. new Vector4( 2, 1, 1, 1 ),
  24310. // negative X
  24311. new Vector4( 0, 1, 1, 1 ),
  24312. // positive Z
  24313. new Vector4( 3, 1, 1, 1 ),
  24314. // negative Z
  24315. new Vector4( 1, 1, 1, 1 ),
  24316. // positive Y
  24317. new Vector4( 3, 0, 1, 1 ),
  24318. // negative Y
  24319. new Vector4( 1, 0, 1, 1 )
  24320. ];
  24321. this._cubeDirections = [
  24322. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  24323. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  24324. ];
  24325. this._cubeUps = [
  24326. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  24327. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  24328. ];
  24329. }
  24330. PointLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  24331. constructor: PointLightShadow,
  24332. isPointLightShadow: true,
  24333. updateMatrices: function ( light, viewportIndex = 0 ) {
  24334. const camera = this.camera,
  24335. shadowMatrix = this.matrix,
  24336. lightPositionWorld = this._lightPositionWorld,
  24337. lookTarget = this._lookTarget,
  24338. projScreenMatrix = this._projScreenMatrix;
  24339. lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24340. camera.position.copy( lightPositionWorld );
  24341. lookTarget.copy( camera.position );
  24342. lookTarget.add( this._cubeDirections[ viewportIndex ] );
  24343. camera.up.copy( this._cubeUps[ viewportIndex ] );
  24344. camera.lookAt( lookTarget );
  24345. camera.updateMatrixWorld();
  24346. shadowMatrix.makeTranslation( - lightPositionWorld.x, - lightPositionWorld.y, - lightPositionWorld.z );
  24347. projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  24348. this._frustum.setFromProjectionMatrix( projScreenMatrix );
  24349. }
  24350. } );
  24351. function PointLight( color, intensity, distance, decay ) {
  24352. Light.call( this, color, intensity );
  24353. this.type = 'PointLight';
  24354. Object.defineProperty( this, 'power', {
  24355. get: function () {
  24356. // intensity = power per solid angle.
  24357. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24358. return this.intensity * 4 * Math.PI;
  24359. },
  24360. set: function ( power ) {
  24361. // intensity = power per solid angle.
  24362. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  24363. this.intensity = power / ( 4 * Math.PI );
  24364. }
  24365. } );
  24366. this.distance = ( distance !== undefined ) ? distance : 0;
  24367. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  24368. this.shadow = new PointLightShadow();
  24369. }
  24370. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24371. constructor: PointLight,
  24372. isPointLight: true,
  24373. copy: function ( source ) {
  24374. Light.prototype.copy.call( this, source );
  24375. this.distance = source.distance;
  24376. this.decay = source.decay;
  24377. this.shadow = source.shadow.clone();
  24378. return this;
  24379. }
  24380. } );
  24381. function OrthographicCamera( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  24382. Camera.call( this );
  24383. this.type = 'OrthographicCamera';
  24384. this.zoom = 1;
  24385. this.view = null;
  24386. this.left = left;
  24387. this.right = right;
  24388. this.top = top;
  24389. this.bottom = bottom;
  24390. this.near = near;
  24391. this.far = far;
  24392. this.updateProjectionMatrix();
  24393. }
  24394. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  24395. constructor: OrthographicCamera,
  24396. isOrthographicCamera: true,
  24397. copy: function ( source, recursive ) {
  24398. Camera.prototype.copy.call( this, source, recursive );
  24399. this.left = source.left;
  24400. this.right = source.right;
  24401. this.top = source.top;
  24402. this.bottom = source.bottom;
  24403. this.near = source.near;
  24404. this.far = source.far;
  24405. this.zoom = source.zoom;
  24406. this.view = source.view === null ? null : Object.assign( {}, source.view );
  24407. return this;
  24408. },
  24409. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  24410. if ( this.view === null ) {
  24411. this.view = {
  24412. enabled: true,
  24413. fullWidth: 1,
  24414. fullHeight: 1,
  24415. offsetX: 0,
  24416. offsetY: 0,
  24417. width: 1,
  24418. height: 1
  24419. };
  24420. }
  24421. this.view.enabled = true;
  24422. this.view.fullWidth = fullWidth;
  24423. this.view.fullHeight = fullHeight;
  24424. this.view.offsetX = x;
  24425. this.view.offsetY = y;
  24426. this.view.width = width;
  24427. this.view.height = height;
  24428. this.updateProjectionMatrix();
  24429. },
  24430. clearViewOffset: function () {
  24431. if ( this.view !== null ) {
  24432. this.view.enabled = false;
  24433. }
  24434. this.updateProjectionMatrix();
  24435. },
  24436. updateProjectionMatrix: function () {
  24437. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  24438. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  24439. const cx = ( this.right + this.left ) / 2;
  24440. const cy = ( this.top + this.bottom ) / 2;
  24441. let left = cx - dx;
  24442. let right = cx + dx;
  24443. let top = cy + dy;
  24444. let bottom = cy - dy;
  24445. if ( this.view !== null && this.view.enabled ) {
  24446. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  24447. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  24448. left += scaleW * this.view.offsetX;
  24449. right = left + scaleW * this.view.width;
  24450. top -= scaleH * this.view.offsetY;
  24451. bottom = top - scaleH * this.view.height;
  24452. }
  24453. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  24454. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  24455. },
  24456. toJSON: function ( meta ) {
  24457. const data = Object3D.prototype.toJSON.call( this, meta );
  24458. data.object.zoom = this.zoom;
  24459. data.object.left = this.left;
  24460. data.object.right = this.right;
  24461. data.object.top = this.top;
  24462. data.object.bottom = this.bottom;
  24463. data.object.near = this.near;
  24464. data.object.far = this.far;
  24465. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  24466. return data;
  24467. }
  24468. } );
  24469. function DirectionalLightShadow() {
  24470. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  24471. }
  24472. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  24473. constructor: DirectionalLightShadow,
  24474. isDirectionalLightShadow: true,
  24475. updateMatrices: function ( light ) {
  24476. LightShadow.prototype.updateMatrices.call( this, light );
  24477. }
  24478. } );
  24479. function DirectionalLight( color, intensity ) {
  24480. Light.call( this, color, intensity );
  24481. this.type = 'DirectionalLight';
  24482. this.position.copy( Object3D.DefaultUp );
  24483. this.updateMatrix();
  24484. this.target = new Object3D();
  24485. this.shadow = new DirectionalLightShadow();
  24486. }
  24487. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24488. constructor: DirectionalLight,
  24489. isDirectionalLight: true,
  24490. copy: function ( source ) {
  24491. Light.prototype.copy.call( this, source );
  24492. this.target = source.target.clone();
  24493. this.shadow = source.shadow.clone();
  24494. return this;
  24495. }
  24496. } );
  24497. function AmbientLight( color, intensity ) {
  24498. Light.call( this, color, intensity );
  24499. this.type = 'AmbientLight';
  24500. }
  24501. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24502. constructor: AmbientLight,
  24503. isAmbientLight: true
  24504. } );
  24505. function RectAreaLight( color, intensity, width, height ) {
  24506. Light.call( this, color, intensity );
  24507. this.type = 'RectAreaLight';
  24508. this.width = ( width !== undefined ) ? width : 10;
  24509. this.height = ( height !== undefined ) ? height : 10;
  24510. }
  24511. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24512. constructor: RectAreaLight,
  24513. isRectAreaLight: true,
  24514. copy: function ( source ) {
  24515. Light.prototype.copy.call( this, source );
  24516. this.width = source.width;
  24517. this.height = source.height;
  24518. return this;
  24519. },
  24520. toJSON: function ( meta ) {
  24521. const data = Light.prototype.toJSON.call( this, meta );
  24522. data.object.width = this.width;
  24523. data.object.height = this.height;
  24524. return data;
  24525. }
  24526. } );
  24527. /**
  24528. * Primary reference:
  24529. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24530. *
  24531. * Secondary reference:
  24532. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24533. */
  24534. // 3-band SH defined by 9 coefficients
  24535. class SphericalHarmonics3 {
  24536. constructor() {
  24537. Object.defineProperty( this, 'isSphericalHarmonics3', { value: true } );
  24538. this.coefficients = [];
  24539. for ( let i = 0; i < 9; i ++ ) {
  24540. this.coefficients.push( new Vector3() );
  24541. }
  24542. }
  24543. set( coefficients ) {
  24544. for ( let i = 0; i < 9; i ++ ) {
  24545. this.coefficients[ i ].copy( coefficients[ i ] );
  24546. }
  24547. return this;
  24548. }
  24549. zero() {
  24550. for ( let i = 0; i < 9; i ++ ) {
  24551. this.coefficients[ i ].set( 0, 0, 0 );
  24552. }
  24553. return this;
  24554. }
  24555. // get the radiance in the direction of the normal
  24556. // target is a Vector3
  24557. getAt( normal, target ) {
  24558. // normal is assumed to be unit length
  24559. const x = normal.x, y = normal.y, z = normal.z;
  24560. const coeff = this.coefficients;
  24561. // band 0
  24562. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  24563. // band 1
  24564. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  24565. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  24566. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  24567. // band 2
  24568. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  24569. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  24570. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  24571. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  24572. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  24573. return target;
  24574. }
  24575. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24576. // target is a Vector3
  24577. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24578. getIrradianceAt( normal, target ) {
  24579. // normal is assumed to be unit length
  24580. const x = normal.x, y = normal.y, z = normal.z;
  24581. const coeff = this.coefficients;
  24582. // band 0
  24583. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  24584. // band 1
  24585. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  24586. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  24587. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  24588. // band 2
  24589. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  24590. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  24591. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  24592. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  24593. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  24594. return target;
  24595. }
  24596. add( sh ) {
  24597. for ( let i = 0; i < 9; i ++ ) {
  24598. this.coefficients[ i ].add( sh.coefficients[ i ] );
  24599. }
  24600. return this;
  24601. }
  24602. addScaledSH( sh, s ) {
  24603. for ( let i = 0; i < 9; i ++ ) {
  24604. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  24605. }
  24606. return this;
  24607. }
  24608. scale( s ) {
  24609. for ( let i = 0; i < 9; i ++ ) {
  24610. this.coefficients[ i ].multiplyScalar( s );
  24611. }
  24612. return this;
  24613. }
  24614. lerp( sh, alpha ) {
  24615. for ( let i = 0; i < 9; i ++ ) {
  24616. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  24617. }
  24618. return this;
  24619. }
  24620. equals( sh ) {
  24621. for ( let i = 0; i < 9; i ++ ) {
  24622. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  24623. return false;
  24624. }
  24625. }
  24626. return true;
  24627. }
  24628. copy( sh ) {
  24629. return this.set( sh.coefficients );
  24630. }
  24631. clone() {
  24632. return new this.constructor().copy( this );
  24633. }
  24634. fromArray( array, offset = 0 ) {
  24635. const coefficients = this.coefficients;
  24636. for ( let i = 0; i < 9; i ++ ) {
  24637. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  24638. }
  24639. return this;
  24640. }
  24641. toArray( array = [], offset = 0 ) {
  24642. const coefficients = this.coefficients;
  24643. for ( let i = 0; i < 9; i ++ ) {
  24644. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  24645. }
  24646. return array;
  24647. }
  24648. // evaluate the basis functions
  24649. // shBasis is an Array[ 9 ]
  24650. static getBasisAt( normal, shBasis ) {
  24651. // normal is assumed to be unit length
  24652. const x = normal.x, y = normal.y, z = normal.z;
  24653. // band 0
  24654. shBasis[ 0 ] = 0.282095;
  24655. // band 1
  24656. shBasis[ 1 ] = 0.488603 * y;
  24657. shBasis[ 2 ] = 0.488603 * z;
  24658. shBasis[ 3 ] = 0.488603 * x;
  24659. // band 2
  24660. shBasis[ 4 ] = 1.092548 * x * y;
  24661. shBasis[ 5 ] = 1.092548 * y * z;
  24662. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  24663. shBasis[ 7 ] = 1.092548 * x * z;
  24664. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  24665. }
  24666. }
  24667. function LightProbe( sh, intensity ) {
  24668. Light.call( this, undefined, intensity );
  24669. this.type = 'LightProbe';
  24670. this.sh = ( sh !== undefined ) ? sh : new SphericalHarmonics3();
  24671. }
  24672. LightProbe.prototype = Object.assign( Object.create( Light.prototype ), {
  24673. constructor: LightProbe,
  24674. isLightProbe: true,
  24675. copy: function ( source ) {
  24676. Light.prototype.copy.call( this, source );
  24677. this.sh.copy( source.sh );
  24678. return this;
  24679. },
  24680. fromJSON: function ( json ) {
  24681. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24682. this.sh.fromArray( json.sh );
  24683. return this;
  24684. },
  24685. toJSON: function ( meta ) {
  24686. const data = Light.prototype.toJSON.call( this, meta );
  24687. data.object.sh = this.sh.toArray();
  24688. return data;
  24689. }
  24690. } );
  24691. function MaterialLoader( manager ) {
  24692. Loader.call( this, manager );
  24693. this.textures = {};
  24694. }
  24695. MaterialLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  24696. constructor: MaterialLoader,
  24697. load: function ( url, onLoad, onProgress, onError ) {
  24698. const scope = this;
  24699. const loader = new FileLoader( scope.manager );
  24700. loader.setPath( scope.path );
  24701. loader.setRequestHeader( scope.requestHeader );
  24702. loader.setWithCredentials( scope.withCredentials );
  24703. loader.load( url, function ( text ) {
  24704. try {
  24705. onLoad( scope.parse( JSON.parse( text ) ) );
  24706. } catch ( e ) {
  24707. if ( onError ) {
  24708. onError( e );
  24709. } else {
  24710. console.error( e );
  24711. }
  24712. scope.manager.itemError( url );
  24713. }
  24714. }, onProgress, onError );
  24715. },
  24716. parse: function ( json ) {
  24717. const textures = this.textures;
  24718. function getTexture( name ) {
  24719. if ( textures[ name ] === undefined ) {
  24720. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  24721. }
  24722. return textures[ name ];
  24723. }
  24724. const material = new Materials[ json.type ]();
  24725. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  24726. if ( json.name !== undefined ) material.name = json.name;
  24727. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  24728. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  24729. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  24730. if ( json.sheen !== undefined ) material.sheen = new Color().setHex( json.sheen );
  24731. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  24732. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  24733. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  24734. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  24735. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  24736. if ( json.fog !== undefined ) material.fog = json.fog;
  24737. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  24738. if ( json.blending !== undefined ) material.blending = json.blending;
  24739. if ( json.combine !== undefined ) material.combine = json.combine;
  24740. if ( json.side !== undefined ) material.side = json.side;
  24741. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24742. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24743. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24744. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24745. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24746. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24747. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  24748. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  24749. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  24750. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  24751. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  24752. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  24753. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  24754. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  24755. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  24756. if ( json.wireframelineWidth !== undefined ) material.wireframelineWidth = json.wireframelineWidth;
  24757. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  24758. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  24759. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  24760. if ( json.lineWidth !== 1 ) material.lineWidth = json.lineWidth;
  24761. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  24762. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  24763. if ( json.scale !== undefined ) material.scale = json.scale;
  24764. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  24765. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24766. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24767. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  24768. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  24769. if ( json.morphNormals !== undefined ) material.morphNormals = json.morphNormals;
  24770. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  24771. if ( json.vertexTangents !== undefined ) material.vertexTangents = json.vertexTangents;
  24772. if ( json.visible !== undefined ) material.visible = json.visible;
  24773. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  24774. if ( json.userData !== undefined ) material.userData = json.userData;
  24775. if ( json.vertexColors !== undefined ) {
  24776. if ( typeof json.vertexColors === 'number' ) {
  24777. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  24778. } else {
  24779. material.vertexColors = json.vertexColors;
  24780. }
  24781. }
  24782. // Shader Material
  24783. if ( json.uniforms !== undefined ) {
  24784. for ( const name in json.uniforms ) {
  24785. const uniform = json.uniforms[ name ];
  24786. material.uniforms[ name ] = {};
  24787. switch ( uniform.type ) {
  24788. case 't':
  24789. material.uniforms[ name ].value = getTexture( uniform.value );
  24790. break;
  24791. case 'c':
  24792. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  24793. break;
  24794. case 'v2':
  24795. material.uniforms[ name ].value = new Vector2$1().fromArray( uniform.value );
  24796. break;
  24797. case 'v3':
  24798. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  24799. break;
  24800. case 'v4':
  24801. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  24802. break;
  24803. case 'm3':
  24804. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  24805. break;
  24806. case 'm4':
  24807. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  24808. break;
  24809. default:
  24810. material.uniforms[ name ].value = uniform.value;
  24811. }
  24812. }
  24813. }
  24814. if ( json.defines !== undefined ) material.defines = json.defines;
  24815. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24816. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24817. if ( json.extensions !== undefined ) {
  24818. for ( const key in json.extensions ) {
  24819. material.extensions[ key ] = json.extensions[ key ];
  24820. }
  24821. }
  24822. // Deprecated
  24823. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  24824. // for PointsMaterial
  24825. if ( json.size !== undefined ) material.size = json.size;
  24826. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24827. // maps
  24828. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24829. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  24830. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  24831. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24832. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24833. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24834. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  24835. if ( json.normalScale !== undefined ) {
  24836. let normalScale = json.normalScale;
  24837. if ( Array.isArray( normalScale ) === false ) {
  24838. // Blender exporter used to export a scalar. See #7459
  24839. normalScale = [ normalScale, normalScale ];
  24840. }
  24841. material.normalScale = new Vector2$1().fromArray( normalScale );
  24842. }
  24843. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24844. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24845. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24846. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24847. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24848. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24849. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24850. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24851. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24852. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  24853. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24854. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  24855. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24856. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24857. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24858. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24859. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24860. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  24861. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  24862. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  24863. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2$1().fromArray( json.clearcoatNormalScale );
  24864. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  24865. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  24866. return material;
  24867. },
  24868. setTextures: function ( value ) {
  24869. this.textures = value;
  24870. return this;
  24871. }
  24872. } );
  24873. const LoaderUtils = {
  24874. decodeText: function ( array ) {
  24875. if ( typeof TextDecoder !== 'undefined' ) {
  24876. return new TextDecoder().decode( array );
  24877. }
  24878. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24879. // throws a "maximum call stack size exceeded" error for large arrays.
  24880. let s = '';
  24881. for ( let i = 0, il = array.length; i < il; i ++ ) {
  24882. // Implicitly assumes little-endian.
  24883. s += String.fromCharCode( array[ i ] );
  24884. }
  24885. try {
  24886. // merges multi-byte utf-8 characters.
  24887. return decodeURIComponent( escape( s ) );
  24888. } catch ( e ) { // see #16358
  24889. return s;
  24890. }
  24891. },
  24892. extractUrlBase: function ( url ) {
  24893. const index = url.lastIndexOf( '/' );
  24894. if ( index === - 1 ) return './';
  24895. return url.substr( 0, index + 1 );
  24896. }
  24897. };
  24898. function InstancedBufferGeometry() {
  24899. BufferGeometry.call( this );
  24900. this.type = 'InstancedBufferGeometry';
  24901. this.instanceCount = Infinity;
  24902. }
  24903. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  24904. constructor: InstancedBufferGeometry,
  24905. isInstancedBufferGeometry: true,
  24906. copy: function ( source ) {
  24907. BufferGeometry.prototype.copy.call( this, source );
  24908. this.instanceCount = source.instanceCount;
  24909. return this;
  24910. },
  24911. clone: function () {
  24912. return new this.constructor().copy( this );
  24913. },
  24914. toJSON: function () {
  24915. const data = BufferGeometry.prototype.toJSON.call( this );
  24916. data.instanceCount = this.instanceCount;
  24917. data.isInstancedBufferGeometry = true;
  24918. return data;
  24919. }
  24920. } );
  24921. function InstancedBufferAttribute( array, itemSize, normalized, meshPerAttribute ) {
  24922. if ( typeof ( normalized ) === 'number' ) {
  24923. meshPerAttribute = normalized;
  24924. normalized = false;
  24925. console.error( 'THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.' );
  24926. }
  24927. BufferAttribute.call( this, array, itemSize, normalized );
  24928. this.meshPerAttribute = meshPerAttribute || 1;
  24929. }
  24930. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  24931. constructor: InstancedBufferAttribute,
  24932. isInstancedBufferAttribute: true,
  24933. copy: function ( source ) {
  24934. BufferAttribute.prototype.copy.call( this, source );
  24935. this.meshPerAttribute = source.meshPerAttribute;
  24936. return this;
  24937. },
  24938. toJSON: function () {
  24939. const data = BufferAttribute.prototype.toJSON.call( this );
  24940. data.meshPerAttribute = this.meshPerAttribute;
  24941. data.isInstancedBufferAttribute = true;
  24942. return data;
  24943. }
  24944. } );
  24945. function BufferGeometryLoader( manager ) {
  24946. Loader.call( this, manager );
  24947. }
  24948. BufferGeometryLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  24949. constructor: BufferGeometryLoader,
  24950. load: function ( url, onLoad, onProgress, onError ) {
  24951. const scope = this;
  24952. const loader = new FileLoader( scope.manager );
  24953. loader.setPath( scope.path );
  24954. loader.setRequestHeader( scope.requestHeader );
  24955. loader.setWithCredentials( scope.withCredentials );
  24956. loader.load( url, function ( text ) {
  24957. try {
  24958. onLoad( scope.parse( JSON.parse( text ) ) );
  24959. } catch ( e ) {
  24960. if ( onError ) {
  24961. onError( e );
  24962. } else {
  24963. console.error( e );
  24964. }
  24965. scope.manager.itemError( url );
  24966. }
  24967. }, onProgress, onError );
  24968. },
  24969. parse: function ( json ) {
  24970. const interleavedBufferMap = {};
  24971. const arrayBufferMap = {};
  24972. function getInterleavedBuffer( json, uuid ) {
  24973. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  24974. const interleavedBuffers = json.interleavedBuffers;
  24975. const interleavedBuffer = interleavedBuffers[ uuid ];
  24976. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  24977. const array = getTypedArray( interleavedBuffer.type, buffer );
  24978. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  24979. ib.uuid = interleavedBuffer.uuid;
  24980. interleavedBufferMap[ uuid ] = ib;
  24981. return ib;
  24982. }
  24983. function getArrayBuffer( json, uuid ) {
  24984. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  24985. const arrayBuffers = json.arrayBuffers;
  24986. const arrayBuffer = arrayBuffers[ uuid ];
  24987. const ab = new Uint32Array( arrayBuffer ).buffer;
  24988. arrayBufferMap[ uuid ] = ab;
  24989. return ab;
  24990. }
  24991. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24992. const index = json.data.index;
  24993. if ( index !== undefined ) {
  24994. const typedArray = getTypedArray( index.type, index.array );
  24995. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  24996. }
  24997. const attributes = json.data.attributes;
  24998. for ( const key in attributes ) {
  24999. const attribute = attributes[ key ];
  25000. let bufferAttribute;
  25001. if ( attribute.isInterleavedBufferAttribute ) {
  25002. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25003. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25004. } else {
  25005. const typedArray = getTypedArray( attribute.type, attribute.array );
  25006. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25007. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  25008. }
  25009. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25010. geometry.setAttribute( key, bufferAttribute );
  25011. }
  25012. const morphAttributes = json.data.morphAttributes;
  25013. if ( morphAttributes ) {
  25014. for ( const key in morphAttributes ) {
  25015. const attributeArray = morphAttributes[ key ];
  25016. const array = [];
  25017. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  25018. const attribute = attributeArray[ i ];
  25019. let bufferAttribute;
  25020. if ( attribute.isInterleavedBufferAttribute ) {
  25021. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25022. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25023. } else {
  25024. const typedArray = getTypedArray( attribute.type, attribute.array );
  25025. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  25026. }
  25027. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25028. array.push( bufferAttribute );
  25029. }
  25030. geometry.morphAttributes[ key ] = array;
  25031. }
  25032. }
  25033. const morphTargetsRelative = json.data.morphTargetsRelative;
  25034. if ( morphTargetsRelative ) {
  25035. geometry.morphTargetsRelative = true;
  25036. }
  25037. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25038. if ( groups !== undefined ) {
  25039. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  25040. const group = groups[ i ];
  25041. geometry.addGroup( group.start, group.count, group.materialIndex );
  25042. }
  25043. }
  25044. const boundingSphere = json.data.boundingSphere;
  25045. if ( boundingSphere !== undefined ) {
  25046. const center = new Vector3();
  25047. if ( boundingSphere.center !== undefined ) {
  25048. center.fromArray( boundingSphere.center );
  25049. }
  25050. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25051. }
  25052. if ( json.name ) geometry.name = json.name;
  25053. if ( json.userData ) geometry.userData = json.userData;
  25054. return geometry;
  25055. }
  25056. } );
  25057. class ObjectLoader extends Loader {
  25058. constructor( manager ) {
  25059. super( manager );
  25060. }
  25061. load( url, onLoad, onProgress, onError ) {
  25062. const scope = this;
  25063. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25064. this.resourcePath = this.resourcePath || path;
  25065. const loader = new FileLoader( this.manager );
  25066. loader.setPath( this.path );
  25067. loader.setRequestHeader( this.requestHeader );
  25068. loader.setWithCredentials( this.withCredentials );
  25069. loader.load( url, function ( text ) {
  25070. let json = null;
  25071. try {
  25072. json = JSON.parse( text );
  25073. } catch ( error ) {
  25074. if ( onError !== undefined ) onError( error );
  25075. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  25076. return;
  25077. }
  25078. const metadata = json.metadata;
  25079. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25080. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25081. return;
  25082. }
  25083. scope.parse( json, onLoad );
  25084. }, onProgress, onError );
  25085. }
  25086. parse( json, onLoad ) {
  25087. const animations = this.parseAnimations( json.animations );
  25088. const shapes = this.parseShapes( json.shapes );
  25089. const geometries = this.parseGeometries( json.geometries, shapes );
  25090. const images = this.parseImages( json.images, function () {
  25091. if ( onLoad !== undefined ) onLoad( object );
  25092. } );
  25093. const textures = this.parseTextures( json.textures, images );
  25094. const materials = this.parseMaterials( json.materials, textures );
  25095. const object = this.parseObject( json.object, geometries, materials, animations );
  25096. const skeletons = this.parseSkeletons( json.skeletons, object );
  25097. this.bindSkeletons( object, skeletons );
  25098. //
  25099. if ( onLoad !== undefined ) {
  25100. let hasImages = false;
  25101. for ( const uuid in images ) {
  25102. if ( images[ uuid ] instanceof HTMLImageElement ) {
  25103. hasImages = true;
  25104. break;
  25105. }
  25106. }
  25107. if ( hasImages === false ) onLoad( object );
  25108. }
  25109. return object;
  25110. }
  25111. parseShapes( json ) {
  25112. const shapes = {};
  25113. if ( json !== undefined ) {
  25114. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25115. const shape = new Shape().fromJSON( json[ i ] );
  25116. shapes[ shape.uuid ] = shape;
  25117. }
  25118. }
  25119. return shapes;
  25120. }
  25121. parseSkeletons( json, object ) {
  25122. const skeletons = {};
  25123. const bones = {};
  25124. // generate bone lookup table
  25125. object.traverse( function ( child ) {
  25126. if ( child.isBone ) bones[ child.uuid ] = child;
  25127. } );
  25128. // create skeletons
  25129. if ( json !== undefined ) {
  25130. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25131. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  25132. skeletons[ skeleton.uuid ] = skeleton;
  25133. }
  25134. }
  25135. return skeletons;
  25136. }
  25137. parseGeometries( json, shapes ) {
  25138. const geometries = {};
  25139. let geometryShapes;
  25140. if ( json !== undefined ) {
  25141. const bufferGeometryLoader = new BufferGeometryLoader();
  25142. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25143. let geometry;
  25144. const data = json[ i ];
  25145. switch ( data.type ) {
  25146. case 'PlaneGeometry':
  25147. case 'PlaneBufferGeometry':
  25148. geometry = new Geometries[ data.type ](
  25149. data.width,
  25150. data.height,
  25151. data.widthSegments,
  25152. data.heightSegments
  25153. );
  25154. break;
  25155. case 'BoxGeometry':
  25156. case 'BoxBufferGeometry':
  25157. case 'CubeGeometry': // backwards compatible
  25158. geometry = new Geometries[ data.type ](
  25159. data.width,
  25160. data.height,
  25161. data.depth,
  25162. data.widthSegments,
  25163. data.heightSegments,
  25164. data.depthSegments
  25165. );
  25166. break;
  25167. case 'CircleGeometry':
  25168. case 'CircleBufferGeometry':
  25169. geometry = new Geometries[ data.type ](
  25170. data.radius,
  25171. data.segments,
  25172. data.thetaStart,
  25173. data.thetaLength
  25174. );
  25175. break;
  25176. case 'CylinderGeometry':
  25177. case 'CylinderBufferGeometry':
  25178. geometry = new Geometries[ data.type ](
  25179. data.radiusTop,
  25180. data.radiusBottom,
  25181. data.height,
  25182. data.radialSegments,
  25183. data.heightSegments,
  25184. data.openEnded,
  25185. data.thetaStart,
  25186. data.thetaLength
  25187. );
  25188. break;
  25189. case 'ConeGeometry':
  25190. case 'ConeBufferGeometry':
  25191. geometry = new Geometries[ data.type ](
  25192. data.radius,
  25193. data.height,
  25194. data.radialSegments,
  25195. data.heightSegments,
  25196. data.openEnded,
  25197. data.thetaStart,
  25198. data.thetaLength
  25199. );
  25200. break;
  25201. case 'SphereGeometry':
  25202. case 'SphereBufferGeometry':
  25203. geometry = new Geometries[ data.type ](
  25204. data.radius,
  25205. data.widthSegments,
  25206. data.heightSegments,
  25207. data.phiStart,
  25208. data.phiLength,
  25209. data.thetaStart,
  25210. data.thetaLength
  25211. );
  25212. break;
  25213. case 'DodecahedronGeometry':
  25214. case 'DodecahedronBufferGeometry':
  25215. case 'IcosahedronGeometry':
  25216. case 'IcosahedronBufferGeometry':
  25217. case 'OctahedronGeometry':
  25218. case 'OctahedronBufferGeometry':
  25219. case 'TetrahedronGeometry':
  25220. case 'TetrahedronBufferGeometry':
  25221. geometry = new Geometries[ data.type ](
  25222. data.radius,
  25223. data.detail
  25224. );
  25225. break;
  25226. case 'RingGeometry':
  25227. case 'RingBufferGeometry':
  25228. geometry = new Geometries[ data.type ](
  25229. data.innerRadius,
  25230. data.outerRadius,
  25231. data.thetaSegments,
  25232. data.phiSegments,
  25233. data.thetaStart,
  25234. data.thetaLength
  25235. );
  25236. break;
  25237. case 'TorusGeometry':
  25238. case 'TorusBufferGeometry':
  25239. geometry = new Geometries[ data.type ](
  25240. data.radius,
  25241. data.tube,
  25242. data.radialSegments,
  25243. data.tubularSegments,
  25244. data.arc
  25245. );
  25246. break;
  25247. case 'TorusKnotGeometry':
  25248. case 'TorusKnotBufferGeometry':
  25249. geometry = new Geometries[ data.type ](
  25250. data.radius,
  25251. data.tube,
  25252. data.tubularSegments,
  25253. data.radialSegments,
  25254. data.p,
  25255. data.q
  25256. );
  25257. break;
  25258. case 'TubeGeometry':
  25259. case 'TubeBufferGeometry':
  25260. // This only works for built-in curves (e.g. CatmullRomCurve3).
  25261. // User defined curves or instances of CurvePath will not be deserialized.
  25262. geometry = new Geometries[ data.type ](
  25263. new Curves[ data.path.type ]().fromJSON( data.path ),
  25264. data.tubularSegments,
  25265. data.radius,
  25266. data.radialSegments,
  25267. data.closed
  25268. );
  25269. break;
  25270. case 'LatheGeometry':
  25271. case 'LatheBufferGeometry':
  25272. geometry = new Geometries[ data.type ](
  25273. data.points,
  25274. data.segments,
  25275. data.phiStart,
  25276. data.phiLength
  25277. );
  25278. break;
  25279. case 'PolyhedronGeometry':
  25280. case 'PolyhedronBufferGeometry':
  25281. geometry = new Geometries[ data.type ](
  25282. data.vertices,
  25283. data.indices,
  25284. data.radius,
  25285. data.details
  25286. );
  25287. break;
  25288. case 'ShapeGeometry':
  25289. case 'ShapeBufferGeometry':
  25290. geometryShapes = [];
  25291. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  25292. const shape = shapes[ data.shapes[ j ] ];
  25293. geometryShapes.push( shape );
  25294. }
  25295. geometry = new Geometries[ data.type ](
  25296. geometryShapes,
  25297. data.curveSegments
  25298. );
  25299. break;
  25300. case 'ExtrudeGeometry':
  25301. case 'ExtrudeBufferGeometry':
  25302. geometryShapes = [];
  25303. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  25304. const shape = shapes[ data.shapes[ j ] ];
  25305. geometryShapes.push( shape );
  25306. }
  25307. const extrudePath = data.options.extrudePath;
  25308. if ( extrudePath !== undefined ) {
  25309. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  25310. }
  25311. geometry = new Geometries[ data.type ](
  25312. geometryShapes,
  25313. data.options
  25314. );
  25315. break;
  25316. case 'BufferGeometry':
  25317. case 'InstancedBufferGeometry':
  25318. geometry = bufferGeometryLoader.parse( data );
  25319. break;
  25320. case 'Geometry':
  25321. console.error( 'THREE.ObjectLoader: Loading "Geometry" is not supported anymore.' );
  25322. break;
  25323. default:
  25324. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  25325. continue;
  25326. }
  25327. geometry.uuid = data.uuid;
  25328. if ( data.name !== undefined ) geometry.name = data.name;
  25329. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  25330. geometries[ data.uuid ] = geometry;
  25331. }
  25332. }
  25333. return geometries;
  25334. }
  25335. parseMaterials( json, textures ) {
  25336. const cache = {}; // MultiMaterial
  25337. const materials = {};
  25338. if ( json !== undefined ) {
  25339. const loader = new MaterialLoader();
  25340. loader.setTextures( textures );
  25341. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25342. const data = json[ i ];
  25343. if ( data.type === 'MultiMaterial' ) {
  25344. // Deprecated
  25345. const array = [];
  25346. for ( let j = 0; j < data.materials.length; j ++ ) {
  25347. const material = data.materials[ j ];
  25348. if ( cache[ material.uuid ] === undefined ) {
  25349. cache[ material.uuid ] = loader.parse( material );
  25350. }
  25351. array.push( cache[ material.uuid ] );
  25352. }
  25353. materials[ data.uuid ] = array;
  25354. } else {
  25355. if ( cache[ data.uuid ] === undefined ) {
  25356. cache[ data.uuid ] = loader.parse( data );
  25357. }
  25358. materials[ data.uuid ] = cache[ data.uuid ];
  25359. }
  25360. }
  25361. }
  25362. return materials;
  25363. }
  25364. parseAnimations( json ) {
  25365. const animations = {};
  25366. if ( json !== undefined ) {
  25367. for ( let i = 0; i < json.length; i ++ ) {
  25368. const data = json[ i ];
  25369. const clip = AnimationClip.parse( data );
  25370. animations[ clip.uuid ] = clip;
  25371. }
  25372. }
  25373. return animations;
  25374. }
  25375. parseImages( json, onLoad ) {
  25376. const scope = this;
  25377. const images = {};
  25378. let loader;
  25379. function loadImage( url ) {
  25380. scope.manager.itemStart( url );
  25381. return loader.load( url, function () {
  25382. scope.manager.itemEnd( url );
  25383. }, undefined, function () {
  25384. scope.manager.itemError( url );
  25385. scope.manager.itemEnd( url );
  25386. } );
  25387. }
  25388. function deserializeImage( image ) {
  25389. if ( typeof image === 'string' ) {
  25390. const url = image;
  25391. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25392. return loadImage( path );
  25393. } else {
  25394. if ( image.data ) {
  25395. return {
  25396. data: getTypedArray( image.type, image.data ),
  25397. width: image.width,
  25398. height: image.height
  25399. };
  25400. } else {
  25401. return null;
  25402. }
  25403. }
  25404. }
  25405. if ( json !== undefined && json.length > 0 ) {
  25406. const manager = new LoadingManager( onLoad );
  25407. loader = new ImageLoader( manager );
  25408. loader.setCrossOrigin( this.crossOrigin );
  25409. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25410. const image = json[ i ];
  25411. const url = image.url;
  25412. if ( Array.isArray( url ) ) {
  25413. // load array of images e.g CubeTexture
  25414. images[ image.uuid ] = [];
  25415. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25416. const currentUrl = url[ j ];
  25417. const deserializedImage = deserializeImage( currentUrl );
  25418. if ( deserializedImage !== null ) {
  25419. if ( deserializedImage instanceof HTMLImageElement ) {
  25420. images[ image.uuid ].push( deserializedImage );
  25421. } else {
  25422. // special case: handle array of data textures for cube textures
  25423. images[ image.uuid ].push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25424. }
  25425. }
  25426. }
  25427. } else {
  25428. // load single image
  25429. const deserializedImage = deserializeImage( image.url );
  25430. if ( deserializedImage !== null ) {
  25431. images[ image.uuid ] = deserializedImage;
  25432. }
  25433. }
  25434. }
  25435. }
  25436. return images;
  25437. }
  25438. parseTextures( json, images ) {
  25439. function parseConstant( value, type ) {
  25440. if ( typeof value === 'number' ) return value;
  25441. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25442. return type[ value ];
  25443. }
  25444. const textures = {};
  25445. if ( json !== undefined ) {
  25446. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25447. const data = json[ i ];
  25448. if ( data.image === undefined ) {
  25449. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25450. }
  25451. if ( images[ data.image ] === undefined ) {
  25452. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25453. }
  25454. let texture;
  25455. const image = images[ data.image ];
  25456. if ( Array.isArray( image ) ) {
  25457. texture = new CubeTexture( image );
  25458. if ( image.length === 6 ) texture.needsUpdate = true;
  25459. } else {
  25460. if ( image && image.data ) {
  25461. texture = new DataTexture( image.data, image.width, image.height );
  25462. } else {
  25463. texture = new Texture( image );
  25464. }
  25465. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  25466. }
  25467. texture.uuid = data.uuid;
  25468. if ( data.name !== undefined ) texture.name = data.name;
  25469. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25470. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25471. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25472. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  25473. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  25474. if ( data.wrap !== undefined ) {
  25475. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25476. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25477. }
  25478. if ( data.format !== undefined ) texture.format = data.format;
  25479. if ( data.type !== undefined ) texture.type = data.type;
  25480. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  25481. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25482. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25483. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25484. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25485. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  25486. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  25487. textures[ data.uuid ] = texture;
  25488. }
  25489. }
  25490. return textures;
  25491. }
  25492. parseObject( data, geometries, materials, animations ) {
  25493. let object;
  25494. function getGeometry( name ) {
  25495. if ( geometries[ name ] === undefined ) {
  25496. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25497. }
  25498. return geometries[ name ];
  25499. }
  25500. function getMaterial( name ) {
  25501. if ( name === undefined ) return undefined;
  25502. if ( Array.isArray( name ) ) {
  25503. const array = [];
  25504. for ( let i = 0, l = name.length; i < l; i ++ ) {
  25505. const uuid = name[ i ];
  25506. if ( materials[ uuid ] === undefined ) {
  25507. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25508. }
  25509. array.push( materials[ uuid ] );
  25510. }
  25511. return array;
  25512. }
  25513. if ( materials[ name ] === undefined ) {
  25514. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  25515. }
  25516. return materials[ name ];
  25517. }
  25518. let geometry, material;
  25519. switch ( data.type ) {
  25520. case 'Scene':
  25521. object = new Scene();
  25522. if ( data.background !== undefined ) {
  25523. if ( Number.isInteger( data.background ) ) {
  25524. object.background = new Color( data.background );
  25525. }
  25526. }
  25527. if ( data.fog !== undefined ) {
  25528. if ( data.fog.type === 'Fog' ) {
  25529. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  25530. } else if ( data.fog.type === 'FogExp2' ) {
  25531. object.fog = new FogExp2( data.fog.color, data.fog.density );
  25532. }
  25533. }
  25534. break;
  25535. case 'PerspectiveCamera':
  25536. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  25537. if ( data.focus !== undefined ) object.focus = data.focus;
  25538. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25539. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  25540. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  25541. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25542. break;
  25543. case 'OrthographicCamera':
  25544. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  25545. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25546. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25547. break;
  25548. case 'AmbientLight':
  25549. object = new AmbientLight( data.color, data.intensity );
  25550. break;
  25551. case 'DirectionalLight':
  25552. object = new DirectionalLight( data.color, data.intensity );
  25553. break;
  25554. case 'PointLight':
  25555. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  25556. break;
  25557. case 'RectAreaLight':
  25558. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  25559. break;
  25560. case 'SpotLight':
  25561. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  25562. break;
  25563. case 'HemisphereLight':
  25564. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  25565. break;
  25566. case 'LightProbe':
  25567. object = new LightProbe().fromJSON( data );
  25568. break;
  25569. case 'SkinnedMesh':
  25570. geometry = getGeometry( data.geometry );
  25571. material = getMaterial( data.material );
  25572. object = new SkinnedMesh( geometry, material );
  25573. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  25574. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  25575. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  25576. break;
  25577. case 'Mesh':
  25578. geometry = getGeometry( data.geometry );
  25579. material = getMaterial( data.material );
  25580. object = new Mesh( geometry, material );
  25581. break;
  25582. case 'InstancedMesh':
  25583. geometry = getGeometry( data.geometry );
  25584. material = getMaterial( data.material );
  25585. const count = data.count;
  25586. const instanceMatrix = data.instanceMatrix;
  25587. object = new InstancedMesh( geometry, material, count );
  25588. object.instanceMatrix = new BufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  25589. break;
  25590. case 'LOD':
  25591. object = new LOD();
  25592. break;
  25593. case 'Line':
  25594. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  25595. break;
  25596. case 'LineLoop':
  25597. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25598. break;
  25599. case 'LineSegments':
  25600. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25601. break;
  25602. case 'PointCloud':
  25603. case 'Points':
  25604. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25605. break;
  25606. case 'Sprite':
  25607. object = new Sprite( getMaterial( data.material ) );
  25608. break;
  25609. case 'Group':
  25610. object = new Group();
  25611. break;
  25612. case 'Bone':
  25613. object = new Bone();
  25614. break;
  25615. default:
  25616. object = new Object3D();
  25617. }
  25618. object.uuid = data.uuid;
  25619. if ( data.name !== undefined ) object.name = data.name;
  25620. if ( data.matrix !== undefined ) {
  25621. object.matrix.fromArray( data.matrix );
  25622. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25623. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  25624. } else {
  25625. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25626. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25627. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25628. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25629. }
  25630. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25631. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25632. if ( data.shadow ) {
  25633. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25634. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  25635. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25636. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  25637. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  25638. }
  25639. if ( data.visible !== undefined ) object.visible = data.visible;
  25640. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  25641. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  25642. if ( data.userData !== undefined ) object.userData = data.userData;
  25643. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  25644. if ( data.children !== undefined ) {
  25645. const children = data.children;
  25646. for ( let i = 0; i < children.length; i ++ ) {
  25647. object.add( this.parseObject( children[ i ], geometries, materials, animations ) );
  25648. }
  25649. }
  25650. if ( data.animations !== undefined ) {
  25651. const objectAnimations = data.animations;
  25652. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  25653. const uuid = objectAnimations[ i ];
  25654. object.animations.push( animations[ uuid ] );
  25655. }
  25656. }
  25657. if ( data.type === 'LOD' ) {
  25658. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  25659. const levels = data.levels;
  25660. for ( let l = 0; l < levels.length; l ++ ) {
  25661. const level = levels[ l ];
  25662. const child = object.getObjectByProperty( 'uuid', level.object );
  25663. if ( child !== undefined ) {
  25664. object.addLevel( child, level.distance );
  25665. }
  25666. }
  25667. }
  25668. return object;
  25669. }
  25670. bindSkeletons( object, skeletons ) {
  25671. if ( Object.keys( skeletons ).length === 0 ) return;
  25672. object.traverse( function ( child ) {
  25673. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  25674. const skeleton = skeletons[ child.skeleton ];
  25675. if ( skeleton === undefined ) {
  25676. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  25677. } else {
  25678. child.bind( skeleton, child.bindMatrix );
  25679. }
  25680. }
  25681. } );
  25682. }
  25683. /* DEPRECATED */
  25684. setTexturePath( value ) {
  25685. console.warn( 'THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().' );
  25686. return this.setResourcePath( value );
  25687. }
  25688. }
  25689. const TEXTURE_MAPPING = {
  25690. UVMapping: UVMapping,
  25691. CubeReflectionMapping: CubeReflectionMapping,
  25692. CubeRefractionMapping: CubeRefractionMapping,
  25693. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25694. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25695. CubeUVReflectionMapping: CubeUVReflectionMapping,
  25696. CubeUVRefractionMapping: CubeUVRefractionMapping
  25697. };
  25698. const TEXTURE_WRAPPING = {
  25699. RepeatWrapping: RepeatWrapping,
  25700. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25701. MirroredRepeatWrapping: MirroredRepeatWrapping
  25702. };
  25703. const TEXTURE_FILTER = {
  25704. NearestFilter: NearestFilter,
  25705. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25706. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25707. LinearFilter: LinearFilter,
  25708. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25709. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25710. };
  25711. function ImageBitmapLoader( manager ) {
  25712. if ( typeof createImageBitmap === 'undefined' ) {
  25713. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  25714. }
  25715. if ( typeof fetch === 'undefined' ) {
  25716. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  25717. }
  25718. Loader.call( this, manager );
  25719. this.options = { premultiplyAlpha: 'none' };
  25720. }
  25721. ImageBitmapLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  25722. constructor: ImageBitmapLoader,
  25723. isImageBitmapLoader: true,
  25724. setOptions: function setOptions( options ) {
  25725. this.options = options;
  25726. return this;
  25727. },
  25728. load: function ( url, onLoad, onProgress, onError ) {
  25729. if ( url === undefined ) url = '';
  25730. if ( this.path !== undefined ) url = this.path + url;
  25731. url = this.manager.resolveURL( url );
  25732. const scope = this;
  25733. const cached = Cache.get( url );
  25734. if ( cached !== undefined ) {
  25735. scope.manager.itemStart( url );
  25736. setTimeout( function () {
  25737. if ( onLoad ) onLoad( cached );
  25738. scope.manager.itemEnd( url );
  25739. }, 0 );
  25740. return cached;
  25741. }
  25742. const fetchOptions = {};
  25743. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  25744. fetch( url, fetchOptions ).then( function ( res ) {
  25745. return res.blob();
  25746. } ).then( function ( blob ) {
  25747. //console.log('getBlob', url )
  25748. return createImageBitmap( blob, scope.options );
  25749. } ).then( function ( imageBitmap ) {
  25750. Cache.add( url, imageBitmap );
  25751. if ( onLoad ) onLoad( imageBitmap );
  25752. scope.manager.itemEnd( url );
  25753. } ).catch( function ( e ) {
  25754. //console.log('error', url, e)
  25755. if ( onError ) onError( e, url );
  25756. scope.manager.itemError( url );
  25757. scope.manager.itemEnd( url );
  25758. } );
  25759. scope.manager.itemStart( url );
  25760. }
  25761. } );
  25762. function ShapePath() {
  25763. this.type = 'ShapePath';
  25764. this.color = new Color();
  25765. this.subPaths = [];
  25766. this.currentPath = null;
  25767. }
  25768. Object.assign( ShapePath.prototype, {
  25769. moveTo: function ( x, y ) {
  25770. this.currentPath = new Path();
  25771. this.subPaths.push( this.currentPath );
  25772. this.currentPath.moveTo( x, y );
  25773. return this;
  25774. },
  25775. lineTo: function ( x, y ) {
  25776. this.currentPath.lineTo( x, y );
  25777. return this;
  25778. },
  25779. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  25780. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  25781. return this;
  25782. },
  25783. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25784. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  25785. return this;
  25786. },
  25787. splineThru: function ( pts ) {
  25788. this.currentPath.splineThru( pts );
  25789. return this;
  25790. },
  25791. toShapes: function ( isCCW, noHoles ) {
  25792. function toShapesNoHoles( inSubpaths ) {
  25793. const shapes = [];
  25794. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  25795. const tmpPath = inSubpaths[ i ];
  25796. const tmpShape = new Shape();
  25797. tmpShape.curves = tmpPath.curves;
  25798. shapes.push( tmpShape );
  25799. }
  25800. return shapes;
  25801. }
  25802. function isPointInsidePolygon( inPt, inPolygon ) {
  25803. const polyLen = inPolygon.length;
  25804. // inPt on polygon contour => immediate success or
  25805. // toggling of inside/outside at every single! intersection point of an edge
  25806. // with the horizontal line through inPt, left of inPt
  25807. // not counting lowerY endpoints of edges and whole edges on that line
  25808. let inside = false;
  25809. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  25810. let edgeLowPt = inPolygon[ p ];
  25811. let edgeHighPt = inPolygon[ q ];
  25812. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  25813. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  25814. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  25815. // not parallel
  25816. if ( edgeDy < 0 ) {
  25817. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  25818. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  25819. }
  25820. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  25821. if ( inPt.y === edgeLowPt.y ) {
  25822. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  25823. // continue; // no intersection or edgeLowPt => doesn't count !!!
  25824. } else {
  25825. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  25826. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  25827. if ( perpEdge < 0 ) continue;
  25828. inside = ! inside; // true intersection left of inPt
  25829. }
  25830. } else {
  25831. // parallel or collinear
  25832. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  25833. // edge lies on the same horizontal line as inPt
  25834. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  25835. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  25836. // continue;
  25837. }
  25838. }
  25839. return inside;
  25840. }
  25841. const isClockWise = ShapeUtils.isClockWise;
  25842. const subPaths = this.subPaths;
  25843. if ( subPaths.length === 0 ) return [];
  25844. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  25845. let solid, tmpPath, tmpShape;
  25846. const shapes = [];
  25847. if ( subPaths.length === 1 ) {
  25848. tmpPath = subPaths[ 0 ];
  25849. tmpShape = new Shape();
  25850. tmpShape.curves = tmpPath.curves;
  25851. shapes.push( tmpShape );
  25852. return shapes;
  25853. }
  25854. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  25855. holesFirst = isCCW ? ! holesFirst : holesFirst;
  25856. // console.log("Holes first", holesFirst);
  25857. const betterShapeHoles = [];
  25858. const newShapes = [];
  25859. let newShapeHoles = [];
  25860. let mainIdx = 0;
  25861. let tmpPoints;
  25862. newShapes[ mainIdx ] = undefined;
  25863. newShapeHoles[ mainIdx ] = [];
  25864. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  25865. tmpPath = subPaths[ i ];
  25866. tmpPoints = tmpPath.getPoints();
  25867. solid = isClockWise( tmpPoints );
  25868. solid = isCCW ? ! solid : solid;
  25869. if ( solid ) {
  25870. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  25871. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  25872. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  25873. if ( holesFirst ) mainIdx ++;
  25874. newShapeHoles[ mainIdx ] = [];
  25875. //console.log('cw', i);
  25876. } else {
  25877. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  25878. //console.log('ccw', i);
  25879. }
  25880. }
  25881. // only Holes? -> probably all Shapes with wrong orientation
  25882. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  25883. if ( newShapes.length > 1 ) {
  25884. let ambiguous = false;
  25885. const toChange = [];
  25886. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  25887. betterShapeHoles[ sIdx ] = [];
  25888. }
  25889. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  25890. const sho = newShapeHoles[ sIdx ];
  25891. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  25892. const ho = sho[ hIdx ];
  25893. let hole_unassigned = true;
  25894. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  25895. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  25896. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  25897. if ( hole_unassigned ) {
  25898. hole_unassigned = false;
  25899. betterShapeHoles[ s2Idx ].push( ho );
  25900. } else {
  25901. ambiguous = true;
  25902. }
  25903. }
  25904. }
  25905. if ( hole_unassigned ) {
  25906. betterShapeHoles[ sIdx ].push( ho );
  25907. }
  25908. }
  25909. }
  25910. // console.log("ambiguous: ", ambiguous);
  25911. if ( toChange.length > 0 ) {
  25912. // console.log("to change: ", toChange);
  25913. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  25914. }
  25915. }
  25916. let tmpHoles;
  25917. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  25918. tmpShape = newShapes[ i ].s;
  25919. shapes.push( tmpShape );
  25920. tmpHoles = newShapeHoles[ i ];
  25921. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  25922. tmpShape.holes.push( tmpHoles[ j ].h );
  25923. }
  25924. }
  25925. //console.log("shape", shapes);
  25926. return shapes;
  25927. }
  25928. } );
  25929. function Font( data ) {
  25930. this.type = 'Font';
  25931. this.data = data;
  25932. }
  25933. Object.assign( Font.prototype, {
  25934. isFont: true,
  25935. generateShapes: function ( text, size = 100 ) {
  25936. const shapes = [];
  25937. const paths = createPaths( text, size, this.data );
  25938. for ( let p = 0, pl = paths.length; p < pl; p ++ ) {
  25939. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  25940. }
  25941. return shapes;
  25942. }
  25943. } );
  25944. function createPaths( text, size, data ) {
  25945. const chars = Array.from ? Array.from( text ) : String( text ).split( '' ); // workaround for IE11, see #13988
  25946. const scale = size / data.resolution;
  25947. const line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  25948. const paths = [];
  25949. let offsetX = 0, offsetY = 0;
  25950. for ( let i = 0; i < chars.length; i ++ ) {
  25951. const char = chars[ i ];
  25952. if ( char === '\n' ) {
  25953. offsetX = 0;
  25954. offsetY -= line_height;
  25955. } else {
  25956. const ret = createPath( char, scale, offsetX, offsetY, data );
  25957. offsetX += ret.offsetX;
  25958. paths.push( ret.path );
  25959. }
  25960. }
  25961. return paths;
  25962. }
  25963. function createPath( char, scale, offsetX, offsetY, data ) {
  25964. const glyph = data.glyphs[ char ] || data.glyphs[ '?' ];
  25965. if ( ! glyph ) {
  25966. console.error( 'THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.' );
  25967. return;
  25968. }
  25969. const path = new ShapePath();
  25970. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  25971. if ( glyph.o ) {
  25972. const outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  25973. for ( let i = 0, l = outline.length; i < l; ) {
  25974. const action = outline[ i ++ ];
  25975. switch ( action ) {
  25976. case 'm': // moveTo
  25977. x = outline[ i ++ ] * scale + offsetX;
  25978. y = outline[ i ++ ] * scale + offsetY;
  25979. path.moveTo( x, y );
  25980. break;
  25981. case 'l': // lineTo
  25982. x = outline[ i ++ ] * scale + offsetX;
  25983. y = outline[ i ++ ] * scale + offsetY;
  25984. path.lineTo( x, y );
  25985. break;
  25986. case 'q': // quadraticCurveTo
  25987. cpx = outline[ i ++ ] * scale + offsetX;
  25988. cpy = outline[ i ++ ] * scale + offsetY;
  25989. cpx1 = outline[ i ++ ] * scale + offsetX;
  25990. cpy1 = outline[ i ++ ] * scale + offsetY;
  25991. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  25992. break;
  25993. case 'b': // bezierCurveTo
  25994. cpx = outline[ i ++ ] * scale + offsetX;
  25995. cpy = outline[ i ++ ] * scale + offsetY;
  25996. cpx1 = outline[ i ++ ] * scale + offsetX;
  25997. cpy1 = outline[ i ++ ] * scale + offsetY;
  25998. cpx2 = outline[ i ++ ] * scale + offsetX;
  25999. cpy2 = outline[ i ++ ] * scale + offsetY;
  26000. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  26001. break;
  26002. }
  26003. }
  26004. }
  26005. return { offsetX: glyph.ha * scale, path: path };
  26006. }
  26007. function FontLoader( manager ) {
  26008. Loader.call( this, manager );
  26009. }
  26010. FontLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  26011. constructor: FontLoader,
  26012. load: function ( url, onLoad, onProgress, onError ) {
  26013. const scope = this;
  26014. const loader = new FileLoader( this.manager );
  26015. loader.setPath( this.path );
  26016. loader.setRequestHeader( this.requestHeader );
  26017. loader.setWithCredentials( scope.withCredentials );
  26018. loader.load( url, function ( text ) {
  26019. let json;
  26020. try {
  26021. json = JSON.parse( text );
  26022. } catch ( e ) {
  26023. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  26024. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  26025. }
  26026. const font = scope.parse( json );
  26027. if ( onLoad ) onLoad( font );
  26028. }, onProgress, onError );
  26029. },
  26030. parse: function ( json ) {
  26031. return new Font( json );
  26032. }
  26033. } );
  26034. let _context;
  26035. const AudioContext = {
  26036. getContext: function () {
  26037. if ( _context === undefined ) {
  26038. _context = new ( window.AudioContext || window.webkitAudioContext )();
  26039. }
  26040. return _context;
  26041. },
  26042. setContext: function ( value ) {
  26043. _context = value;
  26044. }
  26045. };
  26046. function AudioLoader( manager ) {
  26047. Loader.call( this, manager );
  26048. }
  26049. AudioLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  26050. constructor: AudioLoader,
  26051. load: function ( url, onLoad, onProgress, onError ) {
  26052. const scope = this;
  26053. const loader = new FileLoader( scope.manager );
  26054. loader.setResponseType( 'arraybuffer' );
  26055. loader.setPath( scope.path );
  26056. loader.setRequestHeader( scope.requestHeader );
  26057. loader.setWithCredentials( scope.withCredentials );
  26058. loader.load( url, function ( buffer ) {
  26059. try {
  26060. // Create a copy of the buffer. The `decodeAudioData` method
  26061. // detaches the buffer when complete, preventing reuse.
  26062. const bufferCopy = buffer.slice( 0 );
  26063. const context = AudioContext.getContext();
  26064. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  26065. onLoad( audioBuffer );
  26066. } );
  26067. } catch ( e ) {
  26068. if ( onError ) {
  26069. onError( e );
  26070. } else {
  26071. console.error( e );
  26072. }
  26073. scope.manager.itemError( url );
  26074. }
  26075. }, onProgress, onError );
  26076. }
  26077. } );
  26078. function HemisphereLightProbe( skyColor, groundColor, intensity ) {
  26079. LightProbe.call( this, undefined, intensity );
  26080. const color1 = new Color().set( skyColor );
  26081. const color2 = new Color().set( groundColor );
  26082. const sky = new Vector3( color1.r, color1.g, color1.b );
  26083. const ground = new Vector3( color2.r, color2.g, color2.b );
  26084. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  26085. const c0 = Math.sqrt( Math.PI );
  26086. const c1 = c0 * Math.sqrt( 0.75 );
  26087. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  26088. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  26089. }
  26090. HemisphereLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {
  26091. constructor: HemisphereLightProbe,
  26092. isHemisphereLightProbe: true,
  26093. copy: function ( source ) { // modifying colors not currently supported
  26094. LightProbe.prototype.copy.call( this, source );
  26095. return this;
  26096. },
  26097. toJSON: function ( meta ) {
  26098. const data = LightProbe.prototype.toJSON.call( this, meta );
  26099. // data.sh = this.sh.toArray(); // todo
  26100. return data;
  26101. }
  26102. } );
  26103. function AmbientLightProbe( color, intensity ) {
  26104. LightProbe.call( this, undefined, intensity );
  26105. const color1 = new Color().set( color );
  26106. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  26107. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  26108. }
  26109. AmbientLightProbe.prototype = Object.assign( Object.create( LightProbe.prototype ), {
  26110. constructor: AmbientLightProbe,
  26111. isAmbientLightProbe: true,
  26112. copy: function ( source ) { // modifying color not currently supported
  26113. LightProbe.prototype.copy.call( this, source );
  26114. return this;
  26115. },
  26116. toJSON: function ( meta ) {
  26117. const data = LightProbe.prototype.toJSON.call( this, meta );
  26118. // data.sh = this.sh.toArray(); // todo
  26119. return data;
  26120. }
  26121. } );
  26122. const _eyeRight = new Matrix4();
  26123. const _eyeLeft = new Matrix4();
  26124. function StereoCamera() {
  26125. this.type = 'StereoCamera';
  26126. this.aspect = 1;
  26127. this.eyeSep = 0.064;
  26128. this.cameraL = new PerspectiveCamera();
  26129. this.cameraL.layers.enable( 1 );
  26130. this.cameraL.matrixAutoUpdate = false;
  26131. this.cameraR = new PerspectiveCamera();
  26132. this.cameraR.layers.enable( 2 );
  26133. this.cameraR.matrixAutoUpdate = false;
  26134. this._cache = {
  26135. focus: null,
  26136. fov: null,
  26137. aspect: null,
  26138. near: null,
  26139. far: null,
  26140. zoom: null,
  26141. eyeSep: null
  26142. };
  26143. }
  26144. Object.assign( StereoCamera.prototype, {
  26145. update: function ( camera ) {
  26146. const cache = this._cache;
  26147. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  26148. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  26149. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  26150. if ( needsUpdate ) {
  26151. cache.focus = camera.focus;
  26152. cache.fov = camera.fov;
  26153. cache.aspect = camera.aspect * this.aspect;
  26154. cache.near = camera.near;
  26155. cache.far = camera.far;
  26156. cache.zoom = camera.zoom;
  26157. cache.eyeSep = this.eyeSep;
  26158. // Off-axis stereoscopic effect based on
  26159. // http://paulbourke.net/stereographics/stereorender/
  26160. const projectionMatrix = camera.projectionMatrix.clone();
  26161. const eyeSepHalf = cache.eyeSep / 2;
  26162. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  26163. const ymax = ( cache.near * Math.tan( MathUtils.DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  26164. let xmin, xmax;
  26165. // translate xOffset
  26166. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  26167. _eyeRight.elements[ 12 ] = eyeSepHalf;
  26168. // for left eye
  26169. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  26170. xmax = ymax * cache.aspect + eyeSepOnProjection;
  26171. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26172. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26173. this.cameraL.projectionMatrix.copy( projectionMatrix );
  26174. // for right eye
  26175. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  26176. xmax = ymax * cache.aspect - eyeSepOnProjection;
  26177. projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26178. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26179. this.cameraR.projectionMatrix.copy( projectionMatrix );
  26180. }
  26181. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  26182. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  26183. }
  26184. } );
  26185. class Clock {
  26186. constructor( autoStart ) {
  26187. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  26188. this.startTime = 0;
  26189. this.oldTime = 0;
  26190. this.elapsedTime = 0;
  26191. this.running = false;
  26192. }
  26193. start() {
  26194. this.startTime = now();
  26195. this.oldTime = this.startTime;
  26196. this.elapsedTime = 0;
  26197. this.running = true;
  26198. }
  26199. stop() {
  26200. this.getElapsedTime();
  26201. this.running = false;
  26202. this.autoStart = false;
  26203. }
  26204. getElapsedTime() {
  26205. this.getDelta();
  26206. return this.elapsedTime;
  26207. }
  26208. getDelta() {
  26209. let diff = 0;
  26210. if ( this.autoStart && ! this.running ) {
  26211. this.start();
  26212. return 0;
  26213. }
  26214. if ( this.running ) {
  26215. const newTime = now();
  26216. diff = ( newTime - this.oldTime ) / 1000;
  26217. this.oldTime = newTime;
  26218. this.elapsedTime += diff;
  26219. }
  26220. return diff;
  26221. }
  26222. }
  26223. function now() {
  26224. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  26225. }
  26226. const _position$2 = /*@__PURE__*/ new Vector3();
  26227. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  26228. const _scale$1 = /*@__PURE__*/ new Vector3();
  26229. const _orientation = /*@__PURE__*/ new Vector3();
  26230. class AudioListener extends Object3D {
  26231. constructor() {
  26232. super();
  26233. this.type = 'AudioListener';
  26234. this.context = AudioContext.getContext();
  26235. this.gain = this.context.createGain();
  26236. this.gain.connect( this.context.destination );
  26237. this.filter = null;
  26238. this.timeDelta = 0;
  26239. // private
  26240. this._clock = new Clock();
  26241. }
  26242. getInput() {
  26243. return this.gain;
  26244. }
  26245. removeFilter() {
  26246. if ( this.filter !== null ) {
  26247. this.gain.disconnect( this.filter );
  26248. this.filter.disconnect( this.context.destination );
  26249. this.gain.connect( this.context.destination );
  26250. this.filter = null;
  26251. }
  26252. return this;
  26253. }
  26254. getFilter() {
  26255. return this.filter;
  26256. }
  26257. setFilter( value ) {
  26258. if ( this.filter !== null ) {
  26259. this.gain.disconnect( this.filter );
  26260. this.filter.disconnect( this.context.destination );
  26261. } else {
  26262. this.gain.disconnect( this.context.destination );
  26263. }
  26264. this.filter = value;
  26265. this.gain.connect( this.filter );
  26266. this.filter.connect( this.context.destination );
  26267. return this;
  26268. }
  26269. getMasterVolume() {
  26270. return this.gain.gain.value;
  26271. }
  26272. setMasterVolume( value ) {
  26273. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26274. return this;
  26275. }
  26276. updateMatrixWorld( force ) {
  26277. super.updateMatrixWorld( force );
  26278. const listener = this.context.listener;
  26279. const up = this.up;
  26280. this.timeDelta = this._clock.getDelta();
  26281. this.matrixWorld.decompose( _position$2, _quaternion$3, _scale$1 );
  26282. _orientation.set( 0, 0, - 1 ).applyQuaternion( _quaternion$3 );
  26283. if ( listener.positionX ) {
  26284. // code path for Chrome (see #14393)
  26285. const endTime = this.context.currentTime + this.timeDelta;
  26286. listener.positionX.linearRampToValueAtTime( _position$2.x, endTime );
  26287. listener.positionY.linearRampToValueAtTime( _position$2.y, endTime );
  26288. listener.positionZ.linearRampToValueAtTime( _position$2.z, endTime );
  26289. listener.forwardX.linearRampToValueAtTime( _orientation.x, endTime );
  26290. listener.forwardY.linearRampToValueAtTime( _orientation.y, endTime );
  26291. listener.forwardZ.linearRampToValueAtTime( _orientation.z, endTime );
  26292. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26293. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26294. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26295. } else {
  26296. listener.setPosition( _position$2.x, _position$2.y, _position$2.z );
  26297. listener.setOrientation( _orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z );
  26298. }
  26299. }
  26300. }
  26301. class Audio extends Object3D {
  26302. constructor( listener ) {
  26303. super();
  26304. this.type = 'Audio';
  26305. this.listener = listener;
  26306. this.context = listener.context;
  26307. this.gain = this.context.createGain();
  26308. this.gain.connect( listener.getInput() );
  26309. this.autoplay = false;
  26310. this.buffer = null;
  26311. this.detune = 0;
  26312. this.loop = false;
  26313. this.loopStart = 0;
  26314. this.loopEnd = 0;
  26315. this.offset = 0;
  26316. this.duration = undefined;
  26317. this.playbackRate = 1;
  26318. this.isPlaying = false;
  26319. this.hasPlaybackControl = true;
  26320. this.source = null;
  26321. this.sourceType = 'empty';
  26322. this._startedAt = 0;
  26323. this._progress = 0;
  26324. this._connected = false;
  26325. this.filters = [];
  26326. }
  26327. getOutput() {
  26328. return this.gain;
  26329. }
  26330. setNodeSource( audioNode ) {
  26331. this.hasPlaybackControl = false;
  26332. this.sourceType = 'audioNode';
  26333. this.source = audioNode;
  26334. this.connect();
  26335. return this;
  26336. }
  26337. setMediaElementSource( mediaElement ) {
  26338. this.hasPlaybackControl = false;
  26339. this.sourceType = 'mediaNode';
  26340. this.source = this.context.createMediaElementSource( mediaElement );
  26341. this.connect();
  26342. return this;
  26343. }
  26344. setMediaStreamSource( mediaStream ) {
  26345. this.hasPlaybackControl = false;
  26346. this.sourceType = 'mediaStreamNode';
  26347. this.source = this.context.createMediaStreamSource( mediaStream );
  26348. this.connect();
  26349. return this;
  26350. }
  26351. setBuffer( audioBuffer ) {
  26352. this.buffer = audioBuffer;
  26353. this.sourceType = 'buffer';
  26354. if ( this.autoplay ) this.play();
  26355. return this;
  26356. }
  26357. play( delay = 0 ) {
  26358. if ( this.isPlaying === true ) {
  26359. console.warn( 'THREE.Audio: Audio is already playing.' );
  26360. return;
  26361. }
  26362. if ( this.hasPlaybackControl === false ) {
  26363. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26364. return;
  26365. }
  26366. this._startedAt = this.context.currentTime + delay;
  26367. const source = this.context.createBufferSource();
  26368. source.buffer = this.buffer;
  26369. source.loop = this.loop;
  26370. source.loopStart = this.loopStart;
  26371. source.loopEnd = this.loopEnd;
  26372. source.onended = this.onEnded.bind( this );
  26373. source.start( this._startedAt, this._progress + this.offset, this.duration );
  26374. this.isPlaying = true;
  26375. this.source = source;
  26376. this.setDetune( this.detune );
  26377. this.setPlaybackRate( this.playbackRate );
  26378. return this.connect();
  26379. }
  26380. pause() {
  26381. if ( this.hasPlaybackControl === false ) {
  26382. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26383. return;
  26384. }
  26385. if ( this.isPlaying === true ) {
  26386. // update current progress
  26387. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  26388. if ( this.loop === true ) {
  26389. // ensure _progress does not exceed duration with looped audios
  26390. this._progress = this._progress % ( this.duration || this.buffer.duration );
  26391. }
  26392. this.source.stop();
  26393. this.source.onended = null;
  26394. this.isPlaying = false;
  26395. }
  26396. return this;
  26397. }
  26398. stop() {
  26399. if ( this.hasPlaybackControl === false ) {
  26400. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26401. return;
  26402. }
  26403. this._progress = 0;
  26404. this.source.stop();
  26405. this.source.onended = null;
  26406. this.isPlaying = false;
  26407. return this;
  26408. }
  26409. connect() {
  26410. if ( this.filters.length > 0 ) {
  26411. this.source.connect( this.filters[ 0 ] );
  26412. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26413. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26414. }
  26415. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26416. } else {
  26417. this.source.connect( this.getOutput() );
  26418. }
  26419. this._connected = true;
  26420. return this;
  26421. }
  26422. disconnect() {
  26423. if ( this.filters.length > 0 ) {
  26424. this.source.disconnect( this.filters[ 0 ] );
  26425. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26426. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26427. }
  26428. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  26429. } else {
  26430. this.source.disconnect( this.getOutput() );
  26431. }
  26432. this._connected = false;
  26433. return this;
  26434. }
  26435. getFilters() {
  26436. return this.filters;
  26437. }
  26438. setFilters( value ) {
  26439. if ( ! value ) value = [];
  26440. if ( this._connected === true ) {
  26441. this.disconnect();
  26442. this.filters = value.slice();
  26443. this.connect();
  26444. } else {
  26445. this.filters = value.slice();
  26446. }
  26447. return this;
  26448. }
  26449. setDetune( value ) {
  26450. this.detune = value;
  26451. if ( this.source.detune === undefined ) return; // only set detune when available
  26452. if ( this.isPlaying === true ) {
  26453. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  26454. }
  26455. return this;
  26456. }
  26457. getDetune() {
  26458. return this.detune;
  26459. }
  26460. getFilter() {
  26461. return this.getFilters()[ 0 ];
  26462. }
  26463. setFilter( filter ) {
  26464. return this.setFilters( filter ? [ filter ] : [] );
  26465. }
  26466. setPlaybackRate( value ) {
  26467. if ( this.hasPlaybackControl === false ) {
  26468. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26469. return;
  26470. }
  26471. this.playbackRate = value;
  26472. if ( this.isPlaying === true ) {
  26473. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  26474. }
  26475. return this;
  26476. }
  26477. getPlaybackRate() {
  26478. return this.playbackRate;
  26479. }
  26480. onEnded() {
  26481. this.isPlaying = false;
  26482. }
  26483. getLoop() {
  26484. if ( this.hasPlaybackControl === false ) {
  26485. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26486. return false;
  26487. }
  26488. return this.loop;
  26489. }
  26490. setLoop( value ) {
  26491. if ( this.hasPlaybackControl === false ) {
  26492. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26493. return;
  26494. }
  26495. this.loop = value;
  26496. if ( this.isPlaying === true ) {
  26497. this.source.loop = this.loop;
  26498. }
  26499. return this;
  26500. }
  26501. setLoopStart( value ) {
  26502. this.loopStart = value;
  26503. return this;
  26504. }
  26505. setLoopEnd( value ) {
  26506. this.loopEnd = value;
  26507. return this;
  26508. }
  26509. getVolume() {
  26510. return this.gain.gain.value;
  26511. }
  26512. setVolume( value ) {
  26513. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26514. return this;
  26515. }
  26516. }
  26517. const _position$3 = /*@__PURE__*/ new Vector3();
  26518. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  26519. const _scale$2 = /*@__PURE__*/ new Vector3();
  26520. const _orientation$1 = /*@__PURE__*/ new Vector3();
  26521. class PositionalAudio extends Audio {
  26522. constructor( listener ) {
  26523. super( listener );
  26524. this.panner = this.context.createPanner();
  26525. this.panner.panningModel = 'HRTF';
  26526. this.panner.connect( this.gain );
  26527. }
  26528. getOutput() {
  26529. return this.panner;
  26530. }
  26531. getRefDistance() {
  26532. return this.panner.refDistance;
  26533. }
  26534. setRefDistance( value ) {
  26535. this.panner.refDistance = value;
  26536. return this;
  26537. }
  26538. getRolloffFactor() {
  26539. return this.panner.rolloffFactor;
  26540. }
  26541. setRolloffFactor( value ) {
  26542. this.panner.rolloffFactor = value;
  26543. return this;
  26544. }
  26545. getDistanceModel() {
  26546. return this.panner.distanceModel;
  26547. }
  26548. setDistanceModel( value ) {
  26549. this.panner.distanceModel = value;
  26550. return this;
  26551. }
  26552. getMaxDistance() {
  26553. return this.panner.maxDistance;
  26554. }
  26555. setMaxDistance( value ) {
  26556. this.panner.maxDistance = value;
  26557. return this;
  26558. }
  26559. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  26560. this.panner.coneInnerAngle = coneInnerAngle;
  26561. this.panner.coneOuterAngle = coneOuterAngle;
  26562. this.panner.coneOuterGain = coneOuterGain;
  26563. return this;
  26564. }
  26565. updateMatrixWorld( force ) {
  26566. super.updateMatrixWorld( force );
  26567. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  26568. this.matrixWorld.decompose( _position$3, _quaternion$4, _scale$2 );
  26569. _orientation$1.set( 0, 0, 1 ).applyQuaternion( _quaternion$4 );
  26570. const panner = this.panner;
  26571. if ( panner.positionX ) {
  26572. // code path for Chrome and Firefox (see #14393)
  26573. const endTime = this.context.currentTime + this.listener.timeDelta;
  26574. panner.positionX.linearRampToValueAtTime( _position$3.x, endTime );
  26575. panner.positionY.linearRampToValueAtTime( _position$3.y, endTime );
  26576. panner.positionZ.linearRampToValueAtTime( _position$3.z, endTime );
  26577. panner.orientationX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26578. panner.orientationY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26579. panner.orientationZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26580. } else {
  26581. panner.setPosition( _position$3.x, _position$3.y, _position$3.z );
  26582. panner.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z );
  26583. }
  26584. }
  26585. }
  26586. class AudioAnalyser {
  26587. constructor( audio, fftSize = 2048 ) {
  26588. this.analyser = audio.context.createAnalyser();
  26589. this.analyser.fftSize = fftSize;
  26590. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  26591. audio.getOutput().connect( this.analyser );
  26592. }
  26593. getFrequencyData() {
  26594. this.analyser.getByteFrequencyData( this.data );
  26595. return this.data;
  26596. }
  26597. getAverageFrequency() {
  26598. let value = 0;
  26599. const data = this.getFrequencyData();
  26600. for ( let i = 0; i < data.length; i ++ ) {
  26601. value += data[ i ];
  26602. }
  26603. return value / data.length;
  26604. }
  26605. }
  26606. function PropertyMixer( binding, typeName, valueSize ) {
  26607. this.binding = binding;
  26608. this.valueSize = valueSize;
  26609. let mixFunction,
  26610. mixFunctionAdditive,
  26611. setIdentity;
  26612. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26613. //
  26614. // interpolators can use .buffer as their .result
  26615. // the data then goes to 'incoming'
  26616. //
  26617. // 'accu0' and 'accu1' are used frame-interleaved for
  26618. // the cumulative result and are compared to detect
  26619. // changes
  26620. //
  26621. // 'orig' stores the original state of the property
  26622. //
  26623. // 'add' is used for additive cumulative results
  26624. //
  26625. // 'work' is optional and is only present for quaternion types. It is used
  26626. // to store intermediate quaternion multiplication results
  26627. switch ( typeName ) {
  26628. case 'quaternion':
  26629. mixFunction = this._slerp;
  26630. mixFunctionAdditive = this._slerpAdditive;
  26631. setIdentity = this._setAdditiveIdentityQuaternion;
  26632. this.buffer = new Float64Array( valueSize * 6 );
  26633. this._workIndex = 5;
  26634. break;
  26635. case 'string':
  26636. case 'bool':
  26637. mixFunction = this._select;
  26638. // Use the regular mix function and for additive on these types,
  26639. // additive is not relevant for non-numeric types
  26640. mixFunctionAdditive = this._select;
  26641. setIdentity = this._setAdditiveIdentityOther;
  26642. this.buffer = new Array( valueSize * 5 );
  26643. break;
  26644. default:
  26645. mixFunction = this._lerp;
  26646. mixFunctionAdditive = this._lerpAdditive;
  26647. setIdentity = this._setAdditiveIdentityNumeric;
  26648. this.buffer = new Float64Array( valueSize * 5 );
  26649. }
  26650. this._mixBufferRegion = mixFunction;
  26651. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26652. this._setIdentity = setIdentity;
  26653. this._origIndex = 3;
  26654. this._addIndex = 4;
  26655. this.cumulativeWeight = 0;
  26656. this.cumulativeWeightAdditive = 0;
  26657. this.useCount = 0;
  26658. this.referenceCount = 0;
  26659. }
  26660. Object.assign( PropertyMixer.prototype, {
  26661. // accumulate data in the 'incoming' region into 'accu<i>'
  26662. accumulate: function ( accuIndex, weight ) {
  26663. // note: happily accumulating nothing when weight = 0, the caller knows
  26664. // the weight and shouldn't have made the call in the first place
  26665. const buffer = this.buffer,
  26666. stride = this.valueSize,
  26667. offset = accuIndex * stride + stride;
  26668. let currentWeight = this.cumulativeWeight;
  26669. if ( currentWeight === 0 ) {
  26670. // accuN := incoming * weight
  26671. for ( let i = 0; i !== stride; ++ i ) {
  26672. buffer[ offset + i ] = buffer[ i ];
  26673. }
  26674. currentWeight = weight;
  26675. } else {
  26676. // accuN := accuN + incoming * weight
  26677. currentWeight += weight;
  26678. const mix = weight / currentWeight;
  26679. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26680. }
  26681. this.cumulativeWeight = currentWeight;
  26682. },
  26683. // accumulate data in the 'incoming' region into 'add'
  26684. accumulateAdditive: function ( weight ) {
  26685. const buffer = this.buffer,
  26686. stride = this.valueSize,
  26687. offset = stride * this._addIndex;
  26688. if ( this.cumulativeWeightAdditive === 0 ) {
  26689. // add = identity
  26690. this._setIdentity();
  26691. }
  26692. // add := add + incoming * weight
  26693. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  26694. this.cumulativeWeightAdditive += weight;
  26695. },
  26696. // apply the state of 'accu<i>' to the binding when accus differ
  26697. apply: function ( accuIndex ) {
  26698. const stride = this.valueSize,
  26699. buffer = this.buffer,
  26700. offset = accuIndex * stride + stride,
  26701. weight = this.cumulativeWeight,
  26702. weightAdditive = this.cumulativeWeightAdditive,
  26703. binding = this.binding;
  26704. this.cumulativeWeight = 0;
  26705. this.cumulativeWeightAdditive = 0;
  26706. if ( weight < 1 ) {
  26707. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26708. const originalValueOffset = stride * this._origIndex;
  26709. this._mixBufferRegion(
  26710. buffer, offset, originalValueOffset, 1 - weight, stride );
  26711. }
  26712. if ( weightAdditive > 0 ) {
  26713. // accuN := accuN + additive accuN
  26714. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  26715. }
  26716. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  26717. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26718. // value has changed -> update scene graph
  26719. binding.setValue( buffer, offset );
  26720. break;
  26721. }
  26722. }
  26723. },
  26724. // remember the state of the bound property and copy it to both accus
  26725. saveOriginalState: function () {
  26726. const binding = this.binding;
  26727. const buffer = this.buffer,
  26728. stride = this.valueSize,
  26729. originalValueOffset = stride * this._origIndex;
  26730. binding.getValue( buffer, originalValueOffset );
  26731. // accu[0..1] := orig -- initially detect changes against the original
  26732. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26733. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26734. }
  26735. // Add to identity for additive
  26736. this._setIdentity();
  26737. this.cumulativeWeight = 0;
  26738. this.cumulativeWeightAdditive = 0;
  26739. },
  26740. // apply the state previously taken via 'saveOriginalState' to the binding
  26741. restoreOriginalState: function () {
  26742. const originalValueOffset = this.valueSize * 3;
  26743. this.binding.setValue( this.buffer, originalValueOffset );
  26744. },
  26745. _setAdditiveIdentityNumeric: function () {
  26746. const startIndex = this._addIndex * this.valueSize;
  26747. const endIndex = startIndex + this.valueSize;
  26748. for ( let i = startIndex; i < endIndex; i ++ ) {
  26749. this.buffer[ i ] = 0;
  26750. }
  26751. },
  26752. _setAdditiveIdentityQuaternion: function () {
  26753. this._setAdditiveIdentityNumeric();
  26754. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26755. },
  26756. _setAdditiveIdentityOther: function () {
  26757. const startIndex = this._origIndex * this.valueSize;
  26758. const targetIndex = this._addIndex * this.valueSize;
  26759. for ( let i = 0; i < this.valueSize; i ++ ) {
  26760. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26761. }
  26762. },
  26763. // mix functions
  26764. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  26765. if ( t >= 0.5 ) {
  26766. for ( let i = 0; i !== stride; ++ i ) {
  26767. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26768. }
  26769. }
  26770. },
  26771. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  26772. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26773. },
  26774. _slerpAdditive: function ( buffer, dstOffset, srcOffset, t, stride ) {
  26775. const workOffset = this._workIndex * stride;
  26776. // Store result in intermediate buffer offset
  26777. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26778. // Slerp to the intermediate result
  26779. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26780. },
  26781. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  26782. const s = 1 - t;
  26783. for ( let i = 0; i !== stride; ++ i ) {
  26784. const j = dstOffset + i;
  26785. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26786. }
  26787. },
  26788. _lerpAdditive: function ( buffer, dstOffset, srcOffset, t, stride ) {
  26789. for ( let i = 0; i !== stride; ++ i ) {
  26790. const j = dstOffset + i;
  26791. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  26792. }
  26793. }
  26794. } );
  26795. // Characters [].:/ are reserved for track binding syntax.
  26796. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26797. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  26798. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26799. // only latin characters, and the unicode \p{L} is not yet supported. So
  26800. // instead, we exclude reserved characters and match everything else.
  26801. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26802. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  26803. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26804. // be matched to parse the rest of the track name.
  26805. const _directoryRe = /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  26806. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26807. const _nodeRe = /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  26808. // Object on target node, and accessor. May not contain reserved
  26809. // characters. Accessor may contain any character except closing bracket.
  26810. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  26811. // Property and accessor. May not contain reserved characters. Accessor may
  26812. // contain any non-bracket characters.
  26813. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  26814. const _trackRe = new RegExp( ''
  26815. + '^'
  26816. + _directoryRe
  26817. + _nodeRe
  26818. + _objectRe
  26819. + _propertyRe
  26820. + '$'
  26821. );
  26822. const _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  26823. function Composite( targetGroup, path, optionalParsedPath ) {
  26824. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  26825. this._targetGroup = targetGroup;
  26826. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26827. }
  26828. Object.assign( Composite.prototype, {
  26829. getValue: function ( array, offset ) {
  26830. this.bind(); // bind all binding
  26831. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26832. binding = this._bindings[ firstValidIndex ];
  26833. // and only call .getValue on the first
  26834. if ( binding !== undefined ) binding.getValue( array, offset );
  26835. },
  26836. setValue: function ( array, offset ) {
  26837. const bindings = this._bindings;
  26838. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26839. bindings[ i ].setValue( array, offset );
  26840. }
  26841. },
  26842. bind: function () {
  26843. const bindings = this._bindings;
  26844. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26845. bindings[ i ].bind();
  26846. }
  26847. },
  26848. unbind: function () {
  26849. const bindings = this._bindings;
  26850. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26851. bindings[ i ].unbind();
  26852. }
  26853. }
  26854. } );
  26855. function PropertyBinding( rootNode, path, parsedPath ) {
  26856. this.path = path;
  26857. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  26858. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  26859. this.rootNode = rootNode;
  26860. }
  26861. Object.assign( PropertyBinding, {
  26862. Composite: Composite,
  26863. create: function ( root, path, parsedPath ) {
  26864. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26865. return new PropertyBinding( root, path, parsedPath );
  26866. } else {
  26867. return new PropertyBinding.Composite( root, path, parsedPath );
  26868. }
  26869. },
  26870. /**
  26871. * Replaces spaces with underscores and removes unsupported characters from
  26872. * node names, to ensure compatibility with parseTrackName().
  26873. *
  26874. * @param {string} name Node name to be sanitized.
  26875. * @return {string}
  26876. */
  26877. sanitizeNodeName: function ( name ) {
  26878. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26879. },
  26880. parseTrackName: function ( trackName ) {
  26881. const matches = _trackRe.exec( trackName );
  26882. if ( ! matches ) {
  26883. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26884. }
  26885. const results = {
  26886. // directoryName: matches[ 1 ], // (tschw) currently unused
  26887. nodeName: matches[ 2 ],
  26888. objectName: matches[ 3 ],
  26889. objectIndex: matches[ 4 ],
  26890. propertyName: matches[ 5 ], // required
  26891. propertyIndex: matches[ 6 ]
  26892. };
  26893. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26894. if ( lastDot !== undefined && lastDot !== - 1 ) {
  26895. const objectName = results.nodeName.substring( lastDot + 1 );
  26896. // Object names must be checked against an allowlist. Otherwise, there
  26897. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26898. // 'bar' could be the objectName, or part of a nodeName (which can
  26899. // include '.' characters).
  26900. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  26901. results.nodeName = results.nodeName.substring( 0, lastDot );
  26902. results.objectName = objectName;
  26903. }
  26904. }
  26905. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26906. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26907. }
  26908. return results;
  26909. },
  26910. findNode: function ( root, nodeName ) {
  26911. if ( ! nodeName || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  26912. return root;
  26913. }
  26914. // search into skeleton bones.
  26915. if ( root.skeleton ) {
  26916. const bone = root.skeleton.getBoneByName( nodeName );
  26917. if ( bone !== undefined ) {
  26918. return bone;
  26919. }
  26920. }
  26921. // search into node subtree.
  26922. if ( root.children ) {
  26923. const searchNodeSubtree = function ( children ) {
  26924. for ( let i = 0; i < children.length; i ++ ) {
  26925. const childNode = children[ i ];
  26926. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26927. return childNode;
  26928. }
  26929. const result = searchNodeSubtree( childNode.children );
  26930. if ( result ) return result;
  26931. }
  26932. return null;
  26933. };
  26934. const subTreeNode = searchNodeSubtree( root.children );
  26935. if ( subTreeNode ) {
  26936. return subTreeNode;
  26937. }
  26938. }
  26939. return null;
  26940. }
  26941. } );
  26942. Object.assign( PropertyBinding.prototype, { // prototype, continued
  26943. // these are used to "bind" a nonexistent property
  26944. _getValue_unavailable: function () {},
  26945. _setValue_unavailable: function () {},
  26946. BindingType: {
  26947. Direct: 0,
  26948. EntireArray: 1,
  26949. ArrayElement: 2,
  26950. HasFromToArray: 3
  26951. },
  26952. Versioning: {
  26953. None: 0,
  26954. NeedsUpdate: 1,
  26955. MatrixWorldNeedsUpdate: 2
  26956. },
  26957. GetterByBindingType: [
  26958. function getValue_direct( buffer, offset ) {
  26959. buffer[ offset ] = this.node[ this.propertyName ];
  26960. },
  26961. function getValue_array( buffer, offset ) {
  26962. const source = this.resolvedProperty;
  26963. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  26964. buffer[ offset ++ ] = source[ i ];
  26965. }
  26966. },
  26967. function getValue_arrayElement( buffer, offset ) {
  26968. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26969. },
  26970. function getValue_toArray( buffer, offset ) {
  26971. this.resolvedProperty.toArray( buffer, offset );
  26972. }
  26973. ],
  26974. SetterByBindingTypeAndVersioning: [
  26975. [
  26976. // Direct
  26977. function setValue_direct( buffer, offset ) {
  26978. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26979. },
  26980. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  26981. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26982. this.targetObject.needsUpdate = true;
  26983. },
  26984. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26985. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26986. this.targetObject.matrixWorldNeedsUpdate = true;
  26987. }
  26988. ], [
  26989. // EntireArray
  26990. function setValue_array( buffer, offset ) {
  26991. const dest = this.resolvedProperty;
  26992. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26993. dest[ i ] = buffer[ offset ++ ];
  26994. }
  26995. },
  26996. function setValue_array_setNeedsUpdate( buffer, offset ) {
  26997. const dest = this.resolvedProperty;
  26998. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26999. dest[ i ] = buffer[ offset ++ ];
  27000. }
  27001. this.targetObject.needsUpdate = true;
  27002. },
  27003. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27004. const dest = this.resolvedProperty;
  27005. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27006. dest[ i ] = buffer[ offset ++ ];
  27007. }
  27008. this.targetObject.matrixWorldNeedsUpdate = true;
  27009. }
  27010. ], [
  27011. // ArrayElement
  27012. function setValue_arrayElement( buffer, offset ) {
  27013. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27014. },
  27015. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  27016. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27017. this.targetObject.needsUpdate = true;
  27018. },
  27019. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27020. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27021. this.targetObject.matrixWorldNeedsUpdate = true;
  27022. }
  27023. ], [
  27024. // HasToFromArray
  27025. function setValue_fromArray( buffer, offset ) {
  27026. this.resolvedProperty.fromArray( buffer, offset );
  27027. },
  27028. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  27029. this.resolvedProperty.fromArray( buffer, offset );
  27030. this.targetObject.needsUpdate = true;
  27031. },
  27032. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27033. this.resolvedProperty.fromArray( buffer, offset );
  27034. this.targetObject.matrixWorldNeedsUpdate = true;
  27035. }
  27036. ]
  27037. ],
  27038. getValue: function getValue_unbound( targetArray, offset ) {
  27039. this.bind();
  27040. this.getValue( targetArray, offset );
  27041. // Note: This class uses a State pattern on a per-method basis:
  27042. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  27043. // prototype version of these methods with one that represents
  27044. // the bound state. When the property is not found, the methods
  27045. // become no-ops.
  27046. },
  27047. setValue: function getValue_unbound( sourceArray, offset ) {
  27048. this.bind();
  27049. this.setValue( sourceArray, offset );
  27050. },
  27051. // create getter / setter pair for a property in the scene graph
  27052. bind: function () {
  27053. let targetObject = this.node;
  27054. const parsedPath = this.parsedPath;
  27055. const objectName = parsedPath.objectName;
  27056. const propertyName = parsedPath.propertyName;
  27057. let propertyIndex = parsedPath.propertyIndex;
  27058. if ( ! targetObject ) {
  27059. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  27060. this.node = targetObject;
  27061. }
  27062. // set fail state so we can just 'return' on error
  27063. this.getValue = this._getValue_unavailable;
  27064. this.setValue = this._setValue_unavailable;
  27065. // ensure there is a value node
  27066. if ( ! targetObject ) {
  27067. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  27068. return;
  27069. }
  27070. if ( objectName ) {
  27071. let objectIndex = parsedPath.objectIndex;
  27072. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  27073. switch ( objectName ) {
  27074. case 'materials':
  27075. if ( ! targetObject.material ) {
  27076. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27077. return;
  27078. }
  27079. if ( ! targetObject.material.materials ) {
  27080. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  27081. return;
  27082. }
  27083. targetObject = targetObject.material.materials;
  27084. break;
  27085. case 'bones':
  27086. if ( ! targetObject.skeleton ) {
  27087. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  27088. return;
  27089. }
  27090. // potential future optimization: skip this if propertyIndex is already an integer
  27091. // and convert the integer string to a true integer.
  27092. targetObject = targetObject.skeleton.bones;
  27093. // support resolving morphTarget names into indices.
  27094. for ( let i = 0; i < targetObject.length; i ++ ) {
  27095. if ( targetObject[ i ].name === objectIndex ) {
  27096. objectIndex = i;
  27097. break;
  27098. }
  27099. }
  27100. break;
  27101. default:
  27102. if ( targetObject[ objectName ] === undefined ) {
  27103. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  27104. return;
  27105. }
  27106. targetObject = targetObject[ objectName ];
  27107. }
  27108. if ( objectIndex !== undefined ) {
  27109. if ( targetObject[ objectIndex ] === undefined ) {
  27110. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  27111. return;
  27112. }
  27113. targetObject = targetObject[ objectIndex ];
  27114. }
  27115. }
  27116. // resolve property
  27117. const nodeProperty = targetObject[ propertyName ];
  27118. if ( nodeProperty === undefined ) {
  27119. const nodeName = parsedPath.nodeName;
  27120. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  27121. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  27122. return;
  27123. }
  27124. // determine versioning scheme
  27125. let versioning = this.Versioning.None;
  27126. this.targetObject = targetObject;
  27127. if ( targetObject.needsUpdate !== undefined ) { // material
  27128. versioning = this.Versioning.NeedsUpdate;
  27129. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  27130. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  27131. }
  27132. // determine how the property gets bound
  27133. let bindingType = this.BindingType.Direct;
  27134. if ( propertyIndex !== undefined ) {
  27135. // access a sub element of the property array (only primitives are supported right now)
  27136. if ( propertyName === 'morphTargetInfluences' ) {
  27137. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  27138. // support resolving morphTarget names into indices.
  27139. if ( ! targetObject.geometry ) {
  27140. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  27141. return;
  27142. }
  27143. if ( targetObject.geometry.isBufferGeometry ) {
  27144. if ( ! targetObject.geometry.morphAttributes ) {
  27145. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  27146. return;
  27147. }
  27148. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  27149. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  27150. }
  27151. } else {
  27152. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this );
  27153. return;
  27154. }
  27155. }
  27156. bindingType = this.BindingType.ArrayElement;
  27157. this.resolvedProperty = nodeProperty;
  27158. this.propertyIndex = propertyIndex;
  27159. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  27160. // must use copy for Object3D.Euler/Quaternion
  27161. bindingType = this.BindingType.HasFromToArray;
  27162. this.resolvedProperty = nodeProperty;
  27163. } else if ( Array.isArray( nodeProperty ) ) {
  27164. bindingType = this.BindingType.EntireArray;
  27165. this.resolvedProperty = nodeProperty;
  27166. } else {
  27167. this.propertyName = propertyName;
  27168. }
  27169. // select getter / setter
  27170. this.getValue = this.GetterByBindingType[ bindingType ];
  27171. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  27172. },
  27173. unbind: function () {
  27174. this.node = null;
  27175. // back to the prototype version of getValue / setValue
  27176. // note: avoiding to mutate the shape of 'this' via 'delete'
  27177. this.getValue = this._getValue_unbound;
  27178. this.setValue = this._setValue_unbound;
  27179. }
  27180. } );
  27181. // DECLARE ALIAS AFTER assign prototype
  27182. Object.assign( PropertyBinding.prototype, {
  27183. // initial state of these methods that calls 'bind'
  27184. _getValue_unbound: PropertyBinding.prototype.getValue,
  27185. _setValue_unbound: PropertyBinding.prototype.setValue,
  27186. } );
  27187. /**
  27188. *
  27189. * A group of objects that receives a shared animation state.
  27190. *
  27191. * Usage:
  27192. *
  27193. * - Add objects you would otherwise pass as 'root' to the
  27194. * constructor or the .clipAction method of AnimationMixer.
  27195. *
  27196. * - Instead pass this object as 'root'.
  27197. *
  27198. * - You can also add and remove objects later when the mixer
  27199. * is running.
  27200. *
  27201. * Note:
  27202. *
  27203. * Objects of this class appear as one object to the mixer,
  27204. * so cache control of the individual objects must be done
  27205. * on the group.
  27206. *
  27207. * Limitation:
  27208. *
  27209. * - The animated properties must be compatible among the
  27210. * all objects in the group.
  27211. *
  27212. * - A single property can either be controlled through a
  27213. * target group or directly, but not both.
  27214. */
  27215. function AnimationObjectGroup() {
  27216. this.uuid = MathUtils.generateUUID();
  27217. // cached objects followed by the active ones
  27218. this._objects = Array.prototype.slice.call( arguments );
  27219. this.nCachedObjects_ = 0; // threshold
  27220. // note: read by PropertyBinding.Composite
  27221. const indices = {};
  27222. this._indicesByUUID = indices; // for bookkeeping
  27223. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27224. indices[ arguments[ i ].uuid ] = i;
  27225. }
  27226. this._paths = []; // inside: string
  27227. this._parsedPaths = []; // inside: { we don't care, here }
  27228. this._bindings = []; // inside: Array< PropertyBinding >
  27229. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  27230. const scope = this;
  27231. this.stats = {
  27232. objects: {
  27233. get total() {
  27234. return scope._objects.length;
  27235. },
  27236. get inUse() {
  27237. return this.total - scope.nCachedObjects_;
  27238. }
  27239. },
  27240. get bindingsPerObject() {
  27241. return scope._bindings.length;
  27242. }
  27243. };
  27244. }
  27245. Object.assign( AnimationObjectGroup.prototype, {
  27246. isAnimationObjectGroup: true,
  27247. add: function () {
  27248. const objects = this._objects,
  27249. indicesByUUID = this._indicesByUUID,
  27250. paths = this._paths,
  27251. parsedPaths = this._parsedPaths,
  27252. bindings = this._bindings,
  27253. nBindings = bindings.length;
  27254. let knownObject = undefined,
  27255. nObjects = objects.length,
  27256. nCachedObjects = this.nCachedObjects_;
  27257. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27258. const object = arguments[ i ],
  27259. uuid = object.uuid;
  27260. let index = indicesByUUID[ uuid ];
  27261. if ( index === undefined ) {
  27262. // unknown object -> add it to the ACTIVE region
  27263. index = nObjects ++;
  27264. indicesByUUID[ uuid ] = index;
  27265. objects.push( object );
  27266. // accounting is done, now do the same for all bindings
  27267. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27268. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  27269. }
  27270. } else if ( index < nCachedObjects ) {
  27271. knownObject = objects[ index ];
  27272. // move existing object to the ACTIVE region
  27273. const firstActiveIndex = -- nCachedObjects,
  27274. lastCachedObject = objects[ firstActiveIndex ];
  27275. indicesByUUID[ lastCachedObject.uuid ] = index;
  27276. objects[ index ] = lastCachedObject;
  27277. indicesByUUID[ uuid ] = firstActiveIndex;
  27278. objects[ firstActiveIndex ] = object;
  27279. // accounting is done, now do the same for all bindings
  27280. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27281. const bindingsForPath = bindings[ j ],
  27282. lastCached = bindingsForPath[ firstActiveIndex ];
  27283. let binding = bindingsForPath[ index ];
  27284. bindingsForPath[ index ] = lastCached;
  27285. if ( binding === undefined ) {
  27286. // since we do not bother to create new bindings
  27287. // for objects that are cached, the binding may
  27288. // or may not exist
  27289. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  27290. }
  27291. bindingsForPath[ firstActiveIndex ] = binding;
  27292. }
  27293. } else if ( objects[ index ] !== knownObject ) {
  27294. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27295. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27296. } // else the object is already where we want it to be
  27297. } // for arguments
  27298. this.nCachedObjects_ = nCachedObjects;
  27299. },
  27300. remove: function () {
  27301. const objects = this._objects,
  27302. indicesByUUID = this._indicesByUUID,
  27303. bindings = this._bindings,
  27304. nBindings = bindings.length;
  27305. let nCachedObjects = this.nCachedObjects_;
  27306. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27307. const object = arguments[ i ],
  27308. uuid = object.uuid,
  27309. index = indicesByUUID[ uuid ];
  27310. if ( index !== undefined && index >= nCachedObjects ) {
  27311. // move existing object into the CACHED region
  27312. const lastCachedIndex = nCachedObjects ++,
  27313. firstActiveObject = objects[ lastCachedIndex ];
  27314. indicesByUUID[ firstActiveObject.uuid ] = index;
  27315. objects[ index ] = firstActiveObject;
  27316. indicesByUUID[ uuid ] = lastCachedIndex;
  27317. objects[ lastCachedIndex ] = object;
  27318. // accounting is done, now do the same for all bindings
  27319. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27320. const bindingsForPath = bindings[ j ],
  27321. firstActive = bindingsForPath[ lastCachedIndex ],
  27322. binding = bindingsForPath[ index ];
  27323. bindingsForPath[ index ] = firstActive;
  27324. bindingsForPath[ lastCachedIndex ] = binding;
  27325. }
  27326. }
  27327. } // for arguments
  27328. this.nCachedObjects_ = nCachedObjects;
  27329. },
  27330. // remove & forget
  27331. uncache: function () {
  27332. const objects = this._objects,
  27333. indicesByUUID = this._indicesByUUID,
  27334. bindings = this._bindings,
  27335. nBindings = bindings.length;
  27336. let nCachedObjects = this.nCachedObjects_,
  27337. nObjects = objects.length;
  27338. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27339. const object = arguments[ i ],
  27340. uuid = object.uuid,
  27341. index = indicesByUUID[ uuid ];
  27342. if ( index !== undefined ) {
  27343. delete indicesByUUID[ uuid ];
  27344. if ( index < nCachedObjects ) {
  27345. // object is cached, shrink the CACHED region
  27346. const firstActiveIndex = -- nCachedObjects,
  27347. lastCachedObject = objects[ firstActiveIndex ],
  27348. lastIndex = -- nObjects,
  27349. lastObject = objects[ lastIndex ];
  27350. // last cached object takes this object's place
  27351. indicesByUUID[ lastCachedObject.uuid ] = index;
  27352. objects[ index ] = lastCachedObject;
  27353. // last object goes to the activated slot and pop
  27354. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27355. objects[ firstActiveIndex ] = lastObject;
  27356. objects.pop();
  27357. // accounting is done, now do the same for all bindings
  27358. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27359. const bindingsForPath = bindings[ j ],
  27360. lastCached = bindingsForPath[ firstActiveIndex ],
  27361. last = bindingsForPath[ lastIndex ];
  27362. bindingsForPath[ index ] = lastCached;
  27363. bindingsForPath[ firstActiveIndex ] = last;
  27364. bindingsForPath.pop();
  27365. }
  27366. } else {
  27367. // object is active, just swap with the last and pop
  27368. const lastIndex = -- nObjects,
  27369. lastObject = objects[ lastIndex ];
  27370. if ( lastIndex > 0 ) {
  27371. indicesByUUID[ lastObject.uuid ] = index;
  27372. }
  27373. objects[ index ] = lastObject;
  27374. objects.pop();
  27375. // accounting is done, now do the same for all bindings
  27376. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27377. const bindingsForPath = bindings[ j ];
  27378. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27379. bindingsForPath.pop();
  27380. }
  27381. } // cached or active
  27382. } // if object is known
  27383. } // for arguments
  27384. this.nCachedObjects_ = nCachedObjects;
  27385. },
  27386. // Internal interface used by befriended PropertyBinding.Composite:
  27387. subscribe_: function ( path, parsedPath ) {
  27388. // returns an array of bindings for the given path that is changed
  27389. // according to the contained objects in the group
  27390. const indicesByPath = this._bindingsIndicesByPath;
  27391. let index = indicesByPath[ path ];
  27392. const bindings = this._bindings;
  27393. if ( index !== undefined ) return bindings[ index ];
  27394. const paths = this._paths,
  27395. parsedPaths = this._parsedPaths,
  27396. objects = this._objects,
  27397. nObjects = objects.length,
  27398. nCachedObjects = this.nCachedObjects_,
  27399. bindingsForPath = new Array( nObjects );
  27400. index = bindings.length;
  27401. indicesByPath[ path ] = index;
  27402. paths.push( path );
  27403. parsedPaths.push( parsedPath );
  27404. bindings.push( bindingsForPath );
  27405. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  27406. const object = objects[ i ];
  27407. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  27408. }
  27409. return bindingsForPath;
  27410. },
  27411. unsubscribe_: function ( path ) {
  27412. // tells the group to forget about a property path and no longer
  27413. // update the array previously obtained with 'subscribe_'
  27414. const indicesByPath = this._bindingsIndicesByPath,
  27415. index = indicesByPath[ path ];
  27416. if ( index !== undefined ) {
  27417. const paths = this._paths,
  27418. parsedPaths = this._parsedPaths,
  27419. bindings = this._bindings,
  27420. lastBindingsIndex = bindings.length - 1,
  27421. lastBindings = bindings[ lastBindingsIndex ],
  27422. lastBindingsPath = path[ lastBindingsIndex ];
  27423. indicesByPath[ lastBindingsPath ] = index;
  27424. bindings[ index ] = lastBindings;
  27425. bindings.pop();
  27426. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  27427. parsedPaths.pop();
  27428. paths[ index ] = paths[ lastBindingsIndex ];
  27429. paths.pop();
  27430. }
  27431. }
  27432. } );
  27433. class AnimationAction {
  27434. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  27435. this._mixer = mixer;
  27436. this._clip = clip;
  27437. this._localRoot = localRoot;
  27438. this.blendMode = blendMode;
  27439. const tracks = clip.tracks,
  27440. nTracks = tracks.length,
  27441. interpolants = new Array( nTracks );
  27442. const interpolantSettings = {
  27443. endingStart: ZeroCurvatureEnding,
  27444. endingEnd: ZeroCurvatureEnding
  27445. };
  27446. for ( let i = 0; i !== nTracks; ++ i ) {
  27447. const interpolant = tracks[ i ].createInterpolant( null );
  27448. interpolants[ i ] = interpolant;
  27449. interpolant.settings = interpolantSettings;
  27450. }
  27451. this._interpolantSettings = interpolantSettings;
  27452. this._interpolants = interpolants; // bound by the mixer
  27453. // inside: PropertyMixer (managed by the mixer)
  27454. this._propertyBindings = new Array( nTracks );
  27455. this._cacheIndex = null; // for the memory manager
  27456. this._byClipCacheIndex = null; // for the memory manager
  27457. this._timeScaleInterpolant = null;
  27458. this._weightInterpolant = null;
  27459. this.loop = LoopRepeat;
  27460. this._loopCount = - 1;
  27461. // global mixer time when the action is to be started
  27462. // it's set back to 'null' upon start of the action
  27463. this._startTime = null;
  27464. // scaled local time of the action
  27465. // gets clamped or wrapped to 0..clip.duration according to loop
  27466. this.time = 0;
  27467. this.timeScale = 1;
  27468. this._effectiveTimeScale = 1;
  27469. this.weight = 1;
  27470. this._effectiveWeight = 1;
  27471. this.repetitions = Infinity; // no. of repetitions when looping
  27472. this.paused = false; // true -> zero effective time scale
  27473. this.enabled = true; // false -> zero effective weight
  27474. this.clampWhenFinished = false;// keep feeding the last frame?
  27475. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  27476. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  27477. }
  27478. // State & Scheduling
  27479. play() {
  27480. this._mixer._activateAction( this );
  27481. return this;
  27482. }
  27483. stop() {
  27484. this._mixer._deactivateAction( this );
  27485. return this.reset();
  27486. }
  27487. reset() {
  27488. this.paused = false;
  27489. this.enabled = true;
  27490. this.time = 0; // restart clip
  27491. this._loopCount = - 1;// forget previous loops
  27492. this._startTime = null;// forget scheduling
  27493. return this.stopFading().stopWarping();
  27494. }
  27495. isRunning() {
  27496. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27497. this._startTime === null && this._mixer._isActiveAction( this );
  27498. }
  27499. // return true when play has been called
  27500. isScheduled() {
  27501. return this._mixer._isActiveAction( this );
  27502. }
  27503. startAt( time ) {
  27504. this._startTime = time;
  27505. return this;
  27506. }
  27507. setLoop( mode, repetitions ) {
  27508. this.loop = mode;
  27509. this.repetitions = repetitions;
  27510. return this;
  27511. }
  27512. // Weight
  27513. // set the weight stopping any scheduled fading
  27514. // although .enabled = false yields an effective weight of zero, this
  27515. // method does *not* change .enabled, because it would be confusing
  27516. setEffectiveWeight( weight ) {
  27517. this.weight = weight;
  27518. // note: same logic as when updated at runtime
  27519. this._effectiveWeight = this.enabled ? weight : 0;
  27520. return this.stopFading();
  27521. }
  27522. // return the weight considering fading and .enabled
  27523. getEffectiveWeight() {
  27524. return this._effectiveWeight;
  27525. }
  27526. fadeIn( duration ) {
  27527. return this._scheduleFading( duration, 0, 1 );
  27528. }
  27529. fadeOut( duration ) {
  27530. return this._scheduleFading( duration, 1, 0 );
  27531. }
  27532. crossFadeFrom( fadeOutAction, duration, warp ) {
  27533. fadeOutAction.fadeOut( duration );
  27534. this.fadeIn( duration );
  27535. if ( warp ) {
  27536. const fadeInDuration = this._clip.duration,
  27537. fadeOutDuration = fadeOutAction._clip.duration,
  27538. startEndRatio = fadeOutDuration / fadeInDuration,
  27539. endStartRatio = fadeInDuration / fadeOutDuration;
  27540. fadeOutAction.warp( 1.0, startEndRatio, duration );
  27541. this.warp( endStartRatio, 1.0, duration );
  27542. }
  27543. return this;
  27544. }
  27545. crossFadeTo( fadeInAction, duration, warp ) {
  27546. return fadeInAction.crossFadeFrom( this, duration, warp );
  27547. }
  27548. stopFading() {
  27549. const weightInterpolant = this._weightInterpolant;
  27550. if ( weightInterpolant !== null ) {
  27551. this._weightInterpolant = null;
  27552. this._mixer._takeBackControlInterpolant( weightInterpolant );
  27553. }
  27554. return this;
  27555. }
  27556. // Time Scale Control
  27557. // set the time scale stopping any scheduled warping
  27558. // although .paused = true yields an effective time scale of zero, this
  27559. // method does *not* change .paused, because it would be confusing
  27560. setEffectiveTimeScale( timeScale ) {
  27561. this.timeScale = timeScale;
  27562. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27563. return this.stopWarping();
  27564. }
  27565. // return the time scale considering warping and .paused
  27566. getEffectiveTimeScale() {
  27567. return this._effectiveTimeScale;
  27568. }
  27569. setDuration( duration ) {
  27570. this.timeScale = this._clip.duration / duration;
  27571. return this.stopWarping();
  27572. }
  27573. syncWith( action ) {
  27574. this.time = action.time;
  27575. this.timeScale = action.timeScale;
  27576. return this.stopWarping();
  27577. }
  27578. halt( duration ) {
  27579. return this.warp( this._effectiveTimeScale, 0, duration );
  27580. }
  27581. warp( startTimeScale, endTimeScale, duration ) {
  27582. const mixer = this._mixer,
  27583. now = mixer.time,
  27584. timeScale = this.timeScale;
  27585. let interpolant = this._timeScaleInterpolant;
  27586. if ( interpolant === null ) {
  27587. interpolant = mixer._lendControlInterpolant();
  27588. this._timeScaleInterpolant = interpolant;
  27589. }
  27590. const times = interpolant.parameterPositions,
  27591. values = interpolant.sampleValues;
  27592. times[ 0 ] = now;
  27593. times[ 1 ] = now + duration;
  27594. values[ 0 ] = startTimeScale / timeScale;
  27595. values[ 1 ] = endTimeScale / timeScale;
  27596. return this;
  27597. }
  27598. stopWarping() {
  27599. const timeScaleInterpolant = this._timeScaleInterpolant;
  27600. if ( timeScaleInterpolant !== null ) {
  27601. this._timeScaleInterpolant = null;
  27602. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27603. }
  27604. return this;
  27605. }
  27606. // Object Accessors
  27607. getMixer() {
  27608. return this._mixer;
  27609. }
  27610. getClip() {
  27611. return this._clip;
  27612. }
  27613. getRoot() {
  27614. return this._localRoot || this._mixer._root;
  27615. }
  27616. // Interna
  27617. _update( time, deltaTime, timeDirection, accuIndex ) {
  27618. // called by the mixer
  27619. if ( ! this.enabled ) {
  27620. // call ._updateWeight() to update ._effectiveWeight
  27621. this._updateWeight( time );
  27622. return;
  27623. }
  27624. const startTime = this._startTime;
  27625. if ( startTime !== null ) {
  27626. // check for scheduled start of action
  27627. const timeRunning = ( time - startTime ) * timeDirection;
  27628. if ( timeRunning < 0 || timeDirection === 0 ) {
  27629. return; // yet to come / don't decide when delta = 0
  27630. }
  27631. // start
  27632. this._startTime = null; // unschedule
  27633. deltaTime = timeDirection * timeRunning;
  27634. }
  27635. // apply time scale and advance time
  27636. deltaTime *= this._updateTimeScale( time );
  27637. const clipTime = this._updateTime( deltaTime );
  27638. // note: _updateTime may disable the action resulting in
  27639. // an effective weight of 0
  27640. const weight = this._updateWeight( time );
  27641. if ( weight > 0 ) {
  27642. const interpolants = this._interpolants;
  27643. const propertyMixers = this._propertyBindings;
  27644. switch ( this.blendMode ) {
  27645. case AdditiveAnimationBlendMode:
  27646. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27647. interpolants[ j ].evaluate( clipTime );
  27648. propertyMixers[ j ].accumulateAdditive( weight );
  27649. }
  27650. break;
  27651. case NormalAnimationBlendMode:
  27652. default:
  27653. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27654. interpolants[ j ].evaluate( clipTime );
  27655. propertyMixers[ j ].accumulate( accuIndex, weight );
  27656. }
  27657. }
  27658. }
  27659. }
  27660. _updateWeight( time ) {
  27661. let weight = 0;
  27662. if ( this.enabled ) {
  27663. weight = this.weight;
  27664. const interpolant = this._weightInterpolant;
  27665. if ( interpolant !== null ) {
  27666. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27667. weight *= interpolantValue;
  27668. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27669. this.stopFading();
  27670. if ( interpolantValue === 0 ) {
  27671. // faded out, disable
  27672. this.enabled = false;
  27673. }
  27674. }
  27675. }
  27676. }
  27677. this._effectiveWeight = weight;
  27678. return weight;
  27679. }
  27680. _updateTimeScale( time ) {
  27681. let timeScale = 0;
  27682. if ( ! this.paused ) {
  27683. timeScale = this.timeScale;
  27684. const interpolant = this._timeScaleInterpolant;
  27685. if ( interpolant !== null ) {
  27686. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27687. timeScale *= interpolantValue;
  27688. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27689. this.stopWarping();
  27690. if ( timeScale === 0 ) {
  27691. // motion has halted, pause
  27692. this.paused = true;
  27693. } else {
  27694. // warp done - apply final time scale
  27695. this.timeScale = timeScale;
  27696. }
  27697. }
  27698. }
  27699. }
  27700. this._effectiveTimeScale = timeScale;
  27701. return timeScale;
  27702. }
  27703. _updateTime( deltaTime ) {
  27704. const duration = this._clip.duration;
  27705. const loop = this.loop;
  27706. let time = this.time + deltaTime;
  27707. let loopCount = this._loopCount;
  27708. const pingPong = ( loop === LoopPingPong );
  27709. if ( deltaTime === 0 ) {
  27710. if ( loopCount === - 1 ) return time;
  27711. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  27712. }
  27713. if ( loop === LoopOnce ) {
  27714. if ( loopCount === - 1 ) {
  27715. // just started
  27716. this._loopCount = 0;
  27717. this._setEndings( true, true, false );
  27718. }
  27719. handle_stop: {
  27720. if ( time >= duration ) {
  27721. time = duration;
  27722. } else if ( time < 0 ) {
  27723. time = 0;
  27724. } else {
  27725. this.time = time;
  27726. break handle_stop;
  27727. }
  27728. if ( this.clampWhenFinished ) this.paused = true;
  27729. else this.enabled = false;
  27730. this.time = time;
  27731. this._mixer.dispatchEvent( {
  27732. type: 'finished', action: this,
  27733. direction: deltaTime < 0 ? - 1 : 1
  27734. } );
  27735. }
  27736. } else { // repetitive Repeat or PingPong
  27737. if ( loopCount === - 1 ) {
  27738. // just started
  27739. if ( deltaTime >= 0 ) {
  27740. loopCount = 0;
  27741. this._setEndings( true, this.repetitions === 0, pingPong );
  27742. } else {
  27743. // when looping in reverse direction, the initial
  27744. // transition through zero counts as a repetition,
  27745. // so leave loopCount at -1
  27746. this._setEndings( this.repetitions === 0, true, pingPong );
  27747. }
  27748. }
  27749. if ( time >= duration || time < 0 ) {
  27750. // wrap around
  27751. const loopDelta = Math.floor( time / duration ); // signed
  27752. time -= duration * loopDelta;
  27753. loopCount += Math.abs( loopDelta );
  27754. const pending = this.repetitions - loopCount;
  27755. if ( pending <= 0 ) {
  27756. // have to stop (switch state, clamp time, fire event)
  27757. if ( this.clampWhenFinished ) this.paused = true;
  27758. else this.enabled = false;
  27759. time = deltaTime > 0 ? duration : 0;
  27760. this.time = time;
  27761. this._mixer.dispatchEvent( {
  27762. type: 'finished', action: this,
  27763. direction: deltaTime > 0 ? 1 : - 1
  27764. } );
  27765. } else {
  27766. // keep running
  27767. if ( pending === 1 ) {
  27768. // entering the last round
  27769. const atStart = deltaTime < 0;
  27770. this._setEndings( atStart, ! atStart, pingPong );
  27771. } else {
  27772. this._setEndings( false, false, pingPong );
  27773. }
  27774. this._loopCount = loopCount;
  27775. this.time = time;
  27776. this._mixer.dispatchEvent( {
  27777. type: 'loop', action: this, loopDelta: loopDelta
  27778. } );
  27779. }
  27780. } else {
  27781. this.time = time;
  27782. }
  27783. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27784. // invert time for the "pong round"
  27785. return duration - time;
  27786. }
  27787. }
  27788. return time;
  27789. }
  27790. _setEndings( atStart, atEnd, pingPong ) {
  27791. const settings = this._interpolantSettings;
  27792. if ( pingPong ) {
  27793. settings.endingStart = ZeroSlopeEnding;
  27794. settings.endingEnd = ZeroSlopeEnding;
  27795. } else {
  27796. // assuming for LoopOnce atStart == atEnd == true
  27797. if ( atStart ) {
  27798. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27799. } else {
  27800. settings.endingStart = WrapAroundEnding;
  27801. }
  27802. if ( atEnd ) {
  27803. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27804. } else {
  27805. settings.endingEnd = WrapAroundEnding;
  27806. }
  27807. }
  27808. }
  27809. _scheduleFading( duration, weightNow, weightThen ) {
  27810. const mixer = this._mixer, now = mixer.time;
  27811. let interpolant = this._weightInterpolant;
  27812. if ( interpolant === null ) {
  27813. interpolant = mixer._lendControlInterpolant();
  27814. this._weightInterpolant = interpolant;
  27815. }
  27816. const times = interpolant.parameterPositions,
  27817. values = interpolant.sampleValues;
  27818. times[ 0 ] = now;
  27819. values[ 0 ] = weightNow;
  27820. times[ 1 ] = now + duration;
  27821. values[ 1 ] = weightThen;
  27822. return this;
  27823. }
  27824. }
  27825. function AnimationMixer( root ) {
  27826. this._root = root;
  27827. this._initMemoryManager();
  27828. this._accuIndex = 0;
  27829. this.time = 0;
  27830. this.timeScale = 1.0;
  27831. }
  27832. AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  27833. constructor: AnimationMixer,
  27834. _bindAction: function ( action, prototypeAction ) {
  27835. const root = action._localRoot || this._root,
  27836. tracks = action._clip.tracks,
  27837. nTracks = tracks.length,
  27838. bindings = action._propertyBindings,
  27839. interpolants = action._interpolants,
  27840. rootUuid = root.uuid,
  27841. bindingsByRoot = this._bindingsByRootAndName;
  27842. let bindingsByName = bindingsByRoot[ rootUuid ];
  27843. if ( bindingsByName === undefined ) {
  27844. bindingsByName = {};
  27845. bindingsByRoot[ rootUuid ] = bindingsByName;
  27846. }
  27847. for ( let i = 0; i !== nTracks; ++ i ) {
  27848. const track = tracks[ i ],
  27849. trackName = track.name;
  27850. let binding = bindingsByName[ trackName ];
  27851. if ( binding !== undefined ) {
  27852. bindings[ i ] = binding;
  27853. } else {
  27854. binding = bindings[ i ];
  27855. if ( binding !== undefined ) {
  27856. // existing binding, make sure the cache knows
  27857. if ( binding._cacheIndex === null ) {
  27858. ++ binding.referenceCount;
  27859. this._addInactiveBinding( binding, rootUuid, trackName );
  27860. }
  27861. continue;
  27862. }
  27863. const path = prototypeAction && prototypeAction.
  27864. _propertyBindings[ i ].binding.parsedPath;
  27865. binding = new PropertyMixer(
  27866. PropertyBinding.create( root, trackName, path ),
  27867. track.ValueTypeName, track.getValueSize() );
  27868. ++ binding.referenceCount;
  27869. this._addInactiveBinding( binding, rootUuid, trackName );
  27870. bindings[ i ] = binding;
  27871. }
  27872. interpolants[ i ].resultBuffer = binding.buffer;
  27873. }
  27874. },
  27875. _activateAction: function ( action ) {
  27876. if ( ! this._isActiveAction( action ) ) {
  27877. if ( action._cacheIndex === null ) {
  27878. // this action has been forgotten by the cache, but the user
  27879. // appears to be still using it -> rebind
  27880. const rootUuid = ( action._localRoot || this._root ).uuid,
  27881. clipUuid = action._clip.uuid,
  27882. actionsForClip = this._actionsByClip[ clipUuid ];
  27883. this._bindAction( action,
  27884. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27885. this._addInactiveAction( action, clipUuid, rootUuid );
  27886. }
  27887. const bindings = action._propertyBindings;
  27888. // increment reference counts / sort out state
  27889. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27890. const binding = bindings[ i ];
  27891. if ( binding.useCount ++ === 0 ) {
  27892. this._lendBinding( binding );
  27893. binding.saveOriginalState();
  27894. }
  27895. }
  27896. this._lendAction( action );
  27897. }
  27898. },
  27899. _deactivateAction: function ( action ) {
  27900. if ( this._isActiveAction( action ) ) {
  27901. const bindings = action._propertyBindings;
  27902. // decrement reference counts / sort out state
  27903. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27904. const binding = bindings[ i ];
  27905. if ( -- binding.useCount === 0 ) {
  27906. binding.restoreOriginalState();
  27907. this._takeBackBinding( binding );
  27908. }
  27909. }
  27910. this._takeBackAction( action );
  27911. }
  27912. },
  27913. // Memory manager
  27914. _initMemoryManager: function () {
  27915. this._actions = []; // 'nActiveActions' followed by inactive ones
  27916. this._nActiveActions = 0;
  27917. this._actionsByClip = {};
  27918. // inside:
  27919. // {
  27920. // knownActions: Array< AnimationAction > - used as prototypes
  27921. // actionByRoot: AnimationAction - lookup
  27922. // }
  27923. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27924. this._nActiveBindings = 0;
  27925. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27926. this._controlInterpolants = []; // same game as above
  27927. this._nActiveControlInterpolants = 0;
  27928. const scope = this;
  27929. this.stats = {
  27930. actions: {
  27931. get total() {
  27932. return scope._actions.length;
  27933. },
  27934. get inUse() {
  27935. return scope._nActiveActions;
  27936. }
  27937. },
  27938. bindings: {
  27939. get total() {
  27940. return scope._bindings.length;
  27941. },
  27942. get inUse() {
  27943. return scope._nActiveBindings;
  27944. }
  27945. },
  27946. controlInterpolants: {
  27947. get total() {
  27948. return scope._controlInterpolants.length;
  27949. },
  27950. get inUse() {
  27951. return scope._nActiveControlInterpolants;
  27952. }
  27953. }
  27954. };
  27955. },
  27956. // Memory management for AnimationAction objects
  27957. _isActiveAction: function ( action ) {
  27958. const index = action._cacheIndex;
  27959. return index !== null && index < this._nActiveActions;
  27960. },
  27961. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  27962. const actions = this._actions,
  27963. actionsByClip = this._actionsByClip;
  27964. let actionsForClip = actionsByClip[ clipUuid ];
  27965. if ( actionsForClip === undefined ) {
  27966. actionsForClip = {
  27967. knownActions: [ action ],
  27968. actionByRoot: {}
  27969. };
  27970. action._byClipCacheIndex = 0;
  27971. actionsByClip[ clipUuid ] = actionsForClip;
  27972. } else {
  27973. const knownActions = actionsForClip.knownActions;
  27974. action._byClipCacheIndex = knownActions.length;
  27975. knownActions.push( action );
  27976. }
  27977. action._cacheIndex = actions.length;
  27978. actions.push( action );
  27979. actionsForClip.actionByRoot[ rootUuid ] = action;
  27980. },
  27981. _removeInactiveAction: function ( action ) {
  27982. const actions = this._actions,
  27983. lastInactiveAction = actions[ actions.length - 1 ],
  27984. cacheIndex = action._cacheIndex;
  27985. lastInactiveAction._cacheIndex = cacheIndex;
  27986. actions[ cacheIndex ] = lastInactiveAction;
  27987. actions.pop();
  27988. action._cacheIndex = null;
  27989. const clipUuid = action._clip.uuid,
  27990. actionsByClip = this._actionsByClip,
  27991. actionsForClip = actionsByClip[ clipUuid ],
  27992. knownActionsForClip = actionsForClip.knownActions,
  27993. lastKnownAction =
  27994. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27995. byClipCacheIndex = action._byClipCacheIndex;
  27996. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27997. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27998. knownActionsForClip.pop();
  27999. action._byClipCacheIndex = null;
  28000. const actionByRoot = actionsForClip.actionByRoot,
  28001. rootUuid = ( action._localRoot || this._root ).uuid;
  28002. delete actionByRoot[ rootUuid ];
  28003. if ( knownActionsForClip.length === 0 ) {
  28004. delete actionsByClip[ clipUuid ];
  28005. }
  28006. this._removeInactiveBindingsForAction( action );
  28007. },
  28008. _removeInactiveBindingsForAction: function ( action ) {
  28009. const bindings = action._propertyBindings;
  28010. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28011. const binding = bindings[ i ];
  28012. if ( -- binding.referenceCount === 0 ) {
  28013. this._removeInactiveBinding( binding );
  28014. }
  28015. }
  28016. },
  28017. _lendAction: function ( action ) {
  28018. // [ active actions | inactive actions ]
  28019. // [ active actions >| inactive actions ]
  28020. // s a
  28021. // <-swap->
  28022. // a s
  28023. const actions = this._actions,
  28024. prevIndex = action._cacheIndex,
  28025. lastActiveIndex = this._nActiveActions ++,
  28026. firstInactiveAction = actions[ lastActiveIndex ];
  28027. action._cacheIndex = lastActiveIndex;
  28028. actions[ lastActiveIndex ] = action;
  28029. firstInactiveAction._cacheIndex = prevIndex;
  28030. actions[ prevIndex ] = firstInactiveAction;
  28031. },
  28032. _takeBackAction: function ( action ) {
  28033. // [ active actions | inactive actions ]
  28034. // [ active actions |< inactive actions ]
  28035. // a s
  28036. // <-swap->
  28037. // s a
  28038. const actions = this._actions,
  28039. prevIndex = action._cacheIndex,
  28040. firstInactiveIndex = -- this._nActiveActions,
  28041. lastActiveAction = actions[ firstInactiveIndex ];
  28042. action._cacheIndex = firstInactiveIndex;
  28043. actions[ firstInactiveIndex ] = action;
  28044. lastActiveAction._cacheIndex = prevIndex;
  28045. actions[ prevIndex ] = lastActiveAction;
  28046. },
  28047. // Memory management for PropertyMixer objects
  28048. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  28049. const bindingsByRoot = this._bindingsByRootAndName,
  28050. bindings = this._bindings;
  28051. let bindingByName = bindingsByRoot[ rootUuid ];
  28052. if ( bindingByName === undefined ) {
  28053. bindingByName = {};
  28054. bindingsByRoot[ rootUuid ] = bindingByName;
  28055. }
  28056. bindingByName[ trackName ] = binding;
  28057. binding._cacheIndex = bindings.length;
  28058. bindings.push( binding );
  28059. },
  28060. _removeInactiveBinding: function ( binding ) {
  28061. const bindings = this._bindings,
  28062. propBinding = binding.binding,
  28063. rootUuid = propBinding.rootNode.uuid,
  28064. trackName = propBinding.path,
  28065. bindingsByRoot = this._bindingsByRootAndName,
  28066. bindingByName = bindingsByRoot[ rootUuid ],
  28067. lastInactiveBinding = bindings[ bindings.length - 1 ],
  28068. cacheIndex = binding._cacheIndex;
  28069. lastInactiveBinding._cacheIndex = cacheIndex;
  28070. bindings[ cacheIndex ] = lastInactiveBinding;
  28071. bindings.pop();
  28072. delete bindingByName[ trackName ];
  28073. if ( Object.keys( bindingByName ).length === 0 ) {
  28074. delete bindingsByRoot[ rootUuid ];
  28075. }
  28076. },
  28077. _lendBinding: function ( binding ) {
  28078. const bindings = this._bindings,
  28079. prevIndex = binding._cacheIndex,
  28080. lastActiveIndex = this._nActiveBindings ++,
  28081. firstInactiveBinding = bindings[ lastActiveIndex ];
  28082. binding._cacheIndex = lastActiveIndex;
  28083. bindings[ lastActiveIndex ] = binding;
  28084. firstInactiveBinding._cacheIndex = prevIndex;
  28085. bindings[ prevIndex ] = firstInactiveBinding;
  28086. },
  28087. _takeBackBinding: function ( binding ) {
  28088. const bindings = this._bindings,
  28089. prevIndex = binding._cacheIndex,
  28090. firstInactiveIndex = -- this._nActiveBindings,
  28091. lastActiveBinding = bindings[ firstInactiveIndex ];
  28092. binding._cacheIndex = firstInactiveIndex;
  28093. bindings[ firstInactiveIndex ] = binding;
  28094. lastActiveBinding._cacheIndex = prevIndex;
  28095. bindings[ prevIndex ] = lastActiveBinding;
  28096. },
  28097. // Memory management of Interpolants for weight and time scale
  28098. _lendControlInterpolant: function () {
  28099. const interpolants = this._controlInterpolants,
  28100. lastActiveIndex = this._nActiveControlInterpolants ++;
  28101. let interpolant = interpolants[ lastActiveIndex ];
  28102. if ( interpolant === undefined ) {
  28103. interpolant = new LinearInterpolant(
  28104. new Float32Array( 2 ), new Float32Array( 2 ),
  28105. 1, this._controlInterpolantsResultBuffer );
  28106. interpolant.__cacheIndex = lastActiveIndex;
  28107. interpolants[ lastActiveIndex ] = interpolant;
  28108. }
  28109. return interpolant;
  28110. },
  28111. _takeBackControlInterpolant: function ( interpolant ) {
  28112. const interpolants = this._controlInterpolants,
  28113. prevIndex = interpolant.__cacheIndex,
  28114. firstInactiveIndex = -- this._nActiveControlInterpolants,
  28115. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  28116. interpolant.__cacheIndex = firstInactiveIndex;
  28117. interpolants[ firstInactiveIndex ] = interpolant;
  28118. lastActiveInterpolant.__cacheIndex = prevIndex;
  28119. interpolants[ prevIndex ] = lastActiveInterpolant;
  28120. },
  28121. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  28122. // return an action for a clip optionally using a custom root target
  28123. // object (this method allocates a lot of dynamic memory in case a
  28124. // previously unknown clip/root combination is specified)
  28125. clipAction: function ( clip, optionalRoot, blendMode ) {
  28126. const root = optionalRoot || this._root,
  28127. rootUuid = root.uuid;
  28128. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  28129. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  28130. const actionsForClip = this._actionsByClip[ clipUuid ];
  28131. let prototypeAction = null;
  28132. if ( blendMode === undefined ) {
  28133. if ( clipObject !== null ) {
  28134. blendMode = clipObject.blendMode;
  28135. } else {
  28136. blendMode = NormalAnimationBlendMode;
  28137. }
  28138. }
  28139. if ( actionsForClip !== undefined ) {
  28140. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  28141. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  28142. return existingAction;
  28143. }
  28144. // we know the clip, so we don't have to parse all
  28145. // the bindings again but can just copy
  28146. prototypeAction = actionsForClip.knownActions[ 0 ];
  28147. // also, take the clip from the prototype action
  28148. if ( clipObject === null )
  28149. clipObject = prototypeAction._clip;
  28150. }
  28151. // clip must be known when specified via string
  28152. if ( clipObject === null ) return null;
  28153. // allocate all resources required to run it
  28154. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  28155. this._bindAction( newAction, prototypeAction );
  28156. // and make the action known to the memory manager
  28157. this._addInactiveAction( newAction, clipUuid, rootUuid );
  28158. return newAction;
  28159. },
  28160. // get an existing action
  28161. existingAction: function ( clip, optionalRoot ) {
  28162. const root = optionalRoot || this._root,
  28163. rootUuid = root.uuid,
  28164. clipObject = typeof clip === 'string' ?
  28165. AnimationClip.findByName( root, clip ) : clip,
  28166. clipUuid = clipObject ? clipObject.uuid : clip,
  28167. actionsForClip = this._actionsByClip[ clipUuid ];
  28168. if ( actionsForClip !== undefined ) {
  28169. return actionsForClip.actionByRoot[ rootUuid ] || null;
  28170. }
  28171. return null;
  28172. },
  28173. // deactivates all previously scheduled actions
  28174. stopAllAction: function () {
  28175. const actions = this._actions,
  28176. nActions = this._nActiveActions;
  28177. for ( let i = nActions - 1; i >= 0; -- i ) {
  28178. actions[ i ].stop();
  28179. }
  28180. return this;
  28181. },
  28182. // advance the time and update apply the animation
  28183. update: function ( deltaTime ) {
  28184. deltaTime *= this.timeScale;
  28185. const actions = this._actions,
  28186. nActions = this._nActiveActions,
  28187. time = this.time += deltaTime,
  28188. timeDirection = Math.sign( deltaTime ),
  28189. accuIndex = this._accuIndex ^= 1;
  28190. // run active actions
  28191. for ( let i = 0; i !== nActions; ++ i ) {
  28192. const action = actions[ i ];
  28193. action._update( time, deltaTime, timeDirection, accuIndex );
  28194. }
  28195. // update scene graph
  28196. const bindings = this._bindings,
  28197. nBindings = this._nActiveBindings;
  28198. for ( let i = 0; i !== nBindings; ++ i ) {
  28199. bindings[ i ].apply( accuIndex );
  28200. }
  28201. return this;
  28202. },
  28203. // Allows you to seek to a specific time in an animation.
  28204. setTime: function ( timeInSeconds ) {
  28205. this.time = 0; // Zero out time attribute for AnimationMixer object;
  28206. for ( let i = 0; i < this._actions.length; i ++ ) {
  28207. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  28208. }
  28209. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  28210. },
  28211. // return this mixer's root target object
  28212. getRoot: function () {
  28213. return this._root;
  28214. },
  28215. // free all resources specific to a particular clip
  28216. uncacheClip: function ( clip ) {
  28217. const actions = this._actions,
  28218. clipUuid = clip.uuid,
  28219. actionsByClip = this._actionsByClip,
  28220. actionsForClip = actionsByClip[ clipUuid ];
  28221. if ( actionsForClip !== undefined ) {
  28222. // note: just calling _removeInactiveAction would mess up the
  28223. // iteration state and also require updating the state we can
  28224. // just throw away
  28225. const actionsToRemove = actionsForClip.knownActions;
  28226. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  28227. const action = actionsToRemove[ i ];
  28228. this._deactivateAction( action );
  28229. const cacheIndex = action._cacheIndex,
  28230. lastInactiveAction = actions[ actions.length - 1 ];
  28231. action._cacheIndex = null;
  28232. action._byClipCacheIndex = null;
  28233. lastInactiveAction._cacheIndex = cacheIndex;
  28234. actions[ cacheIndex ] = lastInactiveAction;
  28235. actions.pop();
  28236. this._removeInactiveBindingsForAction( action );
  28237. }
  28238. delete actionsByClip[ clipUuid ];
  28239. }
  28240. },
  28241. // free all resources specific to a particular root target object
  28242. uncacheRoot: function ( root ) {
  28243. const rootUuid = root.uuid,
  28244. actionsByClip = this._actionsByClip;
  28245. for ( const clipUuid in actionsByClip ) {
  28246. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  28247. action = actionByRoot[ rootUuid ];
  28248. if ( action !== undefined ) {
  28249. this._deactivateAction( action );
  28250. this._removeInactiveAction( action );
  28251. }
  28252. }
  28253. const bindingsByRoot = this._bindingsByRootAndName,
  28254. bindingByName = bindingsByRoot[ rootUuid ];
  28255. if ( bindingByName !== undefined ) {
  28256. for ( const trackName in bindingByName ) {
  28257. const binding = bindingByName[ trackName ];
  28258. binding.restoreOriginalState();
  28259. this._removeInactiveBinding( binding );
  28260. }
  28261. }
  28262. },
  28263. // remove a targeted clip from the cache
  28264. uncacheAction: function ( clip, optionalRoot ) {
  28265. const action = this.existingAction( clip, optionalRoot );
  28266. if ( action !== null ) {
  28267. this._deactivateAction( action );
  28268. this._removeInactiveAction( action );
  28269. }
  28270. }
  28271. } );
  28272. class Uniform {
  28273. constructor( value ) {
  28274. if ( typeof value === 'string' ) {
  28275. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  28276. value = arguments[ 1 ];
  28277. }
  28278. this.value = value;
  28279. }
  28280. clone() {
  28281. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28282. }
  28283. }
  28284. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  28285. InterleavedBuffer.call( this, array, stride );
  28286. this.meshPerAttribute = meshPerAttribute || 1;
  28287. }
  28288. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  28289. constructor: InstancedInterleavedBuffer,
  28290. isInstancedInterleavedBuffer: true,
  28291. copy: function ( source ) {
  28292. InterleavedBuffer.prototype.copy.call( this, source );
  28293. this.meshPerAttribute = source.meshPerAttribute;
  28294. return this;
  28295. },
  28296. clone: function ( data ) {
  28297. const ib = InterleavedBuffer.prototype.clone.call( this, data );
  28298. ib.meshPerAttribute = this.meshPerAttribute;
  28299. return ib;
  28300. },
  28301. toJSON: function ( data ) {
  28302. const json = InterleavedBuffer.prototype.toJSON.call( this, data );
  28303. json.isInstancedInterleavedBuffer = true;
  28304. json.meshPerAttribute = this.meshPerAttribute;
  28305. return json;
  28306. }
  28307. } );
  28308. function GLBufferAttribute( buffer, type, itemSize, elementSize, count ) {
  28309. this.buffer = buffer;
  28310. this.type = type;
  28311. this.itemSize = itemSize;
  28312. this.elementSize = elementSize;
  28313. this.count = count;
  28314. this.version = 0;
  28315. }
  28316. Object.defineProperty( GLBufferAttribute.prototype, 'needsUpdate', {
  28317. set: function ( value ) {
  28318. if ( value === true ) this.version ++;
  28319. }
  28320. } );
  28321. Object.assign( GLBufferAttribute.prototype, {
  28322. isGLBufferAttribute: true,
  28323. setBuffer: function ( buffer ) {
  28324. this.buffer = buffer;
  28325. return this;
  28326. },
  28327. setType: function ( type, elementSize ) {
  28328. this.type = type;
  28329. this.elementSize = elementSize;
  28330. return this;
  28331. },
  28332. setItemSize: function ( itemSize ) {
  28333. this.itemSize = itemSize;
  28334. return this;
  28335. },
  28336. setCount: function ( count ) {
  28337. this.count = count;
  28338. return this;
  28339. },
  28340. } );
  28341. function Raycaster( origin, direction, near, far ) {
  28342. this.ray = new Ray( origin, direction );
  28343. // direction is assumed to be normalized (for accurate distance calculations)
  28344. this.near = near || 0;
  28345. this.far = far || Infinity;
  28346. this.camera = null;
  28347. this.layers = new Layers();
  28348. this.params = {
  28349. Mesh: {},
  28350. Line: { threshold: 1 },
  28351. LOD: {},
  28352. Points: { threshold: 1 },
  28353. Sprite: {}
  28354. };
  28355. Object.defineProperties( this.params, {
  28356. PointCloud: {
  28357. get: function () {
  28358. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  28359. return this.Points;
  28360. }
  28361. }
  28362. } );
  28363. }
  28364. function ascSort( a, b ) {
  28365. return a.distance - b.distance;
  28366. }
  28367. function intersectObject( object, raycaster, intersects, recursive ) {
  28368. if ( object.layers.test( raycaster.layers ) ) {
  28369. object.raycast( raycaster, intersects );
  28370. }
  28371. if ( recursive === true ) {
  28372. const children = object.children;
  28373. for ( let i = 0, l = children.length; i < l; i ++ ) {
  28374. intersectObject( children[ i ], raycaster, intersects, true );
  28375. }
  28376. }
  28377. }
  28378. Object.assign( Raycaster.prototype, {
  28379. set: function ( origin, direction ) {
  28380. // direction is assumed to be normalized (for accurate distance calculations)
  28381. this.ray.set( origin, direction );
  28382. },
  28383. setFromCamera: function ( coords, camera ) {
  28384. if ( camera && camera.isPerspectiveCamera ) {
  28385. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  28386. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  28387. this.camera = camera;
  28388. } else if ( camera && camera.isOrthographicCamera ) {
  28389. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  28390. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  28391. this.camera = camera;
  28392. } else {
  28393. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  28394. }
  28395. },
  28396. intersectObject: function ( object, recursive, optionalTarget ) {
  28397. const intersects = optionalTarget || [];
  28398. intersectObject( object, this, intersects, recursive );
  28399. intersects.sort( ascSort );
  28400. return intersects;
  28401. },
  28402. intersectObjects: function ( objects, recursive, optionalTarget ) {
  28403. const intersects = optionalTarget || [];
  28404. if ( Array.isArray( objects ) === false ) {
  28405. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  28406. return intersects;
  28407. }
  28408. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  28409. intersectObject( objects[ i ], this, intersects, recursive );
  28410. }
  28411. intersects.sort( ascSort );
  28412. return intersects;
  28413. }
  28414. } );
  28415. /**
  28416. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28417. *
  28418. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  28419. * The azimuthal angle (theta) is measured from the positive z-axis.
  28420. */
  28421. class Spherical {
  28422. constructor( radius = 1, phi = 0, theta = 0 ) {
  28423. this.radius = radius;
  28424. this.phi = phi; // polar angle
  28425. this.theta = theta; // azimuthal angle
  28426. return this;
  28427. }
  28428. set( radius, phi, theta ) {
  28429. this.radius = radius;
  28430. this.phi = phi;
  28431. this.theta = theta;
  28432. return this;
  28433. }
  28434. clone() {
  28435. return new this.constructor().copy( this );
  28436. }
  28437. copy( other ) {
  28438. this.radius = other.radius;
  28439. this.phi = other.phi;
  28440. this.theta = other.theta;
  28441. return this;
  28442. }
  28443. // restrict phi to be betwee EPS and PI-EPS
  28444. makeSafe() {
  28445. const EPS = 0.000001;
  28446. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28447. return this;
  28448. }
  28449. setFromVector3( v ) {
  28450. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28451. }
  28452. setFromCartesianCoords( x, y, z ) {
  28453. this.radius = Math.sqrt( x * x + y * y + z * z );
  28454. if ( this.radius === 0 ) {
  28455. this.theta = 0;
  28456. this.phi = 0;
  28457. } else {
  28458. this.theta = Math.atan2( x, z );
  28459. this.phi = Math.acos( MathUtils.clamp( y / this.radius, - 1, 1 ) );
  28460. }
  28461. return this;
  28462. }
  28463. }
  28464. /**
  28465. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28466. */
  28467. class Cylindrical {
  28468. constructor( radius, theta, y ) {
  28469. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  28470. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28471. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  28472. return this;
  28473. }
  28474. set( radius, theta, y ) {
  28475. this.radius = radius;
  28476. this.theta = theta;
  28477. this.y = y;
  28478. return this;
  28479. }
  28480. clone() {
  28481. return new this.constructor().copy( this );
  28482. }
  28483. copy( other ) {
  28484. this.radius = other.radius;
  28485. this.theta = other.theta;
  28486. this.y = other.y;
  28487. return this;
  28488. }
  28489. setFromVector3( v ) {
  28490. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28491. }
  28492. setFromCartesianCoords( x, y, z ) {
  28493. this.radius = Math.sqrt( x * x + z * z );
  28494. this.theta = Math.atan2( x, z );
  28495. this.y = y;
  28496. return this;
  28497. }
  28498. }
  28499. const _vector$8 = /*@__PURE__*/ new Vector2$1();
  28500. class Box2 {
  28501. constructor( min, max ) {
  28502. Object.defineProperty( this, 'isBox2', { value: true } );
  28503. this.min = ( min !== undefined ) ? min : new Vector2$1( + Infinity, + Infinity );
  28504. this.max = ( max !== undefined ) ? max : new Vector2$1( - Infinity, - Infinity );
  28505. }
  28506. set( min, max ) {
  28507. this.min.copy( min );
  28508. this.max.copy( max );
  28509. return this;
  28510. }
  28511. setFromPoints( points ) {
  28512. this.makeEmpty();
  28513. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28514. this.expandByPoint( points[ i ] );
  28515. }
  28516. return this;
  28517. }
  28518. setFromCenterAndSize( center, size ) {
  28519. const halfSize = _vector$8.copy( size ).multiplyScalar( 0.5 );
  28520. this.min.copy( center ).sub( halfSize );
  28521. this.max.copy( center ).add( halfSize );
  28522. return this;
  28523. }
  28524. clone() {
  28525. return new this.constructor().copy( this );
  28526. }
  28527. copy( box ) {
  28528. this.min.copy( box.min );
  28529. this.max.copy( box.max );
  28530. return this;
  28531. }
  28532. makeEmpty() {
  28533. this.min.x = this.min.y = + Infinity;
  28534. this.max.x = this.max.y = - Infinity;
  28535. return this;
  28536. }
  28537. isEmpty() {
  28538. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28539. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  28540. }
  28541. getCenter( target ) {
  28542. if ( target === undefined ) {
  28543. console.warn( 'THREE.Box2: .getCenter() target is now required' );
  28544. target = new Vector2$1();
  28545. }
  28546. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  28547. }
  28548. getSize( target ) {
  28549. if ( target === undefined ) {
  28550. console.warn( 'THREE.Box2: .getSize() target is now required' );
  28551. target = new Vector2$1();
  28552. }
  28553. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  28554. }
  28555. expandByPoint( point ) {
  28556. this.min.min( point );
  28557. this.max.max( point );
  28558. return this;
  28559. }
  28560. expandByVector( vector ) {
  28561. this.min.sub( vector );
  28562. this.max.add( vector );
  28563. return this;
  28564. }
  28565. expandByScalar( scalar ) {
  28566. this.min.addScalar( - scalar );
  28567. this.max.addScalar( scalar );
  28568. return this;
  28569. }
  28570. containsPoint( point ) {
  28571. return point.x < this.min.x || point.x > this.max.x ||
  28572. point.y < this.min.y || point.y > this.max.y ? false : true;
  28573. }
  28574. containsBox( box ) {
  28575. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28576. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28577. }
  28578. getParameter( point, target ) {
  28579. // This can potentially have a divide by zero if the box
  28580. // has a size dimension of 0.
  28581. if ( target === undefined ) {
  28582. console.warn( 'THREE.Box2: .getParameter() target is now required' );
  28583. target = new Vector2$1();
  28584. }
  28585. return target.set(
  28586. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28587. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28588. );
  28589. }
  28590. intersectsBox( box ) {
  28591. // using 4 splitting planes to rule out intersections
  28592. return box.max.x < this.min.x || box.min.x > this.max.x ||
  28593. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28594. }
  28595. clampPoint( point, target ) {
  28596. if ( target === undefined ) {
  28597. console.warn( 'THREE.Box2: .clampPoint() target is now required' );
  28598. target = new Vector2$1();
  28599. }
  28600. return target.copy( point ).clamp( this.min, this.max );
  28601. }
  28602. distanceToPoint( point ) {
  28603. const clampedPoint = _vector$8.copy( point ).clamp( this.min, this.max );
  28604. return clampedPoint.sub( point ).length();
  28605. }
  28606. intersect( box ) {
  28607. this.min.max( box.min );
  28608. this.max.min( box.max );
  28609. return this;
  28610. }
  28611. union( box ) {
  28612. this.min.min( box.min );
  28613. this.max.max( box.max );
  28614. return this;
  28615. }
  28616. translate( offset ) {
  28617. this.min.add( offset );
  28618. this.max.add( offset );
  28619. return this;
  28620. }
  28621. equals( box ) {
  28622. return box.min.equals( this.min ) && box.max.equals( this.max );
  28623. }
  28624. }
  28625. const _startP = /*@__PURE__*/ new Vector3();
  28626. const _startEnd = /*@__PURE__*/ new Vector3();
  28627. class Line3 {
  28628. constructor( start, end ) {
  28629. this.start = ( start !== undefined ) ? start : new Vector3();
  28630. this.end = ( end !== undefined ) ? end : new Vector3();
  28631. }
  28632. set( start, end ) {
  28633. this.start.copy( start );
  28634. this.end.copy( end );
  28635. return this;
  28636. }
  28637. clone() {
  28638. return new this.constructor().copy( this );
  28639. }
  28640. copy( line ) {
  28641. this.start.copy( line.start );
  28642. this.end.copy( line.end );
  28643. return this;
  28644. }
  28645. getCenter( target ) {
  28646. if ( target === undefined ) {
  28647. console.warn( 'THREE.Line3: .getCenter() target is now required' );
  28648. target = new Vector3();
  28649. }
  28650. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  28651. }
  28652. delta( target ) {
  28653. if ( target === undefined ) {
  28654. console.warn( 'THREE.Line3: .delta() target is now required' );
  28655. target = new Vector3();
  28656. }
  28657. return target.subVectors( this.end, this.start );
  28658. }
  28659. distanceSq() {
  28660. return this.start.distanceToSquared( this.end );
  28661. }
  28662. distance() {
  28663. return this.start.distanceTo( this.end );
  28664. }
  28665. at( t, target ) {
  28666. if ( target === undefined ) {
  28667. console.warn( 'THREE.Line3: .at() target is now required' );
  28668. target = new Vector3();
  28669. }
  28670. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28671. }
  28672. closestPointToPointParameter( point, clampToLine ) {
  28673. _startP.subVectors( point, this.start );
  28674. _startEnd.subVectors( this.end, this.start );
  28675. const startEnd2 = _startEnd.dot( _startEnd );
  28676. const startEnd_startP = _startEnd.dot( _startP );
  28677. let t = startEnd_startP / startEnd2;
  28678. if ( clampToLine ) {
  28679. t = MathUtils.clamp( t, 0, 1 );
  28680. }
  28681. return t;
  28682. }
  28683. closestPointToPoint( point, clampToLine, target ) {
  28684. const t = this.closestPointToPointParameter( point, clampToLine );
  28685. if ( target === undefined ) {
  28686. console.warn( 'THREE.Line3: .closestPointToPoint() target is now required' );
  28687. target = new Vector3();
  28688. }
  28689. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28690. }
  28691. applyMatrix4( matrix ) {
  28692. this.start.applyMatrix4( matrix );
  28693. this.end.applyMatrix4( matrix );
  28694. return this;
  28695. }
  28696. equals( line ) {
  28697. return line.start.equals( this.start ) && line.end.equals( this.end );
  28698. }
  28699. }
  28700. function ImmediateRenderObject( material ) {
  28701. Object3D.call( this );
  28702. this.material = material;
  28703. this.render = function ( /* renderCallback */ ) {};
  28704. this.hasPositions = false;
  28705. this.hasNormals = false;
  28706. this.hasColors = false;
  28707. this.hasUvs = false;
  28708. this.positionArray = null;
  28709. this.normalArray = null;
  28710. this.colorArray = null;
  28711. this.uvArray = null;
  28712. this.count = 0;
  28713. }
  28714. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  28715. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  28716. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  28717. const _vector$9 = /*@__PURE__*/ new Vector3();
  28718. class SpotLightHelper extends Object3D {
  28719. constructor( light, color ) {
  28720. super();
  28721. this.light = light;
  28722. this.light.updateMatrixWorld();
  28723. this.matrix = light.matrixWorld;
  28724. this.matrixAutoUpdate = false;
  28725. this.color = color;
  28726. const geometry = new BufferGeometry();
  28727. const positions = [
  28728. 0, 0, 0, 0, 0, 1,
  28729. 0, 0, 0, 1, 0, 1,
  28730. 0, 0, 0, - 1, 0, 1,
  28731. 0, 0, 0, 0, 1, 1,
  28732. 0, 0, 0, 0, - 1, 1
  28733. ];
  28734. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28735. const p1 = ( i / l ) * Math.PI * 2;
  28736. const p2 = ( j / l ) * Math.PI * 2;
  28737. positions.push(
  28738. Math.cos( p1 ), Math.sin( p1 ), 1,
  28739. Math.cos( p2 ), Math.sin( p2 ), 1
  28740. );
  28741. }
  28742. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28743. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28744. this.cone = new LineSegments( geometry, material );
  28745. this.add( this.cone );
  28746. this.update();
  28747. }
  28748. dispose() {
  28749. this.cone.geometry.dispose();
  28750. this.cone.material.dispose();
  28751. }
  28752. update() {
  28753. this.light.updateMatrixWorld();
  28754. const coneLength = this.light.distance ? this.light.distance : 1000;
  28755. const coneWidth = coneLength * Math.tan( this.light.angle );
  28756. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28757. _vector$9.setFromMatrixPosition( this.light.target.matrixWorld );
  28758. this.cone.lookAt( _vector$9 );
  28759. if ( this.color !== undefined ) {
  28760. this.cone.material.color.set( this.color );
  28761. } else {
  28762. this.cone.material.color.copy( this.light.color );
  28763. }
  28764. }
  28765. }
  28766. const _vector$a = /*@__PURE__*/ new Vector3();
  28767. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28768. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28769. class SkeletonHelper extends LineSegments {
  28770. constructor( object ) {
  28771. const bones = getBoneList( object );
  28772. const geometry = new BufferGeometry();
  28773. const vertices = [];
  28774. const colors = [];
  28775. const color1 = new Color( 0, 0, 1 );
  28776. const color2 = new Color( 0, 1, 0 );
  28777. for ( let i = 0; i < bones.length; i ++ ) {
  28778. const bone = bones[ i ];
  28779. if ( bone.parent && bone.parent.isBone ) {
  28780. vertices.push( 0, 0, 0 );
  28781. vertices.push( 0, 0, 0 );
  28782. colors.push( color1.r, color1.g, color1.b );
  28783. colors.push( color2.r, color2.g, color2.b );
  28784. }
  28785. }
  28786. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28787. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28788. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  28789. super( geometry, material );
  28790. this.type = 'SkeletonHelper';
  28791. this.isSkeletonHelper = true;
  28792. this.root = object;
  28793. this.bones = bones;
  28794. this.matrix = object.matrixWorld;
  28795. this.matrixAutoUpdate = false;
  28796. }
  28797. updateMatrixWorld( force ) {
  28798. const bones = this.bones;
  28799. const geometry = this.geometry;
  28800. const position = geometry.getAttribute( 'position' );
  28801. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  28802. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  28803. const bone = bones[ i ];
  28804. if ( bone.parent && bone.parent.isBone ) {
  28805. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  28806. _vector$a.setFromMatrixPosition( _boneMatrix );
  28807. position.setXYZ( j, _vector$a.x, _vector$a.y, _vector$a.z );
  28808. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  28809. _vector$a.setFromMatrixPosition( _boneMatrix );
  28810. position.setXYZ( j + 1, _vector$a.x, _vector$a.y, _vector$a.z );
  28811. j += 2;
  28812. }
  28813. }
  28814. geometry.getAttribute( 'position' ).needsUpdate = true;
  28815. super.updateMatrixWorld( force );
  28816. }
  28817. }
  28818. function getBoneList( object ) {
  28819. const boneList = [];
  28820. if ( object && object.isBone ) {
  28821. boneList.push( object );
  28822. }
  28823. for ( let i = 0; i < object.children.length; i ++ ) {
  28824. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  28825. }
  28826. return boneList;
  28827. }
  28828. class PointLightHelper extends Mesh {
  28829. constructor( light, sphereSize, color ) {
  28830. const geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  28831. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28832. super( geometry, material );
  28833. this.light = light;
  28834. this.light.updateMatrixWorld();
  28835. this.color = color;
  28836. this.type = 'PointLightHelper';
  28837. this.matrix = this.light.matrixWorld;
  28838. this.matrixAutoUpdate = false;
  28839. this.update();
  28840. /*
  28841. // TODO: delete this comment?
  28842. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  28843. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28844. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28845. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28846. const d = light.distance;
  28847. if ( d === 0.0 ) {
  28848. this.lightDistance.visible = false;
  28849. } else {
  28850. this.lightDistance.scale.set( d, d, d );
  28851. }
  28852. this.add( this.lightDistance );
  28853. */
  28854. }
  28855. dispose() {
  28856. this.geometry.dispose();
  28857. this.material.dispose();
  28858. }
  28859. update() {
  28860. if ( this.color !== undefined ) {
  28861. this.material.color.set( this.color );
  28862. } else {
  28863. this.material.color.copy( this.light.color );
  28864. }
  28865. /*
  28866. const d = this.light.distance;
  28867. if ( d === 0.0 ) {
  28868. this.lightDistance.visible = false;
  28869. } else {
  28870. this.lightDistance.visible = true;
  28871. this.lightDistance.scale.set( d, d, d );
  28872. }
  28873. */
  28874. }
  28875. }
  28876. const _vector$b = /*@__PURE__*/ new Vector3();
  28877. const _color1 = /*@__PURE__*/ new Color();
  28878. const _color2 = /*@__PURE__*/ new Color();
  28879. class HemisphereLightHelper extends Object3D {
  28880. constructor( light, size, color ) {
  28881. super();
  28882. this.light = light;
  28883. this.light.updateMatrixWorld();
  28884. this.matrix = light.matrixWorld;
  28885. this.matrixAutoUpdate = false;
  28886. this.color = color;
  28887. const geometry = new OctahedronBufferGeometry( size );
  28888. geometry.rotateY( Math.PI * 0.5 );
  28889. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28890. if ( this.color === undefined ) this.material.vertexColors = true;
  28891. const position = geometry.getAttribute( 'position' );
  28892. const colors = new Float32Array( position.count * 3 );
  28893. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28894. this.add( new Mesh( geometry, this.material ) );
  28895. this.update();
  28896. }
  28897. dispose() {
  28898. this.children[ 0 ].geometry.dispose();
  28899. this.children[ 0 ].material.dispose();
  28900. }
  28901. update() {
  28902. const mesh = this.children[ 0 ];
  28903. if ( this.color !== undefined ) {
  28904. this.material.color.set( this.color );
  28905. } else {
  28906. const colors = mesh.geometry.getAttribute( 'color' );
  28907. _color1.copy( this.light.color );
  28908. _color2.copy( this.light.groundColor );
  28909. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  28910. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  28911. colors.setXYZ( i, color.r, color.g, color.b );
  28912. }
  28913. colors.needsUpdate = true;
  28914. }
  28915. mesh.lookAt( _vector$b.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28916. }
  28917. }
  28918. class GridHelper extends LineSegments {
  28919. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  28920. color1 = new Color( color1 );
  28921. color2 = new Color( color2 );
  28922. const center = divisions / 2;
  28923. const step = size / divisions;
  28924. const halfSize = size / 2;
  28925. const vertices = [], colors = [];
  28926. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28927. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28928. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28929. const color = i === center ? color1 : color2;
  28930. color.toArray( colors, j ); j += 3;
  28931. color.toArray( colors, j ); j += 3;
  28932. color.toArray( colors, j ); j += 3;
  28933. color.toArray( colors, j ); j += 3;
  28934. }
  28935. const geometry = new BufferGeometry();
  28936. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28937. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28938. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28939. super( geometry, material );
  28940. this.type = 'GridHelper';
  28941. }
  28942. }
  28943. class PolarGridHelper extends LineSegments {
  28944. constructor( radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  28945. color1 = new Color( color1 );
  28946. color2 = new Color( color2 );
  28947. const vertices = [];
  28948. const colors = [];
  28949. // create the radials
  28950. for ( let i = 0; i <= radials; i ++ ) {
  28951. const v = ( i / radials ) * ( Math.PI * 2 );
  28952. const x = Math.sin( v ) * radius;
  28953. const z = Math.cos( v ) * radius;
  28954. vertices.push( 0, 0, 0 );
  28955. vertices.push( x, 0, z );
  28956. const color = ( i & 1 ) ? color1 : color2;
  28957. colors.push( color.r, color.g, color.b );
  28958. colors.push( color.r, color.g, color.b );
  28959. }
  28960. // create the circles
  28961. for ( let i = 0; i <= circles; i ++ ) {
  28962. const color = ( i & 1 ) ? color1 : color2;
  28963. const r = radius - ( radius / circles * i );
  28964. for ( let j = 0; j < divisions; j ++ ) {
  28965. // first vertex
  28966. let v = ( j / divisions ) * ( Math.PI * 2 );
  28967. let x = Math.sin( v ) * r;
  28968. let z = Math.cos( v ) * r;
  28969. vertices.push( x, 0, z );
  28970. colors.push( color.r, color.g, color.b );
  28971. // second vertex
  28972. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28973. x = Math.sin( v ) * r;
  28974. z = Math.cos( v ) * r;
  28975. vertices.push( x, 0, z );
  28976. colors.push( color.r, color.g, color.b );
  28977. }
  28978. }
  28979. const geometry = new BufferGeometry();
  28980. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28981. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28982. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28983. super( geometry, material );
  28984. this.type = 'PolarGridHelper';
  28985. }
  28986. }
  28987. const _v1$6 = /*@__PURE__*/ new Vector3();
  28988. const _v2$3 = /*@__PURE__*/ new Vector3();
  28989. const _v3$1 = /*@__PURE__*/ new Vector3();
  28990. class DirectionalLightHelper extends Object3D {
  28991. constructor( light, size, color ) {
  28992. super();
  28993. this.light = light;
  28994. this.light.updateMatrixWorld();
  28995. this.matrix = light.matrixWorld;
  28996. this.matrixAutoUpdate = false;
  28997. this.color = color;
  28998. if ( size === undefined ) size = 1;
  28999. let geometry = new BufferGeometry();
  29000. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  29001. - size, size, 0,
  29002. size, size, 0,
  29003. size, - size, 0,
  29004. - size, - size, 0,
  29005. - size, size, 0
  29006. ], 3 ) );
  29007. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29008. this.lightPlane = new Line( geometry, material );
  29009. this.add( this.lightPlane );
  29010. geometry = new BufferGeometry();
  29011. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  29012. this.targetLine = new Line( geometry, material );
  29013. this.add( this.targetLine );
  29014. this.update();
  29015. }
  29016. dispose() {
  29017. this.lightPlane.geometry.dispose();
  29018. this.lightPlane.material.dispose();
  29019. this.targetLine.geometry.dispose();
  29020. this.targetLine.material.dispose();
  29021. }
  29022. update() {
  29023. _v1$6.setFromMatrixPosition( this.light.matrixWorld );
  29024. _v2$3.setFromMatrixPosition( this.light.target.matrixWorld );
  29025. _v3$1.subVectors( _v2$3, _v1$6 );
  29026. this.lightPlane.lookAt( _v2$3 );
  29027. if ( this.color !== undefined ) {
  29028. this.lightPlane.material.color.set( this.color );
  29029. this.targetLine.material.color.set( this.color );
  29030. } else {
  29031. this.lightPlane.material.color.copy( this.light.color );
  29032. this.targetLine.material.color.copy( this.light.color );
  29033. }
  29034. this.targetLine.lookAt( _v2$3 );
  29035. this.targetLine.scale.z = _v3$1.length();
  29036. }
  29037. }
  29038. const _vector$c = /*@__PURE__*/ new Vector3();
  29039. const _camera = /*@__PURE__*/ new Camera();
  29040. /**
  29041. * - shows frustum, line of sight and up of the camera
  29042. * - suitable for fast updates
  29043. * - based on frustum visualization in lightgl.js shadowmap example
  29044. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  29045. */
  29046. class CameraHelper extends LineSegments {
  29047. constructor( camera ) {
  29048. const geometry = new BufferGeometry();
  29049. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  29050. const vertices = [];
  29051. const colors = [];
  29052. const pointMap = {};
  29053. // colors
  29054. const colorFrustum = new Color( 0xffaa00 );
  29055. const colorCone = new Color( 0xff0000 );
  29056. const colorUp = new Color( 0x00aaff );
  29057. const colorTarget = new Color( 0xffffff );
  29058. const colorCross = new Color( 0x333333 );
  29059. // near
  29060. addLine( 'n1', 'n2', colorFrustum );
  29061. addLine( 'n2', 'n4', colorFrustum );
  29062. addLine( 'n4', 'n3', colorFrustum );
  29063. addLine( 'n3', 'n1', colorFrustum );
  29064. // far
  29065. addLine( 'f1', 'f2', colorFrustum );
  29066. addLine( 'f2', 'f4', colorFrustum );
  29067. addLine( 'f4', 'f3', colorFrustum );
  29068. addLine( 'f3', 'f1', colorFrustum );
  29069. // sides
  29070. addLine( 'n1', 'f1', colorFrustum );
  29071. addLine( 'n2', 'f2', colorFrustum );
  29072. addLine( 'n3', 'f3', colorFrustum );
  29073. addLine( 'n4', 'f4', colorFrustum );
  29074. // cone
  29075. addLine( 'p', 'n1', colorCone );
  29076. addLine( 'p', 'n2', colorCone );
  29077. addLine( 'p', 'n3', colorCone );
  29078. addLine( 'p', 'n4', colorCone );
  29079. // up
  29080. addLine( 'u1', 'u2', colorUp );
  29081. addLine( 'u2', 'u3', colorUp );
  29082. addLine( 'u3', 'u1', colorUp );
  29083. // target
  29084. addLine( 'c', 't', colorTarget );
  29085. addLine( 'p', 'c', colorCross );
  29086. // cross
  29087. addLine( 'cn1', 'cn2', colorCross );
  29088. addLine( 'cn3', 'cn4', colorCross );
  29089. addLine( 'cf1', 'cf2', colorCross );
  29090. addLine( 'cf3', 'cf4', colorCross );
  29091. function addLine( a, b, color ) {
  29092. addPoint( a, color );
  29093. addPoint( b, color );
  29094. }
  29095. function addPoint( id, color ) {
  29096. vertices.push( 0, 0, 0 );
  29097. colors.push( color.r, color.g, color.b );
  29098. if ( pointMap[ id ] === undefined ) {
  29099. pointMap[ id ] = [];
  29100. }
  29101. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  29102. }
  29103. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29104. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29105. super( geometry, material );
  29106. this.type = 'CameraHelper';
  29107. this.camera = camera;
  29108. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  29109. this.matrix = camera.matrixWorld;
  29110. this.matrixAutoUpdate = false;
  29111. this.pointMap = pointMap;
  29112. this.update();
  29113. }
  29114. update() {
  29115. const geometry = this.geometry;
  29116. const pointMap = this.pointMap;
  29117. const w = 1, h = 1;
  29118. // we need just camera projection matrix inverse
  29119. // world matrix must be identity
  29120. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  29121. // center / target
  29122. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  29123. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  29124. // near
  29125. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  29126. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  29127. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  29128. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  29129. // far
  29130. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  29131. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  29132. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  29133. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  29134. // up
  29135. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  29136. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  29137. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  29138. // cross
  29139. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  29140. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  29141. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  29142. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  29143. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  29144. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  29145. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  29146. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  29147. geometry.getAttribute( 'position' ).needsUpdate = true;
  29148. }
  29149. }
  29150. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  29151. _vector$c.set( x, y, z ).unproject( camera );
  29152. const points = pointMap[ point ];
  29153. if ( points !== undefined ) {
  29154. const position = geometry.getAttribute( 'position' );
  29155. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29156. position.setXYZ( points[ i ], _vector$c.x, _vector$c.y, _vector$c.z );
  29157. }
  29158. }
  29159. }
  29160. const _box$3 = /*@__PURE__*/ new Box3();
  29161. class BoxHelper extends LineSegments {
  29162. constructor( object, color = 0xffff00 ) {
  29163. 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 ] );
  29164. const positions = new Float32Array( 8 * 3 );
  29165. const geometry = new BufferGeometry();
  29166. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29167. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29168. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29169. this.object = object;
  29170. this.type = 'BoxHelper';
  29171. this.matrixAutoUpdate = false;
  29172. this.update();
  29173. }
  29174. update( object ) {
  29175. if ( object !== undefined ) {
  29176. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  29177. }
  29178. if ( this.object !== undefined ) {
  29179. _box$3.setFromObject( this.object );
  29180. }
  29181. if ( _box$3.isEmpty() ) return;
  29182. const min = _box$3.min;
  29183. const max = _box$3.max;
  29184. /*
  29185. 5____4
  29186. 1/___0/|
  29187. | 6__|_7
  29188. 2/___3/
  29189. 0: max.x, max.y, max.z
  29190. 1: min.x, max.y, max.z
  29191. 2: min.x, min.y, max.z
  29192. 3: max.x, min.y, max.z
  29193. 4: max.x, max.y, min.z
  29194. 5: min.x, max.y, min.z
  29195. 6: min.x, min.y, min.z
  29196. 7: max.x, min.y, min.z
  29197. */
  29198. const position = this.geometry.attributes.position;
  29199. const array = position.array;
  29200. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29201. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29202. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29203. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29204. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29205. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29206. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29207. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29208. position.needsUpdate = true;
  29209. this.geometry.computeBoundingSphere();
  29210. }
  29211. setFromObject( object ) {
  29212. this.object = object;
  29213. this.update();
  29214. return this;
  29215. }
  29216. copy( source ) {
  29217. LineSegments.prototype.copy.call( this, source );
  29218. this.object = source.object;
  29219. return this;
  29220. }
  29221. }
  29222. class Box3Helper extends LineSegments {
  29223. constructor( box, color = 0xffff00 ) {
  29224. 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 ] );
  29225. 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 ];
  29226. const geometry = new BufferGeometry();
  29227. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29228. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29229. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29230. this.box = box;
  29231. this.type = 'Box3Helper';
  29232. this.geometry.computeBoundingSphere();
  29233. }
  29234. updateMatrixWorld( force ) {
  29235. const box = this.box;
  29236. if ( box.isEmpty() ) return;
  29237. box.getCenter( this.position );
  29238. box.getSize( this.scale );
  29239. this.scale.multiplyScalar( 0.5 );
  29240. super.updateMatrixWorld( force );
  29241. }
  29242. }
  29243. class PlaneHelper extends Line {
  29244. constructor( plane, size = 1, hex = 0xffff00 ) {
  29245. const color = hex;
  29246. 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 ];
  29247. const geometry = new BufferGeometry();
  29248. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29249. geometry.computeBoundingSphere();
  29250. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29251. this.type = 'PlaneHelper';
  29252. this.plane = plane;
  29253. this.size = size;
  29254. const positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  29255. const geometry2 = new BufferGeometry();
  29256. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29257. geometry2.computeBoundingSphere();
  29258. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29259. }
  29260. updateMatrixWorld( force ) {
  29261. let scale = - this.plane.constant;
  29262. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  29263. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  29264. this.children[ 0 ].material.side = ( scale < 0 ) ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  29265. this.lookAt( this.plane.normal );
  29266. super.updateMatrixWorld( force );
  29267. }
  29268. }
  29269. const _axis = /*@__PURE__*/ new Vector3();
  29270. let _lineGeometry, _coneGeometry;
  29271. class ArrowHelper extends Object3D {
  29272. constructor( dir, origin, length, color, headLength, headWidth ) {
  29273. super();
  29274. // dir is assumed to be normalized
  29275. this.type = 'ArrowHelper';
  29276. if ( dir === undefined ) dir = new Vector3( 0, 0, 1 );
  29277. if ( origin === undefined ) origin = new Vector3( 0, 0, 0 );
  29278. if ( length === undefined ) length = 1;
  29279. if ( color === undefined ) color = 0xffff00;
  29280. if ( headLength === undefined ) headLength = 0.2 * length;
  29281. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  29282. if ( _lineGeometry === undefined ) {
  29283. _lineGeometry = new BufferGeometry();
  29284. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29285. _coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  29286. _coneGeometry.translate( 0, - 0.5, 0 );
  29287. }
  29288. this.position.copy( origin );
  29289. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29290. this.line.matrixAutoUpdate = false;
  29291. this.add( this.line );
  29292. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29293. this.cone.matrixAutoUpdate = false;
  29294. this.add( this.cone );
  29295. this.setDirection( dir );
  29296. this.setLength( length, headLength, headWidth );
  29297. }
  29298. setDirection( dir ) {
  29299. // dir is assumed to be normalized
  29300. if ( dir.y > 0.99999 ) {
  29301. this.quaternion.set( 0, 0, 0, 1 );
  29302. } else if ( dir.y < - 0.99999 ) {
  29303. this.quaternion.set( 1, 0, 0, 0 );
  29304. } else {
  29305. _axis.set( dir.z, 0, - dir.x ).normalize();
  29306. const radians = Math.acos( dir.y );
  29307. this.quaternion.setFromAxisAngle( _axis, radians );
  29308. }
  29309. }
  29310. setLength( length, headLength, headWidth ) {
  29311. if ( headLength === undefined ) headLength = 0.2 * length;
  29312. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  29313. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29314. this.line.updateMatrix();
  29315. this.cone.scale.set( headWidth, headLength, headWidth );
  29316. this.cone.position.y = length;
  29317. this.cone.updateMatrix();
  29318. }
  29319. setColor( color ) {
  29320. this.line.material.color.set( color );
  29321. this.cone.material.color.set( color );
  29322. }
  29323. copy( source ) {
  29324. super.copy( source, false );
  29325. this.line.copy( source.line );
  29326. this.cone.copy( source.cone );
  29327. return this;
  29328. }
  29329. }
  29330. class AxesHelper extends LineSegments {
  29331. constructor( size = 1 ) {
  29332. const vertices = [
  29333. 0, 0, 0, size, 0, 0,
  29334. 0, 0, 0, 0, size, 0,
  29335. 0, 0, 0, 0, 0, size
  29336. ];
  29337. const colors = [
  29338. 1, 0, 0, 1, 0.6, 0,
  29339. 0, 1, 0, 0.6, 1, 0,
  29340. 0, 0, 1, 0, 0.6, 1
  29341. ];
  29342. const geometry = new BufferGeometry();
  29343. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29344. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29345. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29346. super( geometry, material );
  29347. this.type = 'AxesHelper';
  29348. }
  29349. }
  29350. const _floatView = new Float32Array( 1 );
  29351. const _int32View = new Int32Array( _floatView.buffer );
  29352. const DataUtils = {
  29353. // Converts float32 to float16 (stored as uint16 value).
  29354. toHalfFloat: function ( val ) {
  29355. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  29356. /* This method is faster than the OpenEXR implementation (very often
  29357. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  29358. * by James Tursa?s half-precision code. */
  29359. _floatView[ 0 ] = val;
  29360. const x = _int32View[ 0 ];
  29361. let bits = ( x >> 16 ) & 0x8000; /* Get the sign */
  29362. let m = ( x >> 12 ) & 0x07ff; /* Keep one extra bit for rounding */
  29363. const e = ( x >> 23 ) & 0xff; /* Using int is faster here */
  29364. /* If zero, or denormal, or exponent underflows too much for a denormal
  29365. * half, return signed zero. */
  29366. if ( e < 103 ) return bits;
  29367. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  29368. if ( e > 142 ) {
  29369. bits |= 0x7c00;
  29370. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  29371. * not Inf, so make sure we set one mantissa bit too. */
  29372. bits |= ( ( e == 255 ) ? 0 : 1 ) && ( x & 0x007fffff );
  29373. return bits;
  29374. }
  29375. /* If exponent underflows but not too much, return a denormal */
  29376. if ( e < 113 ) {
  29377. m |= 0x0800;
  29378. /* Extra rounding may overflow and set mantissa to 0 and exponent
  29379. * to 1, which is OK. */
  29380. bits |= ( m >> ( 114 - e ) ) + ( ( m >> ( 113 - e ) ) & 1 );
  29381. return bits;
  29382. }
  29383. bits |= ( ( e - 112 ) << 10 ) | ( m >> 1 );
  29384. /* Extra rounding. An overflow will set mantissa to 0 and increment
  29385. * the exponent, which is OK. */
  29386. bits += m & 1;
  29387. return bits;
  29388. }
  29389. };
  29390. const LOD_MIN = 4;
  29391. const LOD_MAX = 8;
  29392. const SIZE_MAX = Math.pow( 2, LOD_MAX );
  29393. // The standard deviations (radians) associated with the extra mips. These are
  29394. // chosen to approximate a Trowbridge-Reitz distribution function times the
  29395. // geometric shadowing function. These sigma values squared must match the
  29396. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  29397. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  29398. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  29399. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  29400. // samples and exit early, but not recompile the shader.
  29401. const MAX_SAMPLES = 20;
  29402. const ENCODINGS = {
  29403. [ LinearEncoding ]: 0,
  29404. [ sRGBEncoding ]: 1,
  29405. [ RGBEEncoding ]: 2,
  29406. [ RGBM7Encoding ]: 3,
  29407. [ RGBM16Encoding ]: 4,
  29408. [ RGBDEncoding ]: 5,
  29409. [ GammaEncoding ]: 6
  29410. };
  29411. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  29412. const { _lodPlanes, _sizeLods, _sigmas } = /*@__PURE__*/ _createPlanes();
  29413. const _clearColor = /*@__PURE__*/ new Color();
  29414. let _oldTarget = null;
  29415. // Golden Ratio
  29416. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  29417. const INV_PHI = 1 / PHI;
  29418. // Vertices of a dodecahedron (except the opposites, which represent the
  29419. // same axis), used as axis directions evenly spread on a sphere.
  29420. const _axisDirections = [
  29421. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  29422. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  29423. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  29424. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  29425. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  29426. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  29427. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  29428. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  29429. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  29430. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  29431. /**
  29432. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  29433. * (PMREM) from a cubeMap environment texture. This allows different levels of
  29434. * blur to be quickly accessed based on material roughness. It is packed into a
  29435. * special CubeUV format that allows us to perform custom interpolation so that
  29436. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  29437. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  29438. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  29439. * higher roughness levels. In this way we maintain resolution to smoothly
  29440. * interpolate diffuse lighting while limiting sampling computation.
  29441. */
  29442. class PMREMGenerator {
  29443. constructor( renderer ) {
  29444. this._renderer = renderer;
  29445. this._pingPongRenderTarget = null;
  29446. this._blurMaterial = _getBlurShader( MAX_SAMPLES );
  29447. this._equirectShader = null;
  29448. this._cubemapShader = null;
  29449. this._compileMaterial( this._blurMaterial );
  29450. }
  29451. /**
  29452. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29453. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29454. * in radians to be applied to the scene before PMREM generation. Optional near
  29455. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  29456. * is placed at the origin).
  29457. */
  29458. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  29459. _oldTarget = this._renderer.getRenderTarget();
  29460. const cubeUVRenderTarget = this._allocateTargets();
  29461. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  29462. if ( sigma > 0 ) {
  29463. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  29464. }
  29465. this._applyPMREM( cubeUVRenderTarget );
  29466. this._cleanup( cubeUVRenderTarget );
  29467. return cubeUVRenderTarget;
  29468. }
  29469. /**
  29470. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29471. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  29472. * as this matches best with the 256 x 256 cubemap output.
  29473. */
  29474. fromEquirectangular( equirectangular ) {
  29475. return this._fromTexture( equirectangular );
  29476. }
  29477. /**
  29478. * Generates a PMREM from an cubemap texture, which can be either LDR
  29479. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  29480. * as this matches best with the 256 x 256 cubemap output.
  29481. */
  29482. fromCubemap( cubemap ) {
  29483. return this._fromTexture( cubemap );
  29484. }
  29485. /**
  29486. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  29487. * your texture's network fetch for increased concurrency.
  29488. */
  29489. compileCubemapShader() {
  29490. if ( this._cubemapShader === null ) {
  29491. this._cubemapShader = _getCubemapShader();
  29492. this._compileMaterial( this._cubemapShader );
  29493. }
  29494. }
  29495. /**
  29496. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  29497. * your texture's network fetch for increased concurrency.
  29498. */
  29499. compileEquirectangularShader() {
  29500. if ( this._equirectShader === null ) {
  29501. this._equirectShader = _getEquirectShader();
  29502. this._compileMaterial( this._equirectShader );
  29503. }
  29504. }
  29505. /**
  29506. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  29507. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  29508. * one of them will cause any others to also become unusable.
  29509. */
  29510. dispose() {
  29511. this._blurMaterial.dispose();
  29512. if ( this._cubemapShader !== null ) this._cubemapShader.dispose();
  29513. if ( this._equirectShader !== null ) this._equirectShader.dispose();
  29514. for ( let i = 0; i < _lodPlanes.length; i ++ ) {
  29515. _lodPlanes[ i ].dispose();
  29516. }
  29517. }
  29518. // private interface
  29519. _cleanup( outputTarget ) {
  29520. this._pingPongRenderTarget.dispose();
  29521. this._renderer.setRenderTarget( _oldTarget );
  29522. outputTarget.scissorTest = false;
  29523. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  29524. }
  29525. _fromTexture( texture ) {
  29526. _oldTarget = this._renderer.getRenderTarget();
  29527. const cubeUVRenderTarget = this._allocateTargets( texture );
  29528. this._textureToCubeUV( texture, cubeUVRenderTarget );
  29529. this._applyPMREM( cubeUVRenderTarget );
  29530. this._cleanup( cubeUVRenderTarget );
  29531. return cubeUVRenderTarget;
  29532. }
  29533. _allocateTargets( texture ) { // warning: null texture is valid
  29534. const params = {
  29535. magFilter: NearestFilter,
  29536. minFilter: NearestFilter,
  29537. generateMipmaps: false,
  29538. type: UnsignedByteType,
  29539. format: RGBEFormat,
  29540. encoding: _isLDR( texture ) ? texture.encoding : RGBEEncoding,
  29541. depthBuffer: false
  29542. };
  29543. const cubeUVRenderTarget = _createRenderTarget( params );
  29544. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  29545. this._pingPongRenderTarget = _createRenderTarget( params );
  29546. return cubeUVRenderTarget;
  29547. }
  29548. _compileMaterial( material ) {
  29549. const tmpMesh = new Mesh( _lodPlanes[ 0 ], material );
  29550. this._renderer.compile( tmpMesh, _flatCamera );
  29551. }
  29552. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  29553. const fov = 90;
  29554. const aspect = 1;
  29555. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  29556. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  29557. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  29558. const renderer = this._renderer;
  29559. const outputEncoding = renderer.outputEncoding;
  29560. const toneMapping = renderer.toneMapping;
  29561. renderer.getClearColor( _clearColor );
  29562. const clearAlpha = renderer.getClearAlpha();
  29563. renderer.toneMapping = NoToneMapping;
  29564. renderer.outputEncoding = LinearEncoding;
  29565. let background = scene.background;
  29566. if ( background && background.isColor ) {
  29567. background.convertSRGBToLinear();
  29568. // Convert linear to RGBE
  29569. const maxComponent = Math.max( background.r, background.g, background.b );
  29570. const fExp = Math.min( Math.max( Math.ceil( Math.log2( maxComponent ) ), - 128.0 ), 127.0 );
  29571. background = background.multiplyScalar( Math.pow( 2.0, - fExp ) );
  29572. const alpha = ( fExp + 128.0 ) / 255.0;
  29573. renderer.setClearColor( background, alpha );
  29574. scene.background = null;
  29575. }
  29576. for ( let i = 0; i < 6; i ++ ) {
  29577. const col = i % 3;
  29578. if ( col == 0 ) {
  29579. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29580. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  29581. } else if ( col == 1 ) {
  29582. cubeCamera.up.set( 0, 0, upSign[ i ] );
  29583. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  29584. } else {
  29585. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29586. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  29587. }
  29588. _setViewport( cubeUVRenderTarget,
  29589. col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX );
  29590. renderer.setRenderTarget( cubeUVRenderTarget );
  29591. renderer.render( scene, cubeCamera );
  29592. }
  29593. renderer.toneMapping = toneMapping;
  29594. renderer.outputEncoding = outputEncoding;
  29595. renderer.setClearColor( _clearColor, clearAlpha );
  29596. }
  29597. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  29598. const renderer = this._renderer;
  29599. if ( texture.isCubeTexture ) {
  29600. if ( this._cubemapShader == null ) {
  29601. this._cubemapShader = _getCubemapShader();
  29602. }
  29603. } else {
  29604. if ( this._equirectShader == null ) {
  29605. this._equirectShader = _getEquirectShader();
  29606. }
  29607. }
  29608. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  29609. const mesh = new Mesh( _lodPlanes[ 0 ], material );
  29610. const uniforms = material.uniforms;
  29611. uniforms[ 'envMap' ].value = texture;
  29612. if ( ! texture.isCubeTexture ) {
  29613. uniforms[ 'texelSize' ].value.set( 1.0 / texture.image.width, 1.0 / texture.image.height );
  29614. }
  29615. uniforms[ 'inputEncoding' ].value = ENCODINGS[ texture.encoding ];
  29616. uniforms[ 'outputEncoding' ].value = ENCODINGS[ cubeUVRenderTarget.texture.encoding ];
  29617. _setViewport( cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX );
  29618. renderer.setRenderTarget( cubeUVRenderTarget );
  29619. renderer.render( mesh, _flatCamera );
  29620. }
  29621. _applyPMREM( cubeUVRenderTarget ) {
  29622. const renderer = this._renderer;
  29623. const autoClear = renderer.autoClear;
  29624. renderer.autoClear = false;
  29625. for ( let i = 1; i < TOTAL_LODS; i ++ ) {
  29626. const sigma = Math.sqrt( _sigmas[ i ] * _sigmas[ i ] - _sigmas[ i - 1 ] * _sigmas[ i - 1 ] );
  29627. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  29628. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  29629. }
  29630. renderer.autoClear = autoClear;
  29631. }
  29632. /**
  29633. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  29634. * vertically and horizontally, but this breaks down on a cube. Here we apply
  29635. * the blur latitudinally (around the poles), and then longitudinally (towards
  29636. * the poles) to approximate the orthogonally-separable blur. It is least
  29637. * accurate at the poles, but still does a decent job.
  29638. */
  29639. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  29640. const pingPongRenderTarget = this._pingPongRenderTarget;
  29641. this._halfBlur(
  29642. cubeUVRenderTarget,
  29643. pingPongRenderTarget,
  29644. lodIn,
  29645. lodOut,
  29646. sigma,
  29647. 'latitudinal',
  29648. poleAxis );
  29649. this._halfBlur(
  29650. pingPongRenderTarget,
  29651. cubeUVRenderTarget,
  29652. lodOut,
  29653. lodOut,
  29654. sigma,
  29655. 'longitudinal',
  29656. poleAxis );
  29657. }
  29658. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  29659. const renderer = this._renderer;
  29660. const blurMaterial = this._blurMaterial;
  29661. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  29662. console.error(
  29663. 'blur direction must be either latitudinal or longitudinal!' );
  29664. }
  29665. // Number of standard deviations at which to cut off the discrete approximation.
  29666. const STANDARD_DEVIATIONS = 3;
  29667. const blurMesh = new Mesh( _lodPlanes[ lodOut ], blurMaterial );
  29668. const blurUniforms = blurMaterial.uniforms;
  29669. const pixels = _sizeLods[ lodIn ] - 1;
  29670. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  29671. const sigmaPixels = sigmaRadians / radiansPerPixel;
  29672. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  29673. if ( samples > MAX_SAMPLES ) {
  29674. console.warn( `sigmaRadians, ${
  29675. sigmaRadians}, is too large and will clip, as it requested ${
  29676. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  29677. }
  29678. const weights = [];
  29679. let sum = 0;
  29680. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  29681. const x = i / sigmaPixels;
  29682. const weight = Math.exp( - x * x / 2 );
  29683. weights.push( weight );
  29684. if ( i == 0 ) {
  29685. sum += weight;
  29686. } else if ( i < samples ) {
  29687. sum += 2 * weight;
  29688. }
  29689. }
  29690. for ( let i = 0; i < weights.length; i ++ ) {
  29691. weights[ i ] = weights[ i ] / sum;
  29692. }
  29693. blurUniforms[ 'envMap' ].value = targetIn.texture;
  29694. blurUniforms[ 'samples' ].value = samples;
  29695. blurUniforms[ 'weights' ].value = weights;
  29696. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  29697. if ( poleAxis ) {
  29698. blurUniforms[ 'poleAxis' ].value = poleAxis;
  29699. }
  29700. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  29701. blurUniforms[ 'mipInt' ].value = LOD_MAX - lodIn;
  29702. blurUniforms[ 'inputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  29703. blurUniforms[ 'outputEncoding' ].value = ENCODINGS[ targetIn.texture.encoding ];
  29704. const outputSize = _sizeLods[ lodOut ];
  29705. const x = 3 * Math.max( 0, SIZE_MAX - 2 * outputSize );
  29706. const y = ( lodOut === 0 ? 0 : 2 * SIZE_MAX ) + 2 * outputSize * ( lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0 );
  29707. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  29708. renderer.setRenderTarget( targetOut );
  29709. renderer.render( blurMesh, _flatCamera );
  29710. }
  29711. }
  29712. function _isLDR( texture ) {
  29713. if ( texture === undefined || texture.type !== UnsignedByteType ) return false;
  29714. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  29715. }
  29716. function _createPlanes() {
  29717. const _lodPlanes = [];
  29718. const _sizeLods = [];
  29719. const _sigmas = [];
  29720. let lod = LOD_MAX;
  29721. for ( let i = 0; i < TOTAL_LODS; i ++ ) {
  29722. const sizeLod = Math.pow( 2, lod );
  29723. _sizeLods.push( sizeLod );
  29724. let sigma = 1.0 / sizeLod;
  29725. if ( i > LOD_MAX - LOD_MIN ) {
  29726. sigma = EXTRA_LOD_SIGMA[ i - LOD_MAX + LOD_MIN - 1 ];
  29727. } else if ( i == 0 ) {
  29728. sigma = 0;
  29729. }
  29730. _sigmas.push( sigma );
  29731. const texelSize = 1.0 / ( sizeLod - 1 );
  29732. const min = - texelSize / 2;
  29733. const max = 1 + texelSize / 2;
  29734. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  29735. const cubeFaces = 6;
  29736. const vertices = 6;
  29737. const positionSize = 3;
  29738. const uvSize = 2;
  29739. const faceIndexSize = 1;
  29740. const position = new Float32Array( positionSize * vertices * cubeFaces );
  29741. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  29742. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  29743. for ( let face = 0; face < cubeFaces; face ++ ) {
  29744. const x = ( face % 3 ) * 2 / 3 - 1;
  29745. const y = face > 2 ? 0 : - 1;
  29746. const coordinates = [
  29747. x, y, 0,
  29748. x + 2 / 3, y, 0,
  29749. x + 2 / 3, y + 1, 0,
  29750. x, y, 0,
  29751. x + 2 / 3, y + 1, 0,
  29752. x, y + 1, 0
  29753. ];
  29754. position.set( coordinates, positionSize * vertices * face );
  29755. uv.set( uv1, uvSize * vertices * face );
  29756. const fill = [ face, face, face, face, face, face ];
  29757. faceIndex.set( fill, faceIndexSize * vertices * face );
  29758. }
  29759. const planes = new BufferGeometry();
  29760. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  29761. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  29762. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  29763. _lodPlanes.push( planes );
  29764. if ( lod > LOD_MIN ) {
  29765. lod --;
  29766. }
  29767. }
  29768. return { _lodPlanes, _sizeLods, _sigmas };
  29769. }
  29770. function _createRenderTarget( params ) {
  29771. const cubeUVRenderTarget = new WebGLRenderTarget( 3 * SIZE_MAX, 3 * SIZE_MAX, params );
  29772. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  29773. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  29774. cubeUVRenderTarget.scissorTest = true;
  29775. return cubeUVRenderTarget;
  29776. }
  29777. function _setViewport( target, x, y, width, height ) {
  29778. target.viewport.set( x, y, width, height );
  29779. target.scissor.set( x, y, width, height );
  29780. }
  29781. function _getBlurShader( maxSamples ) {
  29782. const weights = new Float32Array( maxSamples );
  29783. const poleAxis = new Vector3( 0, 1, 0 );
  29784. const shaderMaterial = new RawShaderMaterial( {
  29785. name: 'SphericalGaussianBlur',
  29786. defines: { 'n': maxSamples },
  29787. uniforms: {
  29788. 'envMap': { value: null },
  29789. 'samples': { value: 1 },
  29790. 'weights': { value: weights },
  29791. 'latitudinal': { value: false },
  29792. 'dTheta': { value: 0 },
  29793. 'mipInt': { value: 0 },
  29794. 'poleAxis': { value: poleAxis },
  29795. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  29796. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  29797. },
  29798. vertexShader: _getCommonVertexShader(),
  29799. fragmentShader: /* glsl */`
  29800. precision mediump float;
  29801. precision mediump int;
  29802. varying vec3 vOutputDirection;
  29803. uniform sampler2D envMap;
  29804. uniform int samples;
  29805. uniform float weights[ n ];
  29806. uniform bool latitudinal;
  29807. uniform float dTheta;
  29808. uniform float mipInt;
  29809. uniform vec3 poleAxis;
  29810. ${ _getEncodings() }
  29811. #define ENVMAP_TYPE_CUBE_UV
  29812. #include <cube_uv_reflection_fragment>
  29813. vec3 getSample( float theta, vec3 axis ) {
  29814. float cosTheta = cos( theta );
  29815. // Rodrigues' axis-angle rotation
  29816. vec3 sampleDirection = vOutputDirection * cosTheta
  29817. + cross( axis, vOutputDirection ) * sin( theta )
  29818. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  29819. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  29820. }
  29821. void main() {
  29822. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  29823. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  29824. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  29825. }
  29826. axis = normalize( axis );
  29827. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29828. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  29829. for ( int i = 1; i < n; i++ ) {
  29830. if ( i >= samples ) {
  29831. break;
  29832. }
  29833. float theta = dTheta * float( i );
  29834. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  29835. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  29836. }
  29837. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29838. }
  29839. `,
  29840. blending: NoBlending,
  29841. depthTest: false,
  29842. depthWrite: false
  29843. } );
  29844. return shaderMaterial;
  29845. }
  29846. function _getEquirectShader() {
  29847. const texelSize = new Vector2$1( 1, 1 );
  29848. const shaderMaterial = new RawShaderMaterial( {
  29849. name: 'EquirectangularToCubeUV',
  29850. uniforms: {
  29851. 'envMap': { value: null },
  29852. 'texelSize': { value: texelSize },
  29853. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  29854. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  29855. },
  29856. vertexShader: _getCommonVertexShader(),
  29857. fragmentShader: /* glsl */`
  29858. precision mediump float;
  29859. precision mediump int;
  29860. varying vec3 vOutputDirection;
  29861. uniform sampler2D envMap;
  29862. uniform vec2 texelSize;
  29863. ${ _getEncodings() }
  29864. #include <common>
  29865. void main() {
  29866. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29867. vec3 outputDirection = normalize( vOutputDirection );
  29868. vec2 uv = equirectUv( outputDirection );
  29869. vec2 f = fract( uv / texelSize - 0.5 );
  29870. uv -= f * texelSize;
  29871. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29872. uv.x += texelSize.x;
  29873. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29874. uv.y += texelSize.y;
  29875. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29876. uv.x -= texelSize.x;
  29877. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29878. vec3 tm = mix( tl, tr, f.x );
  29879. vec3 bm = mix( bl, br, f.x );
  29880. gl_FragColor.rgb = mix( tm, bm, f.y );
  29881. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29882. }
  29883. `,
  29884. blending: NoBlending,
  29885. depthTest: false,
  29886. depthWrite: false
  29887. } );
  29888. return shaderMaterial;
  29889. }
  29890. function _getCubemapShader() {
  29891. const shaderMaterial = new RawShaderMaterial( {
  29892. name: 'CubemapToCubeUV',
  29893. uniforms: {
  29894. 'envMap': { value: null },
  29895. 'inputEncoding': { value: ENCODINGS[ LinearEncoding ] },
  29896. 'outputEncoding': { value: ENCODINGS[ LinearEncoding ] }
  29897. },
  29898. vertexShader: _getCommonVertexShader(),
  29899. fragmentShader: /* glsl */`
  29900. precision mediump float;
  29901. precision mediump int;
  29902. varying vec3 vOutputDirection;
  29903. uniform samplerCube envMap;
  29904. ${ _getEncodings() }
  29905. void main() {
  29906. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29907. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  29908. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29909. }
  29910. `,
  29911. blending: NoBlending,
  29912. depthTest: false,
  29913. depthWrite: false
  29914. } );
  29915. return shaderMaterial;
  29916. }
  29917. function _getCommonVertexShader() {
  29918. return /* glsl */`
  29919. precision mediump float;
  29920. precision mediump int;
  29921. attribute vec3 position;
  29922. attribute vec2 uv;
  29923. attribute float faceIndex;
  29924. varying vec3 vOutputDirection;
  29925. // RH coordinate system; PMREM face-indexing convention
  29926. vec3 getDirection( vec2 uv, float face ) {
  29927. uv = 2.0 * uv - 1.0;
  29928. vec3 direction = vec3( uv, 1.0 );
  29929. if ( face == 0.0 ) {
  29930. direction = direction.zyx; // ( 1, v, u ) pos x
  29931. } else if ( face == 1.0 ) {
  29932. direction = direction.xzy;
  29933. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  29934. } else if ( face == 2.0 ) {
  29935. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  29936. } else if ( face == 3.0 ) {
  29937. direction = direction.zyx;
  29938. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  29939. } else if ( face == 4.0 ) {
  29940. direction = direction.xzy;
  29941. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  29942. } else if ( face == 5.0 ) {
  29943. direction.z *= -1.0; // ( u, v, -1 ) neg z
  29944. }
  29945. return direction;
  29946. }
  29947. void main() {
  29948. vOutputDirection = getDirection( uv, faceIndex );
  29949. gl_Position = vec4( position, 1.0 );
  29950. }
  29951. `;
  29952. }
  29953. function _getEncodings() {
  29954. return /* glsl */`
  29955. uniform int inputEncoding;
  29956. uniform int outputEncoding;
  29957. #include <encodings_pars_fragment>
  29958. vec4 inputTexelToLinear( vec4 value ) {
  29959. if ( inputEncoding == 0 ) {
  29960. return value;
  29961. } else if ( inputEncoding == 1 ) {
  29962. return sRGBToLinear( value );
  29963. } else if ( inputEncoding == 2 ) {
  29964. return RGBEToLinear( value );
  29965. } else if ( inputEncoding == 3 ) {
  29966. return RGBMToLinear( value, 7.0 );
  29967. } else if ( inputEncoding == 4 ) {
  29968. return RGBMToLinear( value, 16.0 );
  29969. } else if ( inputEncoding == 5 ) {
  29970. return RGBDToLinear( value, 256.0 );
  29971. } else {
  29972. return GammaToLinear( value, 2.2 );
  29973. }
  29974. }
  29975. vec4 linearToOutputTexel( vec4 value ) {
  29976. if ( outputEncoding == 0 ) {
  29977. return value;
  29978. } else if ( outputEncoding == 1 ) {
  29979. return LinearTosRGB( value );
  29980. } else if ( outputEncoding == 2 ) {
  29981. return LinearToRGBE( value );
  29982. } else if ( outputEncoding == 3 ) {
  29983. return LinearToRGBM( value, 7.0 );
  29984. } else if ( outputEncoding == 4 ) {
  29985. return LinearToRGBM( value, 16.0 );
  29986. } else if ( outputEncoding == 5 ) {
  29987. return LinearToRGBD( value, 256.0 );
  29988. } else {
  29989. return LinearToGamma( value, 2.2 );
  29990. }
  29991. }
  29992. vec4 envMapTexelToLinear( vec4 color ) {
  29993. return inputTexelToLinear( color );
  29994. }
  29995. `;
  29996. }
  29997. function Face4( a, b, c, d, normal, color, materialIndex ) {
  29998. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  29999. return new Face3( a, b, c, normal, color, materialIndex );
  30000. }
  30001. const LineStrip = 0;
  30002. const LinePieces = 1;
  30003. const NoColors = 0;
  30004. const FaceColors = 1;
  30005. const VertexColors = 2;
  30006. function MeshFaceMaterial( materials ) {
  30007. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  30008. return materials;
  30009. }
  30010. function MultiMaterial( materials = [] ) {
  30011. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  30012. materials.isMultiMaterial = true;
  30013. materials.materials = materials;
  30014. materials.clone = function () {
  30015. return materials.slice();
  30016. };
  30017. return materials;
  30018. }
  30019. function PointCloud( geometry, material ) {
  30020. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  30021. return new Points( geometry, material );
  30022. }
  30023. function Particle( material ) {
  30024. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  30025. return new Sprite( material );
  30026. }
  30027. function ParticleSystem( geometry, material ) {
  30028. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  30029. return new Points( geometry, material );
  30030. }
  30031. function PointCloudMaterial( parameters ) {
  30032. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  30033. return new PointsMaterial( parameters );
  30034. }
  30035. function ParticleBasicMaterial( parameters ) {
  30036. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  30037. return new PointsMaterial( parameters );
  30038. }
  30039. function ParticleSystemMaterial( parameters ) {
  30040. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  30041. return new PointsMaterial( parameters );
  30042. }
  30043. function Vertex( x, y, z ) {
  30044. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  30045. return new Vector3( x, y, z );
  30046. }
  30047. //
  30048. function DynamicBufferAttribute( array, itemSize ) {
  30049. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.' );
  30050. return new BufferAttribute( array, itemSize ).setUsage( DynamicDrawUsage );
  30051. }
  30052. function Int8Attribute( array, itemSize ) {
  30053. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  30054. return new Int8BufferAttribute( array, itemSize );
  30055. }
  30056. function Uint8Attribute( array, itemSize ) {
  30057. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  30058. return new Uint8BufferAttribute( array, itemSize );
  30059. }
  30060. function Uint8ClampedAttribute( array, itemSize ) {
  30061. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  30062. return new Uint8ClampedBufferAttribute( array, itemSize );
  30063. }
  30064. function Int16Attribute( array, itemSize ) {
  30065. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  30066. return new Int16BufferAttribute( array, itemSize );
  30067. }
  30068. function Uint16Attribute( array, itemSize ) {
  30069. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  30070. return new Uint16BufferAttribute( array, itemSize );
  30071. }
  30072. function Int32Attribute( array, itemSize ) {
  30073. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  30074. return new Int32BufferAttribute( array, itemSize );
  30075. }
  30076. function Uint32Attribute( array, itemSize ) {
  30077. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  30078. return new Uint32BufferAttribute( array, itemSize );
  30079. }
  30080. function Float32Attribute( array, itemSize ) {
  30081. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  30082. return new Float32BufferAttribute( array, itemSize );
  30083. }
  30084. function Float64Attribute( array, itemSize ) {
  30085. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  30086. return new Float64BufferAttribute( array, itemSize );
  30087. }
  30088. //
  30089. Curve.create = function ( construct, getPoint ) {
  30090. console.log( 'THREE.Curve.create() has been deprecated' );
  30091. construct.prototype = Object.create( Curve.prototype );
  30092. construct.prototype.constructor = construct;
  30093. construct.prototype.getPoint = getPoint;
  30094. return construct;
  30095. };
  30096. //
  30097. Object.assign( CurvePath.prototype, {
  30098. createPointsGeometry: function ( divisions ) {
  30099. console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  30100. // generate geometry from path points (for Line or Points objects)
  30101. const pts = this.getPoints( divisions );
  30102. return this.createGeometry( pts );
  30103. },
  30104. createSpacedPointsGeometry: function ( divisions ) {
  30105. console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  30106. // generate geometry from equidistant sampling along the path
  30107. const pts = this.getSpacedPoints( divisions );
  30108. return this.createGeometry( pts );
  30109. },
  30110. createGeometry: function ( points ) {
  30111. console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  30112. const geometry = new Geometry();
  30113. for ( let i = 0, l = points.length; i < l; i ++ ) {
  30114. const point = points[ i ];
  30115. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  30116. }
  30117. return geometry;
  30118. }
  30119. } );
  30120. //
  30121. Object.assign( Path.prototype, {
  30122. fromPoints: function ( points ) {
  30123. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  30124. return this.setFromPoints( points );
  30125. }
  30126. } );
  30127. //
  30128. function ClosedSplineCurve3( points ) {
  30129. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  30130. CatmullRomCurve3.call( this, points );
  30131. this.type = 'catmullrom';
  30132. this.closed = true;
  30133. }
  30134. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  30135. //
  30136. function SplineCurve3( points ) {
  30137. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  30138. CatmullRomCurve3.call( this, points );
  30139. this.type = 'catmullrom';
  30140. }
  30141. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  30142. //
  30143. function Spline( points ) {
  30144. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  30145. CatmullRomCurve3.call( this, points );
  30146. this.type = 'catmullrom';
  30147. }
  30148. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  30149. Object.assign( Spline.prototype, {
  30150. initFromArray: function ( /* a */ ) {
  30151. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  30152. },
  30153. getControlPointsArray: function ( /* optionalTarget */ ) {
  30154. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  30155. },
  30156. reparametrizeByArcLength: function ( /* samplingCoef */ ) {
  30157. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  30158. }
  30159. } );
  30160. //
  30161. function AxisHelper( size ) {
  30162. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  30163. return new AxesHelper( size );
  30164. }
  30165. function BoundingBoxHelper( object, color ) {
  30166. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  30167. return new BoxHelper( object, color );
  30168. }
  30169. function EdgesHelper( object, hex ) {
  30170. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  30171. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  30172. }
  30173. GridHelper.prototype.setColors = function () {
  30174. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  30175. };
  30176. SkeletonHelper.prototype.update = function () {
  30177. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  30178. };
  30179. function WireframeHelper( object, hex ) {
  30180. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  30181. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  30182. }
  30183. //
  30184. Object.assign( Loader.prototype, {
  30185. extractUrlBase: function ( url ) {
  30186. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  30187. return LoaderUtils.extractUrlBase( url );
  30188. }
  30189. } );
  30190. Loader.Handlers = {
  30191. add: function ( /* regex, loader */ ) {
  30192. console.error( 'THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.' );
  30193. },
  30194. get: function ( /* file */ ) {
  30195. console.error( 'THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.' );
  30196. }
  30197. };
  30198. function XHRLoader( manager ) {
  30199. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  30200. return new FileLoader( manager );
  30201. }
  30202. function BinaryTextureLoader( manager ) {
  30203. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  30204. return new DataTextureLoader( manager );
  30205. }
  30206. //
  30207. Object.assign( Box2.prototype, {
  30208. center: function ( optionalTarget ) {
  30209. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  30210. return this.getCenter( optionalTarget );
  30211. },
  30212. empty: function () {
  30213. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  30214. return this.isEmpty();
  30215. },
  30216. isIntersectionBox: function ( box ) {
  30217. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  30218. return this.intersectsBox( box );
  30219. },
  30220. size: function ( optionalTarget ) {
  30221. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  30222. return this.getSize( optionalTarget );
  30223. }
  30224. } );
  30225. Object.assign( Box3.prototype, {
  30226. center: function ( optionalTarget ) {
  30227. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  30228. return this.getCenter( optionalTarget );
  30229. },
  30230. empty: function () {
  30231. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  30232. return this.isEmpty();
  30233. },
  30234. isIntersectionBox: function ( box ) {
  30235. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  30236. return this.intersectsBox( box );
  30237. },
  30238. isIntersectionSphere: function ( sphere ) {
  30239. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  30240. return this.intersectsSphere( sphere );
  30241. },
  30242. size: function ( optionalTarget ) {
  30243. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  30244. return this.getSize( optionalTarget );
  30245. }
  30246. } );
  30247. Object.assign( Sphere.prototype, {
  30248. empty: function () {
  30249. console.warn( 'THREE.Sphere: .empty() has been renamed to .isEmpty().' );
  30250. return this.isEmpty();
  30251. },
  30252. } );
  30253. Frustum.prototype.setFromMatrix = function ( m ) {
  30254. console.warn( 'THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().' );
  30255. return this.setFromProjectionMatrix( m );
  30256. };
  30257. Line3.prototype.center = function ( optionalTarget ) {
  30258. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  30259. return this.getCenter( optionalTarget );
  30260. };
  30261. Object.assign( MathUtils, {
  30262. random16: function () {
  30263. console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' );
  30264. return Math.random();
  30265. },
  30266. nearestPowerOfTwo: function ( value ) {
  30267. console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' );
  30268. return MathUtils.floorPowerOfTwo( value );
  30269. },
  30270. nextPowerOfTwo: function ( value ) {
  30271. console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' );
  30272. return MathUtils.ceilPowerOfTwo( value );
  30273. }
  30274. } );
  30275. Object.assign( Matrix3.prototype, {
  30276. flattenToArrayOffset: function ( array, offset ) {
  30277. console.warn( 'THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  30278. return this.toArray( array, offset );
  30279. },
  30280. multiplyVector3: function ( vector ) {
  30281. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  30282. return vector.applyMatrix3( this );
  30283. },
  30284. multiplyVector3Array: function ( /* a */ ) {
  30285. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  30286. },
  30287. applyToBufferAttribute: function ( attribute ) {
  30288. console.warn( 'THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.' );
  30289. return attribute.applyMatrix3( this );
  30290. },
  30291. applyToVector3Array: function ( /* array, offset, length */ ) {
  30292. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  30293. },
  30294. getInverse: function ( matrix ) {
  30295. console.warn( 'THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  30296. return this.copy( matrix ).invert();
  30297. }
  30298. } );
  30299. Object.assign( Matrix4.prototype, {
  30300. extractPosition: function ( m ) {
  30301. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  30302. return this.copyPosition( m );
  30303. },
  30304. flattenToArrayOffset: function ( array, offset ) {
  30305. console.warn( 'THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.' );
  30306. return this.toArray( array, offset );
  30307. },
  30308. getPosition: function () {
  30309. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  30310. return new Vector3().setFromMatrixColumn( this, 3 );
  30311. },
  30312. setRotationFromQuaternion: function ( q ) {
  30313. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  30314. return this.makeRotationFromQuaternion( q );
  30315. },
  30316. multiplyToArray: function () {
  30317. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  30318. },
  30319. multiplyVector3: function ( vector ) {
  30320. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  30321. return vector.applyMatrix4( this );
  30322. },
  30323. multiplyVector4: function ( vector ) {
  30324. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  30325. return vector.applyMatrix4( this );
  30326. },
  30327. multiplyVector3Array: function ( /* a */ ) {
  30328. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  30329. },
  30330. rotateAxis: function ( v ) {
  30331. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  30332. v.transformDirection( this );
  30333. },
  30334. crossVector: function ( vector ) {
  30335. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  30336. return vector.applyMatrix4( this );
  30337. },
  30338. translate: function () {
  30339. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  30340. },
  30341. rotateX: function () {
  30342. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  30343. },
  30344. rotateY: function () {
  30345. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  30346. },
  30347. rotateZ: function () {
  30348. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  30349. },
  30350. rotateByAxis: function () {
  30351. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  30352. },
  30353. applyToBufferAttribute: function ( attribute ) {
  30354. console.warn( 'THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.' );
  30355. return attribute.applyMatrix4( this );
  30356. },
  30357. applyToVector3Array: function ( /* array, offset, length */ ) {
  30358. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  30359. },
  30360. makeFrustum: function ( left, right, bottom, top, near, far ) {
  30361. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  30362. return this.makePerspective( left, right, top, bottom, near, far );
  30363. },
  30364. getInverse: function ( matrix ) {
  30365. console.warn( 'THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.' );
  30366. return this.copy( matrix ).invert();
  30367. }
  30368. } );
  30369. Plane.prototype.isIntersectionLine = function ( line ) {
  30370. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  30371. return this.intersectsLine( line );
  30372. };
  30373. Object.assign( Quaternion.prototype, {
  30374. multiplyVector3: function ( vector ) {
  30375. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  30376. return vector.applyQuaternion( this );
  30377. },
  30378. inverse: function ( ) {
  30379. console.warn( 'THREE.Quaternion: .inverse() has been renamed to invert().' );
  30380. return this.invert();
  30381. }
  30382. } );
  30383. Object.assign( Ray.prototype, {
  30384. isIntersectionBox: function ( box ) {
  30385. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  30386. return this.intersectsBox( box );
  30387. },
  30388. isIntersectionPlane: function ( plane ) {
  30389. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  30390. return this.intersectsPlane( plane );
  30391. },
  30392. isIntersectionSphere: function ( sphere ) {
  30393. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  30394. return this.intersectsSphere( sphere );
  30395. }
  30396. } );
  30397. Object.assign( Triangle.prototype, {
  30398. area: function () {
  30399. console.warn( 'THREE.Triangle: .area() has been renamed to .getArea().' );
  30400. return this.getArea();
  30401. },
  30402. barycoordFromPoint: function ( point, target ) {
  30403. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  30404. return this.getBarycoord( point, target );
  30405. },
  30406. midpoint: function ( target ) {
  30407. console.warn( 'THREE.Triangle: .midpoint() has been renamed to .getMidpoint().' );
  30408. return this.getMidpoint( target );
  30409. },
  30410. normal: function ( target ) {
  30411. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  30412. return this.getNormal( target );
  30413. },
  30414. plane: function ( target ) {
  30415. console.warn( 'THREE.Triangle: .plane() has been renamed to .getPlane().' );
  30416. return this.getPlane( target );
  30417. }
  30418. } );
  30419. Object.assign( Triangle, {
  30420. barycoordFromPoint: function ( point, a, b, c, target ) {
  30421. console.warn( 'THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().' );
  30422. return Triangle.getBarycoord( point, a, b, c, target );
  30423. },
  30424. normal: function ( a, b, c, target ) {
  30425. console.warn( 'THREE.Triangle: .normal() has been renamed to .getNormal().' );
  30426. return Triangle.getNormal( a, b, c, target );
  30427. }
  30428. } );
  30429. Object.assign( Shape.prototype, {
  30430. extractAllPoints: function ( divisions ) {
  30431. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  30432. return this.extractPoints( divisions );
  30433. },
  30434. extrude: function ( options ) {
  30435. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  30436. return new ExtrudeGeometry( this, options );
  30437. },
  30438. makeGeometry: function ( options ) {
  30439. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  30440. return new ShapeGeometry( this, options );
  30441. }
  30442. } );
  30443. Object.assign( Vector2$1.prototype, {
  30444. fromAttribute: function ( attribute, index, offset ) {
  30445. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  30446. return this.fromBufferAttribute( attribute, index, offset );
  30447. },
  30448. distanceToManhattan: function ( v ) {
  30449. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  30450. return this.manhattanDistanceTo( v );
  30451. },
  30452. lengthManhattan: function () {
  30453. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  30454. return this.manhattanLength();
  30455. }
  30456. } );
  30457. Object.assign( Vector3.prototype, {
  30458. setEulerFromRotationMatrix: function () {
  30459. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  30460. },
  30461. setEulerFromQuaternion: function () {
  30462. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  30463. },
  30464. getPositionFromMatrix: function ( m ) {
  30465. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  30466. return this.setFromMatrixPosition( m );
  30467. },
  30468. getScaleFromMatrix: function ( m ) {
  30469. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  30470. return this.setFromMatrixScale( m );
  30471. },
  30472. getColumnFromMatrix: function ( index, matrix ) {
  30473. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  30474. return this.setFromMatrixColumn( matrix, index );
  30475. },
  30476. applyProjection: function ( m ) {
  30477. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  30478. return this.applyMatrix4( m );
  30479. },
  30480. fromAttribute: function ( attribute, index, offset ) {
  30481. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  30482. return this.fromBufferAttribute( attribute, index, offset );
  30483. },
  30484. distanceToManhattan: function ( v ) {
  30485. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  30486. return this.manhattanDistanceTo( v );
  30487. },
  30488. lengthManhattan: function () {
  30489. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  30490. return this.manhattanLength();
  30491. }
  30492. } );
  30493. Object.assign( Vector4.prototype, {
  30494. fromAttribute: function ( attribute, index, offset ) {
  30495. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  30496. return this.fromBufferAttribute( attribute, index, offset );
  30497. },
  30498. lengthManhattan: function () {
  30499. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  30500. return this.manhattanLength();
  30501. }
  30502. } );
  30503. //
  30504. Object.assign( Geometry.prototype, {
  30505. computeTangents: function () {
  30506. console.error( 'THREE.Geometry: .computeTangents() has been removed.' );
  30507. },
  30508. computeLineDistances: function () {
  30509. console.error( 'THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.' );
  30510. },
  30511. applyMatrix: function ( matrix ) {
  30512. console.warn( 'THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  30513. return this.applyMatrix4( matrix );
  30514. }
  30515. } );
  30516. Object.assign( Object3D.prototype, {
  30517. getChildByName: function ( name ) {
  30518. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  30519. return this.getObjectByName( name );
  30520. },
  30521. renderDepth: function () {
  30522. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  30523. },
  30524. translate: function ( distance, axis ) {
  30525. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  30526. return this.translateOnAxis( axis, distance );
  30527. },
  30528. getWorldRotation: function () {
  30529. console.error( 'THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.' );
  30530. },
  30531. applyMatrix: function ( matrix ) {
  30532. console.warn( 'THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().' );
  30533. return this.applyMatrix4( matrix );
  30534. }
  30535. } );
  30536. Object.defineProperties( Object3D.prototype, {
  30537. eulerOrder: {
  30538. get: function () {
  30539. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  30540. return this.rotation.order;
  30541. },
  30542. set: function ( value ) {
  30543. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  30544. this.rotation.order = value;
  30545. }
  30546. },
  30547. useQuaternion: {
  30548. get: function () {
  30549. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  30550. },
  30551. set: function () {
  30552. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  30553. }
  30554. }
  30555. } );
  30556. Object.assign( Mesh.prototype, {
  30557. setDrawMode: function () {
  30558. console.error( 'THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  30559. },
  30560. } );
  30561. Object.defineProperties( Mesh.prototype, {
  30562. drawMode: {
  30563. get: function () {
  30564. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.' );
  30565. return TrianglesDrawMode;
  30566. },
  30567. set: function () {
  30568. console.error( 'THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.' );
  30569. }
  30570. }
  30571. } );
  30572. Object.defineProperties( LOD.prototype, {
  30573. objects: {
  30574. get: function () {
  30575. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  30576. return this.levels;
  30577. }
  30578. }
  30579. } );
  30580. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  30581. get: function () {
  30582. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  30583. },
  30584. set: function () {
  30585. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  30586. }
  30587. } );
  30588. SkinnedMesh.prototype.initBones = function () {
  30589. console.error( 'THREE.SkinnedMesh: initBones() has been removed.' );
  30590. };
  30591. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  30592. get: function () {
  30593. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  30594. return this.arcLengthDivisions;
  30595. },
  30596. set: function ( value ) {
  30597. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  30598. this.arcLengthDivisions = value;
  30599. }
  30600. } );
  30601. //
  30602. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  30603. console.warn( 'THREE.PerspectiveCamera.setLens is deprecated. ' +
  30604. 'Use .setFocalLength and .filmGauge for a photographic setup.' );
  30605. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  30606. this.setFocalLength( focalLength );
  30607. };
  30608. //
  30609. Object.defineProperties( Light.prototype, {
  30610. onlyShadow: {
  30611. set: function () {
  30612. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  30613. }
  30614. },
  30615. shadowCameraFov: {
  30616. set: function ( value ) {
  30617. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  30618. this.shadow.camera.fov = value;
  30619. }
  30620. },
  30621. shadowCameraLeft: {
  30622. set: function ( value ) {
  30623. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  30624. this.shadow.camera.left = value;
  30625. }
  30626. },
  30627. shadowCameraRight: {
  30628. set: function ( value ) {
  30629. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  30630. this.shadow.camera.right = value;
  30631. }
  30632. },
  30633. shadowCameraTop: {
  30634. set: function ( value ) {
  30635. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  30636. this.shadow.camera.top = value;
  30637. }
  30638. },
  30639. shadowCameraBottom: {
  30640. set: function ( value ) {
  30641. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  30642. this.shadow.camera.bottom = value;
  30643. }
  30644. },
  30645. shadowCameraNear: {
  30646. set: function ( value ) {
  30647. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  30648. this.shadow.camera.near = value;
  30649. }
  30650. },
  30651. shadowCameraFar: {
  30652. set: function ( value ) {
  30653. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  30654. this.shadow.camera.far = value;
  30655. }
  30656. },
  30657. shadowCameraVisible: {
  30658. set: function () {
  30659. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  30660. }
  30661. },
  30662. shadowBias: {
  30663. set: function ( value ) {
  30664. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  30665. this.shadow.bias = value;
  30666. }
  30667. },
  30668. shadowDarkness: {
  30669. set: function () {
  30670. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  30671. }
  30672. },
  30673. shadowMapWidth: {
  30674. set: function ( value ) {
  30675. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  30676. this.shadow.mapSize.width = value;
  30677. }
  30678. },
  30679. shadowMapHeight: {
  30680. set: function ( value ) {
  30681. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  30682. this.shadow.mapSize.height = value;
  30683. }
  30684. }
  30685. } );
  30686. //
  30687. Object.defineProperties( BufferAttribute.prototype, {
  30688. length: {
  30689. get: function () {
  30690. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  30691. return this.array.length;
  30692. }
  30693. },
  30694. dynamic: {
  30695. get: function () {
  30696. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  30697. return this.usage === DynamicDrawUsage;
  30698. },
  30699. set: function ( /* value */ ) {
  30700. console.warn( 'THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.' );
  30701. this.setUsage( DynamicDrawUsage );
  30702. }
  30703. }
  30704. } );
  30705. Object.assign( BufferAttribute.prototype, {
  30706. setDynamic: function ( value ) {
  30707. //console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  30708. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  30709. return this;
  30710. },
  30711. copyIndicesArray: function ( /* indices */ ) {
  30712. console.error( 'THREE.BufferAttribute: .copyIndicesArray() has been removed.' );
  30713. },
  30714. setArray: function ( /* array */ ) {
  30715. console.error( 'THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  30716. }
  30717. } );
  30718. Object.assign( BufferGeometry.prototype, {
  30719. addIndex: function ( index ) {
  30720. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  30721. this.setIndex( index );
  30722. },
  30723. addAttribute: function ( name, attribute ) {
  30724. console.warn( 'THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().' );
  30725. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  30726. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  30727. return this.setAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  30728. }
  30729. if ( name === 'index' ) {
  30730. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  30731. this.setIndex( attribute );
  30732. return this;
  30733. }
  30734. return this.setAttribute( name, attribute );
  30735. },
  30736. addDrawCall: function ( start, count, indexOffset ) {
  30737. if ( indexOffset !== undefined ) {
  30738. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  30739. }
  30740. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  30741. this.addGroup( start, count );
  30742. },
  30743. clearDrawCalls: function () {
  30744. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  30745. this.clearGroups();
  30746. },
  30747. computeTangents: function () {
  30748. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  30749. },
  30750. computeOffsets: function () {
  30751. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  30752. },
  30753. removeAttribute: function ( name ) {
  30754. console.warn( 'THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().' );
  30755. return this.deleteAttribute( name );
  30756. },
  30757. applyMatrix: function ( matrix ) {
  30758. console.warn( 'THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().' );
  30759. return this.applyMatrix4( matrix );
  30760. }
  30761. } );
  30762. Object.defineProperties( BufferGeometry.prototype, {
  30763. drawcalls: {
  30764. get: function () {
  30765. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  30766. return this.groups;
  30767. }
  30768. },
  30769. offsets: {
  30770. get: function () {
  30771. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  30772. return this.groups;
  30773. }
  30774. }
  30775. } );
  30776. Object.defineProperties( InstancedBufferGeometry.prototype, {
  30777. maxInstancedCount: {
  30778. get: function () {
  30779. console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' );
  30780. return this.instanceCount;
  30781. },
  30782. set: function ( value ) {
  30783. console.warn( 'THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.' );
  30784. this.instanceCount = value;
  30785. }
  30786. }
  30787. } );
  30788. Object.defineProperties( Raycaster.prototype, {
  30789. linePrecision: {
  30790. get: function () {
  30791. console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
  30792. return this.params.Line.threshold;
  30793. },
  30794. set: function ( value ) {
  30795. console.warn( 'THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.' );
  30796. this.params.Line.threshold = value;
  30797. }
  30798. }
  30799. } );
  30800. Object.defineProperties( InterleavedBuffer.prototype, {
  30801. dynamic: {
  30802. get: function () {
  30803. console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
  30804. return this.usage === DynamicDrawUsage;
  30805. },
  30806. set: function ( value ) {
  30807. console.warn( 'THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.' );
  30808. this.setUsage( value );
  30809. }
  30810. }
  30811. } );
  30812. Object.assign( InterleavedBuffer.prototype, {
  30813. setDynamic: function ( value ) {
  30814. console.warn( 'THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  30815. this.setUsage( value === true ? DynamicDrawUsage : StaticDrawUsage );
  30816. return this;
  30817. },
  30818. setArray: function ( /* array */ ) {
  30819. console.error( 'THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers' );
  30820. }
  30821. } );
  30822. //
  30823. Object.assign( ExtrudeBufferGeometry.prototype, {
  30824. getArrays: function () {
  30825. console.error( 'THREE.ExtrudeBufferGeometry: .getArrays() has been removed.' );
  30826. },
  30827. addShapeList: function () {
  30828. console.error( 'THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.' );
  30829. },
  30830. addShape: function () {
  30831. console.error( 'THREE.ExtrudeBufferGeometry: .addShape() has been removed.' );
  30832. }
  30833. } );
  30834. //
  30835. Object.assign( Scene.prototype, {
  30836. dispose: function () {
  30837. console.error( 'THREE.Scene: .dispose() has been removed.' );
  30838. }
  30839. } );
  30840. //
  30841. Object.defineProperties( Uniform.prototype, {
  30842. dynamic: {
  30843. set: function () {
  30844. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  30845. }
  30846. },
  30847. onUpdate: {
  30848. value: function () {
  30849. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  30850. return this;
  30851. }
  30852. }
  30853. } );
  30854. //
  30855. Object.defineProperties( Material.prototype, {
  30856. wrapAround: {
  30857. get: function () {
  30858. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  30859. },
  30860. set: function () {
  30861. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  30862. }
  30863. },
  30864. overdraw: {
  30865. get: function () {
  30866. console.warn( 'THREE.Material: .overdraw has been removed.' );
  30867. },
  30868. set: function () {
  30869. console.warn( 'THREE.Material: .overdraw has been removed.' );
  30870. }
  30871. },
  30872. wrapRGB: {
  30873. get: function () {
  30874. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  30875. return new Color();
  30876. }
  30877. },
  30878. shading: {
  30879. get: function () {
  30880. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  30881. },
  30882. set: function ( value ) {
  30883. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  30884. this.flatShading = ( value === FlatShading );
  30885. }
  30886. },
  30887. stencilMask: {
  30888. get: function () {
  30889. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  30890. return this.stencilFuncMask;
  30891. },
  30892. set: function ( value ) {
  30893. console.warn( 'THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.' );
  30894. this.stencilFuncMask = value;
  30895. }
  30896. }
  30897. } );
  30898. Object.defineProperties( MeshPhongMaterial.prototype, {
  30899. metal: {
  30900. get: function () {
  30901. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  30902. return false;
  30903. },
  30904. set: function () {
  30905. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  30906. }
  30907. }
  30908. } );
  30909. Object.defineProperties( MeshPhysicalMaterial.prototype, {
  30910. transparency: {
  30911. get: function () {
  30912. console.warn( 'THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.' );
  30913. return this.transmission;
  30914. },
  30915. set: function ( value ) {
  30916. console.warn( 'THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.' );
  30917. this.transmission = value;
  30918. }
  30919. }
  30920. } );
  30921. Object.defineProperties( ShaderMaterial.prototype, {
  30922. derivatives: {
  30923. get: function () {
  30924. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  30925. return this.extensions.derivatives;
  30926. },
  30927. set: function ( value ) {
  30928. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  30929. this.extensions.derivatives = value;
  30930. }
  30931. }
  30932. } );
  30933. //
  30934. Object.assign( WebGLRenderer.prototype, {
  30935. clearTarget: function ( renderTarget, color, depth, stencil ) {
  30936. console.warn( 'THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.' );
  30937. this.setRenderTarget( renderTarget );
  30938. this.clear( color, depth, stencil );
  30939. },
  30940. animate: function ( callback ) {
  30941. console.warn( 'THREE.WebGLRenderer: .animate() is now .setAnimationLoop().' );
  30942. this.setAnimationLoop( callback );
  30943. },
  30944. getCurrentRenderTarget: function () {
  30945. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  30946. return this.getRenderTarget();
  30947. },
  30948. getMaxAnisotropy: function () {
  30949. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  30950. return this.capabilities.getMaxAnisotropy();
  30951. },
  30952. getPrecision: function () {
  30953. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  30954. return this.capabilities.precision;
  30955. },
  30956. resetGLState: function () {
  30957. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  30958. return this.state.reset();
  30959. },
  30960. supportsFloatTextures: function () {
  30961. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  30962. return this.extensions.get( 'OES_texture_float' );
  30963. },
  30964. supportsHalfFloatTextures: function () {
  30965. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  30966. return this.extensions.get( 'OES_texture_half_float' );
  30967. },
  30968. supportsStandardDerivatives: function () {
  30969. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  30970. return this.extensions.get( 'OES_standard_derivatives' );
  30971. },
  30972. supportsCompressedTextureS3TC: function () {
  30973. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  30974. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  30975. },
  30976. supportsCompressedTexturePVRTC: function () {
  30977. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  30978. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  30979. },
  30980. supportsBlendMinMax: function () {
  30981. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  30982. return this.extensions.get( 'EXT_blend_minmax' );
  30983. },
  30984. supportsVertexTextures: function () {
  30985. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  30986. return this.capabilities.vertexTextures;
  30987. },
  30988. supportsInstancedArrays: function () {
  30989. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  30990. return this.extensions.get( 'ANGLE_instanced_arrays' );
  30991. },
  30992. enableScissorTest: function ( boolean ) {
  30993. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  30994. this.setScissorTest( boolean );
  30995. },
  30996. initMaterial: function () {
  30997. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  30998. },
  30999. addPrePlugin: function () {
  31000. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  31001. },
  31002. addPostPlugin: function () {
  31003. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  31004. },
  31005. updateShadowMap: function () {
  31006. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  31007. },
  31008. setFaceCulling: function () {
  31009. console.warn( 'THREE.WebGLRenderer: .setFaceCulling() has been removed.' );
  31010. },
  31011. allocTextureUnit: function () {
  31012. console.warn( 'THREE.WebGLRenderer: .allocTextureUnit() has been removed.' );
  31013. },
  31014. setTexture: function () {
  31015. console.warn( 'THREE.WebGLRenderer: .setTexture() has been removed.' );
  31016. },
  31017. setTexture2D: function () {
  31018. console.warn( 'THREE.WebGLRenderer: .setTexture2D() has been removed.' );
  31019. },
  31020. setTextureCube: function () {
  31021. console.warn( 'THREE.WebGLRenderer: .setTextureCube() has been removed.' );
  31022. },
  31023. getActiveMipMapLevel: function () {
  31024. console.warn( 'THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().' );
  31025. return this.getActiveMipmapLevel();
  31026. }
  31027. } );
  31028. Object.defineProperties( WebGLRenderer.prototype, {
  31029. shadowMapEnabled: {
  31030. get: function () {
  31031. return this.shadowMap.enabled;
  31032. },
  31033. set: function ( value ) {
  31034. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  31035. this.shadowMap.enabled = value;
  31036. }
  31037. },
  31038. shadowMapType: {
  31039. get: function () {
  31040. return this.shadowMap.type;
  31041. },
  31042. set: function ( value ) {
  31043. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  31044. this.shadowMap.type = value;
  31045. }
  31046. },
  31047. shadowMapCullFace: {
  31048. get: function () {
  31049. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  31050. return undefined;
  31051. },
  31052. set: function ( /* value */ ) {
  31053. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.' );
  31054. }
  31055. },
  31056. context: {
  31057. get: function () {
  31058. console.warn( 'THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.' );
  31059. return this.getContext();
  31060. }
  31061. },
  31062. vr: {
  31063. get: function () {
  31064. console.warn( 'THREE.WebGLRenderer: .vr has been renamed to .xr' );
  31065. return this.xr;
  31066. }
  31067. },
  31068. gammaInput: {
  31069. get: function () {
  31070. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  31071. return false;
  31072. },
  31073. set: function () {
  31074. console.warn( 'THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.' );
  31075. }
  31076. },
  31077. gammaOutput: {
  31078. get: function () {
  31079. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  31080. return false;
  31081. },
  31082. set: function ( value ) {
  31083. console.warn( 'THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.' );
  31084. this.outputEncoding = ( value === true ) ? sRGBEncoding : LinearEncoding;
  31085. }
  31086. },
  31087. toneMappingWhitePoint: {
  31088. get: function () {
  31089. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  31090. return 1.0;
  31091. },
  31092. set: function () {
  31093. console.warn( 'THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.' );
  31094. }
  31095. },
  31096. } );
  31097. Object.defineProperties( WebGLShadowMap.prototype, {
  31098. cullFace: {
  31099. get: function () {
  31100. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  31101. return undefined;
  31102. },
  31103. set: function ( /* cullFace */ ) {
  31104. console.warn( 'THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.' );
  31105. }
  31106. },
  31107. renderReverseSided: {
  31108. get: function () {
  31109. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  31110. return undefined;
  31111. },
  31112. set: function () {
  31113. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.' );
  31114. }
  31115. },
  31116. renderSingleSided: {
  31117. get: function () {
  31118. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  31119. return undefined;
  31120. },
  31121. set: function () {
  31122. console.warn( 'THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.' );
  31123. }
  31124. }
  31125. } );
  31126. function WebGLRenderTargetCube( width, height, options ) {
  31127. console.warn( 'THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).' );
  31128. return new WebGLCubeRenderTarget( width, options );
  31129. }
  31130. //
  31131. Object.defineProperties( WebGLRenderTarget.prototype, {
  31132. wrapS: {
  31133. get: function () {
  31134. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  31135. return this.texture.wrapS;
  31136. },
  31137. set: function ( value ) {
  31138. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  31139. this.texture.wrapS = value;
  31140. }
  31141. },
  31142. wrapT: {
  31143. get: function () {
  31144. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  31145. return this.texture.wrapT;
  31146. },
  31147. set: function ( value ) {
  31148. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  31149. this.texture.wrapT = value;
  31150. }
  31151. },
  31152. magFilter: {
  31153. get: function () {
  31154. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  31155. return this.texture.magFilter;
  31156. },
  31157. set: function ( value ) {
  31158. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  31159. this.texture.magFilter = value;
  31160. }
  31161. },
  31162. minFilter: {
  31163. get: function () {
  31164. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  31165. return this.texture.minFilter;
  31166. },
  31167. set: function ( value ) {
  31168. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  31169. this.texture.minFilter = value;
  31170. }
  31171. },
  31172. anisotropy: {
  31173. get: function () {
  31174. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  31175. return this.texture.anisotropy;
  31176. },
  31177. set: function ( value ) {
  31178. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  31179. this.texture.anisotropy = value;
  31180. }
  31181. },
  31182. offset: {
  31183. get: function () {
  31184. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  31185. return this.texture.offset;
  31186. },
  31187. set: function ( value ) {
  31188. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  31189. this.texture.offset = value;
  31190. }
  31191. },
  31192. repeat: {
  31193. get: function () {
  31194. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  31195. return this.texture.repeat;
  31196. },
  31197. set: function ( value ) {
  31198. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  31199. this.texture.repeat = value;
  31200. }
  31201. },
  31202. format: {
  31203. get: function () {
  31204. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  31205. return this.texture.format;
  31206. },
  31207. set: function ( value ) {
  31208. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  31209. this.texture.format = value;
  31210. }
  31211. },
  31212. type: {
  31213. get: function () {
  31214. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  31215. return this.texture.type;
  31216. },
  31217. set: function ( value ) {
  31218. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  31219. this.texture.type = value;
  31220. }
  31221. },
  31222. generateMipmaps: {
  31223. get: function () {
  31224. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  31225. return this.texture.generateMipmaps;
  31226. },
  31227. set: function ( value ) {
  31228. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  31229. this.texture.generateMipmaps = value;
  31230. }
  31231. }
  31232. } );
  31233. //
  31234. Object.defineProperties( Audio.prototype, {
  31235. load: {
  31236. value: function ( file ) {
  31237. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  31238. const scope = this;
  31239. const audioLoader = new AudioLoader();
  31240. audioLoader.load( file, function ( buffer ) {
  31241. scope.setBuffer( buffer );
  31242. } );
  31243. return this;
  31244. }
  31245. },
  31246. startTime: {
  31247. set: function () {
  31248. console.warn( 'THREE.Audio: .startTime is now .play( delay ).' );
  31249. }
  31250. }
  31251. } );
  31252. AudioAnalyser.prototype.getData = function () {
  31253. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  31254. return this.getFrequencyData();
  31255. };
  31256. //
  31257. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  31258. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  31259. return this.update( renderer, scene );
  31260. };
  31261. CubeCamera.prototype.clear = function ( renderer, color, depth, stencil ) {
  31262. console.warn( 'THREE.CubeCamera: .clear() is now .renderTarget.clear().' );
  31263. return this.renderTarget.clear( renderer, color, depth, stencil );
  31264. };
  31265. //
  31266. const GeometryUtils = {
  31267. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  31268. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  31269. let matrix;
  31270. if ( geometry2.isMesh ) {
  31271. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  31272. matrix = geometry2.matrix;
  31273. geometry2 = geometry2.geometry;
  31274. }
  31275. geometry1.merge( geometry2, matrix, materialIndexOffset );
  31276. },
  31277. center: function ( geometry ) {
  31278. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  31279. return geometry.center();
  31280. }
  31281. };
  31282. ImageUtils.crossOrigin = undefined;
  31283. ImageUtils.loadTexture = function ( url, mapping, onLoad, onError ) {
  31284. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  31285. const loader = new TextureLoader();
  31286. loader.setCrossOrigin( this.crossOrigin );
  31287. const texture = loader.load( url, onLoad, undefined, onError );
  31288. if ( mapping ) texture.mapping = mapping;
  31289. return texture;
  31290. };
  31291. ImageUtils.loadTextureCube = function ( urls, mapping, onLoad, onError ) {
  31292. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  31293. const loader = new CubeTextureLoader();
  31294. loader.setCrossOrigin( this.crossOrigin );
  31295. const texture = loader.load( urls, onLoad, undefined, onError );
  31296. if ( mapping ) texture.mapping = mapping;
  31297. return texture;
  31298. };
  31299. ImageUtils.loadCompressedTexture = function () {
  31300. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  31301. };
  31302. ImageUtils.loadCompressedTextureCube = function () {
  31303. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  31304. };
  31305. //
  31306. function CanvasRenderer() {
  31307. console.error( 'THREE.CanvasRenderer has been removed' );
  31308. }
  31309. //
  31310. function JSONLoader() {
  31311. console.error( 'THREE.JSONLoader has been removed.' );
  31312. }
  31313. //
  31314. const SceneUtils = {
  31315. createMultiMaterialObject: function ( /* geometry, materials */ ) {
  31316. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  31317. },
  31318. detach: function ( /* child, parent, scene */ ) {
  31319. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  31320. },
  31321. attach: function ( /* child, scene, parent */ ) {
  31322. console.error( 'THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js' );
  31323. }
  31324. };
  31325. //
  31326. function LensFlare() {
  31327. console.error( 'THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js' );
  31328. }
  31329. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  31330. /* eslint-disable no-undef */
  31331. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  31332. revision: REVISION,
  31333. } } ) );
  31334. /* eslint-enable no-undef */
  31335. }
  31336. var THREE$1 = /*#__PURE__*/Object.freeze({
  31337. __proto__: null,
  31338. ACESFilmicToneMapping: ACESFilmicToneMapping,
  31339. AddEquation: AddEquation,
  31340. AddOperation: AddOperation,
  31341. AdditiveAnimationBlendMode: AdditiveAnimationBlendMode,
  31342. AdditiveBlending: AdditiveBlending,
  31343. AlphaFormat: AlphaFormat,
  31344. AlwaysDepth: AlwaysDepth,
  31345. AlwaysStencilFunc: AlwaysStencilFunc,
  31346. AmbientLight: AmbientLight,
  31347. AmbientLightProbe: AmbientLightProbe,
  31348. AnimationClip: AnimationClip,
  31349. AnimationLoader: AnimationLoader,
  31350. AnimationMixer: AnimationMixer,
  31351. AnimationObjectGroup: AnimationObjectGroup,
  31352. AnimationUtils: AnimationUtils,
  31353. ArcCurve: ArcCurve,
  31354. ArrayCamera: ArrayCamera,
  31355. ArrowHelper: ArrowHelper,
  31356. Audio: Audio,
  31357. AudioAnalyser: AudioAnalyser,
  31358. AudioContext: AudioContext,
  31359. AudioListener: AudioListener,
  31360. AudioLoader: AudioLoader,
  31361. AxesHelper: AxesHelper,
  31362. AxisHelper: AxisHelper,
  31363. BackSide: BackSide,
  31364. BasicDepthPacking: BasicDepthPacking,
  31365. BasicShadowMap: BasicShadowMap,
  31366. BinaryTextureLoader: BinaryTextureLoader,
  31367. Bone: Bone,
  31368. BooleanKeyframeTrack: BooleanKeyframeTrack,
  31369. BoundingBoxHelper: BoundingBoxHelper,
  31370. Box2: Box2,
  31371. Box3: Box3,
  31372. Box3Helper: Box3Helper,
  31373. BoxBufferGeometry: BoxBufferGeometry,
  31374. BoxGeometry: BoxGeometry,
  31375. BoxHelper: BoxHelper,
  31376. BufferAttribute: BufferAttribute,
  31377. BufferGeometry: BufferGeometry,
  31378. BufferGeometryLoader: BufferGeometryLoader,
  31379. ByteType: ByteType,
  31380. Cache: Cache,
  31381. Camera: Camera,
  31382. CameraHelper: CameraHelper,
  31383. CanvasRenderer: CanvasRenderer,
  31384. CanvasTexture: CanvasTexture,
  31385. CatmullRomCurve3: CatmullRomCurve3,
  31386. CineonToneMapping: CineonToneMapping,
  31387. CircleBufferGeometry: CircleBufferGeometry,
  31388. CircleGeometry: CircleGeometry,
  31389. ClampToEdgeWrapping: ClampToEdgeWrapping,
  31390. Clock: Clock,
  31391. ClosedSplineCurve3: ClosedSplineCurve3,
  31392. Color: Color,
  31393. ColorKeyframeTrack: ColorKeyframeTrack,
  31394. CompressedTexture: CompressedTexture,
  31395. CompressedTextureLoader: CompressedTextureLoader,
  31396. ConeBufferGeometry: ConeBufferGeometry,
  31397. ConeGeometry: ConeGeometry,
  31398. CubeCamera: CubeCamera,
  31399. CubeGeometry: BoxGeometry,
  31400. CubeReflectionMapping: CubeReflectionMapping,
  31401. CubeRefractionMapping: CubeRefractionMapping,
  31402. CubeTexture: CubeTexture,
  31403. CubeTextureLoader: CubeTextureLoader,
  31404. CubeUVReflectionMapping: CubeUVReflectionMapping,
  31405. CubeUVRefractionMapping: CubeUVRefractionMapping,
  31406. CubicBezierCurve: CubicBezierCurve,
  31407. CubicBezierCurve3: CubicBezierCurve3,
  31408. CubicInterpolant: CubicInterpolant,
  31409. CullFaceBack: CullFaceBack,
  31410. CullFaceFront: CullFaceFront,
  31411. CullFaceFrontBack: CullFaceFrontBack,
  31412. CullFaceNone: CullFaceNone,
  31413. Curve: Curve,
  31414. CurvePath: CurvePath,
  31415. CustomBlending: CustomBlending,
  31416. CustomToneMapping: CustomToneMapping,
  31417. CylinderBufferGeometry: CylinderBufferGeometry,
  31418. CylinderGeometry: CylinderGeometry,
  31419. Cylindrical: Cylindrical,
  31420. DataTexture: DataTexture,
  31421. DataTexture2DArray: DataTexture2DArray,
  31422. DataTexture3D: DataTexture3D,
  31423. DataTextureLoader: DataTextureLoader,
  31424. DataUtils: DataUtils,
  31425. DecrementStencilOp: DecrementStencilOp,
  31426. DecrementWrapStencilOp: DecrementWrapStencilOp,
  31427. DefaultLoadingManager: DefaultLoadingManager,
  31428. DepthFormat: DepthFormat,
  31429. DepthStencilFormat: DepthStencilFormat,
  31430. DepthTexture: DepthTexture,
  31431. DirectionalLight: DirectionalLight,
  31432. DirectionalLightHelper: DirectionalLightHelper,
  31433. DiscreteInterpolant: DiscreteInterpolant,
  31434. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  31435. DodecahedronGeometry: DodecahedronGeometry,
  31436. DoubleSide: DoubleSide,
  31437. DstAlphaFactor: DstAlphaFactor,
  31438. DstColorFactor: DstColorFactor,
  31439. DynamicBufferAttribute: DynamicBufferAttribute,
  31440. DynamicCopyUsage: DynamicCopyUsage,
  31441. DynamicDrawUsage: DynamicDrawUsage,
  31442. DynamicReadUsage: DynamicReadUsage,
  31443. EdgesGeometry: EdgesGeometry,
  31444. EdgesHelper: EdgesHelper,
  31445. EllipseCurve: EllipseCurve,
  31446. EqualDepth: EqualDepth,
  31447. EqualStencilFunc: EqualStencilFunc,
  31448. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  31449. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  31450. Euler: Euler,
  31451. EventDispatcher: EventDispatcher,
  31452. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  31453. ExtrudeGeometry: ExtrudeGeometry,
  31454. Face3: Face3,
  31455. Face4: Face4,
  31456. FaceColors: FaceColors,
  31457. FileLoader: FileLoader,
  31458. FlatShading: FlatShading,
  31459. Float16BufferAttribute: Float16BufferAttribute,
  31460. Float32Attribute: Float32Attribute,
  31461. Float32BufferAttribute: Float32BufferAttribute,
  31462. Float64Attribute: Float64Attribute,
  31463. Float64BufferAttribute: Float64BufferAttribute,
  31464. FloatType: FloatType,
  31465. Fog: Fog,
  31466. FogExp2: FogExp2,
  31467. Font: Font,
  31468. FontLoader: FontLoader,
  31469. FrontSide: FrontSide,
  31470. Frustum: Frustum,
  31471. GLBufferAttribute: GLBufferAttribute,
  31472. GLSL1: GLSL1,
  31473. GLSL3: GLSL3,
  31474. GammaEncoding: GammaEncoding,
  31475. Geometry: Geometry,
  31476. GeometryUtils: GeometryUtils,
  31477. GreaterDepth: GreaterDepth,
  31478. GreaterEqualDepth: GreaterEqualDepth,
  31479. GreaterEqualStencilFunc: GreaterEqualStencilFunc,
  31480. GreaterStencilFunc: GreaterStencilFunc,
  31481. GridHelper: GridHelper,
  31482. Group: Group,
  31483. HalfFloatType: HalfFloatType,
  31484. HemisphereLight: HemisphereLight,
  31485. HemisphereLightHelper: HemisphereLightHelper,
  31486. HemisphereLightProbe: HemisphereLightProbe,
  31487. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  31488. IcosahedronGeometry: IcosahedronGeometry,
  31489. ImageBitmapLoader: ImageBitmapLoader,
  31490. ImageLoader: ImageLoader,
  31491. ImageUtils: ImageUtils,
  31492. ImmediateRenderObject: ImmediateRenderObject,
  31493. IncrementStencilOp: IncrementStencilOp,
  31494. IncrementWrapStencilOp: IncrementWrapStencilOp,
  31495. InstancedBufferAttribute: InstancedBufferAttribute,
  31496. InstancedBufferGeometry: InstancedBufferGeometry,
  31497. InstancedInterleavedBuffer: InstancedInterleavedBuffer,
  31498. InstancedMesh: InstancedMesh,
  31499. Int16Attribute: Int16Attribute,
  31500. Int16BufferAttribute: Int16BufferAttribute,
  31501. Int32Attribute: Int32Attribute,
  31502. Int32BufferAttribute: Int32BufferAttribute,
  31503. Int8Attribute: Int8Attribute,
  31504. Int8BufferAttribute: Int8BufferAttribute,
  31505. IntType: IntType,
  31506. InterleavedBuffer: InterleavedBuffer,
  31507. InterleavedBufferAttribute: InterleavedBufferAttribute,
  31508. Interpolant: Interpolant,
  31509. InterpolateDiscrete: InterpolateDiscrete,
  31510. InterpolateLinear: InterpolateLinear,
  31511. InterpolateSmooth: InterpolateSmooth,
  31512. InvertStencilOp: InvertStencilOp,
  31513. JSONLoader: JSONLoader,
  31514. KeepStencilOp: KeepStencilOp,
  31515. KeyframeTrack: KeyframeTrack,
  31516. LOD: LOD,
  31517. LatheBufferGeometry: LatheBufferGeometry,
  31518. LatheGeometry: LatheGeometry,
  31519. Layers: Layers,
  31520. LensFlare: LensFlare,
  31521. LessDepth: LessDepth,
  31522. LessEqualDepth: LessEqualDepth,
  31523. LessEqualStencilFunc: LessEqualStencilFunc,
  31524. LessStencilFunc: LessStencilFunc,
  31525. Light: Light,
  31526. LightProbe: LightProbe,
  31527. Line: Line,
  31528. Line3: Line3,
  31529. LineBasicMaterial: LineBasicMaterial,
  31530. LineCurve: LineCurve,
  31531. LineCurve3: LineCurve3,
  31532. LineDashedMaterial: LineDashedMaterial,
  31533. LineLoop: LineLoop,
  31534. LinePieces: LinePieces,
  31535. LineSegments: LineSegments,
  31536. LineStrip: LineStrip,
  31537. LinearEncoding: LinearEncoding,
  31538. LinearFilter: LinearFilter,
  31539. LinearInterpolant: LinearInterpolant,
  31540. LinearMipMapLinearFilter: LinearMipMapLinearFilter,
  31541. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  31542. LinearMipmapLinearFilter: LinearMipmapLinearFilter,
  31543. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  31544. LinearToneMapping: LinearToneMapping,
  31545. Loader: Loader,
  31546. LoaderUtils: LoaderUtils,
  31547. LoadingManager: LoadingManager,
  31548. LogLuvEncoding: LogLuvEncoding,
  31549. LoopOnce: LoopOnce,
  31550. LoopPingPong: LoopPingPong,
  31551. LoopRepeat: LoopRepeat,
  31552. LuminanceAlphaFormat: LuminanceAlphaFormat,
  31553. LuminanceFormat: LuminanceFormat,
  31554. MOUSE: MOUSE,
  31555. Material: Material,
  31556. MaterialLoader: MaterialLoader,
  31557. Math: MathUtils,
  31558. MathUtils: MathUtils,
  31559. Matrix3: Matrix3,
  31560. Matrix4: Matrix4,
  31561. MaxEquation: MaxEquation,
  31562. Mesh: Mesh,
  31563. MeshBasicMaterial: MeshBasicMaterial,
  31564. MeshDepthMaterial: MeshDepthMaterial,
  31565. MeshDistanceMaterial: MeshDistanceMaterial,
  31566. MeshFaceMaterial: MeshFaceMaterial,
  31567. MeshLambertMaterial: MeshLambertMaterial,
  31568. MeshMatcapMaterial: MeshMatcapMaterial,
  31569. MeshNormalMaterial: MeshNormalMaterial,
  31570. MeshPhongMaterial: MeshPhongMaterial,
  31571. MeshPhysicalMaterial: MeshPhysicalMaterial,
  31572. MeshStandardMaterial: MeshStandardMaterial,
  31573. MeshToonMaterial: MeshToonMaterial,
  31574. MinEquation: MinEquation,
  31575. MirroredRepeatWrapping: MirroredRepeatWrapping,
  31576. MixOperation: MixOperation,
  31577. MultiMaterial: MultiMaterial,
  31578. MultiplyBlending: MultiplyBlending,
  31579. MultiplyOperation: MultiplyOperation,
  31580. NearestFilter: NearestFilter,
  31581. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  31582. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  31583. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  31584. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  31585. NeverDepth: NeverDepth,
  31586. NeverStencilFunc: NeverStencilFunc,
  31587. NoBlending: NoBlending,
  31588. NoColors: NoColors,
  31589. NoToneMapping: NoToneMapping,
  31590. NormalAnimationBlendMode: NormalAnimationBlendMode,
  31591. NormalBlending: NormalBlending,
  31592. NotEqualDepth: NotEqualDepth,
  31593. NotEqualStencilFunc: NotEqualStencilFunc,
  31594. NumberKeyframeTrack: NumberKeyframeTrack,
  31595. Object3D: Object3D,
  31596. ObjectLoader: ObjectLoader,
  31597. ObjectSpaceNormalMap: ObjectSpaceNormalMap,
  31598. OctahedronBufferGeometry: OctahedronBufferGeometry,
  31599. OctahedronGeometry: OctahedronGeometry,
  31600. OneFactor: OneFactor,
  31601. OneMinusDstAlphaFactor: OneMinusDstAlphaFactor,
  31602. OneMinusDstColorFactor: OneMinusDstColorFactor,
  31603. OneMinusSrcAlphaFactor: OneMinusSrcAlphaFactor,
  31604. OneMinusSrcColorFactor: OneMinusSrcColorFactor,
  31605. OrthographicCamera: OrthographicCamera,
  31606. PCFShadowMap: PCFShadowMap,
  31607. PCFSoftShadowMap: PCFSoftShadowMap,
  31608. PMREMGenerator: PMREMGenerator,
  31609. ParametricBufferGeometry: ParametricBufferGeometry,
  31610. ParametricGeometry: ParametricGeometry,
  31611. Particle: Particle,
  31612. ParticleBasicMaterial: ParticleBasicMaterial,
  31613. ParticleSystem: ParticleSystem,
  31614. ParticleSystemMaterial: ParticleSystemMaterial,
  31615. Path: Path,
  31616. PerspectiveCamera: PerspectiveCamera,
  31617. Plane: Plane,
  31618. PlaneBufferGeometry: PlaneBufferGeometry,
  31619. PlaneGeometry: PlaneGeometry,
  31620. PlaneHelper: PlaneHelper,
  31621. PointCloud: PointCloud,
  31622. PointCloudMaterial: PointCloudMaterial,
  31623. PointLight: PointLight,
  31624. PointLightHelper: PointLightHelper,
  31625. Points: Points,
  31626. PointsMaterial: PointsMaterial,
  31627. PolarGridHelper: PolarGridHelper,
  31628. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  31629. PolyhedronGeometry: PolyhedronGeometry,
  31630. PositionalAudio: PositionalAudio,
  31631. PropertyBinding: PropertyBinding,
  31632. PropertyMixer: PropertyMixer,
  31633. QuadraticBezierCurve: QuadraticBezierCurve,
  31634. QuadraticBezierCurve3: QuadraticBezierCurve3,
  31635. Quaternion: Quaternion,
  31636. QuaternionKeyframeTrack: QuaternionKeyframeTrack,
  31637. QuaternionLinearInterpolant: QuaternionLinearInterpolant,
  31638. REVISION: REVISION,
  31639. RGBADepthPacking: RGBADepthPacking,
  31640. RGBAFormat: RGBAFormat,
  31641. RGBAIntegerFormat: RGBAIntegerFormat,
  31642. RGBA_ASTC_10x10_Format: RGBA_ASTC_10x10_Format,
  31643. RGBA_ASTC_10x5_Format: RGBA_ASTC_10x5_Format,
  31644. RGBA_ASTC_10x6_Format: RGBA_ASTC_10x6_Format,
  31645. RGBA_ASTC_10x8_Format: RGBA_ASTC_10x8_Format,
  31646. RGBA_ASTC_12x10_Format: RGBA_ASTC_12x10_Format,
  31647. RGBA_ASTC_12x12_Format: RGBA_ASTC_12x12_Format,
  31648. RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
  31649. RGBA_ASTC_5x4_Format: RGBA_ASTC_5x4_Format,
  31650. RGBA_ASTC_5x5_Format: RGBA_ASTC_5x5_Format,
  31651. RGBA_ASTC_6x5_Format: RGBA_ASTC_6x5_Format,
  31652. RGBA_ASTC_6x6_Format: RGBA_ASTC_6x6_Format,
  31653. RGBA_ASTC_8x5_Format: RGBA_ASTC_8x5_Format,
  31654. RGBA_ASTC_8x6_Format: RGBA_ASTC_8x6_Format,
  31655. RGBA_ASTC_8x8_Format: RGBA_ASTC_8x8_Format,
  31656. RGBA_BPTC_Format: RGBA_BPTC_Format,
  31657. RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
  31658. RGBA_PVRTC_2BPPV1_Format: RGBA_PVRTC_2BPPV1_Format,
  31659. RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
  31660. RGBA_S3TC_DXT1_Format: RGBA_S3TC_DXT1_Format$1,
  31661. RGBA_S3TC_DXT3_Format: RGBA_S3TC_DXT3_Format,
  31662. RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format$1,
  31663. RGBDEncoding: RGBDEncoding,
  31664. RGBEEncoding: RGBEEncoding,
  31665. RGBEFormat: RGBEFormat,
  31666. RGBFormat: RGBFormat,
  31667. RGBIntegerFormat: RGBIntegerFormat,
  31668. RGBM16Encoding: RGBM16Encoding,
  31669. RGBM7Encoding: RGBM7Encoding,
  31670. RGB_ETC1_Format: RGB_ETC1_Format,
  31671. RGB_ETC2_Format: RGB_ETC2_Format,
  31672. RGB_PVRTC_2BPPV1_Format: RGB_PVRTC_2BPPV1_Format,
  31673. RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
  31674. RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format,
  31675. RGFormat: RGFormat,
  31676. RGIntegerFormat: RGIntegerFormat,
  31677. RawShaderMaterial: RawShaderMaterial,
  31678. Ray: Ray,
  31679. Raycaster: Raycaster,
  31680. RectAreaLight: RectAreaLight,
  31681. RedFormat: RedFormat,
  31682. RedIntegerFormat: RedIntegerFormat,
  31683. ReinhardToneMapping: ReinhardToneMapping,
  31684. RepeatWrapping: RepeatWrapping,
  31685. ReplaceStencilOp: ReplaceStencilOp,
  31686. ReverseSubtractEquation: ReverseSubtractEquation,
  31687. RingBufferGeometry: RingBufferGeometry,
  31688. RingGeometry: RingGeometry,
  31689. SRGB8_ALPHA8_ASTC_10x10_Format: SRGB8_ALPHA8_ASTC_10x10_Format,
  31690. SRGB8_ALPHA8_ASTC_10x5_Format: SRGB8_ALPHA8_ASTC_10x5_Format,
  31691. SRGB8_ALPHA8_ASTC_10x6_Format: SRGB8_ALPHA8_ASTC_10x6_Format,
  31692. SRGB8_ALPHA8_ASTC_10x8_Format: SRGB8_ALPHA8_ASTC_10x8_Format,
  31693. SRGB8_ALPHA8_ASTC_12x10_Format: SRGB8_ALPHA8_ASTC_12x10_Format,
  31694. SRGB8_ALPHA8_ASTC_12x12_Format: SRGB8_ALPHA8_ASTC_12x12_Format,
  31695. SRGB8_ALPHA8_ASTC_4x4_Format: SRGB8_ALPHA8_ASTC_4x4_Format,
  31696. SRGB8_ALPHA8_ASTC_5x4_Format: SRGB8_ALPHA8_ASTC_5x4_Format,
  31697. SRGB8_ALPHA8_ASTC_5x5_Format: SRGB8_ALPHA8_ASTC_5x5_Format,
  31698. SRGB8_ALPHA8_ASTC_6x5_Format: SRGB8_ALPHA8_ASTC_6x5_Format,
  31699. SRGB8_ALPHA8_ASTC_6x6_Format: SRGB8_ALPHA8_ASTC_6x6_Format,
  31700. SRGB8_ALPHA8_ASTC_8x5_Format: SRGB8_ALPHA8_ASTC_8x5_Format,
  31701. SRGB8_ALPHA8_ASTC_8x6_Format: SRGB8_ALPHA8_ASTC_8x6_Format,
  31702. SRGB8_ALPHA8_ASTC_8x8_Format: SRGB8_ALPHA8_ASTC_8x8_Format,
  31703. Scene: Scene,
  31704. SceneUtils: SceneUtils,
  31705. ShaderChunk: ShaderChunk,
  31706. ShaderLib: ShaderLib,
  31707. ShaderMaterial: ShaderMaterial,
  31708. ShadowMaterial: ShadowMaterial,
  31709. Shape: Shape,
  31710. ShapeBufferGeometry: ShapeBufferGeometry,
  31711. ShapeGeometry: ShapeGeometry,
  31712. ShapePath: ShapePath,
  31713. ShapeUtils: ShapeUtils,
  31714. ShortType: ShortType,
  31715. Skeleton: Skeleton,
  31716. SkeletonHelper: SkeletonHelper,
  31717. SkinnedMesh: SkinnedMesh,
  31718. SmoothShading: SmoothShading,
  31719. Sphere: Sphere,
  31720. SphereBufferGeometry: SphereBufferGeometry,
  31721. SphereGeometry: SphereGeometry,
  31722. Spherical: Spherical,
  31723. SphericalHarmonics3: SphericalHarmonics3,
  31724. Spline: Spline,
  31725. SplineCurve: SplineCurve,
  31726. SplineCurve3: SplineCurve3,
  31727. SpotLight: SpotLight,
  31728. SpotLightHelper: SpotLightHelper,
  31729. Sprite: Sprite,
  31730. SpriteMaterial: SpriteMaterial,
  31731. SrcAlphaFactor: SrcAlphaFactor,
  31732. SrcAlphaSaturateFactor: SrcAlphaSaturateFactor,
  31733. SrcColorFactor: SrcColorFactor,
  31734. StaticCopyUsage: StaticCopyUsage,
  31735. StaticDrawUsage: StaticDrawUsage,
  31736. StaticReadUsage: StaticReadUsage,
  31737. StereoCamera: StereoCamera,
  31738. StreamCopyUsage: StreamCopyUsage,
  31739. StreamDrawUsage: StreamDrawUsage,
  31740. StreamReadUsage: StreamReadUsage,
  31741. StringKeyframeTrack: StringKeyframeTrack,
  31742. SubtractEquation: SubtractEquation,
  31743. SubtractiveBlending: SubtractiveBlending,
  31744. TOUCH: TOUCH,
  31745. TangentSpaceNormalMap: TangentSpaceNormalMap,
  31746. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  31747. TetrahedronGeometry: TetrahedronGeometry,
  31748. TextBufferGeometry: TextBufferGeometry,
  31749. TextGeometry: TextGeometry,
  31750. Texture: Texture,
  31751. TextureLoader: TextureLoader,
  31752. TorusBufferGeometry: TorusBufferGeometry,
  31753. TorusGeometry: TorusGeometry,
  31754. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  31755. TorusKnotGeometry: TorusKnotGeometry,
  31756. Triangle: Triangle,
  31757. TriangleFanDrawMode: TriangleFanDrawMode,
  31758. TriangleStripDrawMode: TriangleStripDrawMode,
  31759. TrianglesDrawMode: TrianglesDrawMode,
  31760. TubeBufferGeometry: TubeBufferGeometry,
  31761. TubeGeometry: TubeGeometry,
  31762. UVMapping: UVMapping,
  31763. Uint16Attribute: Uint16Attribute,
  31764. Uint16BufferAttribute: Uint16BufferAttribute,
  31765. Uint32Attribute: Uint32Attribute,
  31766. Uint32BufferAttribute: Uint32BufferAttribute,
  31767. Uint8Attribute: Uint8Attribute,
  31768. Uint8BufferAttribute: Uint8BufferAttribute,
  31769. Uint8ClampedAttribute: Uint8ClampedAttribute,
  31770. Uint8ClampedBufferAttribute: Uint8ClampedBufferAttribute,
  31771. Uniform: Uniform,
  31772. UniformsLib: UniformsLib,
  31773. UniformsUtils: UniformsUtils,
  31774. UnsignedByteType: UnsignedByteType,
  31775. UnsignedInt248Type: UnsignedInt248Type$1,
  31776. UnsignedIntType: UnsignedIntType,
  31777. UnsignedShort4444Type: UnsignedShort4444Type,
  31778. UnsignedShort5551Type: UnsignedShort5551Type,
  31779. UnsignedShort565Type: UnsignedShort565Type,
  31780. UnsignedShortType: UnsignedShortType,
  31781. VSMShadowMap: VSMShadowMap,
  31782. Vector2: Vector2$1,
  31783. Vector3: Vector3,
  31784. Vector4: Vector4,
  31785. VectorKeyframeTrack: VectorKeyframeTrack,
  31786. Vertex: Vertex,
  31787. VertexColors: VertexColors,
  31788. VideoTexture: VideoTexture,
  31789. WebGL1Renderer: WebGL1Renderer,
  31790. WebGLCubeRenderTarget: WebGLCubeRenderTarget,
  31791. WebGLMultisampleRenderTarget: WebGLMultisampleRenderTarget,
  31792. WebGLRenderTarget: WebGLRenderTarget,
  31793. WebGLRenderTargetCube: WebGLRenderTargetCube,
  31794. WebGLRenderer: WebGLRenderer,
  31795. WebGLUtils: WebGLUtils,
  31796. WireframeGeometry: WireframeGeometry,
  31797. WireframeHelper: WireframeHelper,
  31798. WrapAroundEnding: WrapAroundEnding,
  31799. XHRLoader: XHRLoader,
  31800. ZeroCurvatureEnding: ZeroCurvatureEnding,
  31801. ZeroFactor: ZeroFactor,
  31802. ZeroSlopeEnding: ZeroSlopeEnding,
  31803. ZeroStencilOp: ZeroStencilOp,
  31804. sRGBEncoding: sRGBEncoding
  31805. });
  31806. var points = [];
  31807. var lines = [];
  31808. var rings = [];
  31809. var precision = 0.1; //容错精度 //正常是0.01 但是在编辑时容易出现交错的线看不出来,导致需要getSliceLines 然后多出新增点
  31810. var getPoint = function(o, type){
  31811. var point;
  31812. if(typeof o == "string" || typeof o == "number")point = points.find(p=> p.ids.includes(o));
  31813. else {
  31814. point = points.find(p=> math.closeTo(p.x , o.x, precision) && math.closeTo(p.y , o.y, precision) );
  31815. if(!point) point = new Point(o.x, o.y,{record:true, id:o.id}, type);
  31816. else {
  31817. //console.log('addPoint', point, o)
  31818. point.addPoint(o.id);
  31819. }
  31820. }
  31821. if(!point){
  31822. console.log("no point!");
  31823. }
  31824. return point
  31825. };
  31826. var getLine = function(id){
  31827. return lines.find(line=> line.ids.includes(id));
  31828. };
  31829. var getAngleInfo = function(points){
  31830. var info = {};
  31831. info.angle = points[1].clone().sub(points[0]).angle();
  31832. if(math.closeTo(info.angle, Math.PI*2)){ //如360-0.01
  31833. info.angle -= Math.PI*2; //有可能得到负数-0.001
  31834. }else if(info.angle > Math.PI || math.closeTo(info.angle, Math.PI)){//如180+-0.01
  31835. info.angle -= Math.PI;
  31836. info.reverse = true;
  31837. }
  31838. return info //结果大约是 0 - 3.14
  31839. };
  31840. class Point extends Vector2$1{
  31841. constructor(x, y, o={}){
  31842. super(x, y);
  31843. if(o.record){
  31844. this.id = o.id;
  31845. if(this.id == void 0) this.id = "add_"+points.length;
  31846. this.ids = [this.id] ;//存储拥有该坐标的点原始数据的id
  31847. points.push(this);
  31848. }
  31849. this.type = o.type || "";
  31850. this.lines = [];
  31851. }
  31852. addPoint(id){
  31853. this.ids.push(id);
  31854. }
  31855. searchLineByFactor(dir, type, comeLine){
  31856. var lines = this.lines.filter(line=>line.searchTime<2);
  31857. if(lines.length==0)return;
  31858. else if(lines.length==1)return lines[0];
  31859. else lines = lines.filter(line=>line!=comeLine);
  31860. if(lines.length==1)return lines[0];
  31861. var result;
  31862. lines.forEach(line=>{
  31863. var vec = line.getVector();
  31864. if(line.points[1] == this) vec.negate();
  31865. var factor = math.getVec2Angle(dir, vec);
  31866. if(new Vector3(dir.x, dir.y, 0).cross(new Vector3(vec.x, vec.y, 0)).z<0) factor*= -1; /////
  31867. if(!result){
  31868. result = {line, factor};
  31869. }
  31870. else {
  31871. if(type == "min" && factor<result.factor || type == "max" && factor>result.factor) result = {line, factor};
  31872. }
  31873. });
  31874. return result.line;
  31875. }
  31876. }
  31877. var lineLen=0;
  31878. class Line$1{
  31879. constructor(o){
  31880. if(o.points[0] == o.points[1])return;
  31881. this.points = o.points;
  31882. this.type = o.type || 'line';
  31883. if(this.type == 'line'){
  31884. var oldLine = lines.find(line=>line.points.includes(o.points[0]) && line.points.includes(o.points[1]));
  31885. if(oldLine){
  31886. o.id != void 0 && oldLine.ids.push(o.id);
  31887. return oldLine;
  31888. }
  31889. this.id = o.id == void 0 ? ("line"+lineLen ++) : o.id;
  31890. this.ids = [this.id];
  31891. o.dontWriteToPoint || this.points.forEach((point)=>{point.lines.push(this);});
  31892. o.isChild || lines.push(this);
  31893. this.searchTime = 0; // 最多两次
  31894. }
  31895. this.children = [];//分割
  31896. this.parents = [];//分割
  31897. this.match = [];
  31898. }
  31899. getAngleInfo(){
  31900. var angleInfo = getAngleInfo(this.points);
  31901. this.angle = angleInfo.angle;
  31902. this.reverse = angleInfo.reverse;
  31903. }
  31904. getIntersectWithLine(line, precision){
  31905. var joint = line.points.find(point=>this.points.includes(point));
  31906. if(joint)return {point:joint, type:"joint"};
  31907. var intersect = math.isLineIntersect( line.points , this.points , false, precision );
  31908. if(intersect) return {point: intersect, type:"intersect"};
  31909. }
  31910. writeToPoint(){
  31911. this.points.forEach((point)=>{point.lines.includes(this) || point.lines.push(this);});
  31912. }
  31913. checkIfParent(line){
  31914. if(this == line){
  31915. return true;//原因就是slice的点和端点很近 误差导致
  31916. }
  31917. else return this.parents.find(e=>e.checkIfParent(line))
  31918. }
  31919. splitByPoint(point){
  31920. var line1 = new Line$1({points:[point, this.points[0]], dontWriteToPoint:true, hasntsure:true});
  31921. var line2 = new Line$1({points:[point, this.points[1]], dontWriteToPoint:true, hasntsure:true});
  31922. if(!line1.points || !line2.points){//有至少一个是点相同的,没写到group.lines里
  31923. console.warn('splitByPoint 线有点相同');
  31924. return;
  31925. }
  31926. if(this.checkIfParent(line1)||this.checkIfParent(line2) || line1.checkIfParent(this) || line2.checkIfParent(this)){
  31927. console.warn("splitByPoint 发现parent和children一样");//,请检查getSliceWalls,尤其 if(math.closeTo(line1.angle,line2.angle)){ 处
  31928. return;
  31929. }
  31930. var deal = (line)=>{
  31931. this.children.push(line);
  31932. line.parents.push(this);
  31933. if(!lines.includes(line))lines.push(line);
  31934. line.writeToPoint();
  31935. };
  31936. deal(line1);
  31937. deal(line2);
  31938. var index = this.points[0].lines.indexOf(this);
  31939. index > -1 && this.points[0].lines.splice(index,1);
  31940. var index = this.points[1].lines.indexOf(this);
  31941. index > -1 && this.points[1].lines.splice(index,1);
  31942. return [line1,line2]
  31943. }
  31944. splitByPoints(points){
  31945. points = points.map(point=>{return {dis:point.distanceTo(this.points[0]), point:point}});
  31946. points.sort((point1, point2)=>{return point1.dis - point2.dis});
  31947. var children = [];
  31948. points.forEach((point, index)=>{
  31949. var line1 = new Line$1({points:[point.point, index==0?this.points[0]:points[index-1].point ],group:this.group , dontWriteToPoint:true, hasntsure:true});
  31950. children.push(line1);
  31951. });
  31952. var line2 = new Line$1({points:[points[points.length-1].point, this.points[1] ],group:this.group , dontWriteToPoint:true, hasntsure:true});
  31953. children.push(line2);
  31954. var a = children.find(line=> !line.points || this.checkIfParent(line) || line.checkIfParent(this));
  31955. if(a){
  31956. console.error("splitByPoints return");
  31957. return;
  31958. }
  31959. children.forEach(line=>{
  31960. this.children.push(line);
  31961. line.parents.push(this);
  31962. if(!lines.includes(line))lines.push(line);
  31963. line.writeToPoint();
  31964. line.writeToPoint();
  31965. });
  31966. var index = this.points[0].lines.indexOf(this);
  31967. index > -1 && this.points[0].lines.splice(index,1);
  31968. var index = this.points[1].lines.indexOf(this);
  31969. index > -1 && this.points[1].lines.splice(index,1);
  31970. }
  31971. getAllSlices(){//如果有被分割的片段 就返回片段,否则返回自身
  31972. var children = [];
  31973. var traverse = function(elem){
  31974. if(elem.children.length == 0) children.push(elem);
  31975. else elem.children.forEach(traverse);
  31976. };
  31977. traverse(this);
  31978. return children
  31979. }
  31980. getVector(){
  31981. return this.points[1].clone().sub(this.points[0]);
  31982. }
  31983. getLength(){
  31984. return this.points[0].distanceTo(this.points[1])
  31985. }
  31986. getCenter(){
  31987. return this.points[1].clone().add(this.points[0]).multiplyScalar(.5);
  31988. }
  31989. }
  31990. var getMixedSet = function(arr1, arr2){//交集
  31991. return arr1.filter(item=>arr2.includes(item));
  31992. };
  31993. var getUnionSet = function(arr1, arr2){//并集
  31994. return arr1.concat(arr2.filter(item=>!arr1.includes(item)))
  31995. };
  31996. var getDifferenceSet = function(arr1, arr2){//差集
  31997. var arr11 = arr1.filter(item=>!arr2.includes(item));
  31998. var arr22 = arr2.filter(item=>!arr1.includes(item));
  31999. return arr11.concat(arr22)
  32000. };
  32001. var getDifferenceSetMuti = function(arr){//收集绝对没有重复的元素,也就是判断出现次数=1的
  32002. var set = [];
  32003. arr.forEach(arr1=>{
  32004. arr1.forEach(item=>{
  32005. var index = set.indexOf(item);
  32006. if(index>-1){
  32007. set.splice(index, 1);
  32008. }else {
  32009. set.push(item);
  32010. }
  32011. });
  32012. });
  32013. return set;
  32014. };
  32015. function DoorAtWhichLine(points, lines){
  32016. var mid = points[0].clone().add(points[1]).multiplyScalar(0.5);
  32017. lines = lines.filter(line=>math.ifPointAtLineBound(mid, line.points, precision));
  32018. if(lines.length == 0)return
  32019. var result = {line:null, dis:Infinity};
  32020. lines.forEach(line=>{
  32021. var foot = math.getFootPoint(mid, line.points[0], line.points[1] );
  32022. var dis = foot.distanceTo(mid);
  32023. if(dis<result.dis){
  32024. result.line = line; result.dis = dis;
  32025. }
  32026. });
  32027. return result
  32028. }
  32029. var ringLen = 0;
  32030. class Ring{
  32031. constructor(o){
  32032. this.id = ringLen ++;
  32033. this.type = o.type || 'normal';
  32034. this.points = o.points;
  32035. this.lines = o.lines;
  32036. rings.push(this);
  32037. this.child = [];//包含的环
  32038. this.parent = [];//被包含的环
  32039. this.smallNeibours = [];//相邻最小环(存在和它有一个以上的相同边的最小环)
  32040. var area = math.getArea(this.points);
  32041. this.area = Math.abs(area);
  32042. this.isClockwise = area<0;//是否逆时针。一般都是逆时针得到的,如果是顺时针,可能是贪吃蛇的情况,可能不是最小环,需要去掉。
  32043. }
  32044. }
  32045. var findLine = function(p1,p2){
  32046. return lines.find(line=>line.points.includes(p1) && line.points.includes(p2) )
  32047. };
  32048. var ifSamePart = function(checkPart , part){//checkPart中所包含的part片段是否和基准part的顺序一样(逆序也可以, 中间有其他数也可以,起始不同也行。比如 01234和204一样的)
  32049. var axis, startIndex, newCheckPart=[];
  32050. for(var j=0,len1 = checkPart.length; j<len1; j++){//将checkPart中比part多的数除去,使两个数组中包含的数完全相同。
  32051. if(part.indexOf(checkPart[j])>-1)newCheckPart.push(checkPart[j]);
  32052. }
  32053. for(var i=0,len = part.length; i<len; i++){
  32054. var index = newCheckPart.indexOf(part[i]);
  32055. if(index == -1)return false;
  32056. if(i == 0) startIndex = index;//标记第一个查找点对应的index
  32057. else if(i == 1){//标记查找顺序是正还是逆
  32058. axis = index - startIndex;
  32059. if(axis == len - 1) axis = -1;//刚好是首和尾
  32060. else if(axis == 1- len) axis = 1;
  32061. if(axis != -1 && axis != 1){
  32062. return false
  32063. }
  32064. }else {//判断是否是按顺序的
  32065. if(index != ((startIndex+axis * i + len) % len) ) return false;
  32066. }
  32067. }
  32068. return {sameAxis:axis>0}; //如果一样的话返回正逆是否相同
  32069. };
  32070. //或者判断是否有相同边(但是相同点是可以组成不同环)
  32071. var ifSameRing = function(ring1, ring2){//判断两个环是否相等。 除了可以逆向外顺序要对
  32072. if(ring1 instanceof Ring)ring1 = ring1.points;
  32073. if(ring2 instanceof Ring)ring2 = ring2.points;
  32074. if(ring1.length != ring2.length)return false;
  32075. if(ring1.lines && ring2.lines){
  32076. if(getDifferenceSet(ring1.lines , ring2.lines).length == 0)return true;//差集个数为0
  32077. }else {
  32078. if(ifSamePart(ring1, ring2))return true
  32079. }
  32080. };
  32081. var atWhichChildLine = function(point, line, precision){
  32082. if(line.children.length == 0){//这里可能要放低精度 保证能找到
  32083. if(math.ifPointAtLineBound(point, line.points, precision)) return line;
  32084. }else {
  32085. for(var i=0;i<line.children.length;i++){
  32086. var at = atWhichChildLine(point, line.children[i], precision);
  32087. if(at)return at
  32088. }
  32089. }
  32090. };
  32091. function getSliceLines(){
  32092. var len = lines.length;
  32093. var deal = function(line1,line2){
  32094. if(line1 == line2)return;
  32095. if(line1.angle == void 0) line1.getAngleInfo();
  32096. if(line2.angle == void 0) line2.getAngleInfo();
  32097. var intersect = line1.getIntersectWithLine(line2, precision);
  32098. if(intersect){
  32099. var point; //得到交点
  32100. if(intersect.type == "intersect"){
  32101. point = getPoint(intersect.point, "whenGetSliceLines");
  32102. var line1_ = atWhichChildLine(point, line1);
  32103. var line2_ = atWhichChildLine(point, line2);
  32104. //重合的情况还没考虑(平行)
  32105. if(!line1_) line1_ = atWhichChildLine(point, line1, precision);//降低精度
  32106. if(!line1_) line1_ = atWhichChildLine(point, line1, precision*2);//降低精度
  32107. if(!line2_) line2_ = atWhichChildLine(point, line2, precision);
  32108. if(!line2_) line2_ = atWhichChildLine(point, line2, precision*2);//降低精度
  32109. //拆分线条:
  32110. //如果还报错,找不到ChildLine,就直接返回吧 或者搞个循环 逐渐降低精度
  32111. if(!line1_ || !line2_){
  32112. console.warn("atWhichChildLine仍旧找不到 :" + line1.id + ',' + line2.id + ", pointId: "+point.id);
  32113. line1_ || console.warn("找不到line1");
  32114. line2_ || console.warn("找不到line2");
  32115. return;
  32116. }
  32117. if(line1_.points.find(p=>p == point) && line2_.points.find(p=>p == point)){//这个点是line1_、 line2_端点,不做处理
  32118. //console.log("joint型 "+point.id)
  32119. }else if(line1_.points.find(p=>p == point)){//T型交叉
  32120. line2_.splitByPoint(point);//加入到母线中,之后还先用母线判断交点
  32121. //console.log("T型交叉1 "+point.id)
  32122. }else if(line2_.points.find(p=>p == point)){//T型交叉
  32123. line1_.splitByPoint(point);
  32124. //console.log("T型交叉2 "+point.id)
  32125. }else {//十字交叉
  32126. line1_.splitByPoint(point);
  32127. line2_.splitByPoint(point);
  32128. }
  32129. }else {
  32130. point = intersect.point;//交点是端点
  32131. if(math.closeTo(line1.angle,line2.angle)){ //重合一部分
  32132. var children1 = line1.getAllSlices();
  32133. var children2 = line2.getAllSlices();
  32134. if(children1.length>1 || children2.length>1){ //使用最小分割片段来比较
  32135. children1.forEach(child1=>{
  32136. children2.forEach(child2=>{
  32137. deal(child1, child2);
  32138. });
  32139. });
  32140. return;
  32141. }
  32142. var anotherPoint1 = line1.points.find(point_=>point_!=point);
  32143. var anotherPoint2 = line2.points.find(point_=>point_!=point);
  32144. if(math.ifPointAtLineBound(anotherPoint1, line2.points)){
  32145. line2.splitByPoint(anotherPoint1);
  32146. }else if(math.ifPointAtLineBound(anotherPoint2, line1.points)){
  32147. line1.splitByPoint(anotherPoint2);
  32148. }
  32149. }
  32150. }
  32151. }else if(math.closeTo(line1.angle,line2.angle)){
  32152. var vec1 = line1.getVector();
  32153. var vec = line1.points[0].clone().sub(line2.points[0]);
  32154. var cos = math.getVec2Cos(vec1, vec);
  32155. if(math.closeTo(cos, -1, 1e-4) || math.closeTo(cos, 1, 1e-4)){ //共线
  32156. var children1 = line1.getAllSlices();
  32157. var children2 = line2.getAllSlices();
  32158. if(children1.length>1 || children2.length>1){ //使用最小分割片段来比较
  32159. children1.forEach(child1=>{
  32160. children2.forEach(child2=>{
  32161. deal(child1, child2);
  32162. });
  32163. });
  32164. return;
  32165. }
  32166. //判断是否重叠
  32167. var A = line1.points[0];
  32168. var C = line1.reverse == line2.reverse ? line2.points[0] : line2.points[1];
  32169. var B = line1.points[1];
  32170. var D = line1.reverse == line2.reverse ? line2.points[1] : line2.points[0];
  32171. var BC = C.clone().sub(B);
  32172. var AD = D.clone().sub(A);
  32173. if(BC.length()<AD.length()){
  32174. var BA = A.clone().sub(B);
  32175. if(math.getVec2Angle(BC, BA) >= 1.57 )return;//没有重叠部分
  32176. }else {
  32177. var AB = B.clone().sub(A);
  32178. if(math.getVec2Angle(AD, AB) >= 1.57 )return;
  32179. }
  32180. var f = function(line1,line2){
  32181. var one = math.ifPointAtLineBound(line1.points[0], line2.points);
  32182. var two = math.ifPointAtLineBound(line1.points[1], line2.points);
  32183. if(one && two){//line1在line2上
  32184. line2.splitByPoints( line1.points );
  32185. return true
  32186. }else if(one || two){//错开
  32187. var point1 = one ? line1.points[0] : line1.points[1];
  32188. var anotherPoint1 = one ? line1.points[1] : line1.points[0];
  32189. var dis1 = line2.points[0].distanceTo(anotherPoint1);
  32190. var dis2 = line2.points[1].distanceTo(anotherPoint1);
  32191. var point2 = dis1 < dis2 ? line2.points[0] : line2.points[1];
  32192. line1.splitByPoint(point2);
  32193. line2.splitByPoint(point1);
  32194. return true
  32195. }
  32196. };
  32197. f(line1, line2) || f(line2, line1);
  32198. }
  32199. }
  32200. };
  32201. for(let i=0;i<len;i++){
  32202. let line1 = lines[i];
  32203. for(let j=i+1;j<len;j++){
  32204. let line2 = lines[j];
  32205. deal(line1,line2);
  32206. }
  32207. }
  32208. //console.log("原有线条个数:"+len)
  32209. //lines = lines.filter((line)=>{return line.children.length == 0})
  32210. //console.log("现有线条个数:"+lines.length)
  32211. }
  32212. var bound = new Box2();
  32213. var build = function(o){
  32214. //融合了相近点
  32215. //根据bound 处理precision
  32216. o.points.forEach(p=>{
  32217. bound.expandByPoint(new Vector2$1(p.x,p.y));
  32218. });
  32219. if(o.precision != void 0){
  32220. precision = o.precision;
  32221. }else {
  32222. var boundSize = bound.getSize(new Vector2$1);
  32223. precision = MathUtils.clamp(Math.max(boundSize.x, boundSize.y) / 70, 0.2, 2);
  32224. }
  32225. o.points.forEach(point=>getPoint(point));//{x:..,y:..}
  32226. o.lines.forEach(line=>{ //{p1:id1. p2:id2}
  32227. new Line$1({points:[getPoint(line.p1), getPoint(line.p2)], id:line.id });
  32228. });
  32229. //注意:不能出现一条线的两个点坐标一致,否则寻路时方向出错。 所以手动融合下相近点。
  32230. };
  32231. var searchRings = function(o={}){
  32232. points = [];
  32233. lines = [];
  32234. rings = [];
  32235. lineLen = ringLen = 0;
  32236. o.points = o.points || [];
  32237. o.lines = o.lines || [];
  32238. build(o);
  32239. if(!o.dontSliceLines){
  32240. getSliceLines();
  32241. }
  32242. //查找最小回路:
  32243. //参考: 引入方向因子的最小回路、最大回路搜索算法.pdf
  32244. //方法: 逆时针寻找(标记)最外层大环 -->从走过的点开始逆时针寻找最小环(直到所有可走的路被走过两次)-->逆时针寻找最外层大环(直到所有可走的路被走过两次)-->..
  32245. //其中找大环时选择方向因子最小的路, 而小环则相反(但只有开始第一条路是一样的, 都是选择最左边的点的因子最小的路)。
  32246. //标记方法: 每条线需要被搜索两次才算完毕。搜索完毕的线退出搜索。(依据:搜索完全部最小回路后 , 在无向图中删除搜索过 2 次的边及孤立节点得到退化图 , 恰好构成最大回路。)
  32247. var searchTime = 0;
  32248. var addRingJudgeCount = 0;
  32249. var addRingJudge = function(ring, lines, connectedLines, type){// 处理拣出的片段
  32250. addRingJudgeCount++;
  32251. //console.log("addRingJudge points("+ type+"):"+ ring.map(point=>point.id) )
  32252. if(o.onlyGetOutRing && type == "small")return
  32253. if(type == "small" || o.onlyGetOutRing){//挑出回路:
  32254. var newRings = [];
  32255. while(ring.length){
  32256. var road = [];
  32257. var turnBack = false;
  32258. for(let i=0;i<ring.length;i++){
  32259. if(road.includes(ring[i])){//如果走到方才的点,可能形成回路。 无论是不是回路都要摘去这段。
  32260. var index = road.indexOf(ring[i]);
  32261. var pointArr = ring.slice(index, i);
  32262. var linesArr = lines.slice(index, i);
  32263. ring.splice(index,i-index);
  32264. lines.splice(index,i-index);
  32265. if(pointArr.length>2){// 如果只有两个数,代表原路返回, 如 1->2(->1)
  32266. if( !rings.find(ring_=>ifSameRing(pointArr, ring_))) newRings.push( new Ring({points: pointArr, lines:linesArr}) );
  32267. }
  32268. turnBack = true;
  32269. break;
  32270. }else {
  32271. road.push(ring[i]);
  32272. turnBack = false;
  32273. }
  32274. }
  32275. if(!turnBack){//没有重复的点,那么就直接处理整条。
  32276. if(ring.length>2){// 如果只有两个数,代表原路返回, 如 1->2(->1)
  32277. if( !rings.find(ring_=>ifSameRing(ring, ring_))) newRings.push( new Ring({points: ring, lines}) );
  32278. }
  32279. break;
  32280. }
  32281. }
  32282. if(type != 'small'){
  32283. newRings.forEach(e=>e.isOutRing = true);
  32284. }
  32285. //console.log(newRings)
  32286. }else {
  32287. return ring
  32288. }
  32289. };
  32290. var search = function(point2d, comeRoad, type, connectedLines){
  32291. searchTime++;
  32292. var goLine;
  32293. var direction;
  32294. if(type.includes("big")){
  32295. if(!comeRoad){
  32296. if(type.includes("Left")){//逆时针
  32297. direction = new Vector2$1(1,0);
  32298. }else {
  32299. direction = new Vector2$1(-1,0);
  32300. }
  32301. goLine = point2d.searchLineByFactor(direction,"min");
  32302. }else {
  32303. var lastPoint = comeRoad.points[comeRoad.points.length-1];
  32304. direction = point2d.clone().sub(lastPoint);
  32305. goLine = point2d.searchLineByFactor(direction,"min", findLine(point2d, lastPoint));
  32306. }
  32307. }else {
  32308. if(!comeRoad){
  32309. //似乎找最小环时,第一条线也是找最小的因子,这样才能保证逆时针(除非只有顺时针一条路)
  32310. direction = new Vector2$1(1,0);
  32311. goLine = point2d.searchLineByFactor(direction,"min");
  32312. }else {
  32313. var lastPoint = comeRoad.points[comeRoad.points.length-1];
  32314. direction = point2d.clone().sub(lastPoint);
  32315. goLine = point2d.searchLineByFactor(direction,"max", findLine(point2d, lastPoint));
  32316. }
  32317. }
  32318. if(!goLine)return
  32319. goLine.searchTime++;
  32320. connectedLines.includes(goLine) || connectedLines.push(goLine);
  32321. var nextPoint = goLine.points.find( point => point2d!=point );
  32322. //if( comeRoad && comeRoad.points[comeRoad.points.length - 1] == nextPoint ) return;//不能查找来时的方向(反方向)
  32323. //走不通就原路返回
  32324. var roadPoints = comeRoad ? comeRoad.points.concat([point2d]) : [point2d];//每个分叉都能构成一条新的road
  32325. var roadLines = comeRoad ? comeRoad.lines.concat([goLine]) : [goLine];
  32326. //走到第一个点就算停止,这时候可能得到一个环、或者一段走了两遍的线、或者一条线上带了些环。
  32327. if(nextPoint == roadPoints[0]) return addRingJudge(roadPoints, roadLines, connectedLines, type) //形成环
  32328. else {
  32329. /* var len = roadPoints.indexOf(nextPoint);
  32330. if( len > -1){ //走到走过的路的某一点 构成这段路的回路
  32331. var points = roadPoints.slice(len, roadPoints.length);
  32332. var lines = roadLines.slice(len, roadPoints.length);
  32333. addRingJudge(points, lines)
  32334. }else{ */
  32335. return search(nextPoint, {lines:roadLines, points:roadPoints}, type, connectedLines);//继续寻路
  32336. //}
  32337. }
  32338. };
  32339. while(1){//搜寻一次大环
  32340. var connectedLines = [];//被搜寻过的且searchTime<2的线。一旦全部搜完就说明该连通区域搜寻完毕,继续查下一个连通区域。
  32341. var startPoint = null;
  32342. points.forEach(point=>{//找出x最小的点
  32343. if(!point.lines.find(line=>line.searchTime<2))return;
  32344. if(!startPoint)startPoint = point;
  32345. else if(point.x < startPoint.x)startPoint = point;
  32346. });
  32347. if(!startPoint)break; //说明全部找完
  32348. var ring = search(startPoint, null, "bigLeft", connectedLines);//逆时针
  32349. //search(startPoint, null, "bigRight", connectedLines);//顺时针(为了防止最外层不是回路之前写了顺时针,但如果是回路就会走重复。后来发现只要逆时针即可,因为走完后剩下的可以再次找大环)
  32350. connectedLines = connectedLines.filter(line=>line.searchTime<2);
  32351. while(connectedLines.length>0){//目标是顺着connectedLines把所有连通的小环都找到
  32352. let points_ = [];//connectedLines中所有的点
  32353. connectedLines.forEach(line=>line.points.forEach(point=>{if(!points_.includes(point))points_.push(point); }));
  32354. var startPoint = null;
  32355. points_.forEach(point=>{//找出x最小的点
  32356. if(!point.lines.find(line=>line.searchTime<2))return;
  32357. if(!startPoint)startPoint = point;
  32358. else if(point.x < startPoint.x)startPoint = point;
  32359. });
  32360. if(!startPoint)break;
  32361. search(startPoint, null, "small", connectedLines);
  32362. connectedLines = connectedLines.filter(line=>line.searchTime<2);
  32363. }
  32364. }
  32365. /* if(o.onlyGetOutRing){
  32366. rings = rings.filter(e=>e.isOutRing)
  32367. } */
  32368. //console.log("searchTime "+searchTime + ", addRingJudgeCount " +addRingJudgeCount)
  32369. //找出所有的相邻关系,包括公共边
  32370. var len = rings.length;
  32371. for(let i=0; i<len; i++){
  32372. let ring1 = rings[i];
  32373. for(let j=i+1; j<len; j++){
  32374. let ring2 = rings[j];
  32375. var bothHasLines = getMixedSet(ring1.lines, ring2.lines);
  32376. if(bothHasLines.length){//ring1oíring2?àáú
  32377. ring1.smallNeibours.push(ring2);
  32378. ring2.smallNeibours.push(ring1);
  32379. }else {
  32380. }
  32381. }
  32382. }
  32383. rings.forEach(ring1=>{
  32384. for(let i=0; i<len; i++){
  32385. var ring2 = rings[i];
  32386. if(ring1 == ring2 || ring1.smallNeibours.includes(ring2))continue;
  32387. let inside;
  32388. for(let u=0;u<ring1.points.length;u++){
  32389. inside = math.isPointInArea(ring2.points, null, ring1.points[u]);
  32390. if(!inside)break
  32391. else if(inside && !inside.atLine){
  32392. break
  32393. }
  32394. }
  32395. if(inside){ //只要其中一个点在ring2内,就说明ring1是内环
  32396. if(inside.atLine){//(还是会存在点全在线上的情况,这时候判断中心点)
  32397. var center = math.getCenterOfGravityPoint(ring1.points);
  32398. let inside1 = math.isPointInArea(ring2.points, null, center);
  32399. if(!inside1){
  32400. continue
  32401. }
  32402. }
  32403. ring2.child.push(ring1);
  32404. ring1.parent.push(ring2);
  32405. }
  32406. }
  32407. });
  32408. //去除非最小的ring 是否应该检测parent child?
  32409. /*
  32410. like this:
  32411. |———————————————————————|
  32412. |———|———————|———————| |
  32413. | | | | |
  32414. | |———————|———————| |
  32415. |———————————————————————|
  32416. */
  32417. var wiseRings = rings.filter(r=>!r.isClockwise);//一般都是逆时针得到的,如果是顺时针,可能是贪吃蛇的情况,可能不是最小环,需要去掉。
  32418. if(wiseRings.length > 0){
  32419. //console.log('%c存在非最小的ring! 进行处理:',"color:#00f");
  32420. wiseRings.forEach(ring=>{ //(此案例验证出smallNeibours就是它的最小构成,可以再看看别的案例)
  32421. if(ring.smallNeibours.length>0){//另:如果内部只有一个,说明它是最小环,不需要处理
  32422. var is = false;
  32423. var difference = getDifferenceSet(ring.lines , getDifferenceSetMuti(ring.smallNeibours.concat(ring.child).map(ring=>ring.lines)));//获取所有smallNeibours和child的边中没有重复过的边(就是outline) 和该ring的线比较
  32424. is = difference.every(line=> ring.child.find(r=>r.lines.includes(line)) ); //多出的线只能是child中的线
  32425. if(is){
  32426. console.log('%c删除非最小环 ring'+ring.id,"color:#00f");
  32427. console.log(ring);
  32428. rings.splice(rings.indexOf(ring), 1);
  32429. ring.child.forEach(c=>{var index = c.parent.indexOf(ring);index>-1 && c.parent.splice(index,1);});
  32430. ring.parent.forEach(c=>{var index = c.child.indexOf(ring);index>-1 && c.child.splice(index,1);});
  32431. ring.smallNeibours.forEach(c=>{var index = c.smallNeibours.indexOf(ring);index>-1 && c.smallNeibours.splice(index,1);});
  32432. }
  32433. }
  32434. });
  32435. }
  32436. /* rings = rings.filter(ring=>{
  32437. rings = rings.filter(ring=>{
  32438. var enoughSize = ring.area > 0.5
  32439. if(!enoughSize){console.log('因面积过小去除ring '+ring.id + " , area: "+ring.area)}
  32440. return enoughSize
  32441. })
  32442. rings.forEach(ring=>{
  32443. if(ring.closetChilds){
  32444. ring.closetChilds = ring.closetChilds.filter(e=>rings.includes(e))
  32445. }
  32446. })
  32447. return rings
  32448. }) */ //在dealRings前不能随意删除rings,因为判断是否是最小环时需要全部的环
  32449. rings.forEach(ring=>{ //这里和cad中的不太一样, cad中双数个parent算外环,单数内环; 这里不分内外, 只看有无parent child
  32450. if(ring.parent.length){
  32451. ring.closetParent = ring.parent.find(ring_ => ring_.parent.length == ring.parent.length - 1);//最近一层的大环就是比它的parent个数少一的
  32452. ring.closetParent.closetChilds || (ring.closetParent.closetChilds = []);//内环可能多个
  32453. ring.closetParent.closetChilds.push(ring);
  32454. }
  32455. });
  32456. //console.log(rings)
  32457. var _ring = rings.map(ring=>{
  32458. var data = {
  32459. id: ring.id,
  32460. points: ring.points.map(point=>{return {id: point.ids[0], x:point.x, y:point.y}}),
  32461. /* doors : o.doors.filter(door=>{
  32462. if(ring.closetChilds){
  32463. var childOutLines = getDifferenceSetMuti(ring.closetChilds.map(ring=>ring.lines)) //最近子环的外边
  32464. return ring.lines.concat(childOutLines).includes(door.atLine)
  32465. }else{
  32466. return ring.lines.includes(door.atLine)
  32467. }
  32468. }), */
  32469. area:ring.area,
  32470. closetParent : ring.closetParent && ring.closetParent.id,
  32471. closetChilds : ring.closetChilds && ring.closetChilds.map(e=>e.id)
  32472. };
  32473. return data
  32474. });
  32475. //console.log(JSON.stringify(_ring))
  32476. return _ring
  32477. };
  32478. var math = {
  32479. getBaseLog(x, y) {//返回以 x 为底 y 的对数(即 logx y) . Math.log 返回一个数的自然对数
  32480. return Math.log(y) / Math.log(x);
  32481. }
  32482. ,
  32483. convertVector : {
  32484. ZupToYup: function(e){//navvis -> 4dkk
  32485. return new Vector3(e.x,e.z,-e.y)
  32486. },
  32487. YupToZup: function(e){//4dkk -> navvis
  32488. return new Vector3(e.x,-e.z,e.y)
  32489. },
  32490. },
  32491. convertQuaternion: {
  32492. ZupToYup: function(e){//navvis -> 4dkk //不同于convertVisionQuaternion
  32493. let rotation = new Euler(-Math.PI/2,0,0);
  32494. let quaternion = new Quaternion().setFromEuler(rotation);
  32495. return e.clone().premultiply(quaternion)
  32496. //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)))
  32497. },
  32498. YupToZup: function(e){//4dkk -> navvis
  32499. let rotation = new Euler(Math.PI/2,0,0);
  32500. let quaternion = new Quaternion().setFromEuler(rotation);
  32501. return e.clone().premultiply(quaternion)
  32502. },
  32503. },
  32504. convertVisionQuaternion: function(e) {
  32505. return new Quaternion(e.x,e.z,-e.y,e.w).multiply((new Quaternion).setFromAxisAngle(new Vector3(0,1,0), MathUtils.degToRad(90)))
  32506. },
  32507. invertVisionQuaternion : function(e) {//反转给算法部
  32508. var a = e.clone().multiply((new Quaternion).setFromAxisAngle(new Vector3(0,1,0), MathUtils.degToRad(-90)));
  32509. return new Quaternion(a.x,-a.z,a.y,a.w)
  32510. },
  32511. //------------
  32512. getVec2Angle : function(dir1,dir2){
  32513. return Math.acos( MathUtils.clamp(this.getVec2Cos(dir1,dir2), -1,1) )
  32514. },
  32515. getVec2Cos : function(dir1,dir2){
  32516. return dir1.dot(dir2) / dir1.length() / dir2.length()
  32517. },
  32518. getAngle:function(vec1, vec2, axis){//带方向的角度 vector3
  32519. var angle = vec1.angleTo(vec2);
  32520. var axis_ = vec1.clone().cross(vec2);
  32521. if(axis_[axis] < 0){
  32522. angle *= -1;
  32523. }
  32524. return angle
  32525. },
  32526. closeTo : function(a,b, precision=1e-6){
  32527. let f = (a,b)=>{
  32528. return Math.abs(a-b) < precision;
  32529. };
  32530. if(typeof (a) == 'number'){
  32531. return f(a, b);
  32532. }else {
  32533. let judge = (name)=>{
  32534. if(a[name] == void 0)return true //有值就判断,没值就不判断
  32535. else return f(a[name],b[name])
  32536. };
  32537. return judge('x') && judge('y') && judge('z') && judge('w')
  32538. }
  32539. },
  32540. toPrecision: function (e, t) {//xzw change 保留小数
  32541. var f = function (e, t) {
  32542. var i = Math.pow(10, t);
  32543. return Math.round(e * i) / i
  32544. };
  32545. if (e instanceof Array) {
  32546. for (var s = 0; s < e.length; s++) {
  32547. e[s] = f(e[s], t);
  32548. }
  32549. return e;
  32550. } else if (e instanceof Object) {
  32551. for (var s in e) {
  32552. e[s] = f(e[s], t);
  32553. }
  32554. return e;
  32555. } else return f(e, t)
  32556. },
  32557. isEmptyQuaternion: function(e) {
  32558. return 0 === Math.abs(e.x) && 0 === Math.abs(e.y) && 0 === Math.abs(e.z) && 0 === Math.abs(e.w)
  32559. },
  32560. projectPositionToCanvas: function(e, t, i) {
  32561. i = i || new Vector3,
  32562. i.copy(e);
  32563. var r = .5 * $('#player').width()
  32564. , o = .5 * $('#player').height();
  32565. return i.project(t),
  32566. i.x = i.x * r + r,
  32567. i.y = -(i.y * o) + o,
  32568. i
  32569. },
  32570. handelPadResize:false,
  32571. /* handelPadding : function () { //去除player左边和上面的宽高,因为pc的player左上有其他element 许钟文
  32572. var pads = [];//记录下来避免反复计算
  32573. var index = [];
  32574. var resetPad = function(){
  32575. pads = [];
  32576. index = [];
  32577. math.handelPadResize = false; //switchview时resized为true
  32578. }
  32579. if(config.isEdit && !config.isMobile){
  32580. window.addEventListener('resize',resetPad);
  32581. }
  32582. return function(x, y, domE){
  32583. if(!config.isEdit || config.isMobile) {
  32584. return {
  32585. x: x,
  32586. y: y
  32587. }
  32588. }
  32589. if(this.handelPadResize)resetPad();
  32590. domE = domE || $('#player')[0];
  32591. var pad;
  32592. var i = index.indexOf(domE);
  32593. if (i == -1){
  32594. index.push(domE);
  32595. pad = {
  32596. x: this.getOffset("left", domE),
  32597. y: this.getOffset("top", domE)
  32598. }
  32599. pads.push(pad)
  32600. }
  32601. else pad = pads[i];
  32602. return {
  32603. x: x - pad.x,
  32604. y: y - pad.y
  32605. }
  32606. }
  32607. }(), */
  32608. getOffset: function (type, element, parent) {//获取元素的边距 许钟文
  32609. var offset = (type == "left") ? element.offsetLeft : element.offsetTop;
  32610. if (!parent) parent = $("body")[0];
  32611. while (element = element.offsetParent) {
  32612. if (element == parent) break;
  32613. offset += (type == "left") ? element.offsetLeft : element.offsetTop;
  32614. }
  32615. return offset;
  32616. }
  32617. ,
  32618. constrainedTurn: function(e) {
  32619. var t = e % (2 * Math.PI);
  32620. return t = t > Math.PI ? t -= 2 * Math.PI : t < -Math.PI ? t += 2 * Math.PI : t
  32621. },
  32622. getFOVDotThreshold: function(e) {
  32623. return Math.cos(MathUtils.degToRad(e / 2))
  32624. },
  32625. transform2DForwardVectorByCubeFace: function(e, t, i, n) {
  32626. switch (e) {
  32627. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  32628. i.set(1, t.y, t.x);
  32629. break;
  32630. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  32631. i.set(-1, t.y, -t.x);
  32632. break;
  32633. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
  32634. i.set(-t.x, 1, -t.y);
  32635. break;
  32636. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  32637. i.set(-t.x, -1, t.y);
  32638. break;
  32639. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  32640. i.set(-t.x, t.y, 1);
  32641. break;
  32642. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  32643. i.set(t.x, t.y, -1);
  32644. }
  32645. n && i.normalize();
  32646. },
  32647. getFootPoint : function(oldPos, p1, p2, restricInline){ //找oldPos在线段p1, p2上的垂足
  32648. /* if(isWorld){//输出全局坐标 需要考虑meshGroup.position
  32649. p1 = p1.clone();
  32650. p2 = p2.clone();
  32651. p1.y += mainDesign.meshGroup.position.y;
  32652. p2.y += mainDesign.meshGroup.position.y;
  32653. } */
  32654. if(p1.equals(p2))return p1.clone()
  32655. var op1 = oldPos.clone().sub(p1);
  32656. var p1p2 = p1.clone().sub(p2);
  32657. var p1p2Len = p1p2.length();
  32658. var leftLen = op1.dot(p1p2) / p1p2Len;
  32659. var pos = p1.clone().add(p1p2.multiplyScalar( leftLen/p1p2Len ));
  32660. if(restricInline && pos.clone().sub(p1).dot( pos.clone().sub(p2) ) > 0){//foot不在线段上
  32661. if(pos.distanceTo(p1) < pos.distanceTo(p2)) pos = p1.clone();
  32662. else pos = p2.clone();
  32663. }
  32664. return pos;
  32665. },
  32666. /**
  32667. * 计算多边形的重心
  32668. * @param {*} points
  32669. */
  32670. getCenterOfGravityPoint : function(mPoints){
  32671. var area = 0.0;//多边形面积
  32672. var Gx = 0.0, Gy = 0.0;// 重心的x、y
  32673. for (var i = 1; i <= mPoints.length; i++) {
  32674. var ix = mPoints[i % mPoints.length].x;
  32675. var iy = mPoints[i % mPoints.length].y;
  32676. var nx = mPoints[i - 1].x;
  32677. var ny = mPoints[i - 1].y;
  32678. var temp = (ix * ny - iy * nx) / 2.0;
  32679. area += temp;
  32680. Gx += temp * (ix + nx) / 3.0;
  32681. Gy += temp * (iy + ny) / 3.0;
  32682. }
  32683. Gx = Gx / area;
  32684. Gy = Gy / area;
  32685. return { x: Gx, y: Gy };
  32686. },
  32687. getBound : function(ring){
  32688. var bound = new Box2();
  32689. for(var j=0,len = ring.length; j<len; j++){
  32690. bound.expandByPoint(ring[j]);
  32691. }
  32692. return bound;
  32693. },
  32694. isPointInArea : function(ring, holes, point, ifAtLine){//判断点是否在某个环内, 若传递了holes代表还要不能在内环内
  32695. var bound = this.getBound(ring);
  32696. if(point.x < bound.min.x || point.x > bound.max.x || point.y < bound.min.y || point.y > bound.max.y)return false;
  32697. var inside = false;
  32698. var x = point.x,
  32699. y = point.y;
  32700. for (var i = 0, j = ring.length - 1; i < ring.length; j = i++) {
  32701. var xi = ring[i].x,
  32702. yi = ring[i].y;
  32703. var xj = ring[j].x,
  32704. yj = ring[j].y;
  32705. if((xi - x)*(yj - y) == (xi - x)*(yi - y) && x>=Math.min(xi,xj) && x<=Math.max(xi,xj)//xzw add
  32706. && y>=Math.min(yi,yj) && y<=Math.max(yi,yj)
  32707. ){
  32708. //return !!ifAtLine;//在线段上,则判断为…… (默认在外)
  32709. return {atLine:true}
  32710. }
  32711. if (((yi > y) != (yj > y)) &&
  32712. (x < (xj - xi) * (y - yi) / (yj - yi) + xi)
  32713. ) {
  32714. inside = !inside;
  32715. }
  32716. }
  32717. if(inside && holes){
  32718. return !holes.some(ring=>this.isPointInArea(ring, null, point, ifAtLine) ) //不能存在于任何一个二级内环内
  32719. }else {
  32720. return inside;
  32721. }
  32722. },
  32723. getArea : function (ring) { //求面积 顺时针为正 来自three shape
  32724. for (var t = ring.length, i = 0, n = t - 1, r = 0; r < t; n = r++)
  32725. i += ring[n].x * ring[r].y - ring[r].x * ring[n].y;
  32726. return -.5 * i
  32727. },
  32728. isInBetween : function(a, b, c, precision) {
  32729. // 如果b几乎等于a或c,返回false.为了避免浮点运行时两值几乎相等,但存在相差0.00000...0001的这种情况出现使用下面方式进行避免
  32730. /* if (Math.abs(a - b) < 0.000001 || Math.abs(b - c) < 0.000001) {
  32731. return false;
  32732. }
  32733. return (a <= b && b <= c) || (c <= b && b <= a);*/
  32734. //更改:如果b和a或c中一个接近 就算在a和c之间
  32735. return (a <= b && b <= c) || (c <= b && b <= a) || this.closeTo(a,b,precision) || this.closeTo(b,c,precision);
  32736. },
  32737. ifPointAtLineBound:function(point, linePoints, precision){
  32738. //待验证 横线和竖线比较特殊
  32739. return math.isInBetween(linePoints[0].x, point.x, linePoints[1].x, precision) && math.isInBetween(linePoints[0].y, point.y, linePoints[1].y, precision)
  32740. }
  32741. ,
  32742. isLineIntersect: function (line1, line2, notSegment, precision) {//线段和线段是否有交点. notSegment代表是直线而不是线段
  32743. var a1 = line1[1].y - line1[0].y;
  32744. var b1 = line1[0].x - line1[1].x;
  32745. var c1 = a1 * line1[0].x + b1 * line1[0].y;
  32746. //转换成一般式: Ax+By = C
  32747. var a2 = line2[1].y - line2[0].y;
  32748. var b2 = line2[0].x - line2[1].x;
  32749. var c2 = a2 * line2[0].x + b2 * line2[0].y;
  32750. // 计算交点
  32751. var d = a1 * b2 - a2 * b1;
  32752. // 当d==0时,两线平行
  32753. if (d == 0) {
  32754. return false;
  32755. } else {
  32756. var x = (b2 * c1 - b1 * c2) / d;
  32757. var y = (a1 * c2 - a2 * c1) / d;
  32758. // 检测交点是否在两条线段上
  32759. /* if (notSegment || (isInBetween(line1[0].x, x, line1[1].x) || isInBetween(line1[0].y, y, line1[1].y)) &&
  32760. (isInBetween(line2[0].x, x, line2[1].x) || isInBetween(line2[0].y, y, line2[1].y))) {
  32761. return {x,y};
  32762. } */
  32763. if (notSegment || math.ifPointAtLineBound({x,y}, line1, precision) && math.ifPointAtLineBound({x,y}, line2, precision)){
  32764. return {x,y};
  32765. }
  32766. }
  32767. },
  32768. getNormal2d : function(o={} ){//获取二维法向量 方向向内
  32769. var x,y, x1,y1;
  32770. //line2d的向量
  32771. if(o.vec){
  32772. x1 = o.vec.x; y1 = o.vec.y;
  32773. }else {
  32774. x1 = o.p1.x - o.p2.x;
  32775. y1 = o.p1.y - o.p2.y;
  32776. }
  32777. //假设法向量的x或y固定为1或-1
  32778. if(y1 != 0){
  32779. x = 1;
  32780. y = - (x1 * x) / y1;
  32781. }else if(x1 != 0){//y如果为0,正常情况x不会是0
  32782. y = 1;
  32783. x = - (y1 * y) / x1;
  32784. }else {
  32785. console.log("两个点一样");
  32786. return null;
  32787. }
  32788. //判断方向里或者外:
  32789. var vNormal = new Vector3(x, 0, y);
  32790. var vLine = new Vector3(x1, 0, y1);
  32791. var vDir = vNormal.cross(vLine);
  32792. if(vDir.y>0){
  32793. x *= -1;
  32794. y *= -1;
  32795. }
  32796. return new Vector2$1(x, y).normalize();
  32797. },
  32798. getQuaBetween2Vector:function(oriVec, newVec, upVec){ //获取从oriVec旋转到newVec可以应用的quaternion
  32799. var angle = oriVec.angleTo(newVec);
  32800. var axis = oriVec.clone().cross( newVec).normalize();//两个up之间
  32801. if(axis.length() == 0){//当夹角为180 或 0 度时,得到的axis为(0,0,0),故使用备用的指定upVec
  32802. return new Quaternion().setFromAxisAngle( upVec, angle );
  32803. }
  32804. return new Quaternion().setFromAxisAngle( axis, angle );
  32805. }
  32806. /* ,
  32807. getQuaBetween2Vector2 : function(oriVec, newVec ){//not camera
  32808. var _ = (new THREE.Matrix4).lookAt( oriVec, new THREE.Vector3, new THREE.Vector3(0,1,0))
  32809. var aimQua = (new THREE.Quaternion).setFromRotationMatrix(_)
  32810. var _2 = (new THREE.Matrix4).lookAt( newVec, new THREE.Vector3, new THREE.Vector3(0,1,0))
  32811. var aimQua2 = (new THREE.Quaternion).setFromRotationMatrix(_2)
  32812. return aimQua2.multiply(aimQua.clone().inverse())
  32813. } */
  32814. ,
  32815. getScaleForConstantSize : function(){ //获得规定二维大小的mesh的scale值。可以避免因camera的projection造成的mesh视觉大小改变。 来源:tag.updateDisc
  32816. var w;
  32817. var i = new Vector3, o = new Vector3, l = new Vector3, c = new Vector3, h = new Vector3;
  32818. return function(op={}){
  32819. if(op.width2d) w = op.width2d; //如果恒定二维宽度
  32820. else {//否则考虑上距离,加一丢丢近大远小的效果
  32821. var currentDis, nearBound, farBound;
  32822. if(op.camera.type == "OrthographicCamera"){
  32823. currentDis = 200 / op.camera.zoom; //(op.camera.right - op.camera.left) / op.camera.zoom
  32824. }else {
  32825. currentDis = op.position.distanceTo(op.camera.position);
  32826. }
  32827. w = op.maxSize - ( op.maxSize - op.minSize) * MathUtils.smoothstep(currentDis, op.nearBound, op.farBound);
  32828. //maxSize : mesh要表现的最大像素宽度; nearBound: 最近距离,若比nearBound近,则使用maxSize
  32829. }
  32830. i.copy(op.position).project(op.camera), //tag中心在屏幕上的二维坐标
  32831. o.set(op.resolution.x / 2, op.resolution.y / 2, 1).multiply(i), //转化成px -w/2 到 w/2的范围
  32832. l.set(w / 2, 0, 0).add(o), //加上tag宽度的一半
  32833. c.set(2 / op.resolution.x, 2 / op.resolution.y, 1).multiply(l), //再转回 -1 到 1的范围
  32834. h.copy(c).unproject(op.camera);//再转成三维坐标,求得tag边缘的位置
  32835. var g = h.distanceTo(op.position);//就能得到tag的三维半径
  32836. //这里使用的都是resolution2, 好处是手机端不会太小, 坏处是pc更改网页显示百分比时显示的大小会变(或许可以自己算出设备真实的deviceRatio, 因window.screen是不会改变的),但考虑到用户可以自行调节字大小也许是好的
  32837. return g //可能NAN 当相机和position重叠时
  32838. }
  32839. }()
  32840. ,
  32841. //W , H, left, top分别是rect的宽、高、左、上
  32842. getCrossPointAtRect : function(p1, aim, W , H, left, top){//求射线p1-aim在rect边界上的交点,其中aim在rect范围内,p1则不一定(交点在aim这边的延长线上)
  32843. var x,y, borderX;
  32844. var r = (aim.x - p1.x) / (aim.y - p1.y);//根据相似三角形原理先求出这个比值
  32845. var getX = function(y){
  32846. return r * (y-p1.y) + p1.x;
  32847. };
  32848. var getY = function(x){
  32849. return 1/r * (x-p1.x) + p1.y;
  32850. };
  32851. if(aim.x >= p1.x){
  32852. borderX = W+left;
  32853. }else {
  32854. borderX = left;
  32855. }
  32856. x = borderX;
  32857. y = getY(x);
  32858. if(y < top || y > top+H){
  32859. if(y < top){
  32860. y = top;
  32861. }else {
  32862. y = top+H;
  32863. }
  32864. x = getX(y);
  32865. }
  32866. return new Vector2$1(x, y);
  32867. },
  32868. getDirFromUV : function(uv){ //获取dir 反向计算 - - 二维转三维比较麻烦
  32869. var dirB; //所求 单位向量
  32870. var y = Math.cos(uv.y * Math.PI); //uv中纵向可以直接确定y, 根据上面getUVfromDir的反向计算
  32871. // 故 uv.y * Math.PI 就是到垂直线(向上)的夹角
  32872. var angle = 2 * Math.PI * uv.x - Math.PI; //x/z代表的是角度
  32873. var axisX, axisZ; //axis为1代表是正,-1是负数
  32874. if (-Math.PI <= angle && angle < 0) {
  32875. axisX = -1; //下半圆
  32876. } else {
  32877. axisX = 1; //上半圆
  32878. }
  32879. if (-Math.PI / 2 <= angle && angle < Math.PI / 2) {
  32880. axisZ = 1; //右半圆
  32881. } else {
  32882. axisZ = -1; //左半圆
  32883. }
  32884. var XDivideZ = Math.tan(angle);
  32885. var z = Math.sqrt((1 - y * y) / (1 + XDivideZ * XDivideZ));
  32886. var x = XDivideZ * z;
  32887. if (z * axisZ < 0) { //异号
  32888. z *= -1;
  32889. x *= -1;
  32890. if (x * axisX < 0) {
  32891. // console.log("wrong!!!!!??????????")
  32892. }
  32893. }
  32894. x *= -1; //计算完成后这里不能漏掉 *= -1
  32895. dirB = this.convertVector.YupToZup(new Vector3(x, y, z));
  32896. //理想状态下x和z和anotherDir相同
  32897. return dirB
  32898. },
  32899. getUVfromDir : function(dir) { //获取UV 同shader里的计算
  32900. var dir = this.convertVector.ZupToYup(dir);
  32901. dir.x *= -1; //计算前这里不能漏掉 *= -1 见shader
  32902. var tx = Math.atan2(dir.x, dir.z) / (Math.PI * 2.0) + 0.5; //atan2(y,x) 返回从 X 轴正向逆时针旋转到点 (x,y) 时经过的角度。区间是-PI 到 PI 之间的值
  32903. var ty = Math.acos(dir.y) / Math.PI;
  32904. return new Vector2$1(tx, ty)
  32905. //理想状态下tx相同
  32906. },
  32907. getDirByLonLat : function(lon,lat){
  32908. var dir = new Vector3;
  32909. var phi = MathUtils.degToRad(90 - lat);
  32910. var theta = MathUtils.degToRad(lon);
  32911. dir.x = Math.sin(phi) * Math.cos(theta);
  32912. dir.y = Math.cos(phi);
  32913. dir.z = Math.sin(phi) * Math.sin(theta);
  32914. return dir
  32915. } //0,0 => (1,0,0) 270=>(0,0,-1)
  32916. ,
  32917. projectPointAtPlane:function(o={}){//获取一个点在一个面上的投影 {facePoints:[a,b,c], point:}
  32918. var plane = new Plane().setFromCoplanarPoints(...o.facePoints);
  32919. return plane.projectPoint(o.point, new Vector3() )
  32920. }
  32921. ,
  32922. getPolygonsMixedRings:function( polygons, onlyGetOutRing){//{points:[vector2,...],holes:[[],[]]}
  32923. let points = [];
  32924. let lines = [];
  32925. let i = 0;
  32926. polygons.forEach(e=> points.push(...e.map(a=>new Vector2$1().copy(a) )) );
  32927. polygons.forEach((ps,j)=>{
  32928. let length = ps.length;
  32929. let index = 0;
  32930. while(index<length){
  32931. lines.push({p1:index+i,p2:(index+1)%length+i});
  32932. index ++;
  32933. }
  32934. i+=length;
  32935. });
  32936. points.forEach((p,j)=>{p.id = j;});
  32937. let rings = searchRings({
  32938. points,
  32939. lines,
  32940. onlyGetOutRing
  32941. });
  32942. //console.log(rings)
  32943. rings = rings.filter(e=>e.closetParent == void 0);// 子环不加,被外环包含了
  32944. return rings
  32945. },
  32946. getQuaFromPosAim( position, target ){
  32947. let matrix = (new Matrix4).lookAt(position, target, new Vector3(0,0,1));
  32948. return (new Quaternion).setFromRotationMatrix(matrix)
  32949. },
  32950. getBoundByPoints(points, minSize){
  32951. var bound = new Box3;
  32952. points.forEach(point=>{
  32953. bound.expandByPoint(point);
  32954. });
  32955. let center = bound.getCenter(new Vector3);
  32956. if(minSize){
  32957. let minBound = (new Box3()).setFromCenterAndSize(center, minSize);
  32958. bound.union(minBound);
  32959. }
  32960. return {
  32961. bounding:bound,
  32962. size: bound.getSize(new Vector3),
  32963. center,
  32964. }
  32965. },
  32966. };
  32967. Potree.math = math;
  32968. !function() {
  32969. if ("performance"in window == 0 && (window.performance = {}),
  32970. "now"in window.performance == 0) {
  32971. var e = Date.now();
  32972. performance.timing && performance.timing.navigationStart && (e = performance.timing.navigationStart),
  32973. window.performance.now = function() {
  32974. return Date.now() - e
  32975. };
  32976. }
  32977. }(),
  32978. WebGLRenderer.prototype.paramThreeToGL = function(e) {
  32979. var t, i = this.extensions, r = this.getContext();//context;
  32980. if (e === RepeatWrapping)
  32981. return r.REPEAT;
  32982. if (e === ClampToEdgeWrapping)
  32983. return r.CLAMP_TO_EDGE;
  32984. if (e === MirroredRepeatWrapping)
  32985. return r.MIRRORED_REPEAT;
  32986. if (e === NearestFilter)
  32987. return r.NEAREST;
  32988. if (e === NearestMipMapNearestFilter)
  32989. return r.NEAREST_MIPMAP_NEAREST;
  32990. if (e === NearestMipMapLinearFilter)
  32991. return r.NEAREST_MIPMAP_LINEAR;
  32992. if (e === LinearFilter)
  32993. return r.LINEAR;
  32994. if (e === LinearMipMapNearestFilter)
  32995. return r.LINEAR_MIPMAP_NEAREST;
  32996. if (e === LinearMipMapLinearFilter)
  32997. return r.LINEAR_MIPMAP_LINEAR;
  32998. if (e === UnsignedByteType)
  32999. return r.UNSIGNED_BYTE;
  33000. if (e === UnsignedShort4444Type)
  33001. return r.UNSIGNED_SHORT_4_4_4_4;
  33002. if (e === UnsignedShort5551Type)
  33003. return r.UNSIGNED_SHORT_5_5_5_1;
  33004. if (e === UnsignedShort565Type)
  33005. return r.UNSIGNED_SHORT_5_6_5;
  33006. if (e === ByteType)
  33007. return r.BYTE;
  33008. if (e === ShortType)
  33009. return r.SHORT;
  33010. if (e === UnsignedShortType)
  33011. return r.UNSIGNED_SHORT;
  33012. if (e === IntType)
  33013. return r.INT;
  33014. if (e === UnsignedIntType)
  33015. return r.UNSIGNED_INT;
  33016. if (e === FloatType)
  33017. return r.FLOAT;
  33018. if (t = i.get("OES_texture_half_float"),
  33019. null !== t && e === HalfFloatType)
  33020. return t.HALF_FLOAT_OES;
  33021. if (e === AlphaFormat)
  33022. return r.ALPHA;
  33023. if (e === RGBFormat)
  33024. return r.RGB;
  33025. if (e === RGBAFormat)
  33026. return r.RGBA;
  33027. if (e === LuminanceFormat)
  33028. return r.LUMINANCE;
  33029. if (e === LuminanceAlphaFormat)
  33030. return r.LUMINANCE_ALPHA;
  33031. if (e === AddEquation)
  33032. return r.FUNC_ADD;
  33033. if (e === SubtractEquation)
  33034. return r.FUNC_SUBTRACT;
  33035. if (e === ReverseSubtractEquation)
  33036. return r.FUNC_REVERSE_SUBTRACT;
  33037. if (e === ZeroFactor)
  33038. return r.ZERO;
  33039. if (e === OneFactor)
  33040. return r.ONE;
  33041. if (e === SrcColorFactor)
  33042. return r.SRC_COLOR;
  33043. if (e === OneMinusSrcColorFactor)
  33044. return r.ONE_MINUS_SRC_COLOR;
  33045. if (e === SrcAlphaFactor)
  33046. return r.SRC_ALPHA;
  33047. if (e === OneMinusSrcAlphaFactor)
  33048. return r.ONE_MINUS_SRC_ALPHA;
  33049. if (e === DstAlphaFactor)
  33050. return r.DST_ALPHA;
  33051. if (e === OneMinusDstAlphaFactor)
  33052. return r.ONE_MINUS_DST_ALPHA;
  33053. if (e === DstColorFactor)
  33054. return r.DST_COLOR;
  33055. if (e === OneMinusDstColorFactor)
  33056. return r.ONE_MINUS_DST_COLOR;
  33057. if (e === SrcAlphaSaturateFactor)
  33058. return r.SRC_ALPHA_SATURATE;
  33059. if (t = i.get("WEBGL_compressed_texture_s3tc"),
  33060. null !== t) {
  33061. if (e === RGB_S3TC_DXT1_Format)
  33062. return t.COMPRESSED_RGB_S3TC_DXT1_EXT;
  33063. if (e === RGBA_S3TC_DXT1_Format$1)
  33064. return t.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  33065. if (e === RGBA_S3TC_DXT3_Format)
  33066. return t.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  33067. if (e === RGBA_S3TC_DXT5_Format$1)
  33068. return t.COMPRESSED_RGBA_S3TC_DXT5_EXT
  33069. }
  33070. if (t = i.get("WEBGL_compressed_texture_pvrtc"),
  33071. null !== t) {
  33072. if (e === RGB_PVRTC_4BPPV1_Format)
  33073. return t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  33074. if (e === RGB_PVRTC_2BPPV1_Format)
  33075. return t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  33076. if (e === RGBA_PVRTC_4BPPV1_Format)
  33077. return t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  33078. if (e === RGBA_PVRTC_2BPPV1_Format)
  33079. return t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG
  33080. }
  33081. if (t = i.get("WEBGL_compressed_texture_etc1"),
  33082. null !== t && e === RGB_ETC1_Format)
  33083. return t.COMPRESSED_RGB_ETC1_WEBGL;
  33084. if (t = i.get("EXT_blend_minmax"),
  33085. null !== t) {
  33086. if (e === MinEquation)
  33087. return t.MIN_EXT;
  33088. if (e === MaxEquation)
  33089. return t.MAX_EXT
  33090. }
  33091. return 0
  33092. };
  33093. /* ,
  33094. THREE.WebGLState = function(e, t, i) {
  33095. var r = this
  33096. , o = new THREE.Vector4
  33097. , a = e.getParameter(e.MAX_VERTEX_ATTRIBS)
  33098. , s = new Uint8Array(a)
  33099. , l = new Uint8Array(a)
  33100. , c = new Uint8Array(a)
  33101. , h = {}
  33102. , u = null
  33103. , d = null
  33104. , p = null
  33105. , f = null
  33106. , g = null
  33107. , m = null
  33108. , v = null
  33109. , A = null
  33110. , y = !1
  33111. , C = null
  33112. , I = null
  33113. , E = null
  33114. , b = null
  33115. , w = null
  33116. , _ = null
  33117. , T = null
  33118. , x = null
  33119. , S = null
  33120. , M = null
  33121. , R = null
  33122. , P = null
  33123. , O = null
  33124. , L = null
  33125. , D = null
  33126. , N = e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)
  33127. , B = void 0
  33128. , F = {}
  33129. , V = new THREE.Vector4
  33130. , U = null
  33131. , k = null
  33132. , H = new THREE.Vector4
  33133. , G = new THREE.Vector4;
  33134. this.init = function() {
  33135. this.clearColor(0, 0, 0, 1),
  33136. this.clearDepth(1),
  33137. this.clearStencil(0),
  33138. this.enable(e.DEPTH_TEST),
  33139. e.depthFunc(e.LEQUAL),
  33140. e.frontFace(e.CCW),
  33141. e.cullFace(e.BACK),
  33142. this.enable(e.CULL_FACE),
  33143. this.enable(e.BLEND),
  33144. e.blendEquation(e.FUNC_ADD),
  33145. e.blendFunc(e.SRC_ALPHA, e.ONE_MINUS_SRC_ALPHA)
  33146. }
  33147. ,
  33148. this.initAttributes = function() {
  33149. for (var e = 0, t = s.length; e < t; e++)
  33150. s[e] = 0
  33151. }
  33152. ,
  33153. this.enableAttribute = function(i) {
  33154. if (s[i] = 1,
  33155. 0 === l[i] && (e.enableVertexAttribArray(i),
  33156. l[i] = 1),
  33157. 0 !== c[i]) {
  33158. var n = t.get("ANGLE_instanced_arrays");
  33159. n.vertexAttribDivisorANGLE(i, 0),
  33160. c[i] = 0
  33161. }
  33162. }
  33163. ,
  33164. this.enableAttributeAndDivisor = function(t, i, n) {
  33165. s[t] = 1,
  33166. 0 === l[t] && (e.enableVertexAttribArray(t),
  33167. l[t] = 1),
  33168. c[t] !== i && (n.vertexAttribDivisorANGLE(t, i),
  33169. c[t] = i)
  33170. }
  33171. ,
  33172. this.disableUnusedAttributes = function() {
  33173. for (var t = 0, i = l.length; t < i; t++)
  33174. l[t] !== s[t] && (e.disableVertexAttribArray(t),
  33175. l[t] = 0)
  33176. }
  33177. ,
  33178. this.enable = function(t) {
  33179. h[t] !== !0 && (e.enable(t),
  33180. h[t] = !0)
  33181. }
  33182. ,
  33183. this.disable = function(t) {
  33184. h[t] !== !1 && (e.disable(t),
  33185. h[t] = !1)
  33186. }
  33187. ,
  33188. this.getCompressedTextureFormats = function() {
  33189. if (null === u && (u = [],
  33190. t.get("WEBGL_compressed_texture_pvrtc") || t.get("WEBGL_compressed_texture_s3tc") || t.get("WEBGL_compressed_texture_etc1")))
  33191. for (var i = e.getParameter(e.COMPRESSED_TEXTURE_FORMATS), n = 0; n < i.length; n++)
  33192. u.push(i[n]);
  33193. return u
  33194. }
  33195. ,
  33196. this.setBlending = function(t, r, o, a, s, l, c, h) {
  33197. t === THREE.NoBlending ? this.disable(e.BLEND) : this.enable(e.BLEND),
  33198. t === d && h === y || (t === THREE.AdditiveBlending ? h ? (e.blendEquationSeparate(e.FUNC_ADD, e.FUNC_ADD),
  33199. e.blendFuncSeparate(e.ONE, e.ONE, e.ONE, e.ONE)) : (e.blendEquation(e.FUNC_ADD),
  33200. e.blendFunc(e.SRC_ALPHA, e.ONE)) : t === THREE.SubtractiveBlending ? h ? (e.blendEquationSeparate(e.FUNC_ADD, e.FUNC_ADD),
  33201. e.blendFuncSeparate(e.ZERO, e.ZERO, e.ONE_MINUS_SRC_COLOR, e.ONE_MINUS_SRC_ALPHA)) : (e.blendEquation(e.FUNC_ADD),
  33202. e.blendFunc(e.ZERO, e.ONE_MINUS_SRC_COLOR)) : t === THREE.MultiplyBlending ? h ? (e.blendEquationSeparate(e.FUNC_ADD, e.FUNC_ADD),
  33203. e.blendFuncSeparate(e.ZERO, e.ZERO, e.SRC_COLOR, e.SRC_ALPHA)) : (e.blendEquation(e.FUNC_ADD),
  33204. e.blendFunc(e.ZERO, e.SRC_COLOR)) : h ? (e.blendEquationSeparate(e.FUNC_ADD, e.FUNC_ADD),
  33205. e.blendFuncSeparate(e.ONE, e.ONE_MINUS_SRC_ALPHA, e.ONE, e.ONE_MINUS_SRC_ALPHA)) : (e.blendEquationSeparate(e.FUNC_ADD, e.FUNC_ADD),
  33206. e.blendFuncSeparate(e.SRC_ALPHA, e.ONE_MINUS_SRC_ALPHA, e.ONE, e.ONE_MINUS_SRC_ALPHA)),
  33207. d = t,
  33208. y = h),
  33209. t === THREE.CustomBlending ? (s = s || r,
  33210. l = l || o,
  33211. c = c || a,
  33212. r === p && s === m || (e.blendEquationSeparate(i(r), i(s)),
  33213. p = r,
  33214. m = s),
  33215. o === f && a === g && l === v && c === A || (e.blendFuncSeparate(i(o), i(a), i(l), i(c)),
  33216. f = o,
  33217. g = a,
  33218. v = l,
  33219. A = c)) : (p = null,
  33220. f = null,
  33221. g = null,
  33222. m = null,
  33223. v = null,
  33224. A = null)
  33225. }
  33226. ,
  33227. this.setDepthFunc = function(t) {
  33228. if (C !== t) {
  33229. if (t)
  33230. switch (t) {
  33231. case THREE.NeverDepth:
  33232. e.depthFunc(e.NEVER);
  33233. break;
  33234. case THREE.AlwaysDepth:
  33235. e.depthFunc(e.ALWAYS);
  33236. break;
  33237. case THREE.LessDepth:
  33238. e.depthFunc(e.LESS);
  33239. break;
  33240. case THREE.LessEqualDepth:
  33241. e.depthFunc(e.LEQUAL);
  33242. break;
  33243. case THREE.EqualDepth:
  33244. e.depthFunc(e.EQUAL);
  33245. break;
  33246. case THREE.GreaterEqualDepth:
  33247. e.depthFunc(e.GEQUAL);
  33248. break;
  33249. case THREE.GreaterDepth:
  33250. e.depthFunc(e.GREATER);
  33251. break;
  33252. case THREE.NotEqualDepth:
  33253. e.depthFunc(e.NOTEQUAL);
  33254. break;
  33255. default:
  33256. e.depthFunc(e.LEQUAL)
  33257. }
  33258. else
  33259. e.depthFunc(e.LEQUAL);
  33260. C = t
  33261. }
  33262. }
  33263. ,
  33264. this.setDepthTest = function(t) {
  33265. t ? this.enable(e.DEPTH_TEST) : this.disable(e.DEPTH_TEST)
  33266. }
  33267. ,
  33268. this.setDepthWrite = function(t) {
  33269. I !== t && (e.depthMask(t),
  33270. I = t)
  33271. }
  33272. ,
  33273. this.setColorWrite = function(t) {
  33274. E !== t && (e.colorMask(t, t, t, t),
  33275. E = t)
  33276. }
  33277. ,
  33278. this.setStencilFunc = function(t, i, n) {
  33279. w === t && _ === i && T === n || (e.stencilFunc(t, i, n),
  33280. w = t,
  33281. _ = i,
  33282. T = n)
  33283. }
  33284. ,
  33285. this.setStencilOp = function(t, i, n) {
  33286. x === t && S === i && M === n || (e.stencilOp(t, i, n),
  33287. x = t,
  33288. S = i,
  33289. M = n)
  33290. }
  33291. ,
  33292. this.setStencilTest = function(t) {
  33293. t ? this.enable(e.STENCIL_TEST) : this.disable(e.STENCIL_TEST)
  33294. }
  33295. ,
  33296. this.setStencilWrite = function(t) {
  33297. b !== t && (e.stencilMask(t),
  33298. b = t)
  33299. }
  33300. ,
  33301. this.setFlipSided = function(t) {
  33302. R !== t && (t ? e.frontFace(e.CW) : e.frontFace(e.CCW),
  33303. R = t)
  33304. }
  33305. ,
  33306. this.setLineWidth = function(t) {
  33307. t !== P && (e.lineWidth(t),
  33308. P = t)
  33309. }
  33310. ,
  33311. this.setPolygonOffset = function(t, i, n) {
  33312. t ? this.enable(e.POLYGON_OFFSET_FILL) : this.disable(e.POLYGON_OFFSET_FILL),
  33313. !t || O === i && L === n || (e.polygonOffset(i, n),
  33314. O = i,
  33315. L = n)
  33316. }
  33317. ,
  33318. this.getScissorTest = function() {
  33319. return D
  33320. }
  33321. ,
  33322. this.setScissorTest = function(t) {
  33323. D = t,
  33324. t ? this.enable(e.SCISSOR_TEST) : this.disable(e.SCISSOR_TEST)
  33325. }
  33326. ,
  33327. this.activeTexture = function(t) {
  33328. void 0 === t && (t = e.TEXTURE0 + N - 1),
  33329. B !== t && (e.activeTexture(t),
  33330. B = t)
  33331. }
  33332. ,
  33333. this.bindTexture = function(t, i) {
  33334. void 0 === B && r.activeTexture();
  33335. var n = F[B];
  33336. void 0 === n && (n = {
  33337. type: void 0,
  33338. texture: void 0
  33339. },
  33340. F[B] = n),
  33341. n.type === t && n.texture === i || (e.bindTexture(t, i),
  33342. n.type = t,
  33343. n.texture = i)
  33344. }
  33345. ,
  33346. this.compressedTexImage2D = function() {
  33347. try {
  33348. e.compressedTexImage2D.apply(e, arguments)
  33349. } catch (e) {
  33350. console.error(e)
  33351. }
  33352. }
  33353. ,
  33354. this.texImage2D = function() {
  33355. try {
  33356. e.texImage2D.apply(e, arguments)
  33357. } catch (e) {
  33358. console.error(e)
  33359. }
  33360. }
  33361. ,
  33362. this.clearColor = function(t, i, n, r) {
  33363. o.set(t, i, n, r),
  33364. V.equals(o) === !1 && (e.clearColor(t, i, n, r),
  33365. V.copy(o))
  33366. }
  33367. ,
  33368. this.clearDepth = function(t) {
  33369. U !== t && (e.clearDepth(t),
  33370. U = t)
  33371. }
  33372. ,
  33373. this.clearStencil = function(t) {
  33374. k !== t && (e.clearStencil(t),
  33375. k = t)
  33376. }
  33377. ,
  33378. this.scissor = function(t) {
  33379. H.equals(t) === !1 && (e.scissor(t.x, t.y, t.z, t.w),
  33380. H.copy(t))
  33381. }
  33382. ,
  33383. this.viewport = function(t) {
  33384. G.equals(t) === !1 && (e.viewport(t.x, t.y, t.z, t.w),
  33385. G.copy(t))
  33386. }
  33387. ,
  33388. this.reset = function() {
  33389. for (var t = 0; t < l.length; t++)
  33390. 1 === l[t] && (e.disableVertexAttribArray(t),
  33391. l[t] = 0);
  33392. h = {},
  33393. u = null,
  33394. B = void 0,
  33395. F = {},
  33396. d = null,
  33397. E = null,
  33398. I = null,
  33399. b = null,
  33400. R = null
  33401. }
  33402. } */
  33403. const XHRFactory = {
  33404. config: {
  33405. withCredentials: false,
  33406. customHeaders: [
  33407. { header: null, value: null }
  33408. ]
  33409. },
  33410. createXMLHttpRequest: function () {
  33411. let xhr = new XMLHttpRequest();
  33412. if (this.config.customHeaders &&
  33413. Array.isArray(this.config.customHeaders) &&
  33414. this.config.customHeaders.length > 0) {
  33415. let baseOpen = xhr.open;
  33416. let customHeaders = this.config.customHeaders;
  33417. xhr.open = function () {
  33418. baseOpen.apply(this, [].slice.call(arguments));
  33419. customHeaders.forEach(function (customHeader) {
  33420. if (!!customHeader.header && !!customHeader.value) {
  33421. xhr.setRequestHeader(customHeader.header, customHeader.value);
  33422. }
  33423. });
  33424. };
  33425. }
  33426. return xhr;
  33427. }
  33428. };
  33429. let Shaders = {};
  33430. Shaders["pointcloud.vs"] = `
  33431. precision highp float;
  33432. precision highp int;
  33433. #define max_clip_polygons 8
  33434. #define PI 3.141592653589793
  33435. #if defined(usePanoMap)
  33436. uniform samplerCube pano0Map; //随便设置一个samplerCube去使用都会让点云消失
  33437. uniform samplerCube pano1Map;
  33438. uniform float progress;
  33439. uniform float easeInOutRatio;
  33440. uniform vec3 pano0Position;
  33441. uniform mat4 pano0Matrix;
  33442. uniform vec3 pano1Position;
  33443. uniform mat4 pano1Matrix;
  33444. /*
  33445. varying vec3 vWorldPosition0;
  33446. varying vec3 vWorldPosition1;
  33447. */
  33448. #endif
  33449. //--------------
  33450. attribute vec3 position;
  33451. attribute vec3 color;
  33452. attribute float intensity;
  33453. attribute float classification;
  33454. attribute float returnNumber;
  33455. attribute float numberOfReturns;
  33456. attribute float pointSourceID;
  33457. attribute vec4 indices; //每个点的index
  33458. attribute float spacing;
  33459. attribute float gpsTime;
  33460. attribute vec3 normal;
  33461. attribute float aExtra;
  33462. uniform mat4 modelMatrix;
  33463. uniform mat4 modelViewMatrix;
  33464. uniform mat4 projectionMatrix;
  33465. uniform mat4 viewMatrix;
  33466. uniform mat4 uViewInv;
  33467. //uniform float uScreenWidth;
  33468. //uniform float uScreenHeight;
  33469. uniform vec2 resolution;
  33470. uniform float fov;
  33471. uniform float near;
  33472. uniform float far;
  33473. uniform bool uDebug;
  33474. uniform bool uUseOrthographicCamera;
  33475. uniform float uOrthoWidth;
  33476. uniform float uOrthoHeight;
  33477. #define CLIPTASK_NONE 0
  33478. #define CLIPTASK_HIGHLIGHT 1
  33479. #define CLIPTASK_SHOW_INSIDE 2
  33480. #define CLIPTASK_SHOW_OUTSIDE 3
  33481. #define CLIPMETHOD_INSIDE_ANY 0
  33482. #define CLIPMETHOD_INSIDE_ALL 1
  33483. uniform int clipTask;
  33484. uniform int clipMethod;
  33485. #if defined(num_clipboxes) && num_clipboxes > 0
  33486. uniform mat4 clipBoxes[num_clipboxes];
  33487. #endif
  33488. #if defined(num_clipspheres) && num_clipspheres > 0
  33489. uniform mat4 uClipSpheres[num_clipspheres];
  33490. #endif
  33491. #if defined(num_clippolygons) && num_clippolygons > 0
  33492. uniform int uClipPolygonVCount[num_clippolygons];
  33493. uniform vec3 uClipPolygonVertices[num_clippolygons * 8];
  33494. uniform mat4 uClipPolygonWVP[num_clippolygons];
  33495. #endif
  33496. uniform float size;
  33497. uniform float minSize;
  33498. uniform float maxSize;
  33499. uniform float uPCIndex;
  33500. uniform float uOctreeSpacing;
  33501. uniform float uNodeSpacing;
  33502. uniform float uOctreeSize;
  33503. uniform vec3 uBBSize;
  33504. uniform float uLevel;
  33505. uniform float uVNStart;
  33506. uniform bool uIsLeafNode;
  33507. uniform vec3 uColor;
  33508. uniform float uOpacity;
  33509. varying float vOpacity; //add
  33510. uniform vec2 elevationRange;
  33511. uniform vec2 intensityRange;
  33512. uniform vec2 uFilterReturnNumberRange;
  33513. uniform vec2 uFilterNumberOfReturnsRange;
  33514. uniform vec2 uFilterPointSourceIDClipRange;
  33515. uniform vec2 uFilterGPSTimeClipRange;
  33516. //uniform float ufilterByNormalThreshold;
  33517. uniform float uGpsScale;
  33518. uniform float uGpsOffset;
  33519. uniform vec2 uNormalizedGpsBufferRange;
  33520. uniform vec3 uIntensity_gbc;
  33521. uniform vec3 uRGB_gbc;
  33522. uniform vec3 uExtra_gbc;
  33523. uniform float uTransition;
  33524. uniform float wRGB;
  33525. uniform float wIntensity;
  33526. uniform float wElevation;
  33527. uniform float wClassification;
  33528. uniform float wReturnNumber;
  33529. uniform float wSourceID;
  33530. uniform vec2 uExtraNormalizedRange;
  33531. uniform vec2 uExtraRange;
  33532. uniform float uExtraScale;
  33533. uniform float uExtraOffset;
  33534. uniform vec3 uShadowColor;
  33535. uniform sampler2D visibleNodes;
  33536. uniform sampler2D gradient;
  33537. uniform sampler2D classificationLUT;
  33538. #if defined(color_type_matcap)
  33539. uniform sampler2D matcapTextureUniform;
  33540. #endif
  33541. uniform bool backfaceCulling;
  33542. #if defined(num_shadowmaps) && num_shadowmaps > 0
  33543. uniform sampler2D uShadowMap[num_shadowmaps];
  33544. uniform mat4 uShadowWorldView[num_shadowmaps];
  33545. uniform mat4 uShadowProj[num_shadowmaps];
  33546. #endif
  33547. varying vec3 vColor;
  33548. varying float vLogDepth;
  33549. varying vec3 vViewPosition;
  33550. varying float vRadius;
  33551. varying float vPointSize;
  33552. float round(float number){
  33553. return floor(number + 0.5);
  33554. }
  33555. //
  33556. // ### ######## ### ######## ######## #### ## ## ######## ###### #### ######## ######## ######
  33557. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  33558. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  33559. // ## ## ## ## ## ## ######## ## ## ## ## ###### ###### ## ## ###### ######
  33560. // ######### ## ## ######### ## ## ## ## ## ## ## ## ## ## ##
  33561. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  33562. // ## ## ######## ## ## ## ## #### ### ######## ###### #### ######## ######## ######
  33563. //
  33564. // ---------------------
  33565. // OCTREE
  33566. // ---------------------
  33567. #if (defined(adaptive_point_size) || defined(color_type_level_of_detail)) && defined(tree_type_octree)
  33568. /**
  33569. * number of 1-bits up to inclusive index position
  33570. * number is treated as if it were an integer in the range 0-255
  33571. *
  33572. */
  33573. int numberOfOnes(int number, int index){
  33574. int numOnes = 0;
  33575. int tmp = 128;
  33576. for(int i = 7; i >= 0; i--){
  33577. if(number >= tmp){
  33578. number = number - tmp;
  33579. if(i <= index){
  33580. numOnes++;
  33581. }
  33582. }
  33583. tmp = tmp / 2;
  33584. }
  33585. return numOnes;
  33586. }
  33587. /**
  33588. * checks whether the bit at index is 1
  33589. * number is treated as if it were an integer in the range 0-255
  33590. *
  33591. */
  33592. bool isBitSet(int number, int index){
  33593. // weird multi else if due to lack of proper array, int and bitwise support in WebGL 1.0
  33594. int powi = 1;
  33595. if(index == 0){
  33596. powi = 1;
  33597. }else if(index == 1){
  33598. powi = 2;
  33599. }else if(index == 2){
  33600. powi = 4;
  33601. }else if(index == 3){
  33602. powi = 8;
  33603. }else if(index == 4){
  33604. powi = 16;
  33605. }else if(index == 5){
  33606. powi = 32;
  33607. }else if(index == 6){
  33608. powi = 64;
  33609. }else if(index == 7){
  33610. powi = 128;
  33611. }else{
  33612. return false;
  33613. }
  33614. int ndp = number / powi;
  33615. return mod(float(ndp), 2.0) != 0.0;
  33616. }
  33617. /**
  33618. * find the LOD at the point position
  33619. */
  33620. float getLOD(){//////
  33621. vec3 offset = vec3(0.0, 0.0, 0.0);
  33622. int iOffset = int(uVNStart);
  33623. float depth = uLevel;
  33624. for(float i = 0.0; i <= 30.0; i++){
  33625. float nodeSizeAtLevel = uOctreeSize / pow(2.0, i + uLevel + 0.0);
  33626. vec3 index3d = (position-offset) / nodeSizeAtLevel;
  33627. index3d = floor(index3d + 0.5);
  33628. int index = int(round(4.0 * index3d.x + 2.0 * index3d.y + index3d.z));
  33629. vec4 value = texture2D(visibleNodes, vec2(float(iOffset) / 2048.0, 0.0));
  33630. int mask = int(round(value.r * 255.0));
  33631. if(isBitSet(mask, index)){
  33632. // there are more visible child nodes at this position
  33633. int advanceG = int(round(value.g * 255.0)) * 256;
  33634. int advanceB = int(round(value.b * 255.0));
  33635. int advanceChild = numberOfOnes(mask, index - 1);
  33636. int advance = advanceG + advanceB + advanceChild;
  33637. iOffset = iOffset + advance;
  33638. depth++;
  33639. }else{
  33640. // no more visible child nodes at this position
  33641. //return value.a * 255.0;
  33642. float lodOffset = (255.0 * value.a) / 10.0 - 10.0;
  33643. return depth + lodOffset;
  33644. }
  33645. offset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;
  33646. }
  33647. return depth;
  33648. }
  33649. float getSpacing(){
  33650. vec3 offset = vec3(0.0, 0.0, 0.0);
  33651. int iOffset = int(uVNStart);
  33652. float depth = uLevel;
  33653. float spacing = uNodeSpacing;
  33654. for(float i = 0.0; i <= 30.0; i++){
  33655. float nodeSizeAtLevel = uOctreeSize / pow(2.0, i + uLevel + 0.0);
  33656. vec3 index3d = (position-offset) / nodeSizeAtLevel;
  33657. index3d = floor(index3d + 0.5);
  33658. int index = int(round(4.0 * index3d.x + 2.0 * index3d.y + index3d.z));
  33659. vec4 value = texture2D(visibleNodes, vec2(float(iOffset) / 2048.0, 0.0));
  33660. int mask = int(round(value.r * 255.0));
  33661. float spacingFactor = value.a;
  33662. if(i > 0.0){
  33663. spacing = spacing / (255.0 * spacingFactor);
  33664. }
  33665. if(isBitSet(mask, index)){
  33666. // there are more visible child nodes at this position
  33667. int advanceG = int(round(value.g * 255.0)) * 256;
  33668. int advanceB = int(round(value.b * 255.0));
  33669. int advanceChild = numberOfOnes(mask, index - 1);
  33670. int advance = advanceG + advanceB + advanceChild;
  33671. iOffset = iOffset + advance;
  33672. //spacing = spacing / (255.0 * spacingFactor);
  33673. //spacing = spacing / 3.0;
  33674. depth++;
  33675. }else{
  33676. // no more visible child nodes at this position
  33677. return spacing;
  33678. }
  33679. offset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;
  33680. }
  33681. return spacing;
  33682. }
  33683. float getPointSizeAttenuation(){
  33684. return pow(2.0, getLOD());
  33685. }
  33686. #endif
  33687. // ---------------------
  33688. // KD-TREE
  33689. // ---------------------
  33690. #if (defined(adaptive_point_size) || defined(color_type_level_of_detail)) && defined(tree_type_kdtree)
  33691. float getLOD(){
  33692. vec3 offset = vec3(0.0, 0.0, 0.0);
  33693. float iOffset = 0.0;
  33694. float depth = 0.0;
  33695. vec3 size = uBBSize;
  33696. vec3 pos = position;
  33697. for(float i = 0.0; i <= 1000.0; i++){
  33698. vec4 value = texture2D(visibleNodes, vec2(iOffset / 2048.0, 0.0));
  33699. int children = int(value.r * 255.0);
  33700. float next = value.g * 255.0;
  33701. int split = int(value.b * 255.0);
  33702. if(next == 0.0){
  33703. return depth;
  33704. }
  33705. vec3 splitv = vec3(0.0, 0.0, 0.0);
  33706. if(split == 1){
  33707. splitv.x = 1.0;
  33708. }else if(split == 2){
  33709. splitv.y = 1.0;
  33710. }else if(split == 4){
  33711. splitv.z = 1.0;
  33712. }
  33713. iOffset = iOffset + next;
  33714. float factor = length(pos * splitv / size);
  33715. if(factor < 0.5){
  33716. // left
  33717. if(children == 0 || children == 2){
  33718. return depth;
  33719. }
  33720. }else{
  33721. // right
  33722. pos = pos - size * splitv * 0.5;
  33723. if(children == 0 || children == 1){
  33724. return depth;
  33725. }
  33726. if(children == 3){
  33727. iOffset = iOffset + 1.0;
  33728. }
  33729. }
  33730. size = size * ((1.0 - (splitv + 1.0) / 2.0) + 0.5);
  33731. depth++;
  33732. }
  33733. return depth;
  33734. }
  33735. float getPointSizeAttenuation(){
  33736. return 0.5 * pow(1.3, getLOD());
  33737. }
  33738. #endif
  33739. //
  33740. // ### ######## ######## ######## #### ######## ## ## ######## ######## ######
  33741. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  33742. // ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  33743. // ## ## ## ## ######## ## ######## ## ## ## ###### ######
  33744. // ######### ## ## ## ## ## ## ## ## ## ## ## ##
  33745. // ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
  33746. // ## ## ## ## ## ## #### ######## ####### ## ######## ######
  33747. //
  33748. // formula adapted from: http://www.dfstudios.co.uk/articles/programming/image-programming-algorithms/image-processing-algorithms-part-5-contrast-adjustment/
  33749. float getContrastFactor(float contrast){
  33750. return (1.0158730158730156 * (contrast + 1.0)) / (1.0158730158730156 - contrast);
  33751. }
  33752. vec3 getRGB(){
  33753. vec3 rgb = color;
  33754. rgb = pow(rgb, vec3(uRGB_gbc.x));
  33755. rgb = rgb + uRGB_gbc.y;
  33756. rgb = (rgb - 0.5) * getContrastFactor(uRGB_gbc.z) + 0.5;
  33757. rgb = clamp(rgb, 0.0, 1.0);
  33758. return rgb;
  33759. }
  33760. float getIntensity(){
  33761. float w = (intensity - intensityRange.x) / (intensityRange.y - intensityRange.x);
  33762. w = pow(w, uIntensity_gbc.x);
  33763. w = w + uIntensity_gbc.y;
  33764. w = (w - 0.5) * getContrastFactor(uIntensity_gbc.z) + 0.5;
  33765. w = clamp(w, 0.0, 1.0);
  33766. return w;
  33767. }
  33768. vec3 getGpsTime(){
  33769. float w = (gpsTime + uGpsOffset) * uGpsScale;
  33770. vec3 c = texture2D(gradient, vec2(w, 1.0 - w)).rgb;
  33771. // vec2 r = uNormalizedGpsBufferRange;
  33772. // float w = gpsTime * (r.y - r.x) + r.x;
  33773. // w = clamp(w, 0.0, 1.0);
  33774. // vec3 c = texture2D(gradient, vec2(w,1.0-w)).rgb;
  33775. return c;
  33776. }
  33777. vec3 getElevation(){
  33778. vec4 world = modelMatrix * vec4( position, 1.0 );
  33779. float w = (world.z - elevationRange.x) / (elevationRange.y - elevationRange.x);
  33780. vec3 cElevation = texture2D(gradient, vec2(w,1.0-w)).rgb;
  33781. return cElevation;
  33782. }
  33783. vec4 getClassification(){
  33784. vec2 uv = vec2(classification / 255.0, 0.5);
  33785. vec4 classColor = texture2D(classificationLUT, uv);
  33786. return classColor;
  33787. }
  33788. vec3 getReturns(){
  33789. // 0b 00_000_111
  33790. float rn = mod(returnNumber, 8.0);
  33791. // 0b 00_111_000
  33792. float nr = mod(returnNumber / 8.0, 8.0);
  33793. if(nr <= 1.0){
  33794. return vec3(1.0, 0.0, 0.0);
  33795. }else{
  33796. return vec3(0.0, 1.0, 0.0);
  33797. }
  33798. // return vec3(nr / 4.0, 0.0, 0.0);
  33799. // if(nr == 1.0){
  33800. // return vec3(1.0, 1.0, 0.0);
  33801. // }else{
  33802. // if(rn == 1.0){
  33803. // return vec3(1.0, 0.0, 0.0);
  33804. // }else if(rn == nr){
  33805. // return vec3(0.0, 0.0, 1.0);
  33806. // }else{
  33807. // return vec3(0.0, 1.0, 0.0);
  33808. // }
  33809. // }
  33810. // if(numberOfReturns == 1.0){
  33811. // return vec3(1.0, 1.0, 0.0);
  33812. // }else{
  33813. // if(returnNumber == 1.0){
  33814. // return vec3(1.0, 0.0, 0.0);
  33815. // }else if(returnNumber == numberOfReturns){
  33816. // return vec3(0.0, 0.0, 1.0);
  33817. // }else{
  33818. // return vec3(0.0, 1.0, 0.0);
  33819. // }
  33820. // }
  33821. }
  33822. vec3 getReturnNumber(){
  33823. if(numberOfReturns == 1.0){
  33824. return vec3(1.0, 1.0, 0.0);
  33825. }else{
  33826. if(returnNumber == 1.0){
  33827. return vec3(1.0, 0.0, 0.0);
  33828. }else if(returnNumber == numberOfReturns){
  33829. return vec3(0.0, 0.0, 1.0);
  33830. }else{
  33831. return vec3(0.0, 1.0, 0.0);
  33832. }
  33833. }
  33834. }
  33835. vec3 getNumberOfReturns(){
  33836. float value = numberOfReturns;
  33837. float w = value / 6.0;
  33838. vec3 color = texture2D(gradient, vec2(w, 1.0 - w)).rgb;
  33839. return color;
  33840. }
  33841. vec3 getSourceID(){
  33842. float w = mod(pointSourceID, 10.0) / 10.0;
  33843. return texture2D(gradient, vec2(w,1.0 - w)).rgb;
  33844. }
  33845. vec3 getCompositeColor(){
  33846. vec3 c;
  33847. float w;
  33848. c += wRGB * getRGB();
  33849. w += wRGB;
  33850. c += wIntensity * getIntensity() * vec3(1.0, 1.0, 1.0);
  33851. w += wIntensity;
  33852. c += wElevation * getElevation();
  33853. w += wElevation;
  33854. c += wReturnNumber * getReturnNumber();
  33855. w += wReturnNumber;
  33856. c += wSourceID * getSourceID();
  33857. w += wSourceID;
  33858. vec4 cl = wClassification * getClassification();
  33859. c += cl.a * cl.rgb;
  33860. w += wClassification * cl.a;
  33861. c = c / w;
  33862. if(w == 0.0){
  33863. //c = color;
  33864. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  33865. }
  33866. return c;
  33867. }
  33868. vec3 getNormal(){
  33869. //vec3 n_hsv = vec3( modelMatrix * vec4( normal, 0.0 )) * 0.5 + 0.5; // (n_world.xyz + vec3(1.,1.,1.)) / 2.;
  33870. vec3 n_view = normalize( vec3(modelViewMatrix * vec4( normal, 0.0 )) );
  33871. return n_view;
  33872. }
  33873. bool applyBackfaceCulling() {
  33874. // Black not facing vertices / Backface culling
  33875. vec3 e = normalize(vec3(modelViewMatrix * vec4( position, 1. )));
  33876. vec3 n = getNormal(); // normalize( vec3(modelViewMatrix * vec4( normal, 0.0 )) );
  33877. if((uUseOrthographicCamera && n.z <= 0.) || (!uUseOrthographicCamera && dot( n, e ) >= 0.)) {
  33878. return true;
  33879. } else {
  33880. return false;
  33881. }
  33882. }
  33883. #if defined(color_type_matcap)
  33884. // Matcap Material
  33885. vec3 getMatcap(){
  33886. vec3 eye = normalize( vec3( modelViewMatrix * vec4( position, 1. ) ) );
  33887. if(uUseOrthographicCamera) {
  33888. eye = vec3(0., 0., -1.);
  33889. }
  33890. vec3 r_en = reflect( eye, getNormal() ); // or r_en = e - 2. * dot( n, e ) * n;
  33891. float m = 2. * sqrt(pow( r_en.x, 2. ) + pow( r_en.y, 2. ) + pow( r_en.z + 1., 2. ));
  33892. vec2 vN = r_en.xy / m + .5;
  33893. return texture2D(matcapTextureUniform, vN).rgb;
  33894. }
  33895. #endif
  33896. vec3 getExtra(){
  33897. float w = (aExtra + uExtraOffset) * uExtraScale;
  33898. w = clamp(w, 0.0, 1.0);
  33899. vec3 color = texture2D(gradient, vec2(w,1.0-w)).rgb;
  33900. // vec2 r = uExtraNormalizedRange;
  33901. // float w = aExtra * (r.y - r.x) + r.x;
  33902. // w = (w - uExtraRange.x) / (uExtraRange.y - uExtraRange.x);
  33903. // w = clamp(w, 0.0, 1.0);
  33904. // vec3 color = texture2D(gradient, vec2(w,1.0-w)).rgb;
  33905. return color;
  33906. }
  33907. vec3 getColor(){
  33908. vec3 color;
  33909. #ifdef color_type_rgba
  33910. color = getRGB();
  33911. #elif defined color_type_height || defined color_type_elevation
  33912. color = getElevation();
  33913. #elif defined color_type_rgb_height
  33914. vec3 cHeight = getElevation();
  33915. color = (1.0 - uTransition) * getRGB() + uTransition * cHeight;
  33916. #elif defined color_type_depth
  33917. float linearDepth = gl_Position.w;
  33918. float expDepth = (gl_Position.z / gl_Position.w) * 0.5 + 0.5;
  33919. color = vec3(linearDepth, expDepth, 0.0);
  33920. //color = vec3(1.0, 0.5, 0.3);
  33921. #elif defined color_type_intensity
  33922. float w = getIntensity();
  33923. color = vec3(w, w, w);
  33924. #elif defined color_type_gps_time
  33925. color = getGpsTime();
  33926. #elif defined color_type_intensity_gradient
  33927. float w = getIntensity();
  33928. color = texture2D(gradient, vec2(w,1.0-w)).rgb;
  33929. #elif defined color_type_color
  33930. color = uColor;
  33931. #elif defined color_type_level_of_detail
  33932. float depth = getLOD();
  33933. float w = depth / 10.0;
  33934. color = texture2D(gradient, vec2(w,1.0-w)).rgb;
  33935. #elif defined color_type_indices
  33936. color = indices.rgb;
  33937. #elif defined color_type_classification
  33938. vec4 cl = getClassification();
  33939. color = cl.rgb;
  33940. #elif defined color_type_return_number
  33941. color = getReturnNumber();
  33942. #elif defined color_type_returns
  33943. color = getReturns();
  33944. #elif defined color_type_number_of_returns
  33945. color = getNumberOfReturns();
  33946. #elif defined color_type_source_id
  33947. color = getSourceID();
  33948. #elif defined color_type_point_source_id
  33949. color = getSourceID();
  33950. #elif defined color_type_normal
  33951. color = (modelMatrix * vec4(normal, 0.0)).xyz;
  33952. #elif defined color_type_phong
  33953. color = color;
  33954. #elif defined color_type_composite
  33955. color = getCompositeColor();
  33956. #elif defined color_type_matcap
  33957. color = getMatcap();
  33958. #else
  33959. color = getExtra();
  33960. #endif
  33961. if (backfaceCulling && applyBackfaceCulling()){
  33962. //color = vec3(0.);
  33963. }
  33964. //applyBackfaceCulling直接返回false或者注释color = vec3(0.);都没问题
  33965. return color;
  33966. }
  33967. float getPointSize(){
  33968. float pointSize = 1.0;
  33969. float slope = tan(fov / 2.0);
  33970. float projFactor = -0.5 * resolution.y / (slope * vViewPosition.z);
  33971. /*
  33972. float scale = length(
  33973. modelViewMatrix * vec4(0, 0, 0, 1) -
  33974. modelViewMatrix * vec4(uOctreeSpacing, 0, 0, 1)
  33975. ) / uOctreeSpacing;
  33976. projFactor = projFactor * scale;
  33977. */
  33978. float r = uOctreeSpacing * 1.7;
  33979. //vRadius = r;
  33980. #if defined fixed_point_size
  33981. pointSize = size;
  33982. #elif defined attenuated_point_size
  33983. if(uUseOrthographicCamera){
  33984. pointSize = size * 10.0; //加个乘数
  33985. }else{ //近大远小,模拟真实mesh,边缘放大
  33986. //pointSize = size * spacing * projFactor; //spacing是attribute 为空 如果有这个值就能更自适应填补
  33987. //pointSize = size * uOctreeSpacing * projFactor / 18.0; //直接用cloud的spacing里,不过因为都一样所以可能没有什么意义
  33988. //pointSize = pointSize * projFactor;
  33989. pointSize = size * projFactor ;
  33990. }
  33991. #elif defined adaptive_point_size
  33992. if(uUseOrthographicCamera) {
  33993. float worldSpaceSize = 1.0 * size * r / getPointSizeAttenuation();
  33994. pointSize = (worldSpaceSize / uOrthoWidth) * resolution.x; //uScreenWidth;
  33995. } else {
  33996. float worldSpaceSize = 1.0 * size * r / getPointSizeAttenuation();
  33997. pointSize = worldSpaceSize * projFactor;
  33998. }
  33999. #endif
  34000. pointSize = max(minSize, pointSize);
  34001. pointSize = min(maxSize, pointSize);
  34002. vRadius = pointSize / projFactor;
  34003. return pointSize;
  34004. }
  34005. #if defined(num_clippolygons) && num_clippolygons > 0
  34006. bool pointInClipPolygon(vec3 point, int polyIdx) {
  34007. mat4 wvp = uClipPolygonWVP[polyIdx];
  34008. //vec4 screenClipPos = uClipPolygonVP[polyIdx] * modelMatrix * vec4(point, 1.0);
  34009. //screenClipPos.xy = screenClipPos.xy / screenClipPos.w * 0.5 + 0.5;
  34010. vec4 pointNDC = wvp * vec4(point, 1.0);
  34011. pointNDC.xy = pointNDC.xy / pointNDC.w;
  34012. int j = uClipPolygonVCount[polyIdx] - 1;
  34013. bool c = false;
  34014. for(int i = 0; i < 8; i++) {
  34015. if(i == uClipPolygonVCount[polyIdx]) {
  34016. break;
  34017. }
  34018. //vec4 verti = wvp * vec4(uClipPolygonVertices[polyIdx * 8 + i], 1);
  34019. //vec4 vertj = wvp * vec4(uClipPolygonVertices[polyIdx * 8 + j], 1);
  34020. //verti.xy = verti.xy / verti.w;
  34021. //vertj.xy = vertj.xy / vertj.w;
  34022. //verti.xy = verti.xy / verti.w * 0.5 + 0.5;
  34023. //vertj.xy = vertj.xy / vertj.w * 0.5 + 0.5;
  34024. vec3 verti = uClipPolygonVertices[polyIdx * 8 + i];
  34025. vec3 vertj = uClipPolygonVertices[polyIdx * 8 + j];
  34026. if( ((verti.y > pointNDC.y) != (vertj.y > pointNDC.y)) &&
  34027. (pointNDC.x < (vertj.x-verti.x) * (pointNDC.y-verti.y) / (vertj.y-verti.y) + verti.x) ) {
  34028. c = !c;
  34029. }
  34030. j = i;
  34031. }
  34032. return c;
  34033. }
  34034. #endif
  34035. void doClipping(){
  34036. {
  34037. vec4 cl = getClassification();
  34038. if(cl.a == 0.0){
  34039. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  34040. return;
  34041. }
  34042. }
  34043. #if defined(clip_return_number_enabled)
  34044. { // return number filter
  34045. vec2 range = uFilterReturnNumberRange;
  34046. if(returnNumber < range.x || returnNumber > range.y){
  34047. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  34048. return;
  34049. }
  34050. }
  34051. #endif
  34052. #if defined(clip_number_of_returns_enabled)
  34053. { // number of return filter
  34054. vec2 range = uFilterNumberOfReturnsRange;
  34055. if(numberOfReturns < range.x || numberOfReturns > range.y){
  34056. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  34057. return;
  34058. }
  34059. }
  34060. #endif
  34061. #if defined(clip_gps_enabled)
  34062. { // GPS time filter
  34063. float time = (gpsTime + uGpsOffset) * uGpsScale;
  34064. vec2 range = uFilterGPSTimeClipRange;
  34065. if(time < range.x || time > range.y){
  34066. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  34067. return;
  34068. }
  34069. }
  34070. #endif
  34071. #if defined(clip_point_source_id_enabled)
  34072. { // point source id filter
  34073. vec2 range = uFilterPointSourceIDClipRange;
  34074. if(pointSourceID < range.x || pointSourceID > range.y){
  34075. gl_Position = vec4(100.0, 100.0, 100.0, 0.0);
  34076. return;
  34077. }
  34078. }
  34079. #endif
  34080. int clipVolumesCount = 0;
  34081. int insideCount = 0;
  34082. #if defined(num_clipboxes) && num_clipboxes > 0
  34083. for(int i = 0; i < num_clipboxes; i++){
  34084. vec4 clipPosition = clipBoxes[i] * modelMatrix * vec4( position, 1.0 );
  34085. bool inside = -0.5 <= clipPosition.x && clipPosition.x <= 0.5;
  34086. inside = inside && -0.5 <= clipPosition.y && clipPosition.y <= 0.5;
  34087. inside = inside && -0.5 <= clipPosition.z && clipPosition.z <= 0.5;
  34088. insideCount = insideCount + (inside ? 1 : 0);
  34089. clipVolumesCount++;
  34090. }
  34091. #endif
  34092. #if defined(num_clippolygons) && num_clippolygons > 0
  34093. for(int i = 0; i < num_clippolygons; i++) {
  34094. bool inside = pointInClipPolygon(position, i);
  34095. insideCount = insideCount + (inside ? 1 : 0);
  34096. clipVolumesCount++;
  34097. }
  34098. #endif
  34099. bool insideAny = insideCount > 0;
  34100. bool insideAll = (clipVolumesCount > 0) && (clipVolumesCount == insideCount);
  34101. if(clipMethod == CLIPMETHOD_INSIDE_ANY){
  34102. if(insideAny && clipTask == CLIPTASK_HIGHLIGHT){
  34103. vColor.r += 0.5;
  34104. }else if(!insideAny && clipTask == CLIPTASK_SHOW_INSIDE){
  34105. gl_Position = vec4(100.0, 100.0, 100.0, 1.0);
  34106. }else if(insideAny && clipTask == CLIPTASK_SHOW_OUTSIDE){
  34107. gl_Position = vec4(100.0, 100.0, 100.0, 1.0);
  34108. }
  34109. }else if(clipMethod == CLIPMETHOD_INSIDE_ALL){
  34110. if(insideAll && clipTask == CLIPTASK_HIGHLIGHT){
  34111. vColor.r += 0.5;
  34112. }else if(!insideAll && clipTask == CLIPTASK_SHOW_INSIDE){
  34113. gl_Position = vec4(100.0, 100.0, 100.0, 1.0);
  34114. }else if(insideAll && clipTask == CLIPTASK_SHOW_OUTSIDE){
  34115. gl_Position = vec4(100.0, 100.0, 100.0, 1.0);
  34116. }
  34117. }
  34118. }
  34119. //
  34120. // ## ## ### #### ## ##
  34121. // ### ### ## ## ## ### ##
  34122. // #### #### ## ## ## #### ##
  34123. // ## ### ## ## ## ## ## ## ##
  34124. // ## ## ######### ## ## ####
  34125. // ## ## ## ## ## ## ###
  34126. // ## ## ## ## #### ## ##
  34127. //
  34128. vec2 getSamplerCoord( vec3 direction )
  34129. {
  34130. direction = normalize(direction);
  34131. float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;
  34132. float ty=acos(direction.z)/PI;
  34133. return vec2(tx,ty);
  34134. }
  34135. vec3 transformAxis( vec3 direction ) //navvis->4dkk
  34136. {
  34137. float y = direction.y;
  34138. direction.y = direction.z;
  34139. direction.z = -y;
  34140. return direction;
  34141. }
  34142. void main() {
  34143. //bool filtered_by_normal = false;
  34144. float normalZ = 0.0;
  34145. #ifdef use_filter_by_normal
  34146. /*if(abs(getNormal().z) > 0.4) { //ufilterByNormalThreshold 暂定 3
  34147. // Move point outside clip space space to discard it.
  34148. //gl_Position = vec4(0.0, 0.0, 2.0, 1.0); //gl_Position的可视区域是 x,y,z都是[-1,1]
  34149. //return;
  34150. //filtered_by_normal = true; //标记一下。不直接不绘制,因为有的法线都是垂直向上
  34151. }*/
  34152. normalZ = abs(getNormal().z);
  34153. #endif
  34154. vec4 mvPosition = modelViewMatrix * vec4(position, 1.0 );
  34155. vViewPosition = mvPosition.xyz;
  34156. gl_Position = projectionMatrix * mvPosition;
  34157. vLogDepth = log2(-mvPosition.z);
  34158. // COLOR
  34159. //加-------------------
  34160. #if defined(usePanoMap)
  34161. vec4 worldPosition = modelMatrix * vec4(position, 1.0);
  34162. vec3 positionLocalToPanoCenter0 = worldPosition.xyz - pano0Position;
  34163. vec3 vWorldPosition0 = (vec4(positionLocalToPanoCenter0, 1.0) * pano0Matrix).xyz;
  34164. vWorldPosition0.x *= -1.0;
  34165. vWorldPosition0 = transformAxis(vWorldPosition0);
  34166. vec3 positionLocalToPanoCenter1 = worldPosition.xyz - pano1Position;
  34167. vec3 vWorldPosition1 = (vec4(positionLocalToPanoCenter1, 1.0) * pano1Matrix).xyz;
  34168. vWorldPosition1.x *= -1.0;
  34169. vWorldPosition1 = transformAxis(vWorldPosition1);
  34170. /*
  34171. vec2 samplerCoord0 = getSamplerCoord(vWorldPosition0.xyz);
  34172. vec2 samplerCoord1 = getSamplerCoord(vWorldPosition1.xyz);
  34173. vec4 colorFromPano0 = texture2D(pano0Map,samplerCoord0);
  34174. vec4 colorFromPano1 = texture2D(pano1Map,samplerCoord1);
  34175. */
  34176. vec4 colorFromPano0=textureCube(pano0Map,vWorldPosition0.xyz);
  34177. vec4 colorFromPano1=textureCube(pano1Map,vWorldPosition1.xyz);
  34178. vColor = mix(colorFromPano0,colorFromPano1,progress).xyz;
  34179. //float easeInOutRatio = 0.0; //缓冲,渐变点云到贴图的颜色
  34180. if(progress < easeInOutRatio){
  34181. float easeProgress = (easeInOutRatio - progress) / easeInOutRatio;
  34182. vec3 vColor1 = getColor();
  34183. vColor = mix(vColor,vColor1,easeProgress);
  34184. }else if(progress > 1.0 - easeInOutRatio){
  34185. float easeProgress = (progress - (1.0 - easeInOutRatio) ) / easeInOutRatio;
  34186. vec3 vColor1 = getColor();
  34187. vColor = mix(vColor,vColor1,easeProgress);
  34188. }
  34189. #else
  34190. vColor = getColor();
  34191. #endif
  34192. //-------------------
  34193. #ifdef attenuated_opacity
  34194. //zoom不会改变z 所以这并不是用在分屏时候的
  34195. //vOpacity = uOpacity * exp(-length(-mvPosition.xyz) / 1000.0); // e为底的指数函数 opacityAttenuation = 1000
  34196. vOpacity = uOpacity * exp(gl_Position.z/50.0);
  34197. vOpacity = clamp(vOpacity, 0.001, 1.0);
  34198. /*if(filtered_by_normal){//垂直朝相机时降低透明度
  34199. vOpacity *= 0.2;
  34200. vOpacity = clamp(vOpacity, 0.0001, 0.1);
  34201. } */
  34202. #else
  34203. vOpacity = uOpacity;
  34204. /*if(filtered_by_normal){//垂直朝相机时降低透明度
  34205. /*if(filtered_by_normal){//垂直朝相机时降低透明度
  34206. vOpacity *= 0.3;
  34207. vOpacity = clamp(vOpacity, 0.0001, 0.1);
  34208. }*/
  34209. vOpacity *= max(0.1, (1.0 - normalZ));
  34210. #endif
  34211. // POINT SIZE
  34212. float pointSize = getPointSize();
  34213. gl_PointSize = pointSize;
  34214. vPointSize = pointSize;
  34215. // only for "replacing" approaches
  34216. // if(getLOD() != uLevel){
  34217. // gl_Position = vec4(10.0, 10.0, 10.0, 1.0);
  34218. // }
  34219. #if defined hq_depth_pass
  34220. float originalDepth = gl_Position.w;
  34221. float adjustedDepth = originalDepth + 2.0 * vRadius;
  34222. float adjust = adjustedDepth / originalDepth;
  34223. mvPosition.xyz = mvPosition.xyz * adjust;
  34224. gl_Position = projectionMatrix * mvPosition;
  34225. #endif
  34226. // CLIPPING
  34227. doClipping();
  34228. #if defined(num_clipspheres) && num_clipspheres > 0
  34229. for(int i = 0; i < num_clipspheres; i++){
  34230. vec4 sphereLocal = uClipSpheres[i] * mvPosition;
  34231. float distance = length(sphereLocal.xyz);
  34232. if(distance < 1.0){
  34233. float w = distance;
  34234. vec3 cGradient = texture2D(gradient, vec2(w, 1.0 - w)).rgb;
  34235. vColor = cGradient;
  34236. //vColor = cGradient * 0.7 + vColor * 0.3;
  34237. }
  34238. }
  34239. #endif
  34240. #if defined(num_shadowmaps) && num_shadowmaps > 0
  34241. const float sm_near = 0.1;
  34242. const float sm_far = 10000.0;
  34243. for(int i = 0; i < num_shadowmaps; i++){
  34244. vec3 viewPos = (uShadowWorldView[i] * vec4(position, 1.0)).xyz;
  34245. float distanceToLight = abs(viewPos.z);
  34246. vec4 projPos = uShadowProj[i] * uShadowWorldView[i] * vec4(position, 1);
  34247. vec3 nc = projPos.xyz / projPos.w;
  34248. float u = nc.x * 0.5 + 0.5;
  34249. float v = nc.y * 0.5 + 0.5;
  34250. vec2 sampleStep = vec2(1.0 / (2.0*1024.0), 1.0 / (2.0*1024.0)) * 1.5;
  34251. vec2 sampleLocations[9];
  34252. sampleLocations[0] = vec2(0.0, 0.0);
  34253. sampleLocations[1] = sampleStep;
  34254. sampleLocations[2] = -sampleStep;
  34255. sampleLocations[3] = vec2(sampleStep.x, -sampleStep.y);
  34256. sampleLocations[4] = vec2(-sampleStep.x, sampleStep.y);
  34257. sampleLocations[5] = vec2(0.0, sampleStep.y);
  34258. sampleLocations[6] = vec2(0.0, -sampleStep.y);
  34259. sampleLocations[7] = vec2(sampleStep.x, 0.0);
  34260. sampleLocations[8] = vec2(-sampleStep.x, 0.0);
  34261. float visibleSamples = 0.0;
  34262. float numSamples = 0.0;
  34263. float bias = vRadius * 2.0;
  34264. for(int j = 0; j < 9; j++){
  34265. vec4 depthMapValue = texture2D(uShadowMap[i], vec2(u, v) + sampleLocations[j]);
  34266. float linearDepthFromSM = depthMapValue.x + bias;
  34267. float linearDepthFromViewer = distanceToLight;
  34268. if(linearDepthFromSM > linearDepthFromViewer){
  34269. visibleSamples += 1.0;
  34270. }
  34271. numSamples += 1.0;
  34272. }
  34273. float visibility = visibleSamples / numSamples;
  34274. 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){
  34275. //vColor = vec3(0.0, 0.0, 0.2);
  34276. }else{
  34277. //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);
  34278. vColor = vColor * visibility + vColor * uShadowColor * (1.0 - visibility);
  34279. }
  34280. }
  34281. #endif
  34282. }
  34283. `;
  34284. Shaders["pointcloud.fs"] = `
  34285. #if defined paraboloid_point_shape
  34286. #extension GL_EXT_frag_depth : enable
  34287. #endif
  34288. #define PI 3.141592653589793
  34289. precision highp float;
  34290. precision highp int;
  34291. /*
  34292. #if defined(usePanoMap)
  34293. uniform samplerCube pano0Map; //随便设置一个samplerCube去使用都会让点云消失
  34294. uniform samplerCube pano1Map;
  34295. uniform float progress;
  34296. uniform float easeInOutRatio;
  34297. uniform vec3 pano0Position;
  34298. uniform mat4 pano0Matrix;
  34299. uniform vec3 pano1Position;
  34300. uniform mat4 pano1Matrix;
  34301. varying vec3 vWorldPosition0;
  34302. varying vec3 vWorldPosition1;
  34303. #endif
  34304. */
  34305. //------------
  34306. uniform mat4 viewMatrix;
  34307. uniform mat4 uViewInv;
  34308. uniform mat4 uProjInv;
  34309. uniform vec3 cameraPosition;
  34310. uniform mat4 projectionMatrix;
  34311. //uniform float uOpacity;
  34312. varying float vOpacity; //add
  34313. uniform float blendHardness;
  34314. uniform float blendDepthSupplement;
  34315. uniform float fov;
  34316. uniform float uSpacing;
  34317. uniform float near;
  34318. uniform float far;
  34319. uniform float uPCIndex;
  34320. uniform float uScreenWidth;
  34321. uniform float uScreenHeight;
  34322. varying vec3 vColor;
  34323. varying float vLogDepth;
  34324. varying vec3 vViewPosition;
  34325. varying float vRadius;
  34326. varying float vPointSize;
  34327. varying vec3 vPosition;
  34328. float specularStrength = 1.0;
  34329. vec2 getSamplerCoord( vec3 direction )
  34330. {
  34331. direction = normalize(direction);
  34332. float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;
  34333. float ty=acos(direction.z)/PI;
  34334. return vec2(tx,ty);
  34335. }
  34336. void main() {
  34337. vec3 color = vColor;
  34338. /*#if defined(usePanoMap) //加 经测试,即使全部写在fragment里也是无论pointsize多大都是一个点一个颜色,所以干脆写在vectex里
  34339. vec4 colorFromPano0=textureCube(pano0Map,vWorldPosition0.xyz);
  34340. vec4 colorFromPano1=textureCube(pano1Map,vWorldPosition1.xyz);
  34341. color = mix(colorFromPano0,colorFromPano1,progress).xyz;
  34342. //float easeInOutRatio = 0.0; //缓冲,渐变点云到贴图的颜色
  34343. if(progress < easeInOutRatio){
  34344. float easeProgress = (easeInOutRatio - progress) / easeInOutRatio;
  34345. color = mix(color,vColor,easeProgress);
  34346. }else if(progress > 1.0 - easeInOutRatio){
  34347. float easeProgress = (progress - (1.0 - easeInOutRatio) ) / easeInOutRatio;
  34348. color = mix(color,vColor,easeProgress);
  34349. }
  34350. #else
  34351. color = vColor;
  34352. #endif*/
  34353. float depth = gl_FragCoord.z;
  34354. #if defined(circle_point_shape) || defined(paraboloid_point_shape)
  34355. float u = 2.0 * gl_PointCoord.x - 1.0;
  34356. float v = 2.0 * gl_PointCoord.y - 1.0;
  34357. #endif
  34358. #if defined(circle_point_shape)
  34359. float cc = u*u + v*v;
  34360. if(cc > 1.0){
  34361. discard;
  34362. }
  34363. #endif
  34364. #if defined color_type_indices //pick point recognize
  34365. gl_FragColor = vec4(color, uPCIndex / 255.0); //uPCIndex : node Index
  34366. #else
  34367. gl_FragColor = vec4(color, vOpacity);
  34368. #endif
  34369. #if defined paraboloid_point_shape
  34370. float wi = 0.0 - ( u*u + v*v);
  34371. vec4 pos = vec4(vViewPosition, 1.0);
  34372. pos.z += wi * vRadius;
  34373. float linearDepth = -pos.z;
  34374. pos = projectionMatrix * pos;
  34375. pos = pos / pos.w;
  34376. float expDepth = pos.z;
  34377. depth = (pos.z + 1.0) / 2.0;
  34378. gl_FragDepthEXT = depth;
  34379. #if defined(color_type_depth)
  34380. color.r = linearDepth;
  34381. color.g = expDepth;
  34382. #endif
  34383. #if defined(use_edl)
  34384. gl_FragColor.a = log2(linearDepth);
  34385. #endif
  34386. #else
  34387. #if defined(use_edl)
  34388. gl_FragColor.a = vLogDepth;
  34389. #endif
  34390. #endif
  34391. #if defined(weighted_splats)
  34392. float distance = 2.0 * length(gl_PointCoord.xy - 0.5);
  34393. float weight = max(0.0, 1.0 - distance);
  34394. weight = pow(weight, 1.5);
  34395. gl_FragColor.a = weight;
  34396. gl_FragColor.xyz = gl_FragColor.xyz * weight;
  34397. #endif
  34398. //gl_FragColor = vec4(0.0, 0.7, 0.0, 1.0);
  34399. }
  34400. `;
  34401. Shaders["pointcloud_sm.vs"] = `
  34402. precision mediump float;
  34403. precision mediump int;
  34404. attribute vec3 position;
  34405. attribute vec3 color;
  34406. uniform mat4 modelMatrix;
  34407. uniform mat4 modelViewMatrix;
  34408. uniform mat4 projectionMatrix;
  34409. uniform mat4 viewMatrix;
  34410. uniform float uScreenWidth;
  34411. uniform float uScreenHeight;
  34412. uniform float near;
  34413. uniform float far;
  34414. uniform float uSpacing;
  34415. uniform float uOctreeSize;
  34416. uniform float uLevel;
  34417. uniform float uVNStart;
  34418. uniform sampler2D visibleNodes;
  34419. varying float vLinearDepth;
  34420. varying vec3 vColor;
  34421. #define PI 3.141592653589793
  34422. // ---------------------
  34423. // OCTREE
  34424. // ---------------------
  34425. #if defined(adaptive_point_size)
  34426. /**
  34427. * number of 1-bits up to inclusive index position
  34428. * number is treated as if it were an integer in the range 0-255
  34429. *
  34430. */
  34431. float numberOfOnes(float number, float index){
  34432. float tmp = mod(number, pow(2.0, index + 1.0));
  34433. float numOnes = 0.0;
  34434. for(float i = 0.0; i < 8.0; i++){
  34435. if(mod(tmp, 2.0) != 0.0){
  34436. numOnes++;
  34437. }
  34438. tmp = floor(tmp / 2.0);
  34439. }
  34440. return numOnes;
  34441. }
  34442. /**
  34443. * checks whether the bit at index is 1
  34444. * number is treated as if it were an integer in the range 0-255
  34445. *
  34446. */
  34447. bool isBitSet(float number, float index){
  34448. return mod(floor(number / pow(2.0, index)), 2.0) != 0.0;
  34449. }
  34450. /**
  34451. * find the LOD at the point position
  34452. */
  34453. float getLOD(){
  34454. vec3 offset = vec3(0.0, 0.0, 0.0);
  34455. float iOffset = uVNStart;
  34456. float depth = uLevel;
  34457. for(float i = 0.0; i <= 30.0; i++){
  34458. float nodeSizeAtLevel = uOctreeSize / pow(2.0, i + uLevel + 0.0);
  34459. vec3 index3d = (position-offset) / nodeSizeAtLevel;
  34460. index3d = floor(index3d + 0.5);
  34461. float index = 4.0 * index3d.x + 2.0 * index3d.y + index3d.z;
  34462. vec4 value = texture2D(visibleNodes, vec2(iOffset / 2048.0, 0.0));
  34463. float mask = value.r * 255.0;
  34464. if(isBitSet(mask, index)){
  34465. // there are more visible child nodes at this position
  34466. iOffset = iOffset + value.g * 255.0 * 256.0 + value.b * 255.0 + numberOfOnes(mask, index - 1.0);
  34467. depth++;
  34468. }else{
  34469. // no more visible child nodes at this position
  34470. return depth;
  34471. }
  34472. offset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;
  34473. }
  34474. return depth;
  34475. }
  34476. #endif
  34477. float getPointSize(){
  34478. float pointSize = 1.0;
  34479. float slope = tan(fov / 2.0);
  34480. float projFactor = -0.5 * uScreenHeight / (slope * vViewPosition.z);
  34481. float r = uOctreeSpacing * 1.5;
  34482. vRadius = r;
  34483. #if defined fixed_point_size
  34484. pointSize = size;
  34485. #elif defined attenuated_point_size
  34486. if(uUseOrthographicCamera){
  34487. pointSize = size;
  34488. }else{
  34489. pointSize = pointSize * projFactor;
  34490. }
  34491. #elif defined adaptive_point_size
  34492. if(uUseOrthographicCamera) {
  34493. float worldSpaceSize = 1.5 * size * r / getPointSizeAttenuation();
  34494. pointSize = (worldSpaceSize / uOrthoWidth) * uScreenWidth;
  34495. } else {
  34496. float worldSpaceSize = 1.5 * size * r / getPointSizeAttenuation();
  34497. pointSize = worldSpaceSize * projFactor;
  34498. }
  34499. #endif
  34500. pointSize = max(minSize, pointSize);
  34501. pointSize = min(maxSize, pointSize);
  34502. vRadius = pointSize / projFactor;
  34503. return pointSize;
  34504. }
  34505. void main() {
  34506. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  34507. vLinearDepth = gl_Position.w;
  34508. float pointSize = getPointSize();
  34509. gl_PointSize = pointSize;
  34510. }
  34511. `;
  34512. Shaders["pointcloud_sm.fs"] = `
  34513. precision mediump float;
  34514. precision mediump int;
  34515. varying vec3 vColor;
  34516. varying float vLinearDepth;
  34517. void main() {
  34518. //gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
  34519. //gl_FragColor = vec4(vColor, 1.0);
  34520. //gl_FragColor = vec4(vLinearDepth, pow(vLinearDepth, 2.0), 0.0, 1.0);
  34521. gl_FragColor = vec4(vLinearDepth, vLinearDepth / 30.0, vLinearDepth / 30.0, 1.0);
  34522. }
  34523. `;
  34524. Shaders["normalize.vs"] = `
  34525. precision mediump float;
  34526. precision mediump int;
  34527. attribute vec3 position;
  34528. attribute vec2 uv;
  34529. uniform mat4 projectionMatrix;
  34530. uniform mat4 modelViewMatrix;
  34531. varying vec2 vUv;
  34532. void main() {
  34533. vUv = uv;
  34534. gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
  34535. }`;
  34536. Shaders["normalize.fs"] = `
  34537. #extension GL_EXT_frag_depth : enable
  34538. precision mediump float;
  34539. precision mediump int;
  34540. uniform sampler2D uWeightMap;
  34541. uniform sampler2D uDepthMap;
  34542. varying vec2 vUv;
  34543. void main() {
  34544. float depth = texture2D(uDepthMap, vUv).r;
  34545. if(depth >= 1.0){
  34546. discard;
  34547. }
  34548. gl_FragColor = vec4(depth, 1.0, 0.0, 1.0);
  34549. vec4 color = texture2D(uWeightMap, vUv);
  34550. color = color / color.w;
  34551. gl_FragColor = vec4(color.xyz, 1.0);
  34552. gl_FragDepthEXT = depth;
  34553. }`;
  34554. Shaders["normalize_and_edl.fs"] = `
  34555. #extension GL_EXT_frag_depth : enable
  34556. //
  34557. // adapted from the EDL shader code from Christian Boucheny in cloud compare:
  34558. // https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL
  34559. //
  34560. precision mediump float;
  34561. precision mediump int;
  34562. uniform sampler2D uWeightMap;
  34563. uniform sampler2D uEDLMap;
  34564. uniform sampler2D uDepthMap;
  34565. uniform float screenWidth;
  34566. uniform float screenHeight;
  34567. uniform vec2 neighbours[NEIGHBOUR_COUNT];
  34568. uniform float edlStrength;
  34569. uniform float radius;
  34570. varying vec2 vUv;
  34571. float response(float depth){
  34572. vec2 uvRadius = radius / vec2(screenWidth, screenHeight);
  34573. float sum = 0.0;
  34574. for(int i = 0; i < NEIGHBOUR_COUNT; i++){
  34575. vec2 uvNeighbor = vUv + uvRadius * neighbours[i];
  34576. float neighbourDepth = texture2D(uEDLMap, uvNeighbor).a;
  34577. if(neighbourDepth != 0.0){
  34578. if(depth == 0.0){
  34579. sum += 100.0;
  34580. }else{
  34581. sum += max(0.0, depth - neighbourDepth);
  34582. }
  34583. }
  34584. }
  34585. return sum / float(NEIGHBOUR_COUNT);
  34586. }
  34587. void main() {
  34588. float edlDepth = texture2D(uEDLMap, vUv).a;
  34589. float res = response(edlDepth);
  34590. float shade = exp(-res * 300.0 * edlStrength);
  34591. float depth = texture2D(uDepthMap, vUv).r;
  34592. if(depth >= 1.0 && res == 0.0){
  34593. discard;
  34594. }
  34595. vec4 color = texture2D(uWeightMap, vUv);
  34596. color = color / color.w;
  34597. color = color * shade;
  34598. gl_FragColor = vec4(color.xyz, 1.0);
  34599. gl_FragDepthEXT = depth;
  34600. }`;
  34601. Shaders["edl.vs"] = `
  34602. precision mediump float;
  34603. precision mediump int;
  34604. attribute vec3 position;
  34605. attribute vec2 uv;
  34606. uniform mat4 projectionMatrix;
  34607. uniform mat4 modelViewMatrix;
  34608. varying vec2 vUv;
  34609. void main() {
  34610. vUv = uv;
  34611. vec4 mvPosition = modelViewMatrix * vec4(position,1.0);
  34612. gl_Position = projectionMatrix * mvPosition;
  34613. }`;
  34614. Shaders["edl.fs"] = `
  34615. #extension GL_EXT_frag_depth : enable
  34616. //
  34617. // adapted from the EDL shader code from Christian Boucheny in cloud compare:
  34618. // https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL
  34619. //
  34620. precision mediump float;
  34621. precision mediump int;
  34622. //uniform float screenWidth;
  34623. //uniform float screenHeight;
  34624. uniform vec2 resolution;
  34625. uniform vec2 neighbours[NEIGHBOUR_COUNT];
  34626. uniform float edlStrength;
  34627. uniform float radius;
  34628. uniform float opacity;
  34629. //uniform float uNear;
  34630. //uniform float uFar;
  34631. uniform mat4 uProj;
  34632. uniform sampler2D uEDLColor;
  34633. uniform sampler2D uEDLDepth;
  34634. varying vec2 vUv;
  34635. uniform int useEDL;
  34636. float response(float depth){
  34637. vec2 uvRadius = radius / resolution; //vec2(screenWidth, screenHeight);
  34638. float sum = 0.0;
  34639. for(int i = 0; i < NEIGHBOUR_COUNT; i++){
  34640. vec2 uvNeighbor = vUv + uvRadius * neighbours[i];
  34641. //获取周围八个格子的值
  34642. float neighbourDepth = texture2D(uEDLColor, uvNeighbor).a;
  34643. neighbourDepth = (neighbourDepth == 1.0) ? 0.0 : neighbourDepth;
  34644. if(neighbourDepth != 0.0){
  34645. //if(depth == 0.0){
  34646. // sum += 100.0;
  34647. //}else{
  34648. sum += max(0.0, depth - neighbourDepth); //获取差值
  34649. //}
  34650. }
  34651. }
  34652. return sum / float(NEIGHBOUR_COUNT);
  34653. }
  34654. void main(){
  34655. vec4 cEDL = texture2D(uEDLColor, vUv);
  34656. float depth = cEDL.a;
  34657. depth = (depth == 1.0) ? 0.0 : depth;
  34658. if(depth == 0.0){ //去掉这句就能在无点云像素的地方渲染outline,但会遮住其他mesh
  34659. discard;
  34660. }
  34661. if(useEDL == 1){
  34662. float res = response(depth);
  34663. //if(depth == 0.0 && res == 0.0){ //test
  34664. // discard;
  34665. //}
  34666. float shade = exp(-res * 300.0 * edlStrength); //自然常数e为底的指数函数
  34667. gl_FragColor = vec4(cEDL.rgb * shade, opacity);
  34668. //const vec3 outlineColor = vec3(1.0,0.0,0.0);//test -outline
  34669. //gl_FragColor = vec4(mix(cEDL.rgb, outlineColor, -res), opacity );
  34670. }else{//加 不改颜色的情况
  34671. gl_FragColor = vec4(cEDL.rgb, opacity);
  34672. }
  34673. { // write regular hyperbolic depth values to depth buffer 修改深度
  34674. float dl = pow(2.0, depth);
  34675. vec4 dp = uProj * vec4(0.0, 0.0, -dl, 1.0);
  34676. float pz = dp.z / dp.w;
  34677. float fragDepth = (pz + 1.0) / 2.0;
  34678. gl_FragDepthEXT = fragDepth;
  34679. }
  34680. }
  34681. `;
  34682. Shaders["blur.vs"] = `
  34683. varying vec2 vUv;
  34684. void main() {
  34685. vUv = uv;
  34686. gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
  34687. }`;
  34688. Shaders["blur.fs"] = `
  34689. uniform mat4 projectionMatrix;
  34690. uniform float screenWidth;
  34691. uniform float screenHeight;
  34692. uniform float near;
  34693. uniform float far;
  34694. uniform sampler2D map;
  34695. varying vec2 vUv;
  34696. void main() {
  34697. float dx = 1.0 / screenWidth;
  34698. float dy = 1.0 / screenHeight;
  34699. vec3 color = vec3(0.0, 0.0, 0.0);
  34700. color += texture2D(map, vUv + vec2(-dx, -dy)).rgb;
  34701. color += texture2D(map, vUv + vec2( 0, -dy)).rgb;
  34702. color += texture2D(map, vUv + vec2(+dx, -dy)).rgb;
  34703. color += texture2D(map, vUv + vec2(-dx, 0)).rgb;
  34704. color += texture2D(map, vUv + vec2( 0, 0)).rgb;
  34705. color += texture2D(map, vUv + vec2(+dx, 0)).rgb;
  34706. color += texture2D(map, vUv + vec2(-dx, dy)).rgb;
  34707. color += texture2D(map, vUv + vec2( 0, dy)).rgb;
  34708. color += texture2D(map, vUv + vec2(+dx, dy)).rgb;
  34709. color = color / 9.0;
  34710. gl_FragColor = vec4(color, 1.0);
  34711. }`;
  34712. Shaders["depthBasic.vs"] = `
  34713. varying vec2 vUv;
  34714. void main() {
  34715. vUv = uv;
  34716. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  34717. }
  34718. `;
  34719. Shaders["depthBasic.fs"] = `varying vec2 vUv;
  34720. uniform float opacity;
  34721. uniform vec3 baseColor;
  34722. uniform vec3 backColor;
  34723. uniform float occlusionDistance;
  34724. uniform float clipDistance;
  34725. uniform float maxClipFactor;
  34726. #if defined use_map
  34727. uniform sampler2D map;
  34728. #endif
  34729. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  34730. //似乎通过gl.getExtension('EXT_frag_depth')得到的GL_EXT_frag_depth
  34731. uniform sampler2D depthTexture;
  34732. uniform float nearPlane;
  34733. uniform float farPlane;
  34734. uniform vec2 resolution;
  34735. uniform vec2 viewportOffset; // viewportOffset 范围从0-整个画布的像素
  34736. float convertToLinear(float zValue)
  34737. {
  34738. float z = zValue * 2.0 - 1.0;
  34739. return (2.0 * nearPlane * farPlane) / (farPlane + nearPlane - z * (farPlane - nearPlane));
  34740. }
  34741. #endif
  34742. void main() {
  34743. vec4 color = vec4(baseColor, opacity);
  34744. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  34745. // mixFactor and clipFactor define the color mixing proportion between the states of
  34746. // full visibility and occluded visibility
  34747. // and
  34748. // full visibility and total invisibility
  34749. float mixFactor = 0.0;
  34750. float clipFactor = 0.0;
  34751. // The linear depth value of the current fragment
  34752. float fragDepth = convertToLinear(gl_FragCoord.z);
  34753. // The coordinates of the current fragment in the depth texture
  34754. vec2 depthTxtCoords = vec2(gl_FragCoord.x-viewportOffset.x, gl_FragCoord.y - viewportOffset.y) / resolution;
  34755. // The linear depth value of the pixel occupied by this fragment in the depth buffer
  34756. float textureDepth = convertToLinear(texture2D(depthTexture, depthTxtCoords).r);
  34757. // The difference between the two depths
  34758. float delta = fragDepth - textureDepth;
  34759. if (delta > 0.0)//差距
  34760. {
  34761. // occlusionDistance and clipDistance define the width of the respective zones and
  34762. // mixFactor and clipFactor express the interpolation between the two colors depending on the position
  34763. // of the current fragment withing those zones.
  34764. mixFactor = clamp(delta / occlusionDistance, 0.0, 1.0);
  34765. clipFactor = clamp(delta / clipDistance, 0.0, maxClipFactor);
  34766. }
  34767. // If the fragment is totally transparent, don't bother drawing it
  34768. if (clipFactor == 1.0)
  34769. {
  34770. discard;
  34771. }else{
  34772. #if defined use_map
  34773. color = texture2D(map, vUv) * color;
  34774. #endif
  34775. color = vec4(mix(color.rgb, backColor, mixFactor), color.a * (1.0 - clipFactor));
  34776. }
  34777. #else
  34778. #if defined use_map
  34779. color = texture2D(map, vUv) * color;
  34780. #endif
  34781. #endif
  34782. gl_FragColor = color;
  34783. }
  34784. `;
  34785. Shaders["copyCubeMap.vs"] = `varying vec3 vWorldPos;
  34786. vec3 transformAxis( vec3 direction ) //navvis->4dkk
  34787. {
  34788. float y = direction.y;
  34789. direction.y = direction.z;
  34790. direction.z = -y;
  34791. return direction;
  34792. }
  34793. void main() {
  34794. vWorldPos = vec3(-position.x, -position.y, position.z);
  34795. //vWorldPos = transformAxis(vWorldPos);
  34796. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  34797. }
  34798. `;
  34799. Shaders["copyCubeMap.fs"] = `varying vec3 vWorldPos;
  34800. uniform float alpha;
  34801. uniform samplerCube tDiffuse;
  34802. void main() {
  34803. vec4 texColor = textureCube(tDiffuse, vWorldPos);
  34804. gl_FragColor = vec4(texColor.rgb, texColor.a * alpha);
  34805. }
  34806. `;
  34807. Shaders["basicTextured.vs"] = `varying vec2 vUv;
  34808. void main() {
  34809. vUv = uv;
  34810. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  34811. }
  34812. `;
  34813. Shaders["basicTextured.fs"] = `varying vec2 vUv;
  34814. uniform float alpha;
  34815. uniform sampler2D tDiffuse;
  34816. void main() {
  34817. vec4 texColor = texture2D(tDiffuse, vUv);
  34818. gl_FragColor = vec4(texColor.rgb, texColor.a * alpha);
  34819. }
  34820. `;
  34821. let ftCanvas = document.createElement('canvas');
  34822. const Features = (function () {
  34823. let gl = ftCanvas.getContext('webgl') || ftCanvas.getContext('experimental-webgl');
  34824. if (gl === null){
  34825. return null;
  34826. }
  34827. // -- code taken from THREE.WebGLRenderer --
  34828. let _vertexShaderPrecisionHighpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT);
  34829. let _vertexShaderPrecisionMediumpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT);
  34830. // Unused: let _vertexShaderPrecisionLowpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_FLOAT);
  34831. let _fragmentShaderPrecisionHighpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT);
  34832. let _fragmentShaderPrecisionMediumpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT);
  34833. // Unused: let _fragmentShaderPrecisionLowpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT);
  34834. let highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  34835. let mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  34836. // -----------------------------------------
  34837. let precision;
  34838. if (highpAvailable) {
  34839. precision = 'highp';
  34840. } else if (mediumpAvailable) {
  34841. precision = 'mediump';
  34842. } else {
  34843. precision = 'lowp';
  34844. }
  34845. return {
  34846. SHADER_INTERPOLATION: {
  34847. isSupported: function () {
  34848. let supported = true;
  34849. supported = supported && gl.getExtension('EXT_frag_depth');
  34850. supported = supported && gl.getParameter(gl.MAX_VARYING_VECTORS) >= 8;
  34851. return supported;
  34852. }
  34853. },
  34854. SHADER_SPLATS: {
  34855. isSupported: function () {
  34856. let supported = true;
  34857. supported = supported && gl.getExtension('EXT_frag_depth');
  34858. supported = supported && gl.getExtension('OES_texture_float');
  34859. supported = supported && gl.getParameter(gl.MAX_VARYING_VECTORS) >= 8;
  34860. return supported;
  34861. }
  34862. },
  34863. SHADER_EDL: {
  34864. isSupported: function () {
  34865. let supported = true;
  34866. supported = supported && gl.getExtension('EXT_frag_depth');
  34867. supported = supported && gl.getExtension('OES_texture_float');
  34868. supported = supported && gl.getParameter(gl.MAX_VARYING_VECTORS) >= 8;
  34869. //supported = supported || (gl instanceof WebGL2RenderingContext);
  34870. return supported;
  34871. }
  34872. },
  34873. //add:
  34874. EXT_DEPTH:{
  34875. isSupported: function () {
  34876. if(browser.detectIOS()){
  34877. let {major,minor,patch} = browser.iosVersion();
  34878. if(major == 15 && minor == 4 && patch == 1){
  34879. console.warn('检测到是ios15.4.1, 关闭EXT_frag_depth');//该版本ext_depth有问题,导致clear错乱。没有解决办法先关闭。
  34880. return false
  34881. }
  34882. }
  34883. return gl.getExtension('EXT_frag_depth'); //shader中的GL_EXT_frag_depth需要判断一下detectIOS吗。。
  34884. }
  34885. },
  34886. //WEBGL2: {
  34887. // isSupported: function(){
  34888. // return gl instanceof WebGL2RenderingContext;
  34889. // }
  34890. //},
  34891. precision: precision
  34892. };
  34893. }());
  34894. class DepthBasicMaterial extends ShaderMaterial{
  34895. constructor(o={}){
  34896. let {width, height} = viewer.renderer.getSize(new Vector2$1());
  34897. let uniforms = {
  34898. resolution: { type: 'v2', value: new Vector2$1(width, height ) },
  34899. viewportOffset: { type: 'v2', value: new Vector2$1(0, 0 ) }, //left, top
  34900. nearPlane: { type: 'f', value: 0.1 },
  34901. farPlane: { type: 'f', value: 10000 },
  34902. depthTexture: { type: 't', value: null },
  34903. opacity: { type: 'f', value: 1 },
  34904. map: { type: 't', value: o.map },
  34905. baseColor: {type:'v3', value: o.color ? new Color(o.color) : new Color("#ffffff")},
  34906. backColor: {type:'v3', value: o.backColor ? new Color(o.backColor) : new Color("#ddd")},
  34907. clipDistance : { type: 'f', value:o.clipDistance || 4}, //消失距离
  34908. occlusionDistance : { type: 'f', value: o.occlusionDistance || 1 }, //变为backColor距离
  34909. maxClipFactor : { type: 'f', value: o.maxClipFactor || 1 }, //0-1
  34910. };
  34911. let defines = {};
  34912. let useDepth = o.useDepth && Features.EXT_DEPTH.isSupported();/* && Potree.settings.matUseDepth */
  34913. if(useDepth )defines.useDepth = '';
  34914. if(o.map)defines.use_map = '';
  34915. super({
  34916. uniforms,
  34917. vertexShader: Shaders['depthBasic.vs'],
  34918. fragmentShader: Shaders['depthBasic.fs'],
  34919. depthWrite: !1,
  34920. depthTest: !1,
  34921. transparent: o.transparent == void 0 ? true : o.transparent,
  34922. side: o.side || 0 /* THREE.DoubleSide */,
  34923. defines,
  34924. });
  34925. if(o.opacity != void 0){
  34926. this.opacity = o.opacity;
  34927. }
  34928. if(useDepth) this.useDepth_ = true;
  34929. if(this.useDepth){
  34930. let setSize = (e)=>{//如果出现横条状的异常,往往是viewportOffset出错
  34931. let viewport = e.viewport;
  34932. let viewportOffset = viewport.offset || new Vector2$1();
  34933. this.uniforms.resolution.value.copy(viewport.resolution2);
  34934. this.uniforms.viewportOffset.value.copy(viewportOffset);
  34935. //console.log('depth '+viewportOffset.toArray())
  34936. };
  34937. let viewport = viewer.mainViewport;
  34938. setSize( {viewport} );
  34939. viewer.addEventListener('resize',(e)=>{
  34940. if(!this.useDepth || !e.viewport || e.viewport.camera.isPerspectiveCamera){//地图不需要
  34941. setSize(e);
  34942. }
  34943. });
  34944. /* viewer.addEventListener('camera_changed', (e)=>{
  34945. if(e.viewport.name != 'mapViewport') this.updateDepthParams(e)
  34946. }) */
  34947. viewer.addEventListener("render.begin", (e)=>{//before render 如果有大于两个viewport的话,不同viewport用不同的depthTex
  34948. if(e.viewport.camera.isPerspectiveCamera) this.updateDepthParams(e);
  34949. });
  34950. this.updateDepthParams();
  34951. }
  34952. //点云变化时要一直触发updateDepthParams??
  34953. //viewer.once("render.pass.end",this.updateDepthParams.bind(this))
  34954. }
  34955. updateDepthParams(e={}){//主要用于点云遮住mesh
  34956. if(this.useDepth){
  34957. var viewport = e.viewport || viewer.mainViewport;
  34958. var camera = viewport.camera;
  34959. /* if(Potree.settings.displayMode == 'showPanos' && viewer.images360.currentPano.depthTex){
  34960. this.uniforms.depthTexture.value = viewer.images360.currentPano.depthTex
  34961. }else{ */
  34962. this.uniforms.depthTexture.value = viewer.getPRenderer().getRtEDL(viewport).depthTexture; //其实只赋值一次就行
  34963. //}
  34964. this.uniforms.nearPlane.value = camera.near;
  34965. this.uniforms.farPlane.value = camera.far;
  34966. }
  34967. }
  34968. set map(map){
  34969. this.uniforms.map.value = map;
  34970. }
  34971. get useDepth(){
  34972. return this.useDepth_
  34973. }
  34974. set useDepth(value){//如果不支持 EXT_DEPTH 的话会失效
  34975. if(this.useDepth_ != value){
  34976. if(value && Features.EXT_DEPTH.isSupported()){
  34977. this.defines.useDepth = '';
  34978. this.updateDepthParams();
  34979. }else {
  34980. delete this.defines.useDepth;
  34981. }
  34982. this.useDepth_ = value;
  34983. this.needsUpdate = true;
  34984. }
  34985. }
  34986. get opacity(){
  34987. return this.uniforms.opacity.value
  34988. }
  34989. set opacity(o){
  34990. this.uniforms && (this.uniforms.opacity.value = o);
  34991. }
  34992. /* dispose(){
  34993. super.dispose()
  34994. viewer.depthBasic
  34995. } */
  34996. }
  34997. const geo = new PlaneBufferGeometry(1,1);
  34998. class Sprite$1 extends Mesh{
  34999. constructor(options){
  35000. super(geo, options.mat || new DepthBasicMaterial({map:options.map, useDepth:options.useDepth}));
  35001. this.root = options.root || this;
  35002. this.renderOrder = options.renderOrder != void 0 ? options.renderOrder : 4;
  35003. this.pickOrder = options.pickOrder || 0;
  35004. this.sizeInfo = options.sizeInfo;
  35005. this.dontFixOrient = options.dontFixOrient;
  35006. this.root.matrixAutoUpdate = false;
  35007. this.matrixMap = new Map();
  35008. this.name = options.name || 'sprite';
  35009. this.useViewport = null;
  35010. this.viewports = options.viewports;//指定更新的viewports
  35011. this.visible_ = true;
  35012. let update = (e)=>{
  35013. this.update(e);
  35014. };
  35015. viewer.mapViewer && viewer.mapViewer.addEventListener("camera_changed", update);
  35016. viewer.addEventListener("camera_changed", update);
  35017. /* if(viewer.viewports.length == 1){//直接更新。如果有多个不在这更新,在"render.begin"
  35018. this.update(e)
  35019. } */
  35020. let applyMatrix = (e)=>{
  35021. this.applyMatrix(e);
  35022. };
  35023. viewer.addEventListener("raycaster", applyMatrix); //before render
  35024. viewer.addEventListener("render.begin", applyMatrix); //before render //magnifier时要禁止吗
  35025. this.addEventListener('dispose', ()=>{
  35026. viewer.mapViewer && viewer.mapViewer.removeEventListener("camera_changed", update);
  35027. viewer.removeEventListener("camera_changed", update);
  35028. viewer.removeEventListener("raycaster", applyMatrix); //before render
  35029. viewer.removeEventListener("render.begin", applyMatrix);
  35030. this.dispose();
  35031. });
  35032. }
  35033. set visible(v){
  35034. this.visible_ = v;
  35035. if(v){
  35036. this.update();
  35037. }
  35038. }
  35039. get visible(){
  35040. return this.visible_
  35041. }
  35042. realVisible(){
  35043. let parent = this;
  35044. let v;
  35045. while(parent){
  35046. if(parent.visible === false){
  35047. v = false;
  35048. break;
  35049. }
  35050. parent = parent.parent;
  35051. }
  35052. v = true;
  35053. if(!this.latestRealVisi && v){//变为可见后先update
  35054. this.latestRealVisi = true;
  35055. setTimeout(()=>{
  35056. this.update();
  35057. },1);//延迟 防止无限调用
  35058. return false
  35059. }
  35060. this.latestRealVisi = v;
  35061. return v;
  35062. }
  35063. update(e){
  35064. if(!e){
  35065. (this.viewports || viewer.viewports).forEach(view=>{
  35066. this.update({viewport:view});
  35067. });
  35068. return;
  35069. }
  35070. if(!this.root || ! this.realVisible() /* this.visible */ )return
  35071. if(this.viewports && !this.viewports.includes(e.viewport) )return
  35072. if(e.viewport.name == 'magnifier')return
  35073. let camera = e.viewport.camera;
  35074. //rotation
  35075. this.dontFixOrient || this.root.quaternion.copy(camera.quaternion);
  35076. //scale
  35077. var info = this.sizeInfo;
  35078. if(info){
  35079. this.root.updateMatrix();//先更新,getWorldPosition才能得到正确的
  35080. this.root.updateMatrixWorld(true);
  35081. var scale;
  35082. if(info.restricMeshScale){//仅限制最大或最小的话,不判断像素大小,直接限制mesh的scale
  35083. var dis = camera.position.distanceTo(this.root.getWorldPosition(new Vector3()));
  35084. if(dis < info.nearBound){
  35085. scale = info.scale * dis / info.nearBound;
  35086. }else {
  35087. scale = info.scale;
  35088. }
  35089. }else {
  35090. scale = math.getScaleForConstantSize($.extend(info,{//规定下最小最大像素
  35091. camera , position:this.root.getWorldPosition(new Vector3()) ,
  35092. resolution: e.viewport.resolution//2
  35093. }));
  35094. }
  35095. if(!isNaN(scale)){
  35096. this.root.scale.set(scale, scale, scale);
  35097. }
  35098. }
  35099. this.root.updateMatrix();
  35100. this.root.updateMatrixWorld(true);
  35101. this.matrixMap.set(e.viewport, this.root.matrix.clone());
  35102. this.useViewport = e.viewport;
  35103. }
  35104. applyMatrix(e){
  35105. if(!e)e = {viewport:viewer.mainViewport};//随便写一个viewport
  35106. if(e.viewport.name == 'magnifier')return
  35107. if(this.viewports && !this.viewports.includes(e.viewport) )return
  35108. if( !this.root || !this.realVisible() )return
  35109. var matrix = this.matrixMap.get(e.viewport);
  35110. if(!matrix){
  35111. this.update(e);
  35112. matrix = this.matrixMap.get(e.viewport);
  35113. }
  35114. if(e.viewport == this.useViewport){
  35115. return
  35116. }
  35117. this.useViewport = e.viewport;
  35118. this.root.matrix.copy(matrix);
  35119. this.root.updateMatrixWorld(true);
  35120. //console.log(this.root.name + e.viewport.name + " : "+this.root.matrixWorld.elements)
  35121. }
  35122. setUniforms(name,value){
  35123. this.material.setUniforms(name,value);
  35124. }
  35125. dispose(){
  35126. this.removeAllListeners();
  35127. this.parent && this.parent.remove(this);
  35128. }
  35129. }
  35130. //可能还是要用html写,因为要加按钮和图片
  35131. class TextSprite extends Object3D{
  35132. //注:为了分两层控制scale,不直接extend Sprite
  35133. constructor( options={}){
  35134. super();
  35135. let map = new Texture();
  35136. map.minFilter = LinearFilter;
  35137. map.magFilter = LinearFilter;
  35138. this.sprite = new Sprite$1( Object.assign({
  35139. root:this
  35140. }
  35141. ,options,
  35142. {
  35143. map,
  35144. })
  35145. );
  35146. this.add(this.sprite);
  35147. this.fontWeight = options.fontWeight == void 0 ? 'Bold' : options.fontWeight;
  35148. this.rectBorderThick = options.rectBorderThick || 0;
  35149. this.textBorderThick = options.textBorderThick || 0;
  35150. this.fontface = 'Arial';
  35151. this.fontsize = options.fontsize || 16;
  35152. this.textBorderColor = options.textBorderColor || { r: 0, g: 0, b: 0, a: 0.0 };
  35153. this.backgroundColor = options.backgroundColor || { r: 255, g: 255, b: 255, a: 1.0 };
  35154. this.textColor = options.textColor || {r: 0, g: 0, b: 0, a: 1.0};
  35155. this.borderColor = options.borderColor || { r: 0, g: 0, b: 0, a: 0.0 };
  35156. this.borderRadius = options.borderRadius || 6;
  35157. if(options.text != void 0)this.setText(options.text);
  35158. this.name = options.name;
  35159. //this.setText(text);
  35160. this.addEventListener('dispose', this.dispose.bind(this));
  35161. }
  35162. setText(text){
  35163. if (this.text !== text){
  35164. this.text = text + '';
  35165. this.updateTexture();
  35166. }
  35167. }
  35168. setTextColor(color){
  35169. this.textColor = color;
  35170. this.updateTexture();
  35171. }
  35172. setBorderColor(color){
  35173. this.borderColor = color;
  35174. this.updateTexture();
  35175. }
  35176. setBackgroundColor(color){
  35177. this.backgroundColor = color;
  35178. this.updateTexture();
  35179. }
  35180. setPos(pos){
  35181. this.position.copy(pos);
  35182. this.sprite.update();
  35183. }
  35184. update(){
  35185. this.sprite.update();
  35186. }
  35187. setVisible(v){
  35188. this.visible = v;
  35189. }
  35190. setUniforms(name,value){
  35191. this.sprite.setUniforms(name,value);
  35192. }
  35193. updateTexture(){
  35194. let canvas = document.createElement('canvas');
  35195. let context = canvas.getContext('2d');
  35196. context.font = this.fontWeight + ' ' + this.fontsize + 'px ' + this.fontface;
  35197. //context["font-weight"] = 100; //语法与 CSS font 属性相同。
  35198. // get size data (height depends only on font size)
  35199. //this.text = '啊啊啊啊啊啊fag'
  35200. let metrics = context.measureText(this.text );
  35201. let textWidth = metrics.width;
  35202. let margin = new Vector2$1(this.fontsize, Math.max( this.fontsize*0.4, 10) );
  35203. let spriteWidth = 2 * margin.x + textWidth + 2 * this.rectBorderThick;
  35204. let spriteHeight = 2 * margin.y + this.fontsize + 2 * this.rectBorderThick;
  35205. context.canvas.width = spriteWidth;
  35206. context.canvas.height = spriteHeight;
  35207. context.font = this.fontWeight + ' ' + this.fontsize + 'px ' + this.fontface;
  35208. let diff = 2;//针对英文大部分在baseLine之上所以降低一点(metrics.fontBoundingBoxAscent - metrics.fontBoundingBoxDescent) / 2
  35209. context.textBaseline = "middle";
  35210. // border color
  35211. context.strokeStyle = 'rgba(' + this.borderColor.r + ',' + this.borderColor.g + ',' +
  35212. this.borderColor.b + ',' + this.borderColor.a + ')';
  35213. context.lineWidth = this.rectBorderThick;
  35214. // background color
  35215. context.fillStyle = 'rgba(' + this.backgroundColor.r + ',' + this.backgroundColor.g + ',' +
  35216. this.backgroundColor.b + ',' + this.backgroundColor.a + ')';
  35217. this.roundRect(context, this.rectBorderThick / 2, this.rectBorderThick / 2,
  35218. spriteWidth - this.rectBorderThick, spriteHeight - this.rectBorderThick, this.borderRadius);
  35219. // text color
  35220. if(this.textBorderThick){
  35221. context.strokeStyle = 'rgba(' + this.textBorderColor.r + ',' + this.textBorderColor.g + ',' +
  35222. this.textBorderColor.b + ',' + this.textBorderColor.a + ')';
  35223. context.lineWidth = this.textBorderThick;
  35224. context.strokeText(this.text , this.rectBorderThick + margin.x,spriteHeight/2 + diff );
  35225. }
  35226. context.fillStyle = 'rgba(' + this.textColor.r + ',' + this.textColor.g + ',' +
  35227. this.textColor.b + ',' + this.textColor.a + ')';
  35228. context.fillText(this.text , this.rectBorderThick + margin.x, spriteHeight/2 + diff );//x,y
  35229. let texture = new Texture(canvas);
  35230. texture.minFilter = LinearFilter;
  35231. texture.magFilter = LinearFilter;
  35232. texture.needsUpdate = true;
  35233. //this.material.needsUpdate = true;
  35234. if(this.sprite.material.map){
  35235. this.sprite.material.map.dispose();
  35236. }
  35237. this.sprite.material.map = texture;
  35238. this.sprite.scale.set(spriteWidth * 0.01, spriteHeight * 0.01, 1.0);
  35239. }
  35240. roundRect(ctx, x, y, w, h, r){
  35241. ctx.beginPath();
  35242. ctx.moveTo(x + r, y);
  35243. ctx.lineTo(x + w - r, y);
  35244. ctx.arcTo(x + w, y, x + w, y + r, r );//圆弧。前四个参数同quadraticCurveTo
  35245. //ctx.quadraticCurveTo(x + w, y, x + w, y + r); //二次贝塞尔曲线需要两个点。第一个点是用于二次贝塞尔计算中的控制点,第二个点是曲线的结束点。
  35246. ctx.lineTo(x + w, y + h - r);
  35247. ctx.arcTo(x + w, y + h, x + w - r, y + h, r );
  35248. ctx.lineTo(x + r, y + h);
  35249. ctx.arcTo(x, y + h, x, y + h - r, r );
  35250. ctx.lineTo(x, y + r);
  35251. ctx.arcTo(x, y, x + r, y, r );
  35252. ctx.closePath();
  35253. ctx.fill();
  35254. ctx.stroke();
  35255. }
  35256. dispose(){
  35257. this.sprite.material.uniforms.map.value.dispose();
  35258. this.parent && this.parent.remove(this);
  35259. this.sprite.dispatchEvent({type:'dispose'});
  35260. this.removeAllListeners();
  35261. }
  35262. }
  35263. class Volume extends Object3D {
  35264. constructor (args = {}) {
  35265. super();
  35266. if(this.constructor.name === "Volume"){
  35267. console.warn("Can't create object of class Volume directly. Use classes BoxVolume or SphereVolume instead.");
  35268. }
  35269. //console.log(this);
  35270. //console.log(this.constructor);
  35271. //console.log(this.constructor.name);
  35272. this._clip = args.clip || false;
  35273. this._visible = true;
  35274. this._modifiable = args.modifiable || true;
  35275. { // event listeners
  35276. this.addEventListener('select', e => {});
  35277. this.addEventListener('deselect', e => {});
  35278. }
  35279. }
  35280. get visible(){
  35281. return this._visible;
  35282. }
  35283. set visible(value){
  35284. if(this._visible !== value){
  35285. this._visible = value;
  35286. this.dispatchEvent({type: "visibility_changed", object: this});
  35287. }
  35288. }
  35289. getVolume () {
  35290. console.warn("override this in subclass");
  35291. }
  35292. update () {
  35293. };
  35294. raycast (raycaster, intersects) {
  35295. }
  35296. get clip () {
  35297. return this._clip;
  35298. }
  35299. set clip (value) {
  35300. if(this._clip !== value){
  35301. this._clip = value;
  35302. this.update();
  35303. this.dispatchEvent({
  35304. type: "clip_changed",
  35305. object: this
  35306. });
  35307. }
  35308. }
  35309. get modifieable () {
  35310. return this._modifiable;
  35311. }
  35312. set modifieable (value) {
  35313. this._modifiable = value;
  35314. this.update();
  35315. }
  35316. };
  35317. class BoxVolume extends Volume{
  35318. constructor(args = {}){
  35319. super(args);
  35320. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  35321. this.name = 'box_' + this.constructor.counter;
  35322. let boxGeometry = new BoxGeometry(1, 1, 1);
  35323. boxGeometry.computeBoundingBox();
  35324. let boxFrameGeometry = new Geometry();
  35325. {
  35326. let Vector3$1 = Vector3;
  35327. boxFrameGeometry.vertices.push(
  35328. // bottom
  35329. new Vector3$1(-0.5, -0.5, 0.5),
  35330. new Vector3$1(0.5, -0.5, 0.5),
  35331. new Vector3$1(0.5, -0.5, 0.5),
  35332. new Vector3$1(0.5, -0.5, -0.5),
  35333. new Vector3$1(0.5, -0.5, -0.5),
  35334. new Vector3$1(-0.5, -0.5, -0.5),
  35335. new Vector3$1(-0.5, -0.5, -0.5),
  35336. new Vector3$1(-0.5, -0.5, 0.5),
  35337. // top
  35338. new Vector3$1(-0.5, 0.5, 0.5),
  35339. new Vector3$1(0.5, 0.5, 0.5),
  35340. new Vector3$1(0.5, 0.5, 0.5),
  35341. new Vector3$1(0.5, 0.5, -0.5),
  35342. new Vector3$1(0.5, 0.5, -0.5),
  35343. new Vector3$1(-0.5, 0.5, -0.5),
  35344. new Vector3$1(-0.5, 0.5, -0.5),
  35345. new Vector3$1(-0.5, 0.5, 0.5),
  35346. // sides
  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. new Vector3$1(0.5, -0.5, -0.5),
  35352. new Vector3$1(0.5, 0.5, -0.5),
  35353. new Vector3$1(-0.5, -0.5, -0.5),
  35354. new Vector3$1(-0.5, 0.5, -0.5),
  35355. );
  35356. }
  35357. this.material = new MeshBasicMaterial({
  35358. color: 0x00ff00,
  35359. transparent: true,
  35360. opacity: 0.3,
  35361. depthTest: true,
  35362. depthWrite: false});
  35363. this.box = new Mesh(boxGeometry, this.material);
  35364. this.box.geometry.computeBoundingBox();
  35365. this.boundingBox = this.box.geometry.boundingBox;
  35366. this.add(this.box);
  35367. this.frame = new LineSegments(boxFrameGeometry, new LineBasicMaterial({color: 0x000000}));
  35368. // this.frame.mode = THREE.Lines;
  35369. this.add(this.frame);
  35370. viewer.setObjectLayers(this, 'volume' );
  35371. this.update();
  35372. }
  35373. update(){
  35374. this.boundingBox = this.box.geometry.boundingBox;
  35375. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  35376. if (this._clip) {
  35377. this.box.visible = false;
  35378. } else {
  35379. this.box.visible = true;
  35380. }
  35381. }
  35382. raycast (raycaster, intersects) {
  35383. let is = [];
  35384. this.box.raycast(raycaster, is);
  35385. if (is.length > 0) {
  35386. let I = is[0];
  35387. intersects.push({
  35388. distance: I.distance,
  35389. object: this,
  35390. point: I.point.clone()
  35391. });
  35392. }
  35393. }
  35394. getVolume(){
  35395. return Math.abs(this.scale.x * this.scale.y * this.scale.z);
  35396. }
  35397. };
  35398. class SphereVolume extends Volume{
  35399. constructor(args = {}){
  35400. super(args);
  35401. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  35402. this.name = 'sphere_' + this.constructor.counter;
  35403. let sphereGeometry = new SphereGeometry(1, 32, 32);
  35404. sphereGeometry.computeBoundingBox();
  35405. this.material = new MeshBasicMaterial({
  35406. color: 0x00ff00,
  35407. transparent: true,
  35408. opacity: 0.3,
  35409. depthTest: true,
  35410. depthWrite: false});
  35411. this.sphere = new Mesh(sphereGeometry, this.material);
  35412. this.sphere.visible = false;
  35413. this.sphere.geometry.computeBoundingBox();
  35414. this.boundingBox = this.sphere.geometry.boundingBox;
  35415. this.add(this.sphere);
  35416. let frameGeometry = new Geometry();
  35417. {
  35418. let steps = 64;
  35419. let uSegments = 8;
  35420. let vSegments = 5;
  35421. let r = 1;
  35422. for(let uSegment = 0; uSegment < uSegments; uSegment++){
  35423. let alpha = (uSegment / uSegments) * Math.PI * 2;
  35424. let dirx = Math.cos(alpha);
  35425. let diry = Math.sin(alpha);
  35426. for(let i = 0; i <= steps; i++){
  35427. let v = (i / steps) * Math.PI * 2;
  35428. let vNext = v + 2 * Math.PI / steps;
  35429. let height = Math.sin(v);
  35430. let xyAmount = Math.cos(v);
  35431. let heightNext = Math.sin(vNext);
  35432. let xyAmountNext = Math.cos(vNext);
  35433. let vertex = new Vector3(dirx * xyAmount, diry * xyAmount, height);
  35434. frameGeometry.vertices.push(vertex);
  35435. let vertexNext = new Vector3(dirx * xyAmountNext, diry * xyAmountNext, heightNext);
  35436. frameGeometry.vertices.push(vertexNext);
  35437. }
  35438. }
  35439. // creates rings at poles, just because it's easier to implement
  35440. for(let vSegment = 0; vSegment <= vSegments + 1; vSegment++){
  35441. //let height = (vSegment / (vSegments + 1)) * 2 - 1; // -1 to 1
  35442. let uh = (vSegment / (vSegments + 1)); // -1 to 1
  35443. uh = (1 - uh) * (-Math.PI / 2) + uh *(Math.PI / 2);
  35444. let height = Math.sin(uh);
  35445. console.log(uh, height);
  35446. for(let i = 0; i <= steps; i++){
  35447. let u = (i / steps) * Math.PI * 2;
  35448. let uNext = u + 2 * Math.PI / steps;
  35449. let dirx = Math.cos(u);
  35450. let diry = Math.sin(u);
  35451. let dirxNext = Math.cos(uNext);
  35452. let diryNext = Math.sin(uNext);
  35453. let xyAmount = Math.sqrt(1 - height * height);
  35454. let vertex = new Vector3(dirx * xyAmount, diry * xyAmount, height);
  35455. frameGeometry.vertices.push(vertex);
  35456. let vertexNext = new Vector3(dirxNext * xyAmount, diryNext * xyAmount, height);
  35457. frameGeometry.vertices.push(vertexNext);
  35458. }
  35459. }
  35460. }
  35461. this.frame = new LineSegments(frameGeometry, new LineBasicMaterial({color: 0x000000}));
  35462. this.add(this.frame);
  35463. let frameMaterial = new MeshBasicMaterial({wireframe: true, color: 0x000000});
  35464. this.frame = new Mesh(sphereGeometry, frameMaterial);
  35465. //this.add(this.frame);
  35466. //this.frame = new THREE.LineSegments(boxFrameGeometry, new THREE.LineBasicMaterial({color: 0x000000}));
  35467. // this.frame.mode = THREE.Lines;
  35468. //this.add(this.frame);
  35469. this.update();
  35470. }
  35471. update(){
  35472. this.boundingBox = this.sphere.geometry.boundingBox;
  35473. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  35474. }
  35475. raycast (raycaster, intersects) {
  35476. let is = [];
  35477. this.sphere.raycast(raycaster, is);
  35478. if (is.length > 0) {
  35479. let I = is[0];
  35480. intersects.push({
  35481. distance: I.distance,
  35482. object: this,
  35483. point: I.point.clone()
  35484. });
  35485. }
  35486. }
  35487. // see https://en.wikipedia.org/wiki/Ellipsoid#Volume
  35488. getVolume(){
  35489. return (4 / 3) * Math.PI * this.scale.x * this.scale.y * this.scale.z;
  35490. }
  35491. };
  35492. class Profile extends Object3D{
  35493. constructor () {
  35494. super();
  35495. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  35496. this.name = 'Profile_' + this.constructor.counter;
  35497. this.points = [];
  35498. this.spheres = [];
  35499. this.edges = [];
  35500. this.boxes = [];
  35501. this.width = 1;
  35502. this.height = 20;
  35503. this._modifiable = true;
  35504. this.sphereGeometry = new SphereGeometry(0.4, 10, 10);
  35505. this.color = new Color(0xff0000);
  35506. this.lineColor = new Color(0xff0000);
  35507. }
  35508. createSphereMaterial () {
  35509. let sphereMaterial = new MeshLambertMaterial({
  35510. //shading: THREE.SmoothShading,
  35511. color: 0xff0000,
  35512. depthTest: false,
  35513. depthWrite: false}
  35514. );
  35515. return sphereMaterial;
  35516. };
  35517. getSegments () {
  35518. let segments = [];
  35519. for (let i = 0; i < this.points.length - 1; i++) {
  35520. let start = this.points[i].clone();
  35521. let end = this.points[i + 1].clone();
  35522. segments.push({start: start, end: end});
  35523. }
  35524. return segments;
  35525. }
  35526. getSegmentMatrices () {
  35527. let segments = this.getSegments();
  35528. let matrices = [];
  35529. for (let segment of segments) {
  35530. let {start, end} = segment;
  35531. let box = new Object3D();
  35532. let length;
  35533. if(window.axisYup){
  35534. length = start.clone().setY(0).distanceTo(end.clone().setY(0));
  35535. box.scale.set(length, 10000, this.width); //???
  35536. }else {
  35537. length = start.clone().setZ(0).distanceTo(end.clone().setZ(0));
  35538. box.scale.set(length, 10000, this.width);
  35539. box.up.set(0, 0, 1);
  35540. }
  35541. let center = new Vector3().addVectors(start, end).multiplyScalar(0.5);
  35542. let diff = new Vector3().subVectors(end, start);
  35543. let target = new Vector3(diff.y, -diff.x, 0);
  35544. box.position.set(0, 0, 0);
  35545. box.lookAt(target);
  35546. box.position.copy(center);
  35547. box.updateMatrixWorld();
  35548. matrices.push(box.matrixWorld);
  35549. }
  35550. return matrices;
  35551. }
  35552. addMarker (point) {
  35553. this.points.push(point);
  35554. let sphere = new Mesh(this.sphereGeometry, this.createSphereMaterial());
  35555. this.add(sphere);
  35556. this.spheres.push(sphere);
  35557. // edges & boxes
  35558. if (this.points.length > 1) {
  35559. let lineGeometry = new Geometry();
  35560. lineGeometry.vertices.push(new Vector3(), new Vector3());
  35561. lineGeometry.colors.push(this.lineColor, this.lineColor, this.lineColor);
  35562. let lineMaterial = new LineBasicMaterial({
  35563. vertexColors: VertexColors,
  35564. lineWidth: 2,
  35565. transparent: true,
  35566. opacity: 0.4
  35567. });
  35568. lineMaterial.depthTest = false;
  35569. let edge = new Line(lineGeometry, lineMaterial);
  35570. edge.visible = false;
  35571. this.add(edge);
  35572. this.edges.push(edge);
  35573. let boxGeometry = new BoxGeometry(1, 1, 1);
  35574. let boxMaterial = new MeshBasicMaterial({color: 0xff0000, transparent: true, opacity: 0.2});
  35575. let box = new Mesh(boxGeometry, boxMaterial);
  35576. box.visible = false;
  35577. this.add(box);
  35578. this.boxes.push(box);
  35579. }
  35580. { // event listeners
  35581. let drag = (e) => {
  35582. let I = Utils.getMousePointCloudIntersection(
  35583. e.drag.end,
  35584. e.viewer.scene.getActiveCamera(),
  35585. e.viewer,
  35586. e.viewer.scene.pointclouds);
  35587. if (I) {
  35588. let i = this.spheres.indexOf(e.drag.object);
  35589. if (i !== -1) {
  35590. this.setPosition(i, I.location);
  35591. //this.dispatchEvent({
  35592. // 'type': 'marker_moved',
  35593. // 'profile': this,
  35594. // 'index': i
  35595. //});
  35596. }
  35597. }
  35598. };
  35599. let drop = e => {
  35600. let i = this.spheres.indexOf(e.drag.object);
  35601. if (i !== -1) {
  35602. this.dispatchEvent({
  35603. 'type': 'marker_dropped',
  35604. 'profile': this,
  35605. 'index': i
  35606. });
  35607. }
  35608. };
  35609. let mouseover = (e) => e.object.material.emissive.setHex(0x888888);
  35610. let mouseleave = (e) => e.object.material.emissive.setHex(0x000000);
  35611. sphere.addEventListener('drag', drag);
  35612. sphere.addEventListener('drop', drop);
  35613. sphere.addEventListener('mouseover', mouseover);
  35614. sphere.addEventListener('mouseleave', mouseleave);
  35615. }
  35616. let event = {
  35617. type: 'marker_added',
  35618. profile: this,
  35619. sphere: sphere
  35620. };
  35621. this.dispatchEvent(event);
  35622. this.setPosition(this.points.length - 1, point);
  35623. }
  35624. removeMarker (index) {
  35625. this.points.splice(index, 1);
  35626. this.remove(this.spheres[index]);
  35627. let edgeIndex = (index === 0) ? 0 : (index - 1);
  35628. this.remove(this.edges[edgeIndex]);
  35629. this.edges.splice(edgeIndex, 1);
  35630. this.remove(this.boxes[edgeIndex]);
  35631. this.boxes.splice(edgeIndex, 1);
  35632. this.spheres.splice(index, 1);
  35633. this.update();
  35634. this.dispatchEvent({
  35635. 'type': 'marker_removed',
  35636. 'profile': this
  35637. });
  35638. }
  35639. setPosition (index, position) {
  35640. let point = this.points[index];
  35641. point.copy(position);
  35642. let event = {
  35643. type: 'marker_moved',
  35644. profile: this,
  35645. index: index,
  35646. position: point.clone()
  35647. };
  35648. this.dispatchEvent(event);
  35649. this.update();
  35650. }
  35651. setWidth (width) {
  35652. this.width = width;
  35653. let event = {
  35654. type: 'width_changed',
  35655. profile: this,
  35656. width: width
  35657. };
  35658. this.dispatchEvent(event);
  35659. this.update();
  35660. }
  35661. getWidth () {
  35662. return this.width;
  35663. }
  35664. update () {
  35665. if (this.points.length === 0) {
  35666. return;
  35667. } else if (this.points.length === 1) {
  35668. let point = this.points[0];
  35669. this.spheres[0].position.copy(point);
  35670. return;
  35671. }
  35672. let min = this.points[0].clone();
  35673. let max = this.points[0].clone();
  35674. let centroid = new Vector3();
  35675. let lastIndex = this.points.length - 1;
  35676. for (let i = 0; i <= lastIndex; i++) {
  35677. let point = this.points[i];
  35678. let sphere = this.spheres[i];
  35679. let leftIndex = (i === 0) ? lastIndex : i - 1;
  35680. // let rightIndex = (i === lastIndex) ? 0 : i + 1;
  35681. let leftVertex = this.points[leftIndex];
  35682. // let rightVertex = this.points[rightIndex];
  35683. let leftEdge = this.edges[leftIndex];
  35684. let rightEdge = this.edges[i];
  35685. let leftBox = this.boxes[leftIndex];
  35686. // rightBox = this.boxes[i];
  35687. // let leftEdgeLength = point.distanceTo(leftVertex);
  35688. // let rightEdgeLength = point.distanceTo(rightVertex);
  35689. // let leftEdgeCenter = new THREE.Vector3().addVectors(leftVertex, point).multiplyScalar(0.5);
  35690. // let rightEdgeCenter = new THREE.Vector3().addVectors(point, rightVertex).multiplyScalar(0.5);
  35691. sphere.position.copy(point);
  35692. if (this._modifiable) {
  35693. sphere.visible = true;
  35694. } else {
  35695. sphere.visible = false;
  35696. }
  35697. if (leftEdge) {
  35698. leftEdge.geometry.vertices[1].copy(point);
  35699. leftEdge.geometry.verticesNeedUpdate = true;
  35700. leftEdge.geometry.computeBoundingSphere();
  35701. }
  35702. if (rightEdge) {
  35703. rightEdge.geometry.vertices[0].copy(point);
  35704. rightEdge.geometry.verticesNeedUpdate = true;
  35705. rightEdge.geometry.computeBoundingSphere();
  35706. }
  35707. if (leftBox) {
  35708. let start = leftVertex;
  35709. let end = point;
  35710. let length;
  35711. if(window.axisYup){
  35712. length = start.clone().setY(0).distanceTo(end.clone().setY(0));
  35713. }else {
  35714. length = start.clone().setZ(0).distanceTo(end.clone().setZ(0));
  35715. leftBox.up.set(0, 0, 1);
  35716. }
  35717. leftBox.scale.set(length, 1000000, this.width);
  35718. let center = new Vector3().addVectors(start, end).multiplyScalar(0.5);
  35719. let diff = new Vector3().subVectors(end, start);
  35720. let target = new Vector3(diff.y, -diff.x, 0);
  35721. leftBox.position.set(0, 0, 0);
  35722. leftBox.lookAt(target);
  35723. leftBox.position.copy(center);
  35724. }
  35725. centroid.add(point);
  35726. min.min(point);
  35727. max.max(point);
  35728. }
  35729. centroid.multiplyScalar(1 / this.points.length);
  35730. for (let i = 0; i < this.boxes.length; i++) {
  35731. let box = this.boxes[i];
  35732. box.position.z = min.z + (max.z - min.z) / 2;
  35733. }
  35734. }
  35735. raycast (raycaster, intersects) {
  35736. for (let i = 0; i < this.points.length; i++) {
  35737. let sphere = this.spheres[i];
  35738. sphere.raycast(raycaster, intersects);
  35739. }
  35740. // recalculate distances because they are not necessarely correct
  35741. // for scaled objects.
  35742. // see https://github.com/mrdoob/three.js/issues/5827
  35743. // TODO: remove this once the bug has been fixed
  35744. for (let i = 0; i < intersects.length; i++) {
  35745. let I = intersects[i];
  35746. I.distance = raycaster.ray.origin.distanceTo(I.point);
  35747. }
  35748. intersects.sort(function (a, b) { return a.distance - b.distance; });
  35749. };
  35750. get modifiable () {
  35751. return this._modifiable;
  35752. }
  35753. set modifiable (value) {
  35754. this._modifiable = value;
  35755. this.update();
  35756. }
  35757. }
  35758. class Label extends EventDispatcher{
  35759. constructor(o={}){
  35760. super();
  35761. this.position = o.pos;
  35762. this.text = o.text || '';
  35763. this.elem = $('<div class="hide"><a></a></div>');
  35764. o.className && this.elem.addClass(o.className);
  35765. this.elem.find('a').html(this.text);
  35766. $("#potree_labels").append(this.elem);
  35767. this.pos2d = new Vector3;
  35768. this.dom = o.dom || viewer.renderArea;
  35769. this.camera = o.camera || viewer.scene.getActiveCamera();
  35770. let update = (e)=>{
  35771. this.update(e);
  35772. };
  35773. viewer.addEventListener('camera_changed', update);
  35774. this.addEventListener('dispose', ()=>{
  35775. viewer.removeEventListener('camera_changed', update);
  35776. this.dispose();
  35777. });
  35778. }
  35779. update(){
  35780. if(!this.position || this.elem.hasClass('unvisible'))return
  35781. var p = Utils.getPos2d(this.position,this.camera,this.dom, viewer.mainViewport);
  35782. if(!p.trueSide){
  35783. this.elem.addClass("hide"); return;
  35784. }
  35785. this.elem.css({
  35786. left: p.pos.x +'px',
  35787. top: p.pos.y +'px'
  35788. });
  35789. this.elem.removeClass("hide");
  35790. this.pos2d = p.vector;
  35791. }
  35792. setVisible(visi){
  35793. if(!visi){
  35794. this.elem.addClass("unvisible");
  35795. }else {
  35796. this.elem.removeClass("unvisible");
  35797. this.update();
  35798. }
  35799. }
  35800. setText(text){
  35801. this.text = text || '';
  35802. this.elem.find('a').html(this.text);
  35803. }
  35804. setPos(pos){
  35805. this.position = pos;
  35806. }
  35807. dispose(){
  35808. this.elem.remove();
  35809. this.removeAllListeners();
  35810. }
  35811. }
  35812. const _box$4 = new Box3();
  35813. const _vector$d = new Vector3();
  35814. class LineSegmentsGeometry extends InstancedBufferGeometry {
  35815. constructor() {
  35816. super();
  35817. this.isLineSegmentsGeometry = true;
  35818. this.type = 'LineSegmentsGeometry';
  35819. 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 ];
  35820. const uvs = [ - 1, 2, 1, 2, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 2, 1, - 2 ];
  35821. const index = [ 0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5 ];
  35822. this.setIndex( index );
  35823. this.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  35824. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  35825. }
  35826. applyMatrix4( matrix ) {
  35827. const start = this.attributes.instanceStart;
  35828. const end = this.attributes.instanceEnd;
  35829. if ( start !== undefined ) {
  35830. start.applyMatrix4( matrix );
  35831. end.applyMatrix4( matrix );
  35832. start.needsUpdate = true;
  35833. }
  35834. if ( this.boundingBox !== null ) {
  35835. this.computeBoundingBox();
  35836. }
  35837. if ( this.boundingSphere !== null ) {
  35838. this.computeBoundingSphere();
  35839. }
  35840. return this;
  35841. }
  35842. setPositions( array ) {
  35843. let lineSegments;
  35844. if ( array instanceof Float32Array ) {
  35845. lineSegments = array;
  35846. } else if ( Array.isArray( array ) ) {
  35847. lineSegments = new Float32Array( array );
  35848. }
  35849. const instanceBuffer = new InstancedInterleavedBuffer( lineSegments, 6, 1 ); // xyz, xyz
  35850. this.setAttribute( 'instanceStart', new InterleavedBufferAttribute( instanceBuffer, 3, 0 ) ); // xyz
  35851. this.setAttribute( 'instanceEnd', new InterleavedBufferAttribute( instanceBuffer, 3, 3 ) ); // xyz
  35852. //
  35853. this.computeBoundingBox();
  35854. this.computeBoundingSphere();
  35855. return this;
  35856. }
  35857. setColors( array ) {
  35858. let colors;
  35859. if ( array instanceof Float32Array ) {
  35860. colors = array;
  35861. } else if ( Array.isArray( array ) ) {
  35862. colors = new Float32Array( array );
  35863. }
  35864. const instanceColorBuffer = new InstancedInterleavedBuffer( colors, 6, 1 ); // rgb, rgb
  35865. this.setAttribute( 'instanceColorStart', new InterleavedBufferAttribute( instanceColorBuffer, 3, 0 ) ); // rgb
  35866. this.setAttribute( 'instanceColorEnd', new InterleavedBufferAttribute( instanceColorBuffer, 3, 3 ) ); // rgb
  35867. return this;
  35868. }
  35869. fromWireframeGeometry( geometry ) {
  35870. this.setPositions( geometry.attributes.position.array );
  35871. return this;
  35872. }
  35873. fromEdgesGeometry( geometry ) {
  35874. this.setPositions( geometry.attributes.position.array );
  35875. return this;
  35876. }
  35877. fromMesh( mesh ) {
  35878. this.fromWireframeGeometry( new WireframeGeometry( mesh.geometry ) );
  35879. // set colors, maybe
  35880. return this;
  35881. }
  35882. fromLineSegments( lineSegments ) {
  35883. const geometry = lineSegments.geometry;
  35884. this.setPositions( geometry.attributes.position.array ); // assumes non-indexed
  35885. // set colors, maybe
  35886. return this;
  35887. }
  35888. computeBoundingBox() {
  35889. if ( this.boundingBox === null ) {
  35890. this.boundingBox = new Box3();
  35891. }
  35892. const start = this.attributes.instanceStart;
  35893. const end = this.attributes.instanceEnd;
  35894. if ( start !== undefined && end !== undefined ) {
  35895. this.boundingBox.setFromBufferAttribute( start );
  35896. _box$4.setFromBufferAttribute( end );
  35897. this.boundingBox.union( _box$4 );
  35898. }
  35899. }
  35900. computeBoundingSphere() {
  35901. if ( this.boundingSphere === null ) {
  35902. this.boundingSphere = new Sphere();
  35903. }
  35904. if ( this.boundingBox === null ) {
  35905. this.computeBoundingBox();
  35906. }
  35907. const start = this.attributes.instanceStart;
  35908. const end = this.attributes.instanceEnd;
  35909. if ( start !== undefined && end !== undefined ) {
  35910. const center = this.boundingSphere.center;
  35911. this.boundingBox.getCenter( center );
  35912. let maxRadiusSq = 0;
  35913. for ( let i = 0, il = start.count; i < il; i ++ ) {
  35914. _vector$d.fromBufferAttribute( start, i );
  35915. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$d ) );
  35916. _vector$d.fromBufferAttribute( end, i );
  35917. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$d ) );
  35918. }
  35919. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  35920. if ( isNaN( this.boundingSphere.radius ) ) {
  35921. console.error( 'THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.', this );
  35922. }
  35923. }
  35924. }
  35925. toJSON() {
  35926. // todo
  35927. }
  35928. applyMatrix( matrix ) {
  35929. console.warn( 'THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4().' );
  35930. return this.applyMatrix4( matrix );
  35931. }
  35932. }
  35933. /**
  35934. * parameters = {
  35935. * color: <hex>,
  35936. * lineWidth: <float>,
  35937. * dashed: <boolean>,
  35938. * dashScale: <float>,
  35939. * dashSize: <float>,
  35940. * dashOffset: <float>,
  35941. * gapSize: <float>,
  35942. * resolution: <Vector2>, // to be set by renderer
  35943. * }
  35944. */
  35945. UniformsLib.line = {
  35946. /*
  35947. worldUnits: { value: 1 },
  35948. lineWidth: { value: 1 },
  35949. resolution: { value: new Vector2( 1, 1 ) },
  35950. dashOffset: { value: 0 },
  35951. dashScale: { value: 1 },
  35952. dashSize: { value: 1 },
  35953. gapSize: { value: 1 } // todo FIX - maybe change to totalSize
  35954. */
  35955. worldUnits: { value: 1 },
  35956. lineWidth: { value: 1 },
  35957. resolution: { value: new Vector2$1( 1, 1 ) },
  35958. viewportOffset: { value: new Vector2$1(0, 0 ) }, //left, top
  35959. dashScale: { value: 1 },
  35960. dashSize: { value: 1 },
  35961. dashOffset: { value: 0 },
  35962. gapSize: { value: 1 },
  35963. opacity: { value: 1 },
  35964. backColor: {type:'v3', value: new Color("#ddd")},
  35965. clipDistance : { type: 'f', value: 4}, //消失距离
  35966. occlusionDistance : { type: 'f', value: 1 }, //变为backColor距离
  35967. maxClipFactor : { type: 'f', value: 1 }, //0-1
  35968. depthTexture:{ value: null },
  35969. nearPlane:{value: 0.1},
  35970. farPlane:{value: 100000},
  35971. };
  35972. ShaderLib[ 'line' ] = {
  35973. uniforms: UniformsUtils.merge( [
  35974. UniformsLib.common,
  35975. UniformsLib.fog,
  35976. UniformsLib.line
  35977. ] ),
  35978. vertexShader:
  35979. /* glsl */`
  35980. #include <common>
  35981. #include <color_pars_vertex>
  35982. #include <fog_pars_vertex>
  35983. #include <logdepthbuf_pars_vertex>
  35984. #include <clipping_planes_pars_vertex>
  35985. uniform float lineWidth;
  35986. uniform vec2 resolution;
  35987. attribute vec3 instanceStart;
  35988. attribute vec3 instanceEnd;
  35989. attribute vec3 instanceColorStart;
  35990. attribute vec3 instanceColorEnd;
  35991. #ifdef WORLD_UNITS
  35992. varying vec4 worldPos;
  35993. varying vec3 worldStart;
  35994. varying vec3 worldEnd;
  35995. #ifdef USE_DASH
  35996. varying vec2 vUv;
  35997. #endif
  35998. #else
  35999. varying vec2 vUv;
  36000. #endif
  36001. #ifdef USE_DASH
  36002. uniform float dashScale;
  36003. attribute float instanceDistanceStart;
  36004. attribute float instanceDistanceEnd;
  36005. varying float vLineDistance;
  36006. #endif
  36007. void trimSegment( const in vec4 start, inout vec4 end ) {
  36008. // trim end segment so it terminates between the camera plane and the near plane
  36009. // conservative estimate of the near plane
  36010. float a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column
  36011. float b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column
  36012. float nearEstimate = - 0.5 * b / a;
  36013. float alpha = ( nearEstimate - start.z ) / ( end.z - start.z );
  36014. end.xyz = mix( start.xyz, end.xyz, alpha );
  36015. }
  36016. void main() {
  36017. #ifdef USE_COLOR
  36018. vColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;
  36019. #endif
  36020. #ifdef USE_DASH
  36021. vLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;
  36022. vUv = uv;
  36023. #endif
  36024. float aspect = resolution.x / resolution.y;
  36025. // camera space
  36026. vec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );
  36027. vec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );
  36028. #ifdef WORLD_UNITS
  36029. worldStart = start.xyz;
  36030. worldEnd = end.xyz;
  36031. #else
  36032. vUv = uv;
  36033. #endif
  36034. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  36035. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  36036. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  36037. // perhaps there is a more elegant solution -- WestLangley
  36038. bool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column
  36039. if ( perspective ) {
  36040. if ( start.z < 0.0 && end.z >= 0.0 ) {
  36041. trimSegment( start, end );
  36042. } else if ( end.z < 0.0 && start.z >= 0.0 ) {
  36043. trimSegment( end, start );
  36044. }
  36045. }
  36046. // clip space
  36047. vec4 clipStart = projectionMatrix * start;
  36048. vec4 clipEnd = projectionMatrix * end;
  36049. // ndc space
  36050. vec3 ndcStart = clipStart.xyz / clipStart.w;
  36051. vec3 ndcEnd = clipEnd.xyz / clipEnd.w;
  36052. // direction
  36053. vec2 dir = ndcEnd.xy - ndcStart.xy;
  36054. // account for clip-space aspect ratio
  36055. dir.x *= aspect;
  36056. dir = normalize( dir );
  36057. #ifdef WORLD_UNITS
  36058. // get the offset direction as perpendicular to the view vector
  36059. vec3 worldDir = normalize( end.xyz - start.xyz );
  36060. vec3 offset;
  36061. if ( position.y < 0.5 ) {
  36062. offset = normalize( cross( start.xyz, worldDir ) );
  36063. } else {
  36064. offset = normalize( cross( end.xyz, worldDir ) );
  36065. }
  36066. // sign flip
  36067. if ( position.x < 0.0 ) offset *= - 1.0;
  36068. float forwardOffset = dot( worldDir, vec3( 0.0, 0.0, 1.0 ) );
  36069. // don't extend the line if we're rendering dashes because we
  36070. // won't be rendering the endcaps
  36071. #ifndef USE_DASH
  36072. // extend the line bounds to encompass endcaps
  36073. start.xyz += - worldDir * lineWidth * 0.5;
  36074. end.xyz += worldDir * lineWidth * 0.5;
  36075. // shift the position of the quad so it hugs the forward edge of the line
  36076. offset.xy -= dir * forwardOffset;
  36077. offset.z += 0.5;
  36078. #endif
  36079. // endcaps
  36080. if ( position.y > 1.0 || position.y < 0.0 ) {
  36081. offset.xy += dir * 2.0 * forwardOffset;
  36082. }
  36083. // adjust for lineWidth
  36084. offset *= lineWidth * 0.5;
  36085. // set the world position
  36086. worldPos = ( position.y < 0.5 ) ? start : end;
  36087. worldPos.xyz += offset;
  36088. // project the worldpos
  36089. vec4 clip = projectionMatrix * worldPos;
  36090. // shift the depth of the projected points so the line
  36091. // segments overlap neatly
  36092. vec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;
  36093. clip.z = clipPose.z * clip.w;
  36094. #else
  36095. vec2 offset = vec2( dir.y, - dir.x );
  36096. // undo aspect ratio adjustment
  36097. dir.x /= aspect;
  36098. offset.x /= aspect;
  36099. // sign flip
  36100. if ( position.x < 0.0 ) offset *= - 1.0;
  36101. // endcaps
  36102. if ( position.y < 0.0 ) {
  36103. offset += - dir;
  36104. } else if ( position.y > 1.0 ) {
  36105. offset += dir;
  36106. }
  36107. // adjust for lineWidth
  36108. offset *= lineWidth;
  36109. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  36110. offset /= resolution.y;
  36111. // select end
  36112. vec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;
  36113. // back to clip space
  36114. offset *= clip.w;
  36115. clip.xy += offset;
  36116. #endif
  36117. gl_Position = clip;
  36118. vec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation
  36119. #include <logdepthbuf_vertex>
  36120. #include <clipping_planes_vertex>
  36121. #include <fog_vertex>
  36122. }
  36123. `,
  36124. fragmentShader:
  36125. /* glsl */`
  36126. uniform vec3 diffuse;
  36127. uniform float opacity;
  36128. uniform float lineWidth;
  36129. uniform vec3 backColor;
  36130. uniform float occlusionDistance;
  36131. uniform float clipDistance;
  36132. uniform float maxClipFactor;
  36133. #ifdef USE_DASH
  36134. uniform float dashOffset;
  36135. uniform float dashSize;
  36136. uniform float gapSize;
  36137. #endif
  36138. //加
  36139. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  36140. uniform sampler2D depthTexture;
  36141. uniform float nearPlane;
  36142. uniform float farPlane;
  36143. uniform vec2 resolution;
  36144. uniform vec2 viewportOffset;
  36145. #endif
  36146. varying float vLineDistance;
  36147. #ifdef WORLD_UNITS
  36148. varying vec4 worldPos;
  36149. varying vec3 worldStart;
  36150. varying vec3 worldEnd;
  36151. #ifdef USE_DASH
  36152. varying vec2 vUv;
  36153. #endif
  36154. #else
  36155. varying vec2 vUv;
  36156. #endif
  36157. #include <common>
  36158. #include <color_pars_fragment>
  36159. #include <fog_pars_fragment>
  36160. #include <logdepthbuf_pars_fragment>
  36161. #include <clipping_planes_pars_fragment>
  36162. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  36163. float convertToLinear(float zValue)
  36164. {
  36165. float z = zValue * 2.0 - 1.0;
  36166. return (2.0 * nearPlane * farPlane) / (farPlane + nearPlane - z * (farPlane - nearPlane));
  36167. }
  36168. #endif
  36169. vec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {
  36170. float mua;
  36171. float mub;
  36172. vec3 p13 = p1 - p3;
  36173. vec3 p43 = p4 - p3;
  36174. vec3 p21 = p2 - p1;
  36175. float d1343 = dot( p13, p43 );
  36176. float d4321 = dot( p43, p21 );
  36177. float d1321 = dot( p13, p21 );
  36178. float d4343 = dot( p43, p43 );
  36179. float d2121 = dot( p21, p21 );
  36180. float denom = d2121 * d4343 - d4321 * d4321;
  36181. float numer = d1343 * d4321 - d1321 * d4343;
  36182. mua = numer / denom;
  36183. mua = clamp( mua, 0.0, 1.0 );
  36184. mub = ( d1343 + d4321 * ( mua ) ) / d4343;
  36185. mub = clamp( mub, 0.0, 1.0 );
  36186. return vec2( mua, mub );
  36187. }
  36188. void main() {
  36189. #include <clipping_planes_fragment>
  36190. /*#ifdef USE_DASH
  36191. if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
  36192. if ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX
  36193. #endif*/
  36194. #ifdef USE_DASH
  36195. if ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps
  36196. bool unvisible = mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize;
  36197. //加
  36198. #ifdef DASH_with_depth
  36199. #else
  36200. if (unvisible) discard; // todo - FIX
  36201. #endif
  36202. #endif
  36203. float alpha = opacity;
  36204. #ifdef WORLD_UNITS
  36205. // Find the closest points on the view ray and the line segment
  36206. vec3 rayEnd = normalize( worldPos.xyz ) * 1e5;
  36207. vec3 lineDir = worldEnd - worldStart;
  36208. vec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );
  36209. vec3 p1 = worldStart + lineDir * params.x;
  36210. vec3 p2 = rayEnd * params.y;
  36211. vec3 delta = p1 - p2;
  36212. float len = length( delta );
  36213. float norm = len / lineWidth;
  36214. #ifndef USE_DASH
  36215. #ifdef USE_ALPHA_TO_COVERAGE
  36216. float dnorm = fwidth( norm );
  36217. alpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );
  36218. #else
  36219. if ( norm > 0.5 ) {
  36220. discard;
  36221. }
  36222. #endif
  36223. #endif
  36224. #else
  36225. #ifdef USE_ALPHA_TO_COVERAGE
  36226. // artifacts appear on some hardware if a derivative is taken within a conditional
  36227. float a = vUv.x;
  36228. float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
  36229. float len2 = a * a + b * b;
  36230. float dlen = fwidth( len2 );
  36231. if ( abs( vUv.y ) > 1.0 ) {
  36232. alpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );
  36233. }
  36234. #else
  36235. if ( abs( vUv.y ) > 1.0 ) {
  36236. float a = vUv.x;
  36237. float b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;
  36238. float len2 = a * a + b * b;
  36239. if ( len2 > 1.0 ) discard;
  36240. }
  36241. #endif
  36242. #endif
  36243. vec4 diffuseColor = vec4( diffuse, alpha );
  36244. //加
  36245. #if defined(GL_EXT_frag_depth) && defined(useDepth)
  36246. float mixFactor = 0.0;
  36247. float clipFactor = 0.0;
  36248. float fragDepth = convertToLinear(gl_FragCoord.z);
  36249. vec2 depthTxtCoords = vec2(gl_FragCoord.x - viewportOffset.x, gl_FragCoord.y - viewportOffset.y) / resolution;
  36250. float textureDepth = convertToLinear(texture2D(depthTexture, depthTxtCoords).r);
  36251. float delta = fragDepth - textureDepth;
  36252. if (delta > 0.0)
  36253. {
  36254. mixFactor = clamp(delta / occlusionDistance, 0.0, 1.0);
  36255. clipFactor = clamp(delta / clipDistance, 0.0, maxClipFactor);
  36256. }
  36257. if (clipFactor == 1.0)
  36258. {
  36259. discard;
  36260. }
  36261. vec4 backColor_ = vec4(backColor, opacity); //vec4(0.8,0.8,0.8, 0.8*opacity);
  36262. #ifdef DASH_with_depth
  36263. // 只在被遮住的部分显示虚线, 所以若同时是虚线不可见部分和被遮住时, a为0
  36264. if(unvisible) backColor_.a = 0.0;
  36265. #endif
  36266. //vec4 diffuseColor = vec4(mix(diffuse, backColor_, mixFactor), opacity*(1.0 - clipFactor));
  36267. diffuseColor = mix(diffuseColor, backColor_ , mixFactor);
  36268. diffuseColor.a *= (1.0 - clipFactor);
  36269. #endif
  36270. #include <logdepthbuf_fragment>
  36271. #include <color_fragment>
  36272. //gl_FragColor = vec4( diffuseColor.rgb, alpha );
  36273. gl_FragColor = vec4( diffuseColor.rgb, diffuseColor.a );
  36274. #include <tonemapping_fragment>
  36275. #include <encodings_fragment>
  36276. #include <fog_fragment>
  36277. #include <premultiplied_alpha_fragment>
  36278. }
  36279. `
  36280. };
  36281. class LineMaterial extends ShaderMaterial {
  36282. constructor( parameters ) {
  36283. super( {
  36284. type: 'LineMaterial',
  36285. uniforms: UniformsUtils.clone( ShaderLib[ 'line' ].uniforms ),
  36286. vertexShader: ShaderLib[ 'line' ].vertexShader,
  36287. fragmentShader: ShaderLib[ 'line' ].fragmentShader,
  36288. clipping: true // required for clipping support
  36289. } );
  36290. this.isLineMaterial = true;
  36291. this.lineWidth_ = 0;
  36292. this.supportExtDepth = parameters.supportExtDepth;
  36293. this.depthTestWhenPick = false; //pick时是否识别点云等
  36294. if(parameters.color){
  36295. this.color = new Color(parameters.color);
  36296. }
  36297. if(parameters.backColor){
  36298. this.uniforms.backColor.value = new Color(parameters.backColor);
  36299. }
  36300. if(parameters.clipDistance){
  36301. this.uniforms.clipDistance.value = parameters.clipDistance;
  36302. }
  36303. if(parameters.occlusionDistance){
  36304. this.uniforms.occlusionDistance.value = parameters.occlusionDistance;
  36305. }
  36306. if(parameters.maxClipFactor){
  36307. this.uniforms.maxClipFactor.value = parameters.maxClipFactor;
  36308. }
  36309. Object.defineProperties( this, {
  36310. color: {
  36311. enumerable: true,
  36312. get: function () {
  36313. return this.uniforms.diffuse.value;
  36314. },
  36315. set: function ( value ) {
  36316. this.uniforms.diffuse.value = value;
  36317. }
  36318. },
  36319. worldUnits: {
  36320. enumerable: true,
  36321. get: function () {
  36322. return 'WORLD_UNITS' in this.defines;
  36323. },
  36324. set: function ( value ) {
  36325. if ( value === true ) {
  36326. this.defines.WORLD_UNITS = '';
  36327. } else {
  36328. delete this.defines.WORLD_UNITS;
  36329. }
  36330. }
  36331. },
  36332. lineWidth: {
  36333. enumerable: true,
  36334. get: function () {
  36335. return this.lineWidth_;//this.uniforms.lineWidth.value;
  36336. },
  36337. set: function ( value ) {
  36338. this.uniforms.lineWidth.value = value * window.devicePixelRatio;
  36339. this.lineWidth_ = value;
  36340. }
  36341. },
  36342. dashed: {
  36343. enumerable: true,
  36344. get: function () {
  36345. return Boolean( 'USE_DASH' in this.defines );
  36346. },
  36347. set( value ) {
  36348. if ( Boolean( value ) !== Boolean( 'USE_DASH' in this.defines ) ) {
  36349. this.needsUpdate = true;
  36350. }
  36351. if ( value === true ) {
  36352. this.defines.USE_DASH = '';
  36353. } else {
  36354. delete this.defines.USE_DASH;
  36355. }
  36356. }
  36357. },
  36358. dashScale: {
  36359. enumerable: true,
  36360. get: function () {
  36361. return this.uniforms.dashScale.value;
  36362. },
  36363. set: function ( value ) {
  36364. this.uniforms.dashScale.value = value;
  36365. }
  36366. },
  36367. dashSize: {
  36368. enumerable: true,
  36369. get: function () {
  36370. return this.uniforms.dashSize.value;
  36371. },
  36372. set: function ( value ) {
  36373. this.uniforms.dashSize.value = value;
  36374. }
  36375. },
  36376. dashOffset: {
  36377. enumerable: true,
  36378. get: function () {
  36379. return this.uniforms.dashOffset.value;
  36380. },
  36381. set: function ( value ) {
  36382. this.uniforms.dashOffset.value = value;
  36383. }
  36384. },
  36385. gapSize: {
  36386. enumerable: true,
  36387. get: function () {
  36388. return this.uniforms.gapSize.value;
  36389. },
  36390. set: function ( value ) {
  36391. this.uniforms.gapSize.value = value;
  36392. }
  36393. },
  36394. opacity: {
  36395. enumerable: true,
  36396. get: function () {
  36397. return this.uniforms.opacity.value;
  36398. },
  36399. set: function ( value ) {
  36400. this.uniforms.opacity.value = value;
  36401. }
  36402. },
  36403. resolution: {
  36404. enumerable: true,
  36405. get: function () {
  36406. return this.uniforms.resolution.value;
  36407. },
  36408. set: function ( value ) {
  36409. this.uniforms.resolution.value.copy( value );
  36410. }
  36411. },
  36412. alphaToCoverage: {
  36413. enumerable: true,
  36414. get: function () {
  36415. return Boolean( 'USE_ALPHA_TO_COVERAGE' in this.defines );
  36416. },
  36417. set: function ( value ) {
  36418. if ( Boolean( value ) !== Boolean( 'USE_ALPHA_TO_COVERAGE' in this.defines ) ) {
  36419. this.needsUpdate = true;
  36420. }
  36421. if ( value === true ) {
  36422. this.defines.USE_ALPHA_TO_COVERAGE = '';
  36423. this.extensions.derivatives = true;
  36424. } else {
  36425. delete this.defines.USE_ALPHA_TO_COVERAGE;
  36426. this.extensions.derivatives = false;
  36427. }
  36428. }
  36429. }
  36430. ,
  36431. useDepth:{//add
  36432. enumerable: true,
  36433. get: function () {
  36434. return 'useDepth' in this.defines
  36435. },
  36436. set: function ( value ) {
  36437. value = value && !!this.supportExtDepth;
  36438. if(value != this.useDepth){
  36439. if(value){
  36440. this.defines.useDepth = '';
  36441. this.updateDepthParams();
  36442. }else {
  36443. delete this.defines.useDepth;
  36444. }
  36445. this.needsUpdate = true;
  36446. }
  36447. }
  36448. },
  36449. dashWithDepth:{//add
  36450. enumerable: true,
  36451. get: function () {
  36452. return 'DASH_with_depth' in this.defines
  36453. },
  36454. set: function ( value ) {
  36455. value = value && !!this.supportExtDepth;
  36456. if(value != this.dashWithDepth){
  36457. if(value){
  36458. this.defines.DASH_with_depth = '';
  36459. }else {
  36460. delete this.defines.DASH_with_depth;
  36461. }
  36462. this.needsUpdate = true;
  36463. }
  36464. }
  36465. },
  36466. } );
  36467. this.setValues( parameters );
  36468. let setSize = (e)=>{
  36469. let viewport = e.viewport;
  36470. let viewportOffset = viewport.offset || new Vector2$1();
  36471. this.uniforms.resolution.value.copy(viewport.resolution2);
  36472. this.uniforms.viewportOffset.value.copy(viewportOffset);
  36473. this.lineWidth = this.lineWidth_;
  36474. };
  36475. let viewport = viewer.mainViewport;
  36476. setSize({viewport});
  36477. viewer.addEventListener('resize',(e)=>{
  36478. setSize(e);
  36479. });
  36480. if(this.supportExtDepth){
  36481. //add
  36482. this.updateDepthParams();
  36483. /* viewer.addEventListener('camera_changed', (e)=>{
  36484. if(e.viewport.name != 'mapViewport') this.updateDepthParams(e)
  36485. }) */
  36486. viewer.addEventListener("render.begin", (e)=>{//before render 如果有大于两个viewport的话,不同viewport用不同的depthTex
  36487. if(e.viewport.camera.isPerspectiveCamera) this.updateDepthParams(e);
  36488. });
  36489. }
  36490. }
  36491. updateDepthParams(e={}){
  36492. if(this.useDepth){
  36493. var viewport = e.viewport || viewer.mainViewport;
  36494. var camera = viewport.camera;
  36495. this.uniforms.depthTexture.value = viewer.getPRenderer().getRtEDL(viewport).depthTexture; //viewer.getPRenderer().rtEDL.depthTexture
  36496. this.uniforms.nearPlane.value = camera.near; //似乎因为这个所以对OrthographicCamera 无效
  36497. this.uniforms.farPlane.value = camera.far;
  36498. }
  36499. }
  36500. }
  36501. const _start$2 = new Vector3();
  36502. const _end$2 = new Vector3();
  36503. const _start4 = new Vector4();
  36504. const _end4 = new Vector4();
  36505. const _ssOrigin = new Vector4();
  36506. const _ssOrigin3 = new Vector3();
  36507. const _mvMatrix = new Matrix4();
  36508. const _line = new Line3();
  36509. const _closestPoint = new Vector3();
  36510. const _box$5 = new Box3();
  36511. const _sphere$4 = new Sphere();
  36512. const _clipToWorldVector = new Vector4();
  36513. let _ray$3, _instanceStart, _instanceEnd, _lineWidth;
  36514. // Returns the margin required to expand by in world space given the distance from the camera,
  36515. // line width, resolution, and camera projection
  36516. function getWorldSpaceHalfWidth( camera, distance, resolution ) {
  36517. // transform into clip space, adjust the x and y values by the pixel width offset, then
  36518. // transform back into world space to get world offset. Note clip space is [-1, 1] so full
  36519. // width does not need to be halved.
  36520. _clipToWorldVector.set( 0, 0, - distance, 1.0 ).applyMatrix4( camera.projectionMatrix );
  36521. _clipToWorldVector.multiplyScalar( 1.0 / _clipToWorldVector.w );
  36522. _clipToWorldVector.x = _lineWidth / resolution.width;
  36523. _clipToWorldVector.y = _lineWidth / resolution.height;
  36524. _clipToWorldVector.applyMatrix4( camera.projectionMatrixInverse );
  36525. _clipToWorldVector.multiplyScalar( 1.0 / _clipToWorldVector.w );
  36526. return Math.abs( Math.max( _clipToWorldVector.x, _clipToWorldVector.y ) );
  36527. }
  36528. function raycastWorldUnits( lineSegments, intersects ) {
  36529. for ( let i = 0, l = _instanceStart.count; i < l; i ++ ) {
  36530. _line.start.fromBufferAttribute( _instanceStart, i );
  36531. _line.end.fromBufferAttribute( _instanceEnd, i );
  36532. const pointOnLine = new Vector3();
  36533. const point = new Vector3();
  36534. _ray$3.distanceSqToSegment( _line.start, _line.end, point, pointOnLine );
  36535. const isInside = point.distanceTo( pointOnLine ) < _lineWidth * 0.5;
  36536. if ( isInside ) {
  36537. intersects.push( {
  36538. point,
  36539. pointOnLine,
  36540. distance: _ray$3.origin.distanceTo( point ),
  36541. object: lineSegments,
  36542. face: null,
  36543. faceIndex: i,
  36544. uv: null,
  36545. uv2: null,
  36546. } );
  36547. }
  36548. }
  36549. }
  36550. function raycastScreenSpace( lineSegments, camera, intersects ) {
  36551. const projectionMatrix = camera.projectionMatrix;
  36552. const material = lineSegments.material;
  36553. const resolution = material.resolution;
  36554. const matrixWorld = lineSegments.matrixWorld;
  36555. const geometry = lineSegments.geometry;
  36556. const instanceStart = geometry.attributes.instanceStart;
  36557. const instanceEnd = geometry.attributes.instanceEnd;
  36558. const near = - camera.near;
  36559. //
  36560. // pick a point 1 unit out along the ray to avoid the ray origin
  36561. // sitting at the camera origin which will cause "w" to be 0 when
  36562. // applying the projection matrix.
  36563. _ray$3.at( 1, _ssOrigin );
  36564. // ndc space [ - 1.0, 1.0 ]
  36565. _ssOrigin.w = 1;
  36566. _ssOrigin.applyMatrix4( camera.matrixWorldInverse );
  36567. _ssOrigin.applyMatrix4( projectionMatrix );
  36568. _ssOrigin.multiplyScalar( 1 / _ssOrigin.w );
  36569. // screen space
  36570. _ssOrigin.x *= resolution.x / 2;
  36571. _ssOrigin.y *= resolution.y / 2;
  36572. _ssOrigin.z = 0;
  36573. _ssOrigin3.copy( _ssOrigin );
  36574. _mvMatrix.multiplyMatrices( camera.matrixWorldInverse, matrixWorld );
  36575. for ( let i = 0, l = instanceStart.count; i < l; i ++ ) {
  36576. _start4.fromBufferAttribute( instanceStart, i );
  36577. _end4.fromBufferAttribute( instanceEnd, i );
  36578. _start4.w = 1;
  36579. _end4.w = 1;
  36580. // camera space
  36581. _start4.applyMatrix4( _mvMatrix );
  36582. _end4.applyMatrix4( _mvMatrix );
  36583. // skip the segment if it's entirely behind the camera
  36584. const isBehindCameraNear = _start4.z > near && _end4.z > near;
  36585. if ( isBehindCameraNear ) {
  36586. continue;
  36587. }
  36588. // trim the segment if it extends behind camera near
  36589. if ( _start4.z > near ) {
  36590. const deltaDist = _start4.z - _end4.z;
  36591. const t = ( _start4.z - near ) / deltaDist;
  36592. _start4.lerp( _end4, t );
  36593. } else if ( _end4.z > near ) {
  36594. const deltaDist = _end4.z - _start4.z;
  36595. const t = ( _end4.z - near ) / deltaDist;
  36596. _end4.lerp( _start4, t );
  36597. }
  36598. // clip space
  36599. _start4.applyMatrix4( projectionMatrix );
  36600. _end4.applyMatrix4( projectionMatrix );
  36601. // ndc space [ - 1.0, 1.0 ]
  36602. _start4.multiplyScalar( 1 / _start4.w );
  36603. _end4.multiplyScalar( 1 / _end4.w );
  36604. // screen space
  36605. _start4.x *= resolution.x / 2;
  36606. _start4.y *= resolution.y / 2;
  36607. _end4.x *= resolution.x / 2;
  36608. _end4.y *= resolution.y / 2;
  36609. // create 2d segment
  36610. _line.start.copy( _start4 );
  36611. _line.start.z = 0;
  36612. _line.end.copy( _end4 );
  36613. _line.end.z = 0;
  36614. // get closest point on ray to segment
  36615. const param = _line.closestPointToPointParameter( _ssOrigin3, true );
  36616. _line.at( param, _closestPoint );
  36617. // check if the intersection point is within clip space
  36618. const zPos = MathUtils.lerp( _start4.z, _end4.z, param );
  36619. const isInClipSpace = zPos >= - 1 && zPos <= 1;
  36620. const isInside = _ssOrigin3.distanceTo( _closestPoint ) < _lineWidth * 0.5;
  36621. if ( isInClipSpace && isInside ) {
  36622. _line.start.fromBufferAttribute( instanceStart, i );
  36623. _line.end.fromBufferAttribute( instanceEnd, i );
  36624. _line.start.applyMatrix4( matrixWorld );
  36625. _line.end.applyMatrix4( matrixWorld );
  36626. const pointOnLine = new Vector3();
  36627. const point = new Vector3();
  36628. _ray$3.distanceSqToSegment( _line.start, _line.end, point, pointOnLine );
  36629. intersects.push( {
  36630. point: point,
  36631. pointOnLine: pointOnLine,
  36632. distance: _ray$3.origin.distanceTo( point ),
  36633. object: lineSegments,
  36634. face: null,
  36635. faceIndex: i,
  36636. uv: null,
  36637. uv2: null,
  36638. } );
  36639. }
  36640. }
  36641. }
  36642. class LineSegments2 extends Mesh {
  36643. constructor( geometry = new LineSegmentsGeometry(), material = new LineMaterial( { color: Math.random() * 0xffffff } ) ) {
  36644. super( geometry, material );
  36645. this.isLineSegments2 = true;
  36646. this.type = 'LineSegments2';
  36647. }
  36648. // for backwards-compatibility, but could be a method of LineSegmentsGeometry...
  36649. computeLineDistances() {
  36650. const geometry = this.geometry;
  36651. const instanceStart = geometry.attributes.instanceStart;
  36652. const instanceEnd = geometry.attributes.instanceEnd;
  36653. const lineDistances = new Float32Array( 2 * instanceStart.count );
  36654. for ( let i = 0, j = 0, l = instanceStart.count; i < l; i ++, j += 2 ) {
  36655. _start$2.fromBufferAttribute( instanceStart, i );
  36656. _end$2.fromBufferAttribute( instanceEnd, i );
  36657. lineDistances[ j ] = ( j === 0 ) ? 0 : lineDistances[ j - 1 ];
  36658. lineDistances[ j + 1 ] = lineDistances[ j ] + _start$2.distanceTo( _end$2 );
  36659. }
  36660. const instanceDistanceBuffer = new InstancedInterleavedBuffer( lineDistances, 2, 1 ); // d0, d1
  36661. geometry.setAttribute( 'instanceDistanceStart', new InterleavedBufferAttribute( instanceDistanceBuffer, 1, 0 ) ); // d0
  36662. geometry.setAttribute( 'instanceDistanceEnd', new InterleavedBufferAttribute( instanceDistanceBuffer, 1, 1 ) ); // d1
  36663. return this;
  36664. }
  36665. raycast( raycaster, intersects ) {
  36666. const worldUnits = this.material.worldUnits;
  36667. const camera = raycaster.camera;
  36668. if ( camera === null && ! worldUnits ) {
  36669. console.error( 'LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.' );
  36670. }
  36671. const threshold = ( raycaster.params.Line2 !== undefined ) ? raycaster.params.Line2.threshold || 0 : 0;
  36672. _ray$3 = raycaster.ray;
  36673. const matrixWorld = this.matrixWorld;
  36674. const geometry = this.geometry;
  36675. const material = this.material;
  36676. _lineWidth = material.lineWidth + threshold;
  36677. _instanceStart = geometry.attributes.instanceStart;
  36678. _instanceEnd = geometry.attributes.instanceEnd;
  36679. // check if we intersect the sphere bounds
  36680. if ( geometry.boundingSphere === null ) {
  36681. geometry.computeBoundingSphere();
  36682. }
  36683. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( matrixWorld );
  36684. // increase the sphere bounds by the worst case line screen space width
  36685. let sphereMargin;
  36686. if ( worldUnits ) {
  36687. sphereMargin = _lineWidth * 0.5;
  36688. } else {
  36689. const distanceToSphere = Math.max( camera.near, _sphere$4.distanceToPoint( _ray$3.origin ) );
  36690. sphereMargin = getWorldSpaceHalfWidth( camera, distanceToSphere, material.resolution );
  36691. }
  36692. _sphere$4.radius += sphereMargin;
  36693. if ( _ray$3.intersectsSphere( _sphere$4 ) === false ) {
  36694. return;
  36695. }
  36696. // check if we intersect the box bounds
  36697. if ( geometry.boundingBox === null ) {
  36698. geometry.computeBoundingBox();
  36699. }
  36700. _box$5.copy( geometry.boundingBox ).applyMatrix4( matrixWorld );
  36701. // increase the box bounds by the worst case line width
  36702. let boxMargin;
  36703. if ( worldUnits ) {
  36704. boxMargin = _lineWidth * 0.5;
  36705. } else {
  36706. const distanceToBox = Math.max( camera.near, _box$5.distanceToPoint( _ray$3.origin ) );
  36707. boxMargin = getWorldSpaceHalfWidth( camera, distanceToBox, material.resolution );
  36708. }
  36709. _box$5.expandByScalar( boxMargin );
  36710. if ( _ray$3.intersectsBox( _box$5 ) === false ) {
  36711. return;
  36712. }
  36713. if ( worldUnits ) {
  36714. raycastWorldUnits( this, intersects );
  36715. } else {
  36716. raycastScreenSpace( this, camera, intersects );
  36717. }
  36718. }
  36719. }
  36720. class LineGeometry extends LineSegmentsGeometry {
  36721. constructor() {
  36722. super();
  36723. this.isLineGeometry = true;
  36724. this.type = 'LineGeometry';
  36725. }
  36726. setPositions( array ) {
  36727. // converts [ x1, y1, z1, x2, y2, z2, ... ] to pairs format
  36728. const length = array.length - 3;
  36729. const points = new Float32Array( 2 * length );
  36730. for ( let i = 0; i < length; i += 3 ) {
  36731. points[ 2 * i ] = array[ i ];
  36732. points[ 2 * i + 1 ] = array[ i + 1 ];
  36733. points[ 2 * i + 2 ] = array[ i + 2 ];
  36734. points[ 2 * i + 3 ] = array[ i + 3 ];
  36735. points[ 2 * i + 4 ] = array[ i + 4 ];
  36736. points[ 2 * i + 5 ] = array[ i + 5 ];
  36737. }
  36738. super.setPositions( points );
  36739. return this;
  36740. }
  36741. setColors( array ) {
  36742. // converts [ r1, g1, b1, r2, g2, b2, ... ] to pairs format
  36743. const length = array.length - 3;
  36744. const colors = new Float32Array( 2 * length );
  36745. for ( let i = 0; i < length; i += 3 ) {
  36746. colors[ 2 * i ] = array[ i ];
  36747. colors[ 2 * i + 1 ] = array[ i + 1 ];
  36748. colors[ 2 * i + 2 ] = array[ i + 2 ];
  36749. colors[ 2 * i + 3 ] = array[ i + 3 ];
  36750. colors[ 2 * i + 4 ] = array[ i + 4 ];
  36751. colors[ 2 * i + 5 ] = array[ i + 5 ];
  36752. }
  36753. super.setColors( colors );
  36754. return this;
  36755. }
  36756. fromLine( line ) {
  36757. const geometry = line.geometry;
  36758. this.setPositions( geometry.attributes.position.array ); // assumes non-indexed
  36759. // set colors, maybe
  36760. return this;
  36761. }
  36762. }
  36763. class Line2 extends LineSegments2 {
  36764. constructor( geometry = new LineGeometry(), material = new LineMaterial( { color: Math.random() * 0xffffff } ) ) {
  36765. super( geometry, material );
  36766. this.isLine2 = true;
  36767. this.type = 'Line2';
  36768. }
  36769. }
  36770. var defaultColor = new Color(1,1,1);//config.applicationName == "zhiHouse" ? Colors.zhiBlue : Colors.lightGreen;
  36771. var LineDraw = {
  36772. createLine: function (posArr, o={}) {
  36773. //多段普通线 (第二个点和第三个点之间是没有线段的, 所以不用在意线段顺序)
  36774. var mat;
  36775. if(o.mat){
  36776. mat = o.mat;
  36777. }else {
  36778. let prop = {
  36779. lineWidth: o.lineWidth || 1,
  36780. //windows无效。 似乎mac/ios上粗细有效 ?
  36781. color: o.color || defaultColor,
  36782. transparent: o.dontAlwaysSeen ? false : true,
  36783. depthTest: o.dontAlwaysSeen ? true : false,
  36784. };
  36785. if(o.deshed ){
  36786. prop.dashSize = o.dashSize || 0.1,
  36787. prop.gapSize = o.gapSize || 0.1;
  36788. }
  36789. mat = new THREE$1[o.deshed ? "LineDashedMaterial" : "LineBasicMaterial"](prop);
  36790. }
  36791. var line = new LineSegments(new BufferGeometry, mat);
  36792. line.renderOrder = o.renderOrder || 4;
  36793. this.moveLine(line, posArr);
  36794. return line;
  36795. },
  36796. moveLine: function (line, posArr) {
  36797. if(posArr.length == 0)return
  36798. let position = [];
  36799. posArr.forEach(e=>position.push(e.x,e.y,e.z));
  36800. line.geometry.setAttribute('position', new Float32BufferAttribute(/* new Float32Array( */position/* ) */, 3));
  36801. line.geometry.attributes.position.needsUpdate = true;
  36802. line.geometry.computeBoundingSphere();
  36803. if(line.material instanceof LineDashedMaterial){
  36804. line.computeLineDistances();
  36805. //line.geometry.attributes.lineDistance.needsUpdate = true;
  36806. line.geometry.verticesNeedUpdate = true; //没用
  36807. }
  36808. }
  36809. ,
  36810. createFatLineMat : function(o){
  36811. var supportExtDepth = !!Features.EXT_DEPTH.isSupported();
  36812. let params = $.extend({}, {
  36813. //默认
  36814. lineWidth : 5,
  36815. color:0xffffff,
  36816. transparent : true, depthWrite:false, depthTest:false,
  36817. dashSize : 0.1, gapSize:0.1,
  36818. }, o, {
  36819. //修正覆盖:
  36820. dashed: o.dashWithDepth ? supportExtDepth && !!o.dashed : !!o.dashed ,
  36821. dashWithDepth:!!o.dashWithDepth,//只在被遮住的部分显示虚线
  36822. useDepth: !!o.useDepth,
  36823. supportExtDepth,
  36824. });
  36825. var mat = new LineMaterial(params);
  36826. //if(o.dashed)(mat.defines.USE_DASH = "")
  36827. return mat;
  36828. },
  36829. /*
  36830. 创建可以改变粗细的线。
  36831. */
  36832. createFatLine : function(posArr, o){
  36833. var geometry = new LineGeometry();
  36834. geometry.setColors( o.color || [1,1,1]);
  36835. var matLine = o.material || this.createFatLineMat(o);
  36836. var line = new Line2( geometry, matLine );
  36837. //line.computeLineDistances();
  36838. line.scale.set( 1, 1, 1 );
  36839. line.renderOrder = 2;
  36840. this.moveFatLine(line, posArr);
  36841. return line;
  36842. },
  36843. moveFatLine: function(line, posArr){
  36844. var geometry = line.geometry;
  36845. var positions = [];
  36846. posArr.forEach(e=>{positions.push(...e.toArray());});
  36847. if(positions.length > 0){
  36848. if(!geometry){
  36849. geometry = line.geometry = new LineGeometry();
  36850. }
  36851. if(geometry.attributes.instanceEnd && geometry.attributes.instanceEnd.data.array.length != positions.length){//positions个数改变会有部分显示不出来,所以重建
  36852. geometry.dispose();
  36853. geometry = new LineGeometry();
  36854. line.geometry = geometry;
  36855. }
  36856. geometry.setPositions( positions );
  36857. if(line.material.defines.USE_DASH != void 0){
  36858. //line.geometry.verticesNeedUpdate = true; //没用
  36859. line.geometry.computeBoundingSphere(); //for raycaster
  36860. line.computeLineDistances();
  36861. }
  36862. }else {
  36863. geometry.dispose();
  36864. line.geometry = new LineGeometry();
  36865. }
  36866. },
  36867. updateLine: function(line, posArr){
  36868. if(line instanceof Line2){
  36869. LineDraw.moveFatLine(line,posArr);
  36870. }else {
  36871. LineDraw.moveLine(line,posArr);
  36872. }
  36873. },
  36874. /*
  36875. 为line创建用于检测鼠标的透明mesh,实际是个1-2段圆台。
  36876. 由于近大远小的原因,假设没有透视畸变、创建的是等粗的圆柱的话, 所看到的线上每个位置的粗细应该和距离成反比。所以将圆柱改为根据距离线性渐变其截面半径的圆台,在最近点(相机到线的垂足)最细。如果最近点在线段上,则分成两段圆台,否则一段。
  36877. */
  36878. createBoldLine:function(points, o){
  36879. o = o || {};
  36880. var cylinder = o && o.cylinder;
  36881. var CD = points[1].clone().sub(points[0]);
  36882. var rotate = function(){//根据端点旋转好模型
  36883. cylinder.lastVector = CD;//记录本次的端点向量
  36884. var AB = new Vector3(0,-1,0);
  36885. var axisVec = AB.clone().cross(CD).normalize(); //得到垂直于它们的向量,也就是旋转轴
  36886. var rotationAngle = AB.angleTo(CD);
  36887. cylinder.quaternion.setFromAxisAngle( axisVec, rotationAngle );
  36888. };
  36889. if(o && o.type == "init"){
  36890. cylinder = new Mesh();
  36891. cylinder.material = o.mat;
  36892. if(CD.length() == 0)return cylinder;
  36893. rotate();
  36894. }
  36895. if(CD.length() == 0)return cylinder;
  36896. if(o.type != "update"){
  36897. var CDcenter = points[0].clone().add(points[1]).multiplyScalar(.5);
  36898. cylinder.position.copy(CDcenter);
  36899. if(!cylinder.lastVector || o.type == "moveAndRotate")rotate();
  36900. else if(cylinder.lastVector && CD.angleTo(cylinder.lastVector)>0) rotate();//线方向改了or线反向了 重新旋转一下模型
  36901. if(config.isEdit && !objects.mainDesign.editing )return cylinder;//节省初始加载时间?
  36902. }
  36903. //为了保证线段任何地方的可检测点击范围看起来一样大,更新圆台的结构(但是在镜头边缘会比中心看起来大)
  36904. var height = points[0].distanceTo(points[1]);
  36905. var standPos = o && o.standPos || objects.player.position;
  36906. var k = config.isMobile ? 20 : 40;
  36907. var dis1 = points[0].distanceTo(standPos);
  36908. var dis2 = points[1].distanceTo(standPos);
  36909. var foot = math.getFootPoint(standPos, points[0], points[1]);//垂足
  36910. if(o.constantBold || objects.player.mode != "panorama"){
  36911. var width = 0.1;//0.08;
  36912. var pts = [new Vector2$1(width ,height/2),new Vector2$1(width ,-height/2)];
  36913. }else if(foot.clone().sub(points[0]).dot( foot.clone().sub(points[1]) ) > 0){//foot不在线段上
  36914. var pts = [new Vector2$1(dis1 / k,height/2),new Vector2$1(dis2 / k,-height/2)];
  36915. }else {//在线段上的话,要在垂足这加一个节点,因它距离站位最近,而两端较远
  36916. var dis3 = foot.distanceTo(standPos);
  36917. var len = foot.distanceTo(points[0]);
  36918. var pts = [new Vector2$1(dis1 / k,height/2), new Vector2$1(dis3 / k,height/2-len), new Vector2$1(dis2 / k,-height/2)];
  36919. }
  36920. cylinder.geometry && cylinder.geometry.dispose();//若不删除会占用内存
  36921. cylinder.geometry = new LatheBufferGeometry( pts, 4/* Math.min(dis1,dis2)<10?4:3 */ );
  36922. cylinder.renderOrder = 2;
  36923. return cylinder;
  36924. },
  36925. updateBoldLine:function(cylinder, points, type, standPos, constantBold){
  36926. this.createBoldLine(points,{type:type, cylinder : cylinder, standPos:standPos, constantBold}); //type:move:平移 会改长短 , type:update根据距离和角度更新 不改长短
  36927. },
  36928. };
  36929. var MeshDraw = {
  36930. getShape:function(points, holes){
  36931. var shape = new Shape();
  36932. shape.moveTo( points[0].x, points[0].y );
  36933. for(var i=1,len=points.length; i<len; i++){
  36934. shape.lineTo(points[i].x, points[i].y );
  36935. }
  36936. /* var holePath = new THREE.Path()
  36937. .moveTo( 20, 10 )
  36938. .absarc( 10, 10, 10, 0, Math.PI * 2, true )
  36939. arcShape.holes.push( holePath );
  36940. */
  36941. if(holes){//挖空
  36942. holes.forEach((points)=>{
  36943. var holePath = new Path();
  36944. holePath.moveTo( points[0].x, points[0].y );
  36945. for(var i=1,len=points.length; i<len; i++){
  36946. holePath.lineTo(points[i].x, points[i].y );
  36947. }
  36948. shape.holes.push( holePath );
  36949. });
  36950. }
  36951. return shape
  36952. },
  36953. getShapeGeo: function(points, holes){//获取任意形状(多边形或弧形)的形状面 //quadraticCurveTo() 这是弧形的含函数
  36954. var geometry = new ShapeBufferGeometry( this.getShape(points, holes) ); //ShapeGeometry
  36955. /* var matrix = new THREE.Matrix4();//将竖直的面变为水平
  36956. matrix.set(//z = y
  36957. 1, 0, 0, 0,
  36958. 0, 0, 0, 0,
  36959. 0, 1, 0, 0,
  36960. 0, 0, 0, 1
  36961. )
  36962. geometry.applyMatrix(matrix) */
  36963. //geometry.computeVertexNormals();//对于光照需要的是点法线
  36964. return geometry;
  36965. },
  36966. getExtrudeGeo: function(points, holes, options={}){//获得挤出棱柱,可以选择传递height,或者extrudePath
  36967. var shape = this.getShape(points, holes); //points是横截面 [vector2,...]
  36968. if(options.extrudePath ){// 路径 :[vector3,...]
  36969. var length = extrudePath.reduce((total, currentValue, currentIndex, arr)=>{
  36970. if(currentIndex == 0)return 0
  36971. return total + currentValue.distanceTo(arr[currentIndex-1]);
  36972. },0);
  36973. options.extrudePath = new CatmullRomCurve3(extrudePath, options.closed , 'catmullrom' /* 'centripetal' */ , options.tension);
  36974. }
  36975. var extrudeSettings = $.extend(options,{
  36976. steps: options.steps != void 0 ? options.steps : ( options.extrudePath ? Math.round(length/0.3) : 1),
  36977. bevelEnabled: false, //不加的话,height为0时会有圆弧高度
  36978. //depth
  36979. });
  36980. var geometry = new ExtrudeBufferGeometry( shape, extrudeSettings );
  36981. return geometry;
  36982. },
  36983. getUnPosPlaneGeo : function(){//获取还没有赋值位置的plane geometry
  36984. var e = new Uint16Array([0, 1, 2, 0, 2, 3])
  36985. // , t = new Float32Array([-.5, -.5, 0, .5, -.5, 0, .5, .5, 0, -.5, .5, 0])
  36986. , i = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1])
  36987. , g = new BufferGeometry;
  36988. g.setIndex(new BufferAttribute(e, 1)),
  36989. //g.addAttribute("position", new n.BufferAttribute(t, 3)),
  36990. g.setAttribute("uv", new BufferAttribute(i, 2));
  36991. return function(){
  36992. return g
  36993. }
  36994. }(),
  36995. getPlaneGeo : function(A,B,C,D){
  36996. var geo = this.getUnPosPlaneGeo().clone();
  36997. var pos = [
  36998. A.x, A.y, A.z,
  36999. B.x, B.y, B.z,
  37000. C.x, C.y, C.z,
  37001. D.x, D.y, D.z
  37002. ];
  37003. //geo.addAttribute("position", new THREE.BufferAttribute(pos, 3))
  37004. geo.setAttribute('position', new Float32BufferAttribute(pos, 3));
  37005. geo.computeVertexNormals();
  37006. geo.computeBoundingSphere(); //for raycaster
  37007. return geo;
  37008. },
  37009. drawPlane : function(A,B,C,D, material){
  37010. var wall = new Mesh(this.getPlaneGeo(A,B,C,D), material);
  37011. return wall;
  37012. },
  37013. movePlane: function(mesh, A,B,C,D){
  37014. var pos = new Float32Array([
  37015. A.x, A.y, A.z,
  37016. B.x, B.y, B.z,
  37017. C.x, C.y, C.z,
  37018. D.x, D.y, D.z
  37019. ]);
  37020. mesh.geometry.addAttribute("position", new BufferAttribute(pos, 3));
  37021. mesh.geometry.computeBoundingSphere();//for checkIntersect
  37022. }
  37023. ,
  37024. createGeometry:function(posArr, faceArr, uvArr, normalArr ){//创建复杂mesh. faceArr:[[0,1,2],[0,2,3]]
  37025. let geo = new BufferGeometry;
  37026. let positions = [];
  37027. posArr.forEach(p=>positions.push(p.x,p.y,p.z));
  37028. geo.setAttribute('position', new Float32BufferAttribute(positions, 3));
  37029. if(faceArr){
  37030. let indice = [];
  37031. faceArr.forEach(f=>indice.push(...f));
  37032. geo.setIndex(indice); // auto set Uint16BufferAttribute or Uint32BufferAttribute
  37033. }
  37034. if(uvArr){
  37035. let uvs = [];
  37036. uvArr.forEach(uv=>uvs.push(uv.x,uv.y));
  37037. geo.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
  37038. }
  37039. if(normalArr){
  37040. let normals = [];
  37041. normalArr.forEach(n=>normals.push(n.x,n.y,n.z));
  37042. geo.setAttribute("normal", new Float32BufferAttribute(normals, 3));
  37043. }
  37044. /*
  37045. geo.computeVertexNormals()
  37046. geo.computeBoundingSphere() //for raycaster
  37047. */
  37048. return geo
  37049. },
  37050. updateGeometry:function(geo, posArr, faceArr, uvArr, normalArr ){//创建复杂mesh. faceArr:[[0,1,2],[0,2,3]]
  37051. let positions = [];
  37052. posArr.forEach(p=>positions.push(p.x,p.y,p.z));
  37053. geo.setAttribute('position', new Float32BufferAttribute(positions, 3));
  37054. geo.attributes.position.needsUpdate = true;
  37055. if(faceArr){
  37056. let indice = [];
  37057. faceArr.forEach(f=>indice.push(...f));
  37058. geo.setIndex(indice); // auto set Uint16BufferAttribute or Uint32BufferAttribute
  37059. }
  37060. if(uvArr){
  37061. let uvs = [];
  37062. uvArr.forEach(uv=>uvs.push(uv.x,uv.y));
  37063. geo.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
  37064. }
  37065. if(normalArr){
  37066. let normals = [];
  37067. normalArr.forEach(n=>normals.push(n.x,n.y,n.z));
  37068. geo.setAttribute("normal", new Float32BufferAttribute(normals, 3));
  37069. }
  37070. /*
  37071. geo.computeVertexNormals()
  37072. */
  37073. geo.computeBoundingSphere(); //for raycaster and visi
  37074. return geo
  37075. }
  37076. };
  37077. const verticalLine = new Line3();
  37078. //控制点和边的合集。具有可以拖拽修改的功能,拖拽时能防止线相交。
  37079. class ctrlPolygon extends Object3D {
  37080. constructor (type, prop) {
  37081. super();
  37082. this.type = type;
  37083. this.maxMarkers = Number.MAX_SAFE_INTEGER;
  37084. this.transformData(prop);
  37085. for(let i in prop){
  37086. this[i] = prop[i];
  37087. }
  37088. if(this.closed && this.dimension == '2d'){
  37089. this.areaPlane = this.createAreaPlane();
  37090. this.add(this.areaPlane);
  37091. }
  37092. //数据--刚开始一定是空的
  37093. this.points = [];
  37094. //mesh 不一定有
  37095. this.markers = [];
  37096. this.edges = [];
  37097. this.center;
  37098. }
  37099. initData(prop){
  37100. //开始加数据
  37101. if(Potree.settings.editType == 'merge'){ //融合页面没有地图,measure的不需要指定datasetId,每个点都有各自的datasetId,跟着各自的模型走
  37102. if(this.dataset_points){
  37103. this.dataset_points = this.dataset_points.map(e=>{
  37104. return e && new Vector3().copy(e)
  37105. });
  37106. prop.points = this.dataset_points.map((p,i)=>{
  37107. return Potree.Utils.datasetPosTransform({fromDataset:true, datasetId:this.points_datasets[i], position: p})
  37108. });
  37109. if(prop.points.some(e=>e == void 0)){
  37110. return false
  37111. }
  37112. }else {
  37113. this.dataset_points = [];
  37114. }
  37115. }
  37116. if(prop.points){
  37117. for(const p of prop.points){
  37118. const pos = new Vector3().copy(p);
  37119. this.addMarker({point:pos});
  37120. }
  37121. if(Potree.settings.editType != 'merge'){
  37122. if(this.datasetId != void 0){//初始化位置
  37123. if(this.dataset_points){
  37124. this.dataset_points = this.dataset_points.map(e=>{
  37125. return e && new Vector3().copy(e)
  37126. });
  37127. this.transformByPointcloud(); //根据dataset_points生成points
  37128. }
  37129. }else {
  37130. if(prop.dataset_points && prop.dataset_points.some(e=>e != void 0)){
  37131. console.error('存在测量线的datasetId为空而dataset_points有值,请检查并删除:'+this.sid);//存在过的bug,原因未知,可能是后台处理dataset时替换的错误:http://192.168.0.21/index.php?m=bug&f=view&bugID=23601
  37132. console.log(this);
  37133. }
  37134. }
  37135. }
  37136. this.getFacePlane();
  37137. this.getPoint2dInfo(this.points);
  37138. this.update({ifUpdateMarkers:true});
  37139. //this.dragChange(new THREE.Vector3().copy(prop.points[prop.points.length-1]), prop.points.length-1);
  37140. this.setSelected(false );
  37141. this.markers.forEach(marker=>{marker.dispatchEvent('addHoverEvent'); });
  37142. return true
  37143. }
  37144. }
  37145. addMarker(o={}){
  37146. var index = o.index == void 0 ? this.points.length : o.index; //要当第几个
  37147. this.points = [...this.points.slice(0,index), o.point, ...this.points.slice(index,this.points.length)];
  37148. //this.points.push(o.point);
  37149. if(o.marker){
  37150. this.add(o.marker);
  37151. this.markers = [...this.markers.slice(0,index), o.marker, ...this.markers.slice(index,this.markers.length)];
  37152. this.updateMarker(o.marker, o.point);
  37153. o.marker.addEventListener('drag', this.dragMarker.bind(this));
  37154. o.marker.addEventListener('drop', this.dropMarker.bind(this));
  37155. let addHoverEvent = (e)=>{
  37156. let mouseover = (e) => {
  37157. this.setMarkerSelected(e.object, 'hover', 'single');
  37158. viewer.dispatchEvent({
  37159. type : "CursorChange", action : "add", name:"markerMove"
  37160. });
  37161. };
  37162. let mouseleave = (e) => {
  37163. this.setMarkerSelected(e.object, 'unhover', 'single');
  37164. viewer.dispatchEvent({
  37165. type : "CursorChange", action : "remove", name:"markerMove"
  37166. });
  37167. };
  37168. o.marker.addEventListener('mouseover', mouseover);
  37169. o.marker.addEventListener('mouseleave', mouseleave);
  37170. o.marker.removeEventListener('addHoverEvent',addHoverEvent);
  37171. };
  37172. o.marker.addEventListener('addHoverEvent',addHoverEvent);//当非isNew时才添加事件
  37173. if(!this.isNew){
  37174. o.marker.dispatchEvent('addHoverEvent');
  37175. }
  37176. }
  37177. if(o.edge){
  37178. this.add(o.edge);
  37179. this.edges = [...this.edges.slice(0,index), o.edge, ...this.edges.slice(index,this.edges.length)];
  37180. }
  37181. }
  37182. dragMarker(e){
  37183. var I, atMap;
  37184. if(e.hoverViewport != e.drag.dragViewport){//不能使用e.dragViewport,要使用drag中的,因为drag中存储的要一直继承下来,不因mouseup了而改变。
  37185. viewer.dispatchEvent({
  37186. type : "CursorChange", action : "add", name:"polygon_AtWrongPlace"
  37187. });
  37188. return
  37189. }
  37190. viewer.dispatchEvent({
  37191. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  37192. });
  37193. atMap = e.drag.dragViewport.name == 'mapViewport';
  37194. if(atMap && this.unableDragAtMap){
  37195. e.drag.object = null; //取消拖拽
  37196. return
  37197. }
  37198. e.drag.object.isDragging = true;
  37199. I = e.intersect && (e.intersect.orthoIntersect || e.intersect.location);
  37200. //记录数据集
  37201. //在三维中脱离点云(在map中拉到周围都没有点云的地方)的顶点,无法拖拽怎么办
  37202. if (I) {
  37203. let i = this.markers.indexOf(e.drag.object);
  37204. if (i !== -1) {
  37205. this.dragChange(I.clone(), i, atMap);
  37206. /* if(this.points_datasets){
  37207. if(e.intersect.pointcloud) this.points_datasets[i] = e.intersect.pointcloud.dataset_id
  37208. else this.points_datasets[i] = null
  37209. } */
  37210. if(this.points_datasets){
  37211. if(e.intersect.pointcloud) this.points_datasets[i] = e.intersect.pointcloud.dataset_id;
  37212. else if(e.intersect.object) this.points_datasets[i] = e.intersect.object.dataset_id;
  37213. else this.points_datasets[i] = null;
  37214. }
  37215. }
  37216. this.editStateChange(true);
  37217. return true
  37218. }
  37219. };
  37220. dragChange(intersectPos, i, atMap){
  37221. let len = this.markers.length;
  37222. let oldPoint = this.points[i];
  37223. if(atMap){
  37224. intersectPos.setZ(oldPoint.z); //在地图上拖拽,不改变其高度。
  37225. }
  37226. let location = intersectPos.clone();
  37227. if(this.faceDirection && this.maxMarkers == 2 && len == 2){//add 固定方向的点不直接拖拽
  37228. var p1 = this.markers[0].position;
  37229. if(this.faceDirection == 'horizontal'){
  37230. var projectPos = location.clone().setZ(p1.z);
  37231. }else {
  37232. var projectPos = p1.clone().setZ(location.z);
  37233. }
  37234. //var p2 = p1.clone().add(this.direction)
  37235. //var projectPos = math.getFootPoint(location, p1, p2)
  37236. LineDraw.updateLine(this.guideLine, [location, projectPos]);
  37237. location = projectPos;
  37238. this.guideLine.visible = true;
  37239. }else if( len > 1){
  37240. var points = this.points.map(e=>e.clone());
  37241. points[i].copy(location); //算normal需要提前确认point
  37242. //若为定义了面朝向的矩形
  37243. if(this.faceDirection == 'horizontal'){
  37244. if(len == 2){
  37245. location.setZ(points[0].z);
  37246. }
  37247. if(!this.facePlane){//一个点就能确定面
  37248. this.facePlane = new Plane().setFromNormalAndCoplanarPoint( new Vector3(0,0,1), this.points[0] );
  37249. }
  37250. }else if(this.faceDirection == 'vertical'){//当有两个点时, 有两个方向的可能
  37251. if(len == 2){
  37252. if(this.isRect){
  37253. let vec = points[0].clone().sub(location);
  37254. if(Math.sqrt(vec.x*vec.x+vec.y*vec.y) > Math.abs(vec.z) ){//水平(高度差小于水平距离时)
  37255. location.setZ(points[0].z);
  37256. //this.cannotConfirmNormal = false;//能确定面为水平方向
  37257. }else {//垂直 (当两点一样时也属于这种)
  37258. location.setX(points[0].x);
  37259. location.setY(points[0].y);
  37260. //this.cannotConfirmNormal = true; //不能确定面,因第三点可绕着纵轴线自由移动
  37261. }
  37262. }
  37263. }else {
  37264. {//判断cannotConfirmNormal. 如果前几段都在竖直线上,就不能固定出面方向。
  37265. this.cannotConfirmNormal = true;
  37266. let max = this.isRect ? 1 : len-2;
  37267. for(let i=0;i<max;i++){
  37268. let p1 = points[i].clone();
  37269. let p2 = points[i+1].clone();
  37270. let vec = p1.sub(p2);
  37271. if(vec.x != 0 || vec.y != 0){
  37272. this.cannotConfirmNormal = false;
  37273. break;
  37274. }
  37275. }
  37276. }
  37277. if(!this.facePlane || this.cannotConfirmNormal){//三个点且为水平方向时,计算面
  37278. var points_ = points.map(e=>new Vector2$1(e.x,e.y));
  37279. var points2 = getDifferentPoint(points_, 2);
  37280. if(points2){
  37281. let normal = math.getNormal2d({p1:points2[0], p2:points2[1]});
  37282. normal = new Vector3(normal.x, normal.y, 0);
  37283. this.facePlane = new Plane().setFromNormalAndCoplanarPoint( normal, this.points[0] );
  37284. }
  37285. }
  37286. }
  37287. }
  37288. if(len > 2){//area
  37289. if(!this.faceDirection){
  37290. if(len == 3 || this.isRect) this.cannotConfirmNormal = true; //当第三个点固定后(有四个点时)才能固定面
  37291. if(!this.facePlane || this.cannotConfirmNormal){
  37292. var points3 = getDifferentPoint(points, 3);//只有找到三个不同的点算拥有面和area
  37293. if(points3){
  37294. this.facePlane = new Plane().setFromCoplanarPoints(...points3 );
  37295. }
  37296. }
  37297. }
  37298. if( this.facePlane && !this.cannotConfirmNormal ){//之后加的点一定要在面上
  37299. if(atMap){
  37300. //地图上用垂直线,得到和面的交点。
  37301. verticalLine.set(location.clone().setZ(100000), location.clone().setZ(-100000));//确保长度范围覆盖所有测量面
  37302. location = this.facePlane.intersectLine(verticalLine, new Vector3() );
  37303. if(!location) return;
  37304. }else {
  37305. location = this.facePlane.projectPoint(intersectPos, new Vector3() );
  37306. }
  37307. }
  37308. points[i].copy(location);//再copy确认一次
  37309. if(this.isRect){ //是矩形 (即使没有faceDirection也能执行)
  37310. //根据前两个点计算当前和下一个点
  37311. var p1 = points[(i-2+len)%len];
  37312. var p2 = points[(i-1+len)%len];
  37313. if(p1.equals(p2)){//意外情况:重复点两次 ( bug点,改了好多遍)
  37314. if(this.faceDirection == 'vertical'){
  37315. p2.add(new Vector3(0,0,0.0001));
  37316. }else {
  37317. p2.add(new Vector3(0,0.0001,0));
  37318. }
  37319. }
  37320. //p3 : location
  37321. var foot = math.getFootPoint(location, p1, p2);//p2 修改p2到垂足的位置
  37322. var vec = foot.clone().sub(location);
  37323. var p4 = p1.clone().sub(vec);
  37324. points[(i-1+len)%len].copy(foot);
  37325. points[(i+1)%len].copy(p4);
  37326. this.setPosition((i-1+len)%len, foot);//p2
  37327. this.setPosition((i+1)%len, p4);
  37328. }
  37329. /* let points2d;
  37330. if(this.facePlane){
  37331. var originPoint0 = points[0].clone()
  37332. var qua = math.getQuaBetween2Vector(this.facePlane.normal, new THREE.Vector3(0,0,1), new THREE.Vector3(0,0,1));
  37333. points2d = points.map(e=>e.clone().applyQuaternion(qua))
  37334. } */
  37335. this.getPoint2dInfo(points);
  37336. var isIntersectSelf = !this.isRect && len > 3 && this.intersectSelf(this.point2dInfo.points2d);//检测相交
  37337. if(isIntersectSelf){
  37338. //not-allowed
  37339. viewer.dispatchEvent({
  37340. type : "CursorChange", action : "add", name:"polygon_isIntersectSelf"
  37341. });
  37342. this.isIntersectSelf = true;
  37343. return
  37344. }else {
  37345. this.isIntersectSelf = false;
  37346. viewer.dispatchEvent({
  37347. type : "CursorChange", action : "remove", name:"polygon_isIntersectSelf"
  37348. });
  37349. /* this.facePlane && (this.point2dInfo = {
  37350. originPoint0 ,
  37351. points2d,
  37352. quaInverse : qua.clone().invert()
  37353. }) */
  37354. }
  37355. }
  37356. var showGuideLine = len>1 && (this.faceDirection || len > 3);
  37357. if(showGuideLine && this.guideLine){
  37358. LineDraw.updateLine(this.guideLine, [intersectPos, location]);
  37359. this.guideLine.visible = true;
  37360. }
  37361. //console.log(this.points.map(e=>e.toArray()))
  37362. }
  37363. if(this.restrictArea){
  37364. let holes = this.restrictArea.holes.concat(this.restrictArea.parentHoles);
  37365. let holesPoints = holes.filter(e=>e!=this && e.points.length>2).map(e=>e.points);
  37366. if(!math.isPointInArea(this.restrictArea.points, holesPoints, location)){
  37367. viewer.dispatchEvent({
  37368. type : "CursorChange", action : "add", name:"polygon_AtWrongPlace"
  37369. });
  37370. this.isAtWrongPlace = true;
  37371. return
  37372. }
  37373. //就不处理相交线了。 有个缺点:floor上的hole可以限制room,但hole不受room限制,会导致room的marker被框在hole里而动不了。只能去调整hole了
  37374. }
  37375. viewer.dispatchEvent({
  37376. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  37377. });
  37378. this.isAtWrongPlace = false;
  37379. this.setPosition(i, location);
  37380. this.update();
  37381. this.dispatchEvent({type:'dragChange', index:i});
  37382. }
  37383. dropMarker(e){
  37384. //console.log('dropMarker')
  37385. if (this.isNew && e.pressDistance>Potree.config.clickMaxDragDis){//拖拽的话返回
  37386. return this.continueDrag(null,e)
  37387. }
  37388. if(e.isTouch){
  37389. if(e.hoverViewport != viewer.mainViewport && this.unableDragAtMap){
  37390. viewer.dispatchEvent({type:'reticule_forbit', v:true});
  37391. //console.log('reticule_forbit',true)
  37392. return this.continueDrag(null,e)
  37393. }else {
  37394. viewer.dispatchEvent({type:'reticule_forbit', v:false});
  37395. //console.log('reticule_forbit',false)
  37396. }
  37397. this.dragMarker(e); //触屏时必须先更新下点
  37398. }
  37399. if (e.button != MOUSE.RIGHT && (//右键click的话继续执行,因为会停止
  37400. this.isIntersectSelf && this.isNew //有线相交了
  37401. || this.isAtWrongPlace && this.isNew
  37402. || !e.isAtDomElement && this.isNew//如果是刚添加时在其他dom点击, 不要响应
  37403. || e.hoverViewport != viewer.mainViewport && this.unableDragAtMap //垂直的测量线不允许在地图上放点
  37404. || this.isNew && !getDifferentPoint(this.points, this.points.length ) //不允许和之前的点相同, 但这句在点云稀疏时会导致难结束
  37405. )
  37406. ){
  37407. return this.continueDrag(null,e)
  37408. }
  37409. //console.log('drop marker' )
  37410. let i = this.markers.indexOf(e.drag.object);
  37411. if (i !== -1) {
  37412. this.dispatchEvent({
  37413. 'type': 'marker_dropped',
  37414. 'index': i
  37415. });
  37416. if(this.markers.length>2 && this.facePlane)this.cannotConfirmNormal = false;
  37417. this.guideLine &&(this.guideLine.visible = false);
  37418. }
  37419. this.setMarkerSelected(e.drag.object, 'unhover', 'single');
  37420. this.editStateChange(false);
  37421. e.drag.endDragFun && e.drag.endDragFun(e);// addmarker
  37422. //if(this.changeCallBack)this.changeCallBack()
  37423. return true
  37424. };
  37425. getFacePlane(){//最普通一种get方法,根据顶点。且假设所有点已经共面,且不重合
  37426. if(this.points.length<3) return
  37427. this.facePlane = new Plane().setFromCoplanarPoints(...this.points.slice(0,3) );
  37428. }
  37429. getPoint2dInfo(points){ //在更新areaplane之前必须更新过point2dInfo
  37430. if(this.facePlane){
  37431. var originPoint0 = points[0].clone();
  37432. var qua = math.getQuaBetween2Vector(this.facePlane.normal, new Vector3(0,0,1), new Vector3(0,0,1));
  37433. let points2d = points.map(e=>e.clone().applyQuaternion(qua));
  37434. this.point2dInfo = {
  37435. originPoint0 ,
  37436. points2d,
  37437. quaInverse : qua.clone().invert()
  37438. };
  37439. }
  37440. }
  37441. setPosition (index, position) {//拖拽后设置位置
  37442. let point = this.points[index];
  37443. point.copy(position);
  37444. /* if(this.datasetId){
  37445. this.dataset_points[index] = Potree.Utils.datasetPosTransform({toDataset:true, datasetId:this.datasetId, position:point.clone()})
  37446. } */
  37447. /* if(Potree.settings.editType == 'merge'){
  37448. this.dataset_points[index] = Potree.Utils.datasetPosTransform({toDataset:true,this.points_datasets[i], position:point.clone()})
  37449. } */
  37450. let marker = this.markers[index];
  37451. this.updateMarker(marker, point);
  37452. }
  37453. updateMarker(marker, pos){
  37454. marker.position.copy(pos);
  37455. marker.update();
  37456. }
  37457. intersectSelf(points2d){//add
  37458. var len = points2d.length;
  37459. for(var i=0;i<len;i++){
  37460. for(var j=i+2;j<len;j++){
  37461. if(Math.abs(j-len-i)<2)continue;//不和邻边比
  37462. var p1 = points2d[i];
  37463. var p2 = points2d[i+1];
  37464. var p3 = points2d[j];
  37465. var p4 = points2d[(j+1)%len];
  37466. if(p1.equals(p2) || p3.equals(p4) || p1.equals(p3) || p2.equals(p3) || p1.equals(p4) || p2.equals(p4))continue
  37467. var line1 = [p1,p2];
  37468. var line2 = [p3,p4];
  37469. var intersect = math.isLineIntersect(line1, line2, false, 0.001);
  37470. if(intersect){
  37471. return true
  37472. break
  37473. }
  37474. }
  37475. }
  37476. }
  37477. removeMarker (index) {
  37478. this.points.splice(index, 1);
  37479. const marker = this.markers[index];
  37480. //this.remove(marker);
  37481. this.markers.splice(index, 1);
  37482. marker.dispatchEvent({type:'dispose'});
  37483. let edgeIndex = index; //(index === 0) ? 0 : (index - 1);
  37484. const edge = this.edges[edgeIndex];
  37485. if(edge){
  37486. this.remove(edge);
  37487. this.edges.splice(edgeIndex, 1);
  37488. edge.dispatchEvent({type:'dispose'});
  37489. }
  37490. this.point2dInfo && this.point2dInfo.points2d.splice(index, 1); //add
  37491. this.dispatchEvent({type:'removeMarker',index,marker});
  37492. }
  37493. createAreaPlane(mat){
  37494. var geometry = new Geometry();
  37495. var mesh = new Mesh(geometry, mat);
  37496. return mesh
  37497. }
  37498. updateAreaPlane(){
  37499. if(!this.point2dInfo)return
  37500. this.areaPlane.geometry.dispose();
  37501. if(this.points.length>2){
  37502. this.areaPlane.geometry = MeshDraw.getShapeGeo(this.point2dInfo.points2d);
  37503. var center = math.getCenterOfGravityPoint(this.point2dInfo.points2d); //重心
  37504. var firstPos = this.point2dInfo.points2d[0].clone();
  37505. firstPos.z = 0; //因为shape只读取了xy,所以位移下, 再算出最终位置,得到差距
  37506. firstPos.applyQuaternion(this.point2dInfo.quaInverse);
  37507. var vec = this.point2dInfo.originPoint0.clone().sub(firstPos);
  37508. center = new Vector3(center.x, center.y, 0);
  37509. center.applyQuaternion(this.point2dInfo.quaInverse);
  37510. this.areaPlane.quaternion.copy(this.point2dInfo.quaInverse);
  37511. this.areaPlane.position.copy(vec);
  37512. center.add(vec);
  37513. this.center = center;
  37514. }else {
  37515. this.areaPlane.geometry = new Geometry();
  37516. }
  37517. }
  37518. update(options={}){
  37519. if(this.points.length === 0){
  37520. return;
  37521. }
  37522. let lastIndex = this.points.length - 1;
  37523. for (let index = 0; index <= lastIndex; index++) {
  37524. let nextIndex = (index + 1 > lastIndex) ? 0 : index + 1;
  37525. let previousIndex = (index === 0) ? lastIndex : index - 1;
  37526. let point = this.points[index];
  37527. let nextPoint = this.points[nextIndex];
  37528. let previousPoint = this.points[previousIndex];
  37529. if(options.ifUpdateMarkers){
  37530. this.updateMarker(this.markers[index], point);
  37531. }
  37532. { // edges
  37533. let edge = this.edges[index];
  37534. if(edge){
  37535. LineDraw.updateLine(edge, [point, nextPoint]);
  37536. //edge.visible = index < lastIndex || this.isRect || (this.closed && !this.isNew);
  37537. }
  37538. }
  37539. }
  37540. if(this.areaPlane){
  37541. this.updateAreaPlane();
  37542. }
  37543. //this.dispatchEvent({type:'update'})
  37544. viewer.mapViewer && viewer.mapViewer.dispatchEvent('content_changed'); //暂时先这么都通知
  37545. }
  37546. dispose(){//add
  37547. this.parent.remove(this);
  37548. this.markers.concat(this.edges).forEach(e=>e.dispatchEvent({type:'dispose'}));
  37549. }
  37550. reDraw(restMarkerCount=0){//重新开始画
  37551. let pointCount = this.points.length - restMarkerCount; // restMarkerCount为需要留下的marker数量
  37552. while(pointCount > 0){
  37553. this.removeMarker(--pointCount);
  37554. }
  37555. this.point2dInfo = null;
  37556. this.facePlane = null;
  37557. }
  37558. setMarkerSelected(){}
  37559. editStateChange(state){
  37560. if(!state){
  37561. viewer.dispatchEvent({
  37562. type : "CursorChange", action : "remove", name:"polygon_isIntersectSelf"
  37563. });
  37564. viewer.dispatchEvent({
  37565. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  37566. });
  37567. viewer.dispatchEvent({type:'reticule_forbit', v:false});
  37568. this.markers.forEach(e=>e.isDragging = false );
  37569. }
  37570. }
  37571. transformData(){}
  37572. setSelected(){}
  37573. continueDrag(marker, e){
  37574. let object = marker || e.drag.object;
  37575. object.isDragging = true;
  37576. var timer = setTimeout(()=>{//等 drag=null之后 //右键拖拽结束后需要重新得到drag
  37577. if(this.parent && object.isDragging){
  37578. //console.log('continueDrag')
  37579. viewer.inputHandler.startDragging( object ,
  37580. {endDragFun: e.drag.endDragFun, notPressMouse:e.drag.notPressMouse, dragViewport:e.drag.dragViewport}
  37581. );
  37582. }
  37583. },1);
  37584. return timer
  37585. }
  37586. }
  37587. function getDifferentPoint(points, count){//for facePlane
  37588. var result = [];
  37589. for(let i=0;i<points.length;i++){
  37590. var p = points[i];
  37591. if(result.find(e=>e.equals(p)))continue;
  37592. else result.push(p);
  37593. if(result.length == count)break
  37594. }
  37595. if(result.length == count)return result
  37596. }
  37597. let texLoader = new TextureLoader();
  37598. let defaultColor$1 = new Color(config$1.measure.default.color);
  37599. let highlightColor = new Color(config$1.measure.highlight.color);
  37600. let color = new Color(config$1.measure.color);
  37601. let textColor = new Color(config$1.measure.textColor);
  37602. var markerMats;
  37603. var lineMats;
  37604. var planeMats;
  37605. const lineDepthInfo = {
  37606. clipDistance : 4,//消失距离
  37607. occlusionDistance: 1,//变为backColor距离
  37608. };
  37609. const LabelDepthInfo = {
  37610. clipDistance : 6,//消失距离
  37611. occlusionDistance: 2,//变为backColor距离
  37612. };
  37613. /* const LabelDepthInfo = {
  37614. clipDistance : 0.1,//消失距离
  37615. occlusionDistance: 0.1,//变为backColor距离
  37616. } */
  37617. const markerSizeInfo = {
  37618. minSize : 25 , maxSize : 65, nearBound : 0.2, farBound : 4,
  37619. };
  37620. const labelSizeInfo = {width2d:200};
  37621. const mainLabelProp = {
  37622. backgroundColor: {r: defaultColor$1.r*255, g: defaultColor$1.g*255, b: defaultColor$1.b*255, a:config$1.measure.default.opacity},
  37623. textColor: {r: textColor.r*255, g: textColor.g*255, b: textColor.b*255, a: 1.0},
  37624. fontsize:16,
  37625. useDepth : true ,
  37626. renderOrder : 5, pickOrder:5,
  37627. };
  37628. const subLabelProp = {
  37629. backgroundColor: {r: 255, g: 255, b: 255, a:1},
  37630. textColor: {r: 0, g: 0, b:0, a: 1.0},
  37631. fontsize:14,
  37632. renderOrder : 4, pickOrder:4,
  37633. };
  37634. const angle = MathUtils.degToRad(5);//显示水平垂直辅助线的最小角度
  37635. const guideShowMinAngle = {min: angle, max: Math.PI/2 - angle};
  37636. class Measure extends ctrlPolygon{
  37637. constructor (prop) {
  37638. prop.dimension = '2d';
  37639. super('measure',prop);
  37640. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  37641. this.name = this.measureType + this.constructor.counter; //'Measure_' + this.constructor.counter;
  37642. this.markerLabels = [];
  37643. this.edgeLabels = [];
  37644. this.angleLabels = [];
  37645. this.coordinateLabels = [];
  37646. this.area = {value:0,string:''};
  37647. if(this.closed/* this.showArea */){
  37648. this.areaLabel = this.createAreaLabel();
  37649. this.add(this.areaLabel);
  37650. }
  37651. //add:
  37652. if(this.maxMarkers > 2 || this.faceDirection){
  37653. this.createGuideLine();
  37654. }
  37655. if(this.measureType == 'Distance'){
  37656. this.createHorVerGuideLine();
  37657. }
  37658. this.selectStates = {};
  37659. this.setUnitSystem(prop.unit || viewer.unitConvert.UnitService.defaultSystem);
  37660. viewer.setObjectLayers(this, 'measure' );
  37661. //addMarkers:
  37662. this.initData(prop);
  37663. this.points_datasets || (this.points_datasets = []); //存每个点是哪个数据集
  37664. this.addEventListener('marker_dropped',(e)=>{
  37665. this.updateDatasetBelong(e.index);
  37666. });
  37667. this.addEventListener('isVisible', ()=>{
  37668. viewer.mapViewer && viewer.mapViewer.dispatchEvent({type:'content_changed'});
  37669. });
  37670. }
  37671. initData(prop){
  37672. let makeIt = super.initData(prop);
  37673. if(makeIt){
  37674. this.edges.forEach(edge=>{edge.dispatchEvent('addHoverEvent'); });
  37675. }else {
  37676. this.failBuilded = true;
  37677. }
  37678. }
  37679. updateDatasetBelong(changeIndex){//更新所属数据集
  37680. if(Potree.settings.editType == "merge"){//无地图
  37681. /* this.dataset_points = this.points.map((e,i)=>{
  37682. return Potree.Utils.datasetPosTransform({toDataset:true, datasetId:this.points_datasets[i], position:e.clone()})
  37683. }) */
  37684. this.dataset_points[changeIndex] = Potree.Utils.datasetPosTransform({toDataset:true, datasetId:this.points_datasets[changeIndex], position:this.points[changeIndex].clone()});
  37685. return
  37686. }
  37687. let old = this.datasetId;
  37688. let maxCount = {id:null,count:0};
  37689. let datasets = {};
  37690. this.points_datasets.forEach(e=>{
  37691. if(e == void 0)return
  37692. if(datasets[e]){
  37693. datasets[e] ++;
  37694. }else {
  37695. datasets[e] = 1;
  37696. }
  37697. });
  37698. for(let i in datasets) {
  37699. if(datasets[i]>maxCount.count){
  37700. maxCount = {id:i, count:datasets[i]};
  37701. }
  37702. }
  37703. this.datasetId = maxCount.count > 0 ? maxCount.id : null;
  37704. //if(this.datasetId != old){
  37705. //this.dispatchEvent({type:'changeDatasetId'})
  37706. if(this.datasetId == void 0){
  37707. this.dataset_points = null; //可能为空或[null,null...]
  37708. }else {
  37709. this.dataset_points = this.points.map(e=>{
  37710. return Potree.Utils.datasetPosTransform({toDataset:true,datasetId:this.datasetId, position:e.clone()})
  37711. });
  37712. }
  37713. //}
  37714. }
  37715. transformByPointcloud(){//每次移动点云 or 加载测量线时要获取一下当前position //有地图时
  37716. if(this.datasetId == void 0)return
  37717. this.points = this.dataset_points.map(e=>{
  37718. return Potree.Utils.datasetPosTransform({fromDataset:true, datasetId:this.datasetId, position:e.clone()})
  37719. });
  37720. this.getPoint2dInfo(this.points);
  37721. this.update({ifUpdateMarkers:true});
  37722. this.setSelected(false);//隐藏edgelabel
  37723. }
  37724. update(options={}) {
  37725. super.update(options);
  37726. if(this.showCoordinates && this.points.length>0){
  37727. let position = this.points[0];
  37728. this.markers[0].position.copy(position);
  37729. { // coordinate labels
  37730. let coordinateLabel = this.coordinateLabels[0];
  37731. let lonlat = viewer.transform.lonlatToLocal.inverse(position.toArray());
  37732. let EPSG4550 = viewer.transform.lonlatTo4550.forward(lonlat);
  37733. let pos = [
  37734. position.toArray(),
  37735. lonlat,
  37736. EPSG4550
  37737. ];
  37738. //let msg = position.toArray().map(p => Utils.addCommas(p.toFixed(2))).join(" / ");
  37739. let msg = pos.map(a=>
  37740. a.map(p => Utils.addCommas(p.toFixed(10))).join(", ")
  37741. ).join("<br>");
  37742. coordinateLabel.setText(msg);
  37743. coordinateLabel.setPos(position);
  37744. coordinateLabel.setVisible(true);//this.showCoordinates;
  37745. }
  37746. return
  37747. }
  37748. let setEdgeLabel = (label,p1,p2,distance)=>{//设置label位置和字
  37749. let center = new Vector3().addVectors(p1,p2).multiplyScalar(0.5);
  37750. label.setPos(center);
  37751. distance = distance == void 0 ? p1.distanceTo(p2) : distance;
  37752. var text = viewer.unitConvert.convert(distance, 'distance', 3, this.unitSystem, 0.1 , true);//distance要传0.1 这个factor
  37753. label.setText(text);
  37754. return distance
  37755. };
  37756. let lastIndex = this.points.length - 1;
  37757. for (let index = 0; index <= lastIndex; index++) {
  37758. let nextIndex = (index + 1 > lastIndex) ? 0 : index + 1;
  37759. let previousIndex = (index === 0) ? lastIndex : index - 1;
  37760. let point = this.points[index];
  37761. let nextPoint = this.points[nextIndex];
  37762. let previousPoint = this.points[previousIndex];
  37763. if(this.showDistances){ // edge labels
  37764. let edgeLabel = this.edgeLabels[index];
  37765. let distance = point.distanceTo(nextPoint);
  37766. edgeLabel.shouldVisi = (index < lastIndex || this.isRect || this.closed && !this.isNew /* && this.points.length > 2 */) && distance>0;
  37767. /* this.closed || */edgeLabel.setVisible(edgeLabel.shouldVisi);
  37768. if(edgeLabel.visible){
  37769. setEdgeLabel(edgeLabel,point,nextPoint,distance);
  37770. }
  37771. }
  37772. }
  37773. if(this.measureType == 'Distance' && this.points.length>1){//设置水平垂直辅助线
  37774. var pTop, pBtm;
  37775. if(this.points[0].z > this.points[1].z ){
  37776. pTop = this.points[0];
  37777. pBtm = this.points[1];
  37778. }else {
  37779. pTop = this.points[1];
  37780. pBtm = this.points[0];
  37781. }
  37782. let projectPos = new Vector3(pTop.x, pTop.y, pBtm.z);//两条guideline的交点
  37783. {//倾斜角度太小的时候不显示
  37784. let tan = pTop.distanceTo(projectPos) / pBtm.distanceTo(projectPos);
  37785. let angle = Math.atan(tan);
  37786. this.shouldShowHorVerGuide = angle > guideShowMinAngle.min && angle < guideShowMinAngle.max;
  37787. }
  37788. LineDraw.updateLine(this.verGuideEdge, [pTop, projectPos]);
  37789. LineDraw.updateLine(this.horGuideEdge, [pBtm, projectPos]);
  37790. setEdgeLabel(this.verEdgeLabel,pTop,projectPos);
  37791. setEdgeLabel(this.horEdgeLabel,pBtm,projectPos);
  37792. this.verGuideEdge.visible = this.horGuideEdge.visible = this.shouldShowHorVerGuide;
  37793. this.verEdgeLabel.visible = this.horEdgeLabel.visible = this.shouldShowHorVerGuide;
  37794. }
  37795. if(this.showArea && this.point2dInfo){ // update area
  37796. /* if(this.points.length>2){
  37797. this.area = {value:0};
  37798. this.areaLabel.setVisible(false)
  37799. }else{ */
  37800. let area = Math.abs(math.getArea(this.point2dInfo.points2d));//this.getArea();
  37801. let msg = viewer.unitConvert.convert(area, 'area', 3, this.unitSystem/* , 0.1 */ );
  37802. this.area = {value:area, string:msg};
  37803. this.areaLabel.setPos(this.center);
  37804. this.areaLabel.setText(msg);
  37805. this.areaLabel.setVisible(true);
  37806. //}
  37807. }
  37808. };
  37809. addMarker (o={}) {
  37810. let marker = new Sprite$1({mat:this.getMarkerMaterial('default'), sizeInfo: markerSizeInfo, name:"measure_point"} );
  37811. viewer.setObjectLayers(marker, 'measure' );
  37812. marker.pickOrder = marker.renderOrder = 3;
  37813. marker.markerSelectStates = {};
  37814. marker.addEventListener('startDragging',(e)=>{
  37815. if(e.drag.dragViewport.name == 'MainView')viewer.inputHandler.dispatchEvent( {type: 'isMeasuring',v:true, cause:'startDragging'});
  37816. });
  37817. marker.addEventListener('drop',(e)=>{
  37818. viewer.inputHandler.dispatchEvent({type: 'isMeasuring', v:false, cause:'stopDragging'} );
  37819. });
  37820. let edge;
  37821. { // edges
  37822. edge = LineDraw.createFatLine( [ ],{material:this.getLineMat('edgeDefault')} );
  37823. edge.pickOrder = 0;
  37824. viewer.setObjectLayers(edge, 'measure' );
  37825. let addHoverEvent = ()=>{ //当非isNew时才添加事件
  37826. let mouseover = (e) => {this.setSelected(true, 'edge');};
  37827. let mouseleave = (e) => {this.setSelected(false, 'edge');};
  37828. edge.addEventListener('mouseover', mouseover);
  37829. edge.addEventListener('mouseleave', mouseleave);
  37830. edge.removeEventListener('addHoverEvent', addHoverEvent);
  37831. };
  37832. edge.addEventListener('addHoverEvent', addHoverEvent);
  37833. }
  37834. super.addMarker({point:o.point, marker:marker, edge});
  37835. if(this.showEdges){ // edge labels
  37836. const edgeLabel = this.createEdgeLabel('edgeLabel', !this.closed);
  37837. this.edgeLabels.push(edgeLabel);
  37838. }
  37839. if(this.showCoordinates){ // coordinate labels
  37840. let coordinateLabel = new Label({
  37841. className:'measure_pointPos',
  37842. camera: viewer.scene.getActiveCamera()
  37843. });
  37844. coordinateLabel.setVisible(false);
  37845. this.coordinateLabels.push(coordinateLabel);
  37846. }
  37847. let event = {
  37848. type: 'marker_added',
  37849. measurement: this,
  37850. marker: marker
  37851. };
  37852. this.dispatchEvent(event);
  37853. //this.setMarker(this.points.length - 1, point);
  37854. this.update();//更新一下倒数第二条线
  37855. return marker;//add
  37856. };
  37857. editStateChange(state){ //主要针对edgeLabels显示切换,编辑时显示
  37858. super.editStateChange(state);
  37859. if(!state){
  37860. this.editStateTimer = setTimeout(()=>{
  37861. if(!this.isEditing){
  37862. this.dispatchEvent({type:'editStateChange',state:false});
  37863. this.setEdgesDisplay(false);
  37864. }
  37865. },100);
  37866. }else {
  37867. if(!this.isEditing){
  37868. this.dispatchEvent({type:'editStateChange',state:true});
  37869. this.setEdgesDisplay(true);
  37870. clearTimeout(this.editStateTimer);
  37871. }
  37872. }
  37873. this.isEditing = state;
  37874. }
  37875. setMarkerSelected(marker, state, hoverObject){
  37876. //console.warn(marker.id , state, hoverObject)
  37877. marker.markerSelectStates[hoverObject] = state;
  37878. let absoluteState = false;
  37879. for(var i in marker.markerSelectStates){
  37880. if(marker.markerSelectStates[i] == 'hover'){
  37881. absoluteState = true; break;
  37882. }
  37883. }
  37884. if(absoluteState){
  37885. marker.material = this.getMarkerMaterial('select');
  37886. }else {
  37887. marker.material = this.getMarkerMaterial('default');
  37888. }
  37889. marker.selected = absoluteState;
  37890. viewer.mapViewer && viewer.mapViewer.dispatchEvent('content_changed');
  37891. }
  37892. setEdgesDisplay(state, ignoreGuideLine){
  37893. this.closed && this.edgeLabels.forEach(e=>e.setVisible(!!(state && e.shouldVisi)) );
  37894. if(!ignoreGuideLine && this.measureType == 'Distance'){
  37895. this.horEdgeLabel.visible = this.verEdgeLabel.visible = this.horGuideEdge.visible = this.verGuideEdge.visible = !!(state && this.shouldShowHorVerGuide);
  37896. }
  37897. }
  37898. setSelected(state, hoverObject){//add
  37899. //console.log('setSelected',state, hoverObject)
  37900. hoverObject && (this.selectStates[hoverObject] = state);
  37901. let absoluteState = false;
  37902. for(var i in this.selectStates){
  37903. if(this.selectStates[i]){
  37904. absoluteState = true; break;
  37905. }
  37906. }
  37907. if(absoluteState){
  37908. this.markers.forEach(e=>this.setMarkerSelected(e, 'hover', 'selectAll' ) );
  37909. this.edges.forEach(e=>e.material = this.getLineMat('edgeSelect') );
  37910. this.areaPlane && (this.areaPlane.material = planeMats.selected);
  37911. //this.areaLabel && this.areaLabel.elem.addClass('highLight')
  37912. //this.closed || this.edgeLabels.forEach(e=>e.elem.addClass('highLight') )
  37913. this.setEdgesDisplay(true, hoverObject=="screenshot");
  37914. this.areaLabel && setLabelHightState(this.areaLabel, true);
  37915. this.closed || this.edgeLabels.forEach(e=>setLabelHightState(e, true) );
  37916. }else {
  37917. this.markers.forEach(e=>this.setMarkerSelected(e, 'unhover', 'selectAll' ));
  37918. this.edges.forEach(e=>e.material = this.getLineMat('edgeDefault') );
  37919. this.areaPlane && (this.areaPlane.material = planeMats.default);
  37920. this.setEdgesDisplay(false, hoverObject=="screenshot");
  37921. //this.areaLabel && this.areaLabel.elem.removeClass('highLight')
  37922. //this.closed || this.edgeLabels.forEach(e=>e.elem.removeClass('highLight') )
  37923. this.areaLabel && setLabelHightState(this.areaLabel, false);
  37924. this.closed || this.edgeLabels.forEach(e=>setLabelHightState(e, false) );
  37925. }
  37926. this.selected = absoluteState;
  37927. viewer.mapViewer && viewer.mapViewer.dispatchEvent('content_changed');
  37928. if(hoverObject != 'byList'){
  37929. //this.bus && this.bus.emit('highlight', this.selected)
  37930. this.dispatchEvent({type:'highlight',state:this.selected});//列表高亮
  37931. }
  37932. }
  37933. removeMarker(index ){
  37934. super.removeMarker(index);
  37935. this.points_datasets.splice(index, 1);
  37936. this.dataset_points && this.dataset_points.splice(index, 1);
  37937. this.coordinateLabels.splice(index, 1);
  37938. let edgeIndex = index;//(index === 0) ? 0 : (index - 1);
  37939. if(this.edgeLabels[edgeIndex]){
  37940. this.edgeLabels[edgeIndex].dispose();
  37941. this.edgeLabels.splice(edgeIndex, 1);
  37942. }
  37943. this.update();
  37944. this.dispatchEvent({type: 'marker_removed', measurement: this});
  37945. }
  37946. setPosition(index, position) {
  37947. super.setPosition(index, position);
  37948. let event = {
  37949. type: 'marker_moved',
  37950. measure: this,
  37951. index: index,
  37952. position: position.clone()
  37953. };
  37954. this.dispatchEvent(event);
  37955. }
  37956. dispose(){//add
  37957. var labels = this.edgeLabels.concat(this.coordinateLabels);
  37958. this.areaLabel && labels.push(this.areaLabel);
  37959. labels.forEach(e=>e.dispatchEvent({type:'dispose'}));
  37960. super.dispose();
  37961. }
  37962. getTotalDistance () {
  37963. if (this.points.length === 0) {
  37964. return 0;
  37965. }
  37966. let distance = 0;
  37967. for (let i = 1; i < this.points.length; i++) {
  37968. let prev = this.points[i - 1];
  37969. let curr = this.points[i];
  37970. let d = prev.distanceTo(curr);
  37971. distance += d;
  37972. }
  37973. if (this.closed && this.points.length > 1) {
  37974. let first = this.points[0];
  37975. let last = this.points[this.points.length - 1];
  37976. let d = last.distanceTo(first);
  37977. distance += d;
  37978. }
  37979. return distance;
  37980. }
  37981. getAngleBetweenLines (cornerPoint, point1, point2) {
  37982. let v1 = new Vector3().subVectors(point1, cornerPoint);
  37983. let v2 = new Vector3().subVectors(point2, cornerPoint);
  37984. // avoid the error printed by threejs if denominator is 0
  37985. const denominator = Math.sqrt( v1.lengthSq() * v2.lengthSq() );
  37986. if(denominator === 0){
  37987. return 0;
  37988. }else {
  37989. return v1.angleTo(v2);
  37990. }
  37991. };
  37992. getAngle (index) {
  37993. if (this.points.length < 3 || index >= this.points.length) {
  37994. return 0;
  37995. }
  37996. let previous = (index === 0) ? this.points[this.points.length - 1] : this.points[index - 1];
  37997. let point = this.points[index];
  37998. let next = this.points[(index + 1) % (this.points.length)];
  37999. return this.getAngleBetweenLines(point, previous, next);
  38000. }
  38001. getCenter(/* update */){
  38002. if(this.points.length>=3){
  38003. return this.center.clone()
  38004. }else if(this.points.length == 2){
  38005. return this.points[0].clone().add((this.points[1])).multiplyScalar(0.5)
  38006. }else return this.points[0].clone()
  38007. }
  38008. // updateAzimuth(){
  38009. // // if(this.points.length !== 2){
  38010. // // return;
  38011. // // }
  38012. // // const azimuth = this.azimuth;
  38013. // // const [p0, p1] = this.points;
  38014. // // const r = p0.distanceTo(p1);
  38015. // }
  38016. createGuideLine(){//add 辅助线
  38017. var guideLine = LineDraw.createFatLine([ ],{material:this.getLineMat('guide')} );
  38018. guideLine.visible = false;
  38019. this.guideLine = guideLine;
  38020. this.add(guideLine);
  38021. }
  38022. createHorVerGuideLine(){//创建水平与垂直辅助线,仅距离测量有。
  38023. var verGuideEdge = LineDraw.createFatLine([ ],{material:this.getLineMat('guide')} );
  38024. verGuideEdge.visible = false;
  38025. this.verGuideEdge = verGuideEdge;
  38026. var horGuideEdge = LineDraw.createFatLine([ ],{material:this.getLineMat('guide')} );
  38027. horGuideEdge.visible = false;
  38028. this.horGuideEdge = horGuideEdge;
  38029. this.add(this.verGuideEdge);
  38030. this.add(this.horGuideEdge);
  38031. //label:
  38032. this.verEdgeLabel = this.createEdgeLabel('verGuideEdge');
  38033. this.horEdgeLabel = this.createEdgeLabel('horGuideEdge');
  38034. }
  38035. createEdgeLabel(name, hasHoverEvent){
  38036. const edgeLabel = new TextSprite(
  38037. $.extend(hasHoverEvent ? mainLabelProp : subLabelProp,{sizeInfo: labelSizeInfo, name:name||'edgeLabel'})
  38038. );
  38039. if(hasHoverEvent){
  38040. edgeLabel.addEventListener('mouseover',()=>{
  38041. this.setSelected(true, 'edgeLabel');
  38042. });
  38043. edgeLabel.addEventListener('mouseleave',()=>{
  38044. this.setSelected(false, 'edgeLabel');
  38045. });
  38046. edgeLabel.addEventListener('click',()=>{
  38047. viewer.focusOnObject(this, 'measure');
  38048. });
  38049. }
  38050. edgeLabel.visible = false;
  38051. edgeLabel.sprite.material.depthTestWhenPick = true;
  38052. viewer.setObjectLayers(edgeLabel, 'measure' );
  38053. this.add(edgeLabel);
  38054. return edgeLabel
  38055. }
  38056. createAreaLabel(){
  38057. /* const areaLabel = new Label({
  38058. className:'measure_area',
  38059. })
  38060. areaLabel.elem.on('mouseover',()=>{
  38061. this.setSelected(true, 'areaLabel')
  38062. })
  38063. areaLabel.elem.on('mouseout',()=>{
  38064. this.setSelected(false, 'areaLabel')
  38065. }) */
  38066. const areaLabel = new TextSprite(
  38067. $.extend(mainLabelProp,{sizeInfo: labelSizeInfo, name:'areaLabel_'} )
  38068. );
  38069. areaLabel.addEventListener('mouseover',()=>{
  38070. this.setSelected(true, 'areaLabel');
  38071. });
  38072. areaLabel.addEventListener('mouseleave',()=>{
  38073. this.setSelected(false, 'areaLabel');
  38074. });
  38075. areaLabel.addEventListener('click',()=>{
  38076. viewer.focusOnObject(this, 'measure');
  38077. });
  38078. viewer.setObjectLayers(areaLabel, 'measure' );
  38079. areaLabel.visible = false;
  38080. return areaLabel;
  38081. }
  38082. getMarkerMaterial(type) {
  38083. if(!markerMats){
  38084. markerMats = {
  38085. default: new DepthBasicMaterial($.extend({},lineDepthInfo,{
  38086. transparent: !0,
  38087. opacity: 1,
  38088. map: texLoader.load(Potree.resourcePath+'/textures/pic_point_s32.png' ),
  38089. useDepth:true
  38090. })),
  38091. select: new MeshBasicMaterial({
  38092. transparent: !0,
  38093. opacity: 1,
  38094. depthTest:false,
  38095. map: texLoader.load(Potree.resourcePath+'/textures/pic_point32.png'/* , null, null, { antialias: false } */),
  38096. }),
  38097. };
  38098. Measure.markerMats = markerMats;
  38099. }
  38100. return markerMats[type]
  38101. }
  38102. getLineMat(type) {
  38103. if(!Measure.lineMats){
  38104. Measure.lineMats = {
  38105. edgeDefault: LineDraw.createFatLineMat({
  38106. color: config$1.measure.default.color,
  38107. lineWidth: config$1.measure.lineWidth,
  38108. useDepth :true,
  38109. dashWithDepth :true, // 只在被遮住的部分显示虚线,因为实线容易挡住label
  38110. dashed :true,
  38111. dashSize : 0.04,
  38112. gapSize: 0.04,
  38113. transparent: true,
  38114. opacity: config$1.measure.default.opacity,
  38115. depthTestWhenPick:true,
  38116. }),
  38117. edgeSelect: LineDraw.createFatLineMat({
  38118. color: config$1.measure.highlight.color,//'#f0ff00',
  38119. dashSize: 0.5,
  38120. gapSize: 0.2,
  38121. lineWidth: config$1.measure.lineWidth ,
  38122. transparent: true,
  38123. opacity: config$1.measure.highlight.opacity
  38124. }),
  38125. guide: LineDraw.createFatLineMat({
  38126. color:config$1.measure.guide.color,
  38127. dashSize: 0.1,
  38128. gapSize: 0.02,
  38129. dashed: true,
  38130. lineWidth: config$1.measure.lineWidth
  38131. })
  38132. };
  38133. }
  38134. return Measure.lineMats[type]
  38135. }
  38136. createAreaPlane(){
  38137. planeMats || (planeMats = {
  38138. default: new DepthBasicMaterial( $.extend({},LabelDepthInfo,{
  38139. color:color,
  38140. side:DoubleSide,
  38141. opacity:0.2,
  38142. transparent:true,
  38143. useDepth:true
  38144. })),
  38145. selected: new MeshBasicMaterial({
  38146. color: color ,
  38147. side:DoubleSide,
  38148. opacity:0.3,
  38149. transparent:true,
  38150. })
  38151. },Measure.planeMats = planeMats);
  38152. return super.createAreaPlane(planeMats.default)
  38153. }
  38154. raycast (raycaster, intersects) {
  38155. for (let i = 0; i < this.points.length; i++) {
  38156. let marker = this.markers[i];
  38157. marker.raycast(raycaster, intersects);
  38158. }
  38159. // recalculate distances because they are not necessarely correct
  38160. // for scaled objects.
  38161. // see https://github.com/mrdoob/three.js/issues/5827
  38162. // TODO: remove this once the bug has been fixed
  38163. for (let i = 0; i < intersects.length; i++) {
  38164. let I = intersects[i];
  38165. I.distance = raycaster.ray.origin.distanceTo(I.point);
  38166. }
  38167. intersects.sort(function (a, b) { return a.distance - b.distance; });
  38168. };
  38169. transformData(prop){
  38170. if(prop.measureType == 'Point'){
  38171. prop.showCoordinates = true,
  38172. prop.closed = true,
  38173. prop.maxMarkers = 1,
  38174. prop.minMarkers = 1;
  38175. }else if(prop.measureType == 'Distance'){
  38176. prop.showDistances = true,
  38177. prop.closed = false,
  38178. prop.showEdges = true,
  38179. prop.maxMarkers = 2,
  38180. prop.minMarkers = 2;
  38181. }else if(prop.measureType == 'Ver Distance'){
  38182. prop.showDistances = true,
  38183. prop.closed = false,
  38184. prop.showEdges = true,
  38185. prop.maxMarkers = 2,
  38186. prop.minMarkers = 2,
  38187. prop.faceDirection = "vertical";
  38188. prop.unableDragAtMap = true;
  38189. }else if(prop.measureType == 'Hor Distance'){
  38190. prop.showDistances = true,
  38191. prop.closed = false,
  38192. prop.showEdges = true,
  38193. prop.maxMarkers = 2,
  38194. prop.minMarkers = 2,
  38195. prop.faceDirection = "horizontal";
  38196. }else if(prop.measureType == 'Area'){
  38197. prop.showDistances = true,
  38198. prop.showArea = true,
  38199. prop.showEdges = true,
  38200. prop.closed = true,
  38201. prop.minMarkers = 3;
  38202. }else if(prop.measureType == 'Hor Area'){
  38203. prop.showDistances = true,
  38204. prop.showArea = true,
  38205. prop.showEdges = true,
  38206. prop.closed = true,
  38207. prop.minMarkers = 3;
  38208. prop.faceDirection = "horizontal";
  38209. }else if(prop.measureType == 'Ver Area'){
  38210. prop.showDistances = true,
  38211. prop.showArea = true,
  38212. prop.showEdges = true,
  38213. prop.closed = true,
  38214. prop.minMarkers = 3;
  38215. prop.faceDirection = "vertical";
  38216. prop.unableDragAtMap = true;
  38217. }else if(prop.measureType == 'Rect Area'){
  38218. prop.showDistances = true,
  38219. prop.showArea = true,
  38220. prop.showEdges = true,
  38221. prop.closed = true,
  38222. prop.minMarkers = 4;
  38223. prop.maxMarkers = 4;
  38224. }else if(prop.measureType == 'Hor Rect Area'){
  38225. prop.showDistances = true,
  38226. prop.showArea = true,
  38227. prop.showEdges = true,
  38228. prop.closed = true,
  38229. prop.minMarkers = 4;
  38230. prop.maxMarkers = 4;
  38231. prop.isRect = true;
  38232. prop.faceDirection = "horizontal";
  38233. }else if(prop.measureType == 'Ver Rect Area'){
  38234. prop.showDistances = true,
  38235. prop.showArea = true,
  38236. prop.showEdges = true,
  38237. prop.closed = true,
  38238. prop.minMarkers = 4;
  38239. prop.maxMarkers = 4;
  38240. prop.isRect = true;
  38241. prop.faceDirection = "vertical";
  38242. prop.unableDragAtMap = true;
  38243. }
  38244. }
  38245. setUnitSystem(unitSystem){
  38246. //console.log(this.name +':' +this.unitSystem)
  38247. if(unitSystem != this.unitSystem){
  38248. if(unitSystem == "metric"){
  38249. }else if(unitSystem == 'imperial'){
  38250. }
  38251. this.unitSystem = unitSystem;
  38252. this.update();
  38253. }
  38254. }
  38255. reDraw(restMarkerCount=0){//重新开始画
  38256. super.reDraw(restMarkerCount);
  38257. if(this.measureType == 'Distance'){
  38258. this.shouldShowHorVerGuide = false;
  38259. this.setEdgesDisplay(false);
  38260. }
  38261. if(this.showArea){
  38262. this.area = {value:0};
  38263. this.areaLabel && this.areaLabel.setVisible(false);
  38264. }
  38265. viewer.inputHandler.dispatchEvent( {type:'isMeasuring', v:true, cause:'reDraw'} );
  38266. }
  38267. /* get showCoordinates () {
  38268. return this._showCoordinates;
  38269. }
  38270. set showCoordinates (value) {
  38271. this._showCoordinates = value;
  38272. this.update();
  38273. }
  38274. get showAngles () {
  38275. return this._showAngles;
  38276. }
  38277. set showAngles (value) {
  38278. this._showAngles = value;
  38279. this.update();
  38280. }
  38281. get showCircle () {
  38282. return this._showCircle;
  38283. }
  38284. set showCircle (value) {
  38285. this._showCircle = value;
  38286. this.update();
  38287. }
  38288. get showAzimuth(){
  38289. return this._showAzimuth;
  38290. }
  38291. set showAzimuth(value){
  38292. this._showAzimuth = value;
  38293. this.update();
  38294. }
  38295. get showEdges () {
  38296. return this._showEdges;
  38297. }
  38298. set showEdges (value) {
  38299. this._showEdges = value;
  38300. this.update();
  38301. }
  38302. get showHeight () {
  38303. return this._showHeight;
  38304. }
  38305. set showHeight (value) {
  38306. this._showHeight = value;
  38307. this.update();
  38308. }
  38309. get showArea () {
  38310. return this._showArea;
  38311. }
  38312. set showArea (value) {
  38313. this._showArea = value;
  38314. this.update();
  38315. }
  38316. get closed () {
  38317. return this._closed;
  38318. }
  38319. set closed (value) {
  38320. this._closed = value;
  38321. this.update();
  38322. }
  38323. get showDistances () {
  38324. return this._showDistances;
  38325. }
  38326. set showDistances (value) {
  38327. this._showDistances = value;
  38328. this.update();
  38329. } */
  38330. }
  38331. function setLabelHightState(label, state){
  38332. if(state){
  38333. label.backgroundColor = {r: highlightColor.r*255, g: highlightColor.g*255, b: highlightColor.b*255, a:config$1.measure.highlight.opacity},
  38334. label.backgroundColor.a = config$1.measure.highlight.opacity;
  38335. label.sprite.material.useDepth = false;
  38336. }else {
  38337. label.backgroundColor = mainLabelProp.backgroundColor;
  38338. label.backgroundColor.a = config$1.measure.default.opacity;
  38339. label.sprite.material.useDepth = true;
  38340. }
  38341. label.updateTexture();
  38342. //label.sprite.material.needsUpdate = true
  38343. }
  38344. function createCircleRadiusLabel(){
  38345. const circleRadiusLabel = new TextSprite("");
  38346. circleRadiusLabel.setTextColor({r: 140, g: 250, b: 140, a: 1.0});
  38347. circleRadiusLabel.setBorderColor({r: 0, g: 0, b: 0, a: 1.0});
  38348. circleRadiusLabel.setBackgroundColor({r: 0, g: 0, b: 0, a: 1.0});
  38349. circleRadiusLabel.fontsize = 16;
  38350. circleRadiusLabel.material.depthTest = false;
  38351. circleRadiusLabel.material.opacity = 1;
  38352. circleRadiusLabel.visible = false;
  38353. return circleRadiusLabel;
  38354. }
  38355. function createCircleRadiusLine(){
  38356. /* const lineGeometry = new LineGeometry();
  38357. lineGeometry.setPositions([
  38358. 0, 0, 0,
  38359. 0, 0, 0,
  38360. ]);
  38361. const lineMaterial = new LineMaterial({
  38362. color: 0xff0000,
  38363. lineWidth: 2,
  38364. resolution: new THREE.Vector2(1000, 1000),
  38365. gapSize: 1,
  38366. dashed: true,
  38367. });
  38368. lineMaterial.depthTest = false;
  38369. const circleRadiusLine = new Line2(lineGeometry, lineMaterial);*/
  38370. var circleRadiusLine = LineDraw.createFatLine([ ],{
  38371. color:0xff0000,
  38372. dashSize: 0.5,
  38373. gapSize: 0.2,
  38374. lineWidth: config$1.measure.lineWidth
  38375. });
  38376. circleRadiusLine.visible = false;
  38377. return circleRadiusLine;
  38378. }
  38379. function createCircleLine(){
  38380. const coordinates = [];
  38381. let n = 128;
  38382. for(let i = 0; i <= n; i++){
  38383. let u0 = 2 * Math.PI * (i / n);
  38384. let u1 = 2 * Math.PI * (i + 1) / n;
  38385. let p0 = new Vector3(
  38386. Math.cos(u0),
  38387. Math.sin(u0),
  38388. 0
  38389. );
  38390. let p1 = new Vector3(
  38391. Math.cos(u1),
  38392. Math.sin(u1),
  38393. 0
  38394. );
  38395. coordinates.push(
  38396. p0,
  38397. p1
  38398. );
  38399. }
  38400. /* const geometry = new LineGeometry();
  38401. geometry.setPositions(coordinates);
  38402. const material = new LineMaterial({
  38403. color: 0xff0000,
  38404. dashSize: 5,
  38405. gapSize: 2,
  38406. lineWidth: 2,
  38407. resolution: new THREE.Vector2(1000, 1000),
  38408. });
  38409. material.depthTest = false;
  38410. const circleLine = new Line2(geometry, material);
  38411. circleLine.visible = false;
  38412. circleLine.computeLineDistances();*/
  38413. var circleLine = LineDraw.createFatLine(coordinates,{
  38414. color: 0xff0000,
  38415. dashSize: 0.5,
  38416. gapSize: 0.2,
  38417. lineWidth: config$1.measure.lineWidth
  38418. });
  38419. return circleLine;
  38420. }
  38421. /* function createCircleCenter(){
  38422. const sg = new THREE.markerGeometry(1, 32, 32);
  38423. const sm = new THREE.MeshNormalMaterial();
  38424. const circleCenter = new THREE.Mesh(sg, sm);
  38425. circleCenter.visible = false;
  38426. return circleCenter;
  38427. } */
  38428. function createLine(){
  38429. const line = LineDraw.createFatLine([ ],{
  38430. color: 0xff0000,
  38431. dashSize: 0.5,
  38432. gapSize: 0.2,
  38433. lineWidth: config$1.measure.lineWidth
  38434. });
  38435. return line;
  38436. }
  38437. function createCircle(){
  38438. const coordinates = [];
  38439. let n = 128;
  38440. for(let i = 0; i <= n; i++){
  38441. let u0 = 2 * Math.PI * (i / n);
  38442. let u1 = 2 * Math.PI * (i + 1) / n;
  38443. let p0 = new Vector3(
  38444. Math.cos(u0),
  38445. Math.sin(u0),
  38446. 0
  38447. );
  38448. let p1 = new Vector3(
  38449. Math.cos(u1),
  38450. Math.sin(u1),
  38451. 0
  38452. );
  38453. coordinates.push(
  38454. p0,
  38455. p1
  38456. );
  38457. }
  38458. var line = LineDraw.createFatLine(coordinates,{
  38459. color: 0xff0000,
  38460. dashSize: 0.5,
  38461. gapSize: 0.2,
  38462. lineWidth: config$1.measure.lineWidth
  38463. });
  38464. return line;
  38465. }
  38466. /* function createAzimuth(){
  38467. const azimuth = {
  38468. label: null,
  38469. center: null,
  38470. target: null,
  38471. north: null,
  38472. centerToNorth: null,
  38473. centerToTarget: null,
  38474. centerToTargetground: null,
  38475. targetgroundToTarget: null,
  38476. circle: null,
  38477. node: null,
  38478. };
  38479. const sg = new THREE.markerGeometry(1, 32, 32);
  38480. const sm = new THREE.MeshNormalMaterial();
  38481. {
  38482. const label = new TextSprite("");
  38483. label.setTextColor({r: 140, g: 250, b: 140, a: 1.0});
  38484. label.setBorderColor({r: 0, g: 0, b: 0, a: 1.0});
  38485. label.setBackgroundColor({r: 0, g: 0, b: 0, a: 1.0});
  38486. label.fontsize = 16;
  38487. label.material.depthTest = false;
  38488. label.material.opacity = 1;
  38489. azimuth.label = label;
  38490. }
  38491. azimuth.center = new THREE.Mesh(sg, sm);
  38492. azimuth.target = new THREE.Mesh(sg, sm);
  38493. azimuth.north = new THREE.Mesh(sg, sm);
  38494. azimuth.centerToNorth = createLine();
  38495. azimuth.centerToTarget = createLine();
  38496. azimuth.centerToTargetground = createLine();
  38497. azimuth.targetgroundToTarget = createLine();
  38498. azimuth.circle = createCircle();
  38499. azimuth.node = new THREE.Object3D();
  38500. azimuth.node.add(
  38501. azimuth.centerToNorth,
  38502. azimuth.centerToTarget,
  38503. azimuth.centerToTargetground,
  38504. azimuth.targetgroundToTarget,
  38505. azimuth.circle,
  38506. azimuth.label,
  38507. azimuth.center,
  38508. azimuth.target,
  38509. azimuth.north,
  38510. );
  38511. return azimuth;
  38512. } */
  38513. /*
  38514. */
  38515. class PolygonClipVolume extends Object3D{
  38516. constructor(camera){
  38517. super();
  38518. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  38519. this.name = "polygon_clip_volume_" + this.constructor.counter;
  38520. this.camera = camera.clone();
  38521. this.camera.rotation.set(...camera.rotation.toArray()); // [r85] workaround because camera.clone() doesn't work on rotation
  38522. this.camera.rotation.order = camera.rotation.order;
  38523. this.camera.updateMatrixWorld();
  38524. this.camera.updateProjectionMatrix();
  38525. this.camera.matrixWorldInverse.copy(this.camera.matrixWorld).invert();
  38526. this.viewMatrix = this.camera.matrixWorldInverse.clone();
  38527. this.projMatrix = this.camera.projectionMatrix.clone();
  38528. // projected markers
  38529. this.markers = [];
  38530. this.initialized = false;
  38531. }
  38532. addMarker() {
  38533. let marker = new Mesh();
  38534. let cancel;
  38535. let drag = e => {
  38536. let size = e.viewer.renderer.getSize(new Vector2$1());
  38537. let projectedPos = new Vector3(
  38538. 2.0 * (e.drag.end.x / size.width) - 1.0,
  38539. -2.0 * (e.drag.end.y / size.height) + 1.0,
  38540. 0
  38541. );
  38542. marker.position.copy(projectedPos);
  38543. };
  38544. let drop = e => {
  38545. cancel();
  38546. };
  38547. cancel = e => {
  38548. marker.removeEventListener("drag", drag);
  38549. marker.removeEventListener("drop", drop);
  38550. };
  38551. marker.addEventListener("drag", drag);
  38552. marker.addEventListener("drop", drop);
  38553. this.markers.push(marker);
  38554. }
  38555. removeLastMarker() {
  38556. if(this.markers.length > 0) {
  38557. this.markers.splice(this.markers.length - 1, 1);
  38558. }
  38559. }
  38560. };
  38561. class Utils {
  38562. static async loadShapefileFeatures (file, callback) {
  38563. let features = [];
  38564. let handleFinish = () => {
  38565. callback(features);
  38566. };
  38567. let source = await shapefile.open(file);
  38568. while(true){
  38569. let result = await source.read();
  38570. if (result.done) {
  38571. handleFinish();
  38572. break;
  38573. }
  38574. if (result.value && result.value.type === 'Feature' && result.value.geometry !== undefined) {
  38575. features.push(result.value);
  38576. }
  38577. }
  38578. }
  38579. static toString (value) {
  38580. if (value.x != null) {
  38581. return value.x.toFixed(2) + ', ' + value.y.toFixed(2) + ', ' + value.z.toFixed(2);
  38582. } else {
  38583. return '' + value + '';
  38584. }
  38585. }
  38586. static normalizeURL (url) {
  38587. let u = new URL(url);
  38588. return u.protocol + '//' + u.hostname + u.pathname.replace(/\/+/g, '/');
  38589. };
  38590. static pathExists (url) {
  38591. let req = XHRFactory.createXMLHttpRequest();
  38592. req.open('GET', url, false);
  38593. req.send(null);
  38594. if (req.status !== 200) {
  38595. return false;
  38596. }
  38597. return true;
  38598. };
  38599. static debugSphere(parent, position, scale, color){
  38600. let geometry = new SphereGeometry(1, 8, 8);
  38601. let material;
  38602. if(color !== undefined){
  38603. material = new MeshBasicMaterial({color: color});
  38604. }else {
  38605. material = new MeshNormalMaterial();
  38606. }
  38607. let sphere = new Mesh(geometry, material);
  38608. sphere.position.copy(position);
  38609. sphere.scale.set(scale, scale, scale);
  38610. parent.add(sphere);
  38611. return sphere;
  38612. }
  38613. static debugLine(parent, start, end, color){
  38614. let material = new LineBasicMaterial({ color: color });
  38615. let geometry = new Geometry();
  38616. const p1 = new Vector3(0, 0, 0);
  38617. const p2 = end.clone().sub(start);
  38618. geometry.vertices.push(p1, p2);
  38619. let tl = new Line( geometry, material );
  38620. tl.position.copy(start);
  38621. parent.add(tl);
  38622. let line = {
  38623. node: tl,
  38624. set: (start, end) => {
  38625. geometry.vertices[0].copy(start);
  38626. geometry.vertices[1].copy(end);
  38627. geometry.verticesNeedUpdate = true;
  38628. },
  38629. };
  38630. return line;
  38631. }
  38632. static debugCircle(parent, center, radius, normal, color){
  38633. let material = new LineBasicMaterial({ color: color });
  38634. let geometry = new Geometry();
  38635. let n = 32;
  38636. for(let i = 0; i <= n; i++){
  38637. let u0 = 2 * Math.PI * (i / n);
  38638. let u1 = 2 * Math.PI * (i + 1) / n;
  38639. let p0 = new Vector3(
  38640. Math.cos(u0),
  38641. Math.sin(u0),
  38642. 0
  38643. );
  38644. let p1 = new Vector3(
  38645. Math.cos(u1),
  38646. Math.sin(u1),
  38647. 0
  38648. );
  38649. geometry.vertices.push(p0, p1);
  38650. }
  38651. let tl = new Line( geometry, material );
  38652. tl.position.copy(center);
  38653. tl.scale.set(radius, radius, radius);
  38654. parent.add(tl);
  38655. }
  38656. static debugBox(parent, box, transform = new Matrix4(), color = 0xFFFF00){
  38657. let vertices = [
  38658. [box.min.x, box.min.y, box.min.z],
  38659. [box.min.x, box.min.y, box.max.z],
  38660. [box.min.x, box.max.y, box.min.z],
  38661. [box.min.x, box.max.y, box.max.z],
  38662. [box.max.x, box.min.y, box.min.z],
  38663. [box.max.x, box.min.y, box.max.z],
  38664. [box.max.x, box.max.y, box.min.z],
  38665. [box.max.x, box.max.y, box.max.z],
  38666. ].map(v => new Vector3(...v));
  38667. let edges = [
  38668. [0, 4], [4, 5], [5, 1], [1, 0],
  38669. [2, 6], [6, 7], [7, 3], [3, 2],
  38670. [0, 2], [4, 6], [5, 7], [1, 3]
  38671. ];
  38672. let center = box.getCenter(new Vector3());
  38673. let centroids = [
  38674. {position: [box.min.x, center.y, center.z], color: 0xFF0000},
  38675. {position: [box.max.x, center.y, center.z], color: 0x880000},
  38676. {position: [center.x, box.min.y, center.z], color: 0x00FF00},
  38677. {position: [center.x, box.max.y, center.z], color: 0x008800},
  38678. {position: [center.x, center.y, box.min.z], color: 0x0000FF},
  38679. {position: [center.x, center.y, box.max.z], color: 0x000088},
  38680. ];
  38681. for(let vertex of vertices){
  38682. let pos = vertex.clone().applyMatrix4(transform);
  38683. Utils.debugSphere(parent, pos, 0.1, 0xFF0000);
  38684. }
  38685. for(let edge of edges){
  38686. let start = vertices[edge[0]].clone().applyMatrix4(transform);
  38687. let end = vertices[edge[1]].clone().applyMatrix4(transform);
  38688. Utils.debugLine(parent, start, end, color);
  38689. }
  38690. for(let centroid of centroids){
  38691. let pos = new Vector3(...centroid.position).applyMatrix4(transform);
  38692. Utils.debugSphere(parent, pos, 0.1, centroid.color);
  38693. }
  38694. }
  38695. static debugPlane(parent, plane, size = 1, color = 0x0000FF){
  38696. let planehelper = new PlaneHelper(plane, size, color);
  38697. parent.add(planehelper);
  38698. }
  38699. /**
  38700. * adapted from mhluska at https://github.com/mrdoob/three.js/issues/1561
  38701. */
  38702. static computeTransformedBoundingBox (box, transform) {
  38703. let vertices = [
  38704. new Vector3(box.min.x, box.min.y, box.min.z).applyMatrix4(transform),
  38705. new Vector3(box.min.x, box.min.y, box.min.z).applyMatrix4(transform),
  38706. new Vector3(box.max.x, box.min.y, box.min.z).applyMatrix4(transform),
  38707. new Vector3(box.min.x, box.max.y, box.min.z).applyMatrix4(transform),
  38708. new Vector3(box.min.x, box.min.y, box.max.z).applyMatrix4(transform),
  38709. new Vector3(box.min.x, box.max.y, box.max.z).applyMatrix4(transform),
  38710. new Vector3(box.max.x, box.max.y, box.min.z).applyMatrix4(transform),
  38711. new Vector3(box.max.x, box.min.y, box.max.z).applyMatrix4(transform),
  38712. new Vector3(box.max.x, box.max.y, box.max.z).applyMatrix4(transform)
  38713. ];
  38714. let boundingBox = new Box3();
  38715. boundingBox.setFromPoints(vertices);
  38716. return boundingBox;
  38717. };
  38718. /**
  38719. * add separators to large numbers
  38720. *
  38721. * @param nStr
  38722. * @returns
  38723. */
  38724. static addCommas (nStr) {
  38725. nStr += '';
  38726. let x = nStr.split('.');
  38727. let x1 = x[0];
  38728. let x2 = x.length > 1 ? '.' + x[1] : '';
  38729. let rgx = /(\d+)(\d{3})/;
  38730. while (rgx.test(x1)) {
  38731. x1 = x1.replace(rgx, '$1' + ',' + '$2');
  38732. }
  38733. return x1 + x2;
  38734. };
  38735. static removeCommas (str) {
  38736. return str.replace(/,/g, '');
  38737. }
  38738. /**
  38739. * create worker from a string
  38740. *
  38741. * code from http://stackoverflow.com/questions/10343913/how-to-create-a-web-worker-from-a-string
  38742. */
  38743. static createWorker (code) {
  38744. let blob = new Blob([code], {type: 'application/javascript'});
  38745. let worker = new Worker(URL.createObjectURL(blob));
  38746. return worker;
  38747. };
  38748. static moveTo(scene, endPosition, endTarget){
  38749. let view = scene.view;
  38750. let camera = scene.getActiveCamera();
  38751. let animationDuration = 500;
  38752. let easing = TWEEN.Easing.Quartic.Out;
  38753. { // animate camera position
  38754. let tween = new TWEEN.Tween(view.position).to(endPosition, animationDuration);
  38755. tween.easing(easing);
  38756. tween.start();
  38757. }
  38758. { // animate camera target
  38759. let camTargetDistance = camera.position.distanceTo(endTarget);
  38760. let target = new Vector3().addVectors(
  38761. camera.position,
  38762. camera.getWorldDirection(new Vector3()).clone().multiplyScalar(camTargetDistance)
  38763. );
  38764. let tween = new TWEEN.Tween(target).to(endTarget, animationDuration);
  38765. tween.easing(easing);
  38766. tween.onUpdate(() => {
  38767. view.lookAt(target);
  38768. });
  38769. tween.onComplete(() => {
  38770. view.lookAt(target);
  38771. });
  38772. tween.start();
  38773. }
  38774. }
  38775. static loadSkybox (path) {
  38776. let parent = new Object3D("skybox_root");
  38777. let camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 100000);
  38778. if(!window.axisYup) camera.up.set(0, 0, 1);
  38779. let scene = new Scene();
  38780. let format = '.jpg';
  38781. let urls = [
  38782. path + 'px' + format, path + 'nx' + format,
  38783. path + 'py' + format, path + 'ny' + format,
  38784. path + 'pz' + format, path + 'nz' + format
  38785. ];
  38786. let materialArray = [];
  38787. {
  38788. for (let i = 0; i < 6; i++) {
  38789. let material = new MeshBasicMaterial({
  38790. map: null,
  38791. side: BackSide,
  38792. depthTest: false,
  38793. depthWrite: false,
  38794. color: 0x424556
  38795. });
  38796. materialArray.push(material);
  38797. let loader = new TextureLoader();
  38798. loader.load(urls[i],
  38799. function loaded (texture) {
  38800. material.map = texture;
  38801. material.needsUpdate = true;
  38802. material.color.setHex(0xffffff);
  38803. }, function progress (xhr) {
  38804. // console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
  38805. }, function error (xhr) {
  38806. console.log('An error happened', xhr);
  38807. }
  38808. );
  38809. }
  38810. }
  38811. let skyGeometry = new BoxGeometry(700, 700, 700);
  38812. let skybox = new Mesh(skyGeometry, materialArray);
  38813. scene.add(skybox);
  38814. scene.traverse(n => n.frustumCulled = false);
  38815. // z up
  38816. scene.rotation.x = Math.PI / 2;
  38817. parent.children.push(camera);
  38818. camera.parent = parent;
  38819. return {camera, scene, parent};
  38820. };
  38821. static createGrid (width, length, spacing, color) {
  38822. let material = new LineBasicMaterial({
  38823. color: color || 0x888888
  38824. });
  38825. let geometry = new Geometry();
  38826. for (let i = 0; i <= length; i++) {
  38827. geometry.vertices.push(new Vector3(-(spacing * width) / 2, i * spacing - (spacing * length) / 2, 0));
  38828. geometry.vertices.push(new Vector3(+(spacing * width) / 2, i * spacing - (spacing * length) / 2, 0));
  38829. }
  38830. for (let i = 0; i <= width; i++) {
  38831. geometry.vertices.push(new Vector3(i * spacing - (spacing * width) / 2, -(spacing * length) / 2, 0));
  38832. geometry.vertices.push(new Vector3(i * spacing - (spacing * width) / 2, +(spacing * length) / 2, 0));
  38833. }
  38834. let line = new LineSegments(geometry, material, LinePieces);
  38835. line.receiveShadow = true;
  38836. return line;
  38837. }
  38838. static createBackgroundTexture (width, height) {
  38839. function gauss (x, y) {
  38840. return (1 / (2 * Math.PI)) * Math.exp(-(x * x + y * y) / 2);
  38841. };
  38842. // map.magFilter = THREE.NearestFilter;
  38843. let size = width * height;
  38844. let data = new Uint8Array(3 * size);
  38845. let chroma = [1, 1.5, 1.7];
  38846. let max = gauss(0, 0);
  38847. for (let x = 0; x < width; x++) {
  38848. for (let y = 0; y < height; y++) {
  38849. let u = 2 * (x / width) - 1;
  38850. let v = 2 * (y / height) - 1;
  38851. let i = x + width * y;
  38852. let d = gauss(2 * u, 2 * v) / max;
  38853. let r = (Math.random() + Math.random() + Math.random()) / 3;
  38854. r = (d * 0.5 + 0.5) * r * 0.03;
  38855. r = r * 0.4;
  38856. // d = Math.pow(d, 0.6);
  38857. data[3 * i + 0] = 255 * (d / 15 + 0.05 + r) * chroma[0];
  38858. data[3 * i + 1] = 255 * (d / 15 + 0.05 + r) * chroma[1];
  38859. data[3 * i + 2] = 255 * (d / 15 + 0.05 + r) * chroma[2];
  38860. }
  38861. }
  38862. let texture = new DataTexture(data, width, height, RGBFormat);
  38863. texture.needsUpdate = true;
  38864. return texture;
  38865. }
  38866. static getMousePointCloudIntersection (viewport, mouse, pointer, camera, viewer, pointclouds, pickParams = {} ) {
  38867. if(!pointclouds || pointclouds.length == 0)return
  38868. let renderer = viewer.renderer;
  38869. if(viewport){ //转换到类似整个画面时
  38870. /*let mouseInViewport = Utils.convertNDCToScreenPosition(pointer, null, viewport.resolution.x, viewport.resolution.y)
  38871. pickParams.x = mouseInViewport.x //mouse.x / viewport.width;
  38872. pickParams.y = mouseInViewport.y //renderer.domElement.clientHeight - mouse.y / viewport.height; */
  38873. pickParams.x = mouse.x;
  38874. pickParams.y = viewport.resolution.y - mouse.y;
  38875. }else {
  38876. pickParams.x = mouse.x;
  38877. pickParams.y = renderer.domElement.clientHeight - mouse.y;
  38878. }
  38879. //console.log('getMousePointCloudIntersection')
  38880. /* if(!raycaster){
  38881. raycaster = new THREE.Raycaster();
  38882. raycaster.setFromCamera(pointer, camera);
  38883. } */
  38884. let raycaster = new Raycaster();
  38885. raycaster.setFromCamera(pointer, camera);
  38886. let ray = raycaster.ray;
  38887. let selectedPointcloud = null;
  38888. let closestDistance = Infinity;
  38889. let closestIntersection = null;
  38890. let closestPoint = null;
  38891. let density;
  38892. let sizeType;
  38893. let size = new Map();
  38894. if(pickParams.isMeasuring || Potree.settings.displayMode == 'showPanos'){ //测量或全景模式提高精准度
  38895. density = Potree.settings.pointDensity;
  38896. Potree.settings.pointDensity = 'magnifier';
  38897. pointclouds.forEach(e=>{//因为全景模式的pointSizeType是fixed所以要还原下
  38898. size.set(e, e.temp.pointSize);
  38899. sizeType = e.material.pointSizeType;
  38900. e.material.pointSizeType = Potree.config.material.pointSizeType;
  38901. e.changePointSize(Potree.config.material.realPointSize*2, true);//更改点云大小到能铺满为止,否则容易识别不到
  38902. });
  38903. Potree.updatePointClouds(pointclouds, camera, viewport.resolution );
  38904. }else {
  38905. if(viewer.viewports.filter(e=>!e.noPointcloud && e.active).length>1 || pickParams.cameraChanged){
  38906. viewport.beforeRender && viewport.beforeRender();
  38907. Potree.updatePointClouds(pointclouds, camera, viewport.resolution ); //不加这句的话hover久了会不准 因node是错的
  38908. //但依旧需要camera真的移动到那个位置才能加载出点云
  38909. }
  38910. }
  38911. let allPointclouds = [];
  38912. for(let pointcloud of pointclouds){
  38913. let point = pointcloud.pick(viewer, viewport, camera, ray, pickParams );
  38914. if(!point){
  38915. continue;
  38916. }
  38917. allPointclouds.push(pointcloud);
  38918. let distance = camera.position.distanceTo(point.position);
  38919. if (distance < closestDistance) {
  38920. closestDistance = distance;
  38921. selectedPointcloud = pointcloud;
  38922. closestIntersection = point.position;
  38923. closestPoint = point;
  38924. }
  38925. }
  38926. if(pickParams.isMeasuring || Potree.settings.displayMode == 'showPanos'){
  38927. Potree.settings.pointDensity = density;
  38928. pointclouds.forEach(e=>{
  38929. e.material.pointSizeType = sizeType;
  38930. e.changePointSize(size.get(e));
  38931. });
  38932. }else {
  38933. /* if(viewer.viewports.filter(e=>!e.noPointcloud).length>1){
  38934. viewport.afterRender && viewport.afterRender()
  38935. } */
  38936. }
  38937. if (selectedPointcloud) {
  38938. return {
  38939. location: closestIntersection,
  38940. distance: closestDistance,
  38941. pointcloud: selectedPointcloud,
  38942. point: closestPoint,
  38943. pointclouds: allPointclouds, //add
  38944. normal: new Vector3().fromArray(closestPoint.normal )//add
  38945. };
  38946. } else {
  38947. return null;
  38948. }
  38949. }
  38950. static renderTargetToDataUrl(renderTarget, width, height, renderer, compressRatio = 0.7){
  38951. let pixelCount = width * height;
  38952. let buffer = new Uint8Array(4 * pixelCount);
  38953. renderer.readRenderTargetPixels(renderTarget, 0, 0, width, height, buffer);
  38954. var dataUrl = Potree.Utils.pixelsArrayToDataUrl(buffer, width, height, compressRatio);
  38955. return dataUrl
  38956. }
  38957. static pixelsArrayToDataUrl(pixels, width, height, compressRatio = 0.7) {
  38958. let canvas = document.createElement('canvas');
  38959. canvas.width = width;
  38960. canvas.height = height;
  38961. let context = canvas.getContext('2d');
  38962. pixels = new pixels.constructor(pixels);
  38963. /* for (let i = 0; i < pixels.length; i++) {
  38964. pixels[i * 4 + 3] = 255;
  38965. } */
  38966. // flip vertically
  38967. let bytesPerLine = width * 4;
  38968. for(let i = 0; i < parseInt(height / 2); i++){
  38969. let j = height - i - 1;
  38970. let lineI = pixels.slice(i * bytesPerLine, i * bytesPerLine + bytesPerLine);
  38971. let lineJ = pixels.slice(j * bytesPerLine, j * bytesPerLine + bytesPerLine);
  38972. pixels.set(lineJ, i * bytesPerLine);
  38973. pixels.set(lineI, j * bytesPerLine);
  38974. }
  38975. let imageData = context.createImageData(width, height);
  38976. imageData.data.set(pixels);
  38977. context.putImageData(imageData, 0, 0);
  38978. let dataURL = canvas.toDataURL(compressRatio);
  38979. return dataURL;
  38980. }
  38981. static removeListeners(dispatcher, type){
  38982. if (dispatcher._listeners === undefined) {
  38983. return;
  38984. }
  38985. if (dispatcher._listeners[ type ]) {
  38986. delete dispatcher._listeners[ type ];
  38987. }
  38988. }
  38989. /* static mouseToRay(mouse, camera, width, height){
  38990. let normalizedMouse = {
  38991. x: (mouse.x / width) * 2 - 1,
  38992. y: -(mouse.y / height) * 2 + 1
  38993. };
  38994. let vector = new THREE.Vector3(normalizedMouse.x, normalizedMouse.y, 0.5);
  38995. let origin = camera.position.clone();
  38996. vector.unproject(camera);
  38997. let direction = new THREE.Vector3().subVectors(vector, origin).normalize();
  38998. let ray = new THREE.Ray(origin, direction);
  38999. return ray;
  39000. } */
  39001. static mouseToRay(pointer, camera ){
  39002. let vector = new Vector3(pointer.x, pointer.y, 1);
  39003. let origin = new Vector3(pointer.x, pointer.y, -1); //不能用camera.position,在orbitCamera时不准
  39004. vector.unproject(camera);
  39005. origin.unproject(camera);
  39006. let direction = new Vector3().subVectors(vector, origin).normalize();
  39007. let ray = new Ray(origin, direction);
  39008. return ray;
  39009. }
  39010. static getPos2d(point, camera, dom, viewport){//获取一个三维坐标对应屏幕中的二维坐标
  39011. var pos;
  39012. if(math.closeTo(camera.position, point, 1e-5) ){ //和相机位置重合时显示会四处飘,看是要改成一直显示中间还是隐藏?
  39013. pos = new Vector3(0,0,1.5); //1.5是为了不可见
  39014. }else {
  39015. pos = point.clone().project(camera); //比之前hotspot的计算方式写得简单 project用于3转2(求法同shader); unproject用于2转3 :new r.Vector3(e.x, e.y, -1).unproject(this.camera);
  39016. }
  39017. var x,y,left,top;
  39018. x = (pos.x + 1) / 2 * dom.clientWidth * viewport.width;
  39019. y = (1 - (pos.y + 1) / 2) * dom.clientHeight * viewport.height;
  39020. left = viewport.left * dom.clientWidth;
  39021. top = (1- viewport.bottom - viewport.height) * dom.clientHeight;
  39022. var inSight = pos.x <= 1 && pos.x >= -1 //是否在屏幕中
  39023. && pos.x <= 1 && pos.y >= -1;
  39024. return {
  39025. pos: new Vector2$1(left+x,top+y) ,// 屏幕像素坐标
  39026. vector: pos, //(范围 -1 ~ 1)
  39027. trueSide : pos.z<1, //trueSide为false时,即使在屏幕范围内可见,也是反方向的另一个不可以被渲染的点 参见Tag.update
  39028. inSight : inSight, //在屏幕范围内可见,
  39029. posInViewport: new Vector2$1(x,y)
  39030. };
  39031. }
  39032. static projectedRadius(radius, camera, distance, screenWidth, screenHeight){
  39033. if(camera instanceof OrthographicCamera){
  39034. return Utils.projectedRadiusOrtho(radius, camera.projectionMatrix, screenWidth, screenHeight);
  39035. }else if(camera instanceof PerspectiveCamera){
  39036. return Utils.projectedRadiusPerspective(radius, camera.fov * Math.PI / 180, distance, screenHeight);
  39037. }else {
  39038. throw new Error("invalid parameters");
  39039. }
  39040. }
  39041. static projectedRadiusPerspective(radius, fov, distance, screenHeight) {
  39042. let projFactor = (1 / Math.tan(fov / 2)) / distance;
  39043. projFactor = projFactor * screenHeight / 2;
  39044. return radius * projFactor;
  39045. }
  39046. static projectedRadiusOrtho(radius, proj, screenWidth, screenHeight) {
  39047. let p1 = new Vector4(0);
  39048. let p2 = new Vector4(radius);
  39049. p1.applyMatrix4(proj);
  39050. p2.applyMatrix4(proj);
  39051. p1 = new Vector3(p1.x, p1.y, p1.z);
  39052. p2 = new Vector3(p2.x, p2.y, p2.z);
  39053. p1.x = (p1.x + 1.0) * 0.5 * screenWidth;
  39054. p1.y = (p1.y + 1.0) * 0.5 * screenHeight;
  39055. p2.x = (p2.x + 1.0) * 0.5 * screenWidth;
  39056. p2.y = (p2.y + 1.0) * 0.5 * screenHeight;
  39057. return p1.distanceTo(p2);
  39058. }
  39059. static topView(camera, node){
  39060. camera.position.set(0, 1, 0);
  39061. camera.rotation.set(-Math.PI / 2, 0, 0);
  39062. camera.zoomTo(node, 1);
  39063. }
  39064. static frontView (camera, node) {
  39065. camera.position.set(0, 0, 1);
  39066. camera.rotation.set(0, 0, 0);
  39067. camera.zoomTo(node, 1);
  39068. }
  39069. static leftView (camera, node) {
  39070. camera.position.set(-1, 0, 0);
  39071. camera.rotation.set(0, -Math.PI / 2, 0);
  39072. camera.zoomTo(node, 1);
  39073. }
  39074. static rightView (camera, node) {
  39075. camera.position.set(1, 0, 0);
  39076. camera.rotation.set(0, Math.PI / 2, 0);
  39077. camera.zoomTo(node, 1);
  39078. }
  39079. static findClosestGpsTime(target, viewer){
  39080. const start = performance.now();
  39081. const nodes = [];
  39082. for(const pc of viewer.scene.pointclouds){
  39083. nodes.push(pc.root);
  39084. for(const child of pc.root.children){
  39085. if(child){
  39086. nodes.push(child);
  39087. }
  39088. }
  39089. }
  39090. let closestNode = null;
  39091. let closestIndex = Infinity;
  39092. let closestDistance = Infinity;
  39093. let closestValue = 0;
  39094. for(const node of nodes){
  39095. const isOkay = node.geometryNode != null
  39096. && node.geometryNode.geometry != null
  39097. && node.sceneNode != null;
  39098. if(!isOkay){
  39099. continue;
  39100. }
  39101. let geometry = node.geometryNode.geometry;
  39102. let gpsTime = geometry.attributes["gps-time"];
  39103. let range = gpsTime.potree.range;
  39104. for(let i = 0; i < gpsTime.array.length; i++){
  39105. let value = gpsTime.array[i];
  39106. value = value * (range[1] - range[0]) + range[0];
  39107. const distance = Math.abs(target - value);
  39108. if(distance < closestDistance){
  39109. closestIndex = i;
  39110. closestDistance = distance;
  39111. closestValue = value;
  39112. closestNode = node;
  39113. //console.log("found a closer one: " + value);
  39114. }
  39115. }
  39116. }
  39117. const geometry = closestNode.geometryNode.geometry;
  39118. const position = new Vector3(
  39119. geometry.attributes.position.array[3 * closestIndex + 0],
  39120. geometry.attributes.position.array[3 * closestIndex + 1],
  39121. geometry.attributes.position.array[3 * closestIndex + 2],
  39122. );
  39123. position.applyMatrix4(closestNode.sceneNode.matrixWorld);
  39124. const end = performance.now();
  39125. const duration = (end - start);
  39126. console.log(`duration: ${duration.toFixed(3)}ms`);
  39127. return {
  39128. node: closestNode,
  39129. index: closestIndex,
  39130. position: position,
  39131. };
  39132. }
  39133. /**
  39134. *
  39135. * 0: no intersection
  39136. * 1: intersection
  39137. * 2: fully inside
  39138. */
  39139. static frustumSphereIntersection (frustum, sphere) {
  39140. let planes = frustum.planes;
  39141. let center = sphere.center;
  39142. let negRadius = -sphere.radius;
  39143. let minDistance = Number.MAX_VALUE;
  39144. for (let i = 0; i < 6; i++) {
  39145. let distance = planes[ i ].distanceToPoint(center);
  39146. if (distance < negRadius) {
  39147. return 0;
  39148. }
  39149. minDistance = Math.min(minDistance, distance);
  39150. }
  39151. return (minDistance >= sphere.radius) ? 2 : 1;
  39152. }
  39153. // code taken from three.js
  39154. // ImageUtils - generateDataTexture()
  39155. static generateDataTexture (width, height, color) {
  39156. let size = width * height;
  39157. let data = new Uint8Array(4 * width * height);
  39158. let r = Math.floor(color.r * 255);
  39159. let g = Math.floor(color.g * 255);
  39160. let b = Math.floor(color.b * 255);
  39161. for (let i = 0; i < size; i++) {
  39162. data[ i * 3 ] = r;
  39163. data[ i * 3 + 1 ] = g;
  39164. data[ i * 3 + 2 ] = b;
  39165. }
  39166. let texture = new DataTexture(data, width, height, RGBAFormat);
  39167. texture.needsUpdate = true;
  39168. texture.magFilter = NearestFilter;
  39169. return texture;
  39170. }
  39171. // from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
  39172. static getParameterByName (name) {
  39173. name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
  39174. let regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  39175. let results = regex.exec(document.location.search);
  39176. return results === null ? null : decodeURIComponent(results[1].replace(/\+/g, ' '));
  39177. }
  39178. static setParameter (name, value) {
  39179. // value = encodeURIComponent(value);
  39180. name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
  39181. let regex = new RegExp('([\\?&])(' + name + '=([^&#]*))');
  39182. let results = regex.exec(document.location.search);
  39183. let url = window.location.href;
  39184. if (results === null) {
  39185. if (window.location.search.length === 0) {
  39186. url = url + '?';
  39187. } else {
  39188. url = url + '&';
  39189. }
  39190. url = url + name + '=' + value;
  39191. } else {
  39192. let newValue = name + '=' + value;
  39193. url = url.replace(results[2], newValue);
  39194. }
  39195. window.history.replaceState({}, '', url);
  39196. }
  39197. static createChildAABB(aabb, index){
  39198. let min = aabb.min.clone();
  39199. let max = aabb.max.clone();
  39200. let size = new Vector3().subVectors(max, min);
  39201. if ((index & 0b0001) > 0) {
  39202. min.z += size.z / 2;
  39203. } else {
  39204. max.z -= size.z / 2;
  39205. }
  39206. if ((index & 0b0010) > 0) {
  39207. min.y += size.y / 2;
  39208. } else {
  39209. max.y -= size.y / 2;
  39210. }
  39211. if ((index & 0b0100) > 0) {
  39212. min.x += size.x / 2;
  39213. } else {
  39214. max.x -= size.x / 2;
  39215. }
  39216. return new Box3(min, max);
  39217. }
  39218. // see https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript
  39219. static clipboardCopy(text){
  39220. let textArea = document.createElement("textarea");
  39221. textArea.style.position = 'fixed';
  39222. textArea.style.top = 0;
  39223. textArea.style.left = 0;
  39224. textArea.style.width = '2em';
  39225. textArea.style.height = '2em';
  39226. textArea.style.padding = 0;
  39227. textArea.style.border = 'none';
  39228. textArea.style.outline = 'none';
  39229. textArea.style.boxShadow = 'none';
  39230. textArea.style.background = 'transparent';
  39231. textArea.value = text;
  39232. document.body.appendChild(textArea);
  39233. textArea.select();
  39234. try {
  39235. let success = document.execCommand('copy');
  39236. if(success){
  39237. console.log("copied text to clipboard");
  39238. }else {
  39239. console.log("copy to clipboard failed");
  39240. }
  39241. } catch (err) {
  39242. console.log("error while trying to copy to clipboard");
  39243. }
  39244. document.body.removeChild(textArea);
  39245. }
  39246. static getMeasurementIcon(measurement){
  39247. if (measurement instanceof Measure) {
  39248. if (measurement.showDistances && !measurement.showArea && !measurement.showAngles) {
  39249. return `${Potree.resourcePath}/icons/distance.svg`;
  39250. } else if (measurement.showDistances && measurement.showArea && !measurement.showAngles) {
  39251. return `${Potree.resourcePath}/icons/area.svg`;
  39252. } else if (measurement.maxMarkers === 1) {
  39253. return `${Potree.resourcePath}/icons/point.svg`;
  39254. } else if (!measurement.showDistances && !measurement.showArea && measurement.showAngles) {
  39255. return `${Potree.resourcePath}/icons/angle.png`;
  39256. } else if (measurement.showHeight) {
  39257. return `${Potree.resourcePath}/icons/height.svg`;
  39258. } else {
  39259. return `${Potree.resourcePath}/icons/distance.svg`;
  39260. }
  39261. } else if (measurement instanceof Profile) {
  39262. return `${Potree.resourcePath}/icons/profile.svg`;
  39263. } else if (measurement instanceof Volume) {
  39264. return `${Potree.resourcePath}/icons/volume.svg`;
  39265. } else if (measurement instanceof PolygonClipVolume) {
  39266. return `${Potree.resourcePath}/icons/clip-polygon.svg`;
  39267. }
  39268. }
  39269. static lineToLineIntersection(P0, P1, P2, P3){
  39270. const P = [P0, P1, P2, P3];
  39271. const d = (m, n, o, p) => {
  39272. let result =
  39273. (P[m].x - P[n].x) * (P[o].x - P[p].x)
  39274. + (P[m].y - P[n].y) * (P[o].y - P[p].y)
  39275. + (P[m].z - P[n].z) * (P[o].z - P[p].z);
  39276. return result;
  39277. };
  39278. const mua = (d(0, 2, 3, 2) * d(3, 2, 1, 0) - d(0, 2, 1, 0) * d(3, 2, 3, 2))
  39279. /**-----------------------------------------------------------------**/ /
  39280. (d(1, 0, 1, 0) * d(3, 2, 3, 2) - d(3, 2, 1, 0) * d(3, 2, 1, 0));
  39281. const mub = (d(0, 2, 3, 2) + mua * d(3, 2, 1, 0))
  39282. /**--------------------------------------**/ /
  39283. d(3, 2, 3, 2);
  39284. const P01 = P1.clone().sub(P0);
  39285. const P23 = P3.clone().sub(P2);
  39286. const Pa = P0.clone().add(P01.multiplyScalar(mua));
  39287. const Pb = P2.clone().add(P23.multiplyScalar(mub));
  39288. const center = Pa.clone().add(Pb).multiplyScalar(0.5);
  39289. return center;
  39290. }
  39291. static computeCircleCenter(A, B, C){
  39292. const AB = B.clone().sub(A);
  39293. const AC = C.clone().sub(A);
  39294. const N = AC.clone().cross(AB).normalize();
  39295. const ab_dir = AB.clone().cross(N).normalize();
  39296. const ac_dir = AC.clone().cross(N).normalize();
  39297. const ab_origin = A.clone().add(B).multiplyScalar(0.5);
  39298. const ac_origin = A.clone().add(C).multiplyScalar(0.5);
  39299. const P0 = ab_origin;
  39300. const P1 = ab_origin.clone().add(ab_dir);
  39301. const P2 = ac_origin;
  39302. const P3 = ac_origin.clone().add(ac_dir);
  39303. const center = Utils.lineToLineIntersection(P0, P1, P2, P3);
  39304. return center;
  39305. // Potree.Utils.debugLine(viewer.scene.scene, P0, P1, 0x00ff00);
  39306. // Potree.Utils.debugLine(viewer.scene.scene, P2, P3, 0x0000ff);
  39307. // Potree.Utils.debugSphere(viewer.scene.scene, center, 0.03, 0xff00ff);
  39308. // const radius = center.distanceTo(A);
  39309. // Potree.Utils.debugCircle(viewer.scene.scene, center, radius, new THREE.Vector3(0, 0, 1), 0xff00ff);
  39310. }
  39311. static getNorthVec(p1, distance, projection){
  39312. if(projection){
  39313. // if there is a projection, transform coordinates to WGS84
  39314. // and compute angle to north there
  39315. proj4.defs("pointcloud", projection);
  39316. const transform = proj4("pointcloud", "WGS84");
  39317. const llP1 = transform.forward(p1.toArray());
  39318. let llP2 = transform.forward([p1.x, p1.y + distance]);
  39319. const polarRadius = Math.sqrt((llP2[0] - llP1[0]) ** 2 + (llP2[1] - llP1[1]) ** 2);
  39320. llP2 = [llP1[0], llP1[1] + polarRadius];
  39321. const northVec = transform.inverse(llP2);
  39322. return new Vector3(...northVec, p1.z).sub(p1);
  39323. }else {
  39324. // if there is no projection, assume [0, 1, 0] as north direction
  39325. const vec = new Vector3(0, 1, 0).multiplyScalar(distance);
  39326. return vec;
  39327. }
  39328. }
  39329. static computeAzimuth(p1, p2, projection){
  39330. let azimuth = 0;
  39331. if(projection){
  39332. // if there is a projection, transform coordinates to WGS84
  39333. // and compute angle to north there
  39334. let transform;
  39335. if (projection.includes('EPSG')) {
  39336. transform = proj4(projection, "WGS84");
  39337. } else {
  39338. proj4.defs("pointcloud", projection);
  39339. transform = proj4("pointcloud", "WGS84");
  39340. }
  39341. const llP1 = transform.forward(p1.toArray());
  39342. const llP2 = transform.forward(p2.toArray());
  39343. const dir = [
  39344. llP2[0] - llP1[0],
  39345. llP2[1] - llP1[1],
  39346. ];
  39347. azimuth = Math.atan2(dir[1], dir[0]) - Math.PI / 2;
  39348. }else {
  39349. // if there is no projection, assume [0, 1, 0] as north direction
  39350. const dir = [p2.x - p1.x, p2.y - p1.y];
  39351. azimuth = Math.atan2(dir[1], dir[0]) - Math.PI / 2;
  39352. }
  39353. // make clockwise
  39354. azimuth = -azimuth;
  39355. return azimuth;
  39356. }
  39357. static async loadScript(url){
  39358. return new Promise( resolve => {
  39359. const element = document.getElementById(url);
  39360. if(element){
  39361. resolve();
  39362. }else {
  39363. const script = document.createElement("script");
  39364. script.id = url;
  39365. script.onload = () => {
  39366. resolve();
  39367. };
  39368. script.src = url;
  39369. document.body.appendChild(script);
  39370. }
  39371. });
  39372. }
  39373. static createSvgGradient(scheme){
  39374. // this is what we are creating:
  39375. //
  39376. //<svg width="1em" height="3em" xmlns="http://www.w3.org/2000/svg">
  39377. // <defs>
  39378. // <linearGradient id="gradientID" gradientTransform="rotate(90)">
  39379. // <stop offset="0%" stop-color="rgb(93, 78, 162)" />
  39380. // ...
  39381. // <stop offset="100%" stop-color="rgb(157, 0, 65)" />
  39382. // </linearGradient>
  39383. // </defs>
  39384. //
  39385. // <rect width="100%" height="100%" fill="url('#myGradient')" stroke="black" stroke-width="0.1em"/>
  39386. //</svg>
  39387. const gradientId = `${Math.random()}_${Date.now()}`;
  39388. const svgn = "http://www.w3.org/2000/svg";
  39389. const svg = document.createElementNS(svgn, "svg");
  39390. svg.setAttributeNS(null, "width", "2em");
  39391. svg.setAttributeNS(null, "height", "3em");
  39392. { // <defs>
  39393. const defs = document.createElementNS(svgn, "defs");
  39394. const linearGradient = document.createElementNS(svgn, "linearGradient");
  39395. linearGradient.setAttributeNS(null, "id", gradientId);
  39396. linearGradient.setAttributeNS(null, "gradientTransform", "rotate(90)");
  39397. for(let i = scheme.length - 1; i >= 0; i--){
  39398. const stopVal = scheme[i];
  39399. const percent = parseInt(100 - stopVal[0] * 100);
  39400. const [r, g, b] = stopVal[1].toArray().map(v => parseInt(v * 255));
  39401. const stop = document.createElementNS(svgn, "stop");
  39402. stop.setAttributeNS(null, "offset", `${percent}%`);
  39403. stop.setAttributeNS(null, "stop-color", `rgb(${r}, ${g}, ${b})`);
  39404. linearGradient.appendChild(stop);
  39405. }
  39406. defs.appendChild(linearGradient);
  39407. svg.appendChild(defs);
  39408. }
  39409. const rect = document.createElementNS(svgn, "rect");
  39410. rect.setAttributeNS(null, "width", `100%`);
  39411. rect.setAttributeNS(null, "height", `100%`);
  39412. rect.setAttributeNS(null, "fill", `url("#${gradientId}")`);
  39413. rect.setAttributeNS(null, "stroke", `black`);
  39414. rect.setAttributeNS(null, "stroke-width", `0.1em`);
  39415. svg.appendChild(rect);
  39416. return svg;
  39417. }
  39418. static async waitAny(promises){
  39419. return new Promise( (resolve) => {
  39420. promises.map( promise => {
  39421. promise.then( () => {
  39422. resolve();
  39423. });
  39424. });
  39425. });
  39426. }
  39427. }
  39428. Utils.screenPass = new function () {
  39429. this.screenScene = new Scene();
  39430. this.screenQuad = new Mesh(new PlaneBufferGeometry(2, 2, 1));
  39431. this.screenQuad.material.depthTest = true;
  39432. this.screenQuad.material.depthWrite = true;
  39433. this.screenQuad.material.transparent = true;
  39434. this.screenScene.add(this.screenQuad);
  39435. this.camera = new Camera();
  39436. this.render = function (renderer, material, target) {
  39437. this.screenQuad.material = material;
  39438. if (typeof target === 'undefined') {
  39439. renderer.render(this.screenScene, this.camera);
  39440. } else {
  39441. renderer.setRenderTarget(target);
  39442. renderer.render(this.screenScene, this.camera);
  39443. }
  39444. };
  39445. }();
  39446. //add
  39447. Utils.computePointcloudsBound = function(pointclouds){
  39448. var boundingBox = new Box3();
  39449. pointclouds.forEach(pointcloud=>{
  39450. pointcloud.updateBound();
  39451. boundingBox.union(pointcloud.bound);
  39452. });
  39453. var boundSize = boundingBox.getSize(new Vector3);
  39454. var center = boundingBox.getCenter(new Vector3);
  39455. return {boundSize, center, boundingBox}
  39456. };
  39457. Utils.convertScreenPositionToNDC = function(pointer, mouse, width, height) {
  39458. return pointer = pointer || new Vector2$1,
  39459. pointer.x = mouse.x / width * 2 - 1,
  39460. pointer.y = 2 * -(mouse.y / height) + 1,
  39461. pointer
  39462. };
  39463. Utils.convertNDCToScreenPosition = function(pointer, mouse, width, height) {
  39464. return mouse = mouse || new Vector2$1,
  39465. mouse.x = Math.round((pointer.x + 1 ) / 2 * width),
  39466. mouse.y = Math.round(-(pointer.y - 1 ) / 2 * height),
  39467. mouse
  39468. };
  39469. Utils.getOrthoCameraMoveVec = function(pointerDelta, camera ){//获取当camera为Ortho型时 屏幕点1 到 屏幕点2 的三维距离
  39470. let cameraViewWidth = camera.right / camera.zoom;
  39471. let cameraViewHeight = camera.top / camera.zoom;
  39472. let moveVec = new Vector3;
  39473. moveVec.set( pointerDelta.x * cameraViewWidth , pointerDelta.y * cameraViewHeight , 0).applyQuaternion(camera.quaternion);
  39474. return moveVec
  39475. };
  39476. Utils.VectorFactory = {
  39477. fromArray : function(t) {
  39478. if (t) {
  39479. if (t.length < 2 || t.length > 3)
  39480. console.error("Wrong number of ordinates for a point!");
  39481. return 3 === t.length ? (new Vector3).fromArray(t) : (new Vector2$1).fromArray(t)
  39482. }
  39483. },
  39484. fromArray3 : function(t) {
  39485. if (t) {
  39486. if (3 !== t.length)
  39487. console.error("Wrong number of ordinates for a point!");
  39488. return (new Vector3).fromArray(t)
  39489. }
  39490. },
  39491. fromArray2 : function(t) {
  39492. if (t) {
  39493. if (2 !== t.length)
  39494. console.error("Wrong number of ordinates for a point!");
  39495. return (new Vector2$1).fromArray(t)
  39496. }
  39497. },
  39498. toString : function(t) {
  39499. return t.x.toFixed(8) + "," + t.y.toFixed(8) + "," + t.z.toFixed(3)
  39500. }
  39501. };
  39502. Utils.QuaternionFactory = {
  39503. rot90 : (new Quaternion).setFromAxisAngle(new Vector3(0,0,1), MathUtils.degToRad(-90)),
  39504. fromArray : function(t) {
  39505. if (t) {
  39506. if (4 !== t.length)
  39507. console.error("Wrong number of ordinates for a quaternion!");
  39508. return new Quaternion(t[1],t[2],t[3],t[0]).multiply(this.rot90)
  39509. }
  39510. }
  39511. ,
  39512. toArray : function(t) {
  39513. if (t) {
  39514. var e = t.clone().multiply(a).toArray();
  39515. return [e[3], e[0], e[1], e[2]]
  39516. }
  39517. }
  39518. ,
  39519. fromLonLat : function(t) {
  39520. if (t)
  39521. return (new Quaternion).setFromEuler(new Euler(t.lon,t.lat,0))
  39522. }
  39523. ,
  39524. toLonLat : function(t) {
  39525. if (t) {
  39526. var e = (new Euler).setFromQuaternion(t);
  39527. return {
  39528. lon: e.x,
  39529. lat: e.y
  39530. }
  39531. }
  39532. }
  39533. };
  39534. Utils.datasetPosTransform = function(o={}){
  39535. let pointcloud = o.pointcloud || viewer.scene.pointclouds.find(e=>e.dataset_id == o.datasetId);
  39536. let tranMatrix;
  39537. if(pointcloud){
  39538. if(Potree.settings.editType == 'merge'){
  39539. tranMatrix = o.fromDataset ? pointcloud.matrixWorld : new Matrix4().copy(pointcloud.matrixWorld).invert();
  39540. }else {
  39541. tranMatrix = o.fromDataset ? pointcloud.transformMatrix : pointcloud.transformInvMatrix;
  39542. }
  39543. }else {
  39544. if(Potree.settings.intersectOnObjs){
  39545. let object = o.object || viewer.objs.children.find(e=>e.dataset_id == o.datasetId);
  39546. if(object){
  39547. tranMatrix = o.fromDataset ? object.matrixWorld : new Matrix4().copy(object.matrixWorld).invert();
  39548. }
  39549. }
  39550. }
  39551. if(tranMatrix){
  39552. return (new Vector3).copy(o.position).applyMatrix4(tranMatrix)
  39553. }else {
  39554. if(o.datasetId != void 0){
  39555. console.error(`datasetPosTransform找不到datasetId为${o.datasetId}的数据集或模型,请检查数据, 模型未创建或删除`);
  39556. //很可能是旧的热点,需要删除
  39557. }
  39558. }
  39559. };
  39560. Utils.datasetRotTransform = function(o={}){
  39561. let pointcloud = o.pointcloud || viewer.scene.pointclouds.find(e=>e.dataset_id == o.datasetId);
  39562. if(pointcloud){
  39563. var matrix, newMatrix, result;
  39564. if(o.rotation){
  39565. matrix = new Matrix4().makeRotationFromEuler(o.rotation);
  39566. }else if(o.quaternion){
  39567. matrix = new Matrix4().makeRotationFromQuaternion(o.quaternion);
  39568. }else if(o.matrix){
  39569. matrix = o.matrix.clone();
  39570. }else {
  39571. return
  39572. }
  39573. let rotateMatrix = o.fromDataset ? pointcloud.rotateMatrix : pointcloud.rotateInvMatrix;
  39574. newMatrix = new Matrix4().multiplyMatrices(rotateMatrix, matrix );
  39575. if(o.getRotation){
  39576. result = new Euler().setFromRotationMatrix(newMatrix);
  39577. }else if(o.getQuaternion){
  39578. result = new Quaternion().setFromRotationMatrix(newMatrix);
  39579. }else if(o.getMatrix){
  39580. result = newMatrix;
  39581. }
  39582. return result
  39583. }
  39584. };
  39585. Utils.isInsideFrustum = function(bounding, camera){// boundingBox在视野范围内有可见部分
  39586. let frustumMatrix = new Matrix4;
  39587. frustumMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  39588. let frustum = new Frustum();
  39589. frustum.setFromProjectionMatrix(frustumMatrix);
  39590. if(bounding instanceof Sphere){
  39591. return frustum.intersectsSphere(bounding)
  39592. }else {
  39593. return frustum.intersectsBox(bounding)
  39594. }
  39595. };
  39596. Utils.isInsideBox = function(object, boxMatrixInverse){//object可以是点或者bounding, box原为1*1*1,但可能形变
  39597. let frustum = new Frustum();
  39598. frustum.setFromProjectionMatrix(boxMatrixInverse);
  39599. if(object instanceof Box3){
  39600. return frustum.intersectsSphere(object)
  39601. }else if(object instanceof Array){//点合集,先求Sphere setFromPoints
  39602. let sphere = new Sphere();
  39603. sphere.setFromPoints(object);
  39604. return this.isInsideBox(sphere, boxMatrixInverse)
  39605. }else if(object instanceof Sphere){
  39606. return frustum.intersectsSphere(object)
  39607. }else if(object instanceof Vector3){
  39608. return frustum.containsPoint(object)
  39609. }
  39610. /* containsPoint: ƒ containsPoint( point )
  39611. intersectsBox: ƒ intersectsBox( box )
  39612. intersectsObject: ƒ intersectsObject( object )//geo
  39613. intersectsSphere: ƒ intersectsSphere( sphere )
  39614. intersectsSprite: ƒ intersectsSprite( sprite )
  39615. */
  39616. };
  39617. Utils.getIntersect = function (camera, meshes, pointer, raycaster) {
  39618. //获取鼠标和meshes交点
  39619. camera.updateMatrixWorld();
  39620. if(!raycaster){//getMouseIntersect
  39621. raycaster = new Raycaster();
  39622. var origin = new Vector3(pointer.x, pointer.y, -1).unproject(camera),
  39623. end = new Vector3(pointer.x, pointer.y, 1).unproject(camera);
  39624. var dir = end.sub(origin).normalize();
  39625. raycaster.set(origin, dir);
  39626. }
  39627. meshes.forEach(e=>{
  39628. raycaster.layers.enable(math.getBaseLog(e.layers.mask,2));
  39629. });
  39630. var n = raycaster.intersectObjects(meshes);
  39631. if (0 === n.length) return null
  39632. return n[0]
  39633. };
  39634. var start = function(dom, mapDom, number ){ //t-Zvd3w0m
  39635. /* {
  39636. let obj = JSON.parse(localStorage.getItem('setting'))
  39637. for(let i in obj){
  39638. console.log(i + ': ' + obj[i])
  39639. }
  39640. }
  39641. */
  39642. Potree.settings.number = number || 't-o5YMR13';// 't-iksBApb'// 写在viewer前
  39643. let viewer = new Potree.Viewer(dom , mapDom);
  39644. let Alignment = viewer.modules.Alignment;
  39645. //let pointDensity = config.pointDensity.middle
  39646. viewer.setEDLEnabled(false);
  39647. viewer.setFOV(config$1.view.fov);
  39648. //viewer.setPointBudget(pointDensity.pointBudget);
  39649. viewer.loadSettingsFromURL();
  39650. if(!Potree.settings.isOfficial){
  39651. viewer.loadGUI(() => {
  39652. viewer.setLanguage('en');
  39653. //$("#menu_appearance").next().show();
  39654. $("#menu_tools").next().show();
  39655. $("#menu_scene").next().show();
  39656. $("#siteModel").show();
  39657. //$("#alignment").show();
  39658. viewer.toggleSidebar();
  39659. });
  39660. Potree.settings.sizeFitToLevel = true;//当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2
  39661. }
  39662. Potree.loadDatasetsCallback = function(data, ifReload){
  39663. if(!data || data.length == 0)return console.error('getDataSet加载的数据为空')
  39664. Potree.datasetData = data;
  39665. viewer.transform = null;
  39666. var datasetLength = data.length;
  39667. var pointcloudLoaded = 0;
  39668. var panosLoaded = 0;
  39669. var pointcloudLoadDone = function(){//点云cloud.js加载完毕后
  39670. viewer.updateModelBound();
  39671. let {boundSize, center} = viewer.bound;
  39672. Potree.Log(`中心点: ${math.toPrecision(center.toArray(),2)}, boundSize: ${math.toPrecision(boundSize.toArray(),2)} ` , null, 12);
  39673. if(!Potree.settings.isOfficial){
  39674. Potree.loadMapEntity('all'); //加载floorplan
  39675. }
  39676. if(!ifReload){
  39677. viewer.scene.view.setView({
  39678. position: center.clone().add(new Vector3(10,5,10)),
  39679. target: center
  39680. });
  39681. viewer.dispatchEvent({type:'loadPointCloudDone'});
  39682. if(!Potree.settings.UserPointDensity){
  39683. Potree.settings.UserPointDensity = 'high';//'middle'
  39684. }
  39685. Potree.Log('loadPointCloudDone 点云加载完毕', null, 10);
  39686. }
  39687. };
  39688. var panosLoadDone = function(){
  39689. viewer.images360.loadDone();
  39690. viewer.scene.add360Images(viewer.images360);
  39691. viewer.mapViewer.addListener(viewer.images360);
  39692. {//初始位置
  39693. var urlFirstView = false;
  39694. var panoId = browser.urlHasValue('pano',true);
  39695. if(panoId !== ''){
  39696. var pos;
  39697. var pano = viewer.images360.panos.find(e=>e.id==panoId);
  39698. if(pano){
  39699. viewer.images360.focusPano({
  39700. pano,
  39701. duration:0,
  39702. callback:()=>{/* Potree.settings.displayMode = 'showPanos' */}
  39703. });
  39704. }
  39705. }else {//考虑到多数据集距离很远,或者像隧道那种场景,要使视野范围内一定能看到点云,最好初始点设置在漫游点上
  39706. let {boundSize, center} = viewer.bound;
  39707. let pano = viewer.images360.findNearestPano(center);
  39708. /* pano && viewer.scene.view.setView({
  39709. position: pano.position.clone().add(new THREE.Vector3(10,10,10)),
  39710. target: pano.position
  39711. }) */
  39712. pano && viewer.images360.flyToPano({
  39713. pano, duration:0,
  39714. target : viewer.images360.bound.center
  39715. });
  39716. }
  39717. }
  39718. viewer.addVideo();//addFire()
  39719. console.log('allLoaded');
  39720. viewer.dispatchEvent('allLoaded');
  39721. };
  39722. var transformPointcloud = (pointcloud, dataset)=>{
  39723. var locationLonLat = dataset.location.slice(0,2);
  39724. //当只有一个dataset时,无论如何transform 点云和漫游点都能对应上。
  39725. var location = viewer.transform.lonlatToLocal.forward(locationLonLat); //transform.inverse()
  39726. //初始化位置
  39727. viewer.sidebar && viewer.sidebar.addAlignmentButton(pointcloud);
  39728. //dataset.orientation = 0
  39729. Alignment.rotate(pointcloud, null, dataset.orientation);
  39730. Alignment.translate(pointcloud, new Vector3(location[0], location[1], dataset.location[2]));
  39731. pointcloud.updateMatrixWorld();
  39732. Potree.Log(`点云${pointcloud.dataset_id}旋转值:${pointcloud.orientationUser}, 位置${math.toPrecision(pointcloud.translateUser.toArray(),3)}, 经纬度 ${locationLonLat}, spacing ${pointcloud.material.spacing}`, null, 17 );
  39733. //-------------------
  39734. //viewer.mapView.showSources(false);
  39735. };
  39736. if(!Potree.settings.originDatasetId)Potree.settings.originDatasetId = data[0].id;
  39737. var originDataset = data.find(e=>e.id == Potree.settings.originDatasetId);
  39738. {//拿初始数据集作为基准。它的位置是000
  39739. var locationLonLat = originDataset.location.slice(0,2);
  39740. proj4.defs("NAVVIS:TMERC", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15));
  39741. proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
  39742. let transform1 = proj4("WGS84", "NAVVIS:TMERC"); //这个ok TMERC是展开的平面投影
  39743. 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;");
  39744. viewer.transform = {
  39745. lonlatToLocal : transform1,
  39746. lonlatTo4550 : transform2 // 转大地坐标EPSG:4550
  39747. };
  39748. viewer.mapViewer && viewer.mapViewer.mapLayer.maps[0].updateProjection();
  39749. }
  39750. data.forEach((dataset,index)=>{
  39751. if(!ifReload){
  39752. var datasetCode = dataset.sceneCode || dataset.name; //对应4dkk的场景码
  39753. var cloudPath = `${Potree.settings.urls.prefix}/${Potree.settings.webSite}/${datasetCode}/data/${datasetCode}/webcloud/cloud.js`;
  39754. var timeStamp = dataset.createTime ? dataset.createTime.replace(/[^0-9]/ig,'') : ''; //每重算一次后缀随createTime更新一次
  39755. //console.warn(dataset.name, 'timeStamp', timeStamp)
  39756. Potree.loadPointCloud(cloudPath, dataset.name ,datasetCode, timeStamp, e => {
  39757. let scene = viewer.scene;
  39758. let pointcloud = e.pointcloud;
  39759. let config = Potree.config.material;
  39760. let material = pointcloud.material;
  39761. pointcloud.hasDepthTex = Potree.settings.useDepthTex && (!!dataset.has_depth || Potree.settings.isLocalhost && Potree.settings.number == 'SS-t-7DUfWAUZ3V'); //test
  39762. material.minSize = config.minSize;
  39763. material.maxSize = config.maxSize;
  39764. material.pointSizeType = config.pointSizeType; //Potree.PointSizeType[config.pointSizeType]//Potree.PointSizeType.ADAPTIVE;//FIXED
  39765. pointcloud.changePointSize(config.realPointSize); //material.size = config.pointSize;
  39766. pointcloud.changePointOpacity(1);
  39767. material.shape = Potree.PointShape.SQUARE;
  39768. pointcloud.color = pointcloud.material.color = dataset.color;
  39769. pointcloud.dataset_id = dataset.id;//供漫游点找到属于的dataset点云
  39770. pointcloud.timeStamp = timeStamp;
  39771. transformPointcloud(pointcloud,dataset);
  39772. scene.addPointCloud(pointcloud);
  39773. pointcloudLoaded ++;
  39774. if(pointcloudLoaded == datasetLength)pointcloudLoadDone();
  39775. Potree.loadPanos(dataset.id, (data) => {
  39776. //console.log('loadPanos',dataset.sceneCode, dataset.id, data)
  39777. viewer.images360.addPanoData(data, dataset.id );
  39778. panosLoaded ++;
  39779. if(panosLoaded == datasetLength){
  39780. panosLoadDone();
  39781. }
  39782. });
  39783. });
  39784. }else {
  39785. let pointcloud = viewer.scene.pointclouds.find(p => p.dataset_id == dataset.id);
  39786. if(!pointcloud){
  39787. Potree.Log('数据集id变了,自动使用第一个','#500');
  39788. pointcloud = viewer.scene.pointclouds[0];
  39789. }
  39790. //先归零
  39791. Alignment.translate(pointcloud, pointcloud.translateUser.clone().negate());
  39792. Alignment.rotate(pointcloud, null, - pointcloud.orientationUser);
  39793. transformPointcloud(pointcloud, dataset);
  39794. }
  39795. });
  39796. if(ifReload){
  39797. //loadDone()
  39798. }
  39799. };
  39800. Potree.loadDatasets(Potree.loadDatasetsCallback);
  39801. window.testTransform = function(locationLonLat, location1, location2){
  39802. proj4.defs("NAVVIS:test", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15));
  39803. let transform = proj4("WGS84", "NAVVIS:test"); //这个ok navvis里也是这两种转换 见proj4Factory
  39804. if(location1){//经纬度
  39805. return transform.forward(location1)
  39806. }else {
  39807. return transform.inverse(location2)
  39808. }
  39809. };
  39810. window.THREE = THREE$1;
  39811. window.buttonFunction = function(){
  39812. viewer.scene.pointclouds.forEach(e=>e.predictNodeMaxLevel());
  39813. /*
  39814. viewer.startScreenshot({type:'measure', measurement:viewer.scene.measurements[0]})
  39815. viewer.modules.RouteGuider.routeStart = new THREE.Vector3(0,0,-1.3)
  39816. viewer.modules.RouteGuider.routeEnd = new THREE.Vector3(-10,0,-1.3)
  39817. */
  39818. };
  39819. if(Potree.settings.isLocalhost){
  39820. let before = {};
  39821. viewer.inputHandler.addEventListener('keydown',e=>{ //测试的代码
  39822. if(e.event.key == 't'){
  39823. viewer.images360.cube.visible = true;
  39824. viewer.images360.cube.material.wireframe = true;
  39825. }else if(e.event.key == 'y'){
  39826. viewer.images360.cube.material.wireframe = false;
  39827. viewer.images360.cube.visible = Potree.settings.displayMode == 'showPanos';
  39828. }
  39829. });
  39830. }
  39831. };
  39832. //=======================================================================
  39833. /*
  39834. 漫游点编辑
  39835. */
  39836. //=======================================================================
  39837. var panoEditStart = function(dom, number, fileServer){
  39838. Potree.settings.editType = 'pano';
  39839. Potree.settings.number = number;
  39840. Potree.settings.unableNavigate = true;
  39841. let viewer = new Potree.Viewer(dom);
  39842. let Alignment = viewer.modules.Alignment;
  39843. viewer.setEDLEnabled(false);
  39844. viewer.setFOV(config$1.view.fov);
  39845. viewer.loadSettingsFromURL();
  39846. let datasetLoaded = 0;
  39847. if(!Potree.settings.isOfficial){
  39848. viewer.loadGUI(() => {
  39849. viewer.setLanguage('en');
  39850. $("#menu_tools").next().show();
  39851. $("#panos").show();
  39852. $("#alignment").show();
  39853. viewer.toggleSidebar();
  39854. });
  39855. Potree.settings.sizeFitToLevel = true;
  39856. }
  39857. var pointcloudLoadDone = function( ){//所有点云cloud.js加载完毕后
  39858. viewer.scene.pointclouds.forEach(c=>{
  39859. transformPointcloud(c);
  39860. });
  39861. viewer.images360.loadDone();
  39862. viewer.scene.add360Images(viewer.images360);
  39863. viewer.updateModelBound();
  39864. let {boundSize, center} = viewer.bound;
  39865. Potree.Log(`中心点: ${math.toPrecision(center.toArray(),2)}, boundSize: ${math.toPrecision(boundSize.toArray(),2)} ` , null, 12);
  39866. viewer.scene.view.setView({
  39867. position: center.clone().add(new Vector3(10,5,10)),
  39868. target: center
  39869. });
  39870. viewer.dispatchEvent({type:'loadPointCloudDone'});
  39871. if(!Potree.settings.UserPointDensity){
  39872. Potree.settings.UserPointDensity = 'panoEdit';//'middle'
  39873. }
  39874. Potree.Log('loadPointCloudDone 点云加载完毕', null, 10);
  39875. viewer.dispatchEvent('allLoaded');
  39876. };
  39877. var transformPointcloud = (pointcloud )=>{ //初始化位置
  39878. viewer.sidebar && viewer.sidebar.addAlignmentButton(pointcloud);
  39879. let orientation = pointcloud.panos[0].dataRotation.z;
  39880. let location = pointcloud.panos[0].dataPosition.clone().negate();
  39881. Alignment.rotate(pointcloud, null, orientation );
  39882. Alignment.translate(pointcloud, location );
  39883. pointcloud.updateMatrixWorld();
  39884. };
  39885. let loadPanosDone = Potree.loadPanosDone = (datasetId, panoData )=>{ //一个数据集获取到它的panos后
  39886. Potree.settings.datasetsPanos[datasetId] = {panoData, panos:[]};
  39887. console.log('panoData', datasetId, panoData);
  39888. let panoCount = panoData.length;
  39889. let pointcloudLoaded = 0;
  39890. let datasetsCount = Object.keys(Potree.settings.datasetsPanos).length;
  39891. panoData.forEach((pano, index)=>{
  39892. //let cloudPath = `${Potree.scriptPath}/data/panoEdit/uuidcloud/${pano.uuid}/cloud.js`
  39893. let cloudPath = `https://laser-oss.4dkankan.com/${Potree.settings.webSite}/${Potree.settings.number}/data/bundle_${Potree.settings.number}/building/uuidcloud/${pano.uuid}/cloud.js`;
  39894. let name = datasetId + '-'+pano.uuid;
  39895. let timeStamp = 0;
  39896. pano.index = index; //注意:index不等于uuid,因为有的uuid缺失。但是visibles中存的是下标!
  39897. Potree.loadPointCloud(cloudPath, name , name, timeStamp, e => { //开始加载点云
  39898. let scene = viewer.scene;
  39899. let pointcloud = e.pointcloud;
  39900. let config = Potree.config.material;
  39901. let material = pointcloud.material;
  39902. material.minSize = config.minSize;
  39903. material.maxSize = config.maxSize;
  39904. material.pointSizeType = /* 'ADAPTIVE'// */config.pointSizeType; //Potree.PointSizeType[config.pointSizeType]//Potree.PointSizeType.ADAPTIVE;//FIXED
  39905. pointcloud.changePointSize( 0.2 /* config.realPointSize */ ); //material.size = config.pointSize;
  39906. pointcloud.changePointOpacity(1);
  39907. material.shape = Potree.PointShape.SQUARE;
  39908. pointcloud.color = config.pointColor;
  39909. pointcloud.dataset_id = datasetId; //多个点云指向一个datasetId
  39910. pointcloud.panoUuid = pano.uuid;
  39911. pointcloud.timeStamp = timeStamp;
  39912. //transformPointcloud(pointcloud, pano)
  39913. scene.addPointCloud(pointcloud);
  39914. pointcloudLoaded ++;
  39915. if(pointcloudLoaded == panoCount ){
  39916. datasetLoaded ++;
  39917. viewer.images360.addPanoData(panoData , datasetId );
  39918. if(datasetLoaded == datasetsCount){
  39919. pointcloudLoadDone();
  39920. }
  39921. }
  39922. });
  39923. });
  39924. };
  39925. if(!Potree.settings.isOfficial){
  39926. Potree.settings.datasetsPano = {'testDataset':null};
  39927. Potree.loadPanosInfo( data=>{loadPanosDone('testDataset', data.sweepLocations);} );
  39928. }
  39929. };
  39930. var mergeEditStart = function(dom){
  39931. Potree.settings.editType = 'merge';
  39932. Potree.settings.intersectOnObjs = true;
  39933. Potree.settings.boundAddObjs = true;
  39934. Potree.settings.unableNavigate = true;
  39935. let viewer = new Potree.Viewer(dom );
  39936. let Alignment = viewer.modules.Alignment;
  39937. viewer.setEDLEnabled(false);
  39938. viewer.setFOV(config$1.view.fov);
  39939. viewer.loadSettingsFromURL();
  39940. {
  39941. viewer.mainViewport.view.position.set(30,30,30);
  39942. viewer.mainViewport.view.lookAt(0,0,0);
  39943. viewer.updateModelBound();//init
  39944. //this.bound = new THREE.Box3(new THREE.Vector3(-1,-1,-1),new THREE.Vector3(1,1,1))
  39945. viewer.transformationTool.setModeEnable('scale',false);
  39946. viewer.ssaaRenderPass.sampleLevel = 1; // sampleLevel为1 的话,ground就不会变黑
  39947. viewer.inputHandler.fixSelection = true; //不通过点击屏幕而切换transfrom选中状态
  39948. }
  39949. Potree.settings.sizeFitToLevel = true;//当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2
  39950. Potree.loadPointCloudScene = function(sceneCode, done, onError){//对应4dkk的场景码
  39951. Potree.loadDatasets((data)=>{
  39952. var originDataset = data.find(e=>e.sceneCode == sceneCode);//只加载初始数据集
  39953. var cloudPath = `${Potree.settings.urls.prefix}/${Potree.settings.webSite}/${sceneCode}/data/${sceneCode}/webcloud/cloud.js`;
  39954. var timeStamp = originDataset.createTime ? originDataset.createTime.replace(/[^0-9]/ig,'') : ''; //每重算一次后缀随createTime更新一次
  39955. //console.warn(dataset.sceneName, 'timeStamp', timeStamp)
  39956. Potree.loadPointCloud(cloudPath, originDataset.sceneName , sceneCode, timeStamp, e => {
  39957. let scene = viewer.scene;
  39958. let pointcloud = e.pointcloud;
  39959. let config = Potree.config.material;
  39960. let material = pointcloud.material;
  39961. material.minSize = config.minSize;
  39962. material.maxSize = config.maxSize;
  39963. material.pointSizeType = config.pointSizeType; //Potree.PointSizeType[config.pointSizeType]//Potree.PointSizeType.ADAPTIVE;//FIXED
  39964. pointcloud.changePointSize(config.realPointSize); //material.size = config.pointSize;
  39965. pointcloud.changePointOpacity(1);
  39966. material.shape = Potree.PointShape.SQUARE;
  39967. pointcloud.color = pointcloud.material.color = originDataset.color;
  39968. pointcloud.dataset_id = originDataset.id;//供漫游点找到属于的dataset点云
  39969. pointcloud.timeStamp = timeStamp;
  39970. //transformPointcloud(pointcloud, originDataset)
  39971. scene.addPointCloud(pointcloud);
  39972. {
  39973. viewer.updateModelBound();
  39974. let {boundSize, center} = viewer.bound;
  39975. viewer.dispatchEvent({type:'loadPointCloudDone'});
  39976. if(!Potree.settings.UserPointDensity){
  39977. Potree.settings.UserPointDensity = 'high';//'middle'
  39978. }
  39979. Potree.Log('loadPointCloudDone 点云加载完毕', null, 10);
  39980. }
  39981. /* Potree.loadPanos(dataset.id, (data) => { //暂时不加载panos了,因为没有id
  39982. //console.log('loadPanos',dataset.sceneCode, dataset.id, data)
  39983. viewer.images360.addPanoData(data, dataset.id )
  39984. viewer.images360.loadDone()
  39985. viewer.scene.add360Images(viewer.images360); */
  39986. viewer.dispatchEvent('allLoaded');
  39987. done(pointcloud);
  39988. },onError);
  39989. }, sceneCode, onError);
  39990. };
  39991. let setMatrix = (pointcloud)=>{//为了漫游点变换,要算一下 类似setMatrix
  39992. /* pointcloud.transformMatrix = new THREE.Matrix4().multiplyMatrices(pointcloud.matrix, pointcloud.pos1MatrixInvert)//还原一点位移
  39993. pointcloud.transformInvMatrix.copy(pointcloud.transformMatrix).invert()
  39994. pointcloud.rotateMatrix = new THREE.Matrix4().makeRotationFromEuler(pointcloud.rotation);
  39995. pointcloud.rotateInvMatrix.copy(pointcloud.rotateMatrix).invert()
  39996. pointcloud.panos.forEach(e=>e.transformByPointcloud()) */
  39997. //pointcloud.updateBound()
  39998. //pointcloud.getPanosBound()
  39999. viewer.updateModelBound();
  40000. };
  40001. let moveModel = (e)=>{//根据鼠标移动的位置改变位置
  40002. let camera = viewer.mainViewport.camera;
  40003. var origin = new Vector3(e.pointer.x, e.pointer.y, -1).unproject(camera),
  40004. end = new Vector3(e.pointer.x, e.pointer.y, 1).unproject(camera);
  40005. var dir = end.sub(origin);
  40006. let planeZ = 0;
  40007. let r = (planeZ - origin.z)/dir.z;
  40008. let x = r * dir.x + origin.x;
  40009. let y = r * dir.y + origin.y;
  40010. //过后改为根据intersect的点来设置底部高度;这样的话,需要发送高度
  40011. /*let pos = new THREE.Vector3(x,y, planeZ )
  40012. modelEditing.updateMatrixWorld()
  40013. let boundCenter = modelEditing.boundingBox.getCenter(new THREE.Vector3).applyMatrix4(modelEditing.matrixWorld);
  40014. */
  40015. MergeEditor.moveBoundCenterTo(modelEditing,new Vector3(x,y, modelEditing.boundCenter.z)); //使模型中心的xy在鼠标所在位置
  40016. modelEditing.dispatchEvent("position_changed");
  40017. };
  40018. let cancelMove = ()=>{
  40019. modelEditing = null;
  40020. viewer.removeEventListener('global_mousemove', moveModel);
  40021. viewer.removeEventListener('global_click', confirmPos);
  40022. };
  40023. let confirmPos = ()=>{
  40024. MergeEditor.focusOn(modelEditing);
  40025. cancelMove();
  40026. return {stopContinue:true}
  40027. };
  40028. let modelType, modelEditing, MergeEditor = viewer.modules.MergeEditor;
  40029. Potree.addModel = function(prop, done, onProgress, onError){ //加载模型
  40030. let loadDone = (model)=>{
  40031. model.dataset_id = prop.id; //唯一标识
  40032. if(prop.position){
  40033. model.position.copy(prop.position);
  40034. }
  40035. if(prop.rotation){
  40036. model.rotation.setFromVector3(prop.rotation);
  40037. }
  40038. if(prop.scale){
  40039. model.scale.set(prop.scale,prop.scale,prop.scale);
  40040. }
  40041. if(prop.isFirstLoad){
  40042. modelEditing = model;
  40043. MergeEditor.setModelBtmHeight(model, 0); //默认离地高度为0
  40044. viewer.addEventListener('global_mousemove', moveModel);
  40045. viewer.addEventListener('global_click', confirmPos, 3);
  40046. }else {
  40047. MergeEditor.setModelBtmHeight(model, prop.bottom || 0); //默认离地高度为0
  40048. modelEditing = null;
  40049. }
  40050. if(model.isPointcloud){
  40051. model.renderOrder = Potree.config.renderOrders.model; //same as glb
  40052. }
  40053. {//transform
  40054. let updateBound = ()=>{
  40055. model.updateMatrixWorld();
  40056. viewer.updateModelBound();
  40057. };
  40058. let maintainBtmZAndCenter = ()=>{
  40059. MergeEditor.maintainBoundXY(model);
  40060. MergeEditor.setModelBtmHeight(model);
  40061. updateBound();
  40062. model.dispatchEvent('transformChanged');
  40063. };
  40064. model.addEventListener('position_changed', ()=>{
  40065. updateBound();
  40066. MergeEditor.getBoundCenter(model);//更新boundcenter
  40067. MergeEditor.computeBtmHeight(model);
  40068. if(prop.bottomRange && (model.btmHeight > prop.bottomRange.max || model.btmHeight < prop.bottomRange.min)){
  40069. model.btmHeight = MathUtils.clamp(model.btmHeight, prop.bottomRange.min, prop.bottomRange.max);
  40070. MergeEditor.setModelBtmHeight(model);
  40071. updateBound();
  40072. }
  40073. model.dispatchEvent('transformChanged');
  40074. });
  40075. model.addEventListener("rotation_changed", maintainBtmZAndCenter );
  40076. model.addEventListener("scale_changed", maintainBtmZAndCenter );
  40077. model.addEventListener('transformChanged', ()=>{
  40078. MergeEditor.modelTransformCallback(model);
  40079. });
  40080. }
  40081. model.updateMatrixWorld();
  40082. viewer.updateModelBound();
  40083. MergeEditor.getBoundCenter(model); //初始化
  40084. model.lastMatrixWorld = model.matrixWorld.clone();
  40085. done(model);
  40086. };
  40087. if(prop.type == 'laser'){
  40088. Potree.loadPointCloudScene(prop.url, (pointcloud)=>{
  40089. pointcloud.matrixAutoUpdate = true;
  40090. pointcloud.initialPosition = pointcloud.position.clone();
  40091. pointcloud.pos1MatrixInvert = new Matrix4().setPosition(pointcloud.initialPosition).invert();
  40092. /* let maintainBtmZ = ()=>{
  40093. MergeEditor.setModelBtmHeight(pointcloud)
  40094. updateMatrix()
  40095. }
  40096. let updateMatrix = ()=>{
  40097. setMatrix(pointcloud)
  40098. pointcloud.dispatchEvent('transformChanged')
  40099. }
  40100. pointcloud.addEventListener('position_changed', updateMatrix )
  40101. pointcloud.addEventListener("orientation_changed", maintainBtmZ )
  40102. pointcloud.addEventListener("scale_changed", maintainBtmZ ) */
  40103. loadDone(pointcloud);
  40104. /* pointcloud.addEventListener('select',(e)=>{
  40105. if(Potree.settings.displayMode == 'showPanos')return
  40106. console.log('select',e)
  40107. //viewer.setControls(viewer.orbitControls)
  40108. MergeEditor.focusOnSelect(pointcloud)
  40109. viewer.outlinePass.selectedObjects = [pointcloud]
  40110. return {stopContinue:true}
  40111. },1)
  40112. pointcloud.addEventListener('deselect',(e)=>{
  40113. console.log('deselect',e)
  40114. //viewer.setControls(viewer.fpControls)
  40115. viewer.outlinePass.selectedObjects = []
  40116. }) */
  40117. }, onError);
  40118. }else {
  40119. let callback = (object)=>{
  40120. //focusOnSelect(object, 1000)
  40121. object.isModel = true;
  40122. //object.dataset_id = Date.now() //暂时
  40123. object.traverse(e=>e.material && (e.material.transparent = true));
  40124. /* object.addEventListener('click',(e)=>{
  40125. //只是为了能得到hoverElement识别才加这个侦听
  40126. }) */
  40127. /* let updateBound = ()=>{
  40128. object.updateMatrixWorld()
  40129. viewer.updateModelBound()
  40130. object.dispatchEvent('transformChanged')
  40131. }
  40132. let maintainBtmZ = ()=>{
  40133. MergeEditor.setModelBtmHeight(object)
  40134. updateBound()
  40135. }
  40136. object.addEventListener('position_changed', updateBound )
  40137. object.addEventListener("orientation_changed", maintainBtmZ )
  40138. object.addEventListener("scale_changed", maintainBtmZ ) */
  40139. loadDone(object);
  40140. };
  40141. let info = {
  40142. name: prop.type,
  40143. id: prop.id,
  40144. unlit:true,
  40145. /* transform : {
  40146. position : prop.position,
  40147. rotation : new THREE.Euler().setFromVector3(prop.rotation),
  40148. scale: new THREE.Vector3(prop.scale,prop.scale,prop.scale),
  40149. } */
  40150. };
  40151. if(prop.type == 'glb'){
  40152. info.glburl = prop.url;
  40153. }else {
  40154. info.objurl = prop.url;
  40155. info.mtlurl = prop.mtlurl;
  40156. }
  40157. viewer.loadModel(info , callback, onProgress, onError);
  40158. }
  40159. };
  40160. return {THREE: THREE$1}
  40161. };
  40162. /*
  40163. 坐标转换问题:
  40164. 由于控制点可以随便输入,所以本地和地理位置的转换也是可拉伸的。而navvis的转换是等比由中心展开,
  40165. 所以对比两种转化方式时误差较大。
  40166. 另外地理注册控制点是有参考数据集的,若参考数据集和我放置在0,0,0的数据集一致,就可直接使用,否则要转换。
  40167. */
  40168. class Action extends EventDispatcher {
  40169. constructor (args = {}) {
  40170. super();
  40171. this.icon = args.icon || '';
  40172. this.tooltip = args.tooltip;
  40173. if (args.onclick !== undefined) {
  40174. this.onclick = args.onclick;
  40175. }
  40176. }
  40177. onclick (event) {
  40178. }
  40179. pairWith (object) {
  40180. }
  40181. setIcon (newIcon) {
  40182. let oldIcon = this.icon;
  40183. if (newIcon === oldIcon) {
  40184. return;
  40185. }
  40186. this.icon = newIcon;
  40187. this.dispatchEvent({
  40188. type: 'icon_changed',
  40189. action: this,
  40190. icon: newIcon,
  40191. oldIcon: oldIcon
  40192. });
  40193. }
  40194. };
  40195. //Potree.Actions = {};
  40196. //
  40197. //Potree.Actions.ToggleAnnotationVisibility = class ToggleAnnotationVisibility extends Potree.Action {
  40198. // constructor (args = {}) {
  40199. // super(args);
  40200. //
  40201. // this.icon = Potree.resourcePath + '/icons/eye.svg';
  40202. // this.showIn = 'sidebar';
  40203. // this.tooltip = 'toggle visibility';
  40204. // }
  40205. //
  40206. // pairWith (annotation) {
  40207. // if (annotation.visible) {
  40208. // this.setIcon(Potree.resourcePath + '/icons/eye.svg');
  40209. // } else {
  40210. // this.setIcon(Potree.resourcePath + '/icons/eye_crossed.svg');
  40211. // }
  40212. //
  40213. // annotation.addEventListener('visibility_changed', e => {
  40214. // let annotation = e.annotation;
  40215. //
  40216. // if (annotation.visible) {
  40217. // this.setIcon(Potree.resourcePath + '/icons/eye.svg');
  40218. // } else {
  40219. // this.setIcon(Potree.resourcePath + '/icons/eye_crossed.svg');
  40220. // }
  40221. // });
  40222. // }
  40223. //
  40224. // onclick (event) {
  40225. // let annotation = event.annotation;
  40226. //
  40227. // annotation.visible = !annotation.visible;
  40228. //
  40229. // if (annotation.visible) {
  40230. // this.setIcon(Potree.resourcePath + '/icons/eye.svg');
  40231. // } else {
  40232. // this.setIcon(Potree.resourcePath + '/icons/eye_crossed.svg');
  40233. // }
  40234. // }
  40235. //};
  40236. class PathAnimation{
  40237. constructor(path, start, end, speed, callback){
  40238. this.path = path;
  40239. this.length = this.path.spline.getLength();
  40240. this.speed = speed;
  40241. this.callback = callback;
  40242. this.tween = null;
  40243. this.startPoint = Math.max(start, 0);
  40244. this.endPoint = Math.min(end, this.length);
  40245. this.t = 0.0;
  40246. }
  40247. start(resume = false){
  40248. if(this.tween){
  40249. this.tween.stop();
  40250. this.tween = null;
  40251. }
  40252. let tStart;
  40253. if(resume){
  40254. tStart = this.t;
  40255. }else {
  40256. tStart = this.startPoint / this.length;
  40257. }
  40258. let tEnd = this.endPoint / this.length;
  40259. let animationDuration = (tEnd - tStart) * this.length * 1000 / this.speed;
  40260. let progress = {t: tStart};
  40261. this.tween = new TWEEN.Tween(progress).to({t: tEnd}, animationDuration);
  40262. this.tween.easing(TWEEN.Easing.Linear.None);
  40263. this.tween.onUpdate((e) => {
  40264. this.t = progress.t;
  40265. this.callback(progress.t);
  40266. });
  40267. this.tween.onComplete(() => {
  40268. if(this.repeat){
  40269. this.start();
  40270. }
  40271. });
  40272. setTimeout(() => {
  40273. this.tween.start();
  40274. }, 0);
  40275. }
  40276. stop(){
  40277. if(!this.tween){
  40278. return;
  40279. }
  40280. this.tween.stop();
  40281. this.tween = null;
  40282. this.t = 0;
  40283. }
  40284. pause(){
  40285. if(!this.tween){
  40286. return;
  40287. }
  40288. this.tween.stop();
  40289. TWEEN.remove(this.tween);
  40290. this.tween = null;
  40291. }
  40292. resume(){
  40293. this.start(true);
  40294. }
  40295. getPoint(t){
  40296. return this.path.spline.getPoint(t);
  40297. }
  40298. }
  40299. class AnimationPath{
  40300. constructor (points = []) {
  40301. this.points = points;
  40302. this.spline = new CatmullRomCurve3(points);
  40303. //this.spline.reparametrizeByArcLength(1 / this.spline.getLength().total);
  40304. }
  40305. get (t) {
  40306. return this.spline.getPoint(t);
  40307. }
  40308. getLength () {
  40309. return this.spline.getLength();
  40310. }
  40311. animate (start, end, speed, callback) {
  40312. let animation = new PathAnimation(this, start, end, speed, callback);
  40313. animation.start();
  40314. return animation;
  40315. }
  40316. pause () {
  40317. if (this.tween) {
  40318. this.tween.stop();
  40319. }
  40320. }
  40321. resume () {
  40322. if (this.tween) {
  40323. this.tween.start();
  40324. }
  40325. }
  40326. getGeometry () {
  40327. let geometry = new Geometry();
  40328. let samples = 500;
  40329. let i = 0;
  40330. for (let u = 0; u <= 1; u += 1 / samples) {
  40331. let position = this.spline.getPoint(u);
  40332. geometry.vertices[i] = new Vector3(position.x, position.y, position.z);
  40333. i++;
  40334. }
  40335. if(this.closed){
  40336. let position = this.spline.getPoint(0);
  40337. geometry.vertices[i] = new Vector3(position.x, position.y, position.z);
  40338. }
  40339. return geometry;
  40340. }
  40341. get closed(){
  40342. return this.spline.closed;
  40343. }
  40344. set closed(value){
  40345. this.spline.closed = value;
  40346. }
  40347. }
  40348. class Annotation extends EventDispatcher {
  40349. constructor (args = {}) {
  40350. super();
  40351. this.scene = null;
  40352. this._title = args.title || 'No Title';
  40353. this._description = args.description || '';
  40354. this.offset = new Vector3();
  40355. this.uuid = MathUtils.generateUUID();
  40356. if (!args.position) {
  40357. this.position = null;
  40358. } else if (args.position.x != null) {
  40359. this.position = args.position;
  40360. } else {
  40361. this.position = new Vector3(...args.position);
  40362. }
  40363. this.cameraPosition = (args.cameraPosition instanceof Array)
  40364. ? new Vector3().fromArray(args.cameraPosition) : args.cameraPosition;
  40365. this.cameraTarget = (args.cameraTarget instanceof Array)
  40366. ? new Vector3().fromArray(args.cameraTarget) : args.cameraTarget;
  40367. if(!this.cameraTarget && this.position){//add
  40368. this.cameraTarget = this.position.clone();
  40369. }
  40370. this.radius = args.radius;
  40371. this.view = args.view || null;
  40372. this.keepOpen = false;
  40373. this.descriptionVisible = false;
  40374. this.showDescription = true;
  40375. this.actions = args.actions || [];
  40376. this.isHighlighted = false;
  40377. this._visible = true;
  40378. this.__visible = true;
  40379. this._display = true;
  40380. this._expand = false;
  40381. this.collapseThreshold = [args.collapseThreshold, 100].find(e => e !== undefined);
  40382. this.children = [];
  40383. this.parent = null;
  40384. this.boundingBox = new Box3();
  40385. let iconClose = exports.resourcePath + '/icons/close.svg';
  40386. this.domElement = $(`
  40387. <div class="annotation" oncontextmenu="return false;">
  40388. <div class="annotation-titlebar">
  40389. <span class="annotation-label"></span>
  40390. </div>
  40391. <div class="annotation-description">
  40392. <span class="annotation-description-close">
  40393. <img src="${iconClose}" width="16px">
  40394. </span>
  40395. <span class="annotation-description-content">${this._description}</span>
  40396. </div>
  40397. </div>
  40398. `);
  40399. this.elTitlebar = this.domElement.find('.annotation-titlebar');
  40400. this.elTitle = this.elTitlebar.find('.annotation-label');
  40401. this.elTitle.append(this._title);
  40402. this.elDescription = this.domElement.find('.annotation-description');
  40403. this.elDescriptionClose = this.elDescription.find('.annotation-description-close');
  40404. // this.elDescriptionContent = this.elDescription.find(".annotation-description-content");
  40405. this.clickTitle = () => {
  40406. //if(this.hasView()){
  40407. this.moveHere(this.scene.getActiveCamera());
  40408. //}
  40409. this.dispatchEvent({type: 'click', target: this});
  40410. viewer.renderer.domElement.focus();//add 使得方向键可用
  40411. };
  40412. this.elTitle.click(this.clickTitle);
  40413. this.actions = this.actions.map(a => {
  40414. if (a instanceof Action) {
  40415. return a;
  40416. } else {
  40417. return new Action(a);
  40418. }
  40419. });
  40420. for (let action of this.actions) {
  40421. action.pairWith(this);
  40422. }
  40423. let actions = this.actions.filter(
  40424. a => a.showIn === undefined || a.showIn.includes('scene'));
  40425. for (let action of actions) {
  40426. let elButton = $(`<img src="${action.icon}" class="annotation-action-icon">`);
  40427. this.elTitlebar.append(elButton);
  40428. elButton.click(() => action.onclick({annotation: this}));
  40429. }
  40430. this.elDescriptionClose.hover(
  40431. e => this.elDescriptionClose.css('opacity', '1'),
  40432. e => this.elDescriptionClose.css('opacity', '0.5')
  40433. );
  40434. this.elDescriptionClose.click(e => this.setHighlighted(false));
  40435. // this.elDescriptionContent.html(this._description);
  40436. this.domElement.mouseenter(e => this.setHighlighted(true));
  40437. this.domElement.mouseleave(e => this.setHighlighted(false));
  40438. this.domElement.on('touchstart', e => {
  40439. this.setHighlighted(!this.isHighlighted);
  40440. });
  40441. this.display = false;
  40442. //this.display = true;
  40443. }
  40444. installHandles(viewer){
  40445. if(this.handles !== undefined){
  40446. return;
  40447. }
  40448. let domElement = $(`
  40449. <div style="position: absolute; left: 300; top: 200; pointer-events: none">
  40450. <svg width="300" height="600">
  40451. <line x1="0" y1="0" x2="1200" y2="200" style="stroke: black; stroke-width:2" />
  40452. <circle cx="50" cy="50" r="4" stroke="black" stroke-width="2" fill="gray" />
  40453. <circle cx="150" cy="50" r="4" stroke="black" stroke-width="2" fill="gray" />
  40454. </svg>
  40455. </div>
  40456. `);
  40457. let svg = domElement.find("svg")[0];
  40458. let elLine = domElement.find("line")[0];
  40459. let elStart = domElement.find("circle")[0];
  40460. let elEnd = domElement.find("circle")[1];
  40461. let setCoordinates = (start, end) => {
  40462. elStart.setAttribute("cx", `${start.x}`);
  40463. elStart.setAttribute("cy", `${start.y}`);
  40464. elEnd.setAttribute("cx", `${end.x}`);
  40465. elEnd.setAttribute("cy", `${end.y}`);
  40466. elLine.setAttribute("x1", start.x);
  40467. elLine.setAttribute("y1", start.y);
  40468. elLine.setAttribute("x2", end.x);
  40469. elLine.setAttribute("y2", end.y);
  40470. let box = svg.getBBox();
  40471. svg.setAttribute("width", `${box.width}`);
  40472. svg.setAttribute("height", `${box.height}`);
  40473. svg.setAttribute("viewBox", `${box.x} ${box.y} ${box.width} ${box.height}`);
  40474. let ya = start.y - end.y;
  40475. let xa = start.x - end.x;
  40476. if(ya > 0){
  40477. start.y = start.y - ya;
  40478. }
  40479. if(xa > 0){
  40480. start.x = start.x - xa;
  40481. }
  40482. domElement.css("left", `${start.x}px`);
  40483. domElement.css("top", `${start.y}px`);
  40484. };
  40485. $(viewer.renderArea).append(domElement);
  40486. let annotationStartPos = this.position.clone();
  40487. let annotationStartOffset = this.offset.clone();
  40488. $(this.domElement).draggable({
  40489. start: (event, ui) => {
  40490. annotationStartPos = this.position.clone();
  40491. annotationStartOffset = this.offset.clone();
  40492. $(this.domElement).find(".annotation-titlebar").css("pointer-events", "none");
  40493. console.log($(this.domElement).find(".annotation-titlebar"));
  40494. },
  40495. stop: () => {
  40496. $(this.domElement).find(".annotation-titlebar").css("pointer-events", "");
  40497. },
  40498. drag: (event, ui ) => {
  40499. let renderAreaWidth = viewer.renderer.getSize(new Vector2$1()).width;
  40500. //let renderAreaHeight = viewer.renderer.getSize().height;
  40501. let diff = {
  40502. x: ui.originalPosition.left - ui.position.left,
  40503. y: ui.originalPosition.top - ui.position.top
  40504. };
  40505. let nDiff = {
  40506. x: -(diff.x / renderAreaWidth) * 2,
  40507. y: (diff.y / renderAreaWidth) * 2
  40508. };
  40509. let camera = viewer.scene.getActiveCamera();
  40510. let oldScreenPos = new Vector3()
  40511. .addVectors(annotationStartPos, annotationStartOffset)
  40512. .project(camera);
  40513. let newScreenPos = oldScreenPos.clone();
  40514. newScreenPos.x += nDiff.x;
  40515. newScreenPos.y += nDiff.y;
  40516. let newPos = newScreenPos.clone();
  40517. newPos.unproject(camera);
  40518. let newOffset = new Vector3().subVectors(newPos, this.position);
  40519. this.offset.copy(newOffset);
  40520. }
  40521. });
  40522. let updateCallback = () => {
  40523. let position = this.position;
  40524. let scene = viewer.scene;
  40525. const renderAreaSize = viewer.renderer.getSize(new Vector2$1());
  40526. let renderAreaWidth = renderAreaSize.width;
  40527. let renderAreaHeight = renderAreaSize.height;
  40528. let start = this.position.clone();
  40529. let end = new Vector3().addVectors(this.position, this.offset);
  40530. let toScreen = (position) => {
  40531. let camera = scene.getActiveCamera();
  40532. let screenPos = new Vector3();
  40533. let worldView = new Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  40534. let ndc = new Vector4(position.x, position.y, position.z, 1.0).applyMatrix4(worldView);
  40535. // limit w to small positive value, in case position is behind the camera
  40536. ndc.w = Math.max(ndc.w, 0.1);
  40537. ndc.divideScalar(ndc.w);
  40538. screenPos.copy(ndc);
  40539. screenPos.x = renderAreaWidth * (screenPos.x + 1) / 2;
  40540. screenPos.y = renderAreaHeight * (1 - (screenPos.y + 1) / 2);
  40541. return screenPos;
  40542. };
  40543. start = toScreen(start);
  40544. end = toScreen(end);
  40545. setCoordinates(start, end);
  40546. };
  40547. viewer.addEventListener("update", updateCallback);
  40548. this.handles = {
  40549. domElement: domElement,
  40550. setCoordinates: setCoordinates,
  40551. updateCallback: updateCallback
  40552. };
  40553. }
  40554. removeHandles(viewer){
  40555. if(this.handles === undefined){
  40556. return;
  40557. }
  40558. //$(viewer.renderArea).remove(this.handles.domElement);
  40559. this.handles.domElement.remove();
  40560. viewer.removeEventListener("update", this.handles.updateCallback);
  40561. delete this.handles;
  40562. }
  40563. get visible () {
  40564. return this._visible;
  40565. }
  40566. set visible (value) {
  40567. if (this._visible === value) {
  40568. return;
  40569. }
  40570. this._visible = value;
  40571. //this.traverse(node => {
  40572. // node.display = value;
  40573. //});
  40574. this.dispatchEvent({
  40575. type: 'visibility_changed',
  40576. annotation: this
  40577. });
  40578. }
  40579. get display () {
  40580. return this._display;
  40581. }
  40582. set display (display) {
  40583. if (this._display === display) {
  40584. return;
  40585. }
  40586. this._display = display;
  40587. if (display) {
  40588. // this.domElement.fadeIn(200);
  40589. this.domElement.show();
  40590. } else {
  40591. // this.domElement.fadeOut(200);
  40592. this.domElement.hide();
  40593. }
  40594. }
  40595. get expand () {
  40596. return this._expand;
  40597. }
  40598. set expand (expand) {
  40599. if (this._expand === expand) {
  40600. return;
  40601. }
  40602. if (expand) {
  40603. this.display = false;
  40604. } else {
  40605. this.display = true;
  40606. this.traverseDescendants(node => {
  40607. node.display = false;
  40608. });
  40609. }
  40610. this._expand = expand;
  40611. }
  40612. get title () {
  40613. return this._title;
  40614. }
  40615. set title (title) {
  40616. if (this._title === title) {
  40617. return;
  40618. }
  40619. this._title = title;
  40620. this.elTitle.empty();
  40621. this.elTitle.append(this._title);
  40622. this.dispatchEvent({
  40623. type: "annotation_changed",
  40624. annotation: this,
  40625. });
  40626. }
  40627. get description () {
  40628. return this._description;
  40629. }
  40630. set description (description) {
  40631. if (this._description === description) {
  40632. return;
  40633. }
  40634. this._description = description;
  40635. const elDescriptionContent = this.elDescription.find(".annotation-description-content");
  40636. elDescriptionContent.empty();
  40637. elDescriptionContent.append(this._description);
  40638. this.dispatchEvent({
  40639. type: "annotation_changed",
  40640. annotation: this,
  40641. });
  40642. }
  40643. add (annotation) {
  40644. if (!this.children.includes(annotation)) {
  40645. this.children.push(annotation);
  40646. annotation.parent = this;
  40647. let descendants = [];
  40648. annotation.traverse(a => { descendants.push(a); });
  40649. for (let descendant of descendants) {
  40650. let c = this;
  40651. while (c !== null) {
  40652. c.dispatchEvent({
  40653. 'type': 'annotation_added',
  40654. 'annotation': descendant
  40655. });
  40656. c = c.parent;
  40657. }
  40658. }
  40659. }
  40660. }
  40661. level () {
  40662. if (this.parent === null) {
  40663. return 0;
  40664. } else {
  40665. return this.parent.level() + 1;
  40666. }
  40667. }
  40668. hasChild(annotation) {
  40669. return this.children.includes(annotation);
  40670. }
  40671. remove (annotation) {
  40672. if (this.hasChild(annotation)) {
  40673. annotation.removeAllChildren();
  40674. annotation.dispose();
  40675. this.children = this.children.filter(e => e !== annotation);
  40676. annotation.parent = null;
  40677. }
  40678. }
  40679. removeAllChildren() {
  40680. this.children.forEach((child) => {
  40681. if (child.children.length > 0) {
  40682. child.removeAllChildren();
  40683. }
  40684. this.remove(child);
  40685. });
  40686. }
  40687. updateBounds () {
  40688. let box = new Box3();
  40689. if (this.position) {
  40690. box.expandByPoint(this.position);
  40691. }
  40692. for (let child of this.children) {
  40693. child.updateBounds();
  40694. box.union(child.boundingBox);
  40695. }
  40696. this.boundingBox.copy(box);
  40697. }
  40698. traverse (handler) {
  40699. let expand = handler(this);
  40700. if (expand === undefined || expand === true) {
  40701. for (let child of this.children) {
  40702. child.traverse(handler);
  40703. }
  40704. }
  40705. }
  40706. traverseDescendants (handler) {
  40707. for (let child of this.children) {
  40708. child.traverse(handler);
  40709. }
  40710. }
  40711. flatten () {
  40712. let annotations = [];
  40713. this.traverse(annotation => {
  40714. annotations.push(annotation);
  40715. });
  40716. return annotations;
  40717. }
  40718. descendants () {
  40719. let annotations = [];
  40720. this.traverse(annotation => {
  40721. if (annotation !== this) {
  40722. annotations.push(annotation);
  40723. }
  40724. });
  40725. return annotations;
  40726. }
  40727. setHighlighted (highlighted) {
  40728. if (highlighted) {
  40729. this.domElement.css('opacity', '0.8');
  40730. this.elTitlebar.css('box-shadow', '0 0 5px #fff');
  40731. this.domElement.css('z-index', '1000');
  40732. if (this._description) {
  40733. this.descriptionVisible = true;
  40734. this.elDescription.fadeIn(200);
  40735. this.elDescription.css('position', 'relative');
  40736. }
  40737. } else {
  40738. this.domElement.css('opacity', '0.5');
  40739. this.elTitlebar.css('box-shadow', '');
  40740. this.domElement.css('z-index', '100');
  40741. this.descriptionVisible = false;
  40742. this.elDescription.css('display', 'none');
  40743. }
  40744. this.isHighlighted = highlighted;
  40745. }
  40746. hasView () {
  40747. let hasPosTargetView = this.cameraTarget.x != null;
  40748. hasPosTargetView = hasPosTargetView && this.cameraPosition.x != null;
  40749. let hasRadiusView = this.radius !== undefined;
  40750. let hasView = hasPosTargetView || hasRadiusView;
  40751. return hasView;
  40752. };
  40753. moveHere (camera) {
  40754. if (!this.hasView()) {
  40755. return;
  40756. }
  40757. let view = this.scene.view;
  40758. let animationDuration = 500;
  40759. let easing = TWEEN.Easing.Quartic.Out;
  40760. let endTarget;
  40761. if (this.cameraTarget) {
  40762. endTarget = this.cameraTarget;
  40763. } else if (this.position) {
  40764. endTarget = this.position;
  40765. } else {
  40766. endTarget = this.boundingBox.getCenter(new Vector3());
  40767. }
  40768. if (this.cameraPosition) {
  40769. let endPosition = this.cameraPosition;
  40770. Utils.moveTo(this.scene, endPosition, endTarget);
  40771. } else if (this.radius) {
  40772. let direction = view.direction;
  40773. let endPosition = endTarget.clone().add(direction.multiplyScalar(-this.radius));
  40774. let startRadius = view.radius;
  40775. let endRadius = this.radius;
  40776. { // animate camera position
  40777. let tween = new TWEEN.Tween(view.position).to(endPosition, animationDuration);
  40778. tween.easing(easing);
  40779. tween.start();
  40780. }
  40781. { // animate radius
  40782. let t = {x: 0};
  40783. let tween = new TWEEN.Tween(t)
  40784. .to({x: 1}, animationDuration)
  40785. .onUpdate(function () {
  40786. view.radius = this.x * endRadius + (1 - this.x) * startRadius;
  40787. });
  40788. tween.easing(easing);
  40789. tween.start();
  40790. }
  40791. }
  40792. };
  40793. dispose () {
  40794. if (this.domElement.parentElement) {
  40795. this.domElement.parentElement.removeChild(this.domElement);
  40796. }
  40797. };
  40798. toString () {
  40799. return 'Annotation: ' + this._title;
  40800. }
  40801. };
  40802. class EnumItem{
  40803. constructor(object){
  40804. for(let key of Object.keys(object)){
  40805. this[key] = object[key];
  40806. }
  40807. }
  40808. inspect(){
  40809. return `Enum(${this.name}: ${this.value})`;
  40810. }
  40811. };
  40812. class Enum{//??????做什么用的
  40813. constructor(object){
  40814. this.object = object;
  40815. for(let key of Object.keys(object)){
  40816. let value = object[key];
  40817. if(typeof value === "object"){
  40818. value.name = key;
  40819. }else {
  40820. value = {name: key, value: value};
  40821. }
  40822. this[key] = new EnumItem(value);
  40823. }
  40824. }
  40825. fromValue(value){
  40826. for(let key of Object.keys(this.object)){
  40827. if(this[key].value === value){
  40828. return this[key];
  40829. }
  40830. }
  40831. throw new Error(`No enum for value: ${value}`);
  40832. }
  40833. };
  40834. const CameraMode = {
  40835. ORTHOGRAPHIC: 0,
  40836. PERSPECTIVE: 1,
  40837. VR: 2,
  40838. };
  40839. const ClipTask = {
  40840. NONE: 0,
  40841. HIGHLIGHT: 1,
  40842. SHOW_INSIDE: 2,
  40843. SHOW_OUTSIDE: 3
  40844. };
  40845. const ClipMethod = {
  40846. INSIDE_ANY: 0,
  40847. INSIDE_ALL: 1
  40848. };
  40849. const ElevationGradientRepeat = {
  40850. CLAMP: 0,
  40851. REPEAT: 1,
  40852. MIRRORED_REPEAT: 2,
  40853. };
  40854. const Buttons = {// MouseEvent.buttons
  40855. //buttons,设置按下了鼠标哪些键,是一个3个比特位的二进制值,默认为0。1表示按下主键(通常是左键),2表示按下次要键(通常是右键),4表示按下辅助键(通常是中间的键)。
  40856. NONE:0,//add
  40857. LEFT: 0b0001,
  40858. RIGHT: 0b0010,
  40859. MIDDLE: 0b0100
  40860. };
  40861. /* 如果访问的是button, 用THREE.MOUSE来判断:
  40862. button,设置按下了哪一个鼠标按键,默认为0。-1表示没有按键,0表示按下主键(通常是左键),1表示按下辅助键(通常是中间的键),2表示按下次要键(通常是右键)
  40863. */
  40864. const PointSizeType = {
  40865. FIXED: 0,
  40866. ATTENUATED: 1,
  40867. ADAPTIVE: 2
  40868. };
  40869. const PointShape = {
  40870. SQUARE: 0,
  40871. CIRCLE: 1,
  40872. PARABOLOID: 2
  40873. };
  40874. const TreeType = {
  40875. OCTREE: 0,
  40876. KDTREE: 1
  40877. };
  40878. const LengthUnits = {
  40879. METER: {code: 'm', unitspermeter: 1.0},
  40880. FEET: {code: 'ft', unitspermeter: 3.28084},
  40881. INCH: {code: '\u2033', unitspermeter: 39.3701}
  40882. };
  40883. /////////// add //////////////////////////////////
  40884. var GLCubeFaces$1 = {
  40885. GL_TEXTURE_CUBE_MAP_POSITIVE_X: 0,
  40886. GL_TEXTURE_CUBE_MAP_NEGATIVE_X: 1,
  40887. GL_TEXTURE_CUBE_MAP_POSITIVE_Y: 2,
  40888. GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: 3,
  40889. GL_TEXTURE_CUBE_MAP_POSITIVE_Z: 4,
  40890. GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: 5
  40891. };
  40892. var PanoSizeClass = {
  40893. BASE: 1,
  40894. STANDARD: 2,
  40895. HIGH: 3,
  40896. ULTRAHIGH: 4
  40897. };
  40898. var PanoRendererEvents = {
  40899. PanoRenderComplete: "panorama.render.complete",
  40900. TileRenderFailure: "panorama.tile.render.failed",
  40901. TileRenderSuccess: "panorama.tile.render.success",
  40902. TileUploadAttempted: "panorama.tile.upload.attempted",
  40903. UploadAttemptedForAllTiles: "panorama.upload.attempted.all.tiles",
  40904. ZoomLevelRenderStarted: "panorama.zoom.render.started"
  40905. };
  40906. var SceneRendererEvents = {
  40907. ContextCreated: "scene-renderer-context-created",
  40908. AfterRender: "after-render",
  40909. MemoryUsageUpdated: "scene-renderer-memory-usage-updated"
  40910. };
  40911. var TileDownloaderEvents = {
  40912. TileDownloadSuccess: "tiledownloader.download.success",
  40913. TileDownloadFailure: "tiledownloader.download.failure",
  40914. PanoDownloadComplete: "tiledownloader.pano.download.complete"
  40915. };
  40916. var Vectors = {
  40917. UP: new Vector3(0,1,0),
  40918. DOWN: new Vector3(0,-1,0),
  40919. LEFT: new Vector3(-1,0,0),
  40920. RIGHT: new Vector3(1,0,0),
  40921. FORWARD: new Vector3(0,0,-1),
  40922. BACK: new Vector3(0,0,1)
  40923. };
  40924. var Vectors2 = {};
  40925. for(var i in Vectors){
  40926. Vectors2[i] = math.convertVector.YupToZup(Vectors[i]);
  40927. }
  40928. var DownloadStatus = Object.freeze({
  40929. None: 0,
  40930. Queued: 1,
  40931. ForceQueued: 2,
  40932. Downloading: 3,
  40933. Downloaded: 4,
  40934. DownloadFailed: 5
  40935. });
  40936. var ModelManagerEvents = {
  40937. ModelAdded: "model-added",
  40938. ActiveModelChanged: "active-model-changed"
  40939. };
  40940. var PanoramaEvents = {
  40941. Enter: 'panorama.enter',
  40942. Exit: 'panorama.exit',
  40943. LoadComplete: "panorama.load.complete",
  40944. LoadFailed: "panorama.load.failed",
  40945. TileLoaded: "panorama.tile.loaded",
  40946. VideoRendered: "panorama.video.rendered"
  40947. };
  40948. /**
  40949. * @author mrdoob / http://mrdoob.com/ https://github.com/mrdoob/eventdispatcher.js
  40950. *
  40951. * with slight modifications by mschuetz, http://potree.org
  40952. *
  40953. */
  40954. // The MIT License
  40955. //
  40956. // Copyright (c) 2011 Mr.doob
  40957. //
  40958. // Permission is hereby granted, free of charge, to any person obtaining a copy
  40959. // of this software and associated documentation files (the "Software"), to deal
  40960. // in the Software without restriction, including without limitation the rights
  40961. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  40962. // copies of the Software, and to permit persons to whom the Software is
  40963. // furnished to do so, subject to the following conditions:
  40964. //
  40965. // The above copyright notice and this permission notice shall be included in
  40966. // all copies or substantial portions of the Software.
  40967. //
  40968. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40969. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40970. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40971. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40972. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  40973. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  40974. // THE SOFTWARE.
  40975. class EventDispatcher$1{
  40976. constructor(){
  40977. this._listeners = {};
  40978. }
  40979. addEventListener(type, listener, importance=0 ){//add importance
  40980. const listeners = this._listeners;
  40981. if(listeners[type] === undefined){
  40982. listeners[type] = [];
  40983. }
  40984. if(listeners[type].indexOf(listener) === - 1){
  40985. listeners[type].push({ listener, importance});
  40986. listeners[type] = listeners[type].sort((e,a)=> a.importance - e.importance);//add
  40987. }
  40988. }
  40989. hasEventListener(type, listener){
  40990. const listeners = this._listeners;
  40991. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== - 1;
  40992. }
  40993. removeEventListener(type, listener){
  40994. let listeners = this._listeners;
  40995. let listenerArray = listeners[type];
  40996. if (listenerArray !== undefined){
  40997. /* let index = listenerArray.indexOf(listener);
  40998. if(index !== - 1){
  40999. listenerArray.splice(index, 1);
  41000. } */
  41001. let item = listenerArray.find(e=>e.listener == listener);
  41002. item && listenerArray.splice(listenerArray.indexOf(item), 1);
  41003. }
  41004. }
  41005. removeEventListeners(type){
  41006. if(this._listeners[type] !== undefined){
  41007. delete this._listeners[type];
  41008. }
  41009. };
  41010. dispatchEvent(event){
  41011. if(typeof event == 'string'){//add
  41012. event = {type:event};
  41013. }
  41014. let listeners = this._listeners;
  41015. let listenerArray = listeners[event.type];
  41016. if ( listenerArray !== undefined ) {
  41017. event.target = this;
  41018. for(let {listener} of listenerArray.slice(0)){
  41019. let result = listener.call(this, event); //add stopContinue
  41020. if(result && result.stopContinue){
  41021. break
  41022. }
  41023. }
  41024. }
  41025. }
  41026. //add
  41027. /* emit(type){
  41028. this.dispatchEvent({type, arguments: Array.from(arguments).slice(1, arguments.length) })
  41029. }
  41030. on(type, fun){
  41031. this.addEventListener(type,(ev)=>{
  41032. fun.apply(this, ev.arguments)
  41033. })
  41034. }
  41035. off(type, fun){
  41036. this.removeEventListener(type,)
  41037. }
  41038. once(type, fun) {
  41039. function callback() {
  41040. this.removeEventListener(type, callback),
  41041. n || (n = !0, fun.apply(this, arguments))
  41042. }
  41043. var n = !1;
  41044. return callback.listener = fun,
  41045. this.on(type, callback),
  41046. this
  41047. } */
  41048. removeAllListeners(){
  41049. this._listeners = {};
  41050. }
  41051. }
  41052. const KeyCodes = {
  41053. LEFT: 37,
  41054. UP: 38,
  41055. RIGHT: 39,
  41056. BOTTOM: 40,
  41057. DELETE: 46,
  41058. BACKSPACE:8,
  41059. A: 'A'.charCodeAt(0),
  41060. S: 'S'.charCodeAt(0),
  41061. D: 'D'.charCodeAt(0),
  41062. W: 'W'.charCodeAt(0),
  41063. Q: 'Q'.charCodeAt(0),
  41064. E: 'E'.charCodeAt(0),
  41065. R: 'R'.charCodeAt(0),
  41066. F: 'F'.charCodeAt(0)
  41067. };
  41068. class LRUItem{
  41069. constructor(node){
  41070. this.previous = null;
  41071. this.next = null;
  41072. this.node = node;
  41073. }
  41074. }
  41075. /**
  41076. *
  41077. * @class A doubly-linked-list of the least recently used elements.
  41078. */
  41079. class LRU{
  41080. constructor(){
  41081. // the least recently used item
  41082. this.first = null;
  41083. // the most recently used item
  41084. this.last = null;
  41085. // a list of all items in the lru list
  41086. this.items = {};
  41087. this.elements = 0;
  41088. this.numPoints = 0;
  41089. }
  41090. size(){
  41091. return this.elements;
  41092. }
  41093. contains(node){
  41094. return this.items[node.id] == null;
  41095. }
  41096. touch(node){
  41097. if (!node.loaded) {
  41098. return;
  41099. }
  41100. let item;
  41101. if (this.items[node.id] == null) {
  41102. // add to list
  41103. item = new LRUItem(node);
  41104. item.previous = this.last;
  41105. this.last = item;
  41106. if (item.previous !== null) {
  41107. item.previous.next = item;
  41108. }
  41109. this.items[node.id] = item;
  41110. this.elements++;
  41111. if (this.first === null) {
  41112. this.first = item;
  41113. }
  41114. this.numPoints += node.numPoints;
  41115. } else {
  41116. // update in list
  41117. item = this.items[node.id];
  41118. if (item.previous === null) {
  41119. // handle touch on first element
  41120. if (item.next !== null) {
  41121. this.first = item.next;
  41122. this.first.previous = null;
  41123. item.previous = this.last;
  41124. item.next = null;
  41125. this.last = item;
  41126. item.previous.next = item;
  41127. }
  41128. } else if (item.next === null) {
  41129. // handle touch on last element
  41130. } else {
  41131. // handle touch on any other element
  41132. item.previous.next = item.next;
  41133. item.next.previous = item.previous;
  41134. item.previous = this.last;
  41135. item.next = null;
  41136. this.last = item;
  41137. item.previous.next = item;
  41138. }
  41139. }
  41140. }
  41141. remove(node){
  41142. let lruItem = this.items[node.id];
  41143. if (lruItem) {
  41144. if (this.elements === 1) {
  41145. this.first = null;
  41146. this.last = null;
  41147. } else {
  41148. if (!lruItem.previous) {
  41149. this.first = lruItem.next;
  41150. this.first.previous = null;
  41151. }
  41152. if (!lruItem.next) {
  41153. this.last = lruItem.previous;
  41154. this.last.next = null;
  41155. }
  41156. if (lruItem.previous && lruItem.next) {
  41157. lruItem.previous.next = lruItem.next;
  41158. lruItem.next.previous = lruItem.previous;
  41159. }
  41160. }
  41161. delete this.items[node.id];
  41162. this.elements--;
  41163. this.numPoints -= node.numPoints;
  41164. }
  41165. }
  41166. getLRUItem(){
  41167. if (this.first === null) {
  41168. return null;
  41169. }
  41170. let lru = this.first;
  41171. return lru.node;
  41172. }
  41173. toString(){
  41174. let string = '{ ';
  41175. let curr = this.first;
  41176. while (curr !== null) {
  41177. string += curr.node.id;
  41178. if (curr.next !== null) {
  41179. string += ', ';
  41180. }
  41181. curr = curr.next;
  41182. }
  41183. string += '}';
  41184. string += '(' + this.size() + ')';
  41185. return string;
  41186. }
  41187. freeMemory(){
  41188. if (this.elements <= 1) {
  41189. return;
  41190. }
  41191. /* while (this.numPoints > Potree.pointLoadLimit) {
  41192. let element = this.first;
  41193. let node = element.node;
  41194. this.disposeDescendants(node);
  41195. } */
  41196. //改成navvis的,使用pointBudget,否则四屏点云闪烁。
  41197. let max = /* this.pageVisible ? */viewer.viewports.length * 2 * Potree.pointBudget;// : 1000
  41198. for (; this.numPoints > max; ) {//要根据屏幕数量来增加pointBudget
  41199. var node = this.getLRUItem();
  41200. node && this.disposeSubtree(node);
  41201. }
  41202. }
  41203. disposeSubtree(t) {//add from navvis 25.js
  41204. var e = [t];
  41205. t.traverse((function(t) {
  41206. t.loaded && e.push(t);
  41207. }
  41208. ));
  41209. for (var n = 0, i = e; n < i.length; n++) {
  41210. var o = i[n];
  41211. o.dispose(),
  41212. this.remove(o);
  41213. }
  41214. }
  41215. disposeDescendants(node){
  41216. let stack = [];
  41217. stack.push(node);
  41218. while (stack.length > 0) {
  41219. let current = stack.pop();
  41220. // console.log(current);
  41221. current.dispose();
  41222. this.remove(current);
  41223. for (let key in current.children) {
  41224. if (current.children.hasOwnProperty(key)) {
  41225. let child = current.children[key];
  41226. if (child.loaded) {
  41227. stack.push(current.children[key]);
  41228. }
  41229. }
  41230. }
  41231. }
  41232. }
  41233. }
  41234. class PointCloudTreeNode extends EventDispatcher{
  41235. constructor(){
  41236. super();
  41237. this.needsTransformUpdate = true;
  41238. }
  41239. getChildren () {
  41240. throw new Error('override function');
  41241. }
  41242. getBoundingBox () {
  41243. throw new Error('override function');
  41244. }
  41245. isLoaded () {
  41246. throw new Error('override function');
  41247. }
  41248. isGeometryNode () {
  41249. throw new Error('override function');
  41250. }
  41251. isTreeNode () {
  41252. throw new Error('override function');
  41253. }
  41254. getLevel () {
  41255. throw new Error('override function');
  41256. }
  41257. getBoundingSphere () {
  41258. throw new Error('override function');
  41259. }
  41260. };
  41261. class PointCloudTree extends Object3D {
  41262. constructor () {
  41263. super();
  41264. //this.spriteGroup = new THREE.Object3D //add
  41265. }
  41266. initialized () {
  41267. return this.root !== null;
  41268. }
  41269. };
  41270. /**
  41271. * Some types of possible point attribute data formats
  41272. *
  41273. * @class
  41274. */
  41275. const PointAttributeTypes = {
  41276. DATA_TYPE_DOUBLE: {ordinal: 0, name: "double", size: 8},
  41277. DATA_TYPE_FLOAT: {ordinal: 1, name: "float", size: 4},
  41278. DATA_TYPE_INT8: {ordinal: 2, name: "int8", size: 1},
  41279. DATA_TYPE_UINT8: {ordinal: 3, name: "uint8", size: 1},
  41280. DATA_TYPE_INT16: {ordinal: 4, name: "int16", size: 2},
  41281. DATA_TYPE_UINT16: {ordinal: 5, name: "uint16", size: 2},
  41282. DATA_TYPE_INT32: {ordinal: 6, name: "int32", size: 4},
  41283. DATA_TYPE_UINT32: {ordinal: 7, name: "uint32", size: 4},
  41284. DATA_TYPE_INT64: {ordinal: 8, name: "int64", size: 8},
  41285. DATA_TYPE_UINT64: {ordinal: 9, name: "uint64", size: 8}
  41286. };
  41287. let i$1 = 0;
  41288. for (let obj in PointAttributeTypes) {
  41289. PointAttributeTypes[i$1] = PointAttributeTypes[obj];
  41290. i$1++;
  41291. }
  41292. class PointAttribute{
  41293. constructor(name, type, numElements){
  41294. this.name = name;
  41295. this.type = type;
  41296. this.numElements = numElements;
  41297. this.byteSize = this.numElements * this.type.size;
  41298. this.description = "";
  41299. this.range = [Infinity, -Infinity];
  41300. }
  41301. };
  41302. //add
  41303. const replacements = {
  41304. "COLOR_PACKED": "rgba",
  41305. "RGBA": "rgba",
  41306. "INTENSITY": "intensity",
  41307. "CLASSIFICATION": "classification",
  41308. "GPS_TIME": "gps-time",
  41309. };
  41310. const replaceOldNames = (old) => {
  41311. if(replacements[old]){
  41312. return replacements[old];
  41313. }else {
  41314. return old;
  41315. }
  41316. };
  41317. PointAttribute.POSITION_CARTESIAN = new PointAttribute(
  41318. "POSITION_CARTESIAN", PointAttributeTypes.DATA_TYPE_FLOAT, 3);
  41319. PointAttribute.RGBA_PACKED = new PointAttribute(
  41320. replaceOldNames("COLOR_PACKED"), PointAttributeTypes.DATA_TYPE_INT8, 4);
  41321. PointAttribute.COLOR_PACKED = PointAttribute.RGBA_PACKED;
  41322. PointAttribute.RGB_PACKED = new PointAttribute(
  41323. "COLOR_PACKED", PointAttributeTypes.DATA_TYPE_INT8, 3);
  41324. PointAttribute.NORMAL_FLOATS = new PointAttribute(
  41325. "NORMAL_FLOATS", PointAttributeTypes.DATA_TYPE_FLOAT, 3);
  41326. PointAttribute.INTENSITY = new PointAttribute(
  41327. replaceOldNames("INTENSITY"), PointAttributeTypes.DATA_TYPE_UINT16, 1);
  41328. PointAttribute.CLASSIFICATION = new PointAttribute(
  41329. replaceOldNames("CLASSIFICATION"), PointAttributeTypes.DATA_TYPE_UINT8, 1);
  41330. PointAttribute.NORMAL_SPHEREMAPPED = new PointAttribute(
  41331. "NORMAL_SPHEREMAPPED", PointAttributeTypes.DATA_TYPE_UINT8, 2);
  41332. PointAttribute.NORMAL_OCT16 = new PointAttribute(
  41333. "NORMAL_OCT16", PointAttributeTypes.DATA_TYPE_UINT8, 2);
  41334. PointAttribute.NORMAL = new PointAttribute(
  41335. "NORMAL", PointAttributeTypes.DATA_TYPE_FLOAT, 3);
  41336. PointAttribute.RETURN_NUMBER = new PointAttribute(
  41337. "RETURN_NUMBER", PointAttributeTypes.DATA_TYPE_UINT8, 1);
  41338. PointAttribute.NUMBER_OF_RETURNS = new PointAttribute(
  41339. "NUMBER_OF_RETURNS", PointAttributeTypes.DATA_TYPE_UINT8, 1);
  41340. PointAttribute.SOURCE_ID = new PointAttribute(
  41341. "SOURCE_ID", PointAttributeTypes.DATA_TYPE_UINT16, 1);
  41342. PointAttribute.INDICES = new PointAttribute(
  41343. "INDICES", PointAttributeTypes.DATA_TYPE_UINT32, 1);
  41344. PointAttribute.SPACING = new PointAttribute(
  41345. "SPACING", PointAttributeTypes.DATA_TYPE_FLOAT, 1);
  41346. PointAttribute.GPS_TIME = new PointAttribute(
  41347. replaceOldNames("GPS_TIME"), PointAttributeTypes.DATA_TYPE_DOUBLE, 1);
  41348. class PointAttributes{
  41349. constructor(pointAttributes){
  41350. this.attributes = [];
  41351. this.byteSize = 0;
  41352. this.size = 0;
  41353. this.vectors = [];
  41354. if (pointAttributes != null) {
  41355. for (let i = 0; i < pointAttributes.length; i++) {
  41356. let pointAttributeName = pointAttributes[i];
  41357. let pointAttribute = PointAttribute[pointAttributeName];
  41358. this.attributes.push(pointAttribute);
  41359. this.byteSize += pointAttribute.byteSize;
  41360. this.size++;
  41361. }
  41362. }
  41363. }
  41364. add(pointAttribute){
  41365. this.attributes.push(pointAttribute);
  41366. this.byteSize += pointAttribute.byteSize;
  41367. this.size++;
  41368. };
  41369. addVector(vector){
  41370. this.vectors.push(vector);
  41371. }
  41372. hasNormals(){
  41373. for (let name in this.attributes) {
  41374. let pointAttribute = this.attributes[name];
  41375. if (
  41376. pointAttribute === PointAttribute.NORMAL_SPHEREMAPPED ||
  41377. pointAttribute === PointAttribute.NORMAL_FLOATS ||
  41378. pointAttribute === PointAttribute.NORMAL ||
  41379. pointAttribute === PointAttribute.NORMAL_OCT16) {
  41380. return true;
  41381. }
  41382. }
  41383. return false;
  41384. };
  41385. }
  41386. class U {
  41387. static toVector3(v, offset) {
  41388. return new Vector3().fromArray(v, offset || 0);
  41389. }
  41390. static toBox3(b) {
  41391. return new Box3(U.toVector3(b), U.toVector3(b, 3));
  41392. };
  41393. static findDim(schema, name) {
  41394. var dim = schema.find((dim) => dim.name == name);
  41395. if (!dim) throw new Error('Failed to find ' + name + ' in schema');
  41396. return dim;
  41397. }
  41398. static sphereFrom(b) {
  41399. return b.getBoundingSphere(new Sphere());
  41400. }
  41401. };
  41402. class PointCloudEptGeometry {
  41403. constructor(url, info) {
  41404. let version = info.version;
  41405. let schema = info.schema;
  41406. let bounds = info.bounds;
  41407. let boundsConforming = info.boundsConforming;
  41408. let xyz = [
  41409. U.findDim(schema, 'X'),
  41410. U.findDim(schema, 'Y'),
  41411. U.findDim(schema, 'Z')
  41412. ];
  41413. let scale = xyz.map((d) => d.scale || 1);
  41414. let offset = xyz.map((d) => d.offset || 0);
  41415. this.eptScale = U.toVector3(scale);
  41416. this.eptOffset = U.toVector3(offset);
  41417. this.url = url;
  41418. this.info = info;
  41419. this.type = 'ept';
  41420. this.schema = schema;
  41421. this.span = info.span || info.ticks;
  41422. this.boundingBox = U.toBox3(bounds);
  41423. this.tightBoundingBox = U.toBox3(boundsConforming);
  41424. this.offset = U.toVector3([0, 0, 0]);
  41425. this.boundingSphere = U.sphereFrom(this.boundingBox);
  41426. this.tightBoundingSphere = U.sphereFrom(this.tightBoundingBox);
  41427. this.version = new Potree.Version('1.7');
  41428. this.projection = null;
  41429. this.fallbackProjection = null;
  41430. if (info.srs && info.srs.horizontal) {
  41431. this.projection = info.srs.authority + ':' + info.srs.horizontal;
  41432. }
  41433. if (info.srs.wkt) {
  41434. if (!this.projection) this.projection = info.srs.wkt;
  41435. else this.fallbackProjection = info.srs.wkt;
  41436. }
  41437. {
  41438. // TODO [mschuetz]: named projections that proj4 can't handle seem to cause problems.
  41439. // remove them for now
  41440. try{
  41441. proj4(this.projection);
  41442. }catch(e){
  41443. this.projection = null;
  41444. }
  41445. }
  41446. {
  41447. const attributes = new PointAttributes();
  41448. attributes.add(PointAttribute.POSITION_CARTESIAN);
  41449. attributes.add(new PointAttribute("rgba", PointAttributeTypes.DATA_TYPE_UINT8, 4));
  41450. attributes.add(new PointAttribute("intensity", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  41451. attributes.add(new PointAttribute("classification", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  41452. attributes.add(new PointAttribute("gps-time", PointAttributeTypes.DATA_TYPE_DOUBLE, 1));
  41453. attributes.add(new PointAttribute("returnNumber", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  41454. attributes.add(new PointAttribute("number of returns", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  41455. attributes.add(new PointAttribute("return number", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  41456. attributes.add(new PointAttribute("source id", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  41457. this.pointAttributes = attributes;
  41458. }
  41459. this.spacing =
  41460. (this.boundingBox.max.x - this.boundingBox.min.x) / this.span;
  41461. let hierarchyType = info.hierarchyType || 'json';
  41462. const dataType = info.dataType;
  41463. if (dataType == 'laszip') {
  41464. this.loader = new Potree.EptLaszipLoader();
  41465. }
  41466. else if (dataType == 'binary') {
  41467. this.loader = new Potree.EptBinaryLoader();
  41468. }
  41469. else if (dataType == 'zstandard') {
  41470. this.loader = new Potree.EptZstandardLoader();
  41471. }
  41472. else {
  41473. throw new Error('Could not read data type: ' + dataType);
  41474. }
  41475. }
  41476. };
  41477. class EptKey {
  41478. constructor(ept, b, d, x, y, z) {
  41479. this.ept = ept;
  41480. this.b = b;
  41481. this.d = d;
  41482. this.x = x || 0;
  41483. this.y = y || 0;
  41484. this.z = z || 0;
  41485. }
  41486. name() {
  41487. return this.d + '-' + this.x + '-' + this.y + '-' + this.z;
  41488. }
  41489. step(a, b, c) {
  41490. let min = this.b.min.clone();
  41491. let max = this.b.max.clone();
  41492. let dst = new Vector3().subVectors(max, min);
  41493. if (a) min.x += dst.x / 2;
  41494. else max.x -= dst.x / 2;
  41495. if (b) min.y += dst.y / 2;
  41496. else max.y -= dst.y / 2;
  41497. if (c) min.z += dst.z / 2;
  41498. else max.z -= dst.z / 2;
  41499. return new Potree.EptKey(
  41500. this.ept,
  41501. new Box3(min, max),
  41502. this.d + 1,
  41503. this.x * 2 + a,
  41504. this.y * 2 + b,
  41505. this.z * 2 + c);
  41506. }
  41507. children() {
  41508. var result = [];
  41509. for (var a = 0; a < 2; ++a) {
  41510. for (var b = 0; b < 2; ++b) {
  41511. for (var c = 0; c < 2; ++c) {
  41512. var add = this.step(a, b, c).name();
  41513. if (!result.includes(add)) result = result.concat(add);
  41514. }
  41515. }
  41516. }
  41517. return result;
  41518. }
  41519. }
  41520. class PointCloudEptGeometryNode extends PointCloudTreeNode {
  41521. constructor(ept, b, d, x, y, z) {
  41522. super();
  41523. this.ept = ept;
  41524. this.key = new Potree.EptKey(
  41525. this.ept,
  41526. b || this.ept.boundingBox,
  41527. d || 0,
  41528. x,
  41529. y,
  41530. z);
  41531. this.id = PointCloudEptGeometryNode.IDCount++;
  41532. this.geometry = null;
  41533. this.boundingBox = this.key.b;
  41534. this.tightBoundingBox = this.boundingBox;
  41535. this.spacing = this.ept.spacing / Math.pow(2, this.key.d);
  41536. this.boundingSphere = U.sphereFrom(this.boundingBox);
  41537. // These are set during hierarchy loading.
  41538. this.hasChildren = false;
  41539. this.children = { };
  41540. this.numPoints = -1;
  41541. this.level = this.key.d;
  41542. this.loaded = false;
  41543. this.loading = false;
  41544. this.oneTimeDisposeHandlers = [];
  41545. let k = this.key;
  41546. this.name = this.toPotreeName(k.d, k.x, k.y, k.z);
  41547. this.index = parseInt(this.name.charAt(this.name.length - 1));
  41548. }
  41549. isGeometryNode() { return true; }
  41550. getLevel() { return this.level; }
  41551. isTreeNode() { return false; }
  41552. isLoaded() { return this.loaded; }
  41553. getBoundingSphere() { return this.boundingSphere; }
  41554. getBoundingBox() { return this.boundingBox; }
  41555. url() { return this.ept.url + 'ept-data/' + this.filename(); }
  41556. getNumPoints() { return this.numPoints; }
  41557. filename() { return this.key.name(); }
  41558. getChildren() {
  41559. let children = [];
  41560. for (let i = 0; i < 8; i++) {
  41561. if (this.children[i]) {
  41562. children.push(this.children[i]);
  41563. }
  41564. }
  41565. return children;
  41566. }
  41567. addChild(child) {
  41568. this.children[child.index] = child;
  41569. child.parent = this;
  41570. }
  41571. load() {
  41572. if (this.loaded || this.loading) return;
  41573. if (Potree.numNodesLoading >= Potree.maxNodesLoading) return;
  41574. this.loading = true;
  41575. ++Potree.numNodesLoading;
  41576. if (this.numPoints == -1) this.loadHierarchy();
  41577. this.loadPoints();
  41578. }
  41579. loadPoints(){
  41580. this.ept.loader.load(this);
  41581. }
  41582. async loadHierarchy() {
  41583. let nodes = { };
  41584. nodes[this.filename()] = this;
  41585. this.hasChildren = false;
  41586. let eptHierarchyFile =
  41587. `${this.ept.url}ept-hierarchy/${this.filename()}.json`;
  41588. let response = await fetch(eptHierarchyFile);
  41589. let hier = await response.json();
  41590. // Since we want to traverse top-down, and 10 comes
  41591. // lexicographically before 9 (for example), do a deep sort.
  41592. var keys = Object.keys(hier).sort((a, b) => {
  41593. let [da, xa, ya, za] = a.split('-').map((n) => parseInt(n, 10));
  41594. let [db, xb, yb, zb] = b.split('-').map((n) => parseInt(n, 10));
  41595. if (da < db) return -1; if (da > db) return 1;
  41596. if (xa < xb) return -1; if (xa > xb) return 1;
  41597. if (ya < yb) return -1; if (ya > yb) return 1;
  41598. if (za < zb) return -1; if (za > zb) return 1;
  41599. return 0;
  41600. });
  41601. keys.forEach((v) => {
  41602. let [d, x, y, z] = v.split('-').map((n) => parseInt(n, 10));
  41603. let a = x & 1, b = y & 1, c = z & 1;
  41604. let parentName =
  41605. (d - 1) + '-' + (x >> 1) + '-' + (y >> 1) + '-' + (z >> 1);
  41606. let parentNode = nodes[parentName];
  41607. if (!parentNode) return;
  41608. parentNode.hasChildren = true;
  41609. let key = parentNode.key.step(a, b, c);
  41610. let node = new Potree.PointCloudEptGeometryNode(
  41611. this.ept,
  41612. key.b,
  41613. key.d,
  41614. key.x,
  41615. key.y,
  41616. key.z);
  41617. node.level = d;
  41618. node.numPoints = hier[v];
  41619. parentNode.addChild(node);
  41620. nodes[key.name()] = node;
  41621. });
  41622. }
  41623. doneLoading(bufferGeometry, tightBoundingBox, np, mean) {
  41624. bufferGeometry.boundingBox = this.boundingBox;
  41625. this.geometry = bufferGeometry;
  41626. this.tightBoundingBox = tightBoundingBox;
  41627. this.numPoints = np;
  41628. this.mean = mean;
  41629. this.loaded = true;
  41630. this.loading = false;
  41631. --Potree.numNodesLoading;
  41632. }
  41633. toPotreeName(d, x, y, z) {
  41634. var name = 'r';
  41635. for (var i = 0; i < d; ++i) {
  41636. var shift = d - i - 1;
  41637. var mask = 1 << shift;
  41638. var step = 0;
  41639. if (x & mask) step += 4;
  41640. if (y & mask) step += 2;
  41641. if (z & mask) step += 1;
  41642. name += step;
  41643. }
  41644. return name;
  41645. }
  41646. dispose() {
  41647. if (this.geometry && this.parent != null) {
  41648. this.geometry.dispose();
  41649. this.geometry = null;
  41650. this.loaded = false;
  41651. // this.dispatchEvent( { type: 'dispose' } );
  41652. for (let i = 0; i < this.oneTimeDisposeHandlers.length; i++) {
  41653. let handler = this.oneTimeDisposeHandlers[i];
  41654. handler();
  41655. }
  41656. this.oneTimeDisposeHandlers = [];
  41657. }
  41658. }
  41659. }
  41660. PointCloudEptGeometryNode.IDCount = 0;
  41661. class PointCloudOctreeGeometry extends EventDispatcher{
  41662. constructor(){
  41663. super();
  41664. this.url = null;
  41665. this.octreeDir = null;
  41666. this.spacing = 0;
  41667. this.boundingBox = null;
  41668. this.root = null;
  41669. this.nodes = null;
  41670. this.pointAttributes = null;
  41671. this.hierarchyStepSize = -1;
  41672. this.loader = null;
  41673. }
  41674. }
  41675. class PointCloudOctreeGeometryNode extends PointCloudTreeNode{
  41676. constructor(name, pcoGeometry, boundingBox){
  41677. super();
  41678. this.id = PointCloudOctreeGeometryNode.IDCount++;
  41679. this.name = name;
  41680. this.index = parseInt(name.charAt(name.length - 1));
  41681. this.pcoGeometry = pcoGeometry;
  41682. this.geometry = null;
  41683. this.boundingBox = boundingBox;
  41684. this.boundingSphere = boundingBox.getBoundingSphere(new Sphere());
  41685. this.children = {};
  41686. this.numPoints = 0;
  41687. this.level = null;
  41688. this.loaded = false;
  41689. this.oneTimeDisposeHandlers = [];
  41690. }
  41691. isGeometryNode(){
  41692. return true;
  41693. }
  41694. getLevel(){
  41695. return this.level;
  41696. }
  41697. isTreeNode(){
  41698. return false;
  41699. }
  41700. isLoaded(){
  41701. return this.loaded;
  41702. }
  41703. getBoundingSphere(){
  41704. return this.boundingSphere;
  41705. }
  41706. getBoundingBox(){
  41707. return this.boundingBox;
  41708. }
  41709. getChildren(){
  41710. let children = [];
  41711. for (let i = 0; i < 8; i++) {
  41712. if (this.children[i]) {
  41713. children.push(this.children[i]);
  41714. }
  41715. }
  41716. return children;
  41717. }
  41718. getBoundingBox(){
  41719. return this.boundingBox;
  41720. }
  41721. getURL(){
  41722. let url = '';
  41723. let version = this.pcoGeometry.loader.version;
  41724. if (version.equalOrHigher('1.5')) {
  41725. url = this.pcoGeometry.octreeDir + '/' + this.getHierarchyPath() + '/' + this.name;
  41726. } else if (version.equalOrHigher('1.4')) {
  41727. url = this.pcoGeometry.octreeDir + '/' + this.name;
  41728. } else if (version.upTo('1.3')) {
  41729. url = this.pcoGeometry.octreeDir + '/' + this.name;
  41730. }
  41731. return url;
  41732. }
  41733. getHierarchyPath(){
  41734. let path = 'r/';
  41735. let hierarchyStepSize = this.pcoGeometry.hierarchyStepSize;
  41736. let indices = this.name.substr(1);
  41737. let numParts = Math.floor(indices.length / hierarchyStepSize);
  41738. for (let i = 0; i < numParts; i++) {
  41739. path += indices.substr(i * hierarchyStepSize, hierarchyStepSize) + '/';
  41740. }
  41741. path = path.slice(0, -1);
  41742. return path;
  41743. }
  41744. addChild(child) {
  41745. this.children[child.index] = child;
  41746. child.parent = this;
  41747. }
  41748. load(){
  41749. if (this.loading === true || this.loaded === true || Potree.numNodesLoading >= Potree.maxNodesLoading) {
  41750. return;
  41751. }
  41752. this.loading = true;
  41753. Potree.numNodesLoading++;
  41754. if (this.pcoGeometry.loader.version.equalOrHigher('1.5')) {
  41755. if ((this.level % this.pcoGeometry.hierarchyStepSize) === 0 && this.hasChildren) {
  41756. this.loadHierachyThenPoints();
  41757. } else {
  41758. this.loadPoints();
  41759. }
  41760. } else {
  41761. this.loadPoints();
  41762. }
  41763. }
  41764. loadPoints(){
  41765. this.pcoGeometry.loader.load(this);
  41766. }
  41767. loadHierachyThenPoints(pointcloud){
  41768. let node = this;
  41769. // load hierarchy
  41770. let callback = function (node, hbuffer) {
  41771. let tStart = performance.now();
  41772. let view = new DataView(hbuffer);
  41773. let stack = [];
  41774. let children = view.getUint8(0);
  41775. let numPoints = view.getUint32(1, true);
  41776. node.numPoints = numPoints;
  41777. stack.push({children: children, numPoints: numPoints, name: node.name});
  41778. let decoded = [];
  41779. let offset = 5;
  41780. while (stack.length > 0) {
  41781. let snode = stack.shift();
  41782. let mask = 1;
  41783. for (let i = 0; i < 8; i++) {
  41784. if ((snode.children & mask) !== 0) {
  41785. let childName = snode.name + i;
  41786. let childChildren = view.getUint8(offset);
  41787. let childNumPoints = view.getUint32(offset + 1, true);
  41788. stack.push({children: childChildren, numPoints: childNumPoints, name: childName});
  41789. decoded.push({children: childChildren, numPoints: childNumPoints, name: childName});
  41790. offset += 5;
  41791. }
  41792. mask = mask * 2;
  41793. }
  41794. if (offset === hbuffer.byteLength) {
  41795. break;
  41796. }
  41797. }
  41798. // console.log(decoded);
  41799. let nodes = {};
  41800. nodes[node.name] = node;
  41801. let pco = node.pcoGeometry;
  41802. for (let i = 0; i < decoded.length; i++) {
  41803. let name = decoded[i].name;
  41804. let decodedNumPoints = decoded[i].numPoints;
  41805. let index = parseInt(name.charAt(name.length - 1));
  41806. let parentName = name.substring(0, name.length - 1);
  41807. let parentNode = nodes[parentName];
  41808. let level = name.length - 1;
  41809. pco.dispatchEvent({type:'updateNodeMaxLevel',level});//add
  41810. let boundingBox = Utils.createChildAABB(parentNode.boundingBox, index);
  41811. let currentNode = new PointCloudOctreeGeometryNode(name, pco, boundingBox);
  41812. currentNode.level = level;
  41813. currentNode.numPoints = decodedNumPoints;
  41814. currentNode.hasChildren = decoded[i].children > 0;
  41815. currentNode.spacing = pco.spacing / Math.pow(2, level);
  41816. parentNode.addChild(currentNode);
  41817. nodes[name] = currentNode;
  41818. }
  41819. let duration = performance.now() - tStart;
  41820. if(duration > 5){
  41821. /* let msg = `duration: ${duration}ms, numNodes: ${decoded.length}`;
  41822. console.log(msg); */
  41823. }
  41824. node.loadPoints();
  41825. };
  41826. if ((node.level % node.pcoGeometry.hierarchyStepSize) === 0) {
  41827. // let hurl = node.pcoGeometry.octreeDir + "/../hierarchy/" + node.name + ".hrc";
  41828. let hurl = node.pcoGeometry.octreeDir + '/' + node.getHierarchyPath() + '/' + node.name + '.hrc';
  41829. hurl += '?m='+node.pcoGeometry.timeStamp; //add
  41830. let xhr = XHRFactory.createXMLHttpRequest();
  41831. xhr.open('GET', hurl, true);
  41832. xhr.responseType = 'arraybuffer';
  41833. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  41834. xhr.onreadystatechange = () => {
  41835. if (xhr.readyState === 4) {
  41836. if (xhr.status === 200 || xhr.status === 0) {
  41837. let hbuffer = xhr.response;
  41838. callback(node, hbuffer);
  41839. } else {
  41840. console.log('Failed to load file! HTTP status: ' + xhr.status + ', file: ' + hurl);
  41841. Potree.numNodesLoading--;
  41842. }
  41843. }
  41844. };
  41845. try {
  41846. xhr.send(null);
  41847. } catch (e) {
  41848. console.log('fehler beim laden der punktwolke: ' + e);
  41849. }
  41850. }
  41851. }
  41852. getNumPoints(){
  41853. return this.numPoints;
  41854. }
  41855. dispose(){
  41856. if (this.geometry && this.parent != null) {
  41857. this.geometry.dispose();
  41858. this.geometry = null;
  41859. this.loaded = false;
  41860. this.dispatchEvent( { type: 'dispose' } );
  41861. for (let i = 0; i < this.oneTimeDisposeHandlers.length; i++) {
  41862. let handler = this.oneTimeDisposeHandlers[i];
  41863. handler();
  41864. }
  41865. this.oneTimeDisposeHandlers = [];
  41866. }
  41867. }
  41868. traverse(t, e){//add from navvis 25.js
  41869. void 0 === e && (e = !0);
  41870. for (var n, i = e ? [this] : []; void 0 !== (n = i.pop()); ) {
  41871. t(n);
  41872. for (var o = 0, r = n.children; o < r.length; o++) {
  41873. var a = r[o];
  41874. null !== a && i.push(a);
  41875. }
  41876. }
  41877. }
  41878. }
  41879. PointCloudOctreeGeometryNode.IDCount = 0;
  41880. // -------------------------------------------
  41881. // to get a ready to use gradient array from a chroma.js gradient:
  41882. // http://gka.github.io/chroma.js/
  41883. // -------------------------------------------
  41884. //
  41885. // let stops = [];
  41886. // for(let i = 0; i <= 10; i++){
  41887. // let range = chroma.scale(['yellow', 'navy']).mode('lch').domain([10,0])(i)._rgb
  41888. // .slice(0, 3)
  41889. // .map(v => (v / 255).toFixed(4))
  41890. // .join(", ");
  41891. //
  41892. // let line = `[${i / 10}, new THREE.Color(${range})],`;
  41893. //
  41894. // stops.push(line);
  41895. // }
  41896. // stops.join("\n");
  41897. //
  41898. //
  41899. //
  41900. // -------------------------------------------
  41901. // to get a ready to use gradient array from matplotlib:
  41902. // -------------------------------------------
  41903. // import matplotlib.pyplot as plt
  41904. // import matplotlib.colors as colors
  41905. //
  41906. // norm = colors.Normalize(vmin=0,vmax=1)
  41907. // cmap = plt.cm.viridis
  41908. //
  41909. // for i in range(0,11):
  41910. // u = i / 10
  41911. // rgb = cmap(norm(u))[0:3]
  41912. // rgb = ["{0:.3f}".format(v) for v in rgb]
  41913. // rgb = "[" + str(u) + ", new THREE.Color(" + ", ".join(rgb) + ")],"
  41914. // print(rgb)
  41915. let Gradients = {
  41916. // From chroma spectral http://gka.github.io/chroma.js/
  41917. SPECTRAL: [
  41918. [0, new Color(0.3686, 0.3098, 0.6353)],
  41919. [0.1, new Color(0.1961, 0.5333, 0.7412)],
  41920. [0.2, new Color(0.4000, 0.7608, 0.6471)],
  41921. [0.3, new Color(0.6706, 0.8667, 0.6431)],
  41922. [0.4, new Color(0.9020, 0.9608, 0.5961)],
  41923. [0.5, new Color(1.0000, 1.0000, 0.7490)],
  41924. [0.6, new Color(0.9961, 0.8784, 0.5451)],
  41925. [0.7, new Color(0.9922, 0.6824, 0.3804)],
  41926. [0.8, new Color(0.9569, 0.4275, 0.2627)],
  41927. [0.9, new Color(0.8353, 0.2431, 0.3098)],
  41928. [1, new Color(0.6196, 0.0039, 0.2588)]
  41929. ],
  41930. PLASMA: [
  41931. [0.0, new Color(0.241, 0.015, 0.610)],
  41932. [0.1, new Color(0.387, 0.001, 0.654)],
  41933. [0.2, new Color(0.524, 0.025, 0.653)],
  41934. [0.3, new Color(0.651, 0.125, 0.596)],
  41935. [0.4, new Color(0.752, 0.227, 0.513)],
  41936. [0.5, new Color(0.837, 0.329, 0.431)],
  41937. [0.6, new Color(0.907, 0.435, 0.353)],
  41938. [0.7, new Color(0.963, 0.554, 0.272)],
  41939. [0.8, new Color(0.992, 0.681, 0.195)],
  41940. [0.9, new Color(0.987, 0.822, 0.144)],
  41941. [1.0, new Color(0.940, 0.975, 0.131)]
  41942. ],
  41943. YELLOW_GREEN: [
  41944. [0, new Color(0.1647, 0.2824, 0.3451)],
  41945. [0.1, new Color(0.1338, 0.3555, 0.4227)],
  41946. [0.2, new Color(0.0610, 0.4319, 0.4864)],
  41947. [0.3, new Color(0.0000, 0.5099, 0.5319)],
  41948. [0.4, new Color(0.0000, 0.5881, 0.5569)],
  41949. [0.5, new Color(0.1370, 0.6650, 0.5614)],
  41950. [0.6, new Color(0.2906, 0.7395, 0.5477)],
  41951. [0.7, new Color(0.4453, 0.8099, 0.5201)],
  41952. [0.8, new Color(0.6102, 0.8748, 0.4850)],
  41953. [0.9, new Color(0.7883, 0.9323, 0.4514)],
  41954. [1, new Color(0.9804, 0.9804, 0.4314)]
  41955. ],
  41956. VIRIDIS: [
  41957. [0.0, new Color(0.267, 0.005, 0.329)],
  41958. [0.1, new Color(0.283, 0.141, 0.458)],
  41959. [0.2, new Color(0.254, 0.265, 0.530)],
  41960. [0.3, new Color(0.207, 0.372, 0.553)],
  41961. [0.4, new Color(0.164, 0.471, 0.558)],
  41962. [0.5, new Color(0.128, 0.567, 0.551)],
  41963. [0.6, new Color(0.135, 0.659, 0.518)],
  41964. [0.7, new Color(0.267, 0.749, 0.441)],
  41965. [0.8, new Color(0.478, 0.821, 0.318)],
  41966. [0.9, new Color(0.741, 0.873, 0.150)],
  41967. [1.0, new Color(0.993, 0.906, 0.144)]
  41968. ],
  41969. INFERNO: [
  41970. [0.0, new Color(0.077, 0.042, 0.206)],
  41971. [0.1, new Color(0.225, 0.036, 0.388)],
  41972. [0.2, new Color(0.373, 0.074, 0.432)],
  41973. [0.3, new Color(0.522, 0.128, 0.420)],
  41974. [0.4, new Color(0.665, 0.182, 0.370)],
  41975. [0.5, new Color(0.797, 0.255, 0.287)],
  41976. [0.6, new Color(0.902, 0.364, 0.184)],
  41977. [0.7, new Color(0.969, 0.516, 0.063)],
  41978. [0.8, new Color(0.988, 0.683, 0.072)],
  41979. [0.9, new Color(0.961, 0.859, 0.298)],
  41980. [1.0, new Color(0.988, 0.998, 0.645)]
  41981. ],
  41982. GRAYSCALE: [
  41983. [0, new Color(0, 0, 0)],
  41984. [1, new Color(1, 1, 1)]
  41985. ],
  41986. // 16 samples of the TURBU color scheme
  41987. // values taken from: https://gist.github.com/mikhailov-work/ee72ba4191942acecc03fe6da94fc73f
  41988. // original file licensed under Apache-2.0
  41989. TURBO: [
  41990. [0.00, new Color(0.18995, 0.07176, 0.23217)],
  41991. [0.07, new Color(0.25107, 0.25237, 0.63374)],
  41992. [0.13, new Color(0.27628, 0.42118, 0.89123)],
  41993. [0.20, new Color(0.25862, 0.57958, 0.99876)],
  41994. [0.27, new Color(0.15844, 0.73551, 0.92305)],
  41995. [0.33, new Color(0.09267, 0.86554, 0.7623)],
  41996. [0.40, new Color(0.19659, 0.94901, 0.59466)],
  41997. [0.47, new Color(0.42778, 0.99419, 0.38575)],
  41998. [0.53, new Color(0.64362, 0.98999, 0.23356)],
  41999. [0.60, new Color(0.80473, 0.92452, 0.20459)],
  42000. [0.67, new Color(0.93301, 0.81236, 0.22667)],
  42001. [0.73, new Color(0.99314, 0.67408, 0.20348)],
  42002. [0.80, new Color(0.9836, 0.49291, 0.12849)],
  42003. [0.87, new Color(0.92105, 0.31489, 0.05475)],
  42004. [0.93, new Color(0.81608, 0.18462, 0.01809)],
  42005. [1.00, new Color(0.66449, 0.08436, 0.00424)],
  42006. ],
  42007. RAINBOW: [
  42008. [0, new Color(0.278, 0, 0.714)],
  42009. [1 / 6, new Color(0, 0, 1)],
  42010. [2 / 6, new Color(0, 1, 1)],
  42011. [3 / 6, new Color(0, 1, 0)],
  42012. [4 / 6, new Color(1, 1, 0)],
  42013. [5 / 6, new Color(1, 0.64, 0)],
  42014. [1, new Color(1, 0, 0)]
  42015. ],
  42016. CONTOUR: [
  42017. [0.00, new Color(0, 0, 0)],
  42018. [0.03, new Color(0, 0, 0)],
  42019. [0.04, new Color(1, 1, 1)],
  42020. [1.00, new Color(1, 1, 1)]
  42021. ],
  42022. };
  42023. const ClassificationScheme = {
  42024. DEFAULT: {
  42025. 0: { visible: true, name: 'never classified' , color: [0.5, 0.5, 0.5, 1.0] },
  42026. 1: { visible: true, name: 'unclassified' , color: [0.5, 0.5, 0.5, 1.0] },
  42027. 2: { visible: true, name: 'ground' , color: [0.63, 0.32, 0.18, 1.0] },
  42028. 3: { visible: true, name: 'low vegetation' , color: [0.0, 1.0, 0.0, 1.0] },
  42029. 4: { visible: true, name: 'medium vegetation' , color: [0.0, 0.8, 0.0, 1.0] },
  42030. 5: { visible: true, name: 'high vegetation' , color: [0.0, 0.6, 0.0, 1.0] },
  42031. 6: { visible: true, name: 'building' , color: [1.0, 0.66, 0.0, 1.0] },
  42032. 7: { visible: true, name: 'low point(noise)' , color: [1.0, 0.0, 1.0, 1.0] },
  42033. 8: { visible: true, name: 'key-point' , color: [1.0, 0.0, 0.0, 1.0] },
  42034. 9: { visible: true, name: 'water' , color: [0.0, 0.0, 1.0, 1.0] },
  42035. 12: { visible: true, name: 'overlap' , color: [1.0, 1.0, 0.0, 1.0] },
  42036. DEFAULT: { visible: true, name: 'default' , color: [0.3, 0.6, 0.6, 0.5] },
  42037. }
  42038. };
  42039. Object.defineProperty(ClassificationScheme, 'RANDOM', {
  42040. get: function() {
  42041. let scheme = {};
  42042. for(let i = 0; i <= 255; i++){
  42043. scheme[i] = new Vector4(Math.random(), Math.random(), Math.random());
  42044. }
  42045. scheme["DEFAULT"] = new Vector4(Math.random(), Math.random(), Math.random());
  42046. return scheme;
  42047. }
  42048. });
  42049. //
  42050. // how to calculate the radius of a projected sphere in screen space
  42051. // http://stackoverflow.com/questions/21648630/radius-of-projected-sphere-in-screen-space
  42052. // http://stackoverflow.com/questions/3717226/radius-of-projected-sphere
  42053. //
  42054. class PointCloudMaterial$1 extends RawShaderMaterial {
  42055. constructor (parameters = {}) {
  42056. super();
  42057. this.visibleNodesTexture = Utils.generateDataTexture(2048, 1, new Color(0xffffff));
  42058. this.visibleNodesTexture.minFilter = NearestFilter;
  42059. this.visibleNodesTexture.magFilter = NearestFilter;
  42060. let getValid = (a, b) => {
  42061. if(a !== undefined){
  42062. return a;
  42063. }else {
  42064. return b;
  42065. }
  42066. };
  42067. let pointSize = getValid(parameters.size, 1.0);
  42068. let minSize = getValid(parameters.minSize, 2.0);
  42069. let maxSize = getValid(parameters.maxSize, 1550.0);
  42070. let treeType = getValid(parameters.treeType, TreeType.OCTREE);
  42071. this._pointSizeType = PointSizeType.FIXED;
  42072. this._shape = PointShape.SQUARE;
  42073. this._useClipBox = false;
  42074. this.clipBoxes = [];
  42075. this.clipPolygons = [];
  42076. this._weighted = false;
  42077. this._gradient = Gradients.RAINBOW;//Gradients.SPECTRAL;//海拔贴图种类
  42078. this.gradientTexture = PointCloudMaterial$1.generateGradientTexture(this._gradient);
  42079. this._matcap = "matcap.jpg";
  42080. this.matcapTexture = Potree.PointCloudMaterial.generateMatcapTexture(this._matcap);
  42081. this.lights = false;
  42082. this.fog = false;
  42083. this._treeType = treeType;
  42084. this._useEDL = false;
  42085. this.defines = new Map();
  42086. this.ranges = new Map();
  42087. this._activeAttributeName = null;
  42088. this._defaultIntensityRangeChanged = false;
  42089. this._defaultElevationRangeChanged = false;
  42090. {
  42091. const [width, height] = [256, 1];
  42092. let data = new Uint8Array(width * 4);
  42093. let texture = new DataTexture(data, width, height, RGBAFormat);
  42094. texture.magFilter = NearestFilter;
  42095. texture.needsUpdate = true;
  42096. this.classificationTexture = texture;
  42097. }
  42098. this.attributes = {
  42099. position: { type: 'fv', value: [] },
  42100. color: { type: 'fv', value: [] },
  42101. normal: { type: 'fv', value: [] },
  42102. intensity: { type: 'f', value: [] },
  42103. classification: { type: 'f', value: [] },
  42104. returnNumber: { type: 'f', value: [] },
  42105. numberOfReturns: { type: 'f', value: [] },
  42106. pointSourceID: { type: 'f', value: [] },
  42107. indices: { type: 'fv', value: [] }
  42108. };
  42109. this.uniforms = {
  42110. level: { type: "f", value: 0.0 },
  42111. vnStart: { type: "f", value: 0.0 },
  42112. spacing: { type: "f", value: 1.0 },
  42113. blendHardness: { type: "f", value: 2.0 },
  42114. blendDepthSupplement: { type: "f", value: 0.0 },
  42115. fov: { type: "f", value: 1.0 },
  42116. /* screenWidth: { type: "f", value: 1.0 },
  42117. screenHeight: { type: "f", value: 1.0 }, */
  42118. resolution: { type: 'v2', value: new Vector2$1() },
  42119. near: { type: "f", value: 0.1 },
  42120. far: { type: "f", value: 1.0 },
  42121. uColor: { type: "c", value: new Color( 0xffffff ) },
  42122. uOpacity: { type: "f", value: 1.0 },
  42123. size: { type: "f", value: pointSize },
  42124. minSize: { type: "f", value: minSize },
  42125. maxSize: { type: "f", value: maxSize },
  42126. octreeSize: { type: "f", value: 0 },
  42127. bbSize: { type: "fv", value: [0, 0, 0] },
  42128. elevationRange: { type: "2fv", value: [0, 0] },
  42129. clipBoxCount: { type: "f", value: 0 },
  42130. //clipSphereCount: { type: "f", value: 0 },
  42131. clipPolygonCount: { type: "i", value: 0 },
  42132. clipBoxes: { type: "Matrix4fv", value: [] },
  42133. //clipSpheres: { type: "Matrix4fv", value: [] },
  42134. clipPolygons: { type: "3fv", value: [] },
  42135. clipPolygonVCount: { type: "iv", value: [] },
  42136. clipPolygonVP: { type: "Matrix4fv", value: [] },
  42137. visibleNodes: { type: "t", value: this.visibleNodesTexture },
  42138. pcIndex: { type: "f", value: 0 },
  42139. gradient: { type: "t", value: this.gradientTexture },
  42140. classificationLUT: { type: "t", value: this.classificationTexture },
  42141. uHQDepthMap: { type: "t", value: null },
  42142. toModel: { type: "Matrix4f", value: [] },
  42143. diffuse: { type: "fv", value: [1, 1, 1] },
  42144. transition: { type: "f", value: 0.5 },
  42145. intensityRange: { type: "fv", value: [Infinity, -Infinity] },
  42146. intensity_gbc: { type: "fv", value: [1, 0, 0]},
  42147. uRGB_gbc: { type: "fv", value: [1, 0, 0]},
  42148. // intensityGamma: { type: "f", value: 1 },
  42149. // intensityContrast: { type: "f", value: 0 },
  42150. // intensityBrightness:{ type: "f", value: 0 },
  42151. // rgbGamma: { type: "f", value: 1 },
  42152. // rgbContrast: { type: "f", value: 0 },
  42153. // rgbBrightness: { type: "f", value: 0 },
  42154. wRGB: { type: "f", value: 1 },
  42155. wIntensity: { type: "f", value: 0 },
  42156. wElevation: { type: "f", value: 0 },
  42157. wClassification: { type: "f", value: 0 },
  42158. wReturnNumber: { type: "f", value: 0 },
  42159. wSourceID: { type: "f", value: 0 },
  42160. useOrthographicCamera: { type: "b", value: false },
  42161. elevationGradientRepat: { type: "i", value: ElevationGradientRepeat.CLAMP },
  42162. clipTask: { type: "i", value: 1 },
  42163. clipMethod: { type: "i", value: 1 },
  42164. uShadowColor: { type: "3fv", value: [0, 0, 0] },
  42165. uExtraScale: { type: "f", value: 1},
  42166. uExtraOffset: { type: "f", value: 0},
  42167. uExtraRange: { type: "2fv", value: [0, 1] },
  42168. uExtraGammaBrightContr: { type: "3fv", value: [1, 0, 0] },
  42169. uFilterReturnNumberRange: { type: "fv", value: [0, 7]},
  42170. uFilterNumberOfReturnsRange: { type: "fv", value: [0, 7]},
  42171. uFilterGPSTimeClipRange: { type: "fv", value: [0, 7]},
  42172. uFilterPointSourceIDClipRange: { type: "fv", value: [0, 65535]},
  42173. matcapTextureUniform: { type: "t", value: this.matcapTexture },
  42174. backfaceCulling: { type: "b", value: false },
  42175. ////////////////add
  42176. //usePanoMap:{ type: "i", value: 0 },
  42177. progress: {
  42178. type: "f",
  42179. value: 0
  42180. },
  42181. easeInOutRatio:{
  42182. type: "f",
  42183. value: 0.3
  42184. },
  42185. pano0Map: {
  42186. type: "t",
  42187. value: null
  42188. },
  42189. pano0Position: {
  42190. type: "v3",
  42191. value: new Vector3
  42192. },
  42193. pano0Matrix: {
  42194. type: "m4",
  42195. value: new Matrix4
  42196. },
  42197. pano1Map: {
  42198. type: "t",
  42199. value: null
  42200. },
  42201. pano1Position: {
  42202. type: "v3",
  42203. value: new Vector3
  42204. },
  42205. pano1Matrix: {
  42206. type: "m4",
  42207. value: new Matrix4
  42208. },
  42209. };
  42210. this.classification = ClassificationScheme.DEFAULT;
  42211. this.defaultAttributeValues.normal = [0, 0, 0];
  42212. this.defaultAttributeValues.classification = [0, 0, 0];
  42213. this.defaultAttributeValues.indices = [0, 0, 0, 0];
  42214. this.vertexShader = Shaders['pointcloud.vs'];
  42215. this.fragmentShader = Shaders['pointcloud.fs'];
  42216. this.vertexColors = VertexColors;
  42217. this.updateShaderSource();
  42218. }
  42219. setDefine(key, value){
  42220. if(value !== undefined && value !== null){
  42221. if(this.defines.get(key) !== value){
  42222. this.defines.set(key, value);
  42223. this.updateShaderSource();
  42224. }
  42225. }else {
  42226. this.removeDefine(key);
  42227. }
  42228. }
  42229. removeDefine(key){
  42230. this.defines.delete(key);
  42231. }
  42232. updateShaderSource () {
  42233. let vs = Shaders['pointcloud.vs'];
  42234. let fs = Shaders['pointcloud.fs'];
  42235. let definesString = this.getDefines();
  42236. let vsVersionIndex = vs.indexOf("#version ");
  42237. let fsVersionIndex = fs.indexOf("#version ");
  42238. if(vsVersionIndex >= 0){
  42239. vs = vs.replace(/(#version .*)/, `$1\n${definesString}`);
  42240. }else {
  42241. vs = `${definesString}\n${vs}`;
  42242. }
  42243. if(fsVersionIndex >= 0){
  42244. fs = fs.replace(/(#version .*)/, `$1\n${definesString}`);
  42245. }else {
  42246. fs = `${definesString}\n${fs}`;
  42247. }
  42248. this.vertexShader = vs;
  42249. this.fragmentShader = fs;
  42250. if (this.opacity === 1.0 && !this.useFilterByNormal) {//add useFilterByNormal
  42251. this.blending = NoBlending;
  42252. this.transparent = false;
  42253. this.depthTest = true;
  42254. this.depthWrite = true;
  42255. this.depthFunc = LessEqualDepth;
  42256. } else if ( (this.opacity < 1.0 ||this.useFilterByNormal) && !this.useEDL) {//add useFilterByNormal
  42257. this.blending = AdditiveBlending;
  42258. this.transparent = true;
  42259. this.depthTest = false;
  42260. this.depthWrite = true;
  42261. this.depthFunc = AlwaysDepth;
  42262. }
  42263. if (this.weighted) {
  42264. this.blending = AdditiveBlending;
  42265. this.transparent = true;
  42266. this.depthTest = true;
  42267. this.depthWrite = false;
  42268. }
  42269. this.needsUpdate = true;
  42270. }
  42271. getDefines () {
  42272. let defines = [];
  42273. if (this.pointSizeType === PointSizeType.FIXED) {
  42274. defines.push('#define fixed_point_size');
  42275. } else if (this.pointSizeType === PointSizeType.ATTENUATED) {
  42276. defines.push('#define attenuated_point_size');
  42277. } else if (this.pointSizeType === PointSizeType.ADAPTIVE) {
  42278. defines.push('#define adaptive_point_size');
  42279. }
  42280. if(!Features.EXT_DEPTH.isSupported() && this.shape === PointShape.PARABOLOID){
  42281. this.shape = PointShape.SQUARE ;//强行替换
  42282. }
  42283. if (this.shape === PointShape.SQUARE) {
  42284. defines.push('#define square_point_shape');
  42285. } else if (this.shape === PointShape.CIRCLE) {
  42286. defines.push('#define circle_point_shape');
  42287. } else if (this.shape === PointShape.PARABOLOID) {
  42288. defines.push('#define paraboloid_point_shape');
  42289. }
  42290. //console.log('this.shape PARABOLOID', this.shape, this.shape === PointShape.PARABOLOID)
  42291. if (this._useEDL || this.fakeEDL) {
  42292. defines.push('#define use_edl');
  42293. }
  42294. if(this.activeAttributeName){
  42295. let attributeName = this.activeAttributeName.replace(/[^a-zA-Z0-9]/g, '_');
  42296. defines.push(`#define color_type_${attributeName}`);
  42297. }
  42298. if(this._treeType === TreeType.OCTREE){
  42299. defines.push('#define tree_type_octree');
  42300. }else if(this._treeType === TreeType.KDTREE){
  42301. defines.push('#define tree_type_kdtree');
  42302. }
  42303. if (this.weighted) {
  42304. defines.push('#define weighted_splats');
  42305. }
  42306. for(let [key, value] of this.defines){
  42307. defines.push(value);
  42308. }
  42309. return defines.join("\n");
  42310. }
  42311. setClipBoxes (clipBoxes) {
  42312. if (!clipBoxes) {
  42313. return;
  42314. }
  42315. let doUpdate = (this.clipBoxes.length !== clipBoxes.length) && (clipBoxes.length === 0 || this.clipBoxes.length === 0);
  42316. this.uniforms.clipBoxCount.value = this.clipBoxes.length;
  42317. this.clipBoxes = clipBoxes;
  42318. if (doUpdate) {
  42319. this.updateShaderSource();
  42320. }
  42321. this.uniforms.clipBoxes.value = new Float32Array(this.clipBoxes.length * 16);
  42322. for (let i = 0; i < this.clipBoxes.length; i++) {
  42323. let box = clipBoxes[i];
  42324. this.uniforms.clipBoxes.value.set(box.inverse.elements, 16 * i);
  42325. }
  42326. for (let i = 0; i < this.uniforms.clipBoxes.value.length; i++) {
  42327. if (Number.isNaN(this.uniforms.clipBoxes.value[i])) {
  42328. this.uniforms.clipBoxes.value[i] = Infinity;
  42329. }
  42330. }
  42331. }
  42332. setClipPolygons(clipPolygons, maxPolygonVertices) {
  42333. if(!clipPolygons){
  42334. return;
  42335. }
  42336. this.clipPolygons = clipPolygons;
  42337. let doUpdate = (this.clipPolygons.length !== clipPolygons.length);
  42338. if(doUpdate){
  42339. this.updateShaderSource();
  42340. }
  42341. }
  42342. get gradient(){
  42343. return this._gradient;
  42344. }
  42345. set gradient (value) {//海拔贴图
  42346. if (this._gradient !== value) {
  42347. this._gradient = value;
  42348. this.gradientTexture = PointCloudMaterial$1.generateGradientTexture(this._gradient);
  42349. this.uniforms.gradient.value = this.gradientTexture;
  42350. }
  42351. }
  42352. get matcap(){
  42353. return this._matcap;
  42354. }
  42355. set matcap (value) {
  42356. if (this._matcap !== value) {
  42357. this._matcap = value;
  42358. this.matcapTexture = Potree.PointCloudMaterial.generateMatcapTexture(this._matcap);
  42359. this.uniforms.matcapTextureUniform.value = this.matcapTexture;
  42360. }
  42361. }
  42362. get useOrthographicCamera() {
  42363. return this.uniforms.useOrthographicCamera.value;
  42364. }
  42365. set useOrthographicCamera(value) {
  42366. if(this.uniforms.useOrthographicCamera.value !== value){
  42367. this.uniforms.useOrthographicCamera.value = value;
  42368. }
  42369. }
  42370. get backfaceCulling() {
  42371. return this.uniforms.backfaceCulling.value;
  42372. }
  42373. set backfaceCulling(value) {
  42374. if(this.uniforms.backfaceCulling.value !== value){
  42375. this.uniforms.backfaceCulling.value = value;
  42376. this.dispatchEvent({type: 'backface_changed', target: this});
  42377. }
  42378. }
  42379. recomputeClassification () {
  42380. const classification = this.classification;
  42381. const data = this.classificationTexture.image.data;
  42382. let width = 256;
  42383. const black = [1, 1, 1, 1];
  42384. let valuesChanged = false;
  42385. for (let i = 0; i < width; i++) {
  42386. let color;
  42387. let visible = true;
  42388. if (classification[i]) {
  42389. color = classification[i].color;
  42390. visible = classification[i].visible;
  42391. } else if (classification[i % 32]) {
  42392. color = classification[i % 32].color;
  42393. visible = classification[i % 32].visible;
  42394. } else if(classification.DEFAULT) {
  42395. color = classification.DEFAULT.color;
  42396. visible = classification.DEFAULT.visible;
  42397. }else {
  42398. color = black;
  42399. }
  42400. const r = parseInt(255 * color[0]);
  42401. const g = parseInt(255 * color[1]);
  42402. const b = parseInt(255 * color[2]);
  42403. const a = visible ? parseInt(255 * color[3]) : 0;
  42404. if(data[4 * i + 0] !== r){
  42405. data[4 * i + 0] = r;
  42406. valuesChanged = true;
  42407. }
  42408. if(data[4 * i + 1] !== g){
  42409. data[4 * i + 1] = g;
  42410. valuesChanged = true;
  42411. }
  42412. if(data[4 * i + 2] !== b){
  42413. data[4 * i + 2] = b;
  42414. valuesChanged = true;
  42415. }
  42416. if(data[4 * i + 3] !== a){
  42417. data[4 * i + 3] = a;
  42418. valuesChanged = true;
  42419. }
  42420. }
  42421. if(valuesChanged){
  42422. this.classificationTexture.needsUpdate = true;
  42423. this.dispatchEvent({
  42424. type: 'material_property_changed',
  42425. target: this
  42426. });
  42427. }
  42428. }
  42429. get spacing () {
  42430. return this.uniforms.spacing.value;
  42431. }
  42432. set spacing (value) {
  42433. if (this.uniforms.spacing.value !== value) { // 即 uOctreeSpacing 来自cloud.js里
  42434. this.uniforms.spacing.value = value;
  42435. }
  42436. }
  42437. get useClipBox () {
  42438. return this._useClipBox;
  42439. }
  42440. set useClipBox (value) {
  42441. if (this._useClipBox !== value) {
  42442. this._useClipBox = value;
  42443. this.updateShaderSource();
  42444. }
  42445. }
  42446. get clipTask(){
  42447. return this.uniforms.clipTask.value;
  42448. }
  42449. set clipTask(mode){
  42450. this.uniforms.clipTask.value = mode;
  42451. }
  42452. get elevationGradientRepat(){
  42453. return this.uniforms.elevationGradientRepat.value;
  42454. }
  42455. set elevationGradientRepat(mode){
  42456. this.uniforms.elevationGradientRepat.value = mode;
  42457. }
  42458. get clipMethod(){
  42459. return this.uniforms.clipMethod.value;
  42460. }
  42461. set clipMethod(mode){
  42462. this.uniforms.clipMethod.value = mode;
  42463. }
  42464. get weighted(){
  42465. return this._weighted;
  42466. }
  42467. set weighted (value) {
  42468. if (this._weighted !== value) {
  42469. this._weighted = value;
  42470. this.updateShaderSource();
  42471. }
  42472. }
  42473. get fov () {
  42474. return this.uniforms.fov.value;
  42475. }
  42476. set fov (value) {
  42477. if (this.uniforms.fov.value !== value) {
  42478. this.uniforms.fov.value = value;
  42479. // this.updateShaderSource();
  42480. }
  42481. }
  42482. /* get screenWidth () {
  42483. return this.uniforms.screenWidth.value;
  42484. }
  42485. set screenWidth (value) {
  42486. if (this.uniforms.screenWidth.value !== value) {
  42487. this.uniforms.screenWidth.value = value;
  42488. // this.updateShaderSource();
  42489. }
  42490. }
  42491. get screenHeight () {
  42492. return this.uniforms.screenHeight.value;
  42493. }
  42494. set screenHeight (value) {
  42495. if (this.uniforms.screenHeight.value !== value) {
  42496. this.uniforms.screenHeight.value = value;
  42497. // this.updateShaderSource();
  42498. }
  42499. }*/
  42500. //add--------------
  42501. get resolution(){
  42502. return this.uniforms.resolution.value
  42503. }
  42504. set resolution(value){
  42505. this.uniforms.resolution.value.copy(value);
  42506. }
  42507. //--------------
  42508. get near () {
  42509. return this.uniforms.near.value;
  42510. }
  42511. set near (value) {
  42512. if (this.uniforms.near.value !== value) {
  42513. this.uniforms.near.value = value;
  42514. }
  42515. }
  42516. get far () {
  42517. return this.uniforms.far.value;
  42518. }
  42519. set far (value) {
  42520. if (this.uniforms.far.value !== value) {
  42521. this.uniforms.far.value = value;
  42522. }
  42523. }
  42524. get opacity(){
  42525. return this.uniforms.uOpacity.value;
  42526. }
  42527. set opacity (value) {
  42528. if (this.uniforms && this.uniforms.uOpacity) {
  42529. if (this.uniforms.uOpacity.value !== value) {
  42530. this.uniforms.uOpacity.value = value;
  42531. this.updateShaderSource();
  42532. this.dispatchEvent({
  42533. type: 'opacity_changed',
  42534. target: this
  42535. });
  42536. this.dispatchEvent({
  42537. type: 'material_property_changed',
  42538. target: this
  42539. });
  42540. }
  42541. }
  42542. }
  42543. get activeAttributeName(){
  42544. return this._activeAttributeName;
  42545. }
  42546. set activeAttributeName(value){
  42547. if (this._activeAttributeName !== value) {
  42548. this._activeAttributeName = value;
  42549. this.updateShaderSource();
  42550. this.dispatchEvent({
  42551. type: 'active_attribute_changed',
  42552. target: this
  42553. });
  42554. this.dispatchEvent({
  42555. type: 'material_property_changed',
  42556. target: this
  42557. });
  42558. }
  42559. }
  42560. get pointSizeType () {
  42561. return this._pointSizeType;
  42562. }
  42563. set pointSizeType (value) {
  42564. if(typeof value == 'string' )value = PointSizeType[value];
  42565. if (this._pointSizeType !== value) {
  42566. this._pointSizeType = value;
  42567. this.updateShaderSource(); //这句表明这个属性频繁更改会卡顿
  42568. this.dispatchEvent({
  42569. type: 'point_size_type_changed',
  42570. target: this
  42571. });
  42572. this.dispatchEvent({
  42573. type: 'material_property_changed',
  42574. target: this
  42575. });
  42576. }
  42577. }
  42578. get useEDL(){
  42579. return this._useEDL;
  42580. }
  42581. set useEDL (value) {
  42582. if (this._useEDL !== value) {
  42583. this._useEDL = value;
  42584. this.updateShaderSource();
  42585. }
  42586. }
  42587. get fakeEDL(){
  42588. return this._fakeEDL;
  42589. }
  42590. set fakeEDL (value) {//add
  42591. if (this._fakeEDL !== value) {
  42592. this._fakeEDL = value;
  42593. this.updateShaderSource();
  42594. }
  42595. }
  42596. get color () {
  42597. return this.uniforms.uColor.value;
  42598. }
  42599. set color (value) {//改
  42600. if(value == this.color_)return
  42601. let color = value;
  42602. //if (!this.uniforms.uColor.value.equals(value)) {
  42603. if(typeof value == 'string') {
  42604. var colorArr = Potree.config.colors[value];
  42605. if(!colorArr){
  42606. //console.warn('没找到该颜色值'+ value)
  42607. }else {
  42608. color = new Color().fromArray(colorArr).multiplyScalar(1/255);
  42609. }
  42610. }
  42611. this.uniforms.uColor.value.set(color);
  42612. //this.uniforms.uColor.value.copy(value);
  42613. this.dispatchEvent({
  42614. type: 'color_changed',
  42615. target: this
  42616. });
  42617. this.dispatchEvent({
  42618. type: 'material_property_changed',
  42619. target: this
  42620. });
  42621. //}
  42622. this.color_ = value; //记录下str
  42623. }
  42624. get shape () {
  42625. return this._shape;
  42626. }
  42627. set shape (value) {
  42628. if (this._shape !== value) {
  42629. this._shape = value;
  42630. this.updateShaderSource();
  42631. this.dispatchEvent({type: 'point_shape_changed', target: this});
  42632. this.dispatchEvent({
  42633. type: 'material_property_changed',
  42634. target: this
  42635. });
  42636. }
  42637. }
  42638. get treeType () {
  42639. return this._treeType;
  42640. }
  42641. set treeType (value) {
  42642. if (this._treeType !== value) {
  42643. this._treeType = value;
  42644. this.updateShaderSource();
  42645. }
  42646. }
  42647. get bbSize () {
  42648. return this.uniforms.bbSize.value;
  42649. }
  42650. set bbSize (value) {
  42651. this.uniforms.bbSize.value = value;
  42652. }
  42653. get size () {
  42654. return this.uniforms.size.value;
  42655. }
  42656. set size (value) {
  42657. if (this.uniforms.size.value !== value) {
  42658. this.uniforms.size.value = value;
  42659. this.dispatchEvent({
  42660. type: 'point_size_changed',
  42661. target: this
  42662. });
  42663. this.dispatchEvent({
  42664. type: 'material_property_changed',
  42665. target: this
  42666. });
  42667. }
  42668. }
  42669. get minSize(){
  42670. return this.uniforms.minSize.value;
  42671. }
  42672. set minSize(value){
  42673. if (this.uniforms.minSize.value !== value) {
  42674. this.uniforms.minSize.value = value;
  42675. this.dispatchEvent({
  42676. type: 'point_size_changed',
  42677. target: this
  42678. });
  42679. this.dispatchEvent({
  42680. type: 'material_property_changed',
  42681. target: this
  42682. });
  42683. }
  42684. }
  42685. get elevationRange () {
  42686. return this.uniforms.elevationRange.value;
  42687. }
  42688. set elevationRange (value) {
  42689. let changed = this.uniforms.elevationRange.value[0] !== value[0]
  42690. || this.uniforms.elevationRange.value[1] !== value[1];
  42691. if(changed){
  42692. this.uniforms.elevationRange.value = value;
  42693. this._defaultElevationRangeChanged = true;
  42694. this.dispatchEvent({
  42695. type: 'material_property_changed',
  42696. target: this
  42697. });
  42698. }
  42699. }
  42700. get heightMin () {
  42701. return this.uniforms.elevationRange.value[0];
  42702. }
  42703. set heightMin (value) {
  42704. this.elevationRange = [value, this.elevationRange[1]];
  42705. }
  42706. get heightMax () {
  42707. return this.uniforms.elevationRange.value[1];
  42708. }
  42709. set heightMax (value) {
  42710. this.elevationRange = [this.elevationRange[0], value];
  42711. }
  42712. get transition () {
  42713. return this.uniforms.transition.value;
  42714. }
  42715. set transition (value) {
  42716. this.uniforms.transition.value = value;
  42717. }
  42718. get intensityRange () {
  42719. return this.uniforms.intensityRange.value;
  42720. }
  42721. set intensityRange (value) {
  42722. if (!(value instanceof Array && value.length === 2)) {
  42723. return;
  42724. }
  42725. if (value[0] === this.uniforms.intensityRange.value[0] &&
  42726. value[1] === this.uniforms.intensityRange.value[1]) {
  42727. return;
  42728. }
  42729. this.uniforms.intensityRange.value = value;
  42730. this._defaultIntensityRangeChanged = true;
  42731. this.dispatchEvent({
  42732. type: 'material_property_changed',
  42733. target: this
  42734. });
  42735. }
  42736. get intensityGamma () {
  42737. return this.uniforms.intensity_gbc.value[0];
  42738. }
  42739. set intensityGamma (value) {
  42740. if (this.uniforms.intensity_gbc.value[0] !== value) {
  42741. this.uniforms.intensity_gbc.value[0] = value;
  42742. this.dispatchEvent({
  42743. type: 'material_property_changed',
  42744. target: this
  42745. });
  42746. }
  42747. }
  42748. get intensityContrast () {
  42749. return this.uniforms.intensity_gbc.value[2];
  42750. }
  42751. set intensityContrast (value) {
  42752. if (this.uniforms.intensity_gbc.value[2] !== value) {
  42753. this.uniforms.intensity_gbc.value[2] = value;
  42754. this.dispatchEvent({
  42755. type: 'material_property_changed',
  42756. target: this
  42757. });
  42758. }
  42759. }
  42760. get intensityBrightness () {
  42761. return this.uniforms.intensity_gbc.value[1];
  42762. }
  42763. set intensityBrightness (value) {
  42764. if (this.uniforms.intensity_gbc.value[1] !== value) {
  42765. this.uniforms.intensity_gbc.value[1] = value;
  42766. this.dispatchEvent({
  42767. type: 'material_property_changed',
  42768. target: this
  42769. });
  42770. }
  42771. }
  42772. get rgbGamma () {
  42773. return this.uniforms.uRGB_gbc.value[0];
  42774. }
  42775. set rgbGamma (value) {
  42776. if (this.uniforms.uRGB_gbc.value[0] !== value) {
  42777. this.uniforms.uRGB_gbc.value[0] = value;
  42778. this.dispatchEvent({
  42779. type: 'material_property_changed',
  42780. target: this
  42781. });
  42782. }
  42783. }
  42784. get rgbContrast () {
  42785. return this.uniforms.uRGB_gbc.value[2];
  42786. }
  42787. set rgbContrast (value) {
  42788. if (this.uniforms.uRGB_gbc.value[2] !== value) {
  42789. this.uniforms.uRGB_gbc.value[2] = value;
  42790. this.dispatchEvent({
  42791. type: 'material_property_changed',
  42792. target: this
  42793. });
  42794. }
  42795. }
  42796. get rgbBrightness () {
  42797. return this.uniforms.uRGB_gbc.value[1];
  42798. }
  42799. set rgbBrightness (value) {
  42800. if (this.uniforms.uRGB_gbc.value[1] !== value) {
  42801. this.uniforms.uRGB_gbc.value[1] = value;
  42802. this.dispatchEvent({
  42803. type: 'material_property_changed',
  42804. target: this
  42805. });
  42806. }
  42807. }
  42808. get extraGamma () {
  42809. return this.uniforms.uExtraGammaBrightContr.value[0];
  42810. }
  42811. set extraGamma (value) {
  42812. if (this.uniforms.uExtraGammaBrightContr.value[0] !== value) {
  42813. this.uniforms.uExtraGammaBrightContr.value[0] = value;
  42814. this.dispatchEvent({
  42815. type: 'material_property_changed',
  42816. target: this
  42817. });
  42818. }
  42819. }
  42820. get extraBrightness () {
  42821. return this.uniforms.uExtraGammaBrightContr.value[1];
  42822. }
  42823. set extraBrightness (value) {
  42824. if (this.uniforms.uExtraGammaBrightContr.value[1] !== value) {
  42825. this.uniforms.uExtraGammaBrightContr.value[1] = value;
  42826. this.dispatchEvent({
  42827. type: 'material_property_changed',
  42828. target: this
  42829. });
  42830. }
  42831. }
  42832. get extraContrast () {
  42833. return this.uniforms.uExtraGammaBrightContr.value[2];
  42834. }
  42835. set extraContrast (value) {
  42836. if (this.uniforms.uExtraGammaBrightContr.value[2] !== value) {
  42837. this.uniforms.uExtraGammaBrightContr.value[2] = value;
  42838. this.dispatchEvent({
  42839. type: 'material_property_changed',
  42840. target: this
  42841. });
  42842. }
  42843. }
  42844. getRange(attributeName){
  42845. return this.ranges.get(attributeName);
  42846. }
  42847. setRange(attributeName, newRange){
  42848. let rangeChanged = false;
  42849. let oldRange = this.ranges.get(attributeName);
  42850. if(oldRange != null && newRange != null){
  42851. rangeChanged = oldRange[0] !== newRange[0] || oldRange[1] !== newRange[1];
  42852. }else {
  42853. rangeChanged = true;
  42854. }
  42855. this.ranges.set(attributeName, newRange);
  42856. if(rangeChanged){
  42857. this.dispatchEvent({
  42858. type: 'material_property_changed',
  42859. target: this
  42860. });
  42861. }
  42862. }
  42863. get extraRange () {
  42864. return this.uniforms.uExtraRange.value;
  42865. }
  42866. set extraRange (value) {
  42867. if (!(value instanceof Array && value.length === 2)) {
  42868. return;
  42869. }
  42870. if (value[0] === this.uniforms.uExtraRange.value[0] &&
  42871. value[1] === this.uniforms.uExtraRange.value[1]) {
  42872. return;
  42873. }
  42874. this.uniforms.uExtraRange.value = value;
  42875. this._defaultExtraRangeChanged = true;
  42876. this.dispatchEvent({
  42877. type: 'material_property_changed',
  42878. target: this
  42879. });
  42880. }
  42881. get weightRGB () {
  42882. return this.uniforms.wRGB.value;
  42883. }
  42884. set weightRGB (value) {
  42885. if(this.uniforms.wRGB.value !== value){
  42886. this.uniforms.wRGB.value = value;
  42887. this.dispatchEvent({
  42888. type: 'material_property_changed',
  42889. target: this
  42890. });
  42891. }
  42892. }
  42893. get weightIntensity () {
  42894. return this.uniforms.wIntensity.value;
  42895. }
  42896. set weightIntensity (value) {
  42897. if(this.uniforms.wIntensity.value !== value){
  42898. this.uniforms.wIntensity.value = value;
  42899. this.dispatchEvent({
  42900. type: 'material_property_changed',
  42901. target: this
  42902. });
  42903. }
  42904. }
  42905. get weightElevation () {
  42906. return this.uniforms.wElevation.value;
  42907. }
  42908. set weightElevation (value) {
  42909. if(this.uniforms.wElevation.value !== value){
  42910. this.uniforms.wElevation.value = value;
  42911. this.dispatchEvent({
  42912. type: 'material_property_changed',
  42913. target: this
  42914. });
  42915. }
  42916. }
  42917. get weightClassification () {
  42918. return this.uniforms.wClassification.value;
  42919. }
  42920. set weightClassification (value) {
  42921. if(this.uniforms.wClassification.value !== value){
  42922. this.uniforms.wClassification.value = value;
  42923. this.dispatchEvent({
  42924. type: 'material_property_changed',
  42925. target: this
  42926. });
  42927. }
  42928. }
  42929. get weightReturnNumber () {
  42930. return this.uniforms.wReturnNumber.value;
  42931. }
  42932. set weightReturnNumber (value) {
  42933. if(this.uniforms.wReturnNumber.value !== value){
  42934. this.uniforms.wReturnNumber.value = value;
  42935. this.dispatchEvent({
  42936. type: 'material_property_changed',
  42937. target: this
  42938. });
  42939. }
  42940. }
  42941. get weightSourceID () {
  42942. return this.uniforms.wSourceID.value;
  42943. }
  42944. set weightSourceID (value) {
  42945. if(this.uniforms.wSourceID.value !== value){
  42946. this.uniforms.wSourceID.value = value;
  42947. this.dispatchEvent({
  42948. type: 'material_property_changed',
  42949. target: this
  42950. });
  42951. }
  42952. }
  42953. static generateGradientTexture (gradient) {
  42954. let size = 64;
  42955. // create canvas
  42956. let canvas = document.createElement('canvas');
  42957. canvas.width = size;
  42958. canvas.height = size;
  42959. // get context
  42960. let context = canvas.getContext('2d');
  42961. // draw gradient
  42962. context.rect(0, 0, size, size);
  42963. let ctxGradient = context.createLinearGradient(0, 0, size, size);
  42964. for (let i = 0; i < gradient.length; i++) {
  42965. let step = gradient[i];
  42966. ctxGradient.addColorStop(step[0], '#' + step[1].getHexString());
  42967. }
  42968. context.fillStyle = ctxGradient;
  42969. context.fill();
  42970. //let texture = new THREE.Texture(canvas);
  42971. let texture = new CanvasTexture(canvas);
  42972. texture.needsUpdate = true;
  42973. texture.minFilter = LinearFilter;
  42974. texture.wrap = RepeatWrapping;
  42975. texture.repeat = 2;
  42976. // textureImage = texture.image;
  42977. return texture;
  42978. }
  42979. static generateMatcapTexture (matcap) {
  42980. var url = new URL(Potree.resourcePath + "/textures/matcap/" + matcap).href;
  42981. let texture = new TextureLoader().load( url );
  42982. texture.magFilter = texture.minFilter = LinearFilter;
  42983. texture.needsUpdate = true;
  42984. // 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
  42985. // Switch matcap texture on the fly : viewer.scene.pointclouds[0].material.matcap = 'matcap1.jpg';
  42986. // 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
  42987. return texture;
  42988. }
  42989. disableEvents(){
  42990. if(this._hiddenListeners === undefined){
  42991. this._hiddenListeners = this._listeners;
  42992. this._listeners = {};
  42993. }
  42994. };
  42995. enableEvents(){
  42996. this._listeners = this._hiddenListeners;
  42997. this._hiddenListeners = undefined;
  42998. };
  42999. ////////////////////////add
  43000. setProjectedPanos(pano0, pano1, progressValue, easeInOutRatio){
  43001. //this.uniforms.usePanoMap.value = 1
  43002. this.usePanoMap = true;
  43003. progressValue!=void 0 && (this.uniforms.progress.value = progressValue);
  43004. //pano0.ensureSkyboxReadyForRender();
  43005. this.uniforms.pano0Map.value = pano0.getSkyboxTexture();
  43006. this.uniforms.pano0Position.value.copy(pano0.position);
  43007. this.uniforms.pano0Matrix.value.copy(pano0.panoMatrix );
  43008. //pano1.ensureSkyboxReadyForRender();
  43009. this.uniforms.easeInOutRatio.value = easeInOutRatio || 0; //之前做点云和全景混合时加的,为了让点云颜色柔和切换到全景颜色。如不混合就0
  43010. this.uniforms.pano1Map.value = pano1.getSkyboxTexture();
  43011. this.uniforms.pano1Position.value.copy(pano1.position);
  43012. this.uniforms.pano1Matrix.value.copy(pano1.panoMatrix );
  43013. //this.updateShaderSource()
  43014. //this.needsUpdate = true;
  43015. }
  43016. stopProjectedPanos(){
  43017. //this.uniforms.usePanoMap.value = 0
  43018. this.usePanoMap = false;
  43019. }
  43020. // copyFrom(from){
  43021. // var a = 10;
  43022. // for(let name of Object.keys(this.uniforms)){
  43023. // this.uniforms[name].value = from.uniforms[name].value;
  43024. // }
  43025. // }
  43026. // copy(from){
  43027. // this.copyFrom(from);
  43028. // }
  43029. }
  43030. var Common = {
  43031. sortByScore: function(list, request, rank){
  43032. var i = request ? Common.filterAll(list, request) : list;
  43033. return 0 === i.length ? null : i = i.map(function(e) {
  43034. return {
  43035. item: e,
  43036. score: rank.reduce(function(t, i) {
  43037. return t + i(e)
  43038. }, 0)
  43039. }
  43040. }).sort(function(e, t) {
  43041. return t.score - e.score;
  43042. })
  43043. }
  43044. ,
  43045. filterAll: function(e, t) {
  43046. return e.filter(function (e) {
  43047. return t.every(function (t) {
  43048. return t(e)
  43049. })
  43050. })
  43051. },
  43052. //---------------
  43053. find : function(list, request, rank, sortByScore ) {
  43054. if(sortByScore){
  43055. var r = this.sortByScore(list, request, rank);
  43056. return r && r[0] && r[0].item
  43057. }else {
  43058. var i = request ? Common.filterAll(list, request) : list;
  43059. return 0 === i.length ? null : (rank && rank.forEach(function(e) {
  43060. i = Common.stableSort(i, e);
  43061. }),
  43062. i[0])
  43063. }
  43064. }
  43065. ,
  43066. stableSort: function(e, f) {//用到排序函数,涉及到两个item相减
  43067. return e.map(function(e, i) {
  43068. return {
  43069. value: e,
  43070. index: i
  43071. }
  43072. }).sort(function(e, u) {
  43073. var n = f(e.value, u.value);
  43074. return 0 !== n ? n : e.index - u.index //似乎就是加多了这一步:若差距为0,按照原顺序
  43075. }).map(function(e) {
  43076. return e.value
  43077. })
  43078. },
  43079. average: function (e, t) {
  43080. if (0 === e.length)
  43081. return null;
  43082. for (var i = 0, n = 0, r = 0; r < e.length; r++) {
  43083. var o = t ? e[r][t] : e[r];
  43084. i += o,
  43085. n++;
  43086. }
  43087. return i / n
  43088. },
  43089. //---------------------------
  43090. getMixedSet : function(arr1, arr2){//交集
  43091. return arr1.filter(item=>arr2.includes(item));
  43092. },
  43093. getUnionSet : function(arr1, arr2){//并集
  43094. return arr1.concat(arr2.filter(item=>!arr1.includes(item)))
  43095. },
  43096. getDifferenceSet : function(arr1, arr2){//差集 不能识别重复的,如getDifferenceSet([1,2,2],[1,1,2]) 为空
  43097. var arr11 = arr1.filter(item=>!arr2.includes(item));
  43098. var arr22 = arr2.filter(item=>!arr1.includes(item));
  43099. return arr11.concat(arr22)
  43100. },
  43101. getDifferenceSetMuti : function(arr){//收集绝对没有重复的元素,也就是判断出现次数=1的
  43102. var set = [];
  43103. arr.forEach(arr1=>{
  43104. arr1.forEach(item=>{
  43105. var index = set.indexOf(item);
  43106. if(index>-1){
  43107. set.splice(index, 1);
  43108. }else {
  43109. set.push(item);
  43110. }
  43111. });
  43112. });
  43113. return set;
  43114. }
  43115. ,
  43116. CloneJson : function(data){
  43117. var str = JSON.stringify(data);
  43118. return JSON.parse(str)
  43119. }
  43120. ,
  43121. CloneObject : function(copyObj, result, isSimpleCopy, simpleCopyList=[]) {
  43122. //isSimpleCopy 只复制最外层
  43123. //复制json result的可能:普通数字或字符串、普通数组、复杂对象
  43124. simpleCopyList.push(Object3D); //遇到simpleCopyList中的类直接使用不拷贝
  43125. if(!copyObj || typeof copyObj == 'number' || typeof copyObj == 'string' || copyObj instanceof Function || simpleCopyList.some(className => copyObj instanceof className)){
  43126. return copyObj
  43127. }
  43128. result = result || {};
  43129. if (copyObj instanceof Array) {
  43130. return copyObj.map(e=>{
  43131. return this.CloneObject(e)
  43132. })
  43133. }else {
  43134. if(copyObj.clone instanceof Function ){ //解决一部分
  43135. return copyObj.clone()
  43136. }
  43137. }
  43138. for (var key in copyObj) {
  43139. if (copyObj[key] instanceof Object && !isSimpleCopy)
  43140. result[key] = this.CloneObject(copyObj[key]);
  43141. else
  43142. result[key] = copyObj[key];
  43143. //如果是函数类同基本数据,即复制引用
  43144. }
  43145. return result;
  43146. }
  43147. ,
  43148. CloneClassObject :function(copyObj ){//复杂类对象
  43149. var newobj = new copyObj.constructor();
  43150. this.CopyClassObject(newobj, copyObj);
  43151. return newobj
  43152. }
  43153. ,
  43154. CopyClassObject :function(targetObj, copyObj){//复杂类对象
  43155. for(let i in copyObj){
  43156. if(i in copyObj.__proto__)break; //到函数了跳出
  43157. targetObj[i] = this.CloneObject(copyObj[i], null );
  43158. /* else if(copyObj[i].clone instanceof Function ){
  43159. targetObj[i] = copyObj[i].clone()
  43160. }else{
  43161. targetObj[i] = copyObj[i];
  43162. } */
  43163. }
  43164. }
  43165. ,
  43166. ifSame : function(object1, object2){
  43167. if(object1 == object2 )return true // 0 != undefined , 0 == ''
  43168. else if(!object1 || !object2) return false
  43169. else if(object1.constructor != object2.constructor){
  43170. return false
  43171. }else if(object1 instanceof Array ) {
  43172. if(object1.length != object2.length)return false;
  43173. var _object2 = object2.slice(0);
  43174. for(let i=0;i<object1.length;i++){
  43175. var u = _object2.find(e=>ifSame(object1[i], e));
  43176. if(u == void 0 && !_object2.includes(u) && !object1.includes(u))return false;
  43177. else {
  43178. let index = _object2.indexOf(u);
  43179. _object2.splice(index,1);
  43180. }
  43181. }
  43182. return true
  43183. }else if(object1.equals instanceof Function ){//复杂数据仅支持这种,其他的可能卡住?
  43184. return object1.equals(object2)
  43185. }else if(typeof object1 == 'number' || typeof object1 == 'string'){
  43186. if(isNaN(object1) && isNaN(object2))return true
  43187. else return object1 == object2
  43188. }else if(typeof object1 == "object"){
  43189. var keys1 = Object.keys(object1);
  43190. var keys2 = Object.keys(object2);
  43191. if(!ifSame(keys1,keys2))return false;
  43192. for(let i in object1){
  43193. var same = ifSame(object1[i], object2[i]);
  43194. if(!same)return false
  43195. }
  43196. return true
  43197. }else {
  43198. console.log('isSame出现例外');
  43199. }
  43200. }
  43201. ,
  43202. replaceAll : function (str, f, e) {
  43203. //f全部替换成e
  43204. var reg = new RegExp(f, "g"); //创建正则RegExp对象
  43205. return str.replace(reg, e);
  43206. }
  43207. ,
  43208. downloadFile : function(data, filename, cb) {
  43209. var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
  43210. save_link.href = data;
  43211. save_link.download = filename;
  43212. var event = document.createEvent('MouseEvents');
  43213. event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  43214. save_link.dispatchEvent(event);
  43215. cb && cb();
  43216. },
  43217. intervalTool:{ //延时update,防止卡顿
  43218. list:[],
  43219. isWaiting:function(name, func, delayTime){
  43220. if(!this.list.includes(name)){ //如果没有该项, 则开始判断
  43221. var needWait = func(); //触发了改变,则等待一段时间后再自动判断
  43222. if(needWait){
  43223. this.list.push(name);
  43224. setTimeout(()=>{
  43225. var a = this.list.indexOf(name);
  43226. this.list.splice(a,1);
  43227. this.isWaiting(name, func, delayTime); //循环
  43228. },delayTime);
  43229. }
  43230. }
  43231. },
  43232. /* wait:function(name, delayTime){
  43233. this.list.push(name);
  43234. setTimeout(()=>{
  43235. },delayTime)
  43236. }, */
  43237. }
  43238. ,
  43239. pushToGroupAuto : function(items, groups, recognizeFunction){//自动分组。 items是将分到一起的组合。items.length = 1 or 2.
  43240. recognizeFunction = recognizeFunction || function(){};
  43241. var atGroups = groups.filter(group=>group.find(
  43242. item => items[0] == item || recognizeFunction(item, items[0]) || items[1] == item || items[1] && recognizeFunction(item, items[1])
  43243. ));
  43244. if(atGroups.length){//在不同组
  43245. //因为items是一组的,所以先都放入组1
  43246. items.forEach(item=> {if(!atGroups[0].includes(item)) atGroups[0].push(item);});
  43247. if(atGroups.length>1){//如果在不同组,说明这两个组需要合并
  43248. var combineGroup = [];
  43249. atGroups.forEach(group=>{
  43250. combineGroup = Common.getUnionSet(combineGroup, group);
  43251. groups.splice(groups.indexOf(group),1);
  43252. });
  43253. groups.push(combineGroup);
  43254. }
  43255. }else {//直接加入为一组
  43256. groups.push(items);
  43257. }
  43258. },
  43259. addOrRemoveDefine(material, defineName, type, value=''){
  43260. let defines = material.defines;
  43261. if(type == 'add'){
  43262. if(defines[defineName] != void 0 && defines[defineName] == value)return
  43263. defines[defineName] = value;
  43264. }else {
  43265. if(defines[defineName] != void 0)return;
  43266. delete defines[defineName];
  43267. }
  43268. material.needsUpdate = true;
  43269. },
  43270. makeTexDontResize(map){//避免贴图因非2的次方而缩小。小心使用
  43271. if(!map || map.image && MathUtils.isPowerOfTwo(map.image.width ) && MathUtils.isPowerOfTwo(map.image.height ))return
  43272. map.wrapS = map.wrapT = ClampToEdgeWrapping; //原默认 RepeatWrapping
  43273. map.minFilter = LinearFilter; // or THREE.NearestFilter 原默认 LinearMipmapLinearFilter
  43274. }
  43275. };
  43276. const planeGeo = new PlaneBufferGeometry(1,1);
  43277. const planeMats$1 = new Map();
  43278. let getPlaneMat = (group, removed)=>{
  43279. let mat = planeMats$1.get(group);
  43280. if(mat)return mat
  43281. var planeMat = new MeshBasicMaterial({
  43282. //color: level == 'removed' ? "#f00" : new THREE.Color(1 - level*0.2, 1,1),
  43283. color: (new Color()).setHSL(Math.random(), 0.5, 0.9) ,
  43284. //color: (new THREE.Color()).setHSL(removed ? 0 : 0.6, Math.random(), 0.9/* Math.random() */) ,
  43285. transparent:true,
  43286. side:2,
  43287. opacity: removed ? 0.3 : 0.9,
  43288. });
  43289. planeMats$1.set(group, planeMat);
  43290. return planeMat
  43291. };
  43292. class PointCloudOctreeNode extends PointCloudTreeNode {
  43293. constructor () {
  43294. super();
  43295. //this.children = {};
  43296. this.children = [];
  43297. this.sceneNode = null;
  43298. this.octree = null;
  43299. }
  43300. getNumPoints () {
  43301. return this.geometryNode.numPoints;
  43302. }
  43303. isLoaded () {
  43304. return true;
  43305. }
  43306. isTreeNode () {
  43307. return true;
  43308. }
  43309. isGeometryNode () {
  43310. return false;
  43311. }
  43312. getLevel () {
  43313. return this.geometryNode.level;
  43314. }
  43315. getBoundingSphere () {
  43316. return this.geometryNode.boundingSphere;
  43317. }
  43318. getBoundingBox () {
  43319. return this.geometryNode.boundingBox;
  43320. }
  43321. getChildren () {
  43322. let children = [];
  43323. for (let i = 0; i < 8; i++) {
  43324. if (this.children[i]) {
  43325. children.push(this.children[i]);
  43326. }
  43327. }
  43328. return children;
  43329. }
  43330. getPointsInBox(boxNode){
  43331. if(!this.sceneNode){
  43332. return null;
  43333. }
  43334. let buffer = this.geometryNode.buffer;
  43335. let posOffset = buffer.offset("position");
  43336. let stride = buffer.stride;
  43337. let view = new DataView(buffer.data);
  43338. let worldToBox = boxNode.matrixWorld.clone().invert();
  43339. let objectToBox = new Matrix4().multiplyMatrices(worldToBox, this.sceneNode.matrixWorld);
  43340. let inBox = [];
  43341. let pos = new Vector4();
  43342. for(let i = 0; i < buffer.numElements; i++){
  43343. let x = view.getFloat32(i * stride + posOffset + 0, true);
  43344. let y = view.getFloat32(i * stride + posOffset + 4, true);
  43345. let z = view.getFloat32(i * stride + posOffset + 8, true);
  43346. pos.set(x, y, z, 1);
  43347. pos.applyMatrix4(objectToBox);
  43348. if(-0.5 < pos.x && pos.x < 0.5){
  43349. if(-0.5 < pos.y && pos.y < 0.5){
  43350. if(-0.5 < pos.z && pos.z < 0.5){
  43351. pos.set(x, y, z, 1).applyMatrix4(this.sceneNode.matrixWorld);
  43352. inBox.push(new Vector3(pos.x, pos.y, pos.z));
  43353. }
  43354. }
  43355. }
  43356. }
  43357. return inBox;
  43358. }
  43359. get name () {
  43360. return this.geometryNode.name;
  43361. }
  43362. };
  43363. class PointCloudOctree extends PointCloudTree {
  43364. constructor (geometry, material) {
  43365. super();
  43366. //this.pointBudget = Infinity;
  43367. this.pcoGeometry = geometry;
  43368. this.boundingBox = this.pcoGeometry.tightBoundingBox;//this.pcoGeometry.boundingBox; //boundingBox是正方体,所以换掉
  43369. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  43370. this.material = material || new PointCloudMaterial$1();
  43371. this.visiblePointsTarget = 2 * 1000 * 1000;
  43372. this.minimumNodePixelSize = 150;
  43373. this.level = 0;
  43374. this.position.copy(geometry.offset);
  43375. this.updateMatrix();
  43376. this.nodeMaxLevel = 0;//add
  43377. this.maxLevel = Infinity;
  43378. this.temp = { sizeFitToLevel:{}, opacity:{}};//add
  43379. //add
  43380. this.panos = [];
  43381. this.matrixAutoUpdate = false; //最好禁止updateMatrix 直接使用matrixWorld
  43382. this.orientationUser = 0;
  43383. this.translateUser = new Vector3;
  43384. this.rotateMatrix = new Matrix4;
  43385. this.transformMatrix = new Matrix4;// 数据集的变化矩阵
  43386. this.transformInvMatrix = new Matrix4;
  43387. this.rotateInvMatrix = new Matrix4;
  43388. this.nodeMaxLevelPredict = this.predictNodeMaxLevel();//预测maxNodeLevel
  43389. this.testMaxNodeCount = this.testMaxNodeCount2 = 0;
  43390. this.material.spacing = this.pcoGeometry.spacing;//初始化一下 以便于设置pointsize
  43391. {
  43392. let priorityQueue = ["rgba", "rgb", "intensity", "classification"];
  43393. let selected = "rgba";
  43394. for(let attributeName of priorityQueue){
  43395. let attribute = this.pcoGeometry.pointAttributes.attributes.find(a => a.name === attributeName);
  43396. if(!attribute){
  43397. continue;
  43398. }
  43399. let min = attribute.range[0].constructor.name === "Array" ? attribute.range[0] : [attribute.range[0]];
  43400. let max = attribute.range[1].constructor.name === "Array" ? attribute.range[1] : [attribute.range[1]];
  43401. let range_min = new Vector3(...min);
  43402. let range_max = new Vector3(...max);
  43403. let range = range_min.distanceTo(range_max);
  43404. if(range === 0){
  43405. continue;
  43406. }
  43407. selected = attributeName;
  43408. break;
  43409. }
  43410. this.material.activeAttributeName = selected;
  43411. }
  43412. this.showBoundingBox = false;
  43413. this.boundingBoxNodes = [];
  43414. this.loadQueue = [];
  43415. this.visibleBounds = new Box3();
  43416. this.visibleNodes = [];
  43417. this.visibleGeometry = [];
  43418. this.generateDEM = false;
  43419. this.profileRequests = [];
  43420. this.name = '';
  43421. this._visible = true;
  43422. //this._isVisible = true//add
  43423. //this.unvisibleReasons = []
  43424. {
  43425. let box = [this.pcoGeometry.tightBoundingBox, this.getBoundingBoxWorld()]
  43426. .find(v => v !== undefined);
  43427. this.updateMatrixWorld(true);
  43428. box = Utils.computeTransformedBoundingBox(box, this.matrixWorld);
  43429. let bMin = box.min.z;
  43430. let bMax = box.max.z;
  43431. this.material.heightMin = bMin;
  43432. this.material.heightMax = bMax;
  43433. }
  43434. // TODO read projection from file instead
  43435. this.projection = geometry.projection;
  43436. this.fallbackProjection = geometry.fallbackProjection;
  43437. this.root = this.pcoGeometry.root;
  43438. this.pcoGeometry.addEventListener('updateNodeMaxLevel', this.updateNodeMaxLevel.bind(this));
  43439. this.isPointcloud = true; //add
  43440. }
  43441. /*
  43442. 注释:node的level从最大的box 0开始。
  43443. 且加载任意一个node必定也会加载它的所有祖先。(如visibleNodes中有一个level为4,则一定有3,2,1,0)
  43444. visibleNodes就是所有可见的node,比如:
  43445. 如果相机在0这个位置朝下,这时候的visibleNodes中只有一个level为0的node;
  43446. 而如果朝上看,上方的几个node如果在视野中占据足够大的位置的话,就会加载。
  43447. 如果相机在2这个位置朝上,这时候的visibleNodes中所包含的level为: 0,1,2
  43448. ________________
  43449. | | | |
  43450. |__2| | |
  43451. | 1 | 1 |
  43452. |_______|_______|
  43453. | |
  43454. | |
  43455. | 0 |
  43456. |_______________|
  43457. 查看box可在potree中开启
  43458. */
  43459. updateNodeMaxLevel(e){//目前点云包含node的最高level
  43460. var level = Math.max(e.level, this.nodeMaxLevel);
  43461. if(level != this.nodeMaxLevel){
  43462. this.nodeMaxLevel = level;
  43463. //viewer.dispatchEvent({type:'updateNodeMaxLevel', pointcloud: this, nodeMaxLevel:level})
  43464. //console.log('updateNodeMaxLevel ' + this.dataset_id + " : "+ this.nodeMaxLevel)
  43465. this.setPointLevel();//重新计算
  43466. if(!Potree.settings.sizeFitToLevel){
  43467. this.changePointSize();
  43468. }
  43469. }
  43470. }//注:在没有加载到真实的 nodeMaxLevel之前,点云会显示得偏大
  43471. //panoEdit时比预测值小很多?
  43472. testMaxNodeLevel(){//手动使maxLevel达到最高,从而迫使updateNodeMaxLevel。 因为Potree.settings.pointDensity 不为 'high'时,maxLevel不是所加载的最高,就很容易加载不出下一个层级,导致无法知道nodeMaxLevel
  43473. if(this.testMaxNodeLevelDone ) return
  43474. //if(this.nodeMaxLevel > this.nodeMaxLevelPredict.min )return
  43475. if( this.nodeMaxLevel==0 )return true
  43476. if( !viewer.atDatasets.includes(this))return true //否则老远就count++
  43477. let levels = this.visibleNodes.map(e=>e.getLevel());
  43478. let actMaxLevel = Math.max.apply(null, levels); //实际加载到的最高的node level
  43479. if(actMaxLevel < this.maxLevel)return true// 还没加载到能加载到的最高。 但在细节设置较低时,排除作用微弱。
  43480. //尝试加载出更高级的level
  43481. let old = this.maxLevel;
  43482. this.maxLevel = 12;
  43483. //var visibleNodes1 = this.visibleNodes.map(e=>e.getLevel())
  43484. //console.log('visibleNodes1',visibleNodes1)
  43485. Potree.updatePointClouds([this], viewer.scene.getActiveCamera(), viewer.mainViewport.resolution );
  43486. //不在camera可视范围内还是加载不出来。即使临时修改位置
  43487. var visibleNodes2 = this.visibleNodes.map(e=>e.getLevel());
  43488. //console.log('visibleNodes2',visibleNodes2)
  43489. this.maxLevel = old;
  43490. this.testMaxNodeCount ++;
  43491. if(this.testMaxNodeCount > 500){
  43492. console.log('testMaxNodeLevel次数超出,强制结束:',this.dataset_id, this.nodeMaxLevel, this.nodeMaxLevelPredict.min);
  43493. this.testMaxNodeLevelDone = 'moreThanMaxCount';
  43494. return; //在可以看见点云的情况下,超时,有可能是预测的max是错的
  43495. }
  43496. if(this.nodeMaxLevel < this.nodeMaxLevelPredict.min) return true //仍需要继续testMaxNodeLevel
  43497. this.testMaxNodeCount2 ++; // 已经> this.nodeMaxLevelPredict.min 后,开始计数。因为min可能低于真实nodeMaxLevel所以要再试几次
  43498. /* if(this.name == 'SS-t-CWmVgzP4XU'){
  43499. console.log('SS-t-CWmVgzP4XU count++')
  43500. } */
  43501. if(this.testMaxNodeCount2 < 50) return true //再试几次 ( 主要是细节调得低时需要多测几次才加载到
  43502. this.testMaxNodeLevelDone = true;
  43503. }
  43504. setPointLevel(){
  43505. var pointDensity = Potree.settings.pointDensity;
  43506. var config = Potree.config.pointDensity[pointDensity];
  43507. if(!config)return
  43508. /* if(this.testingMaxLevel){
  43509. this.maxLevel = 12;//先加载到最大的直到测试完毕。由于5个level为一组来加载,所以如果写4最高能加载到5,如果写5最高能加载到下一个级别的最高也就是10
  43510. //console.log('maxLevel: '+e.maxLevel + ' testingMaxLevel中 ' )
  43511. }else{ */
  43512. let percent = config.percentByUser && Potree.settings.UserDensityPercent != void 0 ? Potree.settings.UserDensityPercent : config.maxLevelPercent;
  43513. this.maxLevel = Math.round( percent * this.nodeMaxLevel);
  43514. //console.log('maxLevel: '+e.maxLevel + ', density : '+Potree.settings.pointDensity, ", percent :"+percent);
  43515. if(Potree.settings.sizeFitToLevel){
  43516. this.changePointSize();
  43517. }
  43518. this.changePointOpacity();
  43519. //}
  43520. }
  43521. //预测可能的nodeMaxLevel:
  43522. predictNodeMaxLevel(){//预测maxNodeLevel。 可能只适用于我们相机拍的点云
  43523. let spacing = {min:0.005, max:0.014};//最小节的两点间的距离 ,获得方法:spacing / Math.pow(2, nodeMaxLevel)。 目前观测的我们自己拍的这个数值的范围大概是这样
  43524. let min = Math.log2(this.material.spacing / spacing.max); //有见过最大是0.01368
  43525. let max = Math.log2(this.material.spacing / spacing.min); //大部分是 0.006
  43526. //console.log('predictNodeMaxLevel:', this.name , min, max )
  43527. return {min, max}
  43528. }
  43529. getHighestNodeSpacing(){
  43530. return this.material.spacing / Math.pow(2, this.nodeMaxLevel) //前提是这个nodeMaxLevel是准确的
  43531. }
  43532. setName (name) {
  43533. if (this.name !== name) {
  43534. this.name = name;
  43535. this.dispatchEvent({type: 'name_changed', name: name, pointcloud: this});
  43536. }
  43537. }
  43538. getName () {
  43539. return this.name;
  43540. }
  43541. getAttribute(name){
  43542. const attribute = this.pcoGeometry.pointAttributes.attributes.find(a => a.name === name);
  43543. if(attribute){
  43544. return attribute;
  43545. }else {
  43546. return null;
  43547. }
  43548. }
  43549. getAttributes(){
  43550. return this.pcoGeometry.pointAttributes;
  43551. }
  43552. toTreeNode (geometryNode, parent) {
  43553. let node = new PointCloudOctreeNode();
  43554. // if(geometryNode.name === "r40206"){
  43555. // console.log("creating node for r40206");
  43556. // }
  43557. let sceneNode = new Points(geometryNode.geometry, this.material); //好像没什么用
  43558. sceneNode.name = geometryNode.name;
  43559. sceneNode.position.copy(geometryNode.boundingBox.min);
  43560. sceneNode.frustumCulled = false;
  43561. sceneNode.onBeforeRender = (_this, scene, camera, geometry, material, group) => {
  43562. if (material.program) {
  43563. _this.getContext().useProgram(material.program.program);
  43564. if (material.program.getUniforms().map.level) {
  43565. let level = geometryNode.getLevel();
  43566. material.uniforms.level.value = level;
  43567. material.program.getUniforms().map.level.setValue(_this.getContext(), level);
  43568. }
  43569. if (this.visibleNodeTextureOffsets && material.program.getUniforms().map.vnStart) {
  43570. let vnStart = this.visibleNodeTextureOffsets.get(node);
  43571. material.uniforms.vnStart.value = vnStart;
  43572. material.program.getUniforms().map.vnStart.setValue(_this.getContext(), vnStart);
  43573. }
  43574. if (material.program.getUniforms().map.pcIndex) {
  43575. let i = node.pcIndex ? node.pcIndex : this.visibleNodes.indexOf(node);
  43576. material.uniforms.pcIndex.value = i;
  43577. material.program.getUniforms().map.pcIndex.setValue(_this.getContext(), i);
  43578. }
  43579. }
  43580. };
  43581. // { // DEBUG
  43582. // let sg = new THREE.SphereGeometry(1, 16, 16);
  43583. // let sm = new THREE.MeshNormalMaterial();
  43584. // let s = new THREE.Mesh(sg, sm);
  43585. // s.scale.set(5, 5, 5);
  43586. // s.position.copy(geometryNode.mean)
  43587. // .add(this.position)
  43588. // .add(geometryNode.boundingBox.min);
  43589. //
  43590. // viewer.scene.scene.add(s);
  43591. // }
  43592. node.geometryNode = geometryNode;
  43593. node.sceneNode = sceneNode;
  43594. node.pointcloud = this;
  43595. node.children = [];
  43596. //for (let key in geometryNode.children) {
  43597. // node.children[key] = geometryNode.children[key];
  43598. //}
  43599. for(let i = 0; i < 8; i++){
  43600. node.children[i] = geometryNode.children[i];
  43601. }
  43602. if (!parent) {
  43603. this.root = node;
  43604. this.add(sceneNode);
  43605. } else {
  43606. let childIndex = parseInt(geometryNode.name[geometryNode.name.length - 1]);
  43607. parent.sceneNode.add(sceneNode);
  43608. parent.children[childIndex] = node;
  43609. }
  43610. let disposeListener = function () {
  43611. let childIndex = parseInt(geometryNode.name[geometryNode.name.length - 1]);
  43612. parent.sceneNode.remove(node.sceneNode);
  43613. parent.children[childIndex] = geometryNode;
  43614. };
  43615. geometryNode.oneTimeDisposeHandlers.push(disposeListener);
  43616. //this.buildTexMesh(geometryNode,sceneNode)
  43617. return node;
  43618. }
  43619. buildTexMesh11(geometryNode,sceneNode){
  43620. // viewer.scene.pointclouds.forEach(a=>a.areaPlanes.forEach(e=>e.material = viewer.images360.cube.material))
  43621. //还是无法避免不在同一个平面的点被识别到同一个面上,然后法向都算错了。 另外还有就是破面太多。虽然能算出地板也不错。或者只去算水平面和垂直面。
  43622. let startTime = Date.now();
  43623. if(!this.splitSprites){
  43624. let splitSprites = new Object3D;
  43625. splitSprites.name = 'splitSprites_'+this.name;
  43626. splitSprites.matrixAutoUpdate = false; //同pointcloud一样不自动更新,直接使用
  43627. splitSprites.matrix.copy(this.matrix);
  43628. splitSprites.matrixWorld.copy(this.matrixWorld);
  43629. this.splitSprites = splitSprites;
  43630. viewer.scene.scene.add(splitSprites);
  43631. this.areaPlanes = [];
  43632. }
  43633. if(this.texMeshUseLevel == void 0 || geometryNode.level == this.texMeshUseLevel){//只需要某一层level的点
  43634. let showPointLabel = true, showCenterLabel = false;
  43635. //let spritesGeo = new THREE.BufferGeometry();
  43636. let scaleRatio = 1.4; //稍微放大些,填满缝隙
  43637. let spriteWidth1 = this.material.spacing / Math.pow(2, geometryNode.level);
  43638. if(spriteWidth1 > 3)return
  43639. let spriteWidth = spriteWidth1 * scaleRatio;
  43640. if(this.texMeshUseLevel == void 0 ){
  43641. this.texMeshUseLevel = geometryNode.level;
  43642. console.log('texMeshUseLevel ',geometryNode.level);
  43643. }
  43644. let geometry = geometryNode.geometry;
  43645. let count = geometry.attributes.position.count;
  43646. let end = Math.min(count, 6000);
  43647. let start = Math.min(5000, end);
  43648. console.warn('check points count:', end-start);
  43649. let position = geometry.attributes.position.array;
  43650. let normal = geometry.attributes.normal.array;
  43651. let i;
  43652. let up = new Vector3(0,1,0) , zeroVec = new Vector3; //up写成z向上居然结果一样
  43653. let positions = [];
  43654. let normals = [];
  43655. let newPositions = [];
  43656. let newIndices = [];
  43657. let groupMaxPointCount = 1000 ;//太多找环会崩
  43658. let minDisSquare = Math.pow(spriteWidth1 * 1.8 , 2 ); //这个数太小就连不上啦 1.65太小
  43659. let minDot = Math.cos(MathUtils.degToRad(5));//括号内是最小偏差角度, 20太大。太大的话会将立方体的相邻两面视为一个面。
  43660. //根据相邻点位置和角度是否相近来分组。有风险:两大区域可能因为一个模棱两可中间点连接在一起。
  43661. let closeGroups = [];
  43662. let groupTolerateMaxPoint = 6;//组内点<=这个数的最后会被删除
  43663. let removedCount = 0;
  43664. let useGroupCount = 0;
  43665. let splitSprites = new Object3D;
  43666. splitSprites.name = 'sub_splitSprites_'+geometryNode.name;
  43667. splitSprites.position.copy(sceneNode.position);
  43668. splitSprites.rotation.copy(sceneNode.rotation);
  43669. this.splitSprites.add(splitSprites);
  43670. for(i=start;i<end;i++){
  43671. let pos = new Vector3(position[3*i], position[3*i+1], position[3*i+2] );
  43672. let nor = new Vector3(normal[3*i],normal[3*i+1],normal[3*i+2]);
  43673. pos.nor = nor;
  43674. pos.index = i;
  43675. positions.push(pos);
  43676. normals.push(nor);
  43677. let groups = closeGroups.filter(group=>{
  43678. if(group.length>groupMaxPointCount)return //满员了
  43679. var hasClosed = group.some(p=>{
  43680. var dis = p.distanceToSquared(pos);
  43681. var dot = p.nor.dot(nor);
  43682. if(dis<minDisSquare && dot>minDot){
  43683. //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
  43684. return dis / minDisSquare - p.nor.dot(nor) < 0
  43685. }
  43686. });
  43687. return hasClosed
  43688. });
  43689. if(groups.length == 0){//创建一个新的
  43690. var newGroup = [];
  43691. closeGroups.push(newGroup);
  43692. groups = [newGroup];
  43693. }
  43694. if(groups.length == 1){//直接加入原有的
  43695. pos.belongTo = groups[0];
  43696. }else if(groups.length>1){ // comebine多个组成一个
  43697. let newBigGroup = [];
  43698. groups.forEach(e=>{
  43699. newBigGroup.push(...e);
  43700. let index = closeGroups.indexOf(e);
  43701. closeGroups.splice(index, 1);
  43702. });
  43703. closeGroups.push(newBigGroup);
  43704. pos.belongTo = newBigGroup;
  43705. newBigGroup.forEach(e=>{e.belongTo = newBigGroup;});
  43706. }
  43707. pos.belongTo.push(pos);
  43708. }
  43709. closeGroups.forEach((points,index)=>{//建造面
  43710. if(points.length <= groupTolerateMaxPoint ){
  43711. /* let sprite = new THREE.Mesh(planeGeo, getPlaneMat(pos.belongTo, true))
  43712. sprite.lookAt(nor);
  43713. sprite.position.copy(pos)
  43714. sprite.scale.set(spriteWidth,spriteWidth,spriteWidth)
  43715. sprite.name = geometryNode.name+'_index'+i
  43716. splitSprites.add(sprite)
  43717. removedCount ++; */
  43718. removedCount += points.length;
  43719. return
  43720. }
  43721. useGroupCount ++;
  43722. points.sort(function(a,b){
  43723. return a.index - b.index
  43724. });
  43725. console.log(`开始解析 ${geometryNode.name} - 第${index}组,总第${points[0].index}个点,组内有${points.length}个点`);
  43726. let planeMat = getPlaneMat(points, true);
  43727. if(showPointLabel){
  43728. points.forEach((p,i)=>{
  43729. var label = new TextSprite({
  43730. text : index+"-"+i+" ("+p.index+")"+geometryNode.name, dontFixOrient:true,
  43731. backgroundColor: {r: planeMat.color.r*255, g: planeMat.color.g*255, b: planeMat.color.b*255, a:0.6},
  43732. });
  43733. label.lookAt(p.nor);
  43734. label.position.copy(p);
  43735. label.scale.set(spriteWidth/3, spriteWidth/3, spriteWidth/3);
  43736. splitSprites.add(label);
  43737. /* let sprite = new THREE.Mesh(planeGeo,planeMat)
  43738. sprite.lookAt(p.nor);
  43739. sprite.position.copy(p)
  43740. sprite.scale.set(spriteWidth/3,spriteWidth/3,spriteWidth/3)
  43741. sprite.name = geometryNode.name+'_group'+index+"_"+ i
  43742. splitSprites.add(sprite) */
  43743. });
  43744. }
  43745. var avePos = points.reduce(function(total, currentValue){
  43746. return total.add(currentValue)
  43747. }, new Vector3).multiplyScalar(1/points.length);
  43748. let planeNormals = [];
  43749. {//获得planeNormals
  43750. //随机找两个距离远的点算normal。 按距离排序后, //抽取若干个点,然后算两两之间的法线,其中距离远的多抽取几个。
  43751. var sortPoints = points.slice(0).sort(function(a,b){
  43752. return a.distanceToSquared(avePos) - b.distanceToSquared(avePos)
  43753. });//从小到大
  43754. var pickPoints;
  43755. var length = sortPoints.length;
  43756. if(length>=7){
  43757. var ratio = [0.02,0.15,0.4,0.55,0.7,0.86,0.99];
  43758. var index = ratio.map(e=>Math.round(e * (length-1)));
  43759. //console.log('index ',index)
  43760. pickPoints = index.map(e=>sortPoints[e]);
  43761. }else {
  43762. pickPoints = sortPoints;
  43763. }
  43764. //console.log('pickPoints', pickPoints)
  43765. let num = pickPoints.length;
  43766. for(let i=0;i<num;i++){//任意一个三角形能算出一个normal
  43767. for(let j=i+1;j<num;j++){
  43768. for(let u=j+1;u<num;u++){
  43769. var p1 = pickPoints[i];
  43770. var p2 = pickPoints[j];
  43771. var p3 = pickPoints[u];
  43772. let vec1 = new Vector3().subVectors(p1,p3);
  43773. let vec2 = new Vector3().subVectors(p2,p3);
  43774. let nor = vec1.cross(vec2).normalize();
  43775. if(planeNormals[0]){
  43776. if(nor.dot(planeNormals[0])<0)nor.negate(); //反向下
  43777. }
  43778. console.log('nor',nor);
  43779. planeNormals.push(nor);
  43780. }
  43781. }
  43782. }
  43783. }
  43784. var aveNor = planeNormals.reduce(function(total, currentValue){
  43785. return total.add(currentValue)
  43786. }, new Vector3).normalize();
  43787. console.log('aveNor',aveNor, 'avePos' ,avePos, index);
  43788. if(showCenterLabel){
  43789. var label = new TextSprite({
  43790. //index+"-"+i+" ("+p.index+")"+geometryNode.name
  43791. text : `我是${index}组 ${geometryNode.name} 中心点`, dontFixOrient:true,
  43792. backgroundColor: {r: planeMat.color.r*255, g: planeMat.color.g*255, b: planeMat.color.b*255, a:0.6},
  43793. });
  43794. label.lookAt(aveNor);
  43795. label.position.copy(avePos);
  43796. label.scale.set(spriteWidth, spriteWidth, spriteWidth);
  43797. splitSprites.add(label);
  43798. }
  43799. var facePlane = new Plane().setFromNormalAndCoplanarPoint(aveNor, avePos );
  43800. var coplanarPoints = points.map(p=> facePlane.projectPoint(p, new Vector3() ));
  43801. var originPoint0 = coplanarPoints[0].clone();
  43802. var qua = math.getQuaBetween2Vector(facePlane.normal, new Vector3(0,0,1), new Vector3(0,0,1));
  43803. let points2d = coplanarPoints.map(e=>e.clone().applyQuaternion(qua));
  43804. let quaInverse = qua.clone().invert();
  43805. //--------------------
  43806. let lines = [];
  43807. points2d.forEach((p,j)=>{
  43808. p.id = j;
  43809. for(let i=0;i<j;i++){
  43810. if(p.distanceToSquared(points2d[i])<minDisSquare*1.5){
  43811. lines.push({p1:i,p2:j});
  43812. }
  43813. }
  43814. });
  43815. console.log('points count:',points2d.length, 'lines:',lines);
  43816. var rings = searchRings({
  43817. points:points2d,
  43818. lines,
  43819. onlyGetOutRing:true,
  43820. precision: Math.max(spriteWidth1/10, 0.01)
  43821. });
  43822. console.log( 'rings:', rings );//mesh间可能重叠 但换上贴图材质应该看不出(但只要searchRings时getSliceLines就不会重叠)
  43823. if(!rings)return
  43824. let planeMat2 = planeMat.clone(); planeMat2.opacity = 0.5;
  43825. var firstPos = points2d[0].clone();
  43826. firstPos.z = 0; //因为shape只读取了xy,所以位移下, 再算出最终位置,得到差距
  43827. firstPos.applyQuaternion(quaInverse);
  43828. var vec = originPoint0.clone().sub(firstPos);
  43829. rings.forEach(ring=>{
  43830. var shapeGeo = MeshDraw.getShapeGeo(ring.points);
  43831. var areaPlane = new Mesh(shapeGeo, planeMat2);
  43832. areaPlane.quaternion.copy(quaInverse);
  43833. areaPlane.position.copy(vec);
  43834. areaPlane.name = 'areaPlane_'+index;
  43835. splitSprites.add(areaPlane);
  43836. this.areaPlanes.push(areaPlane);
  43837. });
  43838. });
  43839. console.log(geometryNode.name, '中:');
  43840. console.log('removed point count: ', removedCount/* splitSprites.children.length */);
  43841. console.log(closeGroups);
  43842. console.log('comebine mesh Len:', useGroupCount);
  43843. /*
  43844. spritesGeo.setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(newPositions), 3));
  43845. spritesGeo.setIndex( newIndices );
  43846. let sprites = new THREE.Mesh(spritesGeo, getPlaneMat('use'))
  43847. sprites.name = geometryNode.name
  43848. sprites.position.copy(sceneNode.position)
  43849. sprites.rotation.copy(sceneNode.rotation)
  43850. sceneNode.sprites = sprites
  43851. sprites.pointsNode = sceneNode
  43852. if(geometryNode.level == 0){
  43853. let root = new THREE.Object3D;
  43854. root.name = 'spriteNodeRoot'
  43855. root.matrixAutoUpdate = false //同pointcloud一样不自动更新,直接使用
  43856. root.matrix.copy(this.matrix)
  43857. root.matrixWorld.copy(this.matrixWorld)
  43858. viewer.scene.scene.add(root)
  43859. this.spriteNodeRoot = root
  43860. }
  43861. this.spriteNodeRoot.add(sprites) */
  43862. console.log('computeTime: ' + (Date.now() - startTime));
  43863. }
  43864. //------------------
  43865. /*
  43866. viewer.scene.pointclouds[0].spriteNodeRoot.traverse(e=>e.material && (e.material = viewer.images360.cube.material))
  43867. viewer.scene.scene.children[12].visible = false
  43868. */
  43869. }
  43870. buildTexMesh(geometryNode,sceneNode){
  43871. if(geometryNode.level <= 0){
  43872. let startTime = Date.now();
  43873. let splitSprites = new Object3D;
  43874. splitSprites.name = 'splitSprites_'+geometryNode.name;
  43875. splitSprites.matrixAutoUpdate = false; //同pointcloud一样不自动更新,直接使用
  43876. splitSprites.matrix.copy(this.matrix);
  43877. splitSprites.matrixWorld.copy(this.matrixWorld);
  43878. viewer.scene.scene.add(splitSprites);
  43879. let spritesGeo = new BufferGeometry();
  43880. let scaleRatio = 1.4; //稍微放大些,填满缝隙
  43881. let spriteWidth1 = this.material.spacing / Math.pow(2, geometryNode.level);
  43882. let spriteWidth = spriteWidth1 * scaleRatio;
  43883. console.log('spriteWidth:',spriteWidth);
  43884. const removeChip = false;
  43885. let geometry = geometryNode.geometry;
  43886. let count = geometry.attributes.position.count;
  43887. //count = 4000
  43888. let position = geometry.attributes.position.array;
  43889. let normal = geometry.attributes.normal.array;
  43890. let i;
  43891. let up = new Vector3(0,1,0) , zeroVec = new Vector3; //up写成z向上居然结果一样
  43892. let positions = [];
  43893. let normals = [];
  43894. let newPositions = [];
  43895. //let newNormals = [];
  43896. let newIndices = [];
  43897. let cornerPoints = [new Vector3(-1,1,0),new Vector3(1,1,0),new Vector3(-1,-1,0),new Vector3(1,-1,0) ];
  43898. let indices = [0, 2, 1, 2, 3, 1];
  43899. cornerPoints.forEach(e=>e.multiplyScalar(spriteWidth/2));
  43900. let minDisSquare = spriteWidth1 * spriteWidth1 * 1.5;
  43901. let closeGroups = [];
  43902. let groupTolerateMaxPoint = 4;//组内点<=这个数的最后会被删除
  43903. let removedCount = 0;
  43904. for(i=0;i<count;i++){
  43905. let pos = new Vector3(position[3*i], position[3*i+1], position[3*i+2] );
  43906. let nor = new Vector3(normal[3*i],normal[3*i+1],normal[3*i+2]);
  43907. pos.nor = nor;
  43908. positions.push(pos);
  43909. normals.push(nor);
  43910. if(removeChip){
  43911. let groups = closeGroups.filter(group=>{
  43912. var hasClosed = group.some(p=>{
  43913. var dis = p.distanceToSquared(pos);
  43914. if(dis<minDisSquare){
  43915. //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
  43916. return dis / minDisSquare - p.nor.dot(nor) < 0
  43917. }
  43918. });
  43919. return hasClosed
  43920. });
  43921. if(groups.length == 0){//创建一个新的
  43922. var newGroup = [];
  43923. closeGroups.push(newGroup);
  43924. groups = [newGroup];
  43925. }
  43926. if(groups.length == 1){//直接加入原有的
  43927. pos.belongTo = groups[0];
  43928. }else if(groups.length>1){ // comebine多个组成一个
  43929. let newBigGroup = [];
  43930. groups.forEach(e=>{
  43931. newBigGroup.push(...e);
  43932. let index = closeGroups.indexOf(e);
  43933. closeGroups.splice(index, 1);
  43934. });
  43935. closeGroups.push(newBigGroup);
  43936. pos.belongTo = newBigGroup;
  43937. newBigGroup.forEach(e=>{e.belongTo = newBigGroup;});
  43938. }
  43939. pos.belongTo.push(pos);
  43940. }
  43941. }
  43942. for(i=0;i<count;i++){
  43943. let pos = positions[i];
  43944. let nor = normals[i];
  43945. if(Math.abs(nor.z)>0.2)continue
  43946. if(removeChip){
  43947. if(pos.belongTo.length <= groupTolerateMaxPoint){
  43948. let sprite = new Mesh(planeGeo, getPlaneMat(pos.belongTo, true));
  43949. sprite.lookAt(nor);
  43950. sprite.position.copy(pos);
  43951. sprite.scale.set(spriteWidth,spriteWidth,spriteWidth);
  43952. sprite.name = geometryNode.name+'_index'+i;
  43953. splitSprites.add(sprite);
  43954. removedCount ++;
  43955. continue
  43956. }else {
  43957. /*
  43958. let sprite = new THREE.Mesh(planeGeo, getPlaneMat(pos.belongTo))
  43959. sprite.lookAt(nor);
  43960. sprite.position.copy(pos)
  43961. sprite.scale.set(spriteWidth/3,spriteWidth/3,spriteWidth/3)
  43962. sprite.name = geometryNode.name+'_index'+i
  43963. splitSprites.add(sprite)
  43964. */
  43965. }
  43966. }
  43967. let matrix = (new Matrix4).lookAt( nor, zeroVec, up);
  43968. matrix.elements[12] = pos.x;
  43969. matrix.elements[13] = pos.y;
  43970. matrix.elements[14] = pos.z;
  43971. cornerPoints.forEach(p=>{
  43972. let point = p.clone();
  43973. point.applyMatrix4(matrix);
  43974. newPositions.push(...point.toArray());
  43975. //newNormals
  43976. });
  43977. indices.forEach(index=>{
  43978. newIndices.push(index + i*4);
  43979. });
  43980. }
  43981. /* closeGroups.forEach(e=>{
  43982. if(e.length <= groupTolerateMaxPoint )return
  43983. }) */
  43984. console.log('removed count: ', removedCount/* splitSprites.children.length */);
  43985. console.log(closeGroups);
  43986. console.log('computeTime: ' + (Date.now() - startTime));
  43987. spritesGeo.setAttribute('position', new Float32BufferAttribute(new Float32Array(newPositions), 3));
  43988. spritesGeo.setIndex( newIndices );
  43989. let sprites = new Mesh(spritesGeo, getPlaneMat('use'));
  43990. sprites.name = geometryNode.name;
  43991. sprites.position.copy(sceneNode.position);
  43992. sprites.rotation.copy(sceneNode.rotation);
  43993. sceneNode.sprites = sprites;
  43994. sprites.pointsNode = sceneNode;
  43995. if(geometryNode.level == 0){
  43996. let root = new Object3D;
  43997. root.name = 'spriteNodeRoot';
  43998. root.matrixAutoUpdate = false; //同pointcloud一样不自动更新,直接使用
  43999. root.matrix.copy(this.matrix);
  44000. root.matrixWorld.copy(this.matrixWorld);
  44001. viewer.scene.scene.add(root);
  44002. this.spriteNodeRoot = root;
  44003. }
  44004. this.spriteNodeRoot.add(sprites);
  44005. viewer.setObjectLayers(sprites,'sceneObjects');
  44006. }
  44007. }
  44008. updateVisibleBounds () {
  44009. let leafNodes = [];
  44010. for (let i = 0; i < this.visibleNodes.length; i++) {
  44011. let node = this.visibleNodes[i];
  44012. let isLeaf = true;
  44013. for (let j = 0; j < node.children.length; j++) {
  44014. let child = node.children[j];
  44015. if (child instanceof PointCloudOctreeNode) {
  44016. isLeaf = isLeaf && !child.sceneNode.visible;
  44017. } else if (child instanceof PointCloudOctreeGeometryNode) {
  44018. isLeaf = true;
  44019. }
  44020. }
  44021. if (isLeaf) {
  44022. leafNodes.push(node);
  44023. }
  44024. }
  44025. this.visibleBounds.min = new Vector3(Infinity, Infinity, Infinity);
  44026. this.visibleBounds.max = new Vector3(-Infinity, -Infinity, -Infinity);
  44027. for (let i = 0; i < leafNodes.length; i++) {
  44028. let node = leafNodes[i];
  44029. this.visibleBounds.expandByPoint(node.getBoundingBox().min);
  44030. this.visibleBounds.expandByPoint(node.getBoundingBox().max);
  44031. }
  44032. }
  44033. updateMaterial (material, visibleNodes, camera, renderer, resolution) {
  44034. material.fov = camera.fov * (Math.PI / 180);
  44035. /* material.screenWidth = renderer.domElement.clientWidth;
  44036. material.screenHeight = renderer.domElement.clientHeight; */
  44037. material.resolution = resolution;
  44038. //material.spacing = this.pcoGeometry.spacing; // * Math.max(this.scale.x, this.scale.y, this.scale.z); //应该不需要
  44039. material.near = camera.near;
  44040. material.far = camera.far;
  44041. material.uniforms.octreeSize.value = this.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  44042. }
  44043. computeVisibilityTextureData(nodes, camera){
  44044. if(Potree.measureTimings) performance.mark("computeVisibilityTextureData-start");
  44045. let data = new Uint8Array(nodes.length * 4);
  44046. let visibleNodeTextureOffsets = new Map();
  44047. // copy array
  44048. nodes = nodes.slice();
  44049. // sort by level and index, e.g. r, r0, r3, r4, r01, r07, r30, ...
  44050. let sort = function (a, b) {
  44051. let na = a.geometryNode.name;
  44052. let nb = b.geometryNode.name;
  44053. if (na.length !== nb.length) return na.length - nb.length;
  44054. if (na < nb) return -1;
  44055. if (na > nb) return 1;
  44056. return 0;
  44057. };
  44058. nodes.sort(sort);
  44059. let worldDir = new Vector3();
  44060. let nodeMap = new Map();
  44061. let offsetsToChild = new Array(nodes.length).fill(Infinity);
  44062. for(let i = 0; i < nodes.length; i++){
  44063. let node = nodes[i];
  44064. nodeMap.set(node.name, node);
  44065. visibleNodeTextureOffsets.set(node, i);
  44066. if(i > 0){
  44067. let index = parseInt(node.name.slice(-1));
  44068. let parentName = node.name.slice(0, -1);
  44069. let parent = nodeMap.get(parentName);
  44070. let parentOffset = visibleNodeTextureOffsets.get(parent);
  44071. let parentOffsetToChild = (i - parentOffset);
  44072. offsetsToChild[parentOffset] = Math.min(offsetsToChild[parentOffset], parentOffsetToChild);
  44073. data[parentOffset * 4 + 0] = data[parentOffset * 4 + 0] | (1 << index);
  44074. data[parentOffset * 4 + 1] = (offsetsToChild[parentOffset] >> 8);
  44075. data[parentOffset * 4 + 2] = (offsetsToChild[parentOffset] % 256);
  44076. }
  44077. let density = node.geometryNode.density;
  44078. if(typeof density === "number"){
  44079. let lodOffset = Math.log2(density) / 2 - 1.5;
  44080. let offsetUint8 = (lodOffset + 10) * 10;
  44081. data[i * 4 + 3] = offsetUint8;
  44082. }else {
  44083. data[i * 4 + 3] = 100;
  44084. }
  44085. }
  44086. if(Potree.measureTimings){
  44087. performance.mark("computeVisibilityTextureData-end");
  44088. performance.measure("render.computeVisibilityTextureData", "computeVisibilityTextureData-start", "computeVisibilityTextureData-end");
  44089. }
  44090. return {
  44091. data: data,
  44092. offsets: visibleNodeTextureOffsets
  44093. };
  44094. }
  44095. nodeIntersectsProfile (node, profile) {
  44096. let bbWorld = node.boundingBox.clone().applyMatrix4(this.matrixWorld);
  44097. let bsWorld = bbWorld.getBoundingSphere(new Sphere());
  44098. let intersects = false;
  44099. for (let i = 0; i < profile.points.length - 1; i++) {
  44100. let start = new Vector3(profile.points[i + 0].x, profile.points[i + 0].y, bsWorld.center.z);
  44101. let end = new Vector3(profile.points[i + 1].x, profile.points[i + 1].y, bsWorld.center.z);
  44102. let closest = new Line3(start, end).closestPointToPoint(bsWorld.center, true, new Vector3());
  44103. let distance = closest.distanceTo(bsWorld.center);
  44104. intersects = intersects || (distance < (bsWorld.radius + profile.width));
  44105. }
  44106. //console.log(`${node.name}: ${intersects}`);
  44107. return intersects;
  44108. }
  44109. deepestNodeAt(position){
  44110. const toObjectSpace = this.matrixWorld.clone().invert();
  44111. const objPos = position.clone().applyMatrix4(toObjectSpace);
  44112. let current = this.root;
  44113. while(true){
  44114. let containingChild = null;
  44115. for(const child of current.children){
  44116. if(child !== undefined){
  44117. if(child.getBoundingBox().containsPoint(objPos)){
  44118. containingChild = child;
  44119. }
  44120. }
  44121. }
  44122. if(containingChild !== null && containingChild instanceof PointCloudOctreeNode){
  44123. current = containingChild;
  44124. }else {
  44125. break;
  44126. }
  44127. }
  44128. const deepest = current;
  44129. return deepest;
  44130. }
  44131. nodesOnRay (nodes, ray) {
  44132. let nodesOnRay = [];
  44133. let _ray = ray.clone();
  44134. for (let i = 0; i < nodes.length; i++) {
  44135. let node = nodes[i];
  44136. let sphere = node.getBoundingSphere().clone().applyMatrix4(this.matrixWorld);
  44137. if (_ray.intersectsSphere(sphere)) {
  44138. nodesOnRay.push(node);
  44139. }
  44140. }
  44141. return nodesOnRay;
  44142. }
  44143. updateMatrixWorld (force) {
  44144. if (this.matrixAutoUpdate === true) this.updateMatrix();
  44145. if (this.matrixWorldNeedsUpdate === true || force === true) {
  44146. if (!this.parent) {
  44147. this.matrixWorld.copy(this.matrix);
  44148. } else {
  44149. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  44150. }
  44151. this.matrixWorldNeedsUpdate = false;
  44152. force = true;
  44153. }
  44154. }
  44155. hideDescendants (object) {
  44156. let stack = [];
  44157. for (let i = 0; i < object.children.length; i++) {
  44158. let child = object.children[i];
  44159. if (child.visible) {
  44160. stack.push(child);
  44161. }
  44162. }
  44163. while (stack.length > 0) {
  44164. let object = stack.shift();
  44165. object.visible = false;
  44166. for (let i = 0; i < object.children.length; i++) {
  44167. let child = object.children[i];
  44168. if (child.visible) {
  44169. stack.push(child);
  44170. }
  44171. }
  44172. }
  44173. }
  44174. moveToOrigin () {
  44175. this.position.set(0, 0, 0);
  44176. this.updateMatrixWorld(true);
  44177. let box = this.boundingBox;
  44178. let transform = this.matrixWorld;
  44179. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  44180. this.position.set(0, 0, 0).sub(tBox.getCenter(new Vector3()));
  44181. };
  44182. moveToGroundPlane () {
  44183. this.updateMatrixWorld(true);
  44184. let box = this.boundingBox;
  44185. let transform = this.matrixWorld;
  44186. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  44187. this.position.y += -tBox.min.y;
  44188. };
  44189. getBoundingBoxWorld () {
  44190. this.updateMatrixWorld(true);
  44191. let box = this.boundingBox;
  44192. let transform = this.matrixWorld;
  44193. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  44194. return tBox;
  44195. };
  44196. /**
  44197. * returns points inside the profile points
  44198. *
  44199. * maxDepth: search points up to the given octree depth
  44200. *
  44201. *
  44202. * The return value is an array with all segments of the profile path
  44203. * let segment = {
  44204. * start: THREE.Vector3,
  44205. * end: THREE.Vector3,
  44206. * points: {}
  44207. * project: function()
  44208. * };
  44209. *
  44210. * The project() function inside each segment can be used to transform
  44211. * that segments point coordinates to line up along the x-axis.
  44212. *
  44213. *
  44214. */
  44215. getPointsInProfile (profile, maxDepth, callback) {
  44216. if (callback) {
  44217. let request = new Potree.ProfileRequest(this, profile, maxDepth, callback);
  44218. this.profileRequests.push(request);
  44219. return request;
  44220. }
  44221. let points = {
  44222. segments: [],
  44223. boundingBox: new Box3(),
  44224. projectedBoundingBox: new Box2()
  44225. };
  44226. // evaluate segments
  44227. for (let i = 0; i < profile.points.length - 1; i++) {
  44228. let start = profile.points[i];
  44229. let end = profile.points[i + 1];
  44230. let ps = this.getProfile(start, end, profile.width, maxDepth);
  44231. let segment = {
  44232. start: start,
  44233. end: end,
  44234. points: ps,
  44235. project: null
  44236. };
  44237. points.segments.push(segment);
  44238. points.boundingBox.expandByPoint(ps.boundingBox.min);
  44239. points.boundingBox.expandByPoint(ps.boundingBox.max);
  44240. }
  44241. // add projection functions to the segments
  44242. let mileage = new Vector3();
  44243. for (let i = 0; i < points.segments.length; i++) {
  44244. let segment = points.segments[i];
  44245. let start = segment.start;
  44246. let end = segment.end;
  44247. let project = (function (_start, _end, _mileage, _boundingBox) {
  44248. let start = _start;
  44249. let end = _end;
  44250. let mileage = _mileage;
  44251. let boundingBox = _boundingBox;
  44252. let xAxis = new Vector3(1, 0, 0);
  44253. let dir = new Vector3().subVectors(end, start);
  44254. dir.y = 0;
  44255. dir.normalize();
  44256. let alpha = Math.acos(xAxis.dot(dir));
  44257. if (dir.z > 0) {
  44258. alpha = -alpha;
  44259. }
  44260. return function (position) {
  44261. let toOrigin = new Matrix4().makeTranslation(-start.x, -boundingBox.min.y, -start.z);
  44262. let alignWithX = new Matrix4().makeRotationY(-alpha);
  44263. let applyMileage = new Matrix4().makeTranslation(mileage.x, 0, 0);
  44264. let pos = position.clone();
  44265. pos.applyMatrix4(toOrigin);
  44266. pos.applyMatrix4(alignWithX);
  44267. pos.applyMatrix4(applyMileage);
  44268. return pos;
  44269. };
  44270. }(start, end, mileage.clone(), points.boundingBox.clone()));
  44271. segment.project = project;
  44272. mileage.x += new Vector3(start.x, 0, start.z).distanceTo(new Vector3(end.x, 0, end.z));
  44273. mileage.y += end.y - start.y;
  44274. }
  44275. points.projectedBoundingBox.min.x = 0;
  44276. points.projectedBoundingBox.min.y = points.boundingBox.min.y;
  44277. points.projectedBoundingBox.max.x = mileage.x;
  44278. points.projectedBoundingBox.max.y = points.boundingBox.max.y;
  44279. return points;
  44280. }
  44281. /**
  44282. * returns points inside the given profile bounds.
  44283. *
  44284. * start:
  44285. * end:
  44286. * width:
  44287. * depth: search points up to the given octree depth
  44288. * callback: if specified, points are loaded before searching
  44289. *
  44290. *
  44291. */
  44292. getProfile (start, end, width, depth, callback) {
  44293. let request = new Potree.ProfileRequest(start, end, width, depth, callback);
  44294. this.profileRequests.push(request);
  44295. };
  44296. getVisibleExtent () {
  44297. return this.visibleBounds.applyMatrix4(this.matrixWorld);
  44298. };
  44299. intersectsPoint(position){
  44300. let rootAvailable = this.pcoGeometry.root && this.pcoGeometry.root.geometry;
  44301. if(!rootAvailable){
  44302. return false;
  44303. }
  44304. if(typeof this.signedDistanceField === "undefined"){
  44305. const resolution = 32;
  44306. const field = new Float32Array(resolution ** 3).fill(Infinity);
  44307. const positions = this.pcoGeometry.root.geometry.attributes.position;
  44308. const boundingBox = this.boundingBox;
  44309. const n = positions.count;
  44310. for(let i = 0; i < n; i = i + 3){
  44311. const x = positions.array[3 * i + 0];
  44312. const y = positions.array[3 * i + 1];
  44313. const z = positions.array[3 * i + 2];
  44314. const ix = parseInt(Math.min(resolution * (x / boundingBox.max.x), resolution - 1));
  44315. const iy = parseInt(Math.min(resolution * (y / boundingBox.max.y), resolution - 1));
  44316. const iz = parseInt(Math.min(resolution * (z / boundingBox.max.z), resolution - 1));
  44317. const index = ix + iy * resolution + iz * resolution * resolution;
  44318. field[index] = 0;
  44319. }
  44320. const sdf = {
  44321. resolution: resolution,
  44322. field: field,
  44323. };
  44324. this.signedDistanceField = sdf;
  44325. }
  44326. {
  44327. const sdf = this.signedDistanceField;
  44328. const boundingBox = this.boundingBox;
  44329. const toObjectSpace = this.matrixWorld.clone().invert();
  44330. const objPos = position.clone().applyMatrix4(toObjectSpace);
  44331. const resolution = sdf.resolution;
  44332. const ix = parseInt(resolution * (objPos.x / boundingBox.max.x));
  44333. const iy = parseInt(resolution * (objPos.y / boundingBox.max.y));
  44334. const iz = parseInt(resolution * (objPos.z / boundingBox.max.z));
  44335. if(ix < 0 || iy < 0 || iz < 0){
  44336. return false;
  44337. }
  44338. if(ix >= resolution || iy >= resolution || iz >= resolution){
  44339. return false;
  44340. }
  44341. const index = ix + iy * resolution + iz * resolution * resolution;
  44342. const value = sdf.field[index];
  44343. if(value === 0){
  44344. return true;
  44345. }
  44346. }
  44347. return false;
  44348. }
  44349. /**
  44350. *
  44351. *
  44352. *
  44353. * params.pickWindowSize: Look for points inside a pixel window of this size.
  44354. * Use odd values: 1, 3, 5, ...
  44355. *
  44356. *
  44357. * TODO: only draw pixels that are actually read with readPixels().
  44358. *
  44359. */
  44360. pick(viewer, viewport, camera, ray, params = {}){
  44361. let renderer = viewer.renderer;
  44362. let pRenderer = viewer.pRenderer;
  44363. performance.mark("pick-start");
  44364. let getVal = (a, b) => a != void 0 ? a : b;
  44365. let pickWindowSize_ = MathUtils.clamp( Math.round((1.1-this.maxLevel/this.nodeMaxLevel)*80), 5, 100);
  44366. let pickWindowSize = getVal(params.pickWindowSize, pickWindowSize_ ); /* 65 */ //拾取像素边长,越小越精准,但点云稀疏的话可能容易出现识别不到的情况。 另外左下侧会有缝隙无法识别到,缝隙大小和这个值有关
  44367. let pickOutsideClipRegion = getVal(params.pickOutsideClipRegion, false);
  44368. let size = viewport ? viewport.resolution : renderer.getSize(new Vector2$1());
  44369. let width = Math.ceil(getVal(params.width, size.width)); //renderTarget大小。影响识别精度
  44370. let height = Math.ceil(getVal(params.height, size.height));
  44371. let screenshot = ()=>{
  44372. if(window.testScreen){
  44373. let dataUrl = Potree.Utils.renderTargetToDataUrl(pickState.renderTarget, width, height, renderer);
  44374. Common.downloadFile(dataUrl, 'screenshot.jpg'); //为什么图片上不是只有pickWindowSize区域有颜色??
  44375. window.testScreen = 0;
  44376. }
  44377. };
  44378. let pointSizeType = getVal(params.pointSizeType, this.material.pointSizeType);
  44379. let pointSize = getVal(params.pointSize, this.material.size);
  44380. let nodes = this.nodesOnRay(this.visibleNodes, ray);
  44381. if (nodes.length === 0) {
  44382. return null;
  44383. }
  44384. //console.log('nodes.length != 0', this.name)
  44385. if (!this.pickState) {
  44386. let scene = new Scene();
  44387. let material = new Potree.PointCloudMaterial();
  44388. material.activeAttributeName = "indices";
  44389. let renderTarget = new WebGLRenderTarget(
  44390. 1, 1,
  44391. { minFilter: LinearFilter,
  44392. magFilter: NearestFilter,
  44393. format: RGBAFormat }
  44394. );
  44395. this.pickState = {
  44396. renderTarget: renderTarget,
  44397. material: material,
  44398. scene: scene
  44399. };
  44400. };
  44401. let pickState = this.pickState;
  44402. let pickMaterial = pickState.material;
  44403. { // update pick material
  44404. pickMaterial.pointSizeType = pointSizeType;
  44405. //pickMaterial.shape = this.material.shape;
  44406. pickMaterial.shape = Potree.PointShape.PARABOLOID;
  44407. pickMaterial.uniforms.uFilterReturnNumberRange.value = this.material.uniforms.uFilterReturnNumberRange.value;
  44408. pickMaterial.uniforms.uFilterNumberOfReturnsRange.value = this.material.uniforms.uFilterNumberOfReturnsRange.value;
  44409. pickMaterial.uniforms.uFilterGPSTimeClipRange.value = this.material.uniforms.uFilterGPSTimeClipRange.value;
  44410. pickMaterial.uniforms.uFilterPointSourceIDClipRange.value = this.material.uniforms.uFilterPointSourceIDClipRange.value;
  44411. pickMaterial.activeAttributeName = "indices";
  44412. pickMaterial.size = pointSize;
  44413. pickMaterial.uniforms.minSize.value = this.material.uniforms.minSize.value;
  44414. pickMaterial.uniforms.maxSize.value = this.material.uniforms.maxSize.value;
  44415. pickMaterial.classification = this.material.classification;
  44416. pickMaterial.recomputeClassification();
  44417. if(params.pickClipped){
  44418. pickMaterial.clipBoxes = this.material.clipBoxes;
  44419. pickMaterial.uniforms.clipBoxes = this.material.uniforms.clipBoxes;
  44420. if(this.material.clipTask === Potree.ClipTask.HIGHLIGHT){
  44421. pickMaterial.clipTask = Potree.ClipTask.NONE;
  44422. }else {
  44423. pickMaterial.clipTask = this.material.clipTask;
  44424. }
  44425. pickMaterial.clipMethod = this.material.clipMethod;
  44426. }else {
  44427. pickMaterial.clipBoxes = [];
  44428. }
  44429. this.updateMaterial(pickMaterial, nodes, camera, renderer, new Vector2$1(width, height));
  44430. }
  44431. pickState.renderTarget.setSize(width, height); //仅绘制屏幕大小的,而不乘以devicePixelRatio
  44432. let pixelPos = new Vector2$1(params.x, params.y);
  44433. let gl = renderer.getContext();
  44434. gl.enable(gl.SCISSOR_TEST);
  44435. gl.scissor( //规定渲染范围,只渲染一小块
  44436. parseInt(pixelPos.x - (pickWindowSize - 1) / 2),
  44437. parseInt(pixelPos.y - (pickWindowSize - 1) / 2),
  44438. parseInt(pickWindowSize), parseInt(pickWindowSize));
  44439. renderer.state.buffers.depth.setTest(pickMaterial.depthTest);
  44440. renderer.state.buffers.depth.setMask(pickMaterial.depthWrite);
  44441. renderer.state.setBlending(NoBlending);
  44442. { // RENDER
  44443. renderer.setRenderTarget(pickState.renderTarget);
  44444. gl.clearColor(0, 0, 0, 0);
  44445. renderer.clear(true, true, true);
  44446. let tmp = this.material;
  44447. this.material = pickMaterial;
  44448. pRenderer.renderOctree(this, nodes, camera, pickState.renderTarget);
  44449. screenshot();
  44450. this.material = tmp;
  44451. }
  44452. let clamp = (number, min, max) => Math.min(Math.max(min, number), max);
  44453. let x = parseInt(clamp(pixelPos.x - (pickWindowSize - 1) / 2, 0, width));
  44454. let y = parseInt(clamp(pixelPos.y - (pickWindowSize - 1) / 2, 0, height));
  44455. /* let w = parseInt(Math.min(x + pickWindowSize, width) - x);
  44456. let h = parseInt(Math.min(y + pickWindowSize, height) - y); */
  44457. let pixelCount = pickWindowSize * pickWindowSize;//w * h;
  44458. let buffer = new Uint8Array(4 * pixelCount);
  44459. //w<pickWindowSize会报错
  44460. gl.readPixels(x, y, pickWindowSize, pickWindowSize, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
  44461. renderer.setRenderTarget(null);
  44462. renderer.state.reset();
  44463. renderer.setScissorTest(false);
  44464. gl.disable(gl.SCISSOR_TEST);
  44465. let pixels = buffer;
  44466. let ibuffer = new Uint32Array(buffer.buffer); //四个数整合成一个
  44467. // find closest hit inside pixelWindow boundaries
  44468. let min = Number.MAX_VALUE;
  44469. let hits = [];
  44470. for (let u = 0; u < pickWindowSize; u++) {
  44471. for (let v = 0; v < pickWindowSize; v++) {
  44472. let offset = (u + v * pickWindowSize);
  44473. let distance = Math.pow(u - (pickWindowSize - 1) / 2, 2) + Math.pow(v - (pickWindowSize - 1) / 2, 2);
  44474. let pcIndex = pixels[4 * offset + 3];//nodes index(第四位)
  44475. pixels[4 * offset + 3] = 0; //去除nodes index后剩下的是index(前三位)
  44476. let pIndex = ibuffer[offset]; //index
  44477. if(!(pcIndex === 0 && pIndex === 0) && (pcIndex !== undefined) && (pIndex !== undefined)){
  44478. let hit = {
  44479. pIndex: pIndex,
  44480. pcIndex: pcIndex,
  44481. distanceToCenter: distance
  44482. };
  44483. if(params.all){
  44484. hits.push(hit);
  44485. }else {
  44486. if(hits.length > 0){
  44487. if(distance < hits[0].distanceToCenter){
  44488. hits[0] = hit;
  44489. }
  44490. }else {
  44491. hits.push(hit);
  44492. }
  44493. }
  44494. }
  44495. }
  44496. }
  44497. // { // DEBUG: show panel with pick image
  44498. // let img = Utils.pixelsArrayToImage(buffer, w, h);
  44499. // let screenshot = img.src;
  44500. // if(!this.debugDIV){
  44501. // this.debugDIV = $(`
  44502. // <div id="pickDebug"
  44503. // style="position: absolute;
  44504. // right: 400px; width: 300px;
  44505. // bottom: 44px; width: 300px;
  44506. // z-index: 1000;
  44507. // "></div>`);
  44508. // $(document.body).append(this.debugDIV);
  44509. // }
  44510. // this.debugDIV.empty();
  44511. // this.debugDIV.append($(`<img src="${screenshot}"
  44512. // style="transform: scaleY(-1); width: 300px"/>`));
  44513. // //$(this.debugWindow.document).append($(`<img src="${screenshot}"/>`));
  44514. // //this.debugWindow.document.write('<img src="'+screenshot+'"/>');
  44515. // }
  44516. for(let hit of hits){
  44517. let point = {};
  44518. if (!nodes[hit.pcIndex]) {
  44519. return null;
  44520. }
  44521. let node = nodes[hit.pcIndex];
  44522. let pc = node.sceneNode;
  44523. let geometry = node.geometryNode.geometry;
  44524. for(let attributeName in geometry.attributes){
  44525. let attribute = geometry.attributes[attributeName];
  44526. if (attributeName === 'position') {
  44527. let x = attribute.array[3 * hit.pIndex + 0];
  44528. let y = attribute.array[3 * hit.pIndex + 1];
  44529. let z = attribute.array[3 * hit.pIndex + 2];
  44530. let position = new Vector3(x, y, z);
  44531. position.applyMatrix4( pc.matrixWorld );
  44532. point[attributeName] = position;
  44533. } else if (attributeName === 'indices') {
  44534. } else {
  44535. let values = attribute.array.slice(attribute.itemSize * hit.pIndex, attribute.itemSize * (hit.pIndex + 1)) ;
  44536. if(attribute.potree){
  44537. const {scale, offset} = attribute.potree;
  44538. values = values.map(v => v / scale + offset);
  44539. }
  44540. point[attributeName] = values;
  44541. //debugger;
  44542. //if (values.itemSize === 1) {
  44543. // point[attribute.name] = values.array[hit.pIndex];
  44544. //} else {
  44545. // let value = [];
  44546. // for (let j = 0; j < values.itemSize; j++) {
  44547. // value.push(values.array[values.itemSize * hit.pIndex + j]);
  44548. // }
  44549. // point[attribute.name] = value;
  44550. //}
  44551. }
  44552. }
  44553. hit.point = point;
  44554. }
  44555. performance.mark("pick-end");
  44556. performance.measure("pick", "pick-start", "pick-end");
  44557. if(params.all){
  44558. return hits.map(hit => hit.point);
  44559. }else {
  44560. if(hits.length === 0){
  44561. return null;
  44562. }else {
  44563. return hits[0].point;
  44564. //let sorted = hits.sort( (a, b) => a.distanceToCenter - b.distanceToCenter);
  44565. //return sorted[0].point;
  44566. }
  44567. }
  44568. };
  44569. * getFittedBoxGen(boxNode){//???
  44570. let start = performance.now();
  44571. let shrinkedLocalBounds = new Box3();
  44572. let worldToBox = boxNode.matrixWorld.clone().invert();
  44573. for(let node of this.visibleNodes){
  44574. if(!node.sceneNode){
  44575. continue;
  44576. }
  44577. let buffer = node.geometryNode.buffer;
  44578. let posOffset = buffer.offset("position");
  44579. let stride = buffer.stride;
  44580. let view = new DataView(buffer.data);
  44581. let objectToBox = new Matrix4().multiplyMatrices(worldToBox, node.sceneNode.matrixWorld);
  44582. let pos = new Vector4();
  44583. for(let i = 0; i < buffer.numElements; i++){
  44584. let x = view.getFloat32(i * stride + posOffset + 0, true);
  44585. let y = view.getFloat32(i * stride + posOffset + 4, true);
  44586. let z = view.getFloat32(i * stride + posOffset + 8, true);
  44587. pos.set(x, y, z, 1);
  44588. pos.applyMatrix4(objectToBox);
  44589. if(-0.5 < pos.x && pos.x < 0.5){
  44590. if(-0.5 < pos.y && pos.y < 0.5){
  44591. if(-0.5 < pos.z && pos.z < 0.5){
  44592. shrinkedLocalBounds.expandByPoint(pos);
  44593. }
  44594. }
  44595. }
  44596. }
  44597. yield;
  44598. }
  44599. let fittedPosition = shrinkedLocalBounds.getCenter(new Vector3()).applyMatrix4(boxNode.matrixWorld);
  44600. let fitted = new Object3D();
  44601. fitted.position.copy(fittedPosition);
  44602. fitted.scale.copy(boxNode.scale);
  44603. fitted.rotation.copy(boxNode.rotation);
  44604. let ds = new Vector3().subVectors(shrinkedLocalBounds.max, shrinkedLocalBounds.min);
  44605. fitted.scale.multiply(ds);
  44606. let duration = performance.now() - start;
  44607. console.log("duration: ", duration);
  44608. yield fitted;
  44609. }
  44610. getFittedBox(boxNode, maxLevel = Infinity){
  44611. maxLevel = Infinity;
  44612. let start = performance.now();
  44613. let shrinkedLocalBounds = new Box3();
  44614. let worldToBox = boxNode.matrixWorld.clone().invert();
  44615. for(let node of this.visibleNodes){
  44616. if(!node.sceneNode || node.getLevel() > maxLevel){
  44617. continue;
  44618. }
  44619. let buffer = node.geometryNode.buffer;
  44620. let posOffset = buffer.offset("position");
  44621. let stride = buffer.stride;
  44622. let view = new DataView(buffer.data);
  44623. let objectToBox = new Matrix4().multiplyMatrices(worldToBox, node.sceneNode.matrixWorld);
  44624. let pos = new Vector4();
  44625. for(let i = 0; i < buffer.numElements; i++){
  44626. let x = view.getFloat32(i * stride + posOffset + 0, true);
  44627. let y = view.getFloat32(i * stride + posOffset + 4, true);
  44628. let z = view.getFloat32(i * stride + posOffset + 8, true);
  44629. pos.set(x, y, z, 1);
  44630. pos.applyMatrix4(objectToBox);
  44631. if(-0.5 < pos.x && pos.x < 0.5){
  44632. if(-0.5 < pos.y && pos.y < 0.5){
  44633. if(-0.5 < pos.z && pos.z < 0.5){
  44634. shrinkedLocalBounds.expandByPoint(pos);
  44635. }
  44636. }
  44637. }
  44638. }
  44639. }
  44640. let fittedPosition = shrinkedLocalBounds.getCenter(new Vector3()).applyMatrix4(boxNode.matrixWorld);
  44641. let fitted = new Object3D();
  44642. fitted.position.copy(fittedPosition);
  44643. fitted.scale.copy(boxNode.scale);
  44644. fitted.rotation.copy(boxNode.rotation);
  44645. let ds = new Vector3().subVectors(shrinkedLocalBounds.max, shrinkedLocalBounds.min);
  44646. fitted.scale.multiply(ds);
  44647. let duration = performance.now() - start;
  44648. console.log("duration: ", duration);
  44649. return fitted;
  44650. }
  44651. get progress () {
  44652. return this.visibleNodes.length / this.visibleGeometry.length;
  44653. }
  44654. find(name){
  44655. let node = null;
  44656. for(let char of name){
  44657. if(char === "r"){
  44658. node = this.root;
  44659. }else {
  44660. node = node.children[char];
  44661. }
  44662. }
  44663. return node;
  44664. }
  44665. get visible(){
  44666. return this._visible;
  44667. }
  44668. set visible(value){
  44669. if(value !== this._visible){
  44670. this._visible = value;
  44671. this.dispatchEvent({type: 'visibility_changed', pointcloud: this});
  44672. }
  44673. }
  44674. // 设置点大小
  44675. changePointSize(num, sizeFitToLevel) {
  44676. if(this.material.pointSizeType != PointSizeType.ATTENUATED){
  44677. return num && (this.material.size = num)
  44678. }
  44679. if (num == void 0) {
  44680. num = this.temp.pointSize;
  44681. } else {
  44682. this.temp.pointSize = num;
  44683. }
  44684. num /= (Potree.config.material.realPointSize / Potree.config.material.pointSize); //兼容
  44685. num = Math.pow(num, 1.05) * 6;
  44686. if(sizeFitToLevel || Potree.settings.sizeFitToLevel){//按照点云质量来调整的版本: 近似将pointSizeType换成ADAPTIVE
  44687. let str = this.temp.pointSize+':'+this.maxLevel+':'+this.nodeMaxLevel;
  44688. let value = this.temp.sizeFitToLevel[str]; //储存。防止每次渲染(反复切换density)都要算。
  44689. if(value){
  44690. this.material.size = value;
  44691. }else {
  44692. let base = this.material.spacing / Math.pow(2, this.maxLevel); //点云大小在level为0时设置为spacing,每长一级,大小就除以2
  44693. base *= this.nodeMaxLevel > 0 ? Math.max(0.1, Math.pow(this.maxLevel / this.nodeMaxLevel, 1.3)) : 0.1; //低质量的缩小点,因为视觉上看太大了。navvis是不铺满的,我们也留一点缝隙
  44694. this.material.size = base * 3 * num;/* * window.devicePixelRatio */
  44695. //在t-8BCqxQAr93 会议室 和 t-e2Kb2iU 隧道 两个场景里调节,因为它们的spacing相差较大,观察会议室墙壁的龟裂程度
  44696. this.temp.sizeFitToLevel[str] = this.material.size;
  44697. }
  44698. }else {
  44699. let base = 0.007; //let base = this.material.spacing / Math.pow(2, this.nodeMaxLevel) //点云大小在level为0时设置为spacing,每长一级,大小就除以2
  44700. //base的数值理论上应该是右侧算出来的,但发现有的场景nodeMaxLevel和nodeMaxLevelPredict差别较大的点云显示也过大,而直接换成固定值反而可以适应所有场景。该固定值来源于 getHighestNodeSpacing 最小值,修改了下。(会不会是我们的相机其实该值是固定的,根据该值算出的spacing才是有误差的? 如果换了相机是否要改值?)
  44701. this.material.size = base * 5 * num; /* * window.devicePixelRatio */
  44702. }
  44703. //console.log('changePointSize ' + this.dataset_id + ' , num : ' + num + ' , size : ' + this.material.size, this.material.spacing)
  44704. }
  44705. // 设置点透明度
  44706. changePointOpacity(num, canMoreThanOne) {
  44707. //num:0-1 navvis用的是亮度
  44708. if (num == void 0) {
  44709. num = this.temp.pointOpacity;
  44710. } else {
  44711. this.temp.pointOpacity = num;
  44712. }
  44713. if (num == 1) {
  44714. this.material.opacity = 1;
  44715. } else {
  44716. let str = (Potree.settings.sizeFitToLevel?'sizeFit:':'')+ (canMoreThanOne ? 'canMoreThanOne:':'') +this.temp.pointOpacity+':'+this.maxLevel+':'+this.nodeMaxLevel;
  44717. let value = this.temp.opacity[str]; //储存。防止每次渲染(反复切换density)都要算。
  44718. if(value){
  44719. this.material.opacity = value;
  44720. }else {
  44721. if(Potree.settings.sizeFitToLevel){//按照点云质量来调整的版本:
  44722. let base = this.material.spacing / Math.pow(1.4, this.maxLevel); //随着level提高,点云重叠几率增多
  44723. let minBase = this.material.spacing / Math.pow(1.4, this.nodeMaxLevel);
  44724. let ratio = Math.min(1 / base, 1 / minBase / 3); //ratio为一个能使opacity不大于1 的 乘量,minBase要除以一个数,该数调越大减弱效果越强。level越低opacity和面板越接,level越高效果越弱,以减免过度重叠后的亮度。
  44725. this.material.opacity = base * ratio * num;
  44726. if(!canMoreThanOne){
  44727. this.material.opacity = MathUtils.clamp(this.material.opacity, 0, 0.999); //到1就不透明了(可能出现一段一样)
  44728. }
  44729. }else {
  44730. let base = this.material.spacing / Math.pow(1.8, this.maxLevel);
  44731. let minBase = this.material.spacing / Math.pow(1.8, this.nodeMaxLevel);
  44732. //console.log(1 / base, 1 / minBase / 6)
  44733. let ratio = Math.min(1 / base, 1 / minBase / 6); //ratio为一个能使opacity不大于1 的 乘量,minBase要除以一个数,该数调越大减弱效果越强。level越低opacity和面板越接,level越高效果越弱,以减免过度重叠后的亮度。
  44734. this.material.opacity = base * ratio * num;
  44735. if(!canMoreThanOne){
  44736. this.material.opacity = MathUtils.clamp(this.material.opacity, 0, 0.999); //到1就不透明了(可能出现一段一样)
  44737. }
  44738. }
  44739. this.temp.opacity[str] = this.material.opacity;
  44740. }
  44741. //缺点:防止颜色过亮主要是相机离远时,当在漫游点处由于离点云太近,可能会导致高质量点云看起来很暗。
  44742. }
  44743. //console.log('changePointOpacity ' + this.dataset_id + ', num : ' + num + ' , opacity : ' + this.material.opacity) //检查是否做到了低质量时num==opacity,中质量opacity稍小于num,高质量更小
  44744. }
  44745. updateBound(){
  44746. var boundingBox_ = this.pcoGeometry.tightBoundingBox.clone().applyMatrix4(this.matrixWorld);
  44747. this.bound = boundingBox_;
  44748. }
  44749. getPanosBound(){
  44750. if(this.panos.length > 0){
  44751. let minSize = new Vector3(1,1,1);
  44752. this.panosBound = math.getBoundByPoints(this.panos.map(e=>e.position), minSize);
  44753. }else {
  44754. this.panosBound = null;
  44755. }
  44756. }
  44757. getUnrotBoundPoint(type){//获取没有旋转的tightBounding的水平四个点
  44758. //如果alighment支持任意轴旋转,水平面上看到的可能就是六边形了,失去意义,到时候不能用这个。也可以若只绕z旋转, 使用tightBoundingBox,否则bound
  44759. let bound = this.pcoGeometry.tightBoundingBox;
  44760. if(type == 'all'){
  44761. return [new Vector3(bound.min.x, bound.min.y, bound.min.z),
  44762. new Vector3(bound.max.x, bound.min.y, bound.min.z),
  44763. new Vector3(bound.max.x, bound.max.y,bound.min.z),
  44764. new Vector3(bound.min.x, bound.max.y,bound.min.z),
  44765. new Vector3(bound.min.x, bound.min.y, bound.max.z),
  44766. new Vector3(bound.max.x, bound.min.y, bound.max.z),
  44767. new Vector3(bound.max.x, bound.max.y,bound.max.z),
  44768. new Vector3(bound.min.x, bound.max.y,bound.max.z),
  44769. ].map(e=>e.applyMatrix4(this.matrixWorld))
  44770. }else
  44771. return [new Vector3(bound.min.x, bound.min.y,0),
  44772. new Vector3(bound.max.x, bound.min.y,0),
  44773. new Vector3(bound.max.x, bound.max.y,0),
  44774. new Vector3(bound.min.x, bound.max.y,0),
  44775. ].map(e=>e.applyMatrix4(this.matrixWorld))
  44776. }
  44777. ifContainsPoint(pos){
  44778. if(!this.bound || !this.bound.containsPoint(pos))return
  44779. var points = this.getUnrotBoundPoint();
  44780. return math.isPointInArea(points, null, pos)
  44781. }
  44782. getVolume(){
  44783. var points = this.getUnrotBoundPoint();
  44784. var area = Math.abs(math.getArea(points));
  44785. return area * (this.bound.max.z - this.bound.min.z)
  44786. }
  44787. //数据集的显示影响到其下的:点云、marker .不会影响地图上的显示
  44788. /*
  44789. updateVisible(reason, ifShow){//当所有加入的条件都不为false时才显示
  44790. if(ifShow){
  44791. var index = this.unvisibleReasons.indexOf(reason);
  44792. index > -1 && this.unvisibleReasons.splice(index, 1);
  44793. if(this.unvisibleReasons.length == 0){
  44794. this.visible = true;
  44795. this.dispatchEvent({
  44796. type: 'isVisible'
  44797. visible:true
  44798. })
  44799. }
  44800. }else {
  44801. if(!this.unvisibleReasons.includes(reason)) this.unvisibleReasons.push(reason);
  44802. this.visible = false;
  44803. this.dispatchEvent({
  44804. type: 'isVisible'
  44805. visible:false
  44806. })
  44807. }
  44808. }
  44809. getVisible(reason){//获取在某条件下是否可见. 注: 用户在数据集选择可不可见为"datasetSelection"
  44810. if(this.visible)return true
  44811. else{
  44812. return !this.unvisibleReasons.includes(reason)
  44813. }
  44814. } */
  44815. /* get isVisible(){//add 手动在数据集选择是否显示(和是否全景图、隐藏点云无关)
  44816. return this._isVisible
  44817. }
  44818. set isVisible(visi){
  44819. if(!visi)this.visible = false
  44820. this._isVisible = visi
  44821. } */
  44822. }
  44823. /*
  44824. window.searchOutRing = function(points){
  44825. 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},
  44826. {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},
  44827. {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)=>{
  44828. var a = new THREE.Vector2().copy(e)
  44829. a.id = index;
  44830. return a
  44831. })
  44832. var lines = []
  44833. var minDis = 2*2
  44834. points.forEach((p,j)=>{
  44835. for(let i=0;i<j;i++){
  44836. if(p.distanceToSquared(points[i])<minDis){
  44837. lines.push({p1:i,p2:j})
  44838. }
  44839. }
  44840. })
  44841. searchRings({
  44842. points,
  44843. lines,
  44844. onlyGetOutRing:true
  44845. })
  44846. }
  44847. */
  44848. class Points$1 {
  44849. constructor () {
  44850. this.boundingBox = new Box3();
  44851. this.numPoints = 0;
  44852. this.data = {};
  44853. }
  44854. add (points) {
  44855. let currentSize = this.numPoints;
  44856. let additionalSize = points.numPoints;
  44857. let newSize = currentSize + additionalSize;
  44858. let thisAttributes = Object.keys(this.data);
  44859. let otherAttributes = Object.keys(points.data);
  44860. let attributes = new Set([...thisAttributes, ...otherAttributes]);
  44861. for (let attribute of attributes) {
  44862. if (thisAttributes.includes(attribute) && otherAttributes.includes(attribute)) {
  44863. // attribute in both, merge
  44864. let Type = this.data[attribute].constructor;
  44865. let merged = new Type(this.data[attribute].length + points.data[attribute].length);
  44866. merged.set(this.data[attribute], 0);
  44867. merged.set(points.data[attribute], this.data[attribute].length);
  44868. this.data[attribute] = merged;
  44869. } else if (thisAttributes.includes(attribute) && !otherAttributes.includes(attribute)) {
  44870. // attribute only in this; take over this and expand to new size
  44871. let elementsPerPoint = this.data[attribute].length / this.numPoints;
  44872. let Type = this.data[attribute].constructor;
  44873. let expanded = new Type(elementsPerPoint * newSize);
  44874. expanded.set(this.data[attribute], 0);
  44875. this.data[attribute] = expanded;
  44876. } else if (!thisAttributes.includes(attribute) && otherAttributes.includes(attribute)) {
  44877. // attribute only in points to be added; take over new points and expand to new size
  44878. let elementsPerPoint = points.data[attribute].length / points.numPoints;
  44879. let Type = points.data[attribute].constructor;
  44880. let expanded = new Type(elementsPerPoint * newSize);
  44881. expanded.set(points.data[attribute], elementsPerPoint * currentSize);
  44882. this.data[attribute] = expanded;
  44883. }
  44884. }
  44885. this.numPoints = newSize;
  44886. this.boundingBox.union(points.boundingBox);
  44887. }
  44888. }
  44889. /**
  44890. *
  44891. * code adapted from three.js BoxHelper.js
  44892. * https://github.com/mrdoob/three.js/blob/dev/src/helpers/BoxHelper.js
  44893. *
  44894. * @author mrdoob / http://mrdoob.com/
  44895. * @author Mugen87 / http://github.com/Mugen87
  44896. * @author mschuetz / http://potree.org
  44897. */
  44898. class Box3Helper$1 extends LineSegments {
  44899. constructor (box, color) {
  44900. if (color === undefined) color = 0xffff00;
  44901. 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 ]);
  44902. let positions = new Float32Array([
  44903. box.min.x, box.min.y, box.min.z,
  44904. box.max.x, box.min.y, box.min.z,
  44905. box.max.x, box.min.y, box.max.z,
  44906. box.min.x, box.min.y, box.max.z,
  44907. box.min.x, box.max.y, box.min.z,
  44908. box.max.x, box.max.y, box.min.z,
  44909. box.max.x, box.max.y, box.max.z,
  44910. box.min.x, box.max.y, box.max.z
  44911. ]);
  44912. let geometry = new BufferGeometry();
  44913. geometry.setIndex(new BufferAttribute(indices, 1));
  44914. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  44915. let material = new LineBasicMaterial({ color: color });
  44916. super(geometry, material);
  44917. }
  44918. }
  44919. function updatePointClouds(pointclouds,camera, areaSize /* renderer */){
  44920. for (let pointcloud of pointclouds) {
  44921. let start = performance.now();
  44922. for (let profileRequest of pointcloud.profileRequests) {
  44923. profileRequest.update();
  44924. let duration = performance.now() - start;
  44925. if(duration > 5){
  44926. break;
  44927. }
  44928. }
  44929. let duration = performance.now() - start;
  44930. }
  44931. let result = updateVisibility(pointclouds, camera, areaSize );
  44932. for (let pointcloud of pointclouds) {
  44933. //pointcloud.updateMaterial(pointcloud.material, pointcloud.visibleNodes, camera, renderer);//转移到渲染时
  44934. pointcloud.updateVisibleBounds();
  44935. }
  44936. exports.lru.freeMemory();//即Potree.lru 能看到所有在加载的node
  44937. return result;
  44938. };
  44939. function updateVisibilityStructures(pointclouds, camera, areaSize) {
  44940. let frustums = [];
  44941. let camObjPositions = [];
  44942. let priorityQueue = new BinaryHeap(function (x) { return 1 / x.weight; });
  44943. for (let i = 0; i < pointclouds.length; i++) {
  44944. let pointcloud = pointclouds[i];
  44945. if (!pointcloud.initialized()) {
  44946. continue;
  44947. }
  44948. pointcloud.numVisibleNodes = 0;
  44949. pointcloud.numVisiblePoints = 0;
  44950. pointcloud.deepestVisibleLevel = 0;
  44951. pointcloud.visibleNodes = [];
  44952. pointcloud.visibleGeometry = [];
  44953. // frustum in object space
  44954. camera.updateMatrixWorld();
  44955. let frustum = new Frustum();
  44956. let viewI = camera.matrixWorldInverse;
  44957. let world = pointcloud.matrixWorld;
  44958. // use close near plane for frustum intersection
  44959. let frustumCam = camera.clone();
  44960. frustumCam.near = Math.min(camera.near, 0.1);
  44961. frustumCam.updateProjectionMatrix();
  44962. let proj = camera.projectionMatrix;
  44963. let fm = new Matrix4().multiply(proj).multiply(viewI).multiply(world);
  44964. frustum.setFromProjectionMatrix(fm);
  44965. frustums.push(frustum);
  44966. // camera position in object space
  44967. let view = camera.matrixWorld;
  44968. let worldI = world.clone().invert();
  44969. let camMatrixObject = new Matrix4().multiply(worldI).multiply(view);
  44970. let camObjPos = new Vector3().setFromMatrixPosition(camMatrixObject);
  44971. camObjPositions.push(camObjPos);
  44972. // 因漫游模式而隐藏的话 依旧需要加入visibleNodes,因为pick需要
  44973. /* viewer.getObjVisiByReason(pointcloud, 'datasetSelection') */
  44974. if (pointcloud.visible || pointcloud.unvisibleReasons && pointcloud.unvisibleReasons.length == 1 && pointcloud.unvisibleReasons[0].reason == 'displayMode' && pointcloud.root !== null) {//改 visible ->
  44975. priorityQueue.push({pointcloud: i, node: pointcloud.root, weight: Number.MAX_VALUE});
  44976. }
  44977. // hide all previously visible nodes
  44978. // if(pointcloud.root instanceof PointCloudOctreeNode){
  44979. // pointcloud.hideDescendants(pointcloud.root.sceneNode);
  44980. // }
  44981. if (pointcloud.root.isTreeNode()) {
  44982. pointcloud.hideDescendants(pointcloud.root.sceneNode);
  44983. }
  44984. for (let j = 0; j < pointcloud.boundingBoxNodes.length; j++) {
  44985. pointcloud.boundingBoxNodes[j].visible = false;
  44986. }
  44987. }
  44988. return {
  44989. 'frustums': frustums,
  44990. 'camObjPositions': camObjPositions,
  44991. 'priorityQueue': priorityQueue
  44992. };
  44993. };
  44994. function updateVisibility(pointclouds, camera, areaSize){
  44995. let numVisibleNodes = 0;
  44996. let numVisiblePoints = 0;
  44997. let numVisiblePointsInPointclouds = new Map(pointclouds.map(pc => [pc, 0]));
  44998. let visibleNodes = [];
  44999. let visibleGeometry = [];
  45000. let unloadedGeometry = [];
  45001. let lowestSpacing = Infinity;
  45002. // calculate object space frustum and cam pos and setup priority queue
  45003. let s = updateVisibilityStructures(pointclouds, camera, areaSize);//得到相机可见范围
  45004. let frustums = s.frustums;
  45005. let camObjPositions = s.camObjPositions;
  45006. let priorityQueue = s.priorityQueue;
  45007. let loadedToGPUThisFrame = 0;
  45008. let domWidth = areaSize.x; //renderer.domElement.clientWidth;
  45009. let domHeight = areaSize.y;//renderer.domElement.clientHeight;
  45010. // check if pointcloud has been transformed
  45011. // some code will only be executed if changes have been detected
  45012. if(!Potree._pointcloudTransformVersion){
  45013. Potree._pointcloudTransformVersion = new Map();
  45014. }
  45015. let pointcloudTransformVersion = Potree._pointcloudTransformVersion;
  45016. for(let pointcloud of pointclouds){
  45017. if(!viewer.getObjVisiByReason(pointcloud, 'datasetSelection')){//改 visible ->
  45018. continue;
  45019. }
  45020. pointcloud.updateMatrixWorld();
  45021. if(!pointcloudTransformVersion.has(pointcloud)){
  45022. pointcloudTransformVersion.set(pointcloud, {number: 0, transform: pointcloud.matrixWorld.clone()});
  45023. }else {
  45024. let version = pointcloudTransformVersion.get(pointcloud);
  45025. if(!version.transform.equals(pointcloud.matrixWorld)){
  45026. version.number++;
  45027. version.transform.copy(pointcloud.matrixWorld);
  45028. pointcloud.dispatchEvent({
  45029. type: "transformation_changed",
  45030. target: pointcloud
  45031. });
  45032. }
  45033. }
  45034. }
  45035. while (priorityQueue.size() > 0) {
  45036. let element = priorityQueue.pop();//其实是拿第一个, 再把最后一个放到前面
  45037. let node = element.node;
  45038. let parent = element.parent;
  45039. let pointcloud = pointclouds[element.pointcloud];
  45040. // { // restrict to certain nodes for debugging
  45041. // let allowedNodes = ["r", "r0", "r4"];
  45042. // if(!allowedNodes.includes(node.name)){
  45043. // continue;
  45044. // }
  45045. // }
  45046. let box = node.getBoundingBox();
  45047. let frustum = frustums[element.pointcloud];
  45048. let camObjPos = camObjPositions[element.pointcloud];
  45049. let insideFrustum = frustum.intersectsBox(box);
  45050. let maxLevel = pointcloud.maxLevel == void 0 ? Infinity : pointcloud.maxLevel;
  45051. let level = node.getLevel();
  45052. let visible = insideFrustum;
  45053. visible = visible && !(numVisiblePoints + node.getNumPoints() > Potree.pointBudget);
  45054. visible = visible && !(numVisiblePointsInPointclouds.get(pointcloud) + node.getNumPoints() > pointcloud.pointBudget);
  45055. visible = visible && level <= maxLevel; //< 改为 <=
  45056. //visible = visible || node.getLevel() <= 2;
  45057. let clipBoxes = pointcloud.material.clipBoxes;
  45058. if(true && clipBoxes.length > 0){
  45059. //node.debug = false;
  45060. let numIntersecting = 0;
  45061. let numIntersectionVolumes = 0;
  45062. //if(node.name === "r60"){
  45063. // var a = 10;
  45064. //}
  45065. for(let clipBox of clipBoxes){
  45066. let pcWorldInverse = pointcloud.matrixWorld.clone().invert();
  45067. let toPCObject = pcWorldInverse.multiply(clipBox.box.matrixWorld);
  45068. let px = new Vector3(+0.5, 0, 0).applyMatrix4(pcWorldInverse);
  45069. let nx = new Vector3(-0.5, 0, 0).applyMatrix4(pcWorldInverse);
  45070. let py = new Vector3(0, +0.5, 0).applyMatrix4(pcWorldInverse);
  45071. let ny = new Vector3(0, -0.5, 0).applyMatrix4(pcWorldInverse);
  45072. let pz = new Vector3(0, 0, +0.5).applyMatrix4(pcWorldInverse);
  45073. let nz = new Vector3(0, 0, -0.5).applyMatrix4(pcWorldInverse);
  45074. let pxN = new Vector3().subVectors(nx, px).normalize();
  45075. let nxN = pxN.clone().multiplyScalar(-1);
  45076. let pyN = new Vector3().subVectors(ny, py).normalize();
  45077. let nyN = pyN.clone().multiplyScalar(-1);
  45078. let pzN = new Vector3().subVectors(nz, pz).normalize();
  45079. let nzN = pzN.clone().multiplyScalar(-1);
  45080. let pxPlane = new Plane().setFromNormalAndCoplanarPoint(pxN, px);
  45081. let nxPlane = new Plane().setFromNormalAndCoplanarPoint(nxN, nx);
  45082. let pyPlane = new Plane().setFromNormalAndCoplanarPoint(pyN, py);
  45083. let nyPlane = new Plane().setFromNormalAndCoplanarPoint(nyN, ny);
  45084. let pzPlane = new Plane().setFromNormalAndCoplanarPoint(pzN, pz);
  45085. let nzPlane = new Plane().setFromNormalAndCoplanarPoint(nzN, nz);
  45086. //if(window.debugdraw !== undefined && window.debugdraw === true && node.name === "r60"){
  45087. // Potree.utils.debugPlane(viewer.scene.scene, pxPlane, 1, 0xFF0000);
  45088. // Potree.utils.debugPlane(viewer.scene.scene, nxPlane, 1, 0x990000);
  45089. // Potree.utils.debugPlane(viewer.scene.scene, pyPlane, 1, 0x00FF00);
  45090. // Potree.utils.debugPlane(viewer.scene.scene, nyPlane, 1, 0x009900);
  45091. // Potree.utils.debugPlane(viewer.scene.scene, pzPlane, 1, 0x0000FF);
  45092. // Potree.utils.debugPlane(viewer.scene.scene, nzPlane, 1, 0x000099);
  45093. // Potree.utils.debugBox(viewer.scene.scene, box, new THREE.Matrix4(), 0x00FF00);
  45094. // Potree.utils.debugBox(viewer.scene.scene, box, pointcloud.matrixWorld, 0xFF0000);
  45095. // Potree.utils.debugBox(viewer.scene.scene, clipBox.box.boundingBox, clipBox.box.matrixWorld, 0xFF0000);
  45096. // window.debugdraw = false;
  45097. //}
  45098. let frustum = new Frustum(pxPlane, nxPlane, pyPlane, nyPlane, pzPlane, nzPlane);
  45099. let intersects = frustum.intersectsBox(box);
  45100. if(intersects){
  45101. numIntersecting++;
  45102. }
  45103. numIntersectionVolumes++;
  45104. }
  45105. let insideAny = numIntersecting > 0;
  45106. let insideAll = numIntersecting === numIntersectionVolumes;
  45107. if(pointcloud.material.clipTask === ClipTask.SHOW_INSIDE){
  45108. if(pointcloud.material.clipMethod === ClipMethod.INSIDE_ANY && insideAny){
  45109. //node.debug = true
  45110. }else if(pointcloud.material.clipMethod === ClipMethod.INSIDE_ALL && insideAll){
  45111. //node.debug = true;
  45112. }else {
  45113. visible = false;
  45114. }
  45115. } else if(pointcloud.material.clipTask === ClipTask.SHOW_OUTSIDE){
  45116. //if(pointcloud.material.clipMethod === ClipMethod.INSIDE_ANY && !insideAny){
  45117. // //visible = true;
  45118. // let a = 10;
  45119. //}else if(pointcloud.material.clipMethod === ClipMethod.INSIDE_ALL && !insideAll){
  45120. // //visible = true;
  45121. // let a = 20;
  45122. //}else{
  45123. // visible = false;
  45124. //}
  45125. }
  45126. }
  45127. // visible = ["r", "r0", "r06", "r060"].includes(node.name);
  45128. // visible = ["r"].includes(node.name);
  45129. if (node.spacing) {
  45130. lowestSpacing = Math.min(lowestSpacing, node.spacing);
  45131. } else if (node.geometryNode && node.geometryNode.spacing) {
  45132. lowestSpacing = Math.min(lowestSpacing, node.geometryNode.spacing);
  45133. }
  45134. if (numVisiblePoints + node.getNumPoints() > Potree.pointBudget) {
  45135. break;
  45136. }
  45137. if (!visible) {
  45138. continue;
  45139. }
  45140. // TODO: not used, same as the declaration?
  45141. // numVisibleNodes++;
  45142. numVisiblePoints += node.getNumPoints();
  45143. let numVisiblePointsInPointcloud = numVisiblePointsInPointclouds.get(pointcloud);
  45144. numVisiblePointsInPointclouds.set(pointcloud, numVisiblePointsInPointcloud + node.getNumPoints());
  45145. pointcloud.numVisibleNodes++;
  45146. pointcloud.numVisiblePoints += node.getNumPoints();
  45147. if (node.isGeometryNode() && (!parent || parent.isTreeNode())) {
  45148. if (node.isLoaded() && loadedToGPUThisFrame < 2) {
  45149. node = pointcloud.toTreeNode(node, parent);
  45150. loadedToGPUThisFrame++;
  45151. } else {
  45152. unloadedGeometry.push({pointcloud,node});
  45153. visibleGeometry.push(node);
  45154. }
  45155. }
  45156. if (node.isTreeNode()) {
  45157. exports.lru.touch(node.geometryNode);
  45158. node.sceneNode.visible = true;
  45159. node.sceneNode.material = pointcloud.material;
  45160. visibleNodes.push(node);
  45161. pointcloud.visibleNodes.push(node);
  45162. if(node._transformVersion === undefined){
  45163. node._transformVersion = -1;
  45164. }
  45165. let transformVersion = pointcloudTransformVersion.get(pointcloud);
  45166. if(node._transformVersion !== transformVersion.number){
  45167. node.sceneNode.updateMatrix();
  45168. //node.sceneNode.matrixWorld.multiplyMatrices(pointcloud.matrixWorld, node.sceneNode.matrix);
  45169. node.sceneNode.matrixWorld.multiplyMatrices(pointcloud.matrixWorld, node.sceneNode.matrix);
  45170. node._transformVersion = transformVersion.number;
  45171. }
  45172. if (pointcloud.showBoundingBox && !node.boundingBoxNode && node.getBoundingBox) {
  45173. let boxHelper = new Box3Helper$1(node.getBoundingBox());
  45174. boxHelper.matrixAutoUpdate = false;
  45175. pointcloud.boundingBoxNodes.push(boxHelper);
  45176. node.boundingBoxNode = boxHelper;
  45177. node.boundingBoxNode.matrix.copy(pointcloud.matrixWorld);
  45178. } else if (pointcloud.showBoundingBox) {
  45179. node.boundingBoxNode.visible = true;
  45180. node.boundingBoxNode.matrix.copy(pointcloud.matrixWorld);
  45181. } else if (!pointcloud.showBoundingBox && node.boundingBoxNode) {
  45182. node.boundingBoxNode.visible = false;
  45183. }
  45184. // if(node.boundingBoxNode !== undefined && exports.debug.allowedNodes !== undefined){
  45185. // if(!exports.debug.allowedNodes.includes(node.name)){
  45186. // node.boundingBoxNode.visible = false;
  45187. // }
  45188. // }
  45189. }
  45190. // add child nodes to priorityQueue
  45191. let children = node.getChildren();
  45192. for (let i = 0; i < children.length; i++) {
  45193. let child = children[i];
  45194. let weight = 0;
  45195. if(camera.isPerspectiveCamera){
  45196. let sphere = child.getBoundingSphere();
  45197. let center = sphere.center;
  45198. //let distance = sphere.center.distanceTo(camObjPos);
  45199. let dx = camObjPos.x - center.x;
  45200. let dy = camObjPos.y - center.y;
  45201. let dz = camObjPos.z - center.z;
  45202. let dd = dx * dx + dy * dy + dz * dz;
  45203. let distance = Math.sqrt(dd);
  45204. let radius = sphere.radius;
  45205. let fov = (camera.fov * Math.PI) / 180;
  45206. let slope = Math.tan(fov / 2);
  45207. let projFactor = (0.5 * domHeight) / (slope * distance);
  45208. let screenPixelRadius = radius * projFactor;
  45209. if(screenPixelRadius < pointcloud.minimumNodePixelSize){
  45210. continue;
  45211. }
  45212. weight = screenPixelRadius;
  45213. if(distance - radius < 0){
  45214. weight = Number.MAX_VALUE;
  45215. }
  45216. } else {
  45217. // TODO ortho visibility
  45218. let bb = child.getBoundingBox();
  45219. let distance = child.getBoundingSphere().center.distanceTo(camObjPos);
  45220. let diagonal = bb.max.clone().sub(bb.min).length();
  45221. //weight = diagonal / distance;
  45222. weight = diagonal;
  45223. }
  45224. priorityQueue.push({pointcloud: element.pointcloud, node: child, parent: node, weight: weight});
  45225. }
  45226. }// end priority queue loop
  45227. { // update DEM 这是什么
  45228. let maxDEMLevel = 4;
  45229. let candidates = pointclouds.filter(p => (p.generateDEM && p.dem instanceof Potree.DEM));
  45230. for (let pointcloud of candidates) {
  45231. let updatingNodes = pointcloud.visibleNodes.filter(n => n.getLevel() <= maxDEMLevel);
  45232. pointcloud.dem.update(updatingNodes);
  45233. }
  45234. }
  45235. //加载点云
  45236. for (let i = 0; i < Math.min(Potree.maxNodesLoading, unloadedGeometry.length); i++) {
  45237. unloadedGeometry[i].node.load(unloadedGeometry[i].pointcloud.pcoGeometry);
  45238. }
  45239. return {
  45240. visibleNodes: visibleNodes,
  45241. numVisiblePoints: numVisiblePoints,
  45242. lowestSpacing: lowestSpacing
  45243. };
  45244. };
  45245. //console
  45246. //viewer.scene.pointclouds[0].visibleNodes.map(e=> e && e.name )
  45247. //viewer.scene.pointclouds[0].visibleNodes.map(e=>e.children.map(e=>e && e.name))
  45248. class PointCloudArena4DNode extends PointCloudTreeNode {
  45249. constructor () {
  45250. super();
  45251. this.left = null;
  45252. this.right = null;
  45253. this.sceneNode = null;
  45254. this.kdtree = null;
  45255. }
  45256. getNumPoints () {
  45257. return this.geometryNode.numPoints;
  45258. }
  45259. isLoaded () {
  45260. return true;
  45261. }
  45262. isTreeNode () {
  45263. return true;
  45264. }
  45265. isGeometryNode () {
  45266. return false;
  45267. }
  45268. getLevel () {
  45269. return this.geometryNode.level;
  45270. }
  45271. getBoundingSphere () {
  45272. return this.geometryNode.boundingSphere;
  45273. }
  45274. getBoundingBox () {
  45275. return this.geometryNode.boundingBox;
  45276. }
  45277. toTreeNode (child) {
  45278. let geometryNode = null;
  45279. if (this.left === child) {
  45280. geometryNode = this.left;
  45281. } else if (this.right === child) {
  45282. geometryNode = this.right;
  45283. }
  45284. if (!geometryNode.loaded) {
  45285. return;
  45286. }
  45287. let node = new PointCloudArena4DNode();
  45288. let sceneNode = PointCloud(geometryNode.geometry, this.kdtree.material);
  45289. sceneNode.visible = false;
  45290. node.kdtree = this.kdtree;
  45291. node.geometryNode = geometryNode;
  45292. node.sceneNode = sceneNode;
  45293. node.parent = this;
  45294. node.left = this.geometryNode.left;
  45295. node.right = this.geometryNode.right;
  45296. }
  45297. getChildren () {
  45298. let children = [];
  45299. if (this.left) {
  45300. children.push(this.left);
  45301. }
  45302. if (this.right) {
  45303. children.push(this.right);
  45304. }
  45305. return children;
  45306. }
  45307. };
  45308. class PointCloudArena4D$1 extends PointCloudTree{
  45309. constructor (geometry) {
  45310. super();
  45311. this.root = null;
  45312. if (geometry.root) {
  45313. this.root = geometry.root;
  45314. } else {
  45315. geometry.addEventListener('hierarchy_loaded', () => {
  45316. this.root = geometry.root;
  45317. });
  45318. }
  45319. this.visiblePointsTarget = 2 * 1000 * 1000;
  45320. this.minimumNodePixelSize = 150;
  45321. this.position.sub(geometry.offset);
  45322. this.updateMatrix();
  45323. this.numVisibleNodes = 0;
  45324. this.numVisiblePoints = 0;
  45325. this.boundingBoxNodes = [];
  45326. this.loadQueue = [];
  45327. this.visibleNodes = [];
  45328. this.pcoGeometry = geometry;
  45329. this.boundingBox = this.pcoGeometry.boundingBox;
  45330. this.boundingSphere = this.pcoGeometry.boundingSphere;
  45331. this.material = new PointCloudMaterial$1({vertexColors: VertexColors, size: 0.05, treeType: TreeType.KDTREE});
  45332. this.material.sizeType = PointSizeType.ATTENUATED;
  45333. this.material.size = 0.05;
  45334. this.profileRequests = [];
  45335. this.name = '';
  45336. }
  45337. getBoundingBoxWorld () {
  45338. this.updateMatrixWorld(true);
  45339. let box = this.boundingBox;
  45340. let transform = this.matrixWorld;
  45341. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  45342. return tBox;
  45343. };
  45344. setName (name) {
  45345. if (this.name !== name) {
  45346. this.name = name;
  45347. this.dispatchEvent({type: 'name_changed', name: name, pointcloud: this});
  45348. }
  45349. }
  45350. getName () {
  45351. return this.name;
  45352. }
  45353. getLevel () {
  45354. return this.level;
  45355. }
  45356. toTreeNode (geometryNode, parent) {
  45357. let node = new PointCloudArena4DNode();
  45358. let sceneNode = new Points(geometryNode.geometry, this.material);
  45359. sceneNode.frustumCulled = false;
  45360. sceneNode.onBeforeRender = (_this, scene, camera, geometry, material, group) => {
  45361. if (material.program) {
  45362. _this.getContext().useProgram(material.program.program);
  45363. if (material.program.getUniforms().map.level) {
  45364. let level = geometryNode.getLevel();
  45365. material.uniforms.level.value = level;
  45366. material.program.getUniforms().map.level.setValue(_this.getContext(), level);
  45367. }
  45368. if (this.visibleNodeTextureOffsets && material.program.getUniforms().map.vnStart) {
  45369. let vnStart = this.visibleNodeTextureOffsets.get(node);
  45370. material.uniforms.vnStart.value = vnStart;
  45371. material.program.getUniforms().map.vnStart.setValue(_this.getContext(), vnStart);
  45372. }
  45373. if (material.program.getUniforms().map.pcIndex) {
  45374. let i = node.pcIndex ? node.pcIndex : this.visibleNodes.indexOf(node);
  45375. material.uniforms.pcIndex.value = i;
  45376. material.program.getUniforms().map.pcIndex.setValue(_this.getContext(), i);
  45377. }
  45378. }
  45379. };
  45380. node.geometryNode = geometryNode;
  45381. node.sceneNode = sceneNode;
  45382. node.pointcloud = this;
  45383. node.left = geometryNode.left;
  45384. node.right = geometryNode.right;
  45385. if (!parent) {
  45386. this.root = node;
  45387. this.add(sceneNode);
  45388. } else {
  45389. parent.sceneNode.add(sceneNode);
  45390. if (parent.left === geometryNode) {
  45391. parent.left = node;
  45392. } else if (parent.right === geometryNode) {
  45393. parent.right = node;
  45394. }
  45395. }
  45396. let disposeListener = function () {
  45397. parent.sceneNode.remove(node.sceneNode);
  45398. if (parent.left === node) {
  45399. parent.left = geometryNode;
  45400. } else if (parent.right === node) {
  45401. parent.right = geometryNode;
  45402. }
  45403. };
  45404. geometryNode.oneTimeDisposeHandlers.push(disposeListener);
  45405. return node;
  45406. }
  45407. updateMaterial (material, visibleNodes, camera, renderer) {
  45408. material.fov = camera.fov * (Math.PI / 180);
  45409. material.screenWidth = renderer.domElement.clientWidth;
  45410. material.screenHeight = renderer.domElement.clientHeight;
  45411. material.spacing = this.pcoGeometry.spacing;
  45412. material.near = camera.near;
  45413. material.far = camera.far;
  45414. // reduce shader source updates by setting maxLevel slightly higher than actually necessary
  45415. if (this.maxLevel > material.levels) {
  45416. material.levels = this.maxLevel + 2;
  45417. }
  45418. // material.uniforms.octreeSize.value = this.boundingBox.size().x;
  45419. let bbSize = this.boundingBox.getSize(new Vector3());
  45420. material.bbSize = [bbSize.x, bbSize.y, bbSize.z];
  45421. }
  45422. updateVisibleBounds () {
  45423. }
  45424. hideDescendants (object) {
  45425. let stack = [];
  45426. for (let i = 0; i < object.children.length; i++) {
  45427. let child = object.children[i];
  45428. if (child.visible) {
  45429. stack.push(child);
  45430. }
  45431. }
  45432. while (stack.length > 0) {
  45433. let child = stack.shift();
  45434. child.visible = false;
  45435. if (child.boundingBoxNode) {
  45436. child.boundingBoxNode.visible = false;
  45437. }
  45438. for (let i = 0; i < child.children.length; i++) {
  45439. let childOfChild = child.children[i];
  45440. if (childOfChild.visible) {
  45441. stack.push(childOfChild);
  45442. }
  45443. }
  45444. }
  45445. }
  45446. updateMatrixWorld (force) {
  45447. // node.matrixWorld.multiplyMatrices( node.parent.matrixWorld, node.matrix );
  45448. if (this.matrixAutoUpdate === true) this.updateMatrix();
  45449. if (this.matrixWorldNeedsUpdate === true || force === true) {
  45450. if (this.parent === undefined) {
  45451. this.matrixWorld.copy(this.matrix);
  45452. } else {
  45453. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  45454. }
  45455. this.matrixWorldNeedsUpdate = false;
  45456. force = true;
  45457. }
  45458. }
  45459. nodesOnRay (nodes, ray) {
  45460. let nodesOnRay = [];
  45461. let _ray = ray.clone();
  45462. for (let i = 0; i < nodes.length; i++) {
  45463. let node = nodes[i];
  45464. let sphere = node.getBoundingSphere().clone().applyMatrix4(node.sceneNode.matrixWorld);
  45465. // TODO Unused: let box = node.getBoundingBox().clone().applyMatrix4(node.sceneNode.matrixWorld);
  45466. if (_ray.intersectsSphere(sphere)) {
  45467. nodesOnRay.push(node);
  45468. }
  45469. // if(_ray.isIntersectionBox(box)){
  45470. // nodesOnRay.push(node);
  45471. // }
  45472. }
  45473. return nodesOnRay;
  45474. }
  45475. pick(viewer, camera, ray, params = {}){
  45476. let renderer = viewer.renderer;
  45477. let pRenderer = viewer.pRenderer;
  45478. performance.mark("pick-start");
  45479. let getVal = (a, b) => a !== undefined ? a : b;
  45480. let pickWindowSize = getVal(params.pickWindowSize, 17);
  45481. let pickOutsideClipRegion = getVal(params.pickOutsideClipRegion, false);
  45482. let size = renderer.getSize(new Vector2$1());
  45483. let width = Math.ceil(getVal(params.width, size.width));
  45484. let height = Math.ceil(getVal(params.height, size.height));
  45485. let pointSizeType = getVal(params.pointSizeType, this.material.pointSizeType);
  45486. let pointSize = getVal(params.pointSize, this.material.size);
  45487. let nodes = this.nodesOnRay(this.visibleNodes, ray);
  45488. if (nodes.length === 0) {
  45489. return null;
  45490. }
  45491. if (!this.pickState) {
  45492. let scene = new Scene();
  45493. let material = new PointCloudMaterial$1();
  45494. material.activeAttributeName = "indices";
  45495. let renderTarget = new WebGLRenderTarget(
  45496. 1, 1,
  45497. { minFilter: LinearFilter,
  45498. magFilter: NearestFilter,
  45499. format: RGBAFormat }
  45500. );
  45501. this.pickState = {
  45502. renderTarget: renderTarget,
  45503. material: material,
  45504. scene: scene
  45505. };
  45506. };
  45507. let pickState = this.pickState;
  45508. let pickMaterial = pickState.material;
  45509. { // update pick material
  45510. pickMaterial.pointSizeType = pointSizeType;
  45511. pickMaterial.shape = this.material.shape;
  45512. pickMaterial.size = pointSize;
  45513. pickMaterial.uniforms.minSize.value = this.material.uniforms.minSize.value;
  45514. pickMaterial.uniforms.maxSize.value = this.material.uniforms.maxSize.value;
  45515. pickMaterial.classification = this.material.classification;
  45516. if(params.pickClipped){
  45517. pickMaterial.clipBoxes = this.material.clipBoxes;
  45518. if(this.material.clipTask === ClipTask.HIGHLIGHT){
  45519. pickMaterial.clipTask = ClipTask.NONE;
  45520. }else {
  45521. pickMaterial.clipTask = this.material.clipTask;
  45522. }
  45523. }else {
  45524. pickMaterial.clipBoxes = [];
  45525. }
  45526. this.updateMaterial(pickMaterial, nodes, camera, renderer);
  45527. }
  45528. pickState.renderTarget.setSize(width, height);
  45529. let pixelPos = new Vector2$1(params.x, params.y);
  45530. let gl = renderer.getContext();
  45531. gl.enable(gl.SCISSOR_TEST);
  45532. gl.scissor(
  45533. parseInt(pixelPos.x - (pickWindowSize - 1) / 2),
  45534. parseInt(pixelPos.y - (pickWindowSize - 1) / 2),
  45535. parseInt(pickWindowSize), parseInt(pickWindowSize));
  45536. renderer.state.buffers.depth.setTest(pickMaterial.depthTest);
  45537. renderer.state.buffers.depth.setMask(pickMaterial.depthWrite);
  45538. renderer.state.setBlending(NoBlending);
  45539. renderer.clearTarget(pickState.renderTarget, true, true, true);
  45540. { // RENDER
  45541. renderer.setRenderTarget(pickState.renderTarget);
  45542. gl.clearColor(0, 0, 0, 0);
  45543. renderer.clearTarget( pickState.renderTarget, true, true, true );
  45544. let tmp = this.material;
  45545. this.material = pickMaterial;
  45546. pRenderer.renderOctree(this, nodes, camera, pickState.renderTarget);
  45547. this.material = tmp;
  45548. }
  45549. let clamp = (number, min, max) => Math.min(Math.max(min, number), max);
  45550. let x = parseInt(clamp(pixelPos.x - (pickWindowSize - 1) / 2, 0, width));
  45551. let y = parseInt(clamp(pixelPos.y - (pickWindowSize - 1) / 2, 0, height));
  45552. let w = parseInt(Math.min(x + pickWindowSize, width) - x);
  45553. let h = parseInt(Math.min(y + pickWindowSize, height) - y);
  45554. let pixelCount = w * h;
  45555. let buffer = new Uint8Array(4 * pixelCount);
  45556. gl.readPixels(x, y, pickWindowSize, pickWindowSize, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
  45557. renderer.setRenderTarget(null);
  45558. renderer.state.reset();
  45559. renderer.setScissorTest(false);
  45560. gl.disable(gl.SCISSOR_TEST);
  45561. let pixels = buffer;
  45562. let ibuffer = new Uint32Array(buffer.buffer);
  45563. // find closest hit inside pixelWindow boundaries
  45564. let min = Number.MAX_VALUE;
  45565. let hits = [];
  45566. for (let u = 0; u < pickWindowSize; u++) {
  45567. for (let v = 0; v < pickWindowSize; v++) {
  45568. let offset = (u + v * pickWindowSize);
  45569. let distance = Math.pow(u - (pickWindowSize - 1) / 2, 2) + Math.pow(v - (pickWindowSize - 1) / 2, 2);
  45570. let pcIndex = pixels[4 * offset + 3];
  45571. pixels[4 * offset + 3] = 0;
  45572. let pIndex = ibuffer[offset];
  45573. if(!(pcIndex === 0 && pIndex === 0) && (pcIndex !== undefined) && (pIndex !== undefined)){
  45574. let hit = {
  45575. pIndex: pIndex,
  45576. pcIndex: pcIndex,
  45577. distanceToCenter: distance
  45578. };
  45579. if(params.all){
  45580. hits.push(hit);
  45581. }else {
  45582. if(hits.length > 0){
  45583. if(distance < hits[0].distanceToCenter){
  45584. hits[0] = hit;
  45585. }
  45586. }else {
  45587. hits.push(hit);
  45588. }
  45589. }
  45590. }
  45591. }
  45592. }
  45593. for(let hit of hits){
  45594. let point = {};
  45595. if (!nodes[hit.pcIndex]) {
  45596. return null;
  45597. }
  45598. let node = nodes[hit.pcIndex];
  45599. let pc = node.sceneNode;
  45600. let geometry = node.geometryNode.geometry;
  45601. for(let attributeName in geometry.attributes){
  45602. let attribute = geometry.attributes[attributeName];
  45603. if (attributeName === 'position') {
  45604. let x = attribute.array[3 * hit.pIndex + 0];
  45605. let y = attribute.array[3 * hit.pIndex + 1];
  45606. let z = attribute.array[3 * hit.pIndex + 2];
  45607. let position = new Vector3(x, y, z);
  45608. position.applyMatrix4(pc.matrixWorld);
  45609. point[attributeName] = position;
  45610. } else if (attributeName === 'indices') {
  45611. } else {
  45612. //if (values.itemSize === 1) {
  45613. // point[attribute.name] = values.array[hit.pIndex];
  45614. //} else {
  45615. // let value = [];
  45616. // for (let j = 0; j < values.itemSize; j++) {
  45617. // value.push(values.array[values.itemSize * hit.pIndex + j]);
  45618. // }
  45619. // point[attribute.name] = value;
  45620. //}
  45621. }
  45622. }
  45623. hit.point = point;
  45624. }
  45625. performance.mark("pick-end");
  45626. performance.measure("pick", "pick-start", "pick-end");
  45627. if(params.all){
  45628. return hits.map(hit => hit.point);
  45629. }else {
  45630. if(hits.length === 0){
  45631. return null;
  45632. }else {
  45633. return hits[0].point;
  45634. }
  45635. }
  45636. }
  45637. computeVisibilityTextureData(nodes){
  45638. if(exports.measureTimings) performance.mark("computeVisibilityTextureData-start");
  45639. let data = new Uint8Array(nodes.length * 3);
  45640. let visibleNodeTextureOffsets = new Map();
  45641. // copy array
  45642. nodes = nodes.slice();
  45643. // sort by level and number
  45644. let sort = function (a, b) {
  45645. let la = a.geometryNode.level;
  45646. let lb = b.geometryNode.level;
  45647. let na = a.geometryNode.number;
  45648. let nb = b.geometryNode.number;
  45649. if (la !== lb) return la - lb;
  45650. if (na < nb) return -1;
  45651. if (na > nb) return 1;
  45652. return 0;
  45653. };
  45654. nodes.sort(sort);
  45655. let visibleNodeNames = [];
  45656. for (let i = 0; i < nodes.length; i++) {
  45657. visibleNodeNames.push(nodes[i].geometryNode.number);
  45658. }
  45659. for (let i = 0; i < nodes.length; i++) {
  45660. let node = nodes[i];
  45661. visibleNodeTextureOffsets.set(node, i);
  45662. let b1 = 0; // children
  45663. let b2 = 0; // offset to first child
  45664. let b3 = 0; // split
  45665. if (node.geometryNode.left && visibleNodeNames.indexOf(node.geometryNode.left.number) > 0) {
  45666. b1 += 1;
  45667. b2 = visibleNodeNames.indexOf(node.geometryNode.left.number) - i;
  45668. }
  45669. if (node.geometryNode.right && visibleNodeNames.indexOf(node.geometryNode.right.number) > 0) {
  45670. b1 += 2;
  45671. b2 = (b2 === 0) ? visibleNodeNames.indexOf(node.geometryNode.right.number) - i : b2;
  45672. }
  45673. if (node.geometryNode.split === 'X') {
  45674. b3 = 1;
  45675. } else if (node.geometryNode.split === 'Y') {
  45676. b3 = 2;
  45677. } else if (node.geometryNode.split === 'Z') {
  45678. b3 = 4;
  45679. }
  45680. data[i * 3 + 0] = b1;
  45681. data[i * 3 + 1] = b2;
  45682. data[i * 3 + 2] = b3;
  45683. }
  45684. if(exports.measureTimings){
  45685. performance.mark("computeVisibilityTextureData-end");
  45686. performance.measure("render.computeVisibilityTextureData", "computeVisibilityTextureData-start", "computeVisibilityTextureData-end");
  45687. }
  45688. return {
  45689. data: data,
  45690. offsets: visibleNodeTextureOffsets
  45691. };
  45692. }
  45693. get progress () {
  45694. if (this.pcoGeometry.root) {
  45695. return exports.numNodesLoading > 0 ? 0 : 1;
  45696. } else {
  45697. return 0;
  45698. }
  45699. }
  45700. };
  45701. // Copied from three.js: WebGLRenderer.js
  45702. function paramThreeToGL(_gl, p) {
  45703. let extension;
  45704. if (p === RepeatWrapping) return _gl.REPEAT;
  45705. if (p === ClampToEdgeWrapping) return _gl.CLAMP_TO_EDGE;
  45706. if (p === MirroredRepeatWrapping) return _gl.MIRRORED_REPEAT;
  45707. if (p === NearestFilter) return _gl.NEAREST;
  45708. if (p === NearestMipMapNearestFilter) return _gl.NEAREST_MIPMAP_NEAREST;
  45709. if (p === NearestMipMapLinearFilter) return _gl.NEAREST_MIPMAP_LINEAR;
  45710. if (p === LinearFilter) return _gl.LINEAR;
  45711. if (p === LinearMipMapNearestFilter) return _gl.LINEAR_MIPMAP_NEAREST;
  45712. if (p === LinearMipMapLinearFilter) return _gl.LINEAR_MIPMAP_LINEAR;
  45713. if (p === UnsignedByteType) return _gl.UNSIGNED_BYTE;
  45714. if (p === UnsignedShort4444Type) return _gl.UNSIGNED_SHORT_4_4_4_4;
  45715. if (p === UnsignedShort5551Type) return _gl.UNSIGNED_SHORT_5_5_5_1;
  45716. if (p === UnsignedShort565Type) return _gl.UNSIGNED_SHORT_5_6_5;
  45717. if (p === ByteType) return _gl.BYTE;
  45718. if (p === ShortType) return _gl.SHORT;
  45719. if (p === UnsignedShortType) return _gl.UNSIGNED_SHORT;
  45720. if (p === IntType) return _gl.INT;
  45721. if (p === UnsignedIntType) return _gl.UNSIGNED_INT;
  45722. if (p === FloatType) return _gl.FLOAT;
  45723. if (p === HalfFloatType) {
  45724. extension = extensions.get('OES_texture_half_float');
  45725. if (extension !== null) return extension.HALF_FLOAT_OES;
  45726. }
  45727. if (p === AlphaFormat) return _gl.ALPHA;
  45728. if (p === RGBFormat) return _gl.RGB;
  45729. if (p === RGBAFormat) return _gl.RGBA;
  45730. if (p === LuminanceFormat) return _gl.LUMINANCE;
  45731. if (p === LuminanceAlphaFormat) return _gl.LUMINANCE_ALPHA;
  45732. if (p === DepthFormat) return _gl.DEPTH_COMPONENT;
  45733. if (p === DepthStencilFormat) return _gl.DEPTH_STENCIL;
  45734. if (p === AddEquation) return _gl.FUNC_ADD;
  45735. if (p === SubtractEquation) return _gl.FUNC_SUBTRACT;
  45736. if (p === ReverseSubtractEquation) return _gl.FUNC_REVERSE_SUBTRACT;
  45737. if (p === ZeroFactor) return _gl.ZERO;
  45738. if (p === OneFactor) return _gl.ONE;
  45739. if (p === SrcColorFactor) return _gl.SRC_COLOR;
  45740. if (p === OneMinusSrcColorFactor) return _gl.ONE_MINUS_SRC_COLOR;
  45741. if (p === SrcAlphaFactor) return _gl.SRC_ALPHA;
  45742. if (p === OneMinusSrcAlphaFactor) return _gl.ONE_MINUS_SRC_ALPHA;
  45743. if (p === DstAlphaFactor) return _gl.DST_ALPHA;
  45744. if (p === OneMinusDstAlphaFactor) return _gl.ONE_MINUS_DST_ALPHA;
  45745. if (p === DstColorFactor) return _gl.DST_COLOR;
  45746. if (p === OneMinusDstColorFactor) return _gl.ONE_MINUS_DST_COLOR;
  45747. if (p === SrcAlphaSaturateFactor) return _gl.SRC_ALPHA_SATURATE;
  45748. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  45749. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  45750. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  45751. if (extension !== null) {
  45752. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  45753. if (p === RGBA_S3TC_DXT1_Format$1) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  45754. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  45755. if (p === RGBA_S3TC_DXT5_Format$1) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  45756. }
  45757. }
  45758. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  45759. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  45760. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  45761. if (extension !== null) {
  45762. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  45763. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  45764. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  45765. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  45766. }
  45767. }
  45768. if (p === RGB_ETC1_Format) {
  45769. extension = extensions.get('WEBGL_compressed_texture_etc1');
  45770. if (extension !== null) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  45771. }
  45772. if (p === MinEquation || p === MaxEquation) {
  45773. extension = extensions.get('EXT_blend_minmax');
  45774. if (extension !== null) {
  45775. if (p === MinEquation) return extension.MIN_EXT;
  45776. if (p === MaxEquation) return extension.MAX_EXT;
  45777. }
  45778. }
  45779. if (p === UnsignedInt248Type) {
  45780. extension = extensions.get('WEBGL_depth_texture');
  45781. if (extension !== null) return extension.UNSIGNED_INT_24_8_WEBGL;
  45782. }
  45783. return 0;
  45784. };
  45785. let attributeLocations = {
  45786. "position": {name: "position", location: 0},
  45787. "color": {name: "color", location: 1},
  45788. "rgba": {name: "color", location: 1},
  45789. "intensity": {name: "intensity", location: 2},
  45790. "classification": {name: "classification", location: 3},
  45791. "returnNumber": {name: "returnNumber", location: 4},
  45792. "return number": {name: "returnNumber", location: 4},
  45793. "returns": {name: "returnNumber", location: 4},
  45794. "numberOfReturns": {name: "numberOfReturns", location: 5},
  45795. "number of returns": {name: "numberOfReturns", location: 5},
  45796. "pointSourceID": {name: "pointSourceID", location: 6},
  45797. "source id": {name: "pointSourceID", location: 6},
  45798. "point source id": {name: "pointSourceID", location: 6},
  45799. "indices": {name: "indices", location: 7},
  45800. "normal": {name: "normal", location: 8},
  45801. "spacing": {name: "spacing", location: 9},
  45802. "gps-time": {name: "gpsTime", location: 10},
  45803. "aExtra": {name: "aExtra", location: 11},
  45804. };
  45805. class Shader {
  45806. constructor(gl, name, vsSource, fsSource) {
  45807. this.gl = gl;
  45808. this.name = name;
  45809. this.vsSource = vsSource;
  45810. this.fsSource = fsSource;
  45811. this.cache = new Map();
  45812. this.vs = null;
  45813. this.fs = null;
  45814. this.program = null;
  45815. this.uniformLocations = {};
  45816. this.attributeLocations = {};
  45817. this.uniformBlockIndices = {};
  45818. this.uniformBlocks = {};
  45819. this.uniforms = {};
  45820. this.update(vsSource, fsSource);
  45821. }
  45822. update(vsSource, fsSource) {
  45823. this.vsSource = vsSource;
  45824. this.fsSource = fsSource;
  45825. this.linkProgram();
  45826. }
  45827. compileShader(shader, source){
  45828. let gl = this.gl;
  45829. gl.shaderSource(shader, source);
  45830. gl.compileShader(shader);
  45831. let success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  45832. if (!success) {
  45833. let info = gl.getShaderInfoLog(shader);
  45834. let numberedSource = source.split("\n").map((a, i) => `${i + 1}`.padEnd(5) + a).join("\n");
  45835. throw `could not compile shader ${this.name}: ${info}, \n${numberedSource}`;
  45836. }
  45837. }
  45838. linkProgram() {
  45839. const tStart = performance.now();
  45840. let gl = this.gl;
  45841. this.uniformLocations = {};
  45842. this.attributeLocations = {};
  45843. this.uniforms = {};
  45844. gl.useProgram(null);
  45845. let cached = this.cache.get(`${this.vsSource}, ${this.fsSource}`);
  45846. if (cached) {
  45847. this.program = cached.program;
  45848. this.vs = cached.vs;
  45849. this.fs = cached.fs;
  45850. this.attributeLocations = cached.attributeLocations;
  45851. this.uniformLocations = cached.uniformLocations;
  45852. this.uniformBlocks = cached.uniformBlocks;
  45853. this.uniforms = cached.uniforms;
  45854. return;
  45855. } else {
  45856. this.vs = gl.createShader(gl.VERTEX_SHADER);
  45857. this.fs = gl.createShader(gl.FRAGMENT_SHADER);
  45858. this.program = gl.createProgram();
  45859. if( !gl.isProgram(this.program )){//创建失败 开启多个页面可能会,原因是webglcontextlost
  45860. //console.error('创建program失败');
  45861. viewer.dispatchEvent('webglError', {msg: 'potreeRenderer创建program失败'});
  45862. console.log(this.vs);
  45863. console.log(this.fs);
  45864. return;
  45865. }
  45866. for(let name of Object.keys(attributeLocations)){
  45867. let location = attributeLocations[name].location;
  45868. let glslName = attributeLocations[name].name;
  45869. gl.bindAttribLocation(this.program, location, glslName);
  45870. }
  45871. this.compileShader(this.vs, this.vsSource);
  45872. this.compileShader(this.fs, this.fsSource);
  45873. let program = this.program;
  45874. gl.attachShader(program, this.vs);
  45875. gl.attachShader(program, this.fs);
  45876. gl.linkProgram(program);
  45877. gl.detachShader(program, this.vs);
  45878. gl.detachShader(program, this.fs);
  45879. // 检测当前程序链接状态
  45880. let success = gl.getProgramParameter(program, gl.LINK_STATUS);
  45881. if (!success) {
  45882. let info = gl.getProgramInfoLog(program);
  45883. throw `could not link program ${this.name}: ${info}`;
  45884. }
  45885. { // attribute locations
  45886. let numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  45887. for (let i = 0; i < numAttributes; i++) {
  45888. let attribute = gl.getActiveAttrib(program, i);
  45889. let location = gl.getAttribLocation(program, attribute.name);
  45890. this.attributeLocations[attribute.name] = location;
  45891. }
  45892. }
  45893. { // uniform locations
  45894. let numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  45895. for (let i = 0; i < numUniforms; i++) {
  45896. let uniform = gl.getActiveUniform(program, i);
  45897. let location = gl.getUniformLocation(program, uniform.name);
  45898. this.uniformLocations[uniform.name] = location;
  45899. this.uniforms[uniform.name] = {
  45900. location: location,
  45901. value: null,
  45902. };
  45903. }
  45904. }
  45905. // uniform blocks
  45906. if( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext){ //WebGL2RenderingContext在mac的safari14以下是没有定义的
  45907. let numBlocks = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS);
  45908. for (let i = 0; i < numBlocks; i++) {
  45909. let blockName = gl.getActiveUniformBlockName(program, i);
  45910. let blockIndex = gl.getUniformBlockIndex(program, blockName);
  45911. this.uniformBlockIndices[blockName] = blockIndex;
  45912. gl.uniformBlockBinding(program, blockIndex, blockIndex);
  45913. let dataSize = gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_DATA_SIZE);
  45914. let uBuffer = gl.createBuffer();
  45915. gl.bindBuffer(gl.UNIFORM_BUFFER, uBuffer);
  45916. gl.bufferData(gl.UNIFORM_BUFFER, dataSize, gl.DYNAMIC_READ);
  45917. gl.bindBufferBase(gl.UNIFORM_BUFFER, blockIndex, uBuffer);
  45918. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  45919. this.uniformBlocks[blockName] = {
  45920. name: blockName,
  45921. index: blockIndex,
  45922. dataSize: dataSize,
  45923. buffer: uBuffer
  45924. };
  45925. }
  45926. }
  45927. let cached = {
  45928. program: this.program,
  45929. vs: this.vs,
  45930. fs: this.fs,
  45931. attributeLocations: this.attributeLocations,
  45932. uniformLocations: this.uniformLocations,
  45933. uniforms: this.uniforms,
  45934. uniformBlocks: this.uniformBlocks,
  45935. };
  45936. this.cache.set(`${this.vsSource}, ${this.fsSource}`, cached);
  45937. }
  45938. const tEnd = performance.now();
  45939. const duration = tEnd - tStart;
  45940. //console.log(`shader compile duration: ${duration.toFixed(3)}`);
  45941. }
  45942. setUniformMatrix4(name, value) {
  45943. const gl = this.gl;
  45944. const location = this.uniformLocations[name];
  45945. if (location == null) {
  45946. return;
  45947. }
  45948. let tmp = new Float32Array(value.elements);
  45949. gl.uniformMatrix4fv(location, false, tmp);
  45950. }
  45951. setUniform1f(name, value) {
  45952. const gl = this.gl;
  45953. const uniform = this.uniforms[name];
  45954. if (uniform === undefined) {
  45955. return;
  45956. }
  45957. if(uniform.value === value){
  45958. return;
  45959. }
  45960. uniform.value = value;
  45961. gl.uniform1f(uniform.location, value);
  45962. }
  45963. setUniformBoolean(name, value) {
  45964. const gl = this.gl;
  45965. const uniform = this.uniforms[name];
  45966. if (uniform === undefined) {
  45967. return;
  45968. }
  45969. if(uniform.value === value){
  45970. return;
  45971. }
  45972. uniform.value = value;
  45973. gl.uniform1i(uniform.location, value);
  45974. }
  45975. setUniformTexture(name, value) {
  45976. const gl = this.gl;
  45977. const location = this.uniformLocations[name];
  45978. if (location == null) {
  45979. return;
  45980. }
  45981. gl.uniform1i(location, value);
  45982. }
  45983. setUniform2f(name, value) {
  45984. const gl = this.gl;
  45985. const location = this.uniformLocations[name];
  45986. if (location == null) {
  45987. return;
  45988. }
  45989. gl.uniform2f(location, value[0], value[1]);
  45990. }
  45991. setUniform3f(name, value) {
  45992. const gl = this.gl;
  45993. const location = this.uniformLocations[name];
  45994. if (location == null) {
  45995. return;
  45996. }
  45997. gl.uniform3f(location, value[0], value[1], value[2]);
  45998. }
  45999. setUniform(name, value) {
  46000. if (value.constructor === Matrix4) {
  46001. this.setUniformMatrix4(name, value);
  46002. } else if (typeof value === "number") {
  46003. this.setUniform1f(name, value);
  46004. } else if (typeof value === "boolean") {
  46005. this.setUniformBoolean(name, value);
  46006. } else if (value instanceof WebGLTexture) {
  46007. this.setUniformTexture(name, value);
  46008. } else if (value instanceof Array) {
  46009. if (value.length === 2) {
  46010. this.setUniform2f(name, value);
  46011. } else if (value.length === 3) {
  46012. this.setUniform3f(name, value);
  46013. }
  46014. } else {
  46015. console.error("unhandled uniform type: ", name, value);
  46016. }
  46017. }
  46018. setUniform1i(name, value) {
  46019. let gl = this.gl;
  46020. let location = this.uniformLocations[name];
  46021. if (location == null) {
  46022. return;
  46023. }
  46024. gl.uniform1i(location, value);
  46025. }
  46026. };
  46027. class WebGLTexture {
  46028. constructor(gl, texture) {
  46029. this.gl = gl;
  46030. this.texture = texture;
  46031. this.id = gl.createTexture();
  46032. this.target = gl.TEXTURE_2D;
  46033. this.version = -1;
  46034. this.update(texture);
  46035. }
  46036. update() {
  46037. if (!this.texture.image) {
  46038. this.version = this.texture.version;
  46039. return;
  46040. }
  46041. let gl = this.gl;
  46042. let texture = this.texture;
  46043. if (this.version === texture.version) {
  46044. return;
  46045. }
  46046. this.target = gl.TEXTURE_2D;
  46047. gl.bindTexture(this.target, this.id);
  46048. let level = 0;
  46049. let internalFormat = paramThreeToGL(gl, texture.format);
  46050. let width = texture.image.width;
  46051. let height = texture.image.height;
  46052. let border = 0;
  46053. let srcFormat = internalFormat;
  46054. let srcType = paramThreeToGL(gl, texture.type);
  46055. let data;
  46056. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  46057. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  46058. gl.pixelStorei(gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  46059. if (texture instanceof DataTexture) {
  46060. data = texture.image.data;
  46061. gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  46062. gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  46063. gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL(gl, texture.magFilter));
  46064. gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL(gl, texture.minFilter));
  46065. gl.texImage2D(this.target, level, internalFormat,
  46066. width, height, border, srcFormat, srcType,
  46067. data);
  46068. }/* else if(texture instanceof THREE.CubeTexture){//add
  46069. } */else if ((texture instanceof CanvasTexture) || (texture instanceof Texture)) {
  46070. data = texture.image;
  46071. gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, paramThreeToGL(gl, texture.wrapS));
  46072. gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, paramThreeToGL(gl, texture.wrapT));
  46073. gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL(gl, texture.magFilter));
  46074. gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL(gl, texture.minFilter));
  46075. gl.texImage2D(this.target, level, internalFormat,
  46076. internalFormat, srcType, data);
  46077. if (texture instanceof Texture) {gl.generateMipmap(gl.TEXTURE_2D);}
  46078. }
  46079. gl.bindTexture(this.target, null);
  46080. this.version = texture.version;
  46081. }
  46082. };
  46083. class WebGLBuffer {
  46084. constructor() {
  46085. this.numElements = 0;
  46086. this.vao = null;
  46087. this.vbos = new Map();
  46088. }
  46089. };
  46090. class Renderer {
  46091. constructor(threeRenderer) {
  46092. this.threeRenderer = threeRenderer;
  46093. this.gl = this.threeRenderer.getContext();
  46094. this.buffers = new Map();
  46095. this.shaders = new Map();
  46096. this.textures = new Map();
  46097. this.glTypeMapping = new Map();
  46098. this.glTypeMapping.set(Float32Array, this.gl.FLOAT);
  46099. this.glTypeMapping.set(Uint8Array, this.gl.UNSIGNED_BYTE);
  46100. this.glTypeMapping.set(Uint16Array, this.gl.UNSIGNED_SHORT);
  46101. this.toggle = 0;
  46102. }
  46103. deleteBuffer(geometry) {
  46104. let gl = this.gl;
  46105. let webglBuffer = this.buffers.get(geometry);
  46106. if (webglBuffer != null) {
  46107. for (let attributeName in geometry.attributes) {
  46108. gl.deleteBuffer(webglBuffer.vbos.get(attributeName).handle);
  46109. }
  46110. this.buffers.delete(geometry);
  46111. }
  46112. }
  46113. createBuffer(geometry){
  46114. let gl = this.gl;
  46115. let webglBuffer = new WebGLBuffer();
  46116. webglBuffer.vao = gl.createVertexArray();
  46117. webglBuffer.numElements = geometry.attributes.position.count;
  46118. gl.bindVertexArray(webglBuffer.vao);
  46119. for(let attributeName in geometry.attributes){
  46120. let bufferAttribute = geometry.attributes[attributeName];
  46121. let vbo = gl.createBuffer();
  46122. gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
  46123. gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW);
  46124. let normalized = bufferAttribute.normalized;
  46125. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  46126. if(attributeLocations[attributeName] === undefined){
  46127. //attributeLocation = attributeLocations["aExtra"];
  46128. }else {
  46129. let attributeLocation = attributeLocations[attributeName].location;
  46130. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  46131. gl.enableVertexAttribArray(attributeLocation);
  46132. }
  46133. webglBuffer.vbos.set(attributeName, {
  46134. handle: vbo,
  46135. name: attributeName,
  46136. count: bufferAttribute.count,
  46137. itemSize: bufferAttribute.itemSize,
  46138. type: geometry.attributes.position.array.constructor,
  46139. version: 0
  46140. });
  46141. }
  46142. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  46143. gl.bindVertexArray(null);
  46144. let disposeHandler = (event) => {
  46145. this.deleteBuffer(geometry);
  46146. geometry.removeEventListener("dispose", disposeHandler);
  46147. };
  46148. geometry.addEventListener("dispose", disposeHandler);
  46149. return webglBuffer;
  46150. }
  46151. updateBuffer(geometry){
  46152. let gl = this.gl;
  46153. let webglBuffer = this.buffers.get(geometry);
  46154. gl.bindVertexArray(webglBuffer.vao);
  46155. for(let attributeName in geometry.attributes){
  46156. let bufferAttribute = geometry.attributes[attributeName];
  46157. let normalized = bufferAttribute.normalized;
  46158. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  46159. let vbo = null;
  46160. if(!webglBuffer.vbos.has(attributeName)){
  46161. vbo = gl.createBuffer();
  46162. webglBuffer.vbos.set(attributeName, {
  46163. handle: vbo,
  46164. name: attributeName,
  46165. count: bufferAttribute.count,
  46166. itemSize: bufferAttribute.itemSize,
  46167. type: geometry.attributes.position.array.constructor,
  46168. version: bufferAttribute.version
  46169. });
  46170. }else {
  46171. vbo = webglBuffer.vbos.get(attributeName).handle;
  46172. webglBuffer.vbos.get(attributeName).version = bufferAttribute.version;
  46173. }
  46174. gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
  46175. gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW);
  46176. if(attributeLocations[attributeName] === undefined){
  46177. //attributeLocation = attributeLocations["aExtra"];
  46178. }else {
  46179. let attributeLocation = attributeLocations[attributeName].location;
  46180. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  46181. gl.enableVertexAttribArray(attributeLocation);
  46182. }
  46183. }
  46184. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  46185. gl.bindVertexArray(null);
  46186. }
  46187. traverse(scene) {
  46188. let octrees = [];
  46189. let stack = [scene];
  46190. while (stack.length > 0) {
  46191. let node = stack.pop();
  46192. if (node instanceof PointCloudTree) {
  46193. octrees.push(node);
  46194. continue;
  46195. }
  46196. let visibleChildren = node.children.filter(c => c.visible);
  46197. stack.push(...visibleChildren);
  46198. }
  46199. let result = {
  46200. octrees: octrees
  46201. };
  46202. return result;
  46203. }
  46204. renderNodes(octree, nodes, visibilityTextureData, camera, target, shader, params) {
  46205. if (exports.measureTimings) performance.mark("renderNodes-start");
  46206. let gl = this.gl;
  46207. let material = params.material ? params.material : octree.material;
  46208. let shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  46209. let view = camera.matrixWorldInverse;
  46210. if(params.viewOverride){
  46211. view = params.viewOverride;
  46212. }
  46213. let worldView = new Matrix4();
  46214. let mat4holder = new Float32Array(16);
  46215. let i = 0;
  46216. for (let node of nodes) {
  46217. if(exports.debug.allowedNodes !== undefined){
  46218. if(!exports.debug.allowedNodes.includes(node.name)){
  46219. continue;
  46220. }
  46221. }
  46222. let world = node.sceneNode.matrixWorld;
  46223. worldView.multiplyMatrices(view, world);
  46224. if (visibilityTextureData) {
  46225. let vnStart = visibilityTextureData.offsets.get(node);
  46226. shader.setUniform1f("uVNStart", vnStart);
  46227. }
  46228. let level = node.getLevel();
  46229. if(node.debug){
  46230. shader.setUniform("uDebug", true);
  46231. }else {
  46232. shader.setUniform("uDebug", false);
  46233. }
  46234. // let isLeaf = false;
  46235. // if(node instanceof PointCloudOctreeNode){
  46236. // isLeaf = Object.keys(node.children).length === 0;
  46237. // }else if(node instanceof PointCloudArena4DNode){
  46238. // isLeaf = node.geometryNode.isLeaf;
  46239. // }
  46240. // shader.setUniform("uIsLeafNode", isLeaf);
  46241. // let isLeaf = node.children.filter(n => n != null).length === 0;
  46242. // if(!isLeaf){
  46243. // continue;
  46244. // }
  46245. // TODO consider passing matrices in an array to avoid uniformMatrix4fv overhead
  46246. const lModel = shader.uniformLocations["modelMatrix"];
  46247. if (lModel) {
  46248. mat4holder.set(world.elements);
  46249. gl.uniformMatrix4fv(lModel, false, mat4holder);
  46250. }
  46251. const lModelView = shader.uniformLocations["modelViewMatrix"];
  46252. //mat4holder.set(worldView.elements);
  46253. // faster then set in chrome 63
  46254. for(let j = 0; j < 16; j++){
  46255. mat4holder[j] = worldView.elements[j];
  46256. }
  46257. gl.uniformMatrix4fv(lModelView, false, mat4holder);
  46258. { // Clip Polygons
  46259. if(material.clipPolygons && material.clipPolygons.length > 0){
  46260. let clipPolygonVCount = [];
  46261. let worldViewProjMatrices = [];
  46262. for(let clipPolygon of material.clipPolygons){
  46263. let view = clipPolygon.viewMatrix;
  46264. let proj = clipPolygon.projMatrix;
  46265. let worldViewProj = proj.clone().multiply(view).multiply(world);
  46266. clipPolygonVCount.push(clipPolygon.markers.length);
  46267. worldViewProjMatrices.push(worldViewProj);
  46268. }
  46269. let flattenedMatrices = [].concat(...worldViewProjMatrices.map(m => m.elements));
  46270. let flattenedVertices = new Array(8 * 3 * material.clipPolygons.length);
  46271. for(let i = 0; i < material.clipPolygons.length; i++){
  46272. let clipPolygon = material.clipPolygons[i];
  46273. for(let j = 0; j < clipPolygon.markers.length; j++){
  46274. flattenedVertices[i * 24 + (j * 3 + 0)] = clipPolygon.markers[j].position.x;
  46275. flattenedVertices[i * 24 + (j * 3 + 1)] = clipPolygon.markers[j].position.y;
  46276. flattenedVertices[i * 24 + (j * 3 + 2)] = clipPolygon.markers[j].position.z;
  46277. }
  46278. }
  46279. const lClipPolygonVCount = shader.uniformLocations["uClipPolygonVCount[0]"];
  46280. gl.uniform1iv(lClipPolygonVCount, clipPolygonVCount);
  46281. const lClipPolygonVP = shader.uniformLocations["uClipPolygonWVP[0]"];
  46282. gl.uniformMatrix4fv(lClipPolygonVP, false, flattenedMatrices);
  46283. const lClipPolygons = shader.uniformLocations["uClipPolygonVertices[0]"];
  46284. gl.uniform3fv(lClipPolygons, flattenedVertices);
  46285. }
  46286. }
  46287. //shader.setUniformMatrix4("modelMatrix", world);
  46288. //shader.setUniformMatrix4("modelViewMatrix", worldView);
  46289. shader.setUniform1f("uLevel", level);
  46290. shader.setUniform1f("uNodeSpacing", node.geometryNode.estimatedSpacing);
  46291. shader.setUniform1f("uPCIndex", i);
  46292. // uBBSize
  46293. if (shadowMaps.length > 0) {
  46294. const lShadowMap = shader.uniformLocations["uShadowMap[0]"];
  46295. shader.setUniform3f("uShadowColor", material.uniforms.uShadowColor.value);
  46296. let bindingStart = 5;
  46297. let bindingPoints = new Array(shadowMaps.length).fill(bindingStart).map((a, i) => (a + i));
  46298. gl.uniform1iv(lShadowMap, bindingPoints);
  46299. for (let i = 0; i < shadowMaps.length; i++) {
  46300. let shadowMap = shadowMaps[i];
  46301. let bindingPoint = bindingPoints[i];
  46302. let glTexture = this.threeRenderer.properties.get(shadowMap.target.texture).__webglTexture;
  46303. gl.activeTexture(gl[`TEXTURE${bindingPoint}`]);
  46304. gl.bindTexture(gl.TEXTURE_2D, glTexture);
  46305. }
  46306. {
  46307. let worldViewMatrices = shadowMaps
  46308. .map(sm => sm.camera.matrixWorldInverse)
  46309. .map(view => new Matrix4().multiplyMatrices(view, world));
  46310. let flattenedMatrices = [].concat(...worldViewMatrices.map(c => c.elements));
  46311. const lWorldView = shader.uniformLocations["uShadowWorldView[0]"];
  46312. gl.uniformMatrix4fv(lWorldView, false, flattenedMatrices);
  46313. }
  46314. {
  46315. let flattenedMatrices = [].concat(...shadowMaps.map(sm => sm.camera.projectionMatrix.elements));
  46316. const lProj = shader.uniformLocations["uShadowProj[0]"];
  46317. gl.uniformMatrix4fv(lProj, false, flattenedMatrices);
  46318. }
  46319. }
  46320. const geometry = node.geometryNode.geometry;
  46321. if(geometry.attributes["gps-time"]){
  46322. const bufferAttribute = geometry.attributes["gps-time"];
  46323. const attGPS = octree.getAttribute("gps-time");
  46324. let initialRange = attGPS.initialRange;
  46325. let initialRangeSize = initialRange[1] - initialRange[0];
  46326. let globalRange = attGPS.range;
  46327. let globalRangeSize = globalRange[1] - globalRange[0];
  46328. let scale = initialRangeSize / globalRangeSize;
  46329. let offset = -(globalRange[0] - initialRange[0]) / initialRangeSize;
  46330. scale = Number.isNaN(scale) ? 1 : scale;
  46331. offset = Number.isNaN(offset) ? 0 : offset;
  46332. shader.setUniform1f("uGpsScale", scale);
  46333. shader.setUniform1f("uGpsOffset", offset);
  46334. //shader.setUniform2f("uFilterGPSTimeClipRange", [-Infinity, Infinity]);
  46335. let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  46336. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  46337. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  46338. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  46339. let normalizedClipRange = [
  46340. (uFilterGPSTimeClipRange[0] - globalRange[0]) / globalRangeSize,
  46341. (uFilterGPSTimeClipRange[1] - globalRange[0]) / globalRangeSize,
  46342. ];
  46343. shader.setUniform2f("uFilterGPSTimeClipRange", normalizedClipRange);
  46344. // // ranges in full gps coordinate system
  46345. // const globalRange = attGPS.range;
  46346. // const bufferRange = bufferAttribute.potree.range;
  46347. // // ranges in [0, 1]
  46348. // // normalizedGlobalRange = [0, 1]
  46349. // // normalizedBufferRange: norm buffer within norm global range e.g. [0.2, 0.8]
  46350. // const globalWidth = globalRange[1] - globalRange[0];
  46351. // const normalizedBufferRange = [
  46352. // (bufferRange[0] - globalRange[0]) / globalWidth,
  46353. // (bufferRange[1] - globalRange[0]) / globalWidth,
  46354. // ];
  46355. // shader.setUniform2f("uNormalizedGpsBufferRange", normalizedBufferRange);
  46356. // let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  46357. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  46358. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  46359. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  46360. // shader.setUniform1f("uGpsScale", bufferAttribute.potree.scale);
  46361. // shader.setUniform1f("uGpsOffset", bufferAttribute.potree.offset);
  46362. }
  46363. {
  46364. let uFilterReturnNumberRange = material.uniforms.uFilterReturnNumberRange.value;
  46365. let uFilterNumberOfReturnsRange = material.uniforms.uFilterNumberOfReturnsRange.value;
  46366. let uFilterPointSourceIDClipRange = material.uniforms.uFilterPointSourceIDClipRange.value;
  46367. shader.setUniform2f("uFilterReturnNumberRange", uFilterReturnNumberRange);
  46368. shader.setUniform2f("uFilterNumberOfReturnsRange", uFilterNumberOfReturnsRange);
  46369. shader.setUniform2f("uFilterPointSourceIDClipRange", uFilterPointSourceIDClipRange);
  46370. }
  46371. let webglBuffer = null;
  46372. if(!this.buffers.has(geometry)){
  46373. webglBuffer = this.createBuffer(geometry);
  46374. this.buffers.set(geometry, webglBuffer);
  46375. }else {
  46376. webglBuffer = this.buffers.get(geometry);
  46377. for(let attributeName in geometry.attributes){
  46378. let attribute = geometry.attributes[attributeName];
  46379. if(attribute.version > webglBuffer.vbos.get(attributeName).version){
  46380. this.updateBuffer(geometry);
  46381. }
  46382. }
  46383. }
  46384. gl.bindVertexArray(webglBuffer.vao);
  46385. let isExtraAttribute =
  46386. attributeLocations[material.activeAttributeName] === undefined
  46387. && Object.keys(geometry.attributes).includes(material.activeAttributeName);
  46388. if(isExtraAttribute){
  46389. const attributeLocation = attributeLocations["aExtra"].location;
  46390. for(const attributeName in geometry.attributes){
  46391. const bufferAttribute = geometry.attributes[attributeName];
  46392. const vbo = webglBuffer.vbos.get(attributeName);
  46393. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  46394. gl.disableVertexAttribArray(attributeLocation);
  46395. }
  46396. const attName = material.activeAttributeName;
  46397. const bufferAttribute = geometry.attributes[attName];
  46398. const vbo = webglBuffer.vbos.get(attName);
  46399. if(bufferAttribute !== undefined && vbo !== undefined){
  46400. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  46401. let normalized = bufferAttribute.normalized;
  46402. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  46403. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  46404. gl.enableVertexAttribArray(attributeLocation);
  46405. }
  46406. {
  46407. const attExtra = octree.pcoGeometry.pointAttributes.attributes
  46408. .find(a => a.name === attName);
  46409. let range = material.getRange(attName);
  46410. if(!range){
  46411. range = attExtra.range;
  46412. }
  46413. if(!range){
  46414. range = [0, 1];
  46415. }
  46416. let initialRange = attExtra.initialRange;
  46417. let initialRangeSize = initialRange[1] - initialRange[0];
  46418. let globalRange = range;
  46419. let globalRangeSize = globalRange[1] - globalRange[0];
  46420. let scale = initialRangeSize / globalRangeSize;
  46421. let offset = -(globalRange[0] - initialRange[0]) / initialRangeSize;
  46422. scale = Number.isNaN(scale) ? 1 : scale;
  46423. offset = Number.isNaN(offset) ? 0 : offset;
  46424. shader.setUniform1f("uExtraScale", scale);
  46425. shader.setUniform1f("uExtraOffset", offset);
  46426. }
  46427. }else {
  46428. for(const attributeName in geometry.attributes){
  46429. const bufferAttribute = geometry.attributes[attributeName];
  46430. const vbo = webglBuffer.vbos.get(attributeName);
  46431. if(attributeLocations[attributeName] !== undefined){
  46432. const attributeLocation = attributeLocations[attributeName].location;
  46433. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  46434. let normalized = bufferAttribute.normalized;
  46435. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  46436. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  46437. gl.enableVertexAttribArray(attributeLocation);
  46438. }
  46439. }
  46440. }
  46441. let numPoints = webglBuffer.numElements;
  46442. gl.drawArrays(gl.POINTS, 0, numPoints);
  46443. //gl.drawArrays(gl.TRIANGLES, 0, numPoints);
  46444. i++;
  46445. }
  46446. gl.bindVertexArray(null);
  46447. if (exports.measureTimings) {
  46448. performance.mark("renderNodes-end");
  46449. performance.measure("render.renderNodes", "renderNodes-start", "renderNodes-end");
  46450. }
  46451. }
  46452. renderOctree(octree, nodes, camera, target, params = {}){
  46453. let gl = this.gl;
  46454. let material = params.material ? params.material : octree.material;
  46455. let shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  46456. let view = camera.matrixWorldInverse;
  46457. let viewInv = camera.matrixWorld;
  46458. if(params.viewOverride){
  46459. view = params.viewOverride;
  46460. viewInv = view.clone().invert();
  46461. }
  46462. let proj = camera.projectionMatrix;
  46463. let projInv = proj.clone().invert();
  46464. //let worldView = new THREE.Matrix4();
  46465. let shader = null;
  46466. let visibilityTextureData = null;
  46467. let currentTextureBindingPoint = 0;
  46468. if (material.pointSizeType >= 0) {
  46469. if (material.pointSizeType === PointSizeType.ADAPTIVE ||
  46470. material.activeAttributeName === "level of detail") {
  46471. let vnNodes = (params.vnTextureNodes != null) ? params.vnTextureNodes : nodes;
  46472. visibilityTextureData = octree.computeVisibilityTextureData(vnNodes, camera);
  46473. const vnt = material.visibleNodesTexture;
  46474. const data = vnt.image.data;
  46475. data.set(visibilityTextureData.data);
  46476. vnt.needsUpdate = true;
  46477. }
  46478. }
  46479. { // UPDATE SHADER AND TEXTURES
  46480. if (!this.shaders.has(material)) {
  46481. let [vs, fs] = [material.vertexShader, material.fragmentShader];
  46482. let shader = new Shader(gl, "pointcloud", vs, fs);
  46483. this.shaders.set(material, shader);
  46484. }
  46485. shader = this.shaders.get(material);
  46486. //if(material.needsUpdate){
  46487. {
  46488. let [vs, fs] = [material.vertexShader, material.fragmentShader];
  46489. let numSnapshots = material.snapEnabled ? material.numSnapshots : 0;
  46490. let numClipBoxes = (material.clipBoxes && material.clipBoxes.length) ? material.clipBoxes.length : 0;
  46491. let numClipSpheres = (params.clipSpheres && params.clipSpheres.length) ? params.clipSpheres.length : 0;
  46492. let numClipPolygons = (material.clipPolygons && material.clipPolygons.length) ? material.clipPolygons.length : 0;
  46493. let defines = [
  46494. `#define num_shadowmaps ${shadowMaps.length}`,
  46495. `#define num_snapshots ${numSnapshots}`,
  46496. `#define num_clipboxes ${numClipBoxes}`,
  46497. `#define num_clipspheres ${numClipSpheres}`,
  46498. `#define num_clippolygons ${numClipPolygons}`,
  46499. ];
  46500. //add:-----------
  46501. if(material.usePanoMap){
  46502. defines.push("#define usePanoMap");
  46503. }
  46504. if(material.useFilterByNormal){
  46505. defines.push("#define use_filter_by_normal");
  46506. //Potree.settings.editType == 'pano' ? defines.push("#define attenuated_opacity2") : defines.push("#define attenuated_opacity");
  46507. }
  46508. //---------------
  46509. if(octree.pcoGeometry.root.isLoaded()){
  46510. let attributes = octree.pcoGeometry.root.geometry.attributes;
  46511. if(attributes["gps-time"]){
  46512. defines.push("#define clip_gps_enabled");
  46513. }
  46514. if(attributes["return number"]){
  46515. defines.push("#define clip_return_number_enabled");
  46516. }
  46517. if(attributes["number of returns"]){
  46518. defines.push("#define clip_number_of_returns_enabled");
  46519. }
  46520. if(attributes["source id"] || attributes["point source id"]){
  46521. defines.push("#define clip_point_source_id_enabled");
  46522. }
  46523. }
  46524. let definesString = defines.join("\n");
  46525. let vsVersionIndex = vs.indexOf("#version ");
  46526. let fsVersionIndex = fs.indexOf("#version ");
  46527. if(vsVersionIndex >= 0){
  46528. vs = vs.replace(/(#version .*)/, `$1\n${definesString}`);
  46529. }else {
  46530. vs = `${definesString}\n${vs}`;
  46531. }
  46532. if(fsVersionIndex >= 0){
  46533. fs = fs.replace(/(#version .*)/, `$1\n${definesString}`);
  46534. }else {
  46535. fs = `${definesString}\n${fs}`;
  46536. }
  46537. shader.update(vs, fs);
  46538. material.needsUpdate = false;
  46539. }
  46540. for (let uniformName of Object.keys(material.uniforms)) {
  46541. let uniform = material.uniforms[uniformName];
  46542. if (uniform.type == "t") {
  46543. let texture = uniform.value;
  46544. if (!texture) {
  46545. continue;
  46546. }
  46547. //add
  46548. if(uniformName == 'pano0Map' || uniformName == 'pano1Map' ){ //属于cubeTex,另外设置
  46549. continue
  46550. }
  46551. if (!this.textures.has(texture)) {
  46552. let webglTexture = new WebGLTexture(gl, texture);
  46553. this.textures.set(texture, webglTexture);
  46554. }
  46555. let webGLTexture = this.textures.get(texture);
  46556. webGLTexture.update();
  46557. }
  46558. }
  46559. }
  46560. gl.useProgram(shader.program);
  46561. let transparent = false;
  46562. if(params.transparent !== undefined){
  46563. transparent = params.transparent && material.opacity < 1;
  46564. }else {
  46565. transparent = material.usePanoMap ? false : (material.useFilterByNormal || material.opacity < 1); //add useFilterByNormal
  46566. }
  46567. if (transparent){
  46568. gl.enable(gl.BLEND);
  46569. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  46570. gl.depthMask(false);
  46571. gl.disable(gl.DEPTH_TEST);
  46572. } else {
  46573. gl.disable(gl.BLEND);
  46574. gl.depthMask(true);
  46575. gl.enable(gl.DEPTH_TEST);
  46576. }
  46577. if(params.blendFunc !== undefined){
  46578. gl.enable(gl.BLEND);
  46579. gl.blendFunc(...params.blendFunc);
  46580. }
  46581. if(params.depthTest !== undefined){
  46582. if(params.depthTest === true){
  46583. gl.enable(gl.DEPTH_TEST);
  46584. }else {
  46585. gl.disable(gl.DEPTH_TEST);
  46586. }
  46587. }
  46588. if(params.depthWrite !== undefined){
  46589. if(params.depthWrite === true){
  46590. gl.depthMask(true);
  46591. }else {
  46592. gl.depthMask(false);
  46593. }
  46594. }
  46595. { // UPDATE UNIFORMS
  46596. shader.setUniformMatrix4("projectionMatrix", proj);
  46597. shader.setUniformMatrix4("viewMatrix", view);
  46598. shader.setUniformMatrix4("uViewInv", viewInv);
  46599. shader.setUniformMatrix4("uProjInv", projInv);
  46600. /* let screenWidth = target ? target.width : material.screenWidth;
  46601. let screenHeight = target ? target.height : material.screenHeight;
  46602. shader.setUniform1f("uScreenWidth", screenWidth);
  46603. shader.setUniform1f("uScreenHeight", screenHeight); */
  46604. shader.setUniform2f('resolution', material.resolution.toArray());
  46605. shader.setUniform1f("fov", Math.PI * camera.fov / 180);
  46606. shader.setUniform1f("near", camera.near);
  46607. shader.setUniform1f("far", camera.far);
  46608. if(camera instanceof OrthographicCamera){
  46609. shader.setUniform("uUseOrthographicCamera", true);
  46610. shader.setUniform("uOrthoWidth", camera.right - camera.left);
  46611. shader.setUniform("uOrthoHeight", camera.top - camera.bottom);
  46612. }else {
  46613. shader.setUniform("uUseOrthographicCamera", false);
  46614. }
  46615. if(material.clipBoxes.length + material.clipPolygons.length === 0){
  46616. shader.setUniform1i("clipTask", ClipTask.NONE);
  46617. }else {
  46618. shader.setUniform1i("clipTask", material.clipTask);
  46619. }
  46620. shader.setUniform1i("clipMethod", material.clipMethod);
  46621. if (material.clipBoxes && material.clipBoxes.length > 0) {
  46622. //let flattenedMatrices = [].concat(...material.clipBoxes.map(c => c.inverse.elements));
  46623. //const lClipBoxes = shader.uniformLocations["clipBoxes[0]"];
  46624. //gl.uniformMatrix4fv(lClipBoxes, false, flattenedMatrices);
  46625. const lClipBoxes = shader.uniformLocations["clipBoxes[0]"];
  46626. gl.uniformMatrix4fv(lClipBoxes, false, material.uniforms.clipBoxes.value);
  46627. }
  46628. // TODO CLIPSPHERES
  46629. if(params.clipSpheres && params.clipSpheres.length > 0){
  46630. let clipSpheres = params.clipSpheres;
  46631. let matrices = [];
  46632. for(let clipSphere of clipSpheres){
  46633. //let mScale = new THREE.Matrix4().makeScale(...clipSphere.scale.toArray());
  46634. //let mTranslate = new THREE.Matrix4().makeTranslation(...clipSphere.position.toArray());
  46635. //let clipToWorld = new THREE.Matrix4().multiplyMatrices(mTranslate, mScale);
  46636. let clipToWorld = clipSphere.matrixWorld;
  46637. let viewToWorld = camera.matrixWorld;
  46638. let worldToClip = clipToWorld.clone().invert();
  46639. let viewToClip = new Matrix4().multiplyMatrices(worldToClip, viewToWorld);
  46640. matrices.push(viewToClip);
  46641. }
  46642. let flattenedMatrices = [].concat(...matrices.map(matrix => matrix.elements));
  46643. const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  46644. gl.uniformMatrix4fv(lClipSpheres, false, flattenedMatrices);
  46645. //const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  46646. //gl.uniformMatrix4fv(lClipSpheres, false, material.uniforms.clipSpheres.value);
  46647. }
  46648. shader.setUniform1f("size", material.usePanoMap ? Potree.config.material.absolutePanoramaSize * Math.min(window.devicePixelRatio,2) : material.size);//usePanoMap时控制在不大不小的范围内感觉较好,考虑到有的点云稀疏,用大一点的点
  46649. shader.setUniform1f("maxSize", material.uniforms.maxSize.value);
  46650. shader.setUniform1f("minSize", material.uniforms.minSize.value);
  46651. // uniform float uPCIndex
  46652. shader.setUniform1f("uOctreeSpacing", material.spacing);
  46653. shader.setUniform("uOctreeSize", material.uniforms.octreeSize.value);
  46654. //uniform vec3 uColor;
  46655. shader.setUniform3f("uColor", material.color.toArray());
  46656. //uniform float opacity;
  46657. shader.setUniform1f("uOpacity", material.usePanoMap ? 1: material.opacity);
  46658. shader.setUniform2f("elevationRange", material.elevationRange);
  46659. shader.setUniform2f("intensityRange", material.intensityRange);
  46660. shader.setUniform3f("uIntensity_gbc", [
  46661. material.intensityGamma,
  46662. material.intensityBrightness,
  46663. material.intensityContrast
  46664. ]);
  46665. shader.setUniform3f("uRGB_gbc", [
  46666. material.rgbGamma,
  46667. material.rgbBrightness,
  46668. material.rgbContrast
  46669. ]);
  46670. shader.setUniform1f("uTransition", material.transition);
  46671. shader.setUniform1f("wRGB", material.weightRGB);
  46672. shader.setUniform1f("wIntensity", material.weightIntensity);
  46673. shader.setUniform1f("wElevation", material.weightElevation);
  46674. shader.setUniform1f("wClassification", material.weightClassification);
  46675. shader.setUniform1f("wReturnNumber", material.weightReturnNumber);
  46676. shader.setUniform1f("wSourceID", material.weightSourceID);
  46677. shader.setUniform("backfaceCulling", material.uniforms.backfaceCulling.value);
  46678. //==========================
  46679. //gl.TEXTURE_CUBE_MAP: 34067
  46680. //gl.TEXTURE0=33984 , vnWebGLTexture.target=gl.TEXTURE_2D = 3353
  46681. let vnWebGLTexture = this.textures.get(material.visibleNodesTexture);
  46682. if(vnWebGLTexture){
  46683. shader.setUniform1i("visibleNodesTexture", currentTextureBindingPoint);
  46684. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  46685. gl.bindTexture(vnWebGLTexture.target, vnWebGLTexture.id);
  46686. currentTextureBindingPoint++;
  46687. }
  46688. let gradientTexture = this.textures.get(material.gradientTexture);
  46689. shader.setUniform1i("gradient", currentTextureBindingPoint);
  46690. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  46691. gl.bindTexture(gradientTexture.target, gradientTexture.id);
  46692. const repeat = material.elevationGradientRepeat;
  46693. if(repeat === ElevationGradientRepeat.REPEAT){
  46694. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.REPEAT);
  46695. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.REPEAT);
  46696. }else if(repeat === ElevationGradientRepeat.MIRRORED_REPEAT){
  46697. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT);
  46698. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT);
  46699. }else {
  46700. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  46701. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  46702. }
  46703. currentTextureBindingPoint++;
  46704. let classificationTexture = this.textures.get(material.classificationTexture);
  46705. shader.setUniform1i("classificationLUT", currentTextureBindingPoint);
  46706. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  46707. gl.bindTexture(classificationTexture.target, classificationTexture.id);
  46708. currentTextureBindingPoint++;
  46709. let matcapTexture = this.textures.get(material.matcapTexture);
  46710. shader.setUniform1i("matcapTextureUniform", currentTextureBindingPoint);
  46711. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  46712. gl.bindTexture(matcapTexture.target, matcapTexture.id);
  46713. currentTextureBindingPoint++;
  46714. if (material.snapEnabled === true) {
  46715. {
  46716. const lSnapshot = shader.uniformLocations["uSnapshot[0]"];
  46717. const lSnapshotDepth = shader.uniformLocations["uSnapshotDepth[0]"];
  46718. let bindingStart = currentTextureBindingPoint;
  46719. let lSnapshotBindingPoints = new Array(5).fill(bindingStart).map((a, i) => (a + i));
  46720. let lSnapshotDepthBindingPoints = new Array(5)
  46721. .fill(1 + Math.max(...lSnapshotBindingPoints))
  46722. .map((a, i) => (a + i));
  46723. currentTextureBindingPoint = 1 + Math.max(...lSnapshotDepthBindingPoints);
  46724. gl.uniform1iv(lSnapshot, lSnapshotBindingPoints);
  46725. gl.uniform1iv(lSnapshotDepth, lSnapshotDepthBindingPoints);
  46726. for (let i = 0; i < 5; i++) {
  46727. let texture = material.uniforms[`uSnapshot`].value[i];
  46728. let textureDepth = material.uniforms[`uSnapshotDepth`].value[i];
  46729. if (!texture) {
  46730. break;
  46731. }
  46732. let snapTexture = this.threeRenderer.properties.get(texture).__webglTexture;
  46733. let snapTextureDepth = this.threeRenderer.properties.get(textureDepth).__webglTexture;
  46734. let bindingPoint = lSnapshotBindingPoints[i];
  46735. let depthBindingPoint = lSnapshotDepthBindingPoints[i];
  46736. gl.activeTexture(gl[`TEXTURE${bindingPoint}`]);
  46737. gl.bindTexture(gl.TEXTURE_2D, snapTexture);
  46738. gl.activeTexture(gl[`TEXTURE${depthBindingPoint}`]);
  46739. gl.bindTexture(gl.TEXTURE_2D, snapTextureDepth);
  46740. }
  46741. }
  46742. {
  46743. let flattenedMatrices = [].concat(...material.uniforms.uSnapView.value.map(c => c.elements));
  46744. const lSnapView = shader.uniformLocations["uSnapView[0]"];
  46745. gl.uniformMatrix4fv(lSnapView, false, flattenedMatrices);
  46746. }
  46747. {
  46748. let flattenedMatrices = [].concat(...material.uniforms.uSnapProj.value.map(c => c.elements));
  46749. const lSnapProj = shader.uniformLocations["uSnapProj[0]"];
  46750. gl.uniformMatrix4fv(lSnapProj, false, flattenedMatrices);
  46751. }
  46752. {
  46753. let flattenedMatrices = [].concat(...material.uniforms.uSnapProjInv.value.map(c => c.elements));
  46754. const lSnapProjInv = shader.uniformLocations["uSnapProjInv[0]"];
  46755. gl.uniformMatrix4fv(lSnapProjInv, false, flattenedMatrices);
  46756. }
  46757. {
  46758. let flattenedMatrices = [].concat(...material.uniforms.uSnapViewInv.value.map(c => c.elements));
  46759. const lSnapViewInv = shader.uniformLocations["uSnapViewInv[0]"];
  46760. gl.uniformMatrix4fv(lSnapViewInv, false, flattenedMatrices);
  46761. }
  46762. }
  46763. //=============add===========
  46764. if(material.usePanoMap){//为什么pointsize失效
  46765. shader.setUniform1f("progress", material.uniforms.progress.value);
  46766. shader.setUniform1f("easeInOutRatio", material.uniforms.easeInOutRatio.value);
  46767. shader.setUniform3f("pano0Position", material.uniforms.pano0Position.value.toArray());
  46768. shader.setUniform3f("pano1Position", material.uniforms.pano1Position.value.toArray());
  46769. shader.setUniform('pano0Matrix', material.uniforms.pano0Matrix.value);
  46770. shader.setUniform('pano1Matrix', material.uniforms.pano1Matrix.value);
  46771. let pano0Map = material.uniforms.pano0Map.value;
  46772. if(pano0Map){
  46773. this.threeRenderer._textures.safeSetTextureCube( pano0Map, ++currentTextureBindingPoint );
  46774. shader.setUniform1i('pano0Map', currentTextureBindingPoint);
  46775. }
  46776. let pano1Map = material.uniforms.pano1Map.value;
  46777. if(pano1Map){
  46778. this.threeRenderer._textures.safeSetTextureCube( pano1Map, ++currentTextureBindingPoint );
  46779. shader.setUniform1i('pano1Map', currentTextureBindingPoint);
  46780. }
  46781. //注: three.js我添加了个 _textures, safeSetTextureCube里主要就是activeTexture和bindTexture
  46782. }
  46783. }
  46784. this.renderNodes(octree, nodes, visibilityTextureData, camera, target, shader, params);
  46785. gl.activeTexture(gl.TEXTURE2);
  46786. gl.bindTexture(gl.TEXTURE_2D, null);
  46787. gl.activeTexture(gl.TEXTURE0);
  46788. //gl.bindTexture(gl.TEXTURE_2D, null); //add
  46789. //add 恢复为不透明(否则renderToCubeMap时的贴图会被渲染成高亮的颜色)
  46790. gl.disable(gl.BLEND);
  46791. gl.depthMask(true);
  46792. gl.enable(gl.DEPTH_TEST);
  46793. //DEPTH_TEST等需要恢复吗
  46794. }
  46795. render(scene, camera, target = null, params = {}) {
  46796. const gl = this.gl;
  46797. // PREPARE
  46798. if (target != null) {
  46799. this.threeRenderer.setRenderTarget(target);
  46800. }
  46801. //camera.updateProjectionMatrix();
  46802. // camera.matrixWorldInverse.invert(camera.matrixWorld);
  46803. const traversalResult = this.traverse(scene);
  46804. // RENDER
  46805. for (const octree of traversalResult.octrees) {
  46806. let nodes = octree.visibleNodes;
  46807. this.renderOctree(octree, nodes, camera, target, params);
  46808. }
  46809. // CLEANUP
  46810. gl.activeTexture(gl.TEXTURE1);
  46811. gl.bindTexture(gl.TEXTURE_2D, null);
  46812. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  46813. gl.bindVertexArray(null);
  46814. this.threeRenderer.resetState();
  46815. }
  46816. };
  46817. /*
  46818. 中东的链接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
  46819. geometry: 有的attributes: 属性是:
  46820. classification:
  46821. color:
  46822. indices:
  46823. normal:
  46824. position:
  46825. 最好有个spacing
  46826. */
  46827. class ProfileData {
  46828. constructor (profile) {
  46829. this.profile = profile;
  46830. this.segments = [];
  46831. this.boundingBox = new Box3();
  46832. for (let i = 0; i < profile.points.length - 1; i++) {
  46833. let start = profile.points[i];
  46834. let end = profile.points[i + 1];
  46835. let startGround = new Vector3(start.x, start.y, 0);
  46836. let endGround = new Vector3(end.x, end.y, 0);
  46837. let center = new Vector3().addVectors(endGround, startGround).multiplyScalar(0.5);
  46838. let length = startGround.distanceTo(endGround);
  46839. let side = new Vector3().subVectors(endGround, startGround).normalize();
  46840. let up = new Vector3(0, 0, 1);
  46841. let forward = new Vector3().crossVectors(side, up).normalize();
  46842. let N = forward;
  46843. let cutPlane = new Plane().setFromNormalAndCoplanarPoint(N, startGround);
  46844. let halfPlane = new Plane().setFromNormalAndCoplanarPoint(side, center);
  46845. let segment = {
  46846. start: start,
  46847. end: end,
  46848. cutPlane: cutPlane,
  46849. halfPlane: halfPlane,
  46850. length: length,
  46851. points: new Points$1()
  46852. };
  46853. this.segments.push(segment);
  46854. }
  46855. }
  46856. size () {
  46857. let size = 0;
  46858. for (let segment of this.segments) {
  46859. size += segment.points.numPoints;
  46860. }
  46861. return size;
  46862. }
  46863. };
  46864. class ProfileRequest {
  46865. constructor (pointcloud, profile, maxDepth, callback) {
  46866. this.pointcloud = pointcloud;
  46867. this.profile = profile;
  46868. this.maxDepth = maxDepth || Number.MAX_VALUE;
  46869. this.callback = callback;
  46870. this.temporaryResult = new ProfileData(this.profile);
  46871. this.pointsServed = 0;
  46872. this.highestLevelServed = 0;
  46873. this.priorityQueue = new BinaryHeap(function (x) { return 1 / x.weight; });
  46874. this.initialize();
  46875. }
  46876. initialize () {
  46877. this.priorityQueue.push({node: this.pointcloud.pcoGeometry.root, weight: Infinity});
  46878. };
  46879. // traverse the node and add intersecting descendants to queue
  46880. traverse (node) {
  46881. let stack = [];
  46882. for (let i = 0; i < 8; i++) {
  46883. let child = node.children[i];
  46884. if (child && this.pointcloud.nodeIntersectsProfile(child, this.profile)) {
  46885. stack.push(child);
  46886. }
  46887. }
  46888. while (stack.length > 0) {
  46889. let node = stack.pop();
  46890. let weight = node.boundingSphere.radius;
  46891. this.priorityQueue.push({node: node, weight: weight});
  46892. // add children that intersect the cutting plane
  46893. if (node.level < this.maxDepth) {
  46894. for (let i = 0; i < 8; i++) {
  46895. let child = node.children[i];
  46896. if (child && this.pointcloud.nodeIntersectsProfile(child, this.profile)) {
  46897. stack.push(child);
  46898. }
  46899. }
  46900. }
  46901. }
  46902. }
  46903. update(){
  46904. if(!this.updateGeneratorInstance){
  46905. this.updateGeneratorInstance = this.updateGenerator();
  46906. }
  46907. let result = this.updateGeneratorInstance.next();
  46908. if(result.done){
  46909. this.updateGeneratorInstance = null;
  46910. }
  46911. }
  46912. * updateGenerator(){
  46913. // load nodes in queue
  46914. // if hierarchy expands, also load nodes from expanded hierarchy
  46915. // once loaded, add data to this.points and remove node from queue
  46916. // only evaluate 1-50 nodes per frame to maintain responsiveness
  46917. let start = performance.now();
  46918. let maxNodesPerUpdate = 1;
  46919. let intersectedNodes = [];
  46920. for (let i = 0; i < Math.min(maxNodesPerUpdate, this.priorityQueue.size()); i++) {
  46921. let element = this.priorityQueue.pop();
  46922. let node = element.node;
  46923. if(node.level > this.maxDepth){
  46924. continue;
  46925. }
  46926. if (node.loaded) {
  46927. // add points to result
  46928. intersectedNodes.push(node);
  46929. exports.lru.touch(node);
  46930. this.highestLevelServed = Math.max(node.getLevel(), this.highestLevelServed);
  46931. var geom = node.pcoGeometry;
  46932. var hierarchyStepSize = geom ? geom.hierarchyStepSize : 1;
  46933. var doTraverse = node.getLevel() === 0 ||
  46934. (node.level % hierarchyStepSize === 0 && node.hasChildren);
  46935. if (doTraverse) {
  46936. this.traverse(node);
  46937. }
  46938. } else {
  46939. node.load();
  46940. this.priorityQueue.push(element);
  46941. }
  46942. }
  46943. if (intersectedNodes.length > 0) {
  46944. for(let done of this.getPointsInsideProfile(intersectedNodes, this.temporaryResult)){
  46945. if(!done){
  46946. //console.log("updateGenerator yields");
  46947. yield false;
  46948. }
  46949. }
  46950. if (this.temporaryResult.size() > 100) {
  46951. this.pointsServed += this.temporaryResult.size();
  46952. this.callback.onProgress({request: this, points: this.temporaryResult});
  46953. this.temporaryResult = new ProfileData(this.profile);
  46954. }
  46955. }
  46956. if (this.priorityQueue.size() === 0) {
  46957. // we're done! inform callback and remove from pending requests
  46958. if (this.temporaryResult.size() > 0) {
  46959. this.pointsServed += this.temporaryResult.size();
  46960. this.callback.onProgress({request: this, points: this.temporaryResult});
  46961. this.temporaryResult = new ProfileData(this.profile);
  46962. }
  46963. this.callback.onFinish({request: this});
  46964. let index = this.pointcloud.profileRequests.indexOf(this);
  46965. if (index >= 0) {
  46966. this.pointcloud.profileRequests.splice(index, 1);
  46967. }
  46968. }
  46969. yield true;
  46970. };
  46971. * getAccepted(numPoints, node, matrix, segment, segmentDir, points, totalMileage){
  46972. let checkpoint = performance.now();
  46973. let accepted = new Uint32Array(numPoints);
  46974. let mileage = new Float64Array(numPoints);
  46975. let acceptedPositions = new Float32Array(numPoints * 3);
  46976. let numAccepted = 0;
  46977. let pos = new Vector3();
  46978. let svp = new Vector3();
  46979. let view = new Float32Array(node.geometry.attributes.position.array);
  46980. for (let i = 0; i < numPoints; i++) {
  46981. pos.set(
  46982. view[i * 3 + 0],
  46983. view[i * 3 + 1],
  46984. view[i * 3 + 2]);
  46985. pos.applyMatrix4(matrix);
  46986. let distance = Math.abs(segment.cutPlane.distanceToPoint(pos));
  46987. let centerDistance = Math.abs(segment.halfPlane.distanceToPoint(pos));
  46988. if (distance < this.profile.width / 2 && centerDistance < segment.length / 2) {
  46989. svp.subVectors(pos, segment.start);
  46990. let localMileage = segmentDir.dot(svp);
  46991. accepted[numAccepted] = i;
  46992. mileage[numAccepted] = localMileage + totalMileage;
  46993. points.boundingBox.expandByPoint(pos);
  46994. pos.sub(this.pointcloud.position);
  46995. acceptedPositions[3 * numAccepted + 0] = pos.x;
  46996. acceptedPositions[3 * numAccepted + 1] = pos.y;
  46997. acceptedPositions[3 * numAccepted + 2] = pos.z;
  46998. numAccepted++;
  46999. }
  47000. if((i % 1000) === 0){
  47001. let duration = performance.now() - checkpoint;
  47002. if(duration > 4){
  47003. //console.log(`getAccepted yield after ${duration}ms`);
  47004. yield false;
  47005. checkpoint = performance.now();
  47006. }
  47007. }
  47008. }
  47009. accepted = accepted.subarray(0, numAccepted);
  47010. mileage = mileage.subarray(0, numAccepted);
  47011. acceptedPositions = acceptedPositions.subarray(0, numAccepted * 3);
  47012. //let end = performance.now();
  47013. //let duration = end - start;
  47014. //console.log("accepted duration ", duration)
  47015. //console.log(`getAccepted finished`);
  47016. yield [accepted, mileage, acceptedPositions];
  47017. }
  47018. * getPointsInsideProfile(nodes, target){
  47019. let checkpoint = performance.now();
  47020. let totalMileage = 0;
  47021. let pointsProcessed = 0;
  47022. for (let segment of target.segments) {
  47023. for (let node of nodes) {
  47024. let numPoints = node.numPoints;
  47025. let geometry = node.geometry;
  47026. if(!numPoints){
  47027. continue;
  47028. }
  47029. { // skip if current node doesn't intersect current segment
  47030. let bbWorld = node.boundingBox.clone().applyMatrix4(this.pointcloud.matrixWorld);
  47031. let bsWorld = bbWorld.getBoundingSphere(new Sphere());
  47032. let start = new Vector3(segment.start.x, segment.start.y, bsWorld.center.z);
  47033. let end = new Vector3(segment.end.x, segment.end.y, bsWorld.center.z);
  47034. let closest = new Line3(start, end).closestPointToPoint(bsWorld.center, true, new Vector3());
  47035. let distance = closest.distanceTo(bsWorld.center);
  47036. let intersects = (distance < (bsWorld.radius + target.profile.width));
  47037. if(!intersects){
  47038. continue;
  47039. }
  47040. }
  47041. //{// DEBUG
  47042. // console.log(node.name);
  47043. // let boxHelper = new Potree.Box3Helper(node.getBoundingBox());
  47044. // boxHelper.matrixAutoUpdate = false;
  47045. // boxHelper.matrix.copy(viewer.scene.pointclouds[0].matrixWorld);
  47046. // viewer.scene.scene.add(boxHelper);
  47047. //}
  47048. let sv = new Vector3().subVectors(segment.end, segment.start).setZ(0);
  47049. let segmentDir = sv.clone().normalize();
  47050. let points = new Points$1();
  47051. let nodeMatrix = new Matrix4().makeTranslation(...node.boundingBox.min.toArray());
  47052. let matrix = new Matrix4().multiplyMatrices(
  47053. this.pointcloud.matrixWorld, nodeMatrix);
  47054. pointsProcessed = pointsProcessed + numPoints;
  47055. let accepted = null;
  47056. let mileage = null;
  47057. let acceptedPositions = null;
  47058. for(let result of this.getAccepted(numPoints, node, matrix, segment, segmentDir, points,totalMileage)){
  47059. if(!result){
  47060. let duration = performance.now() - checkpoint;
  47061. //console.log(`getPointsInsideProfile yield after ${duration}ms`);
  47062. yield false;
  47063. checkpoint = performance.now();
  47064. }else {
  47065. [accepted, mileage, acceptedPositions] = result;
  47066. }
  47067. }
  47068. let duration = performance.now() - checkpoint;
  47069. if(duration > 4){
  47070. //console.log(`getPointsInsideProfile yield after ${duration}ms`);
  47071. yield false;
  47072. checkpoint = performance.now();
  47073. }
  47074. points.data.position = acceptedPositions;
  47075. let relevantAttributes = Object.keys(geometry.attributes).filter(a => !["position", "indices"].includes(a));
  47076. for(let attributeName of relevantAttributes){
  47077. let attribute = geometry.attributes[attributeName];
  47078. let numElements = attribute.array.length / numPoints;
  47079. if(numElements !== parseInt(numElements)){
  47080. debugger;
  47081. }
  47082. let Type = attribute.array.constructor;
  47083. let filteredBuffer = new Type(numElements * accepted.length);
  47084. let source = attribute.array;
  47085. let target = filteredBuffer;
  47086. for(let i = 0; i < accepted.length; i++){
  47087. let index = accepted[i];
  47088. let start = index * numElements;
  47089. let end = start + numElements;
  47090. let sub = source.subarray(start, end);
  47091. target.set(sub, i * numElements);
  47092. }
  47093. points.data[attributeName] = filteredBuffer;
  47094. }
  47095. points.data['mileage'] = mileage;
  47096. points.numPoints = accepted.length;
  47097. segment.points.add(points);
  47098. }
  47099. totalMileage += segment.length;
  47100. }
  47101. for (let segment of target.segments) {
  47102. target.boundingBox.union(segment.points.boundingBox);
  47103. }
  47104. //console.log(`getPointsInsideProfile finished`);
  47105. yield true;
  47106. };
  47107. finishLevelThenCancel () {
  47108. if (this.cancelRequested) {
  47109. return;
  47110. }
  47111. this.maxDepth = this.highestLevelServed;
  47112. this.cancelRequested = true;
  47113. //console.log(`maxDepth: ${this.maxDepth}`);
  47114. };
  47115. cancel () {
  47116. this.callback.onCancel();
  47117. this.priorityQueue = new BinaryHeap(function (x) { return 1 / x.weight; });
  47118. let index = this.pointcloud.profileRequests.indexOf(this);
  47119. if (index >= 0) {
  47120. this.pointcloud.profileRequests.splice(index, 1);
  47121. }
  47122. };
  47123. }
  47124. class Version{
  47125. constructor(version){
  47126. this.version = version;
  47127. let vmLength = (version.indexOf('.') === -1) ? version.length : version.indexOf('.');
  47128. this.versionMajor = parseInt(version.substr(0, vmLength));
  47129. this.versionMinor = parseInt(version.substr(vmLength + 1));
  47130. if (this.versionMinor.length === 0) {
  47131. this.versionMinor = 0;
  47132. }
  47133. }
  47134. newerThan(version){
  47135. let v = new Version(version);
  47136. if (this.versionMajor > v.versionMajor) {
  47137. return true;
  47138. } else if (this.versionMajor === v.versionMajor && this.versionMinor > v.versionMinor) {
  47139. return true;
  47140. } else {
  47141. return false;
  47142. }
  47143. }
  47144. equalOrHigher(version){
  47145. let v = new Version(version);
  47146. if (this.versionMajor > v.versionMajor) {
  47147. return true;
  47148. } else if (this.versionMajor === v.versionMajor && this.versionMinor >= v.versionMinor) {
  47149. return true;
  47150. } else {
  47151. return false;
  47152. }
  47153. }
  47154. upTo(version){
  47155. return !this.newerThan(version);
  47156. }
  47157. }
  47158. class WorkerPool{
  47159. constructor(){
  47160. this.workers = {};
  47161. }
  47162. getWorker(url){
  47163. if (!this.workers[url]){
  47164. this.workers[url] = [];
  47165. }
  47166. if (this.workers[url].length === 0){
  47167. let worker = new Worker(url);
  47168. this.workers[url].push(worker);
  47169. }
  47170. let worker = this.workers[url].pop();
  47171. return worker;
  47172. }
  47173. returnWorker(url, worker){
  47174. this.workers[url].push(worker);
  47175. }
  47176. };
  47177. //Potree.workerPool = new Potree.WorkerPool();
  47178. function createPointcloudData(pointcloud) {
  47179. let material = pointcloud.material;
  47180. let ranges = [];
  47181. for(let [name, value] of material.ranges){
  47182. ranges.push({
  47183. name: name,
  47184. value: value,
  47185. });
  47186. }
  47187. if(typeof material.elevationRange[0] === "number"){
  47188. ranges.push({
  47189. name: "elevationRange",
  47190. value: material.elevationRange,
  47191. });
  47192. }
  47193. if(typeof material.intensityRange[0] === "number"){
  47194. ranges.push({
  47195. name: "intensityRange",
  47196. value: material.intensityRange,
  47197. });
  47198. }
  47199. let pointSizeTypeName = Object.entries(Potree.PointSizeType).find(e => e[1] === material.pointSizeType)[0];
  47200. let jsonMaterial = {
  47201. activeAttributeName: material.activeAttributeName,
  47202. ranges: ranges,
  47203. size: material.size,
  47204. minSize: material.minSize,
  47205. pointSizeType: pointSizeTypeName,
  47206. matcap: material.matcap,
  47207. };
  47208. const pcdata = {
  47209. name: pointcloud.name,
  47210. url: pointcloud.pcoGeometry.url,
  47211. position: pointcloud.position.toArray(),
  47212. rotation: pointcloud.rotation.toArray(),
  47213. scale: pointcloud.scale.toArray(),
  47214. material: jsonMaterial,
  47215. };
  47216. return pcdata;
  47217. }
  47218. function createProfileData(profile){
  47219. const data = {
  47220. uuid: profile.uuid,
  47221. name: profile.name,
  47222. points: profile.points.map(p => p.toArray()),
  47223. height: profile.height,
  47224. width: profile.width,
  47225. };
  47226. return data;
  47227. }
  47228. function createVolumeData(volume){
  47229. const data = {
  47230. uuid: volume.uuid,
  47231. type: volume.constructor.name,
  47232. name: volume.name,
  47233. position: volume.position.toArray(),
  47234. rotation: volume.rotation.toArray(),
  47235. scale: volume.scale.toArray(),
  47236. visible: volume.visible,
  47237. clip: volume.clip,
  47238. };
  47239. return data;
  47240. }
  47241. function createCameraAnimationData(animation){
  47242. const controlPoints = animation.controlPoints.map( cp => {
  47243. const cpdata = {
  47244. position: cp.position.toArray(),
  47245. target: cp.target.toArray(),
  47246. };
  47247. return cpdata;
  47248. });
  47249. const data = {
  47250. uuid: animation.uuid,
  47251. name: animation.name,
  47252. duration: animation.duration,
  47253. t: animation.t,
  47254. curveType: animation.curveType,
  47255. visible: animation.visible,
  47256. controlPoints: controlPoints,
  47257. };
  47258. return data;
  47259. }
  47260. function createMeasurementData(measurement){
  47261. /* const data = {
  47262. uuid: measurement.uuid,
  47263. name: measurement.name,
  47264. measureType:measurement.measureType, //add
  47265. direction:measurement.direction,//add
  47266. minMarkers:measurement.minMarkers,//add
  47267. maxMarkers: measurement.maxMarkers,//add
  47268. isRect: measurement.isRect,//add
  47269. faceDirection: measurement.faceDirection,//add
  47270. points: measurement.points.map(p => p.position.toArray()),
  47271. showDistances: measurement.showDistances,
  47272. showCoordinates: measurement.showCoordinates,
  47273. showArea: measurement.showArea,
  47274. closed: measurement.closed,
  47275. showAngles: measurement.showAngles,
  47276. showHeight: measurement.showHeight,
  47277. showCircle: measurement.showCircle,
  47278. showAzimuth: measurement.showAzimuth,
  47279. showEdges: measurement.showEdges,
  47280. color: measurement.color.toArray(),
  47281. }; */
  47282. const data = {
  47283. uuid: measurement.uuid,
  47284. name: measurement.name,
  47285. measureType:measurement.measureType, //add
  47286. points: measurement.points.map(p => p.toArray()),
  47287. };
  47288. return data;
  47289. }
  47290. function createOrientedImagesData(images){
  47291. const data = {
  47292. cameraParamsPath: images.cameraParamsPath,
  47293. imageParamsPath: images.imageParamsPath,
  47294. };
  47295. return data;
  47296. }
  47297. function createGeopackageData(geopackage){
  47298. const data = {
  47299. path: geopackage.path,
  47300. };
  47301. return data;
  47302. }
  47303. function createAnnotationData(annotation){
  47304. const data = {
  47305. uuid: annotation.uuid,
  47306. title: annotation.title.toString(),
  47307. description: annotation.description,
  47308. position: annotation.position.toArray(),
  47309. offset: annotation.offset.toArray(),
  47310. children: [],
  47311. };
  47312. if(annotation.cameraPosition){
  47313. data.cameraPosition = annotation.cameraPosition.toArray();
  47314. }
  47315. if(annotation.cameraTarget){
  47316. data.cameraTarget = annotation.cameraTarget.toArray();
  47317. }
  47318. if(typeof annotation.radius !== "undefined"){
  47319. data.radius = annotation.radius;
  47320. }
  47321. return data;
  47322. }
  47323. function createAnnotationsData(viewer){
  47324. const map = new Map();
  47325. viewer.scene.annotations.traverseDescendants(a => {
  47326. const aData = createAnnotationData(a);
  47327. map.set(a, aData);
  47328. });
  47329. for(const [annotation, data] of map){
  47330. for(const child of annotation.children){
  47331. const childData = map.get(child);
  47332. data.children.push(childData);
  47333. }
  47334. }
  47335. const annotations = viewer.scene.annotations.children.map(a => map.get(a));
  47336. return annotations;
  47337. }
  47338. function createSettingsData(viewer){
  47339. return {
  47340. pointBudget: viewer.getPointBudget(),
  47341. fov: viewer.getFOV(),
  47342. edlEnabled: viewer.getEDLEnabled(),
  47343. edlRadius: viewer.getEDLRadius(),
  47344. edlStrength: viewer.getEDLStrength(),
  47345. background: viewer.getBackground(),
  47346. minNodeSize: viewer.getMinNodeSize(),
  47347. showBoundingBoxes: viewer.getShowBoundingBox(),
  47348. };
  47349. }
  47350. function createSceneContentData(viewer){
  47351. const data = [];
  47352. const potreeObjects = [];
  47353. viewer.scene.scene.traverse(node => {
  47354. if(node.potree){
  47355. potreeObjects.push(node);
  47356. }
  47357. });
  47358. for(const object of potreeObjects){
  47359. if(object.potree.file){
  47360. const saveObject = {
  47361. file: object.potree.file,
  47362. };
  47363. data.push(saveObject);
  47364. }
  47365. }
  47366. return data;
  47367. }
  47368. function createViewData(viewer){
  47369. const view = viewer.scene.view;
  47370. const data = {
  47371. position: view.position.toArray(),
  47372. target: view.getPivot().toArray(),
  47373. };
  47374. return data;
  47375. }
  47376. function createClassificationData(viewer){
  47377. const classifications = viewer.classifications;
  47378. const data = classifications;
  47379. return data;
  47380. }
  47381. function saveProject(viewer) {
  47382. const scene = viewer.scene;
  47383. const data = {
  47384. type: "Potree",
  47385. version: 1.7,
  47386. settings: createSettingsData(viewer),
  47387. view: createViewData(viewer),
  47388. classification: createClassificationData(viewer),
  47389. pointclouds: scene.pointclouds.map(createPointcloudData),
  47390. measurements: scene.measurements.map(createMeasurementData),
  47391. volumes: scene.volumes.map(createVolumeData),
  47392. cameraAnimations: scene.cameraAnimations.map(createCameraAnimationData),
  47393. profiles: scene.profiles.map(createProfileData),
  47394. annotations: createAnnotationsData(viewer),
  47395. orientedImages: scene.orientedImages.map(createOrientedImagesData),
  47396. geopackages: scene.geopackages.map(createGeopackageData),
  47397. // objects: createSceneContentData(viewer),
  47398. };
  47399. return data;
  47400. }
  47401. class HandleSvg extends EventDispatcher{
  47402. constructor(position, color){
  47403. super();
  47404. this.position = position;
  47405. this.color = '#'+new Color(color).getHexString();
  47406. this.svg = this.create();
  47407. this.visible_ = true;
  47408. let update = ()=>{
  47409. this.update();
  47410. };
  47411. viewer.addEventListener("camera_changed", update);
  47412. this.addEventListener('dispose', ()=>{
  47413. viewer.removeEventListener("camera_changed", update);
  47414. });
  47415. }
  47416. create(){
  47417. const svgns = "http://www.w3.org/2000/svg";
  47418. const svg = document.createElementNS(svgns, "svg");
  47419. svg.setAttribute("width", "2em");
  47420. svg.setAttribute("height", "2em");
  47421. svg.setAttribute("position", "absolute");
  47422. svg.style.left = "50px";
  47423. svg.style.top = "50px";
  47424. svg.style.position = "absolute";
  47425. svg.style.zIndex = "10000";
  47426. svg.style.cursor = 'grab';
  47427. svg.style.transform = 'translate(-50%,-50%)';
  47428. const circle = document.createElementNS(svgns, 'circle');
  47429. circle.setAttributeNS(null, 'cx', "1em");
  47430. circle.setAttributeNS(null, 'cy', "1em");
  47431. circle.setAttributeNS(null, 'r', "0.5em");
  47432. circle.setAttributeNS(null, 'style', 'fill: '+this.color+'; stroke: black; stroke-width: 0.2em;' );
  47433. svg.appendChild(circle);
  47434. const element = viewer.renderer.domElement.parentElement;
  47435. element.appendChild(svg);
  47436. const startDrag = (evt) => {
  47437. /* if(evt.button === THREE.MOUSE.RIGHT){
  47438. return
  47439. } */
  47440. this.selectedElement = svg;
  47441. document.addEventListener("mousemove", drag);
  47442. };
  47443. const endDrag = (evt) => {
  47444. this.selectedElement = null;
  47445. document.removeEventListener("mousemove", drag);
  47446. };
  47447. const drag = (evt) => {
  47448. if (this.selectedElement) {
  47449. evt.preventDefault();
  47450. const rect = viewer.renderer.domElement.getBoundingClientRect();
  47451. const x = evt.clientX - rect.x;
  47452. const y = evt.clientY - rect.y;
  47453. const {width, height} = viewer.renderer.getSize(new Vector2$1());
  47454. const camera = viewer.scene.getActiveCamera();
  47455. const projected = this.position.clone().project(camera);
  47456. projected.x = ((x / width) - 0.5) / 0.5;
  47457. projected.y = (-(y - height) / height - 0.5) / 0.5;
  47458. const unprojected = projected.clone().unproject(camera);
  47459. this.position.set(unprojected.x, unprojected.y, unprojected.z);
  47460. this.update();
  47461. this.dispatchEvent({type:'dragged', position: this.position});
  47462. }
  47463. };
  47464. svg.addEventListener('mousedown', startDrag);
  47465. svg.addEventListener('mouseup', endDrag);
  47466. svg.style.display = this.visible ? "" : "none";
  47467. this.addEventListener('dispose',()=>{
  47468. svg.removeEventListener('mousedown', startDrag);
  47469. svg.removeEventListener('mouseup', endDrag);
  47470. });
  47471. return svg
  47472. }
  47473. set visible(v){
  47474. this.visible_ = v;
  47475. if(v){
  47476. this.update();
  47477. }else {
  47478. this.svg.style.display = "none";
  47479. }
  47480. }
  47481. get visible(){
  47482. return this.visible_
  47483. }
  47484. update(){
  47485. if(!this.visible)return
  47486. let camera = viewer.scene.getActiveCamera();
  47487. var p = Potree.Utils.getPos2d( this.position, camera , viewer.renderArea, viewer.mainViewport);
  47488. if(!p.trueSide){
  47489. return this.svg.style.display = 'none';
  47490. }
  47491. this.svg.style.left = p.posInViewport.x;
  47492. this.svg.style.top = p.posInViewport.y;
  47493. this.svg.style.display = '';
  47494. }
  47495. dispose(){
  47496. this.svg.remove();
  47497. this.dispatchEvent('dispose');
  47498. }
  47499. }
  47500. /*
  47501. 两种拖拽方式:
  47502. 1 只依附在点云上
  47503. 2 平行于镜头view移动 */
  47504. const geo$1 = new PlaneBufferGeometry(1,1);
  47505. class HandleSprite extends Sprite$1{
  47506. constructor(position,options={}){
  47507. options.sizeInfo = {width2d:60};
  47508. super(options);
  47509. this.position.copy(position);
  47510. this.dragStyle = options.dragStyle || 'default'; //'default'||'onPointCloud'
  47511. this.bindEvent();
  47512. }
  47513. bindEvent(){
  47514. let projectedStart, pointerStart;
  47515. const drag = (e)=>{
  47516. /* if(e.hoverViewport != e.drag.dragViewport){//不能使用e.dragViewport,要使用drag中的,因为drag中存储的要一直继承下来,不因mouseup了而改变。
  47517. viewer.dispatchEvent({
  47518. type : "CursorChange", action : "add", name:"polygon_AtWrongPlace"
  47519. })
  47520. return
  47521. } */
  47522. const camera = viewer.scene.getActiveCamera();
  47523. if(projectedStart){
  47524. let move2d = new Vector2$1().subVectors(e.pointer, pointerStart);
  47525. let projectNow = projectedStart.clone();
  47526. projectNow.x += move2d.x;
  47527. projectNow.y += move2d.y;
  47528. let unprojected = projectNow.clone().unproject(camera);
  47529. this.position.set(unprojected.x, unprojected.y, unprojected.z);
  47530. }else {
  47531. projectedStart = this.position.clone().project(camera);
  47532. pointerStart = e.pointer.clone();
  47533. }
  47534. this.update();
  47535. this.dispatchEvent({type:'dragged', position: this.position });
  47536. };
  47537. const drop = (e)=>{
  47538. projectedStart = null, pointerStart = null;
  47539. };
  47540. const mouseover = (e) => {
  47541. viewer.dispatchEvent({
  47542. type : "CursorChange", action : "add", name:"markerMove"
  47543. });
  47544. };
  47545. const mouseleave = (e) => {
  47546. viewer.dispatchEvent({
  47547. type : "CursorChange", action : "remove", name:"markerMove"
  47548. });
  47549. };
  47550. this.addEventListener('drag', drag);
  47551. this.addEventListener('drop', drop);
  47552. this.addEventListener('mouseover', mouseover);
  47553. this.addEventListener('mouseleave', mouseleave);
  47554. }
  47555. }
  47556. const sphere = new Mesh(new SphereBufferGeometry(0.08,0.08,3,2), new MeshBasicMaterial({color:'#f88'}));
  47557. class CurveCtrl extends Object3D {
  47558. constructor(points, lineMat, color, name, options={}){
  47559. super();
  47560. this.curve = new CatmullRomCurve3(points, false, "centripetal" /* , tension */);
  47561. this.name = name || 'curveNode';
  47562. this.handleMat = options.handleMat;
  47563. this.lineMat = lineMat;
  47564. this.createPath();
  47565. this.color = color;
  47566. this.handles = [];
  47567. this.wholeLength = 0;
  47568. this.viewports = options.viewports || [viewer.mainViewport]; //for HandleSprite
  47569. for(let i=0,j=this.points.length; i<j;i++){
  47570. this.handles.push(this.createHandle(this.points[i]));
  47571. }
  47572. this.visible_ = true;
  47573. if(Potree.settings.isTest){
  47574. this.spheres = new Object3D;
  47575. /* let i = Count+1;
  47576. while(i>0){
  47577. this.spheres.add(sphere.clone());
  47578. i--;
  47579. } */
  47580. this.add(this.spheres);
  47581. }
  47582. this.updatePath();
  47583. }
  47584. addPoint(position, index, ifUpdate){
  47585. let length = this.points.length;
  47586. if(index == void 0 ){
  47587. index = length;
  47588. }
  47589. let handle = this.createHandle(position);
  47590. this.handles = [...this.handles.slice(0,index), handle, ...this.handles.slice(index,length)];
  47591. this.points = [...this.points.slice(0,index), position, ...this.points.slice(index,length)];
  47592. ifUpdate && (this.updatePath(), this.updateHandle(index));
  47593. }
  47594. removePoint(index){
  47595. let handle = this.handles[index];
  47596. handle.dispose();
  47597. this.handles.splice(index,1);
  47598. this.points.splice(index,1);
  47599. this.updatePath();
  47600. }
  47601. createPath(){
  47602. const line = LineDraw.createFatLine( [ ],this.lineMat);
  47603. this.line = line;
  47604. this.add(line);
  47605. }
  47606. updatePath(){
  47607. this.curve.needsUpdate = true; //如果不更新,得到的点不均匀,开头点少。
  47608. let points, length = this.points.length;
  47609. this.wholeLength = this.points.reduce((total, currentValue, currentIndex, arr)=>{ //所有端点的距离总和
  47610. if(currentIndex == 0)return 0
  47611. return total + currentValue.distanceTo(arr[currentIndex-1]);
  47612. },0);
  47613. if(length > 1){
  47614. const count = MathUtils.clamp(Math.ceil(this.wholeLength * 5), 30, 500);
  47615. points = this.curve.getSpacedPoints( count );
  47616. if(this.needsPercent){ //获取每个节点在整条中的百分比,便于定位(但不精确)
  47617. this.pointsPercent = [0];
  47618. let sums = [0];
  47619. let sum = 0, last = points[0];
  47620. for(let i=1;i<length;i++){
  47621. let point = this.points[i];
  47622. sum += point.distanceTo(last); //参考getLengths函数,根据长度得到百分比
  47623. last = point;
  47624. sums.push(sum);
  47625. }
  47626. for(let i=1;i<length;i++){
  47627. this.pointsPercent.push(sum == 0 ? i/length : sums[i] / sum);
  47628. }
  47629. }
  47630. if(Potree.settings.isTest){
  47631. this.spheres.children.forEach(e=>e.visible = false);
  47632. points.forEach((e,i)=>{
  47633. let sphere1 = this.spheres.children[i];
  47634. if(!sphere1){
  47635. sphere1 = sphere.clone();
  47636. this.spheres.add(sphere1);
  47637. }
  47638. sphere1.position.copy(e);
  47639. sphere1.visible = true;
  47640. });
  47641. }
  47642. }else {
  47643. points = [];
  47644. }
  47645. LineDraw.updateLine(this.line, points);
  47646. this.dispatchEvent('updatePath');
  47647. }
  47648. createHandle(position){
  47649. if(this.handleMat){
  47650. var handle = new HandleSprite(position, {mat:this.handleMat, viewports:this.viewports});
  47651. this.add(handle);
  47652. }else {
  47653. var handle = new HandleSvg(position, this.color);
  47654. }
  47655. handle.visible = this.visible;
  47656. handle.addEventListener('dragged',(e)=>{
  47657. let index = this.handles.indexOf(handle);
  47658. this.points[index].copy(e.position);
  47659. this.updatePath();
  47660. this.dispatchEvent({type:'dragCurvePoint', index});
  47661. });
  47662. return handle
  47663. }
  47664. updateHandle(index){
  47665. if(!this.visible)return
  47666. this.handles[index].update();
  47667. }
  47668. updateHandles(){
  47669. this.handles.forEach((handle,index)=>{
  47670. this.updateHandle(index);
  47671. });
  47672. }
  47673. update(){
  47674. this.updateHandles();
  47675. this.updatePath();
  47676. }
  47677. set visible(v){
  47678. if(v != this.visible_ ){
  47679. this.visible_ = v;
  47680. this.visible = v;
  47681. if(this.handles){
  47682. this.handles.forEach(e=>e.visible = v );
  47683. if(v) this.updateHandles(); //因为不可见时没更新位置
  47684. }
  47685. }
  47686. }
  47687. get visible(){
  47688. return this.visible_
  47689. }
  47690. /* set visible(v){
  47691. this.handles.forEach(e=>e.svg.style.display = v ? "" : "none" )
  47692. if(v) this.updateHandles() //因为不可见时没更新位置
  47693. } */
  47694. get points(){
  47695. return this.curve.points;
  47696. }
  47697. set points(points){
  47698. this.curve.points = points;
  47699. }
  47700. getPointAt(t){
  47701. return this.curve.getPointAt(t)
  47702. }
  47703. getSpacedPoints(t){
  47704. return this.curve.getSpacedPoints(t)
  47705. }
  47706. dispose(){
  47707. this.parent && this.parent.remove(this);
  47708. this.handles.forEach(e=>e.dispose() );
  47709. this.line.geometry && this.line.geometry.dispose();
  47710. }
  47711. }
  47712. var easing = {};
  47713. //渐变曲线函数,反应加速度的变化
  47714. //currentTime:x轴当前时间(从0-到duration), startY:起始点, duration:总时长, wholeY:路程 (即endY-startY)
  47715. //参数基本是 x, 0, 1, 1
  47716. /*
  47717. easeOut 基本是y= m * (x-dur)^k + n, 若k为偶数,m<0, 若k为奇数,m>0; (因为偶数的话必须开口向下才能获得斜率递减的递增的那段,而奇数是对称的,单调递增. )
  47718. 根据x=0时y=0, x=dur时y=S , 得 n = S,m = -S/(-dur)^k
  47719. */
  47720. easing.getEaseOut = function(k){// k 是>=2的整数. 越大变化率越大, 相同初始速度所需要时间越久
  47721. let easeFun;
  47722. k = Math.round(k);
  47723. if(k<2){
  47724. k = Math.PI / 2;
  47725. easeFun = easing.easeOutSine;
  47726. }else {
  47727. easeFun = function(currentTime, startY, wholeY, duration) {
  47728. if(k>2){
  47729. console.log(k);
  47730. }
  47731. return -wholeY/Math.pow(-duration, k) * Math.pow(currentTime-duration, k) + wholeY
  47732. };
  47733. }
  47734. return {
  47735. k,
  47736. easeFun
  47737. }
  47738. };
  47739. easing.linearTween = function(currentTime, startY, wholeY, duration) {
  47740. return wholeY * currentTime / duration + startY
  47741. }
  47742. ,
  47743. easing.easeInQuad = function(currentTime, startY, wholeY, duration) {
  47744. return currentTime /= duration,
  47745. wholeY * currentTime * currentTime + startY
  47746. }
  47747. ,
  47748. 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
  47749. return currentTime /= duration,
  47750. -wholeY * currentTime * (currentTime - 2) + startY
  47751. }
  47752. ,
  47753. easing.easeInOutQuad = function(currentTime, startY, wholeY, duration) {
  47754. return currentTime /= duration / 2,
  47755. currentTime < 1 ? wholeY / 2 * currentTime * currentTime + startY : (currentTime--,
  47756. -wholeY / 2 * (currentTime * (currentTime - 2) - 1) + startY)
  47757. }
  47758. ,
  47759. easing.easeInCubic = function(currentTime, startY, wholeY, duration) {
  47760. return currentTime /= duration,
  47761. wholeY * currentTime * currentTime * currentTime + startY
  47762. }
  47763. ,
  47764. 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
  47765. return currentTime /= duration,
  47766. currentTime--,
  47767. wholeY * (currentTime * currentTime * currentTime + 1) + startY
  47768. }
  47769. ,
  47770. easing.easeInOutCubic = function(currentTime, startY, wholeY, duration) {
  47771. return currentTime /= duration / 2,
  47772. currentTime < 1 ? wholeY / 2 * currentTime * currentTime * currentTime + startY : (currentTime -= 2,
  47773. wholeY / 2 * (currentTime * currentTime * currentTime + 2) + startY)
  47774. }
  47775. ,
  47776. easing.easeInQuart = function(currentTime, startY, wholeY, duration) {
  47777. return currentTime /= duration,
  47778. wholeY * currentTime * currentTime * currentTime * currentTime + startY
  47779. }
  47780. ,
  47781. easing.easeOutQuart = function(currentTime, startY, wholeY, duration) {//根据上面的计算,估计0时速度应该是4S/dur吧……
  47782. return currentTime /= duration,
  47783. currentTime--,
  47784. -wholeY * (currentTime * currentTime * currentTime * currentTime - 1) + startY
  47785. }
  47786. ,
  47787. easing.easeInOutQuart = function(currentTime, startY, wholeY, duration) {
  47788. return currentTime /= duration / 2,
  47789. currentTime < 1 ? wholeY / 2 * currentTime * currentTime * currentTime * currentTime + startY : (currentTime -= 2,
  47790. -wholeY / 2 * (currentTime * currentTime * currentTime * currentTime - 2) + startY)
  47791. }
  47792. ,
  47793. easing.easeInQuint = function(currentTime, startY, wholeY, duration) {
  47794. return currentTime /= duration,
  47795. wholeY * currentTime * currentTime * currentTime * currentTime * currentTime + startY
  47796. }
  47797. ,
  47798. easing.easeOutQuint = function(currentTime, startY, wholeY, duration) {
  47799. return currentTime /= duration,
  47800. currentTime--,
  47801. wholeY * (currentTime * currentTime * currentTime * currentTime * currentTime + 1) + startY
  47802. }
  47803. ,
  47804. easing.easeInOutQuint = function(currentTime, startY, wholeY, duration) {
  47805. return currentTime /= duration / 2,
  47806. currentTime < 1 ? wholeY / 2 * currentTime * currentTime * currentTime * currentTime * currentTime + startY : (currentTime -= 2,
  47807. wholeY / 2 * (currentTime * currentTime * currentTime * currentTime * currentTime + 2) + startY)
  47808. }
  47809. ,
  47810. easing.easeInSine = function(currentTime, startY, wholeY, duration) {
  47811. return -wholeY * Math.cos(currentTime / duration * (Math.PI / 2)) + wholeY + startY
  47812. }
  47813. ,
  47814. easing.easeOutSine = function(currentTime, startY, wholeY, duration) {// y' = S * PI / 2 / dur * cos(PI/2/dur * x)
  47815. console.log('easeOutSine');
  47816. return wholeY * Math.sin(currentTime / duration * (Math.PI / 2)) + startY
  47817. }
  47818. ,
  47819. easing.easeInOutSine = function(currentTime, startY, wholeY, duration) {
  47820. return -wholeY / 2 * (Math.cos(Math.PI * currentTime / duration) - 1) + startY
  47821. }
  47822. ,
  47823. easing.easeInExpo = function(currentTime, startY, wholeY, duration) {
  47824. return wholeY * Math.pow(2, 10 * (currentTime / duration - 1)) + startY
  47825. }
  47826. ,
  47827. easing.easeOutExpo = function(currentTime, startY, wholeY, duration) {
  47828. return wholeY * (-Math.pow(2, -10 * currentTime / duration) + 1) + startY
  47829. }
  47830. ,
  47831. easing.easeInOutExpo = function(currentTime, startY, wholeY, duration) {
  47832. return currentTime /= duration / 2,
  47833. currentTime < 1 ? wholeY / 2 * Math.pow(2, 10 * (currentTime - 1)) + startY : (currentTime--,
  47834. wholeY / 2 * (-Math.pow(2, -10 * currentTime) + 2) + startY)
  47835. }
  47836. ,
  47837. easing.easeInCirc = function(currentTime, startY, wholeY, duration) {
  47838. return currentTime /= duration,
  47839. -wholeY * (Math.sqrt(1 - currentTime * currentTime) - 1) + startY
  47840. }
  47841. ,
  47842. easing.easeOutCirc = function(currentTime, startY, wholeY, duration) {
  47843. return currentTime /= duration,
  47844. currentTime--,
  47845. wholeY * Math.sqrt(1 - currentTime * currentTime) + startY
  47846. }
  47847. ,
  47848. easing.easeInOutCirc = function(currentTime, startY, wholeY, duration) {
  47849. return currentTime /= duration / 2,
  47850. currentTime < 1 ? -wholeY / 2 * (Math.sqrt(1 - currentTime * currentTime) - 1) + startY : (currentTime -= 2,
  47851. wholeY / 2 * (Math.sqrt(1 - currentTime * currentTime) + 1) + startY)
  47852. }
  47853. ,
  47854. easing.easeInElastic = function(currentTime, startY, wholeY, duration) {
  47855. var r = 1.70158
  47856. , o = 0
  47857. , a = wholeY;
  47858. return 0 === currentTime ? startY : 1 === (currentTime /= duration) ? startY + wholeY : (o || (o = .3 * duration),
  47859. a < Math.abs(wholeY) ? (a = wholeY,
  47860. r = o / 4) : r = o / (2 * Math.PI) * Math.asin(wholeY / a),
  47861. -(a * Math.pow(2, 10 * (currentTime -= 1)) * Math.sin((currentTime * duration - r) * (2 * Math.PI) / o)) + startY)
  47862. }
  47863. ,
  47864. easing.easeOutElastic = function(currentTime, startY, wholeY, duration) {
  47865. var r = 1.70158
  47866. , o = 0
  47867. , a = wholeY;
  47868. return 0 === currentTime ? startY : 1 === (currentTime /= duration) ? startY + wholeY : (o || (o = .3 * duration),
  47869. a < Math.abs(wholeY) ? (a = wholeY,
  47870. r = o / 4) : r = o / (2 * Math.PI) * Math.asin(wholeY / a),
  47871. a * Math.pow(2, -10 * currentTime) * Math.sin((currentTime * duration - r) * (2 * Math.PI) / o) + wholeY + startY)
  47872. }
  47873. ,
  47874. easing.easeInOutElastic = function(currentTime, startY, wholeY, duration) {
  47875. var r = 1.70158
  47876. , o = 0
  47877. , a = wholeY;
  47878. return 0 === currentTime ? startY : 2 === (currentTime /= duration / 2) ? startY + wholeY : (o || (o = duration * (.3 * 1.5)),
  47879. a < Math.abs(wholeY) ? (a = wholeY,
  47880. r = o / 4) : r = o / (2 * Math.PI) * Math.asin(wholeY / a),
  47881. 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)
  47882. }
  47883. ,
  47884. easing.easeInBack = function(currentTime, startY, wholeY, duration, r) {
  47885. return void 0 === r && (r = 1.70158),
  47886. wholeY * (currentTime /= duration) * currentTime * ((r + 1) * currentTime - r) + startY
  47887. }
  47888. ,
  47889. easing.easeOutBack = function(currentTime, startY, wholeY, duration, r) {
  47890. return void 0 === r && (r = 1.70158),
  47891. wholeY * ((currentTime = currentTime / duration - 1) * currentTime * ((r + 1) * currentTime + r) + 1) + startY
  47892. }
  47893. ,
  47894. easing.easeInOutBack = function(currentTime, startY, wholeY, duration, r) {
  47895. return void 0 === r && (r = 1.70158),
  47896. (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
  47897. }
  47898. ,
  47899. easing.easeOutBounce = function(currentTime, startY, wholeY, duration) {
  47900. 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
  47901. }
  47902. ,
  47903. easing.easeInBounce = function(currentTime, startY, wholeY, r) {
  47904. return wholeY - easing.easeOutBounce(r - currentTime, 0, wholeY, r) + startY
  47905. }
  47906. ,
  47907. easing.easeInOutBounce = function(currentTime, startY, wholeY, r) {
  47908. 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
  47909. };
  47910. var lerp = {
  47911. /* vector: function(currentTime, startY, f) {//xzw change, add f
  47912. var wholeY = currentTime.clone();
  47913. return startY = startY.clone(),
  47914. function(duration) {
  47915. currentTime.set(wholeY.x * (1 - duration) + startY.x * duration, wholeY.y * (1 - duration) + startY.y * duration, wholeY.z * (1 - duration) + startY.z * duration)
  47916. f && f(currentTime,duration);
  47917. }
  47918. },
  47919. quaternion: function(currentTime, startY, f) {//xzw change, add f
  47920. var wholeY = currentTime.clone();
  47921. return function(duration) {
  47922. currentTime.copy(wholeY).slerp(startY, duration);
  47923. f && f(currentTime,duration);
  47924. }
  47925. },
  47926. property: function(currentTime, startY, wholeY, duration) {
  47927. var r = currentTime[startY];
  47928. return function(o) {
  47929. currentTime[startY] = r * (1 - o) + wholeY * o,
  47930. duration && duration(currentTime[startY])
  47931. }
  47932. },
  47933. uniform: function(currentTime, startY, wholeY) {
  47934. var duration = currentTime.material.uniforms[startY].value;
  47935. return function(r) {
  47936. try{
  47937. currentTime.material.uniforms[startY] && (currentTime.material.uniforms[startY].value = duration * (1 - r) + wholeY * r)
  47938. }catch(currentTime){
  47939. console.log(1)
  47940. }
  47941. }
  47942. },
  47943. matrix4: function(currentTime, startY) {
  47944. var wholeY = currentTime.clone();
  47945. return function(duration) {
  47946. for (var r = currentTime.elements, o = wholeY.elements, a = startY.elements, s = 0; s < 16; s++)
  47947. r[s] = o[s] * (1 - duration) + a[s] * duration
  47948. }
  47949. },
  47950. allUniforms: function(currentTime, startY, wholeY) {
  47951. var duration = currentTime.map(function(currentTime) {
  47952. return this.uniform(currentTime, startY, wholeY)
  47953. }
  47954. .bind(this));
  47955. return function(currentTime) {
  47956. duration.forEach(function(startY) {
  47957. startY(currentTime)
  47958. })
  47959. }
  47960. } */
  47961. vector: function(t, i, f) {//xzw change, add f
  47962. var n = t.clone();
  47963. return i = i.clone(),
  47964. function(e) {
  47965. t.set(n.x * (1 - e) + i.x * e, n.y * (1 - e) + i.y * e, n.z * (1 - e) + i.z * e);
  47966. f && f(t,e);
  47967. }
  47968. },
  47969. quaternion: function(t, i, f) {//xzw change, add f
  47970. var n = t.clone();
  47971. return function(e) {
  47972. t.copy(n).slerp(i, e);
  47973. f && f(t,e);
  47974. }
  47975. },
  47976. property: function(t, i, n, r) {
  47977. var o = t[i];
  47978. return function(e) {
  47979. t[i] = o * (1 - e) + n * e,
  47980. r && r(t[i]);
  47981. }
  47982. },
  47983. uniform: function(t, i, n) {
  47984. var r = t.material.uniforms[i].value;
  47985. return function(e) {
  47986. t.material.uniforms[i] && (t.material.uniforms[i].value = r * (1 - e) + n * e);
  47987. }
  47988. },
  47989. matrix4: function(o, a) {
  47990. var s = o.clone();
  47991. return function(e) {
  47992. for (var t = o.elements, i = s.elements, n = a.elements, r = 0; r < 16; r++)
  47993. t[r] = i[r] * (1 - e) + n[r] * e;
  47994. }
  47995. },
  47996. allUniforms: function(e, t, i) {
  47997. var n = e.map(function(e) {
  47998. return this.uniform(e, t, i)
  47999. }
  48000. .bind(this));
  48001. return function(t) {
  48002. n.forEach(function(e) {
  48003. e(t);
  48004. });
  48005. }
  48006. }
  48007. };
  48008. /*
  48009. 渐变
  48010. */
  48011. var transitions = {
  48012. globalDone: null,
  48013. funcs: [],
  48014. counter: 0,
  48015. uniqueID: 0,
  48016. start: function(func, duration, done, delay, ease, name, id, cancelFun) {
  48017. return delay = delay || 0,
  48018. this.funcs.push({
  48019. func: func,
  48020. current: -delay * Math.abs(duration), //当前时间
  48021. duration: (1 - Math.max(delay, 0)) * Math.abs(duration), //总时长
  48022. done: done,
  48023. easing: ease || easing.linearTween, //渐变曲线
  48024. cycling: duration < 0,
  48025. running: !0,
  48026. debug: delay < 0,
  48027. name: name || "T" + this.counter,
  48028. id: void 0 === id ? this.counter : id,
  48029. paused: !1,
  48030. cancelFun : cancelFun, //取消时执行的函数
  48031. }),
  48032. func(0, 16),
  48033. this.counter += 1,
  48034. func
  48035. },
  48036. trigger: function(e) {
  48037. var t = void 0 === e.delayRatio ? 0 : e.delayRatio
  48038. , u = e.func || function() {}
  48039. , r = void 0 === e.duration ? 0 : e.duration;
  48040. void 0 !== e.cycling && e.cycling && (r = -Math.abs(r));
  48041. var o = e.done || null
  48042. , a = e.easing || easing.linearTween
  48043. , s = e.name || "R" + this.counter
  48044. , l = void 0 === e.id ? this.counter : e.id;
  48045. return this.start(u, r, o, t, a, s, l)
  48046. },
  48047. setTimeout: function(e, t, u) {
  48048. var duration = void 0 === u ? this.counter : u;
  48049. return this.trigger({
  48050. done: e,
  48051. duration: void 0 === t ? 0 : t,
  48052. name: "O" + this.counter,
  48053. id: duration
  48054. })
  48055. },
  48056. pause: function() {
  48057. this.paused = !0;
  48058. },
  48059. resume: function() {
  48060. this.paused = !1;
  48061. },
  48062. update: function(e) {
  48063. this.funcs.forEach(function(t) {
  48064. if (!(t.paused || (t.current += 1e3 * e,
  48065. t.current < 0)))
  48066. if (t.current >= t.duration && !t.cycling) {
  48067. var u = t.easing(1, 0, 1, 1);
  48068. t.func(u, 1e3 * e),
  48069. t.done && t.done(),
  48070. t.running = !1;
  48071. } else {
  48072. var duration = t.easing(t.current % t.duration / t.duration, 0, 1, 1)
  48073. , r = t.func(duration, 1e3 * e) || !1;
  48074. r && (t.done && t.done(),
  48075. t.running = !1);
  48076. }
  48077. });
  48078. var t = this.funcs.length;
  48079. this.funcs = this.funcs.filter(function(e) {
  48080. return e.running
  48081. });
  48082. var u = this.funcs.length;
  48083. if (t > 0 && 0 === u && this.globalDone) {
  48084. var duration = this.globalDone;
  48085. this.globalDone = null,
  48086. duration();
  48087. }
  48088. },
  48089. adjustSpeed: function(e, t) {
  48090. for (var u = this.getById(e), duration = 0; duration < u.length; duration++) {
  48091. var r = u[duration];
  48092. r.duration /= t,
  48093. r.current /= t;
  48094. }
  48095. },
  48096. getById: function(e) {
  48097. return this.funcs.filter(function(t) {
  48098. return e === t.id
  48099. })
  48100. },
  48101. get: function(e) {
  48102. for (var t = 0; t < this.funcs.length; t += 1)
  48103. if (this.funcs[t].func === e)
  48104. return this.funcs[t];
  48105. return null
  48106. },
  48107. isRunning: function(e) {
  48108. var t = this.get(e);
  48109. return null !== t && t.running
  48110. },
  48111. countActive: function() {
  48112. for (var e = 0, t = 0; t < this.funcs.length; t += 1)
  48113. e += this.funcs[t].running;
  48114. return e
  48115. },
  48116. listActive: function() {
  48117. for (var e = [], t = 0; t < this.funcs.length; t += 1)
  48118. this.funcs[t].running && e.push(this.funcs[t].name);
  48119. return e
  48120. },
  48121. done: function(e) {
  48122. this.globalDone = e;
  48123. },
  48124. cancelById: function(e, dealCancelFun) { //xzw add dealDone
  48125. var t = void 0 === e ? 0 : e;
  48126. let cancels = [];
  48127. this.funcs = this.funcs.filter(function(e) {
  48128. var is = e.id == t;
  48129. if(is && dealCancelFun){
  48130. e.cancelFun && cancels.push(e.cancelFun);
  48131. //e.cancelFun && e.cancelFun()
  48132. }
  48133. return !is
  48134. });
  48135. cancels.forEach(e=>{e();}); //先从funcs中去除后再执行
  48136. },
  48137. cancel: function(e) {
  48138. this.funcs = this.funcs.filter(function(t) {
  48139. return t.func !== e
  48140. });
  48141. },
  48142. getUniqueId: function() {
  48143. return this.uniqueID -= 1,
  48144. this.uniqueID
  48145. }
  48146. };
  48147. const colors = {
  48148. position: 'red',
  48149. target : 'blue'
  48150. };
  48151. let lineMats$1;
  48152. const getLineMat = function(name){
  48153. if(!lineMats$1){
  48154. lineMats$1 = {
  48155. position: LineDraw.createFatLineMat({
  48156. color: colors.position,
  48157. lineWidth: 3
  48158. }),
  48159. target : LineDraw.createFatLineMat({
  48160. color: colors.target,
  48161. lineWidth: 3
  48162. }),
  48163. frustum: LineDraw.createFatLineMat({
  48164. color: colors.position,
  48165. lineWidth: 2
  48166. }),
  48167. aimAtTarget: new LineBasicMaterial({color:colors.target})
  48168. };
  48169. }
  48170. return lineMats$1[name]
  48171. };
  48172. class CameraAnimation extends EventDispatcher{
  48173. constructor(viewer){
  48174. super();
  48175. this.viewer = viewer;
  48176. this.selectedElement = null;
  48177. //this.controlPoints = [];
  48178. this.uuid = MathUtils.generateUUID();
  48179. this.node = new Object3D();
  48180. this.node.name = "camera animation";
  48181. this.viewer.scene.scene.add(this.node);
  48182. this.frustum = this.createFrustum();
  48183. this.node.add(this.frustum);
  48184. this.name = "Camera Animation";
  48185. // "centripetal", "chordal", "catmullrom"
  48186. this.curveType = "centripetal";
  48187. this.visible = true;
  48188. this.targets = [];
  48189. this.createPath();
  48190. this.duration = 5;
  48191. this.percent = 0;
  48192. this.currentIndex = 0;
  48193. this.durations = [];
  48194. this.quaternions = [];
  48195. if(!Potree.settings.isTest){
  48196. this.setVisible(false);
  48197. }
  48198. this.addEventListener('dispose', ()=>{
  48199. this.dispose();
  48200. });
  48201. this.targetLines = new Object3D;
  48202. this.node.add(this.targetLines);
  48203. }
  48204. static defaultFromView(viewer){
  48205. const animation = new CameraAnimation(viewer);
  48206. const camera = viewer.scene.getActiveCamera();
  48207. const target = viewer.scene.view.getPivot();
  48208. const cpCenter = new Vector3(
  48209. 0.3 * camera.position.x + 0.7 * target.x,
  48210. 0.3 * camera.position.y + 0.7 * target.y,
  48211. 0.3 * camera.position.z + 0.7 * target.z,
  48212. );
  48213. const targetCenter = new Vector3(
  48214. 0.05 * camera.position.x + 0.95 * target.x,
  48215. 0.05 * camera.position.y + 0.95 * target.y,
  48216. 0.05 * camera.position.z + 0.95 * target.z,
  48217. );
  48218. const r = 2;//camera.position.distanceTo(target) * 0.3;
  48219. //const dir = target.clone().sub(camera.position).normalize();
  48220. const angle = Utils.computeAzimuth(camera.position, target);
  48221. const n = 5;
  48222. for(let i = 0; i < n; i++){
  48223. let u = 1.5 * Math.PI * (i / n) + angle;
  48224. const dx = r * Math.cos(u);
  48225. const dy = r * Math.sin(u);
  48226. const cpPos = new Vector3(
  48227. cpCenter.x + dx,
  48228. cpCenter.y + dy,
  48229. cpCenter.z,
  48230. );
  48231. const targetPos = new Vector3(
  48232. targetCenter.x + dx * 0.1,
  48233. targetCenter.y + dy * 0.1,
  48234. targetCenter.z,
  48235. );
  48236. animation.createControlPoint(null,{position:cpPos, target:targetPos});
  48237. }
  48238. animation.changeCallback();
  48239. return animation;
  48240. }
  48241. createControlPoint(index, posInfo ){
  48242. const length = this.posCurve.points.length;
  48243. const position = new Vector3;
  48244. const target = new Vector3;
  48245. if(index == void 0 ){
  48246. index = length;
  48247. }
  48248. if(!posInfo){
  48249. if(length >= 2 && index === 0){
  48250. const dir = new Vector3().subVectors(this.posCurve.points[0], this.posCurve.points[1] );
  48251. position.copy(this.posCurve.points[0]).add(dir);
  48252. const tDir = new Vector3().subVectors(this.targets[0].position, this.targets[1].position );
  48253. target.copy(this.targets[0].position).add(dir);
  48254. }else if(length >= 2 && index === length){
  48255. const dir = new Vector3().subVectors(this.posCurve.points[length-1], this.posCurve.points[length-2] );
  48256. position.copy(this.posCurve.points[length-2]).add(dir);
  48257. const tDir = new Vector3().subVectors(this.targets[length-1].position, this.targets[length-2].position );
  48258. target.copy(this.targets[length-2].position).add(dir);
  48259. }else if(length >= 2){
  48260. position.copy(this.posCurve.points[index-1].clone().add(this.posCurve.points[index]).multiplyScalar(0.5));
  48261. target.copy(this.targets[length-1].position.clone().add(this.targets[length]).multiplyScalar(0.5));
  48262. }
  48263. }else {
  48264. position.copy(posInfo.position);
  48265. target.copy(posInfo.target);
  48266. }
  48267. this.posCurve.addPoint(position, index/* , true */);
  48268. //this.targetCurve.addPoint(target, index/* , true */)
  48269. let targetSvg = new HandleSvg(target, colors.target);
  48270. targetSvg.visible = this.visible;
  48271. this.targets = [...this.targets.slice(0,index), targetSvg, ...this.targets.slice(index,length)];
  48272. if(this.useDurSlice){//不使用全局的duration,而是分段的
  48273. this.durations = [...this.durations.slice(0,index), posInfo.duration, ...this.durations.slice(index,length)];
  48274. }
  48275. this.dispatchEvent({
  48276. type: "controlpoint_added",
  48277. index
  48278. });
  48279. {
  48280. let targetLine = LineDraw.createLine([position,target] ,{mat: getLineMat('aimAtTarget')});
  48281. this.targetLines.children = [...this.targetLines.children.slice(0,index), targetLine, ...this.targetLines.children.slice(index,length)];
  48282. this.targets[index].addEventListener('dragged', (e)=>{
  48283. this.updatePathCallback();
  48284. this.dragPointCallback(e);
  48285. });
  48286. }
  48287. }
  48288. dragPointCallback(e){
  48289. let index = e.index;
  48290. if(e.index == void 0){
  48291. index = this.targets.indexOf(e.target);
  48292. }
  48293. LineDraw.moveLine(this.targetLines.children[index], [this.posCurve.points[index], this.targets[index].position] );
  48294. this.updateFrustum();
  48295. }
  48296. updatePathCallback(){
  48297. {
  48298. this.quaternions = [];
  48299. let length = this.posCurve.points.length;
  48300. for(let i=0; i<length; i++){
  48301. let quaternion = math.getQuaFromPosAim(this.posCurve.points[i], this.targets[i].position);
  48302. this.quaternions.push( quaternion);
  48303. }
  48304. }
  48305. this.reMapCurvePercent();
  48306. }
  48307. removeControlPoint(index){
  48308. this.posCurve.removePoint(index);
  48309. //this.targetCurve.removePoint(index)
  48310. this.targets[index].dispose();
  48311. this.targets.splice(index, 1);
  48312. this.dispatchEvent({
  48313. type: "controlpoint_removed",
  48314. index
  48315. });
  48316. this.targetLines.remove(this.targetLines.children[index]);
  48317. if(this.useDurSlice){
  48318. this.durations.splice(index, 1);
  48319. }
  48320. }
  48321. createPath(){
  48322. this.posCurve = new CurveCtrl([],getLineMat('position'), colors.position, 'posCurve');
  48323. //this.targetCurve = new CurveCtrl([], getLineMat('target'), colors.target, 'targetCurve', {noLine:true});
  48324. this.posCurve.needsPercent = true;
  48325. this.node.add(this.posCurve);
  48326. //this.node.add(this.targetCurve)
  48327. this.posCurve.addEventListener('dragCurvePoint', this.dragPointCallback.bind(this));
  48328. this.posCurve.addEventListener('updatePath', this.updatePathCallback.bind(this));
  48329. }
  48330. createFrustum(){
  48331. const f = 0.3;
  48332. const positions = [
  48333. new Vector3( 0, 0, 0),
  48334. new Vector3(-f, -f, +1),
  48335. new Vector3( 0, 0, 0),
  48336. new Vector3( f, -f, +1),
  48337. new Vector3( 0, 0, 0),
  48338. new Vector3( f, f, +1),
  48339. new Vector3( 0, 0, 0),
  48340. new Vector3(-f, f, +1),
  48341. new Vector3(-f, -f, +1),
  48342. new Vector3( f, -f, +1),
  48343. new Vector3( f, -f, +1),
  48344. new Vector3( f, f, +1),
  48345. new Vector3( f, f, +1),
  48346. new Vector3(-f, f, +1),
  48347. new Vector3(-f, f, +1),
  48348. new Vector3(-f, -f, +1),
  48349. ];
  48350. positions.forEach(e=>e.z *= -1); //因为得到的rotation是camera的,作用在物体上要反向,所以这里反向一下
  48351. //geometry.computeBoundingSphere();//?
  48352. const line = LineDraw.createFatLine( positions, {material:getLineMat('frustum')});
  48353. //line.scale.set(20, 20, 20);
  48354. line.visible = false;
  48355. return line;
  48356. }
  48357. reMapCurvePercent(){ //因在不同点在相同位置旋转,由于间隔仅和位置距离相关,导致时间间隔为0,采取重新调整间隔的策略。
  48358. var length = this.posCurve.points.length;
  48359. if(length<2){
  48360. return this.newPointsPercents = []
  48361. }
  48362. var newPercents = [0];
  48363. if(this.useDurSlice){ //已经设定好了每一段的duration的话
  48364. let sums = [0];
  48365. let sum = 0, last;
  48366. for(let i=0;i<length-1;i++){ //去掉最后一个duration,因为已到终点
  48367. let duration = this.durations[i];
  48368. sum += duration;
  48369. last = duration;
  48370. sums.push(sum);
  48371. }
  48372. for(let i=1;i<length;i++){
  48373. newPercents.push(sum == 0 ? i/length : sums[i] / sum);
  48374. }
  48375. }else {
  48376. const maxSpaceDur = this.duration / length; //每两点之间修改间隔时间后,最大时间
  48377. const durPerRad = 0.8; //每弧度应该占用的时间
  48378. const minSpaceDur = Math.min(0.8, maxSpaceDur);//每两点之间修改间隔时间后,最小时间
  48379. const maxAngleSpaceDur = MathUtils.clamp(durPerRad * Math.PI, minSpaceDur, maxSpaceDur );// 最大可能差距是180度
  48380. var percents = this.posCurve.pointsPercent;
  48381. for(let i=1;i<length;i++){
  48382. let diff = (percents[i] - percents[i-1]) * this.duration; //间隔时间
  48383. let percent;
  48384. let curMin = minSpaceDur;
  48385. if(diff < maxAngleSpaceDur){ //若小于最大旋转时间
  48386. let rad = this.quaternions[i].angleTo(this.quaternions[i-1]);
  48387. curMin = MathUtils.clamp(rad * durPerRad, minSpaceDur, maxSpaceDur);
  48388. }
  48389. diff = Math.max(diff, curMin);
  48390. percent = newPercents[i-1] + (diff / this.duration); //得到新的percent
  48391. newPercents.push(percent);
  48392. }
  48393. let maxPercent = newPercents[length-1]; //最后一个,若扩充过时间,就会>1
  48394. if( !math.closeTo(maxPercent, 1)){
  48395. let scale = 1 / maxPercent; //需要压缩的比例 <1 这一步会让实际得到的间隔更小
  48396. newPercents = newPercents.map(e=> e*=scale );
  48397. }
  48398. }
  48399. this.newPointsPercents = newPercents;
  48400. //console.log(newPercents)
  48401. }
  48402. at(originPercent, delta, transitionRatio){
  48403. originPercent = MathUtils.clamp(originPercent, 0, 1);
  48404. //修改第一层:起始时间
  48405. let percent = originPercent;
  48406. /* const easePercent = 0.3; //缓动占比 //如果能在所有从静止到运动的中间加缓动就好了呀:lastPos * 0.9 + currentPos * 0.1 ?
  48407. if(originPercent < easePercent){
  48408. console.log('easeIn')
  48409. percent = easing.easeInSine(originPercent, 0, easePercent, easePercent) //currentTime, startY, wholeY, duration 选了一个衔接时接近斜率1的缓动函数
  48410. }else if(originPercent > 1-easePercent){
  48411. console.log('easeOut')
  48412. percent = easing.easeOutSine(originPercent-(1-easePercent), 1-easePercent, easePercent, easePercent)
  48413. } */
  48414. let quaternion;
  48415. if(percent < 1){
  48416. //修改第二层:使用每个点的重定位的 newPointsPercents
  48417. this.currentIndex = this.newPointsPercents.findIndex(e=> e>percent ) - 1;
  48418. //假设每个节点的百分比是精确的,那么:
  48419. let curIndexPercent = this.newPointsPercents[this.currentIndex];
  48420. let nextIndexPercent = this.newPointsPercents[this.currentIndex+1];
  48421. let progress = (percent - curIndexPercent) / (nextIndexPercent - curIndexPercent);//在这两个节点间的百分比
  48422. //投影到原本的 posCurve.pointsPercent上:
  48423. let curIndexOriPercent = this.posCurve.pointsPercent[this.currentIndex];
  48424. let nextIndexOriPercent = this.posCurve.pointsPercent[this.currentIndex+1];
  48425. percent = curIndexOriPercent + (nextIndexOriPercent - curIndexOriPercent) * progress;
  48426. let endQuaternion = this.quaternions[this.currentIndex+1];
  48427. let startQuaternion = this.quaternions[this.currentIndex];
  48428. quaternion = (new Quaternion()).copy(startQuaternion);
  48429. lerp.quaternion(quaternion, endQuaternion)(progress);
  48430. }else {
  48431. this.currentIndex = this.posCurve.points.length - 1;
  48432. quaternion = math.getQuaFromPosAim(this.posCurve.points[this.currentIndex], this.targets[this.currentIndex].position);
  48433. }
  48434. const position = this.posCurve.getPointAt(percent); // 需要this.posCurve.points.length>1 否则报错
  48435. //console.log(this.currentIndex, originPercent)
  48436. //缓动:
  48437. var aimQua, aimPos;
  48438. if(delta != void 0 ){
  48439. if(Potree.settings.tourTestCameraMove){
  48440. aimQua = this.frustum.quaternion.clone();
  48441. aimPos = this.frustum.position.clone();
  48442. }else {
  48443. var camera = viewer.scene.getActiveCamera();
  48444. aimQua = camera.quaternion.clone();
  48445. aimPos = camera.position.clone();
  48446. }
  48447. transitionRatio = transitionRatio || 1 / Potree.settings.cameraAniSmoothRatio;//渐变系数,越小缓动程度越高,越平滑
  48448. transitionRatio *= delta * 60; //假设标准帧率为60fps,当帧率低时(delta大时)要降低缓动
  48449. //console.log(transitionRatio, delta) //画面ui变化会使delta变大
  48450. transitionRatio = MathUtils.clamp(transitionRatio, 0, 1);
  48451. lerp.quaternion(aimQua, quaternion)(transitionRatio); //每次只改变一点点
  48452. lerp.vector(aimPos, position)(transitionRatio);
  48453. }else {
  48454. aimQua = quaternion; aimPos = position;
  48455. }
  48456. let rotation = new Euler().setFromQuaternion(aimQua );
  48457. const frame = {
  48458. position: aimPos,
  48459. rotation
  48460. };
  48461. return frame;
  48462. }
  48463. set(percent){
  48464. this.percent = percent;
  48465. }
  48466. setVisible(visible){
  48467. this.node.visible = visible;
  48468. this.posCurve.visible = visible;
  48469. this.targets.forEach(e=>e.visible = visible );
  48470. this.visible = visible;
  48471. }
  48472. setDuration(duration){
  48473. if(duration != this.duration){
  48474. this.duration = duration;
  48475. if(this.quaternions.length == this.posCurve.points.length)this.reMapCurvePercent();
  48476. }
  48477. }
  48478. getDuration(duration){
  48479. return this.duration;
  48480. }
  48481. play(startOptions={}){
  48482. if(this.onUpdate){
  48483. return console.error('已经开始播放')
  48484. }
  48485. let startPercent = 0, currentIndex = 0;
  48486. if(startOptions.percent != void 0 ){
  48487. startPercent = startOptions.percent;
  48488. }else if(startOptions.index){
  48489. currentIndex = index;
  48490. //startPercent = index/(this.posCurve.points.length-1)
  48491. startPercent = this.posCurve.pointsPercent[index];
  48492. }
  48493. //const tStart = performance.now();
  48494. const duration = this.duration;
  48495. this.originalyVisible = this.visible;
  48496. Potree.settings.tourTestCameraMove || this.setVisible(false);
  48497. let tStart, startTransitionRatio = 0.2;
  48498. let startDelay = 1/startTransitionRatio / 20 ;//因为缓动所以延迟开始,前面前都是at(0),使过渡到开始点位(但是依旧不能准确停在起始点,因为缓动是乘百分比有残留。所以直接平滑衔接到开始后的位置)
  48499. let hasPlayedTime = 0;
  48500. let finishDelay = Potree.settings.cameraAniSmoothRatio / 60 * 3;//结束后还需要多久时间才能大致达到缓动的最终目标
  48501. let hasStoppedTime = 0;
  48502. this.onUpdate = (e) => {
  48503. if(this.posCurve.points.length<2){
  48504. if(this.posCurve.points.length == 1){
  48505. viewer.scene.view.position.copy(this.posCurve.points[0]);
  48506. viewer.scene.view.rotation = new Euler().setFromQuaternion(this.quaternions[0]);
  48507. }
  48508. this.pause();
  48509. return
  48510. }
  48511. let percent, transitionRatio;
  48512. if(tStart){
  48513. let tNow = performance.now();
  48514. let elapsed = (tNow - tStart) / 1000;
  48515. percent = elapsed / duration + startPercent;
  48516. }else {//从当前位置过渡到开始位置
  48517. percent = 0;
  48518. hasPlayedTime += e.delta;
  48519. transitionRatio = startTransitionRatio;
  48520. console.log('延迟开始');
  48521. if(hasPlayedTime > startDelay){
  48522. tStart = performance.now();
  48523. }
  48524. }
  48525. this.set(percent);
  48526. const frame = this.at(percent, e.delta, transitionRatio);
  48527. if(currentIndex != this.currentIndex){
  48528. currentIndex = this.currentIndex;
  48529. console.log('updateCurrentIndex', currentIndex);
  48530. this.dispatchEvent({type:'updateCurrentIndex', currentIndex });
  48531. }
  48532. if(!Potree.settings.tourTestCameraMove){
  48533. viewer.scene.view.position.copy(frame.position);
  48534. //viewer.scene.view.lookAt(frame.target);
  48535. viewer.scene.view.rotation = frame.rotation;
  48536. }
  48537. this.updateFrustum(frame);
  48538. if(percent >= 1){
  48539. if(hasStoppedTime > finishDelay){
  48540. this.pause();
  48541. }else {
  48542. hasStoppedTime += e.delta;
  48543. console.log('延迟结束');
  48544. }
  48545. }
  48546. };
  48547. this.viewer.addEventListener("update", this.onUpdate);
  48548. }
  48549. pause(){
  48550. this.setVisible(this.originalyVisible);
  48551. this.viewer.removeEventListener("update", this.onUpdate);
  48552. this.dispatchEvent('playDone');
  48553. this.onUpdate = null;
  48554. }
  48555. updateFrustum(frame){
  48556. const frustum = this.frustum;
  48557. if(this.posCurve.points.length>1){
  48558. frustum.visible = true;
  48559. }else {
  48560. frustum.visible = false;
  48561. return
  48562. }
  48563. frame = frame || this.at(this.percent);
  48564. frustum.position.copy(frame.position);
  48565. //frustum.lookAt(...frame.target.toArray());
  48566. frustum.rotation.copy(frame.rotation);
  48567. }
  48568. changeCallback(){
  48569. this.posCurve.update();
  48570. //this.targetCurve.update()
  48571. this.targets.forEach(e=>e.update());
  48572. this.updateFrustum();
  48573. }
  48574. dispose(){//add
  48575. this.posCurve.dispose();
  48576. //this.targetCurve.dispatchEvent({type:'dispose'})
  48577. this.targets.forEach(e=>e.dispose());
  48578. this.durations = [];
  48579. this.node.parent.remove(this.node);
  48580. }
  48581. }
  48582. //scene.removeCameraAnimation
  48583. //修改:不使用targetCurve作为target曲线,因为播放时posCuve的节点和targetCurve并没有对应,且使用target的曲线会使角度变化大的情况过渡生硬。
  48584. // 改完旋转了。但是位置也有问题。速度完全和路程相关,当在同一位置设置多点时,这段的总时长为0. (是否要设置最小时长?不过也做不到 - -)
  48585. function loadPointCloud(viewer, data){
  48586. let loadMaterial = (target) => {
  48587. if(data.material){
  48588. if(data.material.activeAttributeName != null){
  48589. target.activeAttributeName = data.material.activeAttributeName;
  48590. }
  48591. if(data.material.ranges != null){
  48592. for(let range of data.material.ranges){
  48593. if(range.name === "elevationRange"){
  48594. target.elevationRange = range.value;
  48595. }else if(range.name === "intensityRange"){
  48596. target.intensityRange = range.value;
  48597. }else {
  48598. target.setRange(range.name, range.value);
  48599. }
  48600. }
  48601. }
  48602. if(data.material.size != null){
  48603. target.size = data.material.size;
  48604. }
  48605. if(data.material.minSize != null){
  48606. target.minSize = data.material.minSize;
  48607. }
  48608. if(data.material.pointSizeType != null){
  48609. target.pointSizeType = PointSizeType[data.material.pointSizeType];
  48610. }
  48611. if(data.material.matcap != null){
  48612. target.matcap = data.material.matcap;
  48613. }
  48614. }else if(data.activeAttributeName != null){
  48615. target.activeAttributeName = data.activeAttributeName;
  48616. }else {
  48617. // no material data
  48618. }
  48619. };
  48620. const promise = new Promise((resolve) => {
  48621. const names = viewer.scene.pointclouds.map(p => p.name);
  48622. const alreadyExists = names.includes(data.name);
  48623. if(alreadyExists){
  48624. resolve();
  48625. return;
  48626. }
  48627. Potree.loadPointCloud(data.url, data.name, (e) => {
  48628. const {pointcloud} = e;
  48629. pointcloud.position.set(...data.position);
  48630. pointcloud.rotation.set(...data.rotation);
  48631. pointcloud.scale.set(...data.scale);
  48632. loadMaterial(pointcloud.material);
  48633. viewer.scene.addPointCloud(pointcloud);
  48634. resolve(pointcloud);
  48635. });
  48636. });
  48637. return promise;
  48638. }
  48639. function loadMeasurement(viewer, data){
  48640. const duplicate = viewer.scene.measurements.find(measure => measure.uuid === data.uuid);
  48641. if(duplicate){
  48642. return;
  48643. }
  48644. data.points = data.points.map(point=>new Vector3(...point));
  48645. const measure = viewer.measuringTool.createMeasureFromData(data);
  48646. }
  48647. function loadVolume(viewer, data){
  48648. const duplicate = viewer.scene.volumes.find(volume => volume.uuid === data.uuid);
  48649. if(duplicate){
  48650. return;
  48651. }
  48652. let volume = new Potree[data.type];
  48653. volume.uuid = data.uuid;
  48654. volume.name = data.name;
  48655. volume.position.set(...data.position);
  48656. volume.rotation.set(...data.rotation);
  48657. volume.scale.set(...data.scale);
  48658. volume.visible = data.visible;
  48659. volume.clip = data.clip;
  48660. viewer.scene.addVolume(volume);
  48661. }
  48662. function loadCameraAnimation(viewer, data){
  48663. const duplicate = viewer.scene.cameraAnimations.find(a => a.uuid === data.uuid);
  48664. if(duplicate){
  48665. return;
  48666. }
  48667. const animation = new CameraAnimation(viewer);
  48668. animation.uuid = data.uuid;
  48669. animation.name = data.name;
  48670. animation.duration = data.duration;
  48671. animation.t = data.t;
  48672. animation.curveType = data.curveType;
  48673. animation.visible = data.visible;
  48674. animation.controlPoints = [];
  48675. for(const cpdata of data.controlPoints){
  48676. const cp = animation.createControlPoint();
  48677. cp.position.set(...cpdata.position);
  48678. cp.target.set(...cpdata.target);
  48679. }
  48680. viewer.scene.addCameraAnimation(animation);
  48681. }
  48682. function loadOrientedImages(viewer, images){
  48683. const {cameraParamsPath, imageParamsPath} = images;
  48684. const duplicate = viewer.scene.orientedImages.find(i => i.imageParamsPath === imageParamsPath);
  48685. if(duplicate){
  48686. return;
  48687. }
  48688. Potree.OrientedImageLoader.load(cameraParamsPath, imageParamsPath, viewer).then( images => {
  48689. viewer.scene.addOrientedImages(images);
  48690. });
  48691. }
  48692. function loadGeopackage(viewer, geopackage){
  48693. const path = geopackage.path;
  48694. const duplicate = viewer.scene.geopackages.find(i => i.path === path);
  48695. if(duplicate){
  48696. return;
  48697. }
  48698. const projection = viewer.getProjection();
  48699. proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
  48700. proj4.defs("pointcloud", projection);
  48701. const transform = proj4("WGS84", "pointcloud");
  48702. const params = {
  48703. transform: transform,
  48704. };
  48705. Potree.GeoPackageLoader.loadUrl(path, params).then(data => {
  48706. viewer.scene.addGeopackage(data);
  48707. });
  48708. }
  48709. function loadSettings(viewer, data){
  48710. if(!data){
  48711. return;
  48712. }
  48713. viewer.setPointBudget(data.pointBudget);
  48714. viewer.setFOV(data.fov);
  48715. viewer.setEDLEnabled(data.edlEnabled);
  48716. viewer.setEDLRadius(data.edlRadius);
  48717. viewer.setEDLStrength(data.edlStrength);
  48718. viewer.setBackground(data.background);
  48719. viewer.setMinNodeSize(data.minNodeSize);
  48720. viewer.setShowBoundingBox(data.showBoundingBoxes);
  48721. }
  48722. function loadView(viewer, view){
  48723. viewer.scene.view.position.set(...view.position);
  48724. viewer.scene.view.lookAt(...view.target);
  48725. }
  48726. function loadAnnotationItem(item){
  48727. const annotation = new Annotation({
  48728. position: item.position,
  48729. title: item.title,
  48730. cameraPosition: item.cameraPosition,
  48731. cameraTarget: item.cameraTarget,
  48732. });
  48733. annotation.description = item.description;
  48734. annotation.uuid = item.uuid;
  48735. if(item.offset){
  48736. annotation.offset.set(...item.offset);
  48737. }
  48738. return annotation;
  48739. }
  48740. function loadAnnotations(viewer, data){
  48741. if(!data){
  48742. return;
  48743. }
  48744. const findDuplicate = (item) => {
  48745. let duplicate = null;
  48746. viewer.scene.annotations.traverse( a => {
  48747. if(a.uuid === item.uuid){
  48748. duplicate = a;
  48749. }
  48750. });
  48751. return duplicate;
  48752. };
  48753. const traverse = (item, parent) => {
  48754. const duplicate = findDuplicate(item);
  48755. if(duplicate){
  48756. return;
  48757. }
  48758. const annotation = loadAnnotationItem(item);
  48759. for(const childItem of item.children){
  48760. traverse(childItem, annotation);
  48761. }
  48762. parent.add(annotation);
  48763. };
  48764. for(const item of data){
  48765. traverse(item, viewer.scene.annotations);
  48766. }
  48767. }
  48768. function loadProfile(viewer, data){
  48769. const {name, points} = data;
  48770. const duplicate = viewer.scene.profiles.find(profile => profile.uuid === data.uuid);
  48771. if(duplicate){
  48772. return;
  48773. }
  48774. let profile = new Potree.Profile();
  48775. profile.name = name;
  48776. profile.uuid = data.uuid;
  48777. profile.setWidth(data.width);
  48778. for(const point of points){
  48779. profile.addMarker(new Vector3(...point));
  48780. }
  48781. viewer.scene.addProfile(profile);
  48782. }
  48783. function loadClassification(viewer, data){
  48784. if(!data){
  48785. return;
  48786. }
  48787. const classifications = data;
  48788. viewer.setClassifications(classifications);
  48789. }
  48790. async function loadProject(viewer, data, done){
  48791. if(data.type !== "Potree"){
  48792. console.error("not a valid Potree project");
  48793. return;
  48794. }
  48795. loadSettings(viewer, data.settings);
  48796. loadView(viewer, data.view);
  48797. /* const pointcloudPromises = [];
  48798. for(const pointcloud of data.pointclouds){
  48799. const promise = loadPointCloud(viewer, pointcloud);
  48800. pointcloudPromises.push(promise);
  48801. } */
  48802. for(const measure of data.measurements){
  48803. loadMeasurement(viewer, measure);
  48804. }
  48805. for(const volume of data.volumes){
  48806. loadVolume(viewer, volume);
  48807. }
  48808. for(const animation of data.cameraAnimations){
  48809. loadCameraAnimation(viewer, animation);
  48810. }
  48811. for(const profile of data.profiles){
  48812. loadProfile(viewer, profile);
  48813. }
  48814. if(data.orientedImages){
  48815. for(const images of data.orientedImages){
  48816. loadOrientedImages(viewer, images);
  48817. }
  48818. }
  48819. loadAnnotations(viewer, data.annotations);
  48820. loadClassification(viewer, data.classification);
  48821. done && done();
  48822. // need to load at least one point cloud that defines the scene projection,
  48823. // before we can load stuff in other projections such as geopackages
  48824. //await Promise.any(pointcloudPromises); // (not yet supported)
  48825. /* Utils.waitAny(pointcloudPromises).then( () => {
  48826. if(data.geopackages){
  48827. for(const geopackage of data.geopackages){
  48828. loadGeopackage(viewer, geopackage);
  48829. }
  48830. }
  48831. });
  48832. await Promise.all(pointcloudPromises); */
  48833. }
  48834. //
  48835. // Algorithm by Christian Boucheny
  48836. // shader code taken and adapted from CloudCompare
  48837. //
  48838. // see
  48839. // https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL
  48840. // http://www.kitware.com/source/home/post/9
  48841. // https://tel.archives-ouvertes.fr/tel-00438464/document p. 115+ (french)
  48842. class EyeDomeLightingMaterial extends RawShaderMaterial{
  48843. constructor(parameters = {}){
  48844. super();
  48845. let uniforms = {
  48846. /* screenWidth: { type: 'f', value: 0 },
  48847. screenHeight: { type: 'f', value: 0 }, */
  48848. resolution: { type: 'v2', value: new Vector2$1() },
  48849. edlStrength: { type: 'f', value: 1.0 },
  48850. uNear: { type: 'f', value: 1.0 },
  48851. uFar: { type: 'f', value: 1.0 },
  48852. radius: { type: 'f', value: 1.0 },
  48853. neighbours: { type: '2fv', value: [] },
  48854. depthMap: { type: 't', value: null },
  48855. uEDLColor: { type: 't', value: null },
  48856. uEDLDepth: { type: 't', value: null },
  48857. opacity: { type: 'f', value: 1.0 },
  48858. uProj: { type: "Matrix4fv", value: [] },
  48859. useEDL: { type: 'i', value: 1 }//add
  48860. };
  48861. this.setValues({
  48862. uniforms: uniforms,
  48863. vertexShader: this.getDefines() + Shaders['edl.vs'],
  48864. fragmentShader: this.getDefines() + Shaders['edl.fs'],
  48865. lights: false
  48866. });
  48867. this.neighbourCount = 8;
  48868. }
  48869. getDefines() {
  48870. let defines = '';
  48871. defines += '#define NEIGHBOUR_COUNT ' + this.neighbourCount + '\n';
  48872. return defines;
  48873. }
  48874. updateShaderSource() {
  48875. let vs = this.getDefines() + Shaders['edl.vs'];
  48876. let fs = this.getDefines() + Shaders['edl.fs'];
  48877. this.setValues({
  48878. vertexShader: vs,
  48879. fragmentShader: fs
  48880. });
  48881. this.uniforms.neighbours.value = this.neighbours;
  48882. this.needsUpdate = true;
  48883. }
  48884. get neighbourCount(){
  48885. return this._neighbourCount;
  48886. }
  48887. set neighbourCount(value){
  48888. if (this._neighbourCount !== value) { //周围八个格子
  48889. this._neighbourCount = value;
  48890. this.neighbours = new Float32Array(this._neighbourCount * 2);
  48891. for (let c = 0; c < this._neighbourCount; c++) {
  48892. this.neighbours[2 * c + 0] = Math.cos(2 * c * Math.PI / this._neighbourCount);
  48893. this.neighbours[2 * c + 1] = Math.sin(2 * c * Math.PI / this._neighbourCount);
  48894. }
  48895. this.updateShaderSource();
  48896. }
  48897. }
  48898. }
  48899. class NormalizationEDLMaterial extends RawShaderMaterial{
  48900. constructor(parameters = {}){
  48901. super();
  48902. let uniforms = {
  48903. screenWidth: { type: 'f', value: 0 },
  48904. screenHeight: { type: 'f', value: 0 },
  48905. edlStrength: { type: 'f', value: 1.0 },
  48906. radius: { type: 'f', value: 1.0 },
  48907. neighbours: { type: '2fv', value: [] },
  48908. uEDLMap: { type: 't', value: null },
  48909. uDepthMap: { type: 't', value: null },
  48910. uWeightMap: { type: 't', value: null },
  48911. };
  48912. this.setValues({
  48913. uniforms: uniforms,
  48914. vertexShader: this.getDefines() + Shaders['normalize.vs'],
  48915. fragmentShader: this.getDefines() + Shaders['normalize_and_edl.fs'],
  48916. });
  48917. this.neighbourCount = 8;
  48918. }
  48919. getDefines() {
  48920. let defines = '';
  48921. defines += '#define NEIGHBOUR_COUNT ' + this.neighbourCount + '\n';
  48922. return defines;
  48923. }
  48924. updateShaderSource() {
  48925. let vs = this.getDefines() + Shaders['normalize.vs'];
  48926. let fs = this.getDefines() + Shaders['normalize_and_edl.fs'];
  48927. this.setValues({
  48928. vertexShader: vs,
  48929. fragmentShader: fs
  48930. });
  48931. this.uniforms.neighbours.value = this.neighbours;
  48932. this.needsUpdate = true;
  48933. }
  48934. get neighbourCount(){
  48935. return this._neighbourCount;
  48936. }
  48937. set neighbourCount(value){
  48938. if (this._neighbourCount !== value) {
  48939. this._neighbourCount = value;
  48940. this.neighbours = new Float32Array(this._neighbourCount * 2);
  48941. for (let c = 0; c < this._neighbourCount; c++) {
  48942. this.neighbours[2 * c + 0] = Math.cos(2 * c * Math.PI / this._neighbourCount);
  48943. this.neighbours[2 * c + 1] = Math.sin(2 * c * Math.PI / this._neighbourCount);
  48944. }
  48945. this.updateShaderSource();
  48946. }
  48947. }
  48948. }
  48949. class NormalizationMaterial extends RawShaderMaterial{
  48950. constructor(parameters = {}){
  48951. super();
  48952. let uniforms = {
  48953. uDepthMap: { type: 't', value: null },
  48954. uWeightMap: { type: 't', value: null },
  48955. };
  48956. this.setValues({
  48957. uniforms: uniforms,
  48958. vertexShader: this.getDefines() + Shaders['normalize.vs'],
  48959. fragmentShader: this.getDefines() + Shaders['normalize.fs'],
  48960. });
  48961. }
  48962. getDefines() {
  48963. let defines = '';
  48964. return defines;
  48965. }
  48966. updateShaderSource() {
  48967. let vs = this.getDefines() + Shaders['normalize.vs'];
  48968. let fs = this.getDefines() + Shaders['normalize.fs'];
  48969. this.setValues({
  48970. vertexShader: vs,
  48971. fragmentShader: fs
  48972. });
  48973. this.needsUpdate = true;
  48974. }
  48975. }
  48976. /**
  48977. * laslaz code taken and adapted from plas.io js-laslaz
  48978. * http://plas.io/
  48979. * https://github.com/verma/plasio
  48980. *
  48981. * Thanks to Uday Verma and Howard Butler
  48982. *
  48983. */
  48984. class LasLazLoader {
  48985. constructor (version, extension) {
  48986. if (typeof (version) === 'string') {
  48987. this.version = new Version(version);
  48988. } else {
  48989. this.version = version;
  48990. }
  48991. this.extension = extension;
  48992. }
  48993. static progressCB () {
  48994. }
  48995. load (node) {
  48996. if (node.loaded) {
  48997. return;
  48998. }
  48999. let url = node.getURL();
  49000. if (this.version.equalOrHigher('1.4')) {
  49001. url += `.${this.extension}`;
  49002. }
  49003. let xhr = XHRFactory.createXMLHttpRequest();
  49004. xhr.open('GET', url, true);
  49005. xhr.responseType = 'arraybuffer';
  49006. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  49007. xhr.onreadystatechange = () => {
  49008. if (xhr.readyState === 4) {
  49009. if (xhr.status === 200 || xhr.status === 0) {
  49010. let buffer = xhr.response;
  49011. this.parse(node, buffer);
  49012. } else {
  49013. console.log('Failed to load file! HTTP status: ' + xhr.status + ', file: ' + url);
  49014. }
  49015. }
  49016. };
  49017. xhr.send(null);
  49018. }
  49019. async parse(node, buffer){
  49020. let lf = new LASFile(buffer);
  49021. let handler = new LasLazBatcher(node);
  49022. try{
  49023. await lf.open();
  49024. lf.isOpen = true;
  49025. }catch(e){
  49026. console.log("failed to open file. :(");
  49027. return;
  49028. }
  49029. let header = await lf.getHeader();
  49030. let skip = 1;
  49031. let totalRead = 0;
  49032. let totalToRead = (skip <= 1 ? header.pointsCount : header.pointsCount / skip);
  49033. let hasMoreData = true;
  49034. while(hasMoreData){
  49035. let data = await lf.readData(1000 * 1000, 0, skip);
  49036. handler.push(new LASDecoder(data.buffer,
  49037. header.pointsFormatId,
  49038. header.pointsStructSize,
  49039. data.count,
  49040. header.scale,
  49041. header.offset,
  49042. header.mins, header.maxs));
  49043. totalRead += data.count;
  49044. LasLazLoader.progressCB(totalRead / totalToRead);
  49045. hasMoreData = data.hasMoreData;
  49046. }
  49047. header.totalRead = totalRead;
  49048. header.versionAsString = lf.versionAsString;
  49049. header.isCompressed = lf.isCompressed;
  49050. LasLazLoader.progressCB(1);
  49051. try{
  49052. await lf.close();
  49053. lf.isOpen = false;
  49054. }catch(e){
  49055. console.error("failed to close las/laz file!!!");
  49056. throw e;
  49057. }
  49058. }
  49059. handle (node, url) {
  49060. }
  49061. };
  49062. class LasLazBatcher{
  49063. constructor (node) {
  49064. this.node = node;
  49065. }
  49066. push (lasBuffer) {
  49067. const workerPath = Potree.scriptPath + '/workers/LASDecoderWorker.js';
  49068. const worker = Potree.workerPool.getWorker(workerPath);
  49069. const node = this.node;
  49070. const pointAttributes = node.pcoGeometry.pointAttributes;
  49071. worker.onmessage = (e) => {
  49072. let geometry = new BufferGeometry();
  49073. let numPoints = lasBuffer.pointsCount;
  49074. let positions = new Float32Array(e.data.position);
  49075. let colors = new Uint8Array(e.data.color);
  49076. let intensities = new Float32Array(e.data.intensity);
  49077. let classifications = new Uint8Array(e.data.classification);
  49078. let returnNumbers = new Uint8Array(e.data.returnNumber);
  49079. let numberOfReturns = new Uint8Array(e.data.numberOfReturns);
  49080. let pointSourceIDs = new Uint16Array(e.data.pointSourceID);
  49081. let indices = new Uint8Array(e.data.indices);
  49082. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  49083. geometry.setAttribute('color', new BufferAttribute(colors, 4, true));
  49084. geometry.setAttribute('intensity', new BufferAttribute(intensities, 1));
  49085. geometry.setAttribute('classification', new BufferAttribute(classifications, 1));
  49086. geometry.setAttribute('return number', new BufferAttribute(returnNumbers, 1));
  49087. geometry.setAttribute('number of returns', new BufferAttribute(numberOfReturns, 1));
  49088. geometry.setAttribute('source id', new BufferAttribute(pointSourceIDs, 1));
  49089. geometry.setAttribute('indices', new BufferAttribute(indices, 4));
  49090. geometry.attributes.indices.normalized = true;
  49091. for(const key in e.data.ranges){
  49092. const range = e.data.ranges[key];
  49093. const attribute = pointAttributes.attributes.find(a => a.name === key);
  49094. attribute.range[0] = Math.min(attribute.range[0], range[0]);
  49095. attribute.range[1] = Math.max(attribute.range[1], range[1]);
  49096. }
  49097. let tightBoundingBox = new Box3(
  49098. new Vector3().fromArray(e.data.tightBoundingBox.min),
  49099. new Vector3().fromArray(e.data.tightBoundingBox.max)
  49100. );
  49101. geometry.boundingBox = this.node.boundingBox;
  49102. this.node.tightBoundingBox = tightBoundingBox;
  49103. this.node.geometry = geometry;
  49104. this.node.numPoints = numPoints;
  49105. this.node.loaded = true;
  49106. this.node.loading = false;
  49107. Potree.numNodesLoading--;
  49108. this.node.mean = new Vector3(...e.data.mean);
  49109. Potree.workerPool.returnWorker(workerPath, worker);
  49110. };
  49111. let message = {
  49112. buffer: lasBuffer.arrayb,
  49113. numPoints: lasBuffer.pointsCount,
  49114. pointSize: lasBuffer.pointSize,
  49115. pointFormatID: 2,
  49116. scale: lasBuffer.scale,
  49117. offset: lasBuffer.offset,
  49118. mins: lasBuffer.mins,
  49119. maxs: lasBuffer.maxs
  49120. };
  49121. worker.postMessage(message, [message.buffer]);
  49122. };
  49123. }
  49124. //加载 解析点云
  49125. class BinaryLoader{
  49126. constructor(version, boundingBox, scale){
  49127. if (typeof (version) === 'string') {
  49128. this.version = new Version(version);
  49129. } else {
  49130. this.version = version;
  49131. }
  49132. this.boundingBox = boundingBox;
  49133. this.scale = scale;
  49134. }
  49135. load(node){
  49136. if (node.loaded) {
  49137. return;
  49138. }
  49139. let url = node.getURL();
  49140. if (this.version.equalOrHigher('1.4')) {
  49141. url += '.bin';
  49142. }
  49143. url += '?m='+node.pcoGeometry.timeStamp; //add
  49144. let xhr = XHRFactory.createXMLHttpRequest();
  49145. xhr.open('GET', url, true);
  49146. xhr.responseType = 'arraybuffer';
  49147. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  49148. xhr.onreadystatechange = () => {
  49149. if (xhr.readyState === 4) {
  49150. if((xhr.status === 200 || xhr.status === 0) && xhr.response !== null){
  49151. let buffer = xhr.response;
  49152. this.parse(node, buffer);
  49153. } else {
  49154. //console.error(`Failed to load file! HTTP status: ${xhr.status}, file: ${url}`);
  49155. throw new Error(`Failed to load file! HTTP status: ${xhr.status}, file: ${url}`);
  49156. }
  49157. }
  49158. };
  49159. try {
  49160. xhr.send(null);
  49161. } catch (e) {
  49162. console.log('fehler beim laden der punktwolke: ' + e);
  49163. }
  49164. };
  49165. parse(node, buffer){ //解析点云
  49166. let pointAttributes = node.pcoGeometry.pointAttributes;
  49167. let numPoints = buffer.byteLength / node.pcoGeometry.pointAttributes.byteSize;
  49168. if (this.version.upTo('1.5')) {
  49169. node.numPoints = numPoints;
  49170. }
  49171. let workerPath = Potree.scriptPath + '/workers/BinaryDecoderWorker.js';
  49172. let worker = Potree.workerPool.getWorker(workerPath);
  49173. worker.onmessage = function (e) {
  49174. let data = e.data;
  49175. let buffers = data.attributeBuffers;
  49176. let tightBoundingBox = new Box3(
  49177. new Vector3().fromArray(data.tightBoundingBox.min),
  49178. new Vector3().fromArray(data.tightBoundingBox.max)
  49179. );
  49180. Potree.workerPool.returnWorker(workerPath, worker);
  49181. let geometry = new BufferGeometry();
  49182. for(let property in buffers){
  49183. let buffer = buffers[property].buffer;
  49184. let batchAttribute = buffers[property].attribute;
  49185. if (property === "POSITION_CARTESIAN") {
  49186. geometry.setAttribute('position', new BufferAttribute(new Float32Array(buffer), 3));
  49187. } else if (property === "rgba") {
  49188. geometry.setAttribute("rgba", new BufferAttribute(new Uint8Array(buffer), 4, true));
  49189. } else if (property === "NORMAL_SPHEREMAPPED") {
  49190. geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3));
  49191. } else if (property === "NORMAL_OCT16") {
  49192. geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3));
  49193. } else if (property === "NORMAL") {
  49194. geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3));
  49195. } else if (property === "INDICES") {
  49196. let bufferAttribute = new BufferAttribute(new Uint8Array(buffer), 4);
  49197. bufferAttribute.normalized = true;
  49198. geometry.setAttribute('indices', bufferAttribute);
  49199. } else if (property === "SPACING") {
  49200. let bufferAttribute = new BufferAttribute(new Float32Array(buffer), 1);
  49201. geometry.setAttribute('spacing', bufferAttribute);
  49202. } else {
  49203. const bufferAttribute = new BufferAttribute(new Float32Array(buffer), 1);
  49204. bufferAttribute.potree = {
  49205. offset: buffers[property].offset,
  49206. scale: buffers[property].scale,
  49207. preciseBuffer: buffers[property].preciseBuffer,
  49208. range: batchAttribute.range,
  49209. };
  49210. geometry.setAttribute(property, bufferAttribute);
  49211. const attribute = pointAttributes.attributes.find(a => a.name === batchAttribute.name);
  49212. attribute.range[0] = Math.min(attribute.range[0], batchAttribute.range[0]);
  49213. attribute.range[1] = Math.max(attribute.range[1], batchAttribute.range[1]);
  49214. if(node.getLevel() === 0){
  49215. attribute.initialRange = batchAttribute.range;
  49216. }
  49217. }
  49218. }
  49219. tightBoundingBox.max.sub(tightBoundingBox.min);
  49220. tightBoundingBox.min.set(0, 0, 0);
  49221. let numPoints = e.data.buffer.byteLength / pointAttributes.byteSize;
  49222. node.numPoints = numPoints;
  49223. node.geometry = geometry;
  49224. node.mean = new Vector3(...data.mean);
  49225. node.tightBoundingBox = tightBoundingBox;
  49226. node.loaded = true;
  49227. node.loading = false;
  49228. node.estimatedSpacing = data.estimatedSpacing;
  49229. Potree.numNodesLoading--;
  49230. };
  49231. let message = {
  49232. buffer: buffer,
  49233. pointAttributes: pointAttributes,
  49234. version: this.version.version,
  49235. min: [ node.boundingBox.min.x, node.boundingBox.min.y, node.boundingBox.min.z ],
  49236. offset: [node.pcoGeometry.offset.x, node.pcoGeometry.offset.y, node.pcoGeometry.offset.z],
  49237. scale: this.scale,
  49238. spacing: node.spacing,
  49239. hasChildren: node.hasChildren,
  49240. name: node.name
  49241. };
  49242. worker.postMessage(message, [message.buffer]);
  49243. };
  49244. }
  49245. var transformFrom4dkk = function(name){
  49246. var jsAttribute = PointAttribute[name];
  49247. return jsAttribute
  49248. /* if(name == "POSITION_CARTESIAN"){
  49249. jsAttribute = {
  49250. description: "",
  49251. elementSize: 4,
  49252. elements: 3,
  49253. name: "POSITION_CARTESIAN",
  49254. size: 12,
  49255. type: "int32",
  49256. }
  49257. }else if(name == "COLOR_PACKED"){
  49258. jsAttribute = {
  49259. description: "" ,
  49260. elementSize: 1,
  49261. elements: 4,
  49262. name: "RGBA",
  49263. size: 4,
  49264. type: 'int8',
  49265. }
  49266. }else if(name == "NORMAL_OCT16"){
  49267. jsAttribute = {
  49268. description: "" ,
  49269. elementSize: 4,
  49270. elements: 2,
  49271. name: "NORMAL_OCT16",
  49272. size: 12,
  49273. type: "uint8",
  49274. }
  49275. } */
  49276. /* var Q = q(L.COLOR_PACKED, K.DATA_TYPE_INT8, 4)
  49277. POSITION_CARTESIAN: q(L.POSITION_CARTESIAN, K.DATA_TYPE_FLOAT, 3),
  49278. RGBA_PACKED: Q,
  49279. COLOR_PACKED: Q,
  49280. RGB_PACKED: q(L.COLOR_PACKED, K.DATA_TYPE_INT8, 3),
  49281. NORMAL_FLOATS: q(L.NORMAL_FLOATS, K.DATA_TYPE_FLOAT, 3),
  49282. FILLER_1B: q(L.FILLER, K.DATA_TYPE_UINT8, 1),
  49283. INTENSITY: q(L.INTENSITY, K.DATA_TYPE_UINT16, 1),
  49284. CLASSIFICATION: q(L.CLASSIFICATION, K.DATA_TYPE_UINT8, 1),
  49285. NORMAL_SPHEREMAPPED: q(L.NORMAL_SPHEREMAPPED, K.DATA_TYPE_UINT8, 2),
  49286. NORMAL_OCT16: q(L.NORMAL_OCT16, K.DATA_TYPE_UINT8, 2),
  49287. NORMAL: q(L.NORMAL, K.DATA_TYPE_FLOAT, 3) */
  49288. };
  49289. function parseAttributes(cloudjs){
  49290. let version = new Version(cloudjs.version);
  49291. const replacements = {
  49292. "COLOR_PACKED": "rgba",
  49293. "RGBA": "rgba",
  49294. "INTENSITY": "intensity",
  49295. "CLASSIFICATION": "classification",
  49296. "GPS_TIME": "gps-time",
  49297. };
  49298. const replaceOldNames = (old) => {
  49299. if(replacements[old]){
  49300. return replacements[old];
  49301. }else {
  49302. return old;
  49303. }
  49304. };
  49305. const pointAttributes = [];
  49306. if(version.upTo('1.7')){
  49307. for(let attributeName of cloudjs.pointAttributes){
  49308. const oldAttribute = PointAttribute[attributeName];
  49309. const attribute = {
  49310. name: oldAttribute.name,
  49311. size: oldAttribute.byteSize,
  49312. elements: oldAttribute.numElements,
  49313. elementSize: oldAttribute.byteSize / oldAttribute.numElements,
  49314. type: oldAttribute.type.name,
  49315. description: "",
  49316. };
  49317. pointAttributes.push(attribute);
  49318. }
  49319. }else {
  49320. pointAttributes.push(...cloudjs.pointAttributes);
  49321. }
  49322. {
  49323. const attributes = new PointAttributes();
  49324. const typeConversion = {
  49325. int8: PointAttributeTypes.DATA_TYPE_INT8,
  49326. int16: PointAttributeTypes.DATA_TYPE_INT16,
  49327. int32: PointAttributeTypes.DATA_TYPE_INT32,
  49328. int64: PointAttributeTypes.DATA_TYPE_INT64,
  49329. uint8: PointAttributeTypes.DATA_TYPE_UINT8,
  49330. uint16: PointAttributeTypes.DATA_TYPE_UINT16,
  49331. uint32: PointAttributeTypes.DATA_TYPE_UINT32,
  49332. uint64: PointAttributeTypes.DATA_TYPE_UINT64,
  49333. double: PointAttributeTypes.DATA_TYPE_DOUBLE,
  49334. float: PointAttributeTypes.DATA_TYPE_FLOAT,
  49335. };
  49336. for(let jsAttribute of pointAttributes){
  49337. if(jsAttribute.name == void 0){//是来自四维看看的数据
  49338. //attribute = transformFrom4dkk(jsAttribute)
  49339. var attribute_ = PointAttribute[jsAttribute];
  49340. attributes.add(attribute_);
  49341. continue;
  49342. }
  49343. const name = replaceOldNames(jsAttribute.name);
  49344. const type = typeConversion[jsAttribute.type];
  49345. const numElements = jsAttribute.elements;
  49346. const description = jsAttribute.description;
  49347. const attribute = new PointAttribute(name, type, numElements);
  49348. attributes.add(attribute);
  49349. }
  49350. {
  49351. // check if it has normals
  49352. let hasNormals =
  49353. pointAttributes.find(a => a.name === "NormalX") !== undefined &&
  49354. pointAttributes.find(a => a.name === "NormalY") !== undefined &&
  49355. pointAttributes.find(a => a.name === "NormalZ") !== undefined;
  49356. if(hasNormals){
  49357. let vector = {
  49358. name: "NORMAL",
  49359. attributes: ["NormalX", "NormalY", "NormalZ"],
  49360. };
  49361. attributes.addVector(vector);
  49362. }
  49363. }
  49364. return attributes;
  49365. }
  49366. }
  49367. function lasLazAttributes(fMno){
  49368. const attributes = new PointAttributes();
  49369. attributes.add(PointAttribute.POSITION_CARTESIAN);
  49370. attributes.add(new PointAttribute("rgba", PointAttributeTypes.DATA_TYPE_UINT8, 4));
  49371. attributes.add(new PointAttribute("intensity", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  49372. attributes.add(new PointAttribute("classification", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  49373. attributes.add(new PointAttribute("gps-time", PointAttributeTypes.DATA_TYPE_DOUBLE, 1));
  49374. attributes.add(new PointAttribute("number of returns", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  49375. attributes.add(new PointAttribute("return number", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  49376. attributes.add(new PointAttribute("source id", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  49377. //attributes.add(new PointAttribute("pointSourceID", PointAttributeTypes.DATA_TYPE_INT8, 4));
  49378. return attributes;
  49379. }
  49380. class POCLoader {
  49381. static load(url, timeStamp, callback){ //add timeStamp
  49382. try {
  49383. let pco = new PointCloudOctreeGeometry();
  49384. pco.timeStamp = timeStamp;
  49385. pco.url = url;
  49386. let xhr = XHRFactory.createXMLHttpRequest();
  49387. xhr.open('GET', url+'?m='+timeStamp, true);
  49388. xhr.onreadystatechange = function () {
  49389. if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 0)) {
  49390. let fMno = JSON.parse(xhr.responseText);
  49391. let version = new Version(fMno.version);
  49392. // assume octreeDir is absolute if it starts with http
  49393. if (fMno.octreeDir.indexOf('http') === 0) {
  49394. pco.octreeDir = fMno.octreeDir;
  49395. } else {
  49396. pco.octreeDir = url + '/../' + fMno.octreeDir;
  49397. }
  49398. pco.spacing = fMno.spacing;
  49399. pco.hierarchyStepSize = fMno.hierarchyStepSize;
  49400. pco.pointAttributes = fMno.pointAttributes;
  49401. let min = new Vector3(fMno.boundingBox.lx, fMno.boundingBox.ly, fMno.boundingBox.lz);
  49402. let max = new Vector3(fMno.boundingBox.ux, fMno.boundingBox.uy, fMno.boundingBox.uz);
  49403. let boundingBox = new Box3(min, max);
  49404. let tightBoundingBox = boundingBox.clone();
  49405. if (fMno.tightBoundingBox) {//这个才是真实的bounding,前面那个bounding的size是个正方体,似乎取了最长边作为边长
  49406. tightBoundingBox.min.copy(new Vector3(fMno.tightBoundingBox.lx, fMno.tightBoundingBox.ly, fMno.tightBoundingBox.lz));
  49407. tightBoundingBox.max.copy(new Vector3(fMno.tightBoundingBox.ux, fMno.tightBoundingBox.uy, fMno.tightBoundingBox.uz));
  49408. }
  49409. let offset = min.clone(); //将成为点云的position,被我用作旋转中心(但在点云中不那么居中,navvis也是这样, 这样可能是为了让模型在这数据的bounding上)
  49410. boundingBox.min.sub(offset); //点云的真实坐标的min都是0,0,0吗(我看案例是,因绕角落旋转,也就是原点)
  49411. boundingBox.max.sub(offset);
  49412. tightBoundingBox.min.sub(offset);
  49413. tightBoundingBox.max.sub(offset);
  49414. //改
  49415. //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 ",
  49416. //"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs" //给地图
  49417. pco.boundingBox = boundingBox;
  49418. pco.tightBoundingBox = tightBoundingBox;
  49419. pco.boundingSphere = boundingBox.getBoundingSphere(new Sphere());
  49420. pco.tightBoundingSphere = tightBoundingBox.getBoundingSphere(new Sphere());
  49421. pco.offset = offset;
  49422. if (fMno.pointAttributes === 'LAS') {
  49423. pco.loader = new LasLazLoader(fMno.version, "las");
  49424. pco.pointAttributes = lasLazAttributes(fMno);
  49425. } else if (fMno.pointAttributes === 'LAZ') {
  49426. pco.loader = new LasLazLoader(fMno.version, "laz");
  49427. pco.pointAttributes = lasLazAttributes(fMno);
  49428. } else {
  49429. pco.loader = new BinaryLoader(fMno.version, boundingBox, fMno.scale);
  49430. pco.pointAttributes = parseAttributes(fMno);
  49431. }
  49432. let nodes = {};
  49433. { // load root
  49434. let name = 'r';
  49435. let root = new PointCloudOctreeGeometryNode(name, pco, boundingBox);
  49436. root.level = 0;
  49437. root.hasChildren = true;
  49438. root.spacing = pco.spacing;
  49439. if (version.upTo('1.5')) {
  49440. root.numPoints = fMno.hierarchy[0][1];
  49441. } else {
  49442. root.numPoints = 0;
  49443. }
  49444. pco.root = root;
  49445. pco.root.load();
  49446. nodes[name] = root;
  49447. }
  49448. // load remaining hierarchy
  49449. if (version.upTo('1.4')) {
  49450. for (let i = 1; i < fMno.hierarchy.length; i++) {
  49451. let name = fMno.hierarchy[i][0];
  49452. let numPoints = fMno.hierarchy[i][1];
  49453. let index = parseInt(name.charAt(name.length - 1));
  49454. let parentName = name.substring(0, name.length - 1);
  49455. let parentNode = nodes[parentName];
  49456. let level = name.length - 1;
  49457. //let boundingBox = POCLoader.createChildAABB(parentNode.boundingBox, index);
  49458. let boundingBox = Utils.createChildAABB(parentNode.boundingBox, index);
  49459. let node = new PointCloudOctreeGeometryNode(name, pco, boundingBox);
  49460. node.level = level;
  49461. node.numPoints = numPoints;
  49462. node.spacing = pco.spacing / Math.pow(2, level);
  49463. parentNode.addChild(node);
  49464. nodes[name] = node;
  49465. }
  49466. }
  49467. pco.nodes = nodes;
  49468. callback(pco);
  49469. }
  49470. };
  49471. xhr.send(null);
  49472. } catch (e) {
  49473. console.log("loading failed: '" + url + "'");
  49474. console.log(e);
  49475. callback();
  49476. }
  49477. }
  49478. loadPointAttributes(mno){
  49479. let fpa = mno.pointAttributes;
  49480. let pa = new PointAttributes();
  49481. for (let i = 0; i < fpa.length; i++) {
  49482. let pointAttribute = PointAttribute[fpa[i]];
  49483. pa.add(pointAttribute);
  49484. }
  49485. return pa;
  49486. }
  49487. createChildAABB(aabb, index){
  49488. let min = aabb.min.clone();
  49489. let max = aabb.max.clone();
  49490. let size = new Vector3().subVectors(max, min);
  49491. if ((index & 0b0001) > 0) {
  49492. min.z += size.z / 2;
  49493. } else {
  49494. max.z -= size.z / 2;
  49495. }
  49496. if ((index & 0b0010) > 0) {
  49497. min.y += size.y / 2;
  49498. } else {
  49499. max.y -= size.y / 2;
  49500. }
  49501. if ((index & 0b0100) > 0) {
  49502. min.x += size.x / 2;
  49503. } else {
  49504. max.x -= size.x / 2;
  49505. }
  49506. return new Box3(min, max);
  49507. }
  49508. }
  49509. /**
  49510. * @author Connor Manning
  49511. */
  49512. class EptLoader {
  49513. static async load(file, callback) {
  49514. let response = await fetch(file);
  49515. let json = await response.json();
  49516. let url = file.substr(0, file.lastIndexOf('ept.json'));
  49517. let geometry = new Potree.PointCloudEptGeometry(url, json);
  49518. let root = new Potree.PointCloudEptGeometryNode(geometry);
  49519. geometry.root = root;
  49520. geometry.root.load();
  49521. callback(geometry);
  49522. }
  49523. };
  49524. class EptBinaryLoader {
  49525. extension() {
  49526. return '.bin';
  49527. }
  49528. workerPath() {
  49529. return Potree.scriptPath + '/workers/EptBinaryDecoderWorker.js';
  49530. }
  49531. load(node) {
  49532. if (node.loaded) return;
  49533. let url = node.url() + this.extension();
  49534. let xhr = XHRFactory.createXMLHttpRequest();
  49535. xhr.open('GET', url, true);
  49536. xhr.responseType = 'arraybuffer';
  49537. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  49538. xhr.onreadystatechange = () => {
  49539. if (xhr.readyState === 4) {
  49540. if (xhr.status === 200) {
  49541. let buffer = xhr.response;
  49542. this.parse(node, buffer);
  49543. } else {
  49544. console.log('Failed ' + url + ': ' + xhr.status);
  49545. }
  49546. }
  49547. };
  49548. try {
  49549. xhr.send(null);
  49550. }
  49551. catch (e) {
  49552. console.log('Failed request: ' + e);
  49553. }
  49554. }
  49555. parse(node, buffer) {
  49556. let workerPath = this.workerPath();
  49557. let worker = Potree.workerPool.getWorker(workerPath);
  49558. worker.onmessage = function(e) {
  49559. let g = new BufferGeometry();
  49560. let numPoints = e.data.numPoints;
  49561. let position = new Float32Array(e.data.position);
  49562. g.setAttribute('position', new BufferAttribute(position, 3));
  49563. let indices = new Uint8Array(e.data.indices);
  49564. g.setAttribute('indices', new BufferAttribute(indices, 4));
  49565. if (e.data.color) {
  49566. let color = new Uint8Array(e.data.color);
  49567. g.setAttribute('color', new BufferAttribute(color, 4, true));
  49568. }
  49569. if (e.data.intensity) {
  49570. let intensity = new Float32Array(e.data.intensity);
  49571. g.setAttribute('intensity',
  49572. new BufferAttribute(intensity, 1));
  49573. }
  49574. if (e.data.classification) {
  49575. let classification = new Uint8Array(e.data.classification);
  49576. g.setAttribute('classification',
  49577. new BufferAttribute(classification, 1));
  49578. }
  49579. if (e.data.returnNumber) {
  49580. let returnNumber = new Uint8Array(e.data.returnNumber);
  49581. g.setAttribute('return number',
  49582. new BufferAttribute(returnNumber, 1));
  49583. }
  49584. if (e.data.numberOfReturns) {
  49585. let numberOfReturns = new Uint8Array(e.data.numberOfReturns);
  49586. g.setAttribute('number of returns',
  49587. new BufferAttribute(numberOfReturns, 1));
  49588. }
  49589. if (e.data.pointSourceId) {
  49590. let pointSourceId = new Uint16Array(e.data.pointSourceId);
  49591. g.setAttribute('source id',
  49592. new BufferAttribute(pointSourceId, 1));
  49593. }
  49594. g.attributes.indices.normalized = true;
  49595. let tightBoundingBox = new Box3(
  49596. new Vector3().fromArray(e.data.tightBoundingBox.min),
  49597. new Vector3().fromArray(e.data.tightBoundingBox.max)
  49598. );
  49599. node.doneLoading(
  49600. g,
  49601. tightBoundingBox,
  49602. numPoints,
  49603. new Vector3(...e.data.mean));
  49604. Potree.workerPool.returnWorker(workerPath, worker);
  49605. };
  49606. let toArray = (v) => [v.x, v.y, v.z];
  49607. let message = {
  49608. buffer: buffer,
  49609. schema: node.ept.schema,
  49610. scale: node.ept.eptScale,
  49611. offset: node.ept.eptOffset,
  49612. mins: toArray(node.key.b.min)
  49613. };
  49614. worker.postMessage(message, [message.buffer]);
  49615. }
  49616. };
  49617. /**
  49618. * laslaz code taken and adapted from plas.io js-laslaz
  49619. * http://plas.io/
  49620. * https://github.com/verma/plasio
  49621. *
  49622. * Thanks to Uday Verma and Howard Butler
  49623. *
  49624. */
  49625. class EptLaszipLoader {
  49626. load(node) {
  49627. if (node.loaded) return;
  49628. let url = node.url() + '.laz';
  49629. let xhr = XHRFactory.createXMLHttpRequest();
  49630. xhr.open('GET', url, true);
  49631. xhr.responseType = 'arraybuffer';
  49632. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  49633. xhr.onreadystatechange = () => {
  49634. if (xhr.readyState === 4) {
  49635. if (xhr.status === 200) {
  49636. let buffer = xhr.response;
  49637. this.parse(node, buffer);
  49638. } else {
  49639. console.log('Failed ' + url + ': ' + xhr.status);
  49640. }
  49641. }
  49642. };
  49643. xhr.send(null);
  49644. }
  49645. async parse(node, buffer){
  49646. let lf = new LASFile(buffer);
  49647. let handler = new EptLazBatcher(node);
  49648. try{
  49649. await lf.open();
  49650. lf.isOpen = true;
  49651. const header = await lf.getHeader();
  49652. {
  49653. let i = 0;
  49654. let toArray = (v) => [v.x, v.y, v.z];
  49655. let mins = toArray(node.key.b.min);
  49656. let maxs = toArray(node.key.b.max);
  49657. let hasMoreData = true;
  49658. while(hasMoreData){
  49659. const data = await lf.readData(1000000, 0, 1);
  49660. let d = new LASDecoder(
  49661. data.buffer,
  49662. header.pointsFormatId,
  49663. header.pointsStructSize,
  49664. data.count,
  49665. header.scale,
  49666. header.offset,
  49667. mins,
  49668. maxs);
  49669. d.extraBytes = header.extraBytes;
  49670. d.pointsFormatId = header.pointsFormatId;
  49671. handler.push(d);
  49672. i += data.count;
  49673. hasMoreData = data.hasMoreData;
  49674. }
  49675. header.totalRead = i;
  49676. header.versionAsString = lf.versionAsString;
  49677. header.isCompressed = lf.isCompressed;
  49678. await lf.close();
  49679. lf.isOpen = false;
  49680. }
  49681. }catch(err){
  49682. console.error('Error reading LAZ:', err);
  49683. if (lf.isOpen) {
  49684. await lf.close();
  49685. lf.isOpen = false;
  49686. }
  49687. throw err;
  49688. }
  49689. }
  49690. };
  49691. class EptLazBatcher {
  49692. constructor(node) { this.node = node; }
  49693. push(las) {
  49694. let workerPath = Potree.scriptPath +
  49695. '/workers/EptLaszipDecoderWorker.js';
  49696. let worker = Potree.workerPool.getWorker(workerPath);
  49697. worker.onmessage = (e) => {
  49698. let g = new BufferGeometry();
  49699. let numPoints = las.pointsCount;
  49700. let positions = new Float32Array(e.data.position);
  49701. let colors = new Uint8Array(e.data.color);
  49702. let intensities = new Float32Array(e.data.intensity);
  49703. let classifications = new Uint8Array(e.data.classification);
  49704. let returnNumbers = new Uint8Array(e.data.returnNumber);
  49705. let numberOfReturns = new Uint8Array(e.data.numberOfReturns);
  49706. let pointSourceIDs = new Uint16Array(e.data.pointSourceID);
  49707. let indices = new Uint8Array(e.data.indices);
  49708. let gpsTime = new Float32Array(e.data.gpsTime);
  49709. g.setAttribute('position',
  49710. new BufferAttribute(positions, 3));
  49711. g.setAttribute('rgba',
  49712. new BufferAttribute(colors, 4, true));
  49713. g.setAttribute('intensity',
  49714. new BufferAttribute(intensities, 1));
  49715. g.setAttribute('classification',
  49716. new BufferAttribute(classifications, 1));
  49717. g.setAttribute('return number',
  49718. new BufferAttribute(returnNumbers, 1));
  49719. g.setAttribute('number of returns',
  49720. new BufferAttribute(numberOfReturns, 1));
  49721. g.setAttribute('source id',
  49722. new BufferAttribute(pointSourceIDs, 1));
  49723. g.setAttribute('indices',
  49724. new BufferAttribute(indices, 4));
  49725. g.setAttribute('gpsTime',
  49726. new BufferAttribute(gpsTime, 1));
  49727. this.node.gpsTime = e.data.gpsMeta;
  49728. g.attributes.indices.normalized = true;
  49729. let tightBoundingBox = new Box3(
  49730. new Vector3().fromArray(e.data.tightBoundingBox.min),
  49731. new Vector3().fromArray(e.data.tightBoundingBox.max)
  49732. );
  49733. this.node.doneLoading(
  49734. g,
  49735. tightBoundingBox,
  49736. numPoints,
  49737. new Vector3(...e.data.mean));
  49738. Potree.workerPool.returnWorker(workerPath, worker);
  49739. };
  49740. let message = {
  49741. buffer: las.arrayb,
  49742. numPoints: las.pointsCount,
  49743. pointSize: las.pointSize,
  49744. pointFormatID: las.pointsFormatId,
  49745. scale: las.scale,
  49746. offset: las.offset,
  49747. mins: las.mins,
  49748. maxs: las.maxs
  49749. };
  49750. worker.postMessage(message, [message.buffer]);
  49751. };
  49752. };
  49753. class EptZstandardLoader extends EptBinaryLoader {
  49754. extension() {
  49755. return '.zst';
  49756. }
  49757. workerPath() {
  49758. return Potree.scriptPath + '/workers/EptZstandardDecoderWorker.js';
  49759. }
  49760. };
  49761. class ShapefileLoader{
  49762. constructor(){
  49763. this.transform = null;
  49764. }
  49765. async load(path){
  49766. const matLine = new LineMaterial( {
  49767. color: 0xff0000,
  49768. lineWidth: 3, // in pixels
  49769. resolution: new Vector2$1(1000, 1000),
  49770. dashed: false
  49771. } );
  49772. const features = await this.loadShapefileFeatures(path);
  49773. const node = new Object3D();
  49774. for(const feature of features){
  49775. const fnode = this.featureToSceneNode(feature, matLine);
  49776. node.add(fnode);
  49777. }
  49778. let setResolution = (x, y) => {
  49779. matLine.resolution.set(x, y);
  49780. };
  49781. const result = {
  49782. features: features,
  49783. node: node,
  49784. setResolution: setResolution,
  49785. };
  49786. return result;
  49787. }
  49788. featureToSceneNode(feature, matLine){
  49789. let geometry = feature.geometry;
  49790. let color = new Color(1, 1, 1);
  49791. let transform = this.transform;
  49792. if(transform === null){
  49793. transform = {forward: (v) => v};
  49794. }
  49795. if(feature.geometry.type === "Point"){
  49796. let sg = new SphereGeometry(1, 18, 18);
  49797. let sm = new MeshNormalMaterial();
  49798. let s = new Mesh(sg, sm);
  49799. let [long, lat] = geometry.coordinates;
  49800. let pos = transform.forward([long, lat]);
  49801. s.position.set(...pos, 20);
  49802. s.scale.set(10, 10, 10);
  49803. return s;
  49804. }else if(geometry.type === "LineString"){
  49805. let coordinates = [];
  49806. let min = new Vector3(Infinity, Infinity, Infinity);
  49807. for(let i = 0; i < geometry.coordinates.length; i++){
  49808. let [long, lat] = geometry.coordinates[i];
  49809. let pos = transform.forward([long, lat]);
  49810. min.x = Math.min(min.x, pos[0]);
  49811. min.y = Math.min(min.y, pos[1]);
  49812. min.z = Math.min(min.z, 20);
  49813. coordinates.push(...pos, 20);
  49814. if(i > 0 && i < geometry.coordinates.length - 1){
  49815. coordinates.push(...pos, 20);
  49816. }
  49817. }
  49818. for(let i = 0; i < coordinates.length; i += 3){
  49819. coordinates[i+0] -= min.x;
  49820. coordinates[i+1] -= min.y;
  49821. coordinates[i+2] -= min.z;
  49822. }
  49823. const lineGeometry = new LineGeometry();
  49824. lineGeometry.setPositions( coordinates );
  49825. const line = new Line2( lineGeometry, matLine );
  49826. line.computeLineDistances();
  49827. line.scale.set( 1, 1, 1 );
  49828. line.position.copy(min);
  49829. return line;
  49830. }else if(geometry.type === "Polygon"){
  49831. for(let pc of geometry.coordinates){
  49832. let coordinates = [];
  49833. let min = new Vector3(Infinity, Infinity, Infinity);
  49834. for(let i = 0; i < pc.length; i++){
  49835. let [long, lat] = pc[i];
  49836. let pos = transform.forward([long, lat]);
  49837. min.x = Math.min(min.x, pos[0]);
  49838. min.y = Math.min(min.y, pos[1]);
  49839. min.z = Math.min(min.z, 20);
  49840. coordinates.push(...pos, 20);
  49841. if(i > 0 && i < pc.length - 1){
  49842. coordinates.push(...pos, 20);
  49843. }
  49844. }
  49845. for(let i = 0; i < coordinates.length; i += 3){
  49846. coordinates[i+0] -= min.x;
  49847. coordinates[i+1] -= min.y;
  49848. coordinates[i+2] -= min.z;
  49849. }
  49850. const lineGeometry = new LineGeometry();
  49851. lineGeometry.setPositions( coordinates );
  49852. const line = new Line2( lineGeometry, matLine );
  49853. line.computeLineDistances();
  49854. line.scale.set( 1, 1, 1 );
  49855. line.position.copy(min);
  49856. return line;
  49857. }
  49858. }else {
  49859. console.log("unhandled feature: ", feature);
  49860. }
  49861. }
  49862. async loadShapefileFeatures(file){
  49863. let features = [];
  49864. let source = await shapefile.open(file);
  49865. while(true){
  49866. let result = await source.read();
  49867. if (result.done) {
  49868. break;
  49869. }
  49870. if (result.value && result.value.type === 'Feature' && result.value.geometry !== undefined) {
  49871. features.push(result.value);
  49872. }
  49873. }
  49874. return features;
  49875. }
  49876. };
  49877. const defaultColors = {
  49878. "landuse": [0.5, 0.5, 0.5],
  49879. "natural": [0.0, 1.0, 0.0],
  49880. "places": [1.0, 0.0, 1.0],
  49881. "points": [0.0, 1.0, 1.0],
  49882. "roads": [1.0, 1.0, 0.0],
  49883. "waterways": [0.0, 0.0, 1.0],
  49884. "default": [0.9, 0.6, 0.1],
  49885. };
  49886. function getColor(feature){
  49887. let color = defaultColors[feature];
  49888. if(!color){
  49889. color = defaultColors["default"];
  49890. }
  49891. return color;
  49892. }
  49893. class Geopackage$1{
  49894. constructor(){
  49895. this.path = null;
  49896. this.node = null;
  49897. }
  49898. };
  49899. class GeoPackageLoader{
  49900. constructor(){
  49901. }
  49902. static async loadUrl(url, params){
  49903. await Promise.all([
  49904. Utils.loadScript(`${Potree.scriptPath}/lazylibs/geopackage/geopackage.js`),
  49905. Utils.loadScript(`${Potree.scriptPath}/lazylibs/sql.js/sql-wasm.js`),
  49906. ]);
  49907. const result = await fetch(url);
  49908. const buffer = await result.arrayBuffer();
  49909. params = params || {};
  49910. params.source = url;
  49911. return GeoPackageLoader.loadBuffer(buffer, params);
  49912. }
  49913. static async loadBuffer(buffer, params){
  49914. await Promise.all([
  49915. Utils.loadScript(`${Potree.scriptPath}/lazylibs/geopackage/geopackage.js`),
  49916. Utils.loadScript(`${Potree.scriptPath}/lazylibs/sql.js/sql-wasm.js`),
  49917. ]);
  49918. params = params || {};
  49919. const resolver = async (resolve) => {
  49920. let transform = params.transform;
  49921. if(!transform){
  49922. transform = {forward: (arg) => arg};
  49923. }
  49924. const wasmPath = `${Potree.scriptPath}/lazylibs/sql.js/sql-wasm.wasm`;
  49925. const SQL = await initSqlJs({ locateFile: filename => wasmPath});
  49926. const u8 = new Uint8Array(buffer);
  49927. const data = await geopackage.open(u8);
  49928. window.data = data;
  49929. const geopackageNode = new Object3D();
  49930. geopackageNode.name = params.source;
  49931. geopackageNode.potree = {
  49932. source: params.source,
  49933. };
  49934. const geo = new Geopackage$1();
  49935. geo.path = params.source;
  49936. geo.node = geopackageNode;
  49937. const tables = data.getTables();
  49938. for(const table of tables.features){
  49939. const dao = data.getFeatureDao(table);
  49940. let boundingBox = dao.getBoundingBox();
  49941. boundingBox = boundingBox.projectBoundingBox(dao.projection, 'EPSG:4326');
  49942. const geoJson = data.queryForGeoJSONFeaturesInTable(table, boundingBox);
  49943. const matLine = new LineMaterial( {
  49944. color: new Color().setRGB(...getColor(table)),
  49945. lineWidth: 2,
  49946. resolution: new Vector2$1(1000, 1000),
  49947. dashed: false
  49948. } );
  49949. const node = new Object3D();
  49950. node.name = table;
  49951. geo.node.add(node);
  49952. for(const [index, feature] of Object.entries(geoJson)){
  49953. //const featureNode = GeoPackageLoader.featureToSceneNode(feature, matLine, transform);
  49954. const featureNode = GeoPackageLoader.featureToSceneNode(feature, matLine, dao.projection, transform);
  49955. node.add(featureNode);
  49956. }
  49957. }
  49958. resolve(geo);
  49959. };
  49960. return new Promise(resolver);
  49961. }
  49962. static featureToSceneNode(feature, matLine, geopackageProjection, transform){
  49963. let geometry = feature.geometry;
  49964. let color = new Color(1, 1, 1);
  49965. if(feature.geometry.type === "Point"){
  49966. let sg = new SphereGeometry(1, 18, 18);
  49967. let sm = new MeshNormalMaterial();
  49968. let s = new Mesh(sg, sm);
  49969. let [long, lat] = geometry.coordinates;
  49970. let pos = transform.forward(geopackageProjection.forward([long, lat]));
  49971. s.position.set(...pos, 20);
  49972. s.scale.set(10, 10, 10);
  49973. return s;
  49974. }else if(geometry.type === "LineString"){
  49975. let coordinates = [];
  49976. let min = new Vector3(Infinity, Infinity, Infinity);
  49977. for(let i = 0; i < geometry.coordinates.length; i++){
  49978. let [long, lat] = geometry.coordinates[i];
  49979. let pos = transform.forward(geopackageProjection.forward([long, lat]));
  49980. min.x = Math.min(min.x, pos[0]);
  49981. min.y = Math.min(min.y, pos[1]);
  49982. min.z = Math.min(min.z, 20);
  49983. coordinates.push(...pos, 20);
  49984. if(i > 0 && i < geometry.coordinates.length - 1){
  49985. coordinates.push(...pos, 20);
  49986. }
  49987. }
  49988. for(let i = 0; i < coordinates.length; i += 3){
  49989. coordinates[i+0] -= min.x;
  49990. coordinates[i+1] -= min.y;
  49991. coordinates[i+2] -= min.z;
  49992. }
  49993. const lineGeometry = new LineGeometry();
  49994. lineGeometry.setPositions( coordinates );
  49995. const line = new Line2( lineGeometry, matLine );
  49996. line.computeLineDistances();
  49997. line.scale.set( 1, 1, 1 );
  49998. line.position.copy(min);
  49999. return line;
  50000. }else if(geometry.type === "Polygon"){
  50001. for(let pc of geometry.coordinates){
  50002. let coordinates = [];
  50003. let min = new Vector3(Infinity, Infinity, Infinity);
  50004. for(let i = 0; i < pc.length; i++){
  50005. let [long, lat] = pc[i];
  50006. let pos = transform.forward(geopackageProjection.forward([long, lat]));
  50007. min.x = Math.min(min.x, pos[0]);
  50008. min.y = Math.min(min.y, pos[1]);
  50009. min.z = Math.min(min.z, 20);
  50010. coordinates.push(...pos, 20);
  50011. if(i > 0 && i < pc.length - 1){
  50012. coordinates.push(...pos, 20);
  50013. }
  50014. }
  50015. for(let i = 0; i < coordinates.length; i += 3){
  50016. coordinates[i+0] -= min.x;
  50017. coordinates[i+1] -= min.y;
  50018. coordinates[i+2] -= min.z;
  50019. }
  50020. const lineGeometry = new LineGeometry();
  50021. lineGeometry.setPositions( coordinates );
  50022. const line = new Line2( lineGeometry, matLine );
  50023. line.computeLineDistances();
  50024. line.scale.set( 1, 1, 1 );
  50025. line.position.copy(min);
  50026. return line;
  50027. }
  50028. }else {
  50029. console.log("unhandled feature: ", feature);
  50030. }
  50031. }
  50032. };
  50033. class ClipVolume extends Object3D{
  50034. constructor(args={}){
  50035. super();
  50036. this.constructor.counter = (this.constructor.counter === undefined) ? 0 : this.constructor.counter + 1;
  50037. this.name = "clip_volume_" + this.constructor.counter;
  50038. let alpha = args.alpha || 0;
  50039. let beta = args.beta || 0;
  50040. let gamma = args.gamma || 0;
  50041. this.rotation.x = alpha;
  50042. this.rotation.y = beta;
  50043. this.rotation.z = gamma;
  50044. this.clipOffset = 0.001;
  50045. this.clipRotOffset = 1;
  50046. let boxGeometry = new BoxGeometry(1, 1, 1);
  50047. boxGeometry.computeBoundingBox();
  50048. let boxFrameGeometry = new Geometry();
  50049. {
  50050. // bottom
  50051. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  50052. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  50053. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  50054. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  50055. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  50056. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  50057. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  50058. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  50059. // top
  50060. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  50061. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  50062. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  50063. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  50064. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  50065. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  50066. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  50067. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  50068. // sides
  50069. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  50070. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  50071. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  50072. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  50073. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  50074. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  50075. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  50076. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  50077. boxFrameGeometry.colors.push(new Vector3(1, 1, 1));
  50078. }
  50079. let planeFrameGeometry = new Geometry();
  50080. {
  50081. // middle line
  50082. planeFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.0));
  50083. planeFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.0));
  50084. planeFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.0));
  50085. planeFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.0));
  50086. planeFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.0));
  50087. planeFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.0));
  50088. planeFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.0));
  50089. planeFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.0));
  50090. }
  50091. this.dimension = new Vector3(1, 1, 1);
  50092. this.material = new MeshBasicMaterial( {
  50093. color: 0x00ff00,
  50094. transparent: true,
  50095. opacity: 0.3,
  50096. depthTest: true,
  50097. depthWrite: false} );
  50098. this.box = new Mesh(boxGeometry, this.material);
  50099. this.box.geometry.computeBoundingBox();
  50100. this.boundingBox = this.box.geometry.boundingBox;
  50101. this.add(this.box);
  50102. this.frame = new LineSegments( boxFrameGeometry, new LineBasicMaterial({color: 0x000000}));
  50103. this.add(this.frame);
  50104. this.planeFrame = new LineSegments( planeFrameGeometry, new LineBasicMaterial({color: 0xff0000}));
  50105. this.add(this.planeFrame);
  50106. // set default thickness
  50107. this.setScaleZ(0.1);
  50108. // create local coordinate system
  50109. let createArrow = (name, direction, color) => {
  50110. let material = new MeshBasicMaterial({
  50111. color: color,
  50112. depthTest: false,
  50113. depthWrite: false});
  50114. let shaftGeometry = new Geometry();
  50115. shaftGeometry.vertices.push(new Vector3(0, 0, 0));
  50116. shaftGeometry.vertices.push(new Vector3(0, 1, 0));
  50117. let shaftMaterial = new LineBasicMaterial({
  50118. color: color,
  50119. depthTest: false,
  50120. depthWrite: false,
  50121. transparent: true
  50122. });
  50123. let shaft = new Line(shaftGeometry, shaftMaterial);
  50124. shaft.name = name + "_shaft";
  50125. let headGeometry = new CylinderGeometry(0, 0.04, 0.1, 10, 1, false);
  50126. let headMaterial = material;
  50127. let head = new Mesh(headGeometry, headMaterial);
  50128. head.name = name + "_head";
  50129. head.position.y = 1;
  50130. let arrow = new Object3D();
  50131. arrow.name = name;
  50132. arrow.add(shaft);
  50133. arrow.add(head);
  50134. return arrow;
  50135. };
  50136. this.arrowX = createArrow("arrow_x", new Vector3(1, 0, 0), 0xFF0000);
  50137. this.arrowY = createArrow("arrow_y", new Vector3(0, 1, 0), 0x00FF00);
  50138. this.arrowZ = createArrow("arrow_z", new Vector3(0, 0, 1), 0x0000FF);
  50139. this.arrowX.rotation.z = -Math.PI / 2;
  50140. this.arrowZ.rotation.x = Math.PI / 2;
  50141. this.arrowX.visible = false;
  50142. this.arrowY.visible = false;
  50143. this.arrowZ.visible = false;
  50144. this.add(this.arrowX);
  50145. this.add(this.arrowY);
  50146. this.add(this.arrowZ);
  50147. { // event listeners
  50148. this.addEventListener("ui_select", e => {
  50149. this.arrowX.visible = true;
  50150. this.arrowY.visible = true;
  50151. this.arrowZ.visible = true;
  50152. });
  50153. this.addEventListener("ui_deselect", e => {
  50154. this.arrowX.visible = false;
  50155. this.arrowY.visible = false;
  50156. this.arrowZ.visible = false;
  50157. });
  50158. this.addEventListener("select", e => {
  50159. let scene_header = $("#" + this.name + " .scene_header");
  50160. if(!scene_header.next().is(":visible")) {
  50161. scene_header.click();
  50162. }
  50163. });
  50164. this.addEventListener("deselect", e => {
  50165. let scene_header = $("#" + this.name + " .scene_header");
  50166. if(scene_header.next().is(":visible")) {
  50167. scene_header.click();
  50168. }
  50169. });
  50170. }
  50171. this.update();
  50172. };
  50173. setClipOffset(offset) {
  50174. this.clipOffset = offset;
  50175. }
  50176. setClipRotOffset(offset) {
  50177. this.clipRotOffset = offset;
  50178. }
  50179. setScaleX(x) {
  50180. this.box.scale.x = x;
  50181. this.frame.scale.x = x;
  50182. this.planeFrame.scale.x = x;
  50183. }
  50184. setScaleY(y) {
  50185. this.box.scale.y = y;
  50186. this.frame.scale.y = y;
  50187. this.planeFrame.scale.y = y;
  50188. }
  50189. setScaleZ(z) {
  50190. this.box.scale.z = z;
  50191. this.frame.scale.z = z;
  50192. this.planeFrame.scale.z = z;
  50193. }
  50194. offset(args) {
  50195. let cs = args.cs || null;
  50196. let axis = args.axis || null;
  50197. let dir = args.dir || null;
  50198. if(!cs || !axis || !dir) return;
  50199. if(axis === "x") {
  50200. if(cs === "local") {
  50201. this.position.add(this.localX.clone().multiplyScalar(dir * this.clipOffset));
  50202. } else if(cs === "global") {
  50203. this.position.x = this.position.x + dir * this.clipOffset;
  50204. }
  50205. }else if(axis === "y") {
  50206. if(cs === "local") {
  50207. this.position.add(this.localY.clone().multiplyScalar(dir * this.clipOffset));
  50208. } else if(cs === "global") {
  50209. this.position.y = this.position.y + dir * this.clipOffset;
  50210. }
  50211. }else if(axis === "z") {
  50212. if(cs === "local") {
  50213. this.position.add(this.localZ.clone().multiplyScalar(dir * this.clipOffset));
  50214. } else if(cs === "global") {
  50215. this.position.z = this.position.z + dir * this.clipOffset;
  50216. }
  50217. }
  50218. this.dispatchEvent({"type": "clip_volume_changed", "viewer": viewer, "volume": this});
  50219. }
  50220. rotate(args) {
  50221. let cs = args.cs || null;
  50222. let axis = args.axis || null;
  50223. let dir = args.dir || null;
  50224. if(!cs || !axis || !dir) return;
  50225. if(cs === "local") {
  50226. if(axis === "x") {
  50227. this.rotateOnAxis(new Vector3(1, 0, 0), dir * this.clipRotOffset * Math.PI / 180);
  50228. } else if(axis === "y") {
  50229. this.rotateOnAxis(new Vector3(0, 1, 0), dir * this.clipRotOffset * Math.PI / 180);
  50230. } else if(axis === "z") {
  50231. this.rotateOnAxis(new Vector3(0, 0, 1), dir * this.clipRotOffset * Math.PI / 180);
  50232. }
  50233. } else if(cs === "global") {
  50234. let rotaxis = new Vector4(1, 0, 0, 0);
  50235. if(axis === "y") {
  50236. rotaxis = new Vector4(0, 1, 0, 0);
  50237. } else if(axis === "z") {
  50238. rotaxis = new Vector4(0, 0, 1, 0);
  50239. }
  50240. this.updateMatrixWorld();
  50241. let invM = newthis.matrixWorld.clone().invert();
  50242. rotaxis = rotaxis.applyMatrix4(invM).normalize();
  50243. rotaxis = new Vector3(rotaxis.x, rotaxis.y, rotaxis.z);
  50244. this.rotateOnAxis(rotaxis, dir * this.clipRotOffset * Math.PI / 180);
  50245. }
  50246. this.updateLocalSystem();
  50247. this.dispatchEvent({"type": "clip_volume_changed", "viewer": viewer, "volume": this});
  50248. }
  50249. update(){
  50250. this.boundingBox = this.box.geometry.boundingBox;
  50251. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  50252. this.box.visible = false;
  50253. this.updateLocalSystem();
  50254. };
  50255. updateLocalSystem() {
  50256. // extract local coordinate axes
  50257. let rotQuat = this.getWorldQuaternion();
  50258. this.localX = new Vector3(1, 0, 0).applyQuaternion(rotQuat).normalize();
  50259. this.localY = new Vector3(0, 1, 0).applyQuaternion(rotQuat).normalize();
  50260. this.localZ = new Vector3(0, 0, 1).applyQuaternion(rotQuat).normalize();
  50261. }
  50262. raycast(raycaster, intersects){
  50263. let is = [];
  50264. this.box.raycast(raycaster, is);
  50265. if(is.length > 0){
  50266. let I = is[0];
  50267. intersects.push({
  50268. distance: I.distance,
  50269. object: this,
  50270. point: I.point.clone()
  50271. });
  50272. }
  50273. };
  50274. };
  50275. class ClippingTool extends EventDispatcher{
  50276. constructor(viewer){
  50277. super();
  50278. this.viewer = viewer;
  50279. this.maxPolygonVertices = 8;
  50280. this.addEventListener("start_inserting_clipping_volume", e => {
  50281. this.viewer.dispatchEvent({
  50282. type: "cancel_insertions"
  50283. });
  50284. });
  50285. this.sceneMarker = new Scene();
  50286. this.sceneVolume = new Scene();
  50287. this.sceneVolume.name = "scene_clip_volume";
  50288. this.viewer.inputHandler.registerInteractiveScene(this.sceneVolume);
  50289. this.onRemove = e => {
  50290. this.sceneVolume.remove(e.volume);
  50291. };
  50292. this.onAdd = e => {
  50293. this.sceneVolume.add(e.volume);
  50294. };
  50295. this.viewer.inputHandler.addEventListener("delete", e => {
  50296. let volumes = e.selection.filter(e => (e instanceof ClipVolume));
  50297. volumes.forEach(e => this.viewer.scene.removeClipVolume(e));
  50298. let polyVolumes = e.selection.filter(e => (e instanceof PolygonClipVolume));
  50299. polyVolumes.forEach(e => this.viewer.scene.removePolygonClipVolume(e));
  50300. });
  50301. //----
  50302. /* var a = new ClipVolume()
  50303. viewer.scene.addVolume(a);
  50304. viewer.setObjectLayers(a, 'volume' ) */
  50305. }
  50306. setScene(scene){
  50307. if(this.scene === scene){
  50308. return;
  50309. }
  50310. if(this.scene){
  50311. this.scene.removeEventListeners("clip_volume_added", this.onAdd);
  50312. this.scene.removeEventListeners("clip_volume_removed", this.onRemove);
  50313. this.scene.removeEventListeners("polygon_clip_volume_added", this.onAdd);
  50314. this.scene.removeEventListeners("polygon_clip_volume_removed", this.onRemove);
  50315. }
  50316. this.scene = scene;
  50317. this.scene.addEventListener("clip_volume_added", this.onAdd);
  50318. this.scene.addEventListener("clip_volume_removed", this.onRemove);
  50319. this.scene.addEventListener("polygon_clip_volume_added", this.onAdd);
  50320. this.scene.addEventListener("polygon_clip_volume_removed", this.onRemove);
  50321. }
  50322. startInsertion(args = {}) {
  50323. let type = args.type || null;
  50324. if(!type) return null;
  50325. let domElement = this.viewer.renderer.domElement;
  50326. let canvasSize = this.viewer.renderer.getSize(new Vector2$1());
  50327. let svg = $(`
  50328. <svg height="${canvasSize.height}" width="${canvasSize.width}" style="position:absolute; pointer-events: none">
  50329. <defs>
  50330. <marker id="diamond" markerWidth="24" markerHeight="24" refX="12" refY="12"
  50331. markerUnits="userSpaceOnUse">
  50332. <circle cx="12" cy="12" r="6" fill="white" stroke="black" stroke-width="3"/>
  50333. </marker>
  50334. </defs>
  50335. <polyline fill="none" stroke="black"
  50336. style="stroke:rgb(0, 0, 0);
  50337. stroke-width:6;"
  50338. stroke-dasharray="9, 6"
  50339. stroke-dashoffset="2"
  50340. />
  50341. <polyline fill="none" stroke="black"
  50342. style="stroke:rgb(255, 255, 255);
  50343. stroke-width:2;"
  50344. stroke-dasharray="5, 10"
  50345. marker-start="url(#diamond)"
  50346. marker-mid="url(#diamond)"
  50347. marker-end="url(#diamond)"
  50348. />
  50349. </svg>`);
  50350. $(domElement.parentElement).append(svg);
  50351. let polyClipVol = new PolygonClipVolume(this.viewer.scene.getActiveCamera().clone());
  50352. this.dispatchEvent({"type": "start_inserting_clipping_volume"});
  50353. this.viewer.scene.addPolygonClipVolume(polyClipVol);
  50354. this.sceneMarker.add(polyClipVol);
  50355. let cancel = {
  50356. callback: null
  50357. };
  50358. let insertionCallback = (e) => {
  50359. if(e.button === MOUSE.LEFT){
  50360. polyClipVol.addMarker();
  50361. // SVC Screen Line
  50362. svg.find("polyline").each((index, target) => {
  50363. let newPoint = svg[0].createSVGPoint();
  50364. newPoint.x = e.offsetX;
  50365. newPoint.y = e.offsetY;
  50366. let polyline = target.points.appendItem(newPoint);
  50367. });
  50368. if(polyClipVol.markers.length > this.maxPolygonVertices){
  50369. cancel.callback();
  50370. }
  50371. this.viewer.inputHandler.startDragging(
  50372. polyClipVol.markers[polyClipVol.markers.length - 1]);
  50373. }else if(e.button === MOUSE.RIGHT){
  50374. cancel.callback(e);
  50375. }
  50376. };
  50377. cancel.callback = e => {
  50378. //let first = svg.find("polyline")[0].points[0];
  50379. //svg.find("polyline").each((index, target) => {
  50380. // let newPoint = svg[0].createSVGPoint();
  50381. // newPoint.x = first.x;
  50382. // newPoint.y = first.y;
  50383. // let polyline = target.points.appendItem(newPoint);
  50384. //});
  50385. svg.remove();
  50386. if(polyClipVol.markers.length > 3) {
  50387. polyClipVol.removeLastMarker();
  50388. polyClipVol.initialized = true;
  50389. } else {
  50390. this.viewer.scene.removePolygonClipVolume(polyClipVol);
  50391. }
  50392. this.viewer.renderer.domElement.removeEventListener("mouseup", insertionCallback, true);
  50393. this.viewer.removeEventListener("cancel_insertions", cancel.callback);
  50394. this.viewer.inputHandler.enabled = true;
  50395. };
  50396. this.viewer.addEventListener("cancel_insertions", cancel.callback);
  50397. this.viewer.renderer.domElement.addEventListener("mouseup", insertionCallback , true);
  50398. this.viewer.inputHandler.enabled = false;
  50399. polyClipVol.addMarker();
  50400. this.viewer.inputHandler.startDragging(
  50401. polyClipVol.markers[polyClipVol.markers.length - 1]);
  50402. return polyClipVol;
  50403. }
  50404. update() {
  50405. }
  50406. };
  50407. var GeoTIFF = (function (exports) {
  50408. 'use strict';
  50409. const Endianness = new Enum({
  50410. LITTLE: "II",
  50411. BIG: "MM",
  50412. });
  50413. const Type = new Enum({
  50414. BYTE: {value: 1, bytes: 1},
  50415. ASCII: {value: 2, bytes: 1},
  50416. SHORT: {value: 3, bytes: 2},
  50417. LONG: {value: 4, bytes: 4},
  50418. RATIONAL: {value: 5, bytes: 8},
  50419. SBYTE: {value: 6, bytes: 1},
  50420. UNDEFINED: {value: 7, bytes: 1},
  50421. SSHORT: {value: 8, bytes: 2},
  50422. SLONG: {value: 9, bytes: 4},
  50423. SRATIONAL: {value: 10, bytes: 8},
  50424. FLOAT: {value: 11, bytes: 4},
  50425. DOUBLE: {value: 12, bytes: 8},
  50426. });
  50427. const Tag = new Enum({
  50428. IMAGE_WIDTH: 256,
  50429. IMAGE_HEIGHT: 257,
  50430. BITS_PER_SAMPLE: 258,
  50431. COMPRESSION: 259,
  50432. PHOTOMETRIC_INTERPRETATION: 262,
  50433. STRIP_OFFSETS: 273,
  50434. ORIENTATION: 274,
  50435. SAMPLES_PER_PIXEL: 277,
  50436. ROWS_PER_STRIP: 278,
  50437. STRIP_BYTE_COUNTS: 279,
  50438. X_RESOLUTION: 282,
  50439. Y_RESOLUTION: 283,
  50440. PLANAR_CONFIGURATION: 284,
  50441. RESOLUTION_UNIT: 296,
  50442. SOFTWARE: 305,
  50443. COLOR_MAP: 320,
  50444. SAMPLE_FORMAT: 339,
  50445. MODEL_PIXEL_SCALE: 33550, // [GeoTIFF] TYPE: double N: 3
  50446. MODEL_TIEPOINT: 33922, // [GeoTIFF] TYPE: double N: 6 * NUM_TIEPOINTS
  50447. GEO_KEY_DIRECTORY: 34735, // [GeoTIFF] TYPE: short N: >= 4
  50448. GEO_DOUBLE_PARAMS: 34736, // [GeoTIFF] TYPE: short N: variable
  50449. GEO_ASCII_PARAMS: 34737, // [GeoTIFF] TYPE: ascii N: variable
  50450. });
  50451. const typeMapping = new Map([
  50452. [Type.BYTE, Uint8Array],
  50453. [Type.ASCII, Uint8Array],
  50454. [Type.SHORT, Uint16Array],
  50455. [Type.LONG, Uint32Array],
  50456. [Type.RATIONAL, Uint32Array],
  50457. [Type.SBYTE, Int8Array],
  50458. [Type.UNDEFINED, Uint8Array],
  50459. [Type.SSHORT, Int16Array],
  50460. [Type.SLONG, Int32Array],
  50461. [Type.SRATIONAL, Int32Array],
  50462. [Type.FLOAT, Float32Array],
  50463. [Type.DOUBLE, Float64Array],
  50464. ]);
  50465. class IFDEntry{
  50466. constructor(tag, type, count, offset, value){
  50467. this.tag = tag;
  50468. this.type = type;
  50469. this.count = count;
  50470. this.offset = offset;
  50471. this.value = value;
  50472. }
  50473. }
  50474. class Image{
  50475. constructor(){
  50476. this.width = 0;
  50477. this.height = 0;
  50478. this.buffer = null;
  50479. this.metadata = [];
  50480. }
  50481. }
  50482. class Reader{
  50483. constructor(){
  50484. }
  50485. static read(data){
  50486. let endiannessTag = String.fromCharCode(...Array.from(data.slice(0, 2)));
  50487. let endianness = Endianness.fromValue(endiannessTag);
  50488. let tiffCheckTag = data.readUInt8(2);
  50489. if(tiffCheckTag !== 42){
  50490. throw new Error("not a valid tiff file");
  50491. }
  50492. let offsetToFirstIFD = data.readUInt32LE(4);
  50493. console.log("offsetToFirstIFD", offsetToFirstIFD);
  50494. let ifds = [];
  50495. let IFDsRead = false;
  50496. let currentIFDOffset = offsetToFirstIFD;
  50497. let i = 0;
  50498. while(IFDsRead || i < 100){
  50499. console.log("currentIFDOffset", currentIFDOffset);
  50500. let numEntries = data.readUInt16LE(currentIFDOffset);
  50501. let nextIFDOffset = data.readUInt32LE(currentIFDOffset + 2 + numEntries * 12);
  50502. console.log("next offset: ", currentIFDOffset + 2 + numEntries * 12);
  50503. let entryBuffer = data.slice(currentIFDOffset + 2, currentIFDOffset + 2 + 12 * numEntries);
  50504. for(let i = 0; i < numEntries; i++){
  50505. let tag = Tag.fromValue(entryBuffer.readUInt16LE(i * 12));
  50506. let type = Type.fromValue(entryBuffer.readUInt16LE(i * 12 + 2));
  50507. let count = entryBuffer.readUInt32LE(i * 12 + 4);
  50508. let offsetOrValue = entryBuffer.readUInt32LE(i * 12 + 8);
  50509. let valueBytes = type.bytes * count;
  50510. let value;
  50511. if(valueBytes <= 4){
  50512. value = offsetOrValue;
  50513. }else {
  50514. let valueBuffer = new Uint8Array(valueBytes);
  50515. valueBuffer.set(data.slice(offsetOrValue, offsetOrValue + valueBytes));
  50516. let ArrayType = typeMapping.get(type);
  50517. value = new ArrayType(valueBuffer.buffer);
  50518. if(type === Type.ASCII){
  50519. value = String.fromCharCode(...value);
  50520. }
  50521. }
  50522. let ifd = new IFDEntry(tag, type, count, offsetOrValue, value);
  50523. ifds.push(ifd);
  50524. }
  50525. console.log("nextIFDOffset", nextIFDOffset);
  50526. if(nextIFDOffset === 0){
  50527. break;
  50528. }
  50529. currentIFDOffset = nextIFDOffset;
  50530. i++;
  50531. }
  50532. let ifdForTag = (tag) => {
  50533. for(let entry of ifds){
  50534. if(entry.tag === tag){
  50535. return entry;
  50536. }
  50537. }
  50538. return null;
  50539. };
  50540. let width = ifdForTag(Tag.IMAGE_WIDTH, ifds).value;
  50541. let height = ifdForTag(Tag.IMAGE_HEIGHT, ifds).value;
  50542. let compression = ifdForTag(Tag.COMPRESSION, ifds).value;
  50543. let rowsPerStrip = ifdForTag(Tag.ROWS_PER_STRIP, ifds).value;
  50544. let ifdStripOffsets = ifdForTag(Tag.STRIP_OFFSETS, ifds);
  50545. let ifdStripByteCounts = ifdForTag(Tag.STRIP_BYTE_COUNTS, ifds);
  50546. let numStrips = Math.ceil(height / rowsPerStrip);
  50547. let stripByteCounts = [];
  50548. for(let i = 0; i < ifdStripByteCounts.count; i++){
  50549. let type = ifdStripByteCounts.type;
  50550. let offset = ifdStripByteCounts.offset + i * type.bytes;
  50551. let value;
  50552. if(type === Type.SHORT){
  50553. value = data.readUInt16LE(offset);
  50554. }else if(type === Type.LONG){
  50555. value = data.readUInt32LE(offset);
  50556. }
  50557. stripByteCounts.push(value);
  50558. }
  50559. let stripOffsets = [];
  50560. for(let i = 0; i < ifdStripOffsets.count; i++){
  50561. let type = ifdStripOffsets.type;
  50562. let offset = ifdStripOffsets.offset + i * type.bytes;
  50563. let value;
  50564. if(type === Type.SHORT){
  50565. value = data.readUInt16LE(offset);
  50566. }else if(type === Type.LONG){
  50567. value = data.readUInt32LE(offset);
  50568. }
  50569. stripOffsets.push(value);
  50570. }
  50571. let imageBuffer = new Uint8Array(width * height * 3);
  50572. let linesProcessed = 0;
  50573. for(let i = 0; i < numStrips; i++){
  50574. let stripOffset = stripOffsets[i];
  50575. let stripBytes = stripByteCounts[i];
  50576. let stripData = data.slice(stripOffset, stripOffset + stripBytes);
  50577. let lineBytes = width * 3;
  50578. for(let y = 0; y < rowsPerStrip; y++){
  50579. let line = stripData.slice(y * lineBytes, y * lineBytes + lineBytes);
  50580. imageBuffer.set(line, linesProcessed * lineBytes);
  50581. if(line.length === lineBytes){
  50582. linesProcessed++;
  50583. }else {
  50584. break;
  50585. }
  50586. }
  50587. }
  50588. console.log(`width: ${width}`);
  50589. console.log(`height: ${height}`);
  50590. console.log(`numStrips: ${numStrips}`);
  50591. console.log("stripByteCounts", stripByteCounts.join(", "));
  50592. console.log("stripOffsets", stripOffsets.join(", "));
  50593. let image = new Image();
  50594. image.width = width;
  50595. image.height = height;
  50596. image.buffer = imageBuffer;
  50597. image.metadata = ifds;
  50598. return image;
  50599. }
  50600. }
  50601. class Exporter{
  50602. constructor(){
  50603. }
  50604. static toTiffBuffer(image, params = {}){
  50605. let offsetToFirstIFD = 8;
  50606. let headerBuffer = new Uint8Array([0x49, 0x49, 42, 0, offsetToFirstIFD, 0, 0, 0]);
  50607. let [width, height] = [image.width, image.height];
  50608. let ifds = [
  50609. new IFDEntry(Tag.IMAGE_WIDTH, Type.SHORT, 1, null, width),
  50610. new IFDEntry(Tag.IMAGE_HEIGHT, Type.SHORT, 1, null, height),
  50611. new IFDEntry(Tag.BITS_PER_SAMPLE, Type.SHORT, 4, null, new Uint16Array([8, 8, 8, 8])),
  50612. new IFDEntry(Tag.COMPRESSION, Type.SHORT, 1, null, 1),
  50613. new IFDEntry(Tag.PHOTOMETRIC_INTERPRETATION, Type.SHORT, 1, null, 2),
  50614. new IFDEntry(Tag.ORIENTATION, Type.SHORT, 1, null, 1),
  50615. new IFDEntry(Tag.SAMPLES_PER_PIXEL, Type.SHORT, 1, null, 4),
  50616. new IFDEntry(Tag.ROWS_PER_STRIP, Type.LONG, 1, null, height),
  50617. new IFDEntry(Tag.STRIP_BYTE_COUNTS, Type.LONG, 1, null, width * height * 3),
  50618. new IFDEntry(Tag.PLANAR_CONFIGURATION, Type.SHORT, 1, null, 1),
  50619. new IFDEntry(Tag.RESOLUTION_UNIT, Type.SHORT, 1, null, 1),
  50620. new IFDEntry(Tag.SOFTWARE, Type.ASCII, 6, null, "......"),
  50621. new IFDEntry(Tag.STRIP_OFFSETS, Type.LONG, 1, null, null),
  50622. new IFDEntry(Tag.X_RESOLUTION, Type.RATIONAL, 1, null, new Uint32Array([1, 1])),
  50623. new IFDEntry(Tag.Y_RESOLUTION, Type.RATIONAL, 1, null, new Uint32Array([1, 1])),
  50624. ];
  50625. if(params.ifdEntries){
  50626. ifds.push(...params.ifdEntries);
  50627. }
  50628. let valueOffset = offsetToFirstIFD + 2 + ifds.length * 12 + 4;
  50629. // create 12 byte buffer for each ifd and variable length buffers for ifd values
  50630. let ifdEntryBuffers = new Map();
  50631. let ifdValueBuffers = new Map();
  50632. for(let ifd of ifds){
  50633. let entryBuffer = new ArrayBuffer(12);
  50634. let entryView = new DataView(entryBuffer);
  50635. let valueBytes = ifd.type.bytes * ifd.count;
  50636. entryView.setUint16(0, ifd.tag.value, true);
  50637. entryView.setUint16(2, ifd.type.value, true);
  50638. entryView.setUint32(4, ifd.count, true);
  50639. if(ifd.count === 1 && ifd.type.bytes <= 4){
  50640. entryView.setUint32(8, ifd.value, true);
  50641. }else {
  50642. entryView.setUint32(8, valueOffset, true);
  50643. let valueBuffer = new Uint8Array(ifd.count * ifd.type.bytes);
  50644. if(ifd.type === Type.ASCII){
  50645. valueBuffer.set(new Uint8Array(ifd.value.split("").map(c => c.charCodeAt(0))));
  50646. }else {
  50647. valueBuffer.set(new Uint8Array(ifd.value.buffer));
  50648. }
  50649. ifdValueBuffers.set(ifd.tag, valueBuffer);
  50650. valueOffset = valueOffset + valueBuffer.byteLength;
  50651. }
  50652. ifdEntryBuffers.set(ifd.tag, entryBuffer);
  50653. }
  50654. let imageBufferOffset = valueOffset;
  50655. new DataView(ifdEntryBuffers.get(Tag.STRIP_OFFSETS)).setUint32(8, imageBufferOffset, true);
  50656. let concatBuffers = (buffers) => {
  50657. let totalLength = buffers.reduce( (sum, buffer) => (sum + buffer.byteLength), 0);
  50658. let merged = new Uint8Array(totalLength);
  50659. let offset = 0;
  50660. for(let buffer of buffers){
  50661. merged.set(new Uint8Array(buffer), offset);
  50662. offset += buffer.byteLength;
  50663. }
  50664. return merged;
  50665. };
  50666. let ifdBuffer = concatBuffers([
  50667. new Uint16Array([ifds.length]),
  50668. ...ifdEntryBuffers.values(),
  50669. new Uint32Array([0])]);
  50670. let ifdValueBuffer = concatBuffers([...ifdValueBuffers.values()]);
  50671. let tiffBuffer = concatBuffers([
  50672. headerBuffer,
  50673. ifdBuffer,
  50674. ifdValueBuffer,
  50675. image.buffer
  50676. ]);
  50677. return {width: width, height: height, buffer: tiffBuffer};
  50678. }
  50679. }
  50680. exports.Tag = Tag;
  50681. exports.Type = Type;
  50682. exports.IFDEntry = IFDEntry;
  50683. exports.Image = Image;
  50684. exports.Reader = Reader;
  50685. exports.Exporter = Exporter;
  50686. return exports;
  50687. }({}));
  50688. function updateAzimuth(viewer, measure){
  50689. if(!measure.showAzimuth)return
  50690. const azimuth = measure.azimuth;
  50691. const isOkay = measure.points.length === 2;
  50692. azimuth.node.visible = isOkay;
  50693. if(!azimuth.node.visible){
  50694. return;
  50695. }
  50696. const camera = viewer.scene.getActiveCamera();
  50697. const renderAreaSize = viewer.renderer.getSize(new Vector2$1());
  50698. const width = renderAreaSize.width;
  50699. const height = renderAreaSize.height;
  50700. const [p0, p1] = measure.points;
  50701. const r = p0.position.distanceTo(p1.position);
  50702. const northVec = Utils.getNorthVec(p0.position, r, viewer.getProjection());
  50703. const northPos = p0.position.clone().add(northVec);
  50704. azimuth.center.position.copy(p0.position);
  50705. azimuth.center.scale.set(2, 2, 2);
  50706. azimuth.center.visible = false;
  50707. // azimuth.target.visible = false;
  50708. { // north
  50709. azimuth.north.position.copy(northPos);
  50710. azimuth.north.scale.set(2, 2, 2);
  50711. let distance = azimuth.north.position.distanceTo(camera.position);
  50712. let pr = Utils.projectedRadius(1, camera, distance, width, height);
  50713. let scale = (5 / pr);
  50714. azimuth.north.scale.set(scale, scale, scale);
  50715. }
  50716. { // target
  50717. azimuth.target.position.copy(p1.position);
  50718. azimuth.target.position.z = azimuth.north.position.z;
  50719. let distance = azimuth.target.position.distanceTo(camera.position);
  50720. let pr = Utils.projectedRadius(1, camera, distance, width, height);
  50721. let scale = (5 / pr);
  50722. azimuth.target.scale.set(scale, scale, scale);
  50723. }
  50724. azimuth.circle.position.copy(p0.position);
  50725. azimuth.circle.scale.set(r, r, r);
  50726. azimuth.circle.material.resolution.set(width, height);
  50727. // to target
  50728. azimuth.centerToTarget.geometry.setPositions([
  50729. 0, 0, 0,
  50730. ...p1.position.clone().sub(p0.position).toArray(),
  50731. ]);
  50732. azimuth.centerToTarget.position.copy(p0.position);
  50733. azimuth.centerToTarget.geometry.verticesNeedUpdate = true;
  50734. azimuth.centerToTarget.geometry.computeBoundingSphere();
  50735. azimuth.centerToTarget.computeLineDistances();
  50736. azimuth.centerToTarget.material.resolution.set(width, height);
  50737. // to target ground
  50738. azimuth.centerToTargetground.geometry.setPositions([
  50739. 0, 0, 0,
  50740. p1.position.x - p0.position.x,
  50741. p1.position.y - p0.position.y,
  50742. 0,
  50743. ]);
  50744. azimuth.centerToTargetground.position.copy(p0.position);
  50745. azimuth.centerToTargetground.geometry.verticesNeedUpdate = true;
  50746. azimuth.centerToTargetground.geometry.computeBoundingSphere();
  50747. azimuth.centerToTargetground.computeLineDistances();
  50748. azimuth.centerToTargetground.material.resolution.set(width, height);
  50749. // to north
  50750. azimuth.centerToNorth.geometry.setPositions([
  50751. 0, 0, 0,
  50752. northPos.x - p0.position.x,
  50753. northPos.y - p0.position.y,
  50754. 0,
  50755. ]);
  50756. azimuth.centerToNorth.position.copy(p0.position);
  50757. azimuth.centerToNorth.geometry.verticesNeedUpdate = true;
  50758. azimuth.centerToNorth.geometry.computeBoundingSphere();
  50759. azimuth.centerToNorth.computeLineDistances();
  50760. azimuth.centerToNorth.material.resolution.set(width, height);
  50761. // label
  50762. const radians = Utils.computeAzimuth(p0.position, p1.position, viewer.getProjection());
  50763. let degrees = MathUtils.radToDeg(radians);
  50764. if(degrees < 0){
  50765. degrees = 360 + degrees;
  50766. }
  50767. const txtDegrees = `${degrees.toFixed(2)}°`;
  50768. const labelDir = northPos.clone().add(p1.position).multiplyScalar(0.5).sub(p0.position);
  50769. if(labelDir.length() > 0){
  50770. labelDir.z = 0;
  50771. labelDir.normalize();
  50772. const labelVec = labelDir.clone().multiplyScalar(r);
  50773. const labelPos = p0.position.clone().add(labelVec);
  50774. azimuth.label.position.copy(labelPos);
  50775. }
  50776. azimuth.label.setText(txtDegrees);
  50777. let distance = azimuth.label.position.distanceTo(camera.position);
  50778. let pr = Utils.projectedRadius(1, camera, distance, width, height);
  50779. let scale = (70 / pr);
  50780. azimuth.label.scale.set(scale, scale, scale);
  50781. }
  50782. class MeasuringTool extends EventDispatcher{
  50783. constructor (viewer) {
  50784. super();
  50785. this.viewer = viewer;
  50786. this.renderer = viewer.renderer;
  50787. this.viewer.addEventListener('start_inserting_measurement', e => {
  50788. this.viewer.dispatchEvent({
  50789. type: 'cancel_insertions'
  50790. });
  50791. });
  50792. this.showLabels = true;
  50793. this.scene = new Scene();
  50794. this.scene.name = 'scene_measurement';
  50795. //this.light = new THREE.PointLight(0xffffff, 1.0);
  50796. //this.scene.add(this.light);
  50797. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  50798. //this.scene = viewer.overlay//
  50799. this.onRemove = (e) => { e.measurement.dispose();/* this.scene.remove(e.measurement); */};
  50800. this.onAdd = e => {this.scene.add(e.measurement);};
  50801. for(let measurement of viewer.scene.measurements){
  50802. this.onAdd({measurement: measurement});
  50803. }
  50804. viewer.addEventListener('camera_changed',(e)=>{
  50805. if(e.viewport == viewer.mainViewport ) this.update();
  50806. });
  50807. //viewer.addEventListener("update", this.update.bind(this));
  50808. viewer.addEventListener("render.pass.perspective_overlay", this.render.bind(this));
  50809. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  50810. viewer.scene.addEventListener('measurement_added', this.onAdd);
  50811. viewer.scene.addEventListener('measurement_removed', this.onRemove);
  50812. viewer.addEventListener('resize',this.setSize.bind(this));
  50813. }
  50814. onSceneChange(e){
  50815. if(e.oldScene){
  50816. e.oldScene.removeEventListener('measurement_added', this.onAdd);
  50817. e.oldScene.removeEventListener('measurement_removed', this.onRemove);
  50818. }
  50819. e.scene.addEventListener('measurement_added', this.onAdd);
  50820. e.scene.addEventListener('measurement_removed', this.onRemove);
  50821. }
  50822. createMeasureFromData(data){//add
  50823. const measure = new Measure(data);
  50824. if(measure.failBuilded){
  50825. return
  50826. }
  50827. viewer.scene.addMeasurement(measure);
  50828. if(measure.guideLine)measure.guideLine.visible = false;
  50829. return measure
  50830. }
  50831. update(){
  50832. return;
  50833. let camera = this.viewer.scene.getActiveCamera();
  50834. let domElement = this.renderer.domElement;
  50835. let measurements = this.viewer.scene.measurements;
  50836. // make size independant of distance
  50837. let mainLabels = [], subLabels = [];
  50838. for (let measure of measurements) {
  50839. measure.lengthUnit = this.viewer.lengthUnit;
  50840. measure.lengthUnitDisplay = this.viewer.lengthUnitDisplay;
  50841. //measure.update();
  50842. updateAzimuth(this.viewer, measure);
  50843. /* [...measure.markers, ...measure.edgeLabels, measure.areaLabel].forEach(e=>{
  50844. e && e.update()
  50845. }); */
  50846. // labels
  50847. /* let labels = measure.edgeLabels.concat(measure.angleLabels);
  50848. for(let label of labels){
  50849. label.update()
  50850. if(label.elem.hasClass('sub')){
  50851. subLabels.push(label)
  50852. }else{
  50853. mainLabels.push(label)
  50854. }
  50855. }
  50856. // coordinate labels
  50857. for (let j = 0; j < measure.coordinateLabels.length; j++) {
  50858. let label = measure.coordinateLabels[j];
  50859. label.update()
  50860. mainLabels.push(label)
  50861. }
  50862. if(measure.showArea){ // area label
  50863. let label = measure.areaLabel;
  50864. label.update()
  50865. mainLabels.push(label)
  50866. } */
  50867. /* if(measure.showCircle){ // radius label
  50868. let label = measure.circleRadiusLabel;
  50869. let distance = label.position.distanceTo(camera.position);
  50870. let pr = Utils.projectedRadius(1, camera, distance, clientWidth, clientHeight);
  50871. let scale = (70 / pr);
  50872. label.scale.set(scale, scale, scale);
  50873. } */
  50874. if(!this.showLabels){
  50875. const labels = [
  50876. ...measure.sphereLabels,
  50877. ...measure.angleLabels,
  50878. measure.circleRadiusLabel,
  50879. ];
  50880. for(const label of labels){
  50881. label.visible = false;
  50882. }
  50883. }
  50884. }
  50885. //this.updateLabelZIndex([{labels:subLabels},{labels:mainLabels}])
  50886. }
  50887. setSize(e){ //e.resolution
  50888. /* if(Measure.lineMats){
  50889. for(var m in Measure.lineMats){
  50890. Measure.lineMats[m].resolution.set(e.canvasWidth, e.canvasHeight);
  50891. }
  50892. }
  50893. if(Measure.sphereMats){
  50894. for(var s in Measure.sphereMats){
  50895. Measure.sphereMats[s].uniforms.resolution.value.set(e.canvasWidth, e.canvasHeight);
  50896. }
  50897. }
  50898. for (let measure of this.viewer.scene.measurements) {
  50899. measure.edgeLabels.concat(measure.areaLabel).forEach(label=>{
  50900. label.sprite.material.uniforms.resolution.value.set(e.canvasWidth, e.canvasHeight);
  50901. })
  50902. } */
  50903. }
  50904. updateLabelZIndex(group){//[{labels:[]},{}] 顺序按照z-index低到高
  50905. group.forEach((e,i)=>{
  50906. e.base = group[i-1] ? group[i-1].base + group[i-1].labels.length : 0;
  50907. var labels = e.labels.sort((a,b)=>{
  50908. return b.pos2d.z - a.pos2d.z
  50909. });
  50910. labels.forEach((label,index)=>{
  50911. $(label.elem).css('z-index', e.base+index);
  50912. });
  50913. });
  50914. }
  50915. editStateChange(e){
  50916. //console.log("editStateChange" , e.state)
  50917. let state = e.state;
  50918. if(!state){
  50919. state = viewer.scene.measurements.some(e=>e.isEditing);
  50920. }
  50921. if(state){
  50922. viewer.dispatchEvent({type:"measureMovePoint"});
  50923. }else {
  50924. viewer.dispatchEvent({type:"endMeasureMove"});
  50925. }
  50926. //this.editing =
  50927. }
  50928. startInsertion (args = {}, callback, cancelFun) {
  50929. let domElement = this.viewer.renderer.domElement;
  50930. const pick = (defaul, alternative) => {
  50931. if(defaul != null){
  50932. return defaul;
  50933. }else {
  50934. return alternative;
  50935. }
  50936. };
  50937. args.showDistances = (args.showDistances === null) ? true : args.showDistances;
  50938. args.showArea = pick(args.showArea, false);
  50939. args.showAngles = pick(args.showAngles, false);
  50940. args.showCoordinates = pick(args.showCoordinates, false);
  50941. args.showHeight = pick(args.showHeight, false);
  50942. args.showCircle = pick(args.showCircle, false);
  50943. args.showAzimuth = pick(args.showAzimuth, false);
  50944. args.showEdges = pick(args.showEdges, true);
  50945. args.closed = pick(args.closed, false);
  50946. args.maxMarkers = pick(args.maxMarkers, Infinity);
  50947. args.direction = args.direction;//add
  50948. args.type = args.type; /* || 'Measurement'; */
  50949. args.showGuideLine = pick(args.showGuideLine, false);
  50950. args.isRect = pick(args.isRect, false);
  50951. let measure = new Measure(args);
  50952. this.scene.add(measure);
  50953. measure.isNew = true;
  50954. this.viewer.dispatchEvent({
  50955. type: 'start_inserting_measurement',
  50956. measure: measure
  50957. });
  50958. measure.addEventListener('editStateChange', this.editStateChange.bind(this));
  50959. measure.editStateChange(true);
  50960. let timer;
  50961. let endDragFun = (e) => {
  50962. let length = measure.points.length;
  50963. if (e.button == MOUSE.LEFT || e.isTouch) {
  50964. if (length >= measure.maxMarkers) {
  50965. end({finish:true});
  50966. }else {
  50967. var marker = measure.addMarker({point:measure.points[length - 1].clone()});
  50968. if(args.isRect && measure.markers.length == 3){//marker全可见
  50969. measure.addMarker({point:measure.points[0].clone()});
  50970. }else {
  50971. measure.markers[length].visible = false;
  50972. measure.edges[length].visible = false;
  50973. }
  50974. measure.edges[length-1].visible = true;
  50975. measure.markers[length-1].visible = true;
  50976. measure.editStateChange(true); //重新激活reticule状态
  50977. marker.isDragging = true;
  50978. measure.continueDrag(marker, e);
  50979. }
  50980. } else if (e.button === MOUSE.RIGHT ) { //触屏怎么取消?
  50981. if(e.pressDistance < Potree.config.clickMaxDragDis )end(e);//非拖拽的话
  50982. else measure.continueDrag(null, e);
  50983. }
  50984. };
  50985. let end = (e={}) => {//确定、结束
  50986. if(!measure.isNew)return
  50987. if(args.minMarkers != void 0){
  50988. if(!e.finish && measure.markers.length<=args.minMarkers){//右键 当个数不够时取消
  50989. //this.viewer.scene.removeMeasurement(measure)
  50990. //cancelFun && cancelFun()
  50991. //重新开始画
  50992. measure.markers[0].removeEventListener('mousedown',end);
  50993. measure.reDraw();
  50994. this.viewer.addEventListener('global_click', click, 10);
  50995. measure.editStateChange(true);
  50996. return
  50997. /* if(!Potree.settings.isOfficial) this.viewer.scene.removeMeasurement(measure)
  50998. else if(e.drag){ //正式版本不允许右键退出, 继续
  50999. continueDrag(e.drag.object)
  51000. measure.editStateChange(true)
  51001. return
  51002. } */
  51003. }
  51004. }
  51005. if (/* !e.finish && */measure.markers.length > 3) {
  51006. measure.removeMarker(measure.points.length - 1);
  51007. measure.markers[0].removeEventListener('mouseover', mouseover);
  51008. measure.markers[0].removeEventListener('mouseleave', mouseleave);
  51009. measure.markers[0].removeEventListener('click'/* 'mousedown' */,Exit);
  51010. if(e.byClickMarker && measure.markers.length > 3){//通过点击第一个marker而结束的话,会多一个marker
  51011. measure.removeMarker(measure.points.length - 1);
  51012. }
  51013. }
  51014. measure.isNew = false;
  51015. let length = measure.points.length;
  51016. if(length){
  51017. measure.markers[length-1].visible = true;
  51018. measure.edges[length-1].visible = true;
  51019. measure.markers.forEach(marker=>{marker.dispatchEvent('addHoverEvent'); });
  51020. measure.edges.forEach(edge=>{edge.dispatchEvent('addHoverEvent'); });
  51021. }
  51022. clearTimeout(timer);
  51023. this.viewer.removeEventListener('cancel_insertions', Exit);
  51024. //pressExit && this.viewer.inputHandler.removeEventListener('keydown', pressExit);
  51025. this.viewer.removeEventListener('global_click', click);
  51026. this.viewer.removeEventListener('global_mousemove', ifAtWrongPlace);
  51027. viewer.dispatchEvent({
  51028. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  51029. });
  51030. viewer.inputHandler.dispatchEvent({type:'isMeasuring', v:false, cause:'stopInsertion'} );
  51031. e.remove || callback && callback();
  51032. /* this.viewer.dispatchEvent({
  51033. type: 'finish_inserting_measurement',
  51034. measure: measure
  51035. }); */
  51036. };
  51037. let Exit = (e)=>{//强制退出
  51038. if(e.measure && e.measure != measure){
  51039. return;//若指定了退出的measure但和该measure不一致,就返回
  51040. }
  51041. console.log('Exit: ' + measure.id);
  51042. if(e.remove){
  51043. viewer.scene.removeMeasurement(measure);
  51044. }
  51045. measure.editStateChange(false);
  51046. measure.cannotConfirmNormal = false; //一些dropMarker中的句子
  51047. measure.guideLine &&(measure.guideLine.visible = false);
  51048. /*
  51049. if(this.viewer.inputHandler.drag && !e.remove ){//还未触发drop的话
  51050. this.viewer.inputHandler.drag.object.dispatchEvent({ //这句会导致又增一个marker
  51051. type: 'drop',
  51052. drag: this.viewer.inputHandler.drag,
  51053. viewer: this.viewer,
  51054. pressDistance:0,
  51055. button : THREE.MOUSE.RIGHT
  51056. });
  51057. } else {*///未结束时添加新的measure时会触发
  51058. end({finish:true, remove:e.remove, byClickMarker: e.type == 'click'});
  51059. //}
  51060. this.viewer.inputHandler.drag && (this.viewer.inputHandler.drag.object = null);
  51061. };
  51062. this.viewer.addEventListener('cancel_insertions', Exit);
  51063. /*let pressExit
  51064. if(!Potree.settings.isOfficial){
  51065. pressExit = (e)=>{
  51066. if(e.keyCode == 27){//Esc
  51067. //Exit()
  51068. //怎么模拟右键???//现由前端发出
  51069. }
  51070. }
  51071. this.viewer.inputHandler.addEventListener('keydown', pressExit)
  51072. } */
  51073. let mouseover = (e) => {
  51074. measure.setMarkerSelected(e.object, 'hover', 'single');
  51075. };
  51076. let mouseleave = (e) => {
  51077. measure.setMarkerSelected(e.object, 'unhover', 'single');
  51078. };
  51079. let click = (e)=>{//一旦点击就立刻增加两marker
  51080. if(ifAtWrongPlace(e))return
  51081. if(e.button === MOUSE.RIGHT)return
  51082. //console.log('measure clicked33', !!e.intersectPoint)
  51083. //var I = e.intersectPoint && (e.intersectPoint.orthoIntersect || e.intersectPoint.location)
  51084. var I = e.intersect && (e.intersect.orthoIntersect || e.intersect.location);
  51085. if(!I){
  51086. return measure.dispatchEvent('intersectNoPointcloud')
  51087. }
  51088. var atMap = e.drag.dragViewport.name == 'mapViewport';
  51089. //在地图上测量的首个点按楼层高度(暂时先只按mainViewport相机高度吧,但navvis是按楼层,画在楼层的地面上,可能因为平面图显示的是楼层近地面),
  51090. if(atMap){
  51091. I = I.clone().setZ(viewer.mainViewport.camera.position.z );
  51092. }
  51093. var marker = measure.addMarker({point:I});
  51094. marker.isDragging = true;
  51095. this.viewer.inputHandler.startDragging(marker , {endDragFun, notPressMouse:true} ); //notPressMouse代表不是通过按下鼠标来拖拽
  51096. e.drag = this.viewer.inputHandler.drag;
  51097. e.drag.endDragFun = endDragFun;
  51098. e.drag.notPressMouse = true;
  51099. //if(!measure.dragMarker(e) || !measure.dropMarker(e))return
  51100. measure.dragMarker(e);
  51101. measure.dropMarker(e);
  51102. if(measure.maxMarkers > 1 ){
  51103. measure.markers[1].visible = false;
  51104. measure.edges[1].visible = false;
  51105. }
  51106. if(measure.maxMarkers>2 && !measure.isRect){
  51107. measure.markers[0].addEventListener('mouseover', mouseover);
  51108. measure.markers[0].addEventListener('mouseleave', mouseleave);
  51109. measure.markers[0].addEventListener('click'/* 'mousedown' */,Exit); //点击到第一个marker就结束
  51110. }
  51111. this.viewer.removeEventListener('global_click', click);///* global_drop */
  51112. //console.log('measure clicked')
  51113. e.consume && e.consume();
  51114. return {stopContinue:true}//防止继续执行别的侦听,如flytopano
  51115. };
  51116. //点击第n下拥有n+1个marker, n>0
  51117. viewer.inputHandler.dispatchEvent({type: 'isMeasuring', v: true, cause:'startInsertion'});
  51118. this.viewer.addEventListener('global_click', click, 10);//add importance:10
  51119. let ifAtWrongPlace = (e)=>{
  51120. if(measure.unableDragAtMap && e.hoverViewport.name == 'mapViewport' ){
  51121. if(e.isTouch){
  51122. viewer.dispatchEvent({type:'reticule_forbit', v:true});
  51123. }else {
  51124. viewer.dispatchEvent({
  51125. type : "CursorChange", action : "add", name:"polygon_AtWrongPlace"
  51126. });
  51127. }
  51128. return true
  51129. }else {
  51130. if(e.isTouch){
  51131. viewer.dispatchEvent({type:'reticule_forbit',v:false});
  51132. }else {
  51133. viewer.dispatchEvent({
  51134. type : "CursorChange", action : "remove", name:"polygon_AtWrongPlace"
  51135. });
  51136. }
  51137. }
  51138. };
  51139. if(measure.unableDragAtMap){
  51140. this.viewer.addEventListener('global_mousemove', ifAtWrongPlace);
  51141. }
  51142. this.viewer.scene.addMeasurement(measure);
  51143. return measure;
  51144. }
  51145. render(o={}){
  51146. if(this.scene.children.length == 0)return
  51147. viewer.setCameraLayers(o.camera, ['measure']);
  51148. if(o.screenshot){ //抗锯齿
  51149. this.viewer.ssaaRenderPass.sampleLevel = 4;
  51150. this.viewer.composer.render(this.scene, o.camera );
  51151. /* viewer.scene.measurements.forEach(e=>{ //隐藏除了label以外的
  51152. e.children.forEach((c)=>{
  51153. if(!(c instanceof TextSprite)){
  51154. c.visible = false
  51155. }
  51156. })
  51157. }) */
  51158. }else {
  51159. this.viewer.renderer.render(this.scene, o.camera );
  51160. }
  51161. }
  51162. };
  51163. class Message{
  51164. constructor(content){
  51165. this.content = content;
  51166. let closeIcon = `${exports.resourcePath}/icons/close.svg`;
  51167. this.element = $(`
  51168. <div class="potree_message">
  51169. <span name="content_container" style="flex-grow: 1; padding: 5px"></span>
  51170. <img name="close" src="${closeIcon}" class="button-icon" style="width: 16px; height: 16px;">
  51171. </div>`);
  51172. this.elClose = this.element.find("img[name=close]");
  51173. this.elContainer = this.element.find("span[name=content_container]");
  51174. if(typeof content === "string"){
  51175. this.elContainer.append($(`<span>${content}</span>`));
  51176. }else {
  51177. this.elContainer.append(content);
  51178. }
  51179. }
  51180. setMessage(content){
  51181. this.elContainer.empty();
  51182. if(typeof content === "string"){
  51183. this.elContainer.append($(`<span>${content}</span>`));
  51184. }else {
  51185. this.elContainer.append(content);
  51186. }
  51187. }
  51188. }
  51189. class PointCloudSM{//shadow material ?
  51190. constructor(potreeRenderer){
  51191. this.potreeRenderer = potreeRenderer;
  51192. this.threeRenderer = this.potreeRenderer.threeRenderer;
  51193. this.target = new WebGLRenderTarget(2 * 1024, 2 * 1024, {
  51194. minFilter: LinearFilter,
  51195. magFilter: LinearFilter,
  51196. format: RGBAFormat,
  51197. type: FloatType,
  51198. });
  51199. this.target.depthTexture = new DepthTexture();
  51200. this.target.depthTexture.type = UnsignedIntType;
  51201. //this.threeRenderer.setClearColor(0x000000, 1);
  51202. this.threeRenderer.setClearColor(0xff0000, 1);
  51203. //HACK? removed while moving to three.js 109
  51204. //this.threeRenderer.clearTarget(this.target, true, true, true);
  51205. {
  51206. const oldTarget = this.threeRenderer.getRenderTarget();
  51207. this.threeRenderer.setRenderTarget(this.target);
  51208. //this.threeRenderer.clear(true, true, true); //救命,为什么iphoneX ios13.6执行这一句clear会崩溃?即使把target的大小改为1*1.
  51209. this.threeRenderer.setRenderTarget(oldTarget);
  51210. }
  51211. }
  51212. setLight(light){
  51213. this.light = light;
  51214. let fov = (180 * light.angle) / Math.PI;
  51215. let aspect = light.shadow.mapSize.width / light.shadow.mapSize.height;
  51216. let near = 0.1;
  51217. let far = light.distance === 0 ? 10000 : light.distance;
  51218. this.camera = new PerspectiveCamera(fov, aspect, near, far);
  51219. this.camera.up.set(0, 0, 1);
  51220. this.camera.position.copy(light.position);
  51221. let target = new Vector3().subVectors(light.position, light.getWorldDirection(new Vector3()));
  51222. this.camera.lookAt(target);
  51223. this.camera.updateProjectionMatrix();
  51224. this.camera.updateMatrix();
  51225. this.camera.updateMatrixWorld();
  51226. this.camera.matrixWorldInverse.copy(this.camera.matrixWorld).invert();
  51227. }
  51228. setSize(width, height){
  51229. if(this.target.width !== width || this.target.height !== height){
  51230. this.target.dispose();
  51231. }
  51232. this.target.setSize(width, height);
  51233. }
  51234. render(scene, camera){
  51235. this.threeRenderer.setClearColor(0x000000, 1);
  51236. const oldTarget = this.threeRenderer.getRenderTarget();
  51237. this.threeRenderer.setRenderTarget(this.target);
  51238. this.threeRenderer.clear(true, true, true);
  51239. this.potreeRenderer.render(scene, this.camera, this.target, {});
  51240. this.threeRenderer.setRenderTarget(oldTarget);
  51241. }
  51242. }
  51243. class ProfileTool extends EventDispatcher {
  51244. constructor (viewer) {
  51245. super();
  51246. this.viewer = viewer;
  51247. this.renderer = viewer.renderer;
  51248. this.addEventListener('start_inserting_profile', e => {
  51249. this.viewer.dispatchEvent({
  51250. type: 'cancel_insertions'
  51251. });
  51252. });
  51253. this.scene = new Scene();
  51254. this.scene.name = 'scene_profile';
  51255. this.light = new PointLight(0xffffff, 1.0);
  51256. this.scene.add(this.light);
  51257. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  51258. this.onRemove = e => this.scene.remove(e.profile);
  51259. this.onAdd = e => this.scene.add(e.profile);
  51260. for(let profile of viewer.scene.profiles){
  51261. this.onAdd({profile: profile});
  51262. }
  51263. viewer.addEventListener("update", this.update.bind(this));
  51264. viewer.addEventListener("render.pass.perspective_overlay", this.render.bind(this));
  51265. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  51266. viewer.scene.addEventListener('profile_added', this.onAdd);
  51267. viewer.scene.addEventListener('profile_removed', this.onRemove);
  51268. }
  51269. onSceneChange(e){
  51270. if(e.oldScene){
  51271. e.oldScene.removeEventListeners('profile_added', this.onAdd);
  51272. e.oldScene.removeEventListeners('profile_removed', this.onRemove);
  51273. }
  51274. e.scene.addEventListener('profile_added', this.onAdd);
  51275. e.scene.addEventListener('profile_removed', this.onRemove);
  51276. }
  51277. startInsertion (args = {}) {
  51278. let domElement = this.viewer.renderer.domElement;
  51279. let profile = new Profile();
  51280. profile.name = args.name || 'Profile';
  51281. this.dispatchEvent({
  51282. type: 'start_inserting_profile',
  51283. profile: profile
  51284. });
  51285. this.scene.add(profile);
  51286. let cancel = {
  51287. callback: null
  51288. };
  51289. let insertionCallback = (e) => {
  51290. if(e.button === MOUSE.LEFT){
  51291. if(profile.points.length <= 1){
  51292. let camera = this.viewer.scene.getActiveCamera();
  51293. let distance = camera.position.distanceTo(profile.points[0]);
  51294. let clientSize = this.viewer.renderer.getSize(new Vector2$1());
  51295. let pr = Utils.projectedRadius(1, camera, distance, clientSize.width, clientSize.height);
  51296. let width = (10 / pr);
  51297. profile.setWidth(width);
  51298. }
  51299. profile.addMarker(profile.points[profile.points.length - 1].clone());
  51300. this.viewer.inputHandler.startDragging(
  51301. profile.spheres[profile.spheres.length - 1]);
  51302. } else if (e.button === MOUSE.RIGHT) {
  51303. cancel.callback();
  51304. }
  51305. };
  51306. cancel.callback = e => {
  51307. profile.removeMarker(profile.points.length - 1);
  51308. domElement.removeEventListener('mouseup', insertionCallback, false);
  51309. this.viewer.removeEventListener('cancel_insertions', cancel.callback);
  51310. };
  51311. this.viewer.addEventListener('cancel_insertions', cancel.callback);
  51312. domElement.addEventListener('mouseup', insertionCallback, false);
  51313. profile.addMarker(new Vector3(0, 0, 0));
  51314. this.viewer.inputHandler.startDragging(
  51315. profile.spheres[profile.spheres.length - 1]);
  51316. this.viewer.scene.addProfile(profile);
  51317. return profile;
  51318. }
  51319. update(){
  51320. let camera = this.viewer.scene.getActiveCamera();
  51321. let profiles = this.viewer.scene.profiles;
  51322. let renderAreaSize = this.viewer.renderer.getSize(new Vector2$1());
  51323. let clientWidth = renderAreaSize.width;
  51324. let clientHeight = renderAreaSize.height;
  51325. this.light.position.copy(camera.position);
  51326. // make size independant of distance
  51327. for(let profile of profiles){
  51328. for(let sphere of profile.spheres){
  51329. let distance = camera.position.distanceTo(sphere.getWorldPosition(new Vector3()));
  51330. let pr = Utils.projectedRadius(1, camera, distance, clientWidth, clientHeight);
  51331. let scale = (15 / pr);
  51332. sphere.scale.set(scale, scale, scale);
  51333. }
  51334. }
  51335. }
  51336. render(){
  51337. this.viewer.renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  51338. }
  51339. }
  51340. class ScreenBoxSelectTool extends EventDispatcher{
  51341. constructor(viewer){
  51342. super();
  51343. this.viewer = viewer;
  51344. this.scene = new Scene();
  51345. viewer.addEventListener("update", this.update.bind(this));
  51346. viewer.addEventListener("render.pass.perspective_overlay", this.render.bind(this));
  51347. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  51348. }
  51349. onSceneChange(scene){
  51350. console.log("scene changed");
  51351. }
  51352. startInsertion(){
  51353. let domElement = this.viewer.renderer.domElement;
  51354. let volume = new BoxVolume();
  51355. volume.position.set(12345, 12345, 12345);
  51356. volume.showVolumeLabel = false;
  51357. volume.visible = false;
  51358. volume.update();
  51359. this.viewer.scene.addVolume(volume);
  51360. this.importance = 10;
  51361. let selectionBox = $(`<div style="position: absolute; border: 2px solid white; pointer-events: none; border-style:dashed"></div>`);
  51362. $(domElement.parentElement).append(selectionBox);
  51363. selectionBox.css("right", "10px");
  51364. selectionBox.css("bottom", "10px");
  51365. let drag = e =>{
  51366. volume.visible = true;
  51367. let mStart = e.drag.start;
  51368. let mEnd = e.drag.end;
  51369. let box2D = new Box2();
  51370. box2D.expandByPoint(mStart);
  51371. box2D.expandByPoint(mEnd);
  51372. selectionBox.css("left", `${box2D.min.x}px`);
  51373. selectionBox.css("top", `${box2D.min.y}px`);
  51374. selectionBox.css("width", `${box2D.max.x - box2D.min.x}px`);
  51375. selectionBox.css("height", `${box2D.max.y - box2D.min.y}px`);
  51376. let camera = e.viewer.scene.getActiveCamera();
  51377. let size = e.viewer.renderer.getSize(new Vector2$1());
  51378. let frustumSize = new Vector2$1(
  51379. camera.right - camera.left,
  51380. camera.top - camera.bottom);
  51381. let screenCentroid = new Vector2$1().addVectors(e.drag.end, e.drag.start).multiplyScalar(0.5);
  51382. let pointer = new Vector3(0, 0, 0.5);
  51383. Utils.convertScreenPositionToNDC(pointer, screenCentroid, size.width, size.height);
  51384. pointer.unproject(camera);
  51385. //let ray = Utils.mouseToRay( pointer, camera, size.width, size.height);
  51386. let diff = new Vector2$1().subVectors(e.drag.end, e.drag.start);
  51387. diff.divide(size).multiply(frustumSize);
  51388. volume.position.copy(pointer);
  51389. //volume.position.copy(ray.origin); //orthographicCamera不能用这种方式 而且也该是用end
  51390. volume.up.copy(camera.up);
  51391. volume.rotation.copy(camera.rotation);
  51392. volume.scale.set(diff.x, diff.y, 1000 * 100);
  51393. e.consume();
  51394. };
  51395. let drop = e => {
  51396. this.importance = 0;
  51397. $(selectionBox).remove();
  51398. this.viewer.inputHandler.deselectAll();
  51399. this.viewer.inputHandler.toggleSelection(volume);
  51400. let camera = e.viewer.scene.getActiveCamera();
  51401. let size = e.viewer.renderer.getSize(new Vector2$1());
  51402. let screenCentroid = new Vector2$1().addVectors(e.drag.end, e.drag.start).multiplyScalar(0.5);
  51403. let pointer = new Vector3(0, 0, 0.5);
  51404. Utils.convertScreenPositionToNDC(pointer, screenCentroid, size.width, size.height);
  51405. let ray = Utils.mouseToRay(pointer/* screenCentroid */, camera, size.width, size.height);
  51406. //let line = new THREE.Line3(ray.origin, new THREE.Vector3().addVectors(ray.origin, ray.direction));
  51407. this.removeEventListener("drag", drag);
  51408. this.removeEventListener("drop", drop);
  51409. let allPointsNear = [];
  51410. let allPointsFar = [];
  51411. // TODO support more than one point cloud
  51412. for(let pointcloud of this.viewer.scene.pointclouds){
  51413. if(!pointcloud.visible){
  51414. continue;
  51415. }
  51416. let volCam = camera.clone();
  51417. volCam.left = -volume.scale.x / 2;
  51418. volCam.right = +volume.scale.x / 2;
  51419. volCam.top = +volume.scale.y / 2;
  51420. volCam.bottom = -volume.scale.y / 2;
  51421. volCam.near = -volume.scale.z / 2;
  51422. volCam.far = +volume.scale.z / 2;
  51423. volCam.rotation.copy(volume.rotation);
  51424. volCam.position.copy(volume.position);
  51425. volCam.updateMatrix();
  51426. volCam.updateMatrixWorld();
  51427. volCam.updateProjectionMatrix();
  51428. volCam.matrixWorldInverse.copy(volCam.matrixWorld).invert();
  51429. let ray = new Ray(volCam.getWorldPosition(new Vector3()), volCam.getWorldDirection(new Vector3()));
  51430. let rayInverse = new Ray(
  51431. ray.origin.clone().add(ray.direction.clone().multiplyScalar(volume.scale.z)),
  51432. ray.direction.clone().multiplyScalar(-1));
  51433. let diff = new Vector2$1().subVectors(e.drag.end, e.drag.start);
  51434. let pickerSettings = {
  51435. width: 16, //renderTarget大小,数值越大识别精度越高 原本的8太低了
  51436. height: 16,
  51437. pickWindowSize: 16, //??????
  51438. all: true,
  51439. pickClipped: true,
  51440. pointSizeType: PointSizeType.FIXED,
  51441. pointSize: 1
  51442. };
  51443. let pointsNear = pointcloud.pick(viewer, null, volCam, ray, pickerSettings);
  51444. volCam.rotateX(Math.PI);
  51445. volCam.updateMatrix();
  51446. volCam.updateMatrixWorld();
  51447. volCam.updateProjectionMatrix();
  51448. volCam.matrixWorldInverse.copy(volCam.matrixWorld).invert();
  51449. let pointsFar = pointcloud.pick(viewer,null, volCam, rayInverse, pickerSettings);
  51450. pointsNear && allPointsNear.push(...pointsNear);
  51451. pointsFar && allPointsFar.push(...pointsFar);
  51452. }
  51453. /* if(allPointsNear.length > 0 && allPointsFar.length > 0){
  51454. let viewLine = new THREE.Line3(ray.origin, new THREE.Vector3().addVectors(ray.origin, ray.direction));
  51455. let closestOnLine = allPointsNear.map(p => viewLine.closestPointToPoint(p.position, false, new THREE.Vector3()));
  51456. let closest = closestOnLine.sort( (a, b) => ray.origin.distanceTo(a) - ray.origin.distanceTo(b))[0];
  51457. let farthestOnLine = allPointsFar.map(p => viewLine.closestPointToPoint(p.position, false, new THREE.Vector3()));
  51458. let farthest = farthestOnLine.sort( (a, b) => ray.origin.distanceTo(b) - ray.origin.distanceTo(a))[0];
  51459. let distance = closest.distanceTo(farthest);
  51460. let centroid = new THREE.Vector3().addVectors(closest, farthest).multiplyScalar(0.5);
  51461. volume.scale.z = distance * 1.1;
  51462. volume.position.copy(centroid);
  51463. } */
  51464. if(allPointsNear.length > 0 || allPointsFar.length > 0){
  51465. let viewLine = new Line3(ray.origin, new Vector3().addVectors(ray.origin, ray.direction));
  51466. let closestOnLine = allPointsNear.map(p => viewLine.closestPointToPoint(p.position, false, new Vector3()));
  51467. let closests = closestOnLine.sort( (a, b) => ray.origin.distanceTo(a) - ray.origin.distanceTo(b));//[0];
  51468. let farthestOnLine = allPointsFar.map(p => viewLine.closestPointToPoint(p.position, false, new Vector3()));
  51469. let farthests = farthestOnLine.sort( (a, b) => ray.origin.distanceTo(b) - ray.origin.distanceTo(a));//[0];
  51470. let closest, farthest;
  51471. if(closests.length == 0){
  51472. closest = farthests[farthests.length-1];
  51473. farthest = farthests[0];
  51474. }else if(farthests.length == 0){
  51475. closest = closests[closests.length-1];
  51476. farthest = closests[0];
  51477. }else {
  51478. closest = closests[0];
  51479. farthest = farthests[0];
  51480. }
  51481. let distance = closest.distanceTo(farthest);
  51482. let centroid = new Vector3().addVectors(closest, farthest).multiplyScalar(0.5);
  51483. volume.scale.z = distance * 1.1;
  51484. //volume.position.copy(centroid);
  51485. var pos2d = centroid.project(camera); //改变深度
  51486. pointer.setZ(pos2d.z);
  51487. pointer.unproject(camera);
  51488. volume.position.copy(pointer);
  51489. }
  51490. volume.clip = true;
  51491. };
  51492. this.addEventListener("drag", drag);
  51493. this.addEventListener("drop", drop);
  51494. viewer.inputHandler.addInputListener(this);
  51495. return volume;
  51496. }
  51497. update(e){
  51498. //console.log(e.delta)
  51499. }
  51500. render(){
  51501. this.viewer.renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  51502. }
  51503. }
  51504. class SpotLightHelper$1 extends Object3D{
  51505. constructor(light, color){
  51506. super();
  51507. this.light = light;
  51508. this.color = color;
  51509. //this.up.set(0, 0, 1);
  51510. this.updateMatrix();
  51511. this.updateMatrixWorld();
  51512. { // SPHERE
  51513. let sg = new SphereGeometry(1, 32, 32);
  51514. let sm = new MeshNormalMaterial();
  51515. this.sphere = new Mesh(sg, sm);
  51516. this.sphere.scale.set(0.5, 0.5, 0.5);
  51517. this.add(this.sphere);
  51518. }
  51519. { // LINES
  51520. let positions = new Float32Array([
  51521. +0, +0, +0, +0, +0, -1,
  51522. +0, +0, +0, -1, -1, -1,
  51523. +0, +0, +0, +1, -1, -1,
  51524. +0, +0, +0, +1, +1, -1,
  51525. +0, +0, +0, -1, +1, -1,
  51526. -1, -1, -1, +1, -1, -1,
  51527. +1, -1, -1, +1, +1, -1,
  51528. +1, +1, -1, -1, +1, -1,
  51529. -1, +1, -1, -1, -1, -1,
  51530. ]);
  51531. let geometry = new BufferGeometry();
  51532. geometry.setAttribute("position", new BufferAttribute(positions, 3));
  51533. let material = new LineBasicMaterial();
  51534. this.frustum = new LineSegments(geometry, material);
  51535. this.add(this.frustum);
  51536. }
  51537. this.update();
  51538. }
  51539. update(){
  51540. this.light.updateMatrix();
  51541. this.light.updateMatrixWorld();
  51542. let position = this.light.position;
  51543. let target = new Vector3().addVectors(
  51544. this.light.position, this.light.getWorldDirection(new Vector3()).multiplyScalar(-1));
  51545. let quat = new Quaternion().setFromRotationMatrix(
  51546. new Matrix4().lookAt( position, target, new Vector3( 0, 0, 1 ) )
  51547. );
  51548. this.setRotationFromQuaternion(quat);
  51549. this.position.copy(position);
  51550. let coneLength = (this.light.distance > 0) ? this.light.distance : 1000;
  51551. let coneWidth = coneLength * Math.tan( this.light.angle * 0.5 );
  51552. this.frustum.scale.set(coneWidth, coneWidth, coneLength);
  51553. }
  51554. }
  51555. //add-------------------------------------
  51556. const OpaWhenNotSelect = 0.6;
  51557. const ScaleRatio = 8;
  51558. const OutlineColor = 0x666666;
  51559. //----------------------------------------
  51560. const hideFocusHandles = true;//add
  51561. class TransformationTool {
  51562. constructor(viewer) {
  51563. this.viewer = viewer;
  51564. this.scene = new Scene();
  51565. this.modesEnabled = {scale:true,translation:true,rotation:true};//add
  51566. this.selection = [];
  51567. this.pivot = new Vector3();
  51568. this.dragging = false;
  51569. this.showPickVolumes = false;
  51570. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  51571. this.viewer.inputHandler.addEventListener('selection_changed', (e) => {
  51572. for(let selected of this.selection){
  51573. this.viewer.inputHandler.blacklist.delete(selected);
  51574. }
  51575. this.selection = e.selection;
  51576. for(let selected of this.selection){
  51577. this.viewer.inputHandler.blacklist.add(selected);
  51578. }
  51579. });
  51580. this.viewer.addEventListener('global_touchstart',(e)=>{ //add
  51581. this.update();
  51582. });
  51583. let red = Potree.config.axis.x.color;
  51584. let green = Potree.config.axis.y.color;
  51585. let blue = Potree.config.axis.z.color;
  51586. this.activeHandle = null;
  51587. this.scaleHandles = {
  51588. "scale.x+": {name: "scale.x+", node: new Object3D(), color: red, alignment: [+1, +0, +0]},
  51589. "scale.x-": {name: "scale.x-", node: new Object3D(), color: red, alignment: [-1, +0, +0]},
  51590. "scale.y+": {name: "scale.y+", node: new Object3D(), color: green, alignment: [+0, +1, +0]},
  51591. "scale.y-": {name: "scale.y-", node: new Object3D(), color: green, alignment: [+0, -1, +0]},
  51592. "scale.z+": {name: "scale.z+", node: new Object3D(), color: blue, alignment: [+0, +0, +1]},
  51593. "scale.z-": {name: "scale.z-", node: new Object3D(), color: blue, alignment: [+0, +0, -1]},
  51594. };
  51595. this.focusHandles = {
  51596. "focus.x+": {name: "focus.x+", node: new Object3D(), color: red, alignment: [+1, +0, +0]},
  51597. "focus.x-": {name: "focus.x-", node: new Object3D(), color: red, alignment: [-1, +0, +0]},
  51598. "focus.y+": {name: "focus.y+", node: new Object3D(), color: green, alignment: [+0, +1, +0]},
  51599. "focus.y-": {name: "focus.y-", node: new Object3D(), color: green, alignment: [+0, -1, +0]},
  51600. "focus.z+": {name: "focus.z+", node: new Object3D(), color: blue, alignment: [+0, +0, +1]},
  51601. "focus.z-": {name: "focus.z-", node: new Object3D(), color: blue, alignment: [+0, +0, -1]},
  51602. };
  51603. this.translationHandles = {
  51604. "translation.x": {name: "translation.x", node: new Object3D(), color: red, alignment: [1, 0, 0]},
  51605. "translation.y": {name: "translation.y", node: new Object3D(), color: green, alignment: [0, 1, 0]},
  51606. "translation.z": {name: "translation.z", node: new Object3D(), color: blue, alignment: [0, 0, 1]},
  51607. };
  51608. this.rotationHandles = {
  51609. "rotation.x": {name: "rotation.x", node: new Object3D(), color: red, alignment: [1, 0, 0]},
  51610. "rotation.y": {name: "rotation.y", node: new Object3D(), color: green, alignment: [0, 1, 0]},
  51611. "rotation.z": {name: "rotation.z", node: new Object3D(), color: blue, alignment: [0, 0, 1]},
  51612. };
  51613. this.handles = Object.assign({}, this.scaleHandles, hideFocusHandles?{}:this.focusHandles, this.translationHandles, this.rotationHandles);
  51614. this.pickVolumes = [];
  51615. this.initializeScaleHandles();
  51616. this.initializeFocusHandles();
  51617. this.initializeTranslationHandles();
  51618. this.initializeRotationHandles();
  51619. let boxFrameGeometry = new Geometry();
  51620. {
  51621. // bottom
  51622. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  51623. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  51624. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  51625. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  51626. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  51627. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  51628. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  51629. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  51630. // top
  51631. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  51632. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  51633. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  51634. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  51635. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  51636. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  51637. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  51638. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  51639. // sides
  51640. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  51641. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  51642. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  51643. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  51644. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  51645. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  51646. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  51647. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  51648. }
  51649. this.frame = new LineSegments(boxFrameGeometry, new LineBasicMaterial({color: 0xffff00}));
  51650. this.scene.add(this.frame);
  51651. viewer.setObjectLayers(this.scene, 'transformationTool' );
  51652. this.scene.traverse(e=>{
  51653. e.pickDontCheckDis = true; //pick时不需要识别是否在点云之上
  51654. });
  51655. }
  51656. setModeEnable(mode,enable){//xzw add
  51657. let handels = this[mode + 'Handles'];
  51658. if(!handels)return
  51659. for(let o in handels){
  51660. handels[o].node.visible = !!enable;
  51661. }
  51662. this.modesEnabled[mode] = !!enable;
  51663. }
  51664. initializeScaleHandles(){
  51665. let sgSphere = new SphereGeometry(1, 32, 32);
  51666. let sgLowPolySphere = new SphereGeometry(1, 16, 16);
  51667. for(let handleName of Object.keys(this.scaleHandles)){
  51668. let handle = this.scaleHandles[handleName];
  51669. let node = handle.node;
  51670. this.scene.add(node);
  51671. node.position.set(...handle.alignment).multiplyScalar(0.5);
  51672. let material = new MeshBasicMaterial({
  51673. color: handle.color,
  51674. opacity: OpaWhenNotSelect,
  51675. transparent: true
  51676. });
  51677. let outlineMaterial = new MeshBasicMaterial({
  51678. color: OutlineColor,
  51679. side: BackSide,
  51680. opacity: OpaWhenNotSelect,
  51681. transparent: true});
  51682. let pickMaterial = new MeshNormalMaterial({
  51683. opacity: 0.2,
  51684. transparent: true,
  51685. visible: this.showPickVolumes});
  51686. let sphere = new Mesh(sgSphere, material);
  51687. sphere.scale.set(2, 2, 2 );
  51688. sphere.name = `${handleName}.handle`;
  51689. node.add(sphere);
  51690. let outline = new Mesh(sgSphere, outlineMaterial);
  51691. outline.scale.set(1.1, 1.1, 1.1);
  51692. outline.name = `${handleName}.outline`;
  51693. sphere.add(outline);
  51694. let pickSphere = new Mesh(sgLowPolySphere, pickMaterial);
  51695. pickSphere.name = `${handleName}.pick_volume`;
  51696. pickSphere.scale.set(2, 2, 2);
  51697. sphere.add(pickSphere);
  51698. pickSphere.handle = handleName;
  51699. this.pickVolumes.push(pickSphere);
  51700. node.setOpacity = (target) => {
  51701. let opacity = {x: material.opacity};
  51702. let t = new TWEEN.Tween(opacity).to({x: target}, 100);
  51703. t.onUpdate(() => {
  51704. sphere.visible = opacity.x > 0;
  51705. pickSphere.visible = opacity.x > 0;
  51706. material.opacity = opacity.x;
  51707. outlineMaterial.opacity = opacity.x;
  51708. pickSphere.material.opacity = opacity.x * 0.5;
  51709. });
  51710. t.start();
  51711. };
  51712. pickSphere.addEventListener("drag", (e) => this.dragScaleHandle(e));
  51713. pickSphere.addEventListener("drop", (e) => this.dropScaleHandle(e));
  51714. pickSphere.addEventListener("mouseover", e => {
  51715. //node.setOpacity(1);
  51716. });
  51717. pickSphere.addEventListener("click", e => {
  51718. //e.consume();
  51719. });
  51720. pickSphere.addEventListener("mouseleave", e => {
  51721. //node.setOpacity(OpaWhenNotSelect);
  51722. });
  51723. }
  51724. }
  51725. initializeFocusHandles(){
  51726. if(hideFocusHandles)return//add
  51727. //let sgBox = new THREE.BoxGeometry(1, 1, 1);
  51728. let sgPlane = new PlaneGeometry(4, 4, 1, 1);
  51729. let sgLowPolySphere = new SphereGeometry(1, 16, 16);
  51730. let texture = new TextureLoader().load(`${exports.resourcePath}/icons/eye_2.png`);
  51731. for(let handleName of Object.keys(this.focusHandles)){
  51732. let handle = this.focusHandles[handleName];
  51733. let node = handle.node;
  51734. this.scene.add(node);
  51735. let align = handle.alignment;
  51736. //node.lookAt(new THREE.Vector3().addVectors(node.position, new THREE.Vector3(...align)));
  51737. node.lookAt(new Vector3(...align));
  51738. let off = 0.8;
  51739. if(align[0] === 1){
  51740. node.position.set(1, off, -off).multiplyScalar(0.5);
  51741. node.rotation.z = Math.PI / 2;
  51742. }else if(align[0] === -1){
  51743. node.position.set(-1, -off, -off).multiplyScalar(0.5);
  51744. node.rotation.z = Math.PI / 2;
  51745. }else if(align[1] === 1){
  51746. node.position.set(-off, 1, -off).multiplyScalar(0.5);
  51747. node.rotation.set(Math.PI / 2, Math.PI, 0.0);
  51748. }else if(align[1] === -1){
  51749. node.position.set(off, -1, -off).multiplyScalar(0.5);
  51750. node.rotation.set(Math.PI / 2, 0.0, 0.0);
  51751. }else if(align[2] === 1){
  51752. node.position.set(off, off, 1).multiplyScalar(0.5);
  51753. }else if(align[2] === -1){
  51754. node.position.set(-off, off, -1).multiplyScalar(0.5);
  51755. }
  51756. let material = new MeshBasicMaterial({
  51757. color: handle.color,
  51758. opacity: 0,
  51759. transparent: true,
  51760. map: texture
  51761. });
  51762. //let outlineMaterial = new THREE.MeshBasicMaterial({
  51763. // color: 0x000000,
  51764. // side: THREE.BackSide,
  51765. // opacity: 0,
  51766. // transparent: true});
  51767. let pickMaterial = new MeshNormalMaterial({
  51768. //opacity: 0,
  51769. transparent: true,
  51770. visible: this.showPickVolumes});
  51771. let box = new Mesh(sgPlane, material);
  51772. box.name = `${handleName}.handle`;
  51773. box.scale.set(1.5, 1.5, 1.5);
  51774. box.position.set(0, 0, 0);
  51775. box.visible = false;
  51776. node.add(box);
  51777. //handle.focusNode = box;
  51778. //let outline = new THREE.Mesh(sgPlane, outlineMaterial);
  51779. //outline.scale.set(1.4, 1.4, 1.4);
  51780. //outline.name = `${handleName}.outline`;
  51781. //box.add(outline);
  51782. let pickSphere = new Mesh(sgLowPolySphere, pickMaterial);
  51783. pickSphere.name = `${handleName}.pick_volume`;
  51784. pickSphere.scale.set(2, 2, 2);
  51785. box.add(pickSphere);
  51786. pickSphere.handle = handleName;
  51787. this.pickVolumes.push(pickSphere);
  51788. node.setOpacity = (target) => {
  51789. let opacity = {x: material.opacity};
  51790. let t = new TWEEN.Tween(opacity).to({x: target}, 100);
  51791. t.onUpdate(() => {
  51792. pickSphere.visible = opacity.x > 0;
  51793. box.visible = opacity.x > 0;
  51794. material.opacity = opacity.x;
  51795. //outlineMaterial.opacity = opacity.x;
  51796. pickSphere.material.opacity = opacity.x * 0.5;
  51797. });
  51798. t.start();
  51799. };
  51800. //pickSphere.addEventListener("drag", e => {});
  51801. pickSphere.addEventListener("mouseup", e => {
  51802. //e.consume();
  51803. });
  51804. pickSphere.addEventListener("mousedown", e => {
  51805. //e.consume();
  51806. });
  51807. pickSphere.addEventListener("click", e => {
  51808. //e.consume();
  51809. let selected = this.selection[0];
  51810. let maxScale = Math.max(...selected.scale.toArray());
  51811. let minScale = Math.min(...selected.scale.toArray());
  51812. let handleLength = Math.abs(selected.scale.dot(new Vector3(...handle.alignment)));
  51813. let alignment = new Vector3(...handle.alignment).multiplyScalar(2 * maxScale / handleLength);
  51814. alignment.applyMatrix4(selected.matrixWorld);
  51815. let newCamPos = alignment;
  51816. let newCamTarget = selected.getWorldPosition(new Vector3());
  51817. Utils.moveTo(this.viewer.scene, newCamPos, newCamTarget);
  51818. });
  51819. pickSphere.addEventListener("mouseover", e => {
  51820. //box.setOpacity(1);
  51821. });
  51822. pickSphere.addEventListener("mouseleave", e => {
  51823. //box.setOpacity(OpaWhenNotSelect);
  51824. });
  51825. }
  51826. }
  51827. initializeTranslationHandles(){
  51828. let boxGeometry = new BoxGeometry(1, 1, 1);
  51829. for(let handleName of Object.keys(this.translationHandles)){
  51830. let handle = this.handles[handleName];
  51831. let node = handle.node;
  51832. this.scene.add(node);
  51833. let material = new MeshBasicMaterial({
  51834. color: handle.color,
  51835. opacity: OpaWhenNotSelect,
  51836. transparent: true});
  51837. let outlineMaterial = new MeshBasicMaterial({
  51838. color: OutlineColor,
  51839. side: BackSide,
  51840. opacity: OpaWhenNotSelect,
  51841. transparent: true});
  51842. let pickMaterial = new MeshNormalMaterial({
  51843. opacity: 0.2,
  51844. transparent: true,
  51845. visible: this.showPickVolumes
  51846. });
  51847. let box = new Mesh(boxGeometry, material);
  51848. box.name = `${handleName}.handle`;
  51849. box.scale.set(1, 1, 72);
  51850. box.lookAt(new Vector3(...handle.alignment));
  51851. box.renderOrder = 10;
  51852. node.add(box);
  51853. handle.translateNode = box;
  51854. let outline = new Mesh(boxGeometry, outlineMaterial);
  51855. outline.name = `${handleName}.outline`;
  51856. outline.scale.set(1.3, 1.3, 1.01);
  51857. outline.renderOrder = 0;
  51858. box.add(outline);
  51859. let pickVolume = new Mesh(boxGeometry, pickMaterial);
  51860. pickVolume.name = `${handleName}.pick_volume`;
  51861. pickVolume.scale.set(4, 4, 1.1);
  51862. pickVolume.handle = handleName;
  51863. box.add(pickVolume);
  51864. this.pickVolumes.push(pickVolume);
  51865. node.setOpacity = (target) => {
  51866. let opacity = {x: material.opacity};
  51867. let t = new TWEEN.Tween(opacity).to({x: target}, 100);
  51868. t.onUpdate(() => {
  51869. box.visible = opacity.x > 0;
  51870. pickVolume.visible = opacity.x > 0;
  51871. material.opacity = opacity.x;
  51872. outlineMaterial.opacity = opacity.x;
  51873. pickMaterial.opacity = opacity.x * 0.5;
  51874. });
  51875. t.start();
  51876. };
  51877. pickVolume.addEventListener("drag", (e) => {this.dragTranslationHandle(e);});
  51878. pickVolume.addEventListener("drop", (e) => {this.dropTranslationHandle(e);});
  51879. }
  51880. }
  51881. initializeRotationHandles(){
  51882. let adjust = 1.5;
  51883. let torusGeometry = new TorusGeometry(1, adjust * 0.015, 8, 64, Math.PI / 2);
  51884. let outlineGeometry = new TorusGeometry(1, adjust * 0.018, 8, 64, Math.PI / 2);
  51885. let pickGeometry = new TorusGeometry(1, adjust * 0.04, 6, 4, Math.PI / 2);
  51886. for(let handleName of Object.keys(this.rotationHandles)){
  51887. let handle = this.handles[handleName];
  51888. let node = handle.node;
  51889. this.scene.add(node);
  51890. let material = new MeshBasicMaterial({
  51891. color: handle.color,
  51892. opacity: OpaWhenNotSelect,
  51893. transparent: true
  51894. });
  51895. let outlineMaterial = new MeshBasicMaterial({
  51896. color: OutlineColor,
  51897. side: BackSide,
  51898. opacity: OpaWhenNotSelect,
  51899. transparent: true
  51900. });
  51901. let pickMaterial = new MeshNormalMaterial({
  51902. opacity: 0.2,
  51903. transparent: true,
  51904. visible: this.showPickVolumes
  51905. });
  51906. let box = new Mesh(torusGeometry, material);
  51907. box.name = `${handleName}.handle`;
  51908. box.scale.set(30, 30, 30);
  51909. box.lookAt(new Vector3(...handle.alignment));
  51910. node.add(box);
  51911. handle.translateNode = box;
  51912. let outline = new Mesh(outlineGeometry, outlineMaterial);
  51913. outline.name = `${handleName}.outline`;
  51914. outline.scale.set(1, 1, 1);
  51915. outline.renderOrder = 0;
  51916. box.add(outline);
  51917. let pickVolume = new Mesh(pickGeometry, pickMaterial);
  51918. pickVolume.name = `${handleName}.pick_volume`;
  51919. pickVolume.scale.set(1, 1, 1);
  51920. pickVolume.handle = handleName;
  51921. box.add(pickVolume);
  51922. this.pickVolumes.push(pickVolume);
  51923. node.setOpacity = (target) => {
  51924. let opacity = {x: material.opacity};
  51925. let t = new TWEEN.Tween(opacity).to({x: target}, 100);
  51926. t.onUpdate(() => {
  51927. box.visible = opacity.x > 0;
  51928. pickVolume.visible = opacity.x > 0;
  51929. material.opacity = opacity.x;
  51930. outlineMaterial.opacity = opacity.x;
  51931. pickMaterial.opacity = opacity.x * 0.5;
  51932. });
  51933. t.start();
  51934. };
  51935. //pickVolume.addEventListener("mouseover", (e) => {
  51936. // //let a = this.viewer.scene.getActiveCamera().getWorldDirection(new THREE.Vector3()).dot(pickVolume.getWorldDirection(new THREE.Vector3()));
  51937. // console.log(pickVolume.getWorldDirection(new THREE.Vector3()));
  51938. //});
  51939. pickVolume.addEventListener("drag", (e) => {this.dragRotationHandle(e);});
  51940. pickVolume.addEventListener("drop", (e) => {this.dropRotationHandle(e);});
  51941. }
  51942. }
  51943. dragRotationHandle(e){
  51944. let drag = e.drag;
  51945. let handle = this.activeHandle;
  51946. let camera = this.viewer.scene.getActiveCamera();
  51947. if(!handle){
  51948. return
  51949. };
  51950. let localNormal = new Vector3(...handle.alignment);
  51951. let n = new Vector3();
  51952. n.copy(new Vector4(...localNormal.toArray(), 0).applyMatrix4(handle.node.matrixWorld));
  51953. n.normalize();
  51954. if (!drag.intersectionStart){
  51955. //this.viewer.scene.scene.remove(this.debug);
  51956. //this.debug = new THREE.Object3D();
  51957. //this.viewer.scene.scene.add(this.debug);
  51958. //Utils.debugSphere(this.debug, drag.location, 3, 0xaaaaaa);
  51959. //let debugEnd = drag.location.clone().add(n.clone().multiplyScalar(20));
  51960. //Utils.debugLine(this.debug, drag.location, debugEnd, 0xff0000);
  51961. drag.intersectionStart = drag.location;
  51962. drag.objectStart = drag.object.getWorldPosition(new Vector3());
  51963. drag.handle = handle;
  51964. let plane = new Plane().setFromNormalAndCoplanarPoint(n, drag.intersectionStart);
  51965. drag.dragPlane = plane;
  51966. drag.pivot = drag.intersectionStart;
  51967. }else {
  51968. handle = drag.handle;
  51969. }
  51970. this.dragging = true;
  51971. let pointer = this.viewer.inputHandler.pointer;
  51972. let domElement = this.viewer.renderer.domElement;
  51973. let ray = Utils.mouseToRay(pointer, camera, domElement.clientWidth, domElement.clientHeight);
  51974. let I = ray.intersectPlane(drag.dragPlane, new Vector3());
  51975. if (I) {
  51976. let center = this.scene.getWorldPosition(new Vector3());
  51977. let from = drag.pivot;
  51978. let to = I;
  51979. let v1 = from.clone().sub(center).normalize();
  51980. let v2 = to.clone().sub(center).normalize();
  51981. let angle = Math.acos(v1.dot(v2));
  51982. let sign = Math.sign(v1.cross(v2).dot(n));
  51983. angle = angle * sign;
  51984. if (Number.isNaN(angle)) {
  51985. return;
  51986. }
  51987. let normal = new Vector3(...handle.alignment);
  51988. for (let selection of this.selection) {
  51989. selection.rotateOnAxis(normal, angle);
  51990. selection.dispatchEvent({
  51991. type: "orientation_changed",
  51992. object: selection
  51993. });
  51994. }
  51995. drag.pivot = I;
  51996. }
  51997. }
  51998. dropRotationHandle(e){
  51999. this.dragging = false;
  52000. this.setActiveHandle(null);
  52001. }
  52002. dragTranslationHandle(e){
  52003. let drag = e.drag;
  52004. let handle = this.activeHandle;
  52005. let camera = this.viewer.scene.getActiveCamera();
  52006. if(!drag.intersectionStart && handle){
  52007. drag.intersectionStart = drag.location;
  52008. drag.objectStart = drag.object.getWorldPosition(new Vector3());
  52009. let start = drag.intersectionStart;
  52010. let dir = new Vector4(...handle.alignment, 0).applyMatrix4(this.scene.matrixWorld);
  52011. let end = new Vector3().addVectors(start, dir);
  52012. let line = new Line3(start.clone(), end.clone());
  52013. drag.line = line;
  52014. let camOnLine = line.closestPointToPoint(camera.position, false, new Vector3());
  52015. let normal = new Vector3().subVectors(camera.position, camOnLine);
  52016. let plane = new Plane().setFromNormalAndCoplanarPoint(normal, drag.intersectionStart);
  52017. drag.dragPlane = plane;
  52018. drag.pivot = drag.intersectionStart;
  52019. }else {
  52020. handle = drag.handle;
  52021. }
  52022. this.dragging = true;
  52023. {
  52024. let pointer = this.viewer.inputHandler.pointer;
  52025. let domElement = this.viewer.renderer.domElement;
  52026. let ray = Utils.mouseToRay(pointer, camera, domElement.clientWidth, domElement.clientHeight);
  52027. let I = ray.intersectPlane(drag.dragPlane, new Vector3());
  52028. if (I) {
  52029. let iOnLine = drag.line.closestPointToPoint(I, false, new Vector3());
  52030. let diff = new Vector3().subVectors(iOnLine, drag.pivot);
  52031. for (let selection of this.selection) {
  52032. selection.position.add(diff);
  52033. selection.dispatchEvent({
  52034. type: "position_changed",
  52035. object: selection
  52036. });
  52037. }
  52038. drag.pivot = drag.pivot.add(diff);
  52039. }
  52040. }
  52041. }
  52042. dropTranslationHandle(e){
  52043. this.dragging = false;
  52044. this.setActiveHandle(null);
  52045. }
  52046. dropScaleHandle(e){
  52047. this.dragging = false;
  52048. this.setActiveHandle(null);
  52049. }
  52050. dragScaleHandle(e){
  52051. let drag = e.drag;
  52052. let handle = this.activeHandle;
  52053. let camera = this.viewer.scene.getActiveCamera();
  52054. if(!drag.intersectionStart){
  52055. drag.intersectionStart = drag.location;
  52056. drag.objectStart = drag.object.getWorldPosition(new Vector3());
  52057. drag.handle = handle;
  52058. let start = drag.intersectionStart;
  52059. let dir = new Vector4(...handle.alignment, 0).applyMatrix4(this.scene.matrixWorld);
  52060. let end = new Vector3().addVectors(start, dir);
  52061. let line = new Line3(start.clone(), end.clone());
  52062. drag.line = line;
  52063. let camOnLine = line.closestPointToPoint(camera.position, false, new Vector3());
  52064. let normal = new Vector3().subVectors(camera.position, camOnLine);
  52065. let plane = new Plane().setFromNormalAndCoplanarPoint(normal, drag.intersectionStart);
  52066. drag.dragPlane = plane;
  52067. drag.pivot = drag.intersectionStart;
  52068. //Utils.debugSphere(viewer.scene.scene, drag.pivot, 0.05);
  52069. }else {
  52070. handle = drag.handle;
  52071. }
  52072. this.dragging = true;
  52073. {
  52074. let pointer = this.viewer.inputHandler.pointer;
  52075. let domElement = this.viewer.renderer.domElement;
  52076. let ray = Utils.mouseToRay(pointer, camera, domElement.clientWidth, domElement.clientHeight);
  52077. let I = ray.intersectPlane(drag.dragPlane, new Vector3());
  52078. if (I) {
  52079. let iOnLine = drag.line.closestPointToPoint(I, false, new Vector3());
  52080. let direction = handle.alignment.reduce( (a, v) => a + v, 0);
  52081. let toObjectSpace = this.selection[0].matrixWorld.clone().invert();
  52082. let iOnLineOS = iOnLine.clone().applyMatrix4(toObjectSpace);
  52083. let pivotOS = drag.pivot.clone().applyMatrix4(toObjectSpace);
  52084. let diffOS = new Vector3().subVectors(iOnLineOS, pivotOS);
  52085. let dragDirectionOS = diffOS.clone().normalize();
  52086. if(iOnLine.distanceTo(drag.pivot) === 0){
  52087. dragDirectionOS.set(0, 0, 0);
  52088. }
  52089. let dragDirection = dragDirectionOS.dot(new Vector3(...handle.alignment));
  52090. let diff = new Vector3().subVectors(iOnLine, drag.pivot);
  52091. let diffScale = new Vector3(...handle.alignment).multiplyScalar(diff.length() * direction * dragDirection);
  52092. let diffPosition = diff.clone().multiplyScalar(0.5);
  52093. for (let selection of this.selection) {
  52094. //xzw 改:否则不跟手
  52095. let diffScale_ = diffScale.clone().divide(selection.boundingBox.getSize(new Vector3));
  52096. selection.scale.add(diffScale_);
  52097. //selection.scale.add(diffScale);
  52098. selection.scale.x = Math.max(0.1, selection.scale.x);
  52099. selection.scale.y = Math.max(0.1, selection.scale.y);
  52100. selection.scale.z = Math.max(0.1, selection.scale.z);
  52101. selection.position.add(diffPosition);
  52102. selection.dispatchEvent({
  52103. type: "position_changed",
  52104. object: selection
  52105. });
  52106. selection.dispatchEvent({
  52107. type: "scale_changed",
  52108. object: selection
  52109. });
  52110. }
  52111. drag.pivot.copy(iOnLine);
  52112. //Utils.debugSphere(viewer.scene.scene, drag.pivot, 0.05);
  52113. }
  52114. }
  52115. }
  52116. setActiveHandle(handle){
  52117. if(this.dragging){
  52118. return;
  52119. }
  52120. if(this.activeHandle === handle){
  52121. return;
  52122. }
  52123. this.activeHandle = handle;
  52124. if(handle === null){
  52125. for(let handleName of Object.keys(this.handles)){
  52126. let handle = this.handles[handleName];
  52127. handle.node.setOpacity(0);
  52128. }
  52129. }
  52130. if(!hideFocusHandles){
  52131. for(let handleName of Object.keys(this.focusHandles)){
  52132. let handle = this.focusHandles[handleName];
  52133. if(this.activeHandle === handle){
  52134. handle.node.setOpacity(1.0);
  52135. }else {
  52136. handle.node.setOpacity(OpaWhenNotSelect);
  52137. }
  52138. }
  52139. }
  52140. for(let handleName of Object.keys(this.translationHandles)){
  52141. let handle = this.translationHandles[handleName];
  52142. if(this.activeHandle === handle){
  52143. handle.node.setOpacity(1.0);
  52144. }else {
  52145. handle.node.setOpacity(OpaWhenNotSelect);
  52146. }
  52147. }
  52148. for(let handleName of Object.keys(this.rotationHandles)){
  52149. let handle = this.rotationHandles[handleName];
  52150. //if(this.activeHandle === handle){
  52151. // handle.node.setOpacity(1.0);
  52152. //}else{
  52153. // handle.node.setOpacity(OpaWhenNotSelect)
  52154. //}
  52155. handle.node.setOpacity(OpaWhenNotSelect);
  52156. }
  52157. for(let handleName of Object.keys(this.scaleHandles)){
  52158. let handle = this.scaleHandles[handleName];
  52159. if(this.activeHandle === handle){
  52160. handle.node.setOpacity(1.0);
  52161. if(!hideFocusHandles){
  52162. let relatedFocusHandle = this.focusHandles[handle.name.replace("scale", "focus")];
  52163. let relatedFocusNode = relatedFocusHandle.node;
  52164. relatedFocusNode.setOpacity(OpaWhenNotSelect);
  52165. }
  52166. for(let translationHandleName of Object.keys(this.translationHandles)){
  52167. let translationHandle = this.translationHandles[translationHandleName];
  52168. translationHandle.node.setOpacity(OpaWhenNotSelect);
  52169. }
  52170. //let relatedTranslationHandle = this.translationHandles[
  52171. // handle.name.replace("scale", "translation").replace(/[+-]/g, "")];
  52172. //let relatedTranslationNode = relatedTranslationHandle.node;
  52173. //relatedTranslationNode.setOpacity(OpaWhenNotSelect);
  52174. }else {
  52175. handle.node.setOpacity(OpaWhenNotSelect);
  52176. }
  52177. }
  52178. if(handle){
  52179. handle.node.setOpacity(1.0);
  52180. }
  52181. }
  52182. update () {
  52183. if(this.selection.length === 1){
  52184. this.scene.visible = true;
  52185. this.scene.updateMatrix();
  52186. this.scene.updateMatrixWorld();
  52187. let selected = this.selection[0];
  52188. let world = selected.matrixWorld;
  52189. let camera = this.viewer.scene.getActiveCamera();
  52190. let domElement = this.viewer.renderer.domElement;
  52191. let pointer = this.viewer.inputHandler.pointer;
  52192. let center = selected.boundingBox.getCenter(new Vector3()).clone().applyMatrix4(selected.matrixWorld);
  52193. this.scene.scale.copy(selected.boundingBox.getSize(new Vector3()).multiply(selected.scale));
  52194. this.scene.position.copy(center);
  52195. this.scene.rotation.copy(selected.rotation);
  52196. this.scene.updateMatrixWorld();
  52197. {
  52198. // adjust rotation handles
  52199. if(!this.dragging){
  52200. let tWorld = this.scene.matrixWorld;
  52201. let tObject = tWorld.clone().invert();
  52202. let camObjectPos = camera.getWorldPosition(new Vector3()).applyMatrix4(tObject);
  52203. let x = this.rotationHandles["rotation.x"].node.rotation;
  52204. let y = this.rotationHandles["rotation.y"].node.rotation;
  52205. let z = this.rotationHandles["rotation.z"].node.rotation;
  52206. x.order = "ZYX";
  52207. y.order = "ZYX";
  52208. let above = camObjectPos.z > 0;
  52209. let below = !above;
  52210. let PI_HALF = Math.PI / 2;
  52211. if(above){
  52212. if(camObjectPos.x > 0 && camObjectPos.y > 0){
  52213. x.x = 1 * PI_HALF;
  52214. y.y = 3 * PI_HALF;
  52215. z.z = 0 * PI_HALF;
  52216. }else if(camObjectPos.x < 0 && camObjectPos.y > 0){
  52217. x.x = 1 * PI_HALF;
  52218. y.y = 2 * PI_HALF;
  52219. z.z = 1 * PI_HALF;
  52220. }else if(camObjectPos.x < 0 && camObjectPos.y < 0){
  52221. x.x = 2 * PI_HALF;
  52222. y.y = 2 * PI_HALF;
  52223. z.z = 2 * PI_HALF;
  52224. }else if(camObjectPos.x > 0 && camObjectPos.y < 0){
  52225. x.x = 2 * PI_HALF;
  52226. y.y = 3 * PI_HALF;
  52227. z.z = 3 * PI_HALF;
  52228. }
  52229. }else if(below){
  52230. if(camObjectPos.x > 0 && camObjectPos.y > 0){
  52231. x.x = 0 * PI_HALF;
  52232. y.y = 0 * PI_HALF;
  52233. z.z = 0 * PI_HALF;
  52234. }else if(camObjectPos.x < 0 && camObjectPos.y > 0){
  52235. x.x = 0 * PI_HALF;
  52236. y.y = 1 * PI_HALF;
  52237. z.z = 1 * PI_HALF;
  52238. }else if(camObjectPos.x < 0 && camObjectPos.y < 0){
  52239. x.x = 3 * PI_HALF;
  52240. y.y = 1 * PI_HALF;
  52241. z.z = 2 * PI_HALF;
  52242. }else if(camObjectPos.x > 0 && camObjectPos.y < 0){
  52243. x.x = 3 * PI_HALF;
  52244. y.y = 0 * PI_HALF;
  52245. z.z = 3 * PI_HALF;
  52246. }
  52247. }
  52248. }
  52249. // adjust scale of components
  52250. for(let handleName of Object.keys(this.handles)){
  52251. let handle = this.handles[handleName];
  52252. let node = handle.node;
  52253. let handlePos = node.getWorldPosition(new Vector3());
  52254. let distance = handlePos.distanceTo(camera.position);
  52255. let pr = Utils.projectedRadius(1, camera, distance, domElement.clientWidth, domElement.clientHeight);
  52256. let ws = node.parent.getWorldScale(new Vector3());
  52257. let s = (ScaleRatio / pr);
  52258. let scale = new Vector3(s, s, s).divide(ws);
  52259. let rot = new Matrix4().makeRotationFromEuler(node.rotation); //需要使用到旋转,所以我把设置scale的移到旋转后了,否则在视图上下旋转的分界线处rotateHandel会被拉长从而闪烁。
  52260. let rotInv = rot.clone().invert();
  52261. scale.applyMatrix4(rotInv);
  52262. scale.x = Math.abs(scale.x);
  52263. scale.y = Math.abs(scale.y);
  52264. scale.z = Math.abs(scale.z);
  52265. node.scale.copy(scale);
  52266. }
  52267. {
  52268. let ray = Utils.mouseToRay(pointer, camera, domElement.clientWidth, domElement.clientHeight);
  52269. let raycaster = new Raycaster(ray.origin, ray.direction);
  52270. raycaster.layers.enableAll();//add
  52271. let pickVolumes = this.pickVolumes.filter(v=>{
  52272. let mode = v.handle.split('.')[0];
  52273. return this.modesEnabled[mode]
  52274. });
  52275. let intersects = raycaster.intersectObjects(pickVolumes, true);
  52276. if(intersects.length > 0){
  52277. let I = intersects[0];
  52278. let handleName = I.object.handle;
  52279. console.log(handleName);
  52280. this.setActiveHandle(this.handles[handleName]);
  52281. }else {
  52282. this.setActiveHandle(null);
  52283. }
  52284. }
  52285. //
  52286. for(let handleName of Object.keys(this.scaleHandles)){
  52287. let handle = this.handles[handleName];
  52288. let node = handle.node;
  52289. let alignment = handle.alignment;
  52290. }
  52291. }
  52292. }else {
  52293. this.scene.visible = false;
  52294. }
  52295. }
  52296. };
  52297. /*
  52298. note:
  52299. transformationTool.scene会跟随选中物体,其scale就是boundingbox的大小。因此transformationTool.frame这个框也会跟着缩放
  52300. */
  52301. class VolumeTool extends EventDispatcher{
  52302. constructor (viewer) {
  52303. super();
  52304. this.viewer = viewer;
  52305. this.renderer = viewer.renderer;
  52306. this.addEventListener('start_inserting_volume', e => {
  52307. this.viewer.dispatchEvent({
  52308. type: 'cancel_insertions'
  52309. });
  52310. });
  52311. this.scene = new Scene();
  52312. this.scene.name = 'scene_volume';
  52313. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  52314. this.onRemove = e => {
  52315. this.scene.remove(e.volume);
  52316. };
  52317. this.onAdd = e => {
  52318. this.scene.add(e.volume);
  52319. };
  52320. for(let volume of viewer.scene.volumes){
  52321. this.onAdd({volume: volume});
  52322. }
  52323. this.viewer.inputHandler.addEventListener('delete', e => {
  52324. let volumes = e.selection.filter(e => (e instanceof Volume));
  52325. volumes.forEach(e => this.viewer.scene.removeVolume(e));
  52326. });
  52327. viewer.addEventListener("update", this.update.bind(this));
  52328. viewer.addEventListener("render.pass.scene", e => this.render(e));
  52329. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  52330. viewer.scene.addEventListener('volume_added', this.onAdd);
  52331. viewer.scene.addEventListener('volume_removed', this.onRemove);
  52332. }
  52333. onSceneChange(e){
  52334. if(e.oldScene){
  52335. e.oldScene.removeEventListeners('volume_added', this.onAdd);
  52336. e.oldScene.removeEventListeners('volume_removed', this.onRemove);
  52337. }
  52338. e.scene.addEventListener('volume_added', this.onAdd);
  52339. e.scene.addEventListener('volume_removed', this.onRemove);
  52340. }
  52341. startInsertion (args = {}) {
  52342. let volume;
  52343. if(args.type){
  52344. volume = new args.type();
  52345. }else {
  52346. volume = new BoxVolume();
  52347. }
  52348. volume.clip = args.clip || false;
  52349. volume.name = args.name || 'Volume';
  52350. this.dispatchEvent({
  52351. type: 'start_inserting_volume',
  52352. volume: volume
  52353. });
  52354. this.viewer.scene.addVolume(volume);
  52355. //this.scene.add(volume);
  52356. let cancel = {
  52357. callback: null
  52358. };
  52359. let drag = e => {
  52360. let camera = this.viewer.scene.getActiveCamera();
  52361. var I = e.intersect;
  52362. if (I) {
  52363. volume.position.copy(I.location);
  52364. let wp = volume.getWorldPosition(new Vector3()).applyMatrix4(camera.matrixWorldInverse);
  52365. // let pp = new THREE.Vector4(wp.x, wp.y, wp.z).applyMatrix4(camera.projectionMatrix);
  52366. let w = Math.abs((wp.z / 5));
  52367. volume.scale.set(w, w, w);
  52368. }
  52369. };
  52370. let drop = e => {
  52371. volume.removeEventListener('drag', drag);
  52372. volume.removeEventListener('drop', drop);
  52373. cancel.callback();
  52374. };
  52375. cancel.callback = e => {
  52376. volume.removeEventListener('drag', drag);
  52377. volume.removeEventListener('drop', drop);
  52378. this.viewer.removeEventListener('cancel_insertions', cancel.callback);
  52379. };
  52380. volume.addEventListener('drag', drag);
  52381. volume.addEventListener('drop', drop);
  52382. this.viewer.addEventListener('cancel_insertions', cancel.callback);
  52383. this.viewer.inputHandler.startDragging(volume);
  52384. return volume;
  52385. }
  52386. update(){
  52387. if (!this.viewer.scene) {
  52388. return;
  52389. }
  52390. let camera = this.viewer.scene.getActiveCamera();
  52391. let renderAreaSize = this.viewer.renderer.getSize(new Vector2$1());
  52392. let clientWidth = renderAreaSize.width;
  52393. let clientHeight = renderAreaSize.height;
  52394. let volumes = this.viewer.scene.volumes;
  52395. for (let volume of volumes) {
  52396. }
  52397. }
  52398. render(params){
  52399. const renderer = this.viewer.renderer;
  52400. const oldTarget = renderer.getRenderTarget();
  52401. if(params.renderTarget){
  52402. renderer.setRenderTarget(params.renderTarget);
  52403. }
  52404. renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  52405. renderer.setRenderTarget(oldTarget);
  52406. }
  52407. }
  52408. class Compass{
  52409. constructor(viewer){
  52410. this.viewer = viewer;
  52411. this.visible = false;
  52412. this.dom = this.createElement();
  52413. viewer.addEventListener("update", () => {
  52414. const direction = viewer.scene.view.direction.clone();
  52415. direction.z = 0;
  52416. direction.normalize();
  52417. const camera = viewer.scene.getActiveCamera();
  52418. const p1 = camera.getWorldPosition(new Vector3());
  52419. const p2 = p1.clone().add(direction);
  52420. const projection = viewer.getProjection();
  52421. const azimuth = Utils.computeAzimuth(p1, p2, projection);
  52422. this.dom.css("transform", `rotateZ(${-azimuth}rad)`);
  52423. });
  52424. this.dom.click( () => {
  52425. viewer.setTopView();
  52426. });
  52427. const renderArea = $(viewer.renderArea);
  52428. renderArea.append(this.dom);
  52429. this.setVisible(this.visible);
  52430. }
  52431. setVisible(visible){
  52432. this.visible = visible;
  52433. const value = visible ? "" : "none";
  52434. this.dom.css("display", value);
  52435. }
  52436. isVisible(){
  52437. return this.visible;
  52438. }
  52439. createElement(){
  52440. const style = `style="position: absolute; top: 10px; right: 10px; z-index: 10000; width: 64px;"`;
  52441. const img = $(`<img src="${Potree.resourcePath}/images/compas.svg" ${style} />`);
  52442. return img;
  52443. }
  52444. };
  52445. class PotreeRenderer {
  52446. constructor (viewer) {
  52447. this.viewer = viewer;
  52448. this.renderer = viewer.renderer;
  52449. {
  52450. let dummyScene = new Scene();
  52451. let geometry = new SphereGeometry(0.001, 2, 2);
  52452. let mesh = new Mesh(geometry, new MeshBasicMaterial());
  52453. mesh.position.set(36453, 35163, 764712);
  52454. dummyScene.add(mesh);
  52455. this.dummyMesh = mesh;
  52456. this.dummyScene = dummyScene;
  52457. }
  52458. }
  52459. clearTargets(params){//add
  52460. const viewer = this.viewer;
  52461. const {renderer} = viewer;
  52462. const oldTarget = renderer.getRenderTarget();
  52463. if(params.target){//add
  52464. renderer.setRenderTarget( params.target);
  52465. renderer.clear();
  52466. }
  52467. if(params.rtEDL){
  52468. renderer.setRenderTarget( params.rtEDL);
  52469. renderer.clear();
  52470. }else {
  52471. renderer.setRenderTarget( this.rtEDL );
  52472. renderer.clear( true, true, true );
  52473. }
  52474. /* renderer.setRenderTarget( this.rtRegular );
  52475. renderer.clear( true, true, false ); */
  52476. renderer.setRenderTarget(oldTarget);
  52477. }
  52478. clear(params={}){
  52479. let {viewer, renderer} = this;
  52480. // render skybox
  52481. if(viewer.background === "skybox"){
  52482. renderer.setClearColor(0xff0000, 1);
  52483. }else if(viewer.background === "gradient"){
  52484. renderer.setClearColor(0x00ff00, 1);
  52485. }else if(viewer.background === "black"){
  52486. renderer.setClearColor(0x000000, 1);
  52487. }else if(viewer.background === "white"){
  52488. renderer.setClearColor(0xFFFFFF, 1);
  52489. }else {
  52490. renderer.setClearColor(0x000000, 0);
  52491. }
  52492. params.target || renderer.clear();
  52493. renderer.clear();
  52494. this.clearTargets(params);
  52495. }
  52496. render(params={}){
  52497. let {viewer, renderer} = this;
  52498. const camera = params.camera ? params.camera : viewer.scene.getActiveCamera();
  52499. viewer.dispatchEvent({type: "render.pass.begin",viewer: viewer});
  52500. const renderAreaSize = renderer.getSize(new Vector2$1());
  52501. const width = params.width ? params.width : params.viewport ? params.viewport[2] : renderAreaSize.x;
  52502. const height = params.height ? params.height : params.viewport ? params.viewport[3] : renderAreaSize.y;
  52503. // render skybox
  52504. if(viewer.background === "skybox"){
  52505. viewer.skybox.camera.rotation.copy(viewer.scene.cameraP.rotation);
  52506. viewer.skybox.camera.fov = viewer.scene.cameraP.fov;
  52507. viewer.skybox.camera.aspect = viewer.scene.cameraP.aspect;
  52508. viewer.skybox.parent.rotation.x = 0;
  52509. viewer.skybox.parent.updateMatrixWorld();
  52510. viewer.skybox.camera.updateProjectionMatrix();
  52511. renderer.render(viewer.skybox.scene, viewer.skybox.camera);
  52512. }else if(viewer.background === "gradient"){
  52513. if(params.target){//add
  52514. renderer.setRenderTarget(params.target);
  52515. renderer.render(viewer.scene.sceneBG, viewer.scene.cameraBG);
  52516. renderer.setRenderTarget(null);
  52517. }else {
  52518. renderer.render(viewer.scene.sceneBG, viewer.scene.cameraBG);
  52519. }
  52520. }
  52521. for(let pointcloud of this.viewer.scene.pointclouds){
  52522. const {material} = pointcloud;
  52523. material.useEDL = false;
  52524. }
  52525. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, params.target || null, {
  52526. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof Potree.SphereVolume)),
  52527. });
  52528. // render scene
  52529. viewer.dispatchEvent({type: "render.pass.scene",viewer: viewer});
  52530. renderer.setRenderTarget(params.target ? params.target : null);//add
  52531. renderer.render(viewer.scene.scene, camera);
  52532. renderer.render(viewer.scene.sceneOverlay, camera);// add 透明贴图层
  52533. renderer.clearDepth();
  52534. viewer.transformationTool.update();
  52535. if(!params.target){
  52536. //测量线
  52537. viewer.dispatchEvent({type: "render.pass.perspective_overlay", viewer: viewer, camera});
  52538. viewer.renderer.render(viewer.overlay, camera);//从 viewer.renderDefault搬过来,为了reticule不遮住测量线
  52539. }
  52540. viewer.clippingTool.update();
  52541. renderer.render(viewer.clippingTool.sceneMarker, viewer.scene.cameraScreenSpace); //viewer.scene.cameraScreenSpace);
  52542. renderer.render(viewer.clippingTool.sceneVolume, camera);
  52543. renderer.render(viewer.controls.sceneControls, camera);
  52544. viewer.renderer.render(viewer.transformationTool.scene, camera);
  52545. //viewer.renderer.render(viewer.transformationTool.scene, camera);
  52546. // renderer.render(viewer.controls.sceneControls, camera);
  52547. // renderer.render(viewer.clippingTool.sceneVolume, camera);
  52548. // renderer.render(viewer.transformationTool.scene, camera);
  52549. // renderer.setViewport(width - viewer.navigationCube.width,
  52550. // height - viewer.navigationCube.width,
  52551. // viewer.navigationCube.width, viewer.navigationCube.width);
  52552. // renderer.render(viewer.navigationCube, viewer.navigationCube.camera);
  52553. // renderer.setViewport(0, 0, width, height);
  52554. viewer.dispatchEvent({type: "render.pass.end",viewer: viewer});
  52555. }
  52556. }
  52557. const copyShader = {
  52558. uniforms: {
  52559. tDiffuse: {
  52560. type: "t",
  52561. value: null
  52562. },
  52563. opacity: {
  52564. type: "f",
  52565. value: 1
  52566. }
  52567. },
  52568. vertexShader: `
  52569. varying vec2 vUv;
  52570. void main() {
  52571. vUv = uv;
  52572. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  52573. }
  52574. `,
  52575. fragmentShader: `
  52576. uniform float opacity;
  52577. uniform sampler2D tDiffuse;
  52578. varying vec2 vUv;
  52579. void main() {
  52580. vec4 texel = texture2D( tDiffuse, vUv );
  52581. gl_FragColor = opacity * texel;
  52582. }
  52583. `
  52584. };
  52585. class EDLRenderer{//Eye-Dome Lighting 眼罩照明
  52586. constructor(viewer){
  52587. this.viewer = viewer;
  52588. this.edlMaterial = null;
  52589. //this.rtRegular;
  52590. this.rtEDLs = new Map;
  52591. this.gl = viewer.renderer.getContext();
  52592. //反正也没用到,注释了:
  52593. //this.shadowMap = new PointCloudSM(this.viewer.pRenderer);
  52594. viewer.addEventListener('resize',this.resize.bind(this));
  52595. this.initEDL(viewer);
  52596. }
  52597. initEDL(viewer){
  52598. if (this.edlMaterial != null) {
  52599. return;
  52600. }
  52601. this.edlMaterial = new EyeDomeLightingMaterial();
  52602. this.edlMaterial.depthTest = true;
  52603. this.edlMaterial.depthWrite = true;
  52604. this.edlMaterial.transparent = true;
  52605. /* this.rtRegular = new THREE.WebGLRenderTarget(viewer.mainViewport.resolution2.x, viewer.mainViewport.resolution2.y, {
  52606. minFilter: THREE.NearestFilter,
  52607. magFilter: THREE.NearestFilter,
  52608. format: THREE.RGBAFormat,
  52609. depthTexture: new THREE.DepthTexture(undefined, undefined, THREE.UnsignedIntType)
  52610. });
  52611. */
  52612. /* let copyUniforms = THREE.UniformsUtils.clone( copyShader.uniforms );
  52613. this.copyMaterial = new THREE.ShaderMaterial( {
  52614. uniforms: copyUniforms,
  52615. vertexShader: copyShader.vertexShader,
  52616. fragmentShader: copyShader.fragmentShader,
  52617. //premultipliedAlpha: true,
  52618. transparent: true,
  52619. //blending: THREE.AdditiveBlending,
  52620. depthTest: false,
  52621. depthWrite: false
  52622. }); */
  52623. };
  52624. resize(e ){
  52625. if(Features.EXT_DEPTH.isSupported()){
  52626. let viewport = e.viewport;
  52627. this.getRtEDL(viewport).setSize(viewport.resolution2.x, viewport.resolution2.y);
  52628. }
  52629. }
  52630. clearTargets(params={}){
  52631. const viewer = this.viewer;
  52632. const {renderer} = viewer;
  52633. const oldTarget = renderer.getRenderTarget();
  52634. if(params.target){//add
  52635. renderer.setRenderTarget( params.target);
  52636. renderer.clear();
  52637. }
  52638. if(Features.EXT_DEPTH.isSupported()){
  52639. if(params.rtEDL){
  52640. renderer.setRenderTarget( params.rtEDL);
  52641. renderer.clear();
  52642. }else {
  52643. var rtEDL = this.getRtEDL(params.viewport);
  52644. if(rtEDL){
  52645. renderer.setRenderTarget( rtEDL );
  52646. renderer.clear( true, true, true );
  52647. }
  52648. }
  52649. }
  52650. //renderer.setRenderTarget( this.rtRegular );
  52651. //renderer.clear( true, true, false );
  52652. renderer.setRenderTarget(oldTarget);
  52653. }
  52654. getRtEDL(viewport){//根据不同viewport返回rtEDL的texture
  52655. if(!viewport){
  52656. console.warn('getRtEDL没传viewport!!!! !!!!!!!!!!');
  52657. viewport = viewer.mainViewport;
  52658. }
  52659. var rtEDL = this.rtEDLs.get(viewport);
  52660. if(!rtEDL){
  52661. if(Features.EXT_DEPTH.isSupported()){
  52662. rtEDL = new WebGLRenderTarget(viewport.resolution2.x, viewport.resolution2.y, {
  52663. minFilter: NearestFilter,
  52664. magFilter: NearestFilter,
  52665. format: RGBAFormat,
  52666. type: FloatType,
  52667. depthTexture: new DepthTexture(undefined, undefined, UnsignedIntType)
  52668. });
  52669. //注: 部分手机在resize时会崩溃,经检验去掉rtEDL的resize可以解决,所以更应该注释掉这个
  52670. this.rtEDLs.set(viewport, rtEDL);
  52671. }
  52672. }
  52673. return rtEDL
  52674. }
  52675. renderShadowMap(visiblePointClouds, camera, lights){
  52676. const {viewer} = this;
  52677. const doShadows = lights.length > 0 && !(lights[0].disableShadowUpdates);
  52678. if(doShadows){
  52679. let light = lights[0];
  52680. this.shadowMap.setLight(light);
  52681. let originalAttributes = new Map();
  52682. for(let pointcloud of viewer.scene.pointclouds){
  52683. // TODO IMPORTANT !!! check
  52684. originalAttributes.set(pointcloud, pointcloud.material.activeAttributeName);
  52685. pointcloud.material.disableEvents();
  52686. pointcloud.material.activeAttributeName = "depth";
  52687. //pointcloud.material.pointColorType = PointColorType.DEPTH;
  52688. }
  52689. this.shadowMap.render(viewer.scene.scenePointCloud, camera);
  52690. for(let pointcloud of visiblePointClouds){
  52691. let originalAttribute = originalAttributes.get(pointcloud);
  52692. // TODO IMPORTANT !!! check
  52693. pointcloud.material.activeAttributeName = originalAttribute;
  52694. pointcloud.material.enableEvents();
  52695. }
  52696. viewer.shadowTestCam.updateMatrixWorld();
  52697. viewer.shadowTestCam.matrixWorldInverse.copy(viewer.shadowTestCam.matrixWorld).invert();
  52698. viewer.shadowTestCam.updateProjectionMatrix();
  52699. }
  52700. }
  52701. render(params={}){
  52702. /*
  52703. 渲染顺序:
  52704. 底层:背景 -> skybox(也可中间)
  52705. 中间层(含有深度信息):1 点云、marker等mesh,
  52706. 2 测量线(现在被做成借用depthTex
  52707. 顶层:maginifier
  52708. magnifier的贴图渲染不需要顶层、中间层只需要点云。
  52709. */
  52710. const viewer = this.viewer;
  52711. let camera = params.camera ? params.camera : viewer.scene.getActiveCamera();
  52712. const resolution = params.viewport ? params.viewport.resolution2 : this.viewer.renderer.getSize(new Vector2$1());
  52713. //viewer.dispatchEvent({type: "render.pass.begin",viewer: viewer});
  52714. let lights = [];
  52715. /* viewer.scene.scene.traverse(node => {
  52716. if(node.type === "SpotLight"){
  52717. lights.push(node);
  52718. }
  52719. }); */
  52720. viewer.renderer.setRenderTarget(params.target || null);
  52721. let background = params.background || viewer.background;
  52722. let backgroundOpacity = params.backgroundOpacity == void 0 ? viewer.backgroundOpacity : params.backgroundOpacity;//如果想完全透明,只需要backgroundOpacity为0
  52723. if(backgroundOpacity != 0){//绘制背景
  52724. if(background === "skybox"){
  52725. viewer.skybox.camera.rotation.copy(viewer.scene.cameraP.rotation);
  52726. viewer.skybox.camera.fov = viewer.scene.cameraP.fov;
  52727. viewer.skybox.camera.aspect = viewer.scene.cameraP.aspect;
  52728. viewer.skybox.parent.rotation.x = 0;
  52729. viewer.skybox.parent.updateMatrixWorld();
  52730. viewer.skybox.camera.updateProjectionMatrix();
  52731. viewer.renderer.render(viewer.skybox.scene, viewer.skybox.camera);
  52732. }else if(background === 'gradient'){
  52733. viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg);
  52734. viewer.renderer.render(viewer.scene.scene, viewer.scene.cameraBG);
  52735. }else if(background === 'overlayColor'){//在不clear的前提下加一层背景色
  52736. viewer.scene.bg2.material.color.copy(params.backgroundColor);
  52737. viewer.scene.bg2.material.opacity = params.backgroundOpacity;
  52738. viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg2);
  52739. viewer.renderer.render(viewer.scene.scene, viewer.scene.cameraBG);
  52740. }
  52741. }
  52742. //skybox 全景图
  52743. if(!params.magnifier){
  52744. viewer.setCameraLayers(camera, ['skybox']);
  52745. let useDepthTex;
  52746. if(Potree.settings.displayMode == 'showPanos' && viewer.images360.currentPano.pointcloud.hasDepthTex && Features.EXT_DEPTH.isSupported()){//渲染深度图
  52747. useDepthTex = true;
  52748. viewer.renderer.setRenderTarget(params.rtEDL || this.getRtEDL(params.viewport)); //将带有深度图的skybox画在rtEDL一下,这样就不需要绘制后边的点云了
  52749. viewer.renderer.render(viewer.scene.scene, camera);
  52750. viewer.renderer.setRenderTarget(params.target || null);
  52751. }
  52752. viewer.renderer.render(viewer.scene.scene, camera);
  52753. if(useDepthTex)return
  52754. }
  52755. const visiblePointClouds2 = viewer.scene.pointclouds.filter(pc => viewer.getObjVisiByReason(pc,'datasetSelection') ); //需要绘制到rtEDL的
  52756. const showPointClouds = params.magnifier ? visiblePointClouds2.length>0 : viewer.scene.pointclouds.some(e=>e.visible); //是否有需要绘制到屏幕的
  52757. visiblePointClouds2.forEach(e=>{//为了绘制到depthTexture,先显示(展示全景图时隐藏了点云,所以需要显示下。且放大镜需要绘制点云)
  52758. e.oldVisi = e.visible;
  52759. e.visible = true;
  52760. });
  52761. viewer.setCameraLayers(camera, ['pointcloud']);
  52762. camera.layers.set(Potree.config.renderLayers.pointcloud);
  52763. //TODO adapt to multiple lights
  52764. //this.renderShadowMap(visiblePointClouds2, camera, lights); //???????
  52765. {
  52766. for (let pointcloud of visiblePointClouds2) {
  52767. let material = pointcloud.material;
  52768. let octreeSize = pointcloud.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  52769. material.fov = MathUtils.degToRad(camera.fov);
  52770. /* material.screenWidth = width;
  52771. material.screenHeight = height; */
  52772. material.resolution = resolution;
  52773. material.spacing = pointcloud.pcoGeometry.spacing; // * Math.max(this.scale.x, this.scale.y, this.scale.z);
  52774. material.near = camera.near;
  52775. material.far = camera.far;
  52776. material.uniforms.octreeSize.value = octreeSize;
  52777. if(viewer.useEDL && Potree.settings.displayMode != 'showPanos'){
  52778. /* material.weighted = false;
  52779. material.useLogarithmicDepthBuffer = false; */
  52780. material.useEDL = true;
  52781. //material.fakeEDL = false; //add
  52782. }else {
  52783. material.useEDL = false;
  52784. //material.fakeEDL = true; //add 使也输出深度
  52785. }
  52786. }
  52787. if(Features.EXT_DEPTH.isSupported() && !params.dontRenderRtEDL){
  52788. //借用rtEDL存储深度信息
  52789. viewer.renderer.setRenderTarget(params.rtEDL || this.getRtEDL(params.viewport)/* this.rtEDL */);
  52790. if(visiblePointClouds2.length>0){
  52791. //渲染scenePointCloud到rtEDL
  52792. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, params.rtEDL || this.getRtEDL(params.viewport), {
  52793. shadowMaps: lights.length > 0 ? [this.shadowMap] : null,
  52794. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof SphereVolume)),
  52795. transparent: false,
  52796. });
  52797. }
  52798. if(Potree.settings.intersectOnObjs){// model也要渲染到rtEDL
  52799. camera.layers.set(Potree.config.renderLayers.model);
  52800. viewer.renderer.render(viewer.scene.scene, camera);
  52801. }
  52802. //test
  52803. /* {
  52804. viewer.objs.traverse((obj)=>{
  52805. if(obj.material){
  52806. obj.material = obj.depthMat
  52807. }
  52808. })
  52809. viewer.setCameraLayers(camera, ['sceneObjects'])
  52810. viewer.renderer.render(viewer.scene.scene, camera)
  52811. viewer.objs.traverse((obj)=>{
  52812. if(obj.material){
  52813. obj.material = obj.standardMat
  52814. }
  52815. })
  52816. } */
  52817. }
  52818. }
  52819. //渲染到rtEDL完毕
  52820. viewer.dispatchEvent({type: "render.pass.scene", viewer: viewer/* , renderTarget: this.rtRegular */});
  52821. viewer.renderer.setRenderTarget(params.target || null);
  52822. if(!params.magnifier)visiblePointClouds2.forEach(e=>{//放大镜显示点云
  52823. e.visible = e.oldVisi;
  52824. });
  52825. if(showPointClouds){ //绘制点云到画布
  52826. if(viewer.useEDL) { //设置edlMaterial
  52827. //Features.EXT_DEPTH不支持的话不会到这一块
  52828. const uniforms = this.edlMaterial.uniforms;
  52829. //if(viewer.useEDL){
  52830. /* uniforms.screenWidth.value = width;
  52831. uniforms.screenHeight.value = height; */
  52832. uniforms.resolution.value.copy(resolution);
  52833. uniforms.edlStrength.value = viewer.edlStrength;
  52834. uniforms.radius.value = viewer.edlRadius;
  52835. uniforms.useEDL.value = 1;//add
  52836. /* }else{
  52837. uniforms.useEDL.value = 0;//add
  52838. } */
  52839. let proj = camera.projectionMatrix;
  52840. let projArray = new Float32Array(16);
  52841. projArray.set(proj.elements);
  52842. uniforms.uProj.value = projArray;
  52843. uniforms.uEDLColor.value = (params.rtEDL || this.getRtEDL(params.viewport)).texture;
  52844. //uniforms.uEDLDepth.value = (params.rtEDL || this.getRtEDL(params.viewport)).depthTexture; //其实没用到
  52845. uniforms.opacity.value = viewer.edlOpacity; // HACK
  52846. Utils.screenPass.render(viewer.renderer, this.edlMaterial, params.target);
  52847. }else {
  52848. //渲染点云 (直接用rtEDL上的会失去抗锯齿)
  52849. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, null , {
  52850. shadowMaps: lights.length > 0 ? [this.shadowMap] : null,
  52851. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof SphereVolume))
  52852. });
  52853. }
  52854. }
  52855. //viewer.dispatchEvent({type: "render.pass.end",viewer: viewer});
  52856. visiblePointClouds2.forEach(e=>{
  52857. e.visible = e.oldVisi;
  52858. });
  52859. }
  52860. }
  52861. class HQSplatRenderer{
  52862. //rtAttribute 估计需要给magnifer复制一份
  52863. constructor(viewer){
  52864. this.viewer = viewer;
  52865. this.depthMaterials = new Map();
  52866. this.attributeMaterials = new Map();
  52867. this.normalizationMaterial = null;
  52868. this.rtDepth = null;
  52869. this.rtAttribute = null;
  52870. this.gl = viewer.renderer.getContext();
  52871. this.initialized = false;
  52872. viewer.addEventListener('resize',this.resize.bind(this));
  52873. }
  52874. init(){
  52875. if (this.initialized) {
  52876. return;
  52877. }
  52878. this.normalizationMaterial = new NormalizationMaterial();
  52879. this.normalizationMaterial.depthTest = true;
  52880. this.normalizationMaterial.depthWrite = true;
  52881. this.normalizationMaterial.transparent = true;
  52882. this.normalizationEDLMaterial = new NormalizationEDLMaterial();
  52883. this.normalizationEDLMaterial.depthTest = true;
  52884. this.normalizationEDLMaterial.depthWrite = true;
  52885. this.normalizationEDLMaterial.transparent = true;
  52886. this.rtDepth = new WebGLRenderTarget(1024, 1024, {
  52887. minFilter: NearestFilter,
  52888. magFilter: NearestFilter,
  52889. format: RGBAFormat,
  52890. type: FloatType,
  52891. depthTexture: new DepthTexture(undefined, undefined, UnsignedIntType)
  52892. });
  52893. this.rtAttribute = new WebGLRenderTarget(1024, 1024, {
  52894. minFilter: NearestFilter,
  52895. magFilter: NearestFilter,
  52896. format: RGBAFormat,
  52897. type: FloatType,
  52898. depthTexture: this.rtDepth.depthTexture,
  52899. });
  52900. this.initialized = true;
  52901. };
  52902. resize(e/* width, height */){
  52903. this.rtDepth.setSize(e.canvasWidth, e.canvasHeight);
  52904. this.rtAttribute.setSize(e.canvasWidth, e.canvasHeight);
  52905. }
  52906. clearTargets(params){
  52907. const viewer = this.viewer;
  52908. const {renderer} = viewer;
  52909. const oldTarget = renderer.getRenderTarget();
  52910. if(params.target){//add
  52911. renderer.setRenderTarget( params.target);
  52912. renderer.clear();
  52913. }
  52914. renderer.setClearColor(0x000000, 0);
  52915. renderer.setRenderTarget( this.rtDepth );
  52916. renderer.clear( true, true, true );
  52917. renderer.setRenderTarget( this.rtAttribute );
  52918. renderer.clear( true, true, true );
  52919. renderer.setRenderTarget(oldTarget);
  52920. }
  52921. clear(params={}){
  52922. this.init();
  52923. const {renderer, background} = this.viewer;
  52924. if(background === "skybox"){
  52925. renderer.setClearColor(0x000000, 0);
  52926. } else if (background === 'gradient') {
  52927. renderer.setClearColor(0x000000, 0);
  52928. } else if (background === 'black') {
  52929. renderer.setClearColor(0x000000, 1);
  52930. } else if (background === 'white') {
  52931. renderer.setClearColor(0xFFFFFF, 1);
  52932. } else {
  52933. renderer.setClearColor(0x000000, 0);
  52934. }
  52935. params.target || renderer.clear();
  52936. this.clearTargets(params);
  52937. }
  52938. render(params={}) {
  52939. this.init();
  52940. const viewer = this.viewer;
  52941. const camera = params.camera ? params.camera : viewer.scene.getActiveCamera();
  52942. const {width, height} = params.width ? params : this.viewer.renderer.getSize(new Vector2$1());
  52943. viewer.renderer.setRenderTarget(params.target||null);
  52944. viewer.dispatchEvent({type: "render.pass.begin",viewer: viewer});
  52945. //params.target || this.resize(width, height);
  52946. const visiblePointClouds = viewer.scene.pointclouds.filter(pc => pc.visible);
  52947. const originalMaterials = new Map();
  52948. for(let pointcloud of visiblePointClouds){
  52949. originalMaterials.set(pointcloud, pointcloud.material);
  52950. if(!this.attributeMaterials.has(pointcloud)){
  52951. let attributeMaterial = new PointCloudMaterial$1();
  52952. this.attributeMaterials.set(pointcloud, attributeMaterial);
  52953. }
  52954. if(!this.depthMaterials.has(pointcloud)){
  52955. let depthMaterial = new PointCloudMaterial$1();
  52956. depthMaterial.setDefine("depth_pass", "#define hq_depth_pass");
  52957. depthMaterial.setDefine("use_edl", "#define use_edl");
  52958. this.depthMaterials.set(pointcloud, depthMaterial);
  52959. }
  52960. }
  52961. { // DEPTH PASS
  52962. for (let pointcloud of visiblePointClouds) {
  52963. let octreeSize = pointcloud.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  52964. let material = originalMaterials.get(pointcloud);
  52965. let depthMaterial = this.depthMaterials.get(pointcloud);
  52966. depthMaterial.size = material.size;
  52967. depthMaterial.minSize = material.minSize;
  52968. depthMaterial.maxSize = material.maxSize;
  52969. depthMaterial.pointSizeType = material.pointSizeType;
  52970. depthMaterial.visibleNodesTexture = material.visibleNodesTexture;
  52971. depthMaterial.weighted = false;
  52972. depthMaterial.screenWidth = width;
  52973. depthMaterial.shape = PointShape.CIRCLE;
  52974. depthMaterial.screenHeight = height;
  52975. depthMaterial.uniforms.visibleNodes.value = material.visibleNodesTexture;
  52976. depthMaterial.uniforms.octreeSize.value = octreeSize;
  52977. depthMaterial.spacing = pointcloud.pcoGeometry.spacing; // * Math.max(...pointcloud.scale.toArray());
  52978. depthMaterial.classification = material.classification;
  52979. depthMaterial.uniforms.classificationLUT.value.image.data = material.uniforms.classificationLUT.value.image.data;
  52980. depthMaterial.classificationTexture.needsUpdate = true;
  52981. depthMaterial.uniforms.uFilterReturnNumberRange.value = material.uniforms.uFilterReturnNumberRange.value;
  52982. depthMaterial.uniforms.uFilterNumberOfReturnsRange.value = material.uniforms.uFilterNumberOfReturnsRange.value;
  52983. depthMaterial.uniforms.uFilterGPSTimeClipRange.value = material.uniforms.uFilterGPSTimeClipRange.value;
  52984. depthMaterial.uniforms.uFilterPointSourceIDClipRange.value = material.uniforms.uFilterPointSourceIDClipRange.value;
  52985. depthMaterial.clipTask = material.clipTask;
  52986. depthMaterial.clipMethod = material.clipMethod;
  52987. depthMaterial.setClipBoxes(material.clipBoxes);
  52988. depthMaterial.setClipPolygons(material.clipPolygons);
  52989. pointcloud.material = depthMaterial;
  52990. }
  52991. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, (params.rtEDL || this.rtDepth), {
  52992. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof SphereVolume)),
  52993. });
  52994. }
  52995. { // ATTRIBUTE PASS
  52996. for (let pointcloud of visiblePointClouds) {
  52997. let octreeSize = pointcloud.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  52998. let material = originalMaterials.get(pointcloud);
  52999. let attributeMaterial = this.attributeMaterials.get(pointcloud);
  53000. attributeMaterial.size = material.size;
  53001. attributeMaterial.minSize = material.minSize;
  53002. attributeMaterial.maxSize = material.maxSize;
  53003. attributeMaterial.pointSizeType = material.pointSizeType;
  53004. attributeMaterial.activeAttributeName = material.activeAttributeName;
  53005. attributeMaterial.visibleNodesTexture = material.visibleNodesTexture;
  53006. attributeMaterial.weighted = true;
  53007. attributeMaterial.screenWidth = width;
  53008. attributeMaterial.screenHeight = height;
  53009. attributeMaterial.shape = PointShape.CIRCLE;
  53010. attributeMaterial.uniforms.visibleNodes.value = material.visibleNodesTexture;
  53011. attributeMaterial.uniforms.octreeSize.value = octreeSize;
  53012. attributeMaterial.spacing = pointcloud.pcoGeometry.spacing; // * Math.max(...pointcloud.scale.toArray());
  53013. attributeMaterial.classification = material.classification;
  53014. attributeMaterial.uniforms.classificationLUT.value.image.data = material.uniforms.classificationLUT.value.image.data;
  53015. attributeMaterial.classificationTexture.needsUpdate = true;
  53016. attributeMaterial.uniforms.uFilterReturnNumberRange.value = material.uniforms.uFilterReturnNumberRange.value;
  53017. attributeMaterial.uniforms.uFilterNumberOfReturnsRange.value = material.uniforms.uFilterNumberOfReturnsRange.value;
  53018. attributeMaterial.uniforms.uFilterGPSTimeClipRange.value = material.uniforms.uFilterGPSTimeClipRange.value;
  53019. attributeMaterial.uniforms.uFilterPointSourceIDClipRange.value = material.uniforms.uFilterPointSourceIDClipRange.value;
  53020. attributeMaterial.elevationGradientRepeat = material.elevationGradientRepeat;
  53021. attributeMaterial.elevationRange = material.elevationRange;
  53022. attributeMaterial.gradient = material.gradient;
  53023. attributeMaterial.matcap = material.matcap;
  53024. attributeMaterial.intensityRange = material.intensityRange;
  53025. attributeMaterial.intensityGamma = material.intensityGamma;
  53026. attributeMaterial.intensityContrast = material.intensityContrast;
  53027. attributeMaterial.intensityBrightness = material.intensityBrightness;
  53028. attributeMaterial.rgbGamma = material.rgbGamma;
  53029. attributeMaterial.rgbContrast = material.rgbContrast;
  53030. attributeMaterial.rgbBrightness = material.rgbBrightness;
  53031. attributeMaterial.weightRGB = material.weightRGB;
  53032. attributeMaterial.weightIntensity = material.weightIntensity;
  53033. attributeMaterial.weightElevation = material.weightElevation;
  53034. attributeMaterial.weightRGB = material.weightRGB;
  53035. attributeMaterial.weightClassification = material.weightClassification;
  53036. attributeMaterial.weightReturnNumber = material.weightReturnNumber;
  53037. attributeMaterial.weightSourceID = material.weightSourceID;
  53038. attributeMaterial.color = material.color;
  53039. attributeMaterial.clipTask = material.clipTask;
  53040. attributeMaterial.clipMethod = material.clipMethod;
  53041. attributeMaterial.setClipBoxes(material.clipBoxes);
  53042. attributeMaterial.setClipPolygons(material.clipPolygons);
  53043. pointcloud.material = attributeMaterial;
  53044. }
  53045. let gl = this.gl;
  53046. //viewer.renderer.setRenderTarget(null);
  53047. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, this.rtAttribute, {
  53048. clipSpheres: viewer.scene.volumes.filter(v => (v instanceof SphereVolume)),
  53049. //material: this.attributeMaterial,
  53050. blendFunc: [gl.SRC_ALPHA, gl.ONE],
  53051. //depthTest: false,
  53052. depthWrite: false
  53053. });
  53054. }
  53055. for(let [pointcloud, material] of originalMaterials){
  53056. pointcloud.material = material;
  53057. }
  53058. if(viewer.background === "skybox"){
  53059. viewer.renderer.setClearColor(0x000000, 0);
  53060. viewer.renderer.clear();
  53061. viewer.skybox.camera.rotation.copy(viewer.scene.cameraP.rotation);
  53062. viewer.skybox.camera.fov = viewer.scene.cameraP.fov;
  53063. viewer.skybox.camera.aspect = viewer.scene.cameraP.aspect;
  53064. viewer.skybox.parent.rotation.x = 0;
  53065. viewer.skybox.parent.updateMatrixWorld();
  53066. viewer.skybox.camera.updateProjectionMatrix();
  53067. viewer.renderer.render(viewer.skybox.scene, viewer.skybox.camera);
  53068. } else if (viewer.background === 'gradient') {
  53069. viewer.renderer.setClearColor(0x000000, 0);
  53070. viewer.renderer.clear();
  53071. viewer.renderer.render(viewer.scene.sceneBG, viewer.scene.cameraBG);
  53072. } else if (viewer.background === 'black') {
  53073. viewer.renderer.setClearColor(0x000000, 1);
  53074. viewer.renderer.clear();
  53075. } else if (viewer.background === 'white') {
  53076. viewer.renderer.setClearColor(0xFFFFFF, 1);
  53077. viewer.renderer.clear();
  53078. } else {
  53079. viewer.renderer.setClearColor(0x000000, 0);
  53080. viewer.renderer.clear();
  53081. }
  53082. { // NORMALIZATION PASS
  53083. let normalizationMaterial = this.useEDL ? this.normalizationEDLMaterial : this.normalizationMaterial;
  53084. if(this.useEDL){
  53085. normalizationMaterial.uniforms.edlStrength.value = viewer.edlStrength;
  53086. normalizationMaterial.uniforms.radius.value = viewer.edlRadius;
  53087. normalizationMaterial.uniforms.screenWidth.value = width;
  53088. normalizationMaterial.uniforms.screenHeight.value = height;
  53089. normalizationMaterial.uniforms.uEDLMap.value = (params.rtEDL || this.rtDepth).texture;
  53090. }
  53091. normalizationMaterial.uniforms.uWeightMap.value = this.rtAttribute.texture;
  53092. normalizationMaterial.uniforms.uDepthMap.value = this.rtAttribute.depthTexture;
  53093. Utils.screenPass.render(viewer.renderer, normalizationMaterial);
  53094. }
  53095. viewer.renderer.render(viewer.scene.scene, camera);
  53096. viewer.dispatchEvent({type: "render.pass.scene", viewer: viewer});
  53097. viewer.renderer.render(viewer.scene.sceneOverlay, camera);// add 透明贴图层
  53098. viewer.renderer.clearDepth();
  53099. viewer.transformationTool.update();
  53100. if(!params.target){
  53101. //测量线
  53102. viewer.dispatchEvent({type: "render.pass.perspective_overlay",viewer: viewer, camera});
  53103. viewer.renderer.render(viewer.overlay, camera);//从 viewer.renderDefault搬过来,为了reticule不遮住测量线
  53104. }
  53105. viewer.renderer.render(viewer.controls.sceneControls, camera);
  53106. viewer.renderer.render(viewer.clippingTool.sceneVolume, camera);
  53107. viewer.renderer.render(viewer.transformationTool.scene, camera);
  53108. viewer.renderer.setViewport(width - viewer.navigationCube.width,
  53109. height - viewer.navigationCube.width,
  53110. viewer.navigationCube.width, viewer.navigationCube.width);
  53111. viewer.renderer.render(viewer.navigationCube, viewer.navigationCube.camera);
  53112. viewer.renderer.setViewport(0, 0, width, height);
  53113. viewer.dispatchEvent({type: "render.pass.end",viewer: viewer});
  53114. viewer.renderer.setRenderTarget(null);
  53115. }
  53116. }
  53117. let sid = 0;
  53118. class View extends EventDispatcher{
  53119. constructor () {
  53120. super();
  53121. this.position = new Vector3(0, 0, 0);
  53122. this.yaw = 0;//Math.PI / 4; // = 4dkk lon + 90
  53123. this._pitch = 0;//-Math.PI / 4; //上下旋转 = 4dkk lat
  53124. this.radius = 1;
  53125. this.maxPitch = Math.PI / 2;
  53126. this.minPitch = -Math.PI / 2;
  53127. this.sid = sid++;
  53128. this.LookTransition = 'LookTransition'+this.sid;
  53129. }
  53130. //add------
  53131. applyToCamera(camera){
  53132. camera.position.copy(this.position);
  53133. camera.rotation.copy(this.rotation);
  53134. camera.updateMatrix();
  53135. camera.updateMatrixWorld();
  53136. //camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  53137. }
  53138. get rotation(){
  53139. var rotation = new Euler;
  53140. rotation.order = "ZXY";
  53141. rotation.x = Math.PI / 2 + this.pitch;
  53142. rotation.z = this.yaw;
  53143. return rotation
  53144. }
  53145. set rotation(rotation){
  53146. //因为 rotation的y不一定是0 , 所以不能直接逆着写。
  53147. this.direction = new Vector3(0,0,-1).applyEuler(rotation);
  53148. }
  53149. copy(a){
  53150. Common.CopyClassObject(this, a);
  53151. }
  53152. clone () {
  53153. /* let c = new View();
  53154. c.yaw = this.yaw;
  53155. c._pitch = this.pitch;
  53156. c.radius = this.radius;
  53157. c.maxPitch = this.maxPitch;
  53158. c.minPitch = this.minPitch;
  53159. return c; */
  53160. return Common.CloneClassObject(this)
  53161. }
  53162. //----------
  53163. get pitch () {
  53164. return this._pitch;
  53165. }
  53166. set pitch (angle) {
  53167. this._pitch = Math.max(Math.min(angle, this.maxPitch), this.minPitch);
  53168. }
  53169. get direction () {
  53170. let dir = new Vector3(0, 1, 0);
  53171. dir.applyAxisAngle(new Vector3(1, 0, 0), this.pitch);
  53172. dir.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);
  53173. return dir;
  53174. }
  53175. set direction (dir) {
  53176. //if(dir.x === dir.y){
  53177. if(dir.x === 0 && dir.y === 0){
  53178. this.pitch = Math.PI / 2 * Math.sign(dir.z);
  53179. }else {
  53180. let yaw = Math.atan2(dir.y, dir.x) - Math.PI / 2;
  53181. let pitch = Math.atan2(dir.z, Math.sqrt(dir.x * dir.x + dir.y * dir.y));
  53182. this.yaw = yaw;
  53183. this.pitch = pitch;
  53184. }
  53185. }
  53186. lookAt(t){//setPivot
  53187. let V;
  53188. if(arguments.length === 1){
  53189. V = new Vector3().subVectors(t, this.position);
  53190. }else if(arguments.length === 3){
  53191. V = new Vector3().subVectors(new Vector3(...arguments), this.position);
  53192. }
  53193. let radius = V.length();
  53194. let dir = V.normalize();
  53195. this.radius = radius;
  53196. this.direction = dir;
  53197. }
  53198. getPivot () {
  53199. return new Vector3().addVectors(this.position, this.direction.multiplyScalar(this.radius));
  53200. }
  53201. getSide () {
  53202. let side = new Vector3(1, 0, 0);
  53203. side.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);
  53204. return side;
  53205. }
  53206. /* pan (x, y) {
  53207. let dir = new THREE.Vector3(0, 1, 0);
  53208. dir.applyAxisAngle(new THREE.Vector3(1, 0, 0), this.pitch);
  53209. dir.applyAxisAngle(new THREE.Vector3(0, 0, 1), this.yaw);
  53210. // let side = new THREE.Vector3(1, 0, 0);
  53211. // side.applyAxisAngle(new THREE.Vector3(0, 0, 1), this.yaw);
  53212. let side = this.getSide();
  53213. let up = side.clone().cross(dir);
  53214. let pan = side.multiplyScalar(x).add(up.multiplyScalar(y));
  53215. this.position = this.position.add(pan);
  53216. // this.target = this.target.add(pan);
  53217. } */
  53218. pan (x, y) { //发现pan其实就是translate
  53219. this.translate(x, 0, y);
  53220. }
  53221. translate (x, y, z, forceHorizon ) {
  53222. //相机方向
  53223. let dir = new Vector3(0, 1, 0);
  53224. dir.applyAxisAngle(new Vector3(1, 0, 0), forceHorizon ? 0 : this.pitch); //上下角度
  53225. dir.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);//水平角度
  53226. let side = new Vector3(1, 0, 0);
  53227. side.applyAxisAngle(new Vector3(0, 0, 1), this.yaw); //垂直于相机当前水平朝向的 左右方向
  53228. let up = side.clone().cross(dir); //垂直于相机当前水平朝向的 向上方向
  53229. let t = side.multiplyScalar(x) //x影响 左右分量
  53230. .add(dir.multiplyScalar(y)) //y影响 前后分量
  53231. .add(up.multiplyScalar(z)); //z影响 上下分量
  53232. this.position = this.position.add(t);
  53233. this.restrictPos();
  53234. }
  53235. translateWorld (x, y, z) {
  53236. this.position.x += x;
  53237. this.position.y += y;
  53238. this.position.z += z;
  53239. this.restrictPos();
  53240. }
  53241. restrictPos(){//add
  53242. if(this.limitBound){
  53243. this.position.clamp(this.limitBound.min, this.limitBound.max);
  53244. }
  53245. }
  53246. setCubeView(dir) {
  53247. switch(dir) {
  53248. case "front":
  53249. this.yaw = 0;
  53250. this.pitch = 0;
  53251. break;
  53252. case "back":
  53253. this.yaw = Math.PI;
  53254. this.pitch = 0;
  53255. break;
  53256. case "left":
  53257. this.yaw = -Math.PI / 2;
  53258. this.pitch = 0;
  53259. break;
  53260. case "right":
  53261. this.yaw = Math.PI / 2;
  53262. this.pitch = 0;
  53263. break;
  53264. case "top":
  53265. this.yaw = 0;
  53266. this.pitch = -Math.PI / 2;
  53267. break;
  53268. case "bottom":
  53269. this.yaw = -Math.PI;
  53270. this.pitch = Math.PI / 2;
  53271. break;
  53272. }
  53273. }
  53274. isFlying(){
  53275. return transitions.getById(this.LookTransition).length > 0
  53276. }
  53277. cancelFlying(){//外界只能通过这个来cancel
  53278. transitions.cancelById(this.LookTransition, true );
  53279. }
  53280. setView( info = {}){
  53281. // position, target, duration = 0, callback = null, onUpdate = null, Easing='', cancelFun
  53282. this.cancelFlying();
  53283. let done = ()=>{
  53284. if(endTarget){
  53285. this.lookAt(endTarget); //compute radius for orbitcontrol
  53286. }else if(endQuaternion){
  53287. this.rotation = new Euler().setFromQuaternion(endQuaternion);
  53288. }
  53289. let f = ()=>{
  53290. info.callback && info.callback();
  53291. this.dispatchEvent('flyingDone');
  53292. };
  53293. if(info.duration){
  53294. setTimeout(f,1);//延迟是为了使isFlying先为false
  53295. }else {
  53296. f(); //有的需要迅速执行回调
  53297. }
  53298. };
  53299. let endPosition = new Vector3().copy(info.position);
  53300. const startPosition = this.position.clone();
  53301. const startTarget = this.getPivot();
  53302. let startQuaternion = math.getQuaFromPosAim(startPosition,startTarget);
  53303. let endTarget = null, endQuaternion ;
  53304. if(info.target ){
  53305. endTarget = new Vector3().copy(info.target);
  53306. endQuaternion = math.getQuaFromPosAim(endPosition,endTarget);
  53307. }else if(info.quaternion){
  53308. endQuaternion = info.quaternion.clone();
  53309. }
  53310. if(!info.duration){
  53311. this.position.copy(endPosition);
  53312. this.restrictPos();
  53313. info.onUpdate && info.onUpdate(1);
  53314. done();
  53315. }else {
  53316. transitions.start(lerp.vector(this.position, endPosition, (pos, progress)=>{
  53317. let t = progress;
  53318. if(endQuaternion){
  53319. let quaternion = (new Quaternion()).copy(startQuaternion);
  53320. lerp.quaternion(quaternion, endQuaternion)(progress),
  53321. this.rotation = new Euler().setFromQuaternion(quaternion);
  53322. }
  53323. this.restrictPos();
  53324. info.onUpdate && info.onUpdate(t);//add
  53325. }), info.duration, done, 0, info.Easing ? easing[info.Easing] : easing.easeInOutSine /*easeInOutQuad */,null, this.LookTransition, info.cancelFun);
  53326. }
  53327. }
  53328. //平移Ortho相机
  53329. moveOrthoCamera(viewport, info, duration, easeName){//boundSize优先于endZoom。
  53330. let camera = viewport.camera;
  53331. let startZoom = camera.zoom;
  53332. let endPosition = info.endPosition;
  53333. let boundSize = info.boundSize;
  53334. let endZoom = info.endZoom;
  53335. let margin = info.margin || {x:0,y:0};/* 200 */ //像素
  53336. if(info.bound){//需要修改boundSize以适应相机的旋转,当相机不在xy水平面上朝向z时
  53337. endPosition = endPosition || info.bound.getCenter(new Vector3());
  53338. let matrixRot = new Matrix4().makeRotationFromEuler(this.rotation).invert();
  53339. let boundingBox = info.bound.clone().applyMatrix4(matrixRot);
  53340. boundSize = boundingBox.getSize(new Vector3());
  53341. }
  53342. if(boundSize && boundSize.x == 0 && boundSize.y == 0){
  53343. boundSize.set(1,1); //避免infinity
  53344. }
  53345. this.setView({ position:endPosition, duration,
  53346. callback:()=>{//done
  53347. },
  53348. onUpdate:(progress)=>{
  53349. if(boundSize || endZoom){
  53350. if(boundSize){
  53351. let aspect = boundSize.x / boundSize.y;
  53352. let w, h;
  53353. if(camera.aspect > aspect){//视野更宽则用bound的纵向来决定
  53354. h = boundSize.y;
  53355. endZoom = (viewport.resolution.y - margin.y) / h; //注意,要在resolution不为0时执行
  53356. }else {
  53357. w = boundSize.x;
  53358. endZoom = (viewport.resolution.x - margin.x) / w;
  53359. }
  53360. //onUpdate时更新endzoom是因为画布大小可能更改
  53361. }
  53362. camera.zoom = endZoom * progress + startZoom * (1 - progress);
  53363. camera.updateProjectionMatrix();
  53364. }
  53365. },
  53366. Easing:easeName
  53367. });
  53368. }
  53369. zoomOrthoCamera(camera, endZoom, pointer, duration, onProgress){//定点缩放
  53370. let startZoom = camera.zoom;
  53371. let pointerPos = new Vector3(pointer.x, pointer.y,0.5);
  53372. transitions.start(( progress)=>{
  53373. let oldPos = pointerPos.clone().unproject(camera);
  53374. camera.zoom = endZoom * progress + startZoom * (1 - progress);
  53375. camera.updateProjectionMatrix();
  53376. let newPos = pointerPos.clone().unproject(camera);
  53377. //定点缩放, 恢复一下鼠标所在位置的位置改变量
  53378. let moveVec = new Vector3().subVectors(newPos, oldPos);
  53379. camera.position.sub(moveVec);
  53380. this.position.copy(camera.position);
  53381. onProgress && onProgress();
  53382. } , duration, null/* done */, 0, easing.easeInOutSine, null, "zoomInView"/* , info.cancelFun */);
  53383. }
  53384. };
  53385. /*
  53386. z
  53387. |
  53388. |
  53389. |
  53390. |
  53391. x <-------| 中心为点云position加boudingbox中心
  53392. /
  53393. /
  53394. y
  53395. */
  53396. var lineLen$1 = 2, stemLen = 4, arrowLen = 2, lineDisToStem = 5;
  53397. var opacity = 0.5;
  53398. class Axis extends Object3D {// 坐标轴
  53399. constructor (position) {
  53400. super();
  53401. this.getArrow();
  53402. this.createArrows();
  53403. //this.position.copy(position) 点云的中心点就是在(0,0,0)
  53404. //this.scale.set(2,2,2)
  53405. }
  53406. getArrow(){
  53407. var arrowGroup = new Object3D();
  53408. var line = LineDraw.createLine([new Vector3, new Vector3(0,0,lineLen$1)]);
  53409. var stem = new Mesh(new BoxGeometry(0.3, 0.3, stemLen));
  53410. stem.position.set(0,0,lineLen$1+lineDisToStem+stemLen/2);
  53411. 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
  53412. arrow.position.set(0,0,lineLen$1+lineDisToStem+stemLen + arrowLen/2);
  53413. arrow.rotation.set(Math.PI/2,0,0);
  53414. arrowGroup.add(stem);
  53415. arrowGroup.add(line);
  53416. arrowGroup.add(arrow);
  53417. this.arrowGroup = arrowGroup;
  53418. }
  53419. createArrows(){
  53420. var material = new MeshBasicMaterial({color:"#00d7df",side:2,transparent:true,opacity:0.8, depthWrite:false});
  53421. let axis = Object.keys(Potree.config.axis);
  53422. axis.forEach((axisText)=>{
  53423. let color = Potree.config.axis[axisText].color;
  53424. var group = this.arrowGroup.clone();
  53425. group.children.forEach(e=>{
  53426. e.material = e.material.clone();
  53427. /* e.material.opacity = opacity
  53428. e.material.transparent = true */
  53429. e.material.color.set(color);
  53430. });
  53431. var label = this.createLabel(axisText, color);
  53432. label.position.set(0, 0, lineLen$1 + stemLen + arrowLen + lineDisToStem + 3);
  53433. group.add(label);
  53434. if(axisText == 'y'){
  53435. group.rotation.x = -Math.PI / 2;
  53436. }else if(axisText == 'x'){
  53437. group.rotation.y = Math.PI / 2;
  53438. }
  53439. this.add(group);
  53440. });
  53441. }
  53442. createLabel(text,color){
  53443. var canvas = document.createElement("canvas");
  53444. var context = canvas.getContext("2d");
  53445. canvas.width = 256,
  53446. canvas.height = 256;
  53447. var fontSize = 120;
  53448. context.fillStyle = color; //"#00ffee";
  53449. context.font = "normal " + fontSize + "px 微软雅黑";
  53450. var textWidth = context.measureText(text).width;
  53451. context.clearRect(0,0,canvas.width,canvas.height);
  53452. context.fillText(text, (canvas.width - textWidth) / 2 , (canvas.height + fontSize) / 2);
  53453. var tex = new Texture(canvas);
  53454. tex.needsUpdate = true;
  53455. tex.minFilter = NearestFilter;//防止边缘发黑
  53456. tex.magFilter = NearestFilter;//防止边缘发黑
  53457. var sprite = new Sprite(new SpriteMaterial({
  53458. map: tex , // depthWrite:false,
  53459. }));
  53460. sprite.renderOrder = 1;//防止在透明后还是出现白矩形挡住其他mesh
  53461. sprite.scale.set(3,3,3);
  53462. return sprite
  53463. }
  53464. }
  53465. class Scene$1 extends EventDispatcher{
  53466. constructor(){
  53467. super();
  53468. this.annotations = new Annotation();
  53469. this.scene = new Scene();
  53470. //this.sceneBG = new THREE.Scene(); //用来放skybox
  53471. //this.sceneOverlay = new THREE.Scene();
  53472. this.scenePointCloud = new Scene();
  53473. this.cameraP = new PerspectiveCamera(this.fov, 1, Potree.config.view.near, Potree.config.view.near);
  53474. this.cameraO = new OrthographicCamera(-1, 1, 1, -1, Potree.config.view.near, Potree.settings.cameraFar);
  53475. this.cameraP.limitFar = true;//add
  53476. this.cameraVR = new PerspectiveCamera();
  53477. this.cameraBG = new Camera();
  53478. this.cameraScreenSpace = new OrthographicCamera(-1, 1, 1, -1, 0.1, 10);
  53479. this.cameraMode = CameraMode.PERSPECTIVE;
  53480. this.overrideCamera = null;
  53481. this.pointclouds = [];
  53482. this.measurements = [];
  53483. this.profiles = [];
  53484. this.volumes = [];
  53485. this.polygonClipVolumes = [];
  53486. this.cameraAnimations = [];
  53487. this.orientedImages = [];
  53488. this.images360 = [];
  53489. this.geopackages = [];
  53490. this.fpControls = null;
  53491. this.orbitControls = null;
  53492. this.earthControls = null;
  53493. this.geoControls = null;
  53494. this.deviceControls = null;
  53495. this.inputHandler = null;
  53496. this.view = new View();
  53497. this.directionalLight = null;
  53498. this.initialize();
  53499. //-------------
  53500. this.axisArrow = new Axis();
  53501. this.scene.add(this.axisArrow);
  53502. if(!Potree.settings.isDebug)this.axisArrow.visible = false;
  53503. viewer.setObjectLayers(this.axisArrow, 'bothMapAndScene' );
  53504. this.tags = new Object3D;
  53505. this.scene.add(this.tags);
  53506. }
  53507. estimateHeightAt (position) {
  53508. let height = null;
  53509. let fromSpacing = Infinity;
  53510. for (let pointcloud of this.pointclouds) {
  53511. if (pointcloud.root.geometryNode === undefined) {
  53512. continue;
  53513. }
  53514. let pHeight = null;
  53515. let pFromSpacing = Infinity;
  53516. let lpos = position.clone().sub(pointcloud.position);
  53517. lpos.z = 0;
  53518. let ray = new Ray(lpos, new Vector3(0, 0, 1));
  53519. let stack = [pointcloud.root];
  53520. while (stack.length > 0) {
  53521. let node = stack.pop();
  53522. let box = node.getBoundingBox();
  53523. let inside = ray.intersectBox(box);
  53524. if (!inside) {
  53525. continue;
  53526. }
  53527. let h = node.geometryNode.mean.z +
  53528. pointcloud.position.z +
  53529. node.geometryNode.boundingBox.min.z;
  53530. if (node.geometryNode.spacing <= pFromSpacing) {
  53531. pHeight = h;
  53532. pFromSpacing = node.geometryNode.spacing;
  53533. }
  53534. for (let index of Object.keys(node.children)) {
  53535. let child = node.children[index];
  53536. if (child.geometryNode) {
  53537. stack.push(node.children[index]);
  53538. }
  53539. }
  53540. }
  53541. if (height === null || pFromSpacing < fromSpacing) {
  53542. height = pHeight;
  53543. fromSpacing = pFromSpacing;
  53544. }
  53545. }
  53546. return height;
  53547. }
  53548. getBoundingBox(pointclouds = this.pointclouds){
  53549. let box = new Box3();
  53550. this.scenePointCloud.updateMatrixWorld(true);
  53551. this.referenceFrame.updateMatrixWorld(true);
  53552. for (let pointcloud of pointclouds) {
  53553. pointcloud.updateMatrixWorld(true);
  53554. let pointcloudBox = pointcloud.pcoGeometry.tightBoundingBox ? pointcloud.pcoGeometry.tightBoundingBox : pointcloud.boundingBox;
  53555. let boxWorld = Utils.computeTransformedBoundingBox(pointcloudBox, pointcloud.matrixWorld);
  53556. box.union(boxWorld);
  53557. }
  53558. return box;
  53559. }
  53560. addPointCloud (pointcloud) {
  53561. this.pointclouds.push(pointcloud);
  53562. this.scenePointCloud.add(pointcloud);
  53563. this.dispatchEvent({
  53564. type: 'pointcloud_added',
  53565. pointcloud: pointcloud
  53566. });
  53567. }
  53568. //add:
  53569. removePointCloud (pointcloud) {
  53570. let index = this.pointclouds.indexOf(pointcloud);
  53571. if(index == -1)return
  53572. this.pointclouds.splice(index, 1);
  53573. this.scenePointCloud.remove(pointcloud);
  53574. pointcloud.panos.forEach(pano=>{
  53575. pano.dispose();
  53576. });
  53577. }
  53578. addVolume (volume) {
  53579. this.volumes.push(volume);
  53580. this.dispatchEvent({
  53581. 'type': 'volume_added',
  53582. 'scene': this,
  53583. 'volume': volume
  53584. });
  53585. }
  53586. addOrientedImages(images){
  53587. this.orientedImages.push(images);
  53588. this.scene.add(images.node);
  53589. this.dispatchEvent({
  53590. 'type': 'oriented_images_added',
  53591. 'scene': this,
  53592. 'images': images
  53593. });
  53594. };
  53595. removeOrientedImages(images){
  53596. let index = this.orientedImages.indexOf(images);
  53597. if (index > -1) {
  53598. this.orientedImages.splice(index, 1);
  53599. this.dispatchEvent({
  53600. 'type': 'oriented_images_removed',
  53601. 'scene': this,
  53602. 'images': images
  53603. });
  53604. }
  53605. };
  53606. add360Images(images){
  53607. this.images360.push(images);
  53608. this.scene.add(images.node);
  53609. //this.sceneOverlay.add(images.node);//add
  53610. this.dispatchEvent({
  53611. 'type': '360_images_added',
  53612. 'scene': this,
  53613. 'images': images
  53614. });
  53615. }
  53616. remove360Images(images){
  53617. let index = this.images360.indexOf(images);
  53618. if (index > -1) {
  53619. this.images360.splice(index, 1);
  53620. this.dispatchEvent({
  53621. 'type': '360_images_removed',
  53622. 'scene': this,
  53623. 'images': images
  53624. });
  53625. }
  53626. }
  53627. addGeopackage(geopackage){
  53628. this.geopackages.push(geopackage);
  53629. this.scene.add(geopackage.node);
  53630. this.dispatchEvent({
  53631. 'type': 'geopackage_added',
  53632. 'scene': this,
  53633. 'geopackage': geopackage
  53634. });
  53635. };
  53636. removeGeopackage(geopackage){
  53637. let index = this.geopackages.indexOf(geopackage);
  53638. if (index > -1) {
  53639. this.geopackages.splice(index, 1);
  53640. this.dispatchEvent({
  53641. 'type': 'geopackage_removed',
  53642. 'scene': this,
  53643. 'geopackage': geopackage
  53644. });
  53645. }
  53646. };
  53647. removeVolume (volume) {
  53648. let index = this.volumes.indexOf(volume);
  53649. if (index > -1) {
  53650. this.volumes.splice(index, 1);
  53651. this.dispatchEvent({
  53652. 'type': 'volume_removed',
  53653. 'scene': this,
  53654. 'volume': volume
  53655. });
  53656. }
  53657. };
  53658. addCameraAnimation(animation) {
  53659. this.cameraAnimations.push(animation);
  53660. this.dispatchEvent({
  53661. 'type': 'camera_animation_added',
  53662. 'scene': this,
  53663. 'animation': animation
  53664. });
  53665. };
  53666. removeCameraAnimation(animation){
  53667. let index = this.cameraAnimations.indexOf(animation);
  53668. if (index > -1) {
  53669. this.cameraAnimations.splice(index, 1);
  53670. this.dispatchEvent({
  53671. 'type': 'camera_animation_removed',
  53672. 'scene': this,
  53673. 'animation': animation
  53674. });
  53675. }
  53676. };
  53677. addPolygonClipVolume(volume){
  53678. this.polygonClipVolumes.push(volume);
  53679. this.dispatchEvent({
  53680. "type": "polygon_clip_volume_added",
  53681. "scene": this,
  53682. "volume": volume
  53683. });
  53684. };
  53685. removePolygonClipVolume(volume){
  53686. let index = this.polygonClipVolumes.indexOf(volume);
  53687. if (index > -1) {
  53688. this.polygonClipVolumes.splice(index, 1);
  53689. this.dispatchEvent({
  53690. "type": "polygon_clip_volume_removed",
  53691. "scene": this,
  53692. "volume": volume
  53693. });
  53694. }
  53695. };
  53696. addMeasurement(measurement){
  53697. measurement.lengthUnit = this.lengthUnit;
  53698. measurement.lengthUnitDisplay = this.lengthUnitDisplay;
  53699. this.measurements.push(measurement);
  53700. this.dispatchEvent({
  53701. 'type': 'measurement_added',
  53702. 'scene': this,
  53703. 'measurement': measurement
  53704. });
  53705. };
  53706. removeMeasurement (measurement) {
  53707. let index = this.measurements.indexOf(measurement);
  53708. if (index > -1) {
  53709. this.measurements.splice(index, 1);
  53710. this.dispatchEvent({
  53711. 'type': 'measurement_removed',
  53712. 'scene': this,
  53713. 'measurement': measurement
  53714. });
  53715. }
  53716. }
  53717. addProfile (profile) {
  53718. this.profiles.push(profile);
  53719. this.dispatchEvent({
  53720. 'type': 'profile_added',
  53721. 'scene': this,
  53722. 'profile': profile
  53723. });
  53724. }
  53725. removeProfile (profile) {
  53726. let index = this.profiles.indexOf(profile);
  53727. if (index > -1) {
  53728. this.profiles.splice(index, 1);
  53729. this.dispatchEvent({
  53730. 'type': 'profile_removed',
  53731. 'scene': this,
  53732. 'profile': profile
  53733. });
  53734. }
  53735. }
  53736. removeAllMeasurements () {
  53737. while (this.measurements.length > 0) {
  53738. this.removeMeasurement(this.measurements[0]);
  53739. }
  53740. while (this.profiles.length > 0) {
  53741. this.removeProfile(this.profiles[0]);
  53742. }
  53743. while (this.volumes.length > 0) {
  53744. this.removeVolume(this.volumes[0]);
  53745. }
  53746. }
  53747. removeAllClipVolumes(){
  53748. let clipVolumes = this.volumes.filter(volume => volume.clip === true);
  53749. for(let clipVolume of clipVolumes){
  53750. this.removeVolume(clipVolume);
  53751. }
  53752. while(this.polygonClipVolumes.length > 0){
  53753. this.removePolygonClipVolume(this.polygonClipVolumes[0]);
  53754. }
  53755. }
  53756. getActiveCamera() {
  53757. return viewer.mainViewport.camera
  53758. if(this.overrideCamera){
  53759. return this.overrideCamera;
  53760. }
  53761. if(this.cameraMode === CameraMode.PERSPECTIVE){
  53762. return this.cameraP;
  53763. }else if(this.cameraMode === CameraMode.ORTHOGRAPHIC){
  53764. return this.cameraO;
  53765. }else if(this.cameraMode === CameraMode.VR){
  53766. return this.cameraVR;
  53767. }
  53768. return null;
  53769. }
  53770. initialize(){
  53771. this.referenceFrame = new Object3D();
  53772. this.referenceFrame.matrixAutoUpdate = false;
  53773. this.scenePointCloud.add(this.referenceFrame);
  53774. if(window.axisYup){
  53775. }else {
  53776. this.cameraP.up.set(0, 0, 1);
  53777. this.cameraO.up.set(0, 0, 1);
  53778. }
  53779. this.cameraP.position.set(1000, 1000, 1000);
  53780. this.cameraO.position.set(1000, 1000, 1000);
  53781. //this.camera.rotation.y = -Math.PI / 4;
  53782. //this.camera.rotation.x = -Math.PI / 6;
  53783. this.cameraScreenSpace.lookAt(new Vector3(0, 0, 0), new Vector3(0, 0, -1), new Vector3(0, 1, 0));
  53784. this.directionalLight = new DirectionalLight( 0xffffff, 0.5 );
  53785. this.directionalLight.position.set( 10, 10, 10 );
  53786. this.directionalLight.lookAt( new Vector3(0, 0, 0));
  53787. this.scenePointCloud.add( this.directionalLight );
  53788. let light = new AmbientLight( 0x555555 ); // soft white light
  53789. this.scenePointCloud.add( light );
  53790. //add:------给空间模型的box 或其他obj------
  53791. let light2 = new AmbientLight( 16777215, 1 );
  53792. viewer.setObjectLayers(light2, 'bothMapAndScene');
  53793. this.scene.add(light2);
  53794. let light3 = new DirectionalLight( 16777215, 1);
  53795. light3.position.set( 10, 10, 10 );
  53796. light3.lookAt( new Vector3(0, 0, 0));
  53797. viewer.setObjectLayers(light3, 'bothMapAndScene');
  53798. this.scene.add(light3);
  53799. //--------------------------------------------
  53800. { // background
  53801. let texture = Utils.createBackgroundTexture(512, 512);
  53802. texture.minFilter = texture.magFilter = NearestFilter;
  53803. texture.minFilter = texture.magFilter = LinearFilter;
  53804. let bg = new Mesh(
  53805. new PlaneBufferGeometry(2, 2, 1),
  53806. new MeshBasicMaterial({
  53807. map: texture
  53808. })
  53809. );
  53810. bg.material.depthTest = false;
  53811. bg.material.depthWrite = false;
  53812. bg.name = 'bg';
  53813. //this.sceneBG.add(bg);
  53814. this.scene.add(bg);
  53815. bg.layers.set(Potree.config.renderLayers.bg);
  53816. }
  53817. { // background color
  53818. let bg2 = new Mesh(
  53819. new PlaneBufferGeometry(2, 2, 1),
  53820. new MeshBasicMaterial({
  53821. transparent : true
  53822. })
  53823. );
  53824. bg2.material.depthTest = false;
  53825. bg2.material.depthWrite = false;
  53826. bg2.name = 'bg2';
  53827. this.scene.add(bg2);
  53828. bg2.layers.set(Potree.config.renderLayers.bg2);
  53829. this.bg2 = bg2;
  53830. }
  53831. // { // lights
  53832. // {
  53833. // let light = new THREE.DirectionalLight(0xffffff);
  53834. // light.position.set(10, 10, 1);
  53835. // light.target.position.set(0, 0, 0);
  53836. // this.scene.add(light);
  53837. // }
  53838. // {
  53839. // let light = new THREE.DirectionalLight(0xffffff);
  53840. // light.position.set(-10, 10, 1);
  53841. // light.target.position.set(0, 0, 0);
  53842. // this.scene.add(light);
  53843. // }
  53844. // {
  53845. // let light = new THREE.DirectionalLight(0xffffff);
  53846. // light.position.set(0, -10, 20);
  53847. // light.target.position.set(0, 0, 0);
  53848. // this.scene.add(light);
  53849. // }
  53850. // }
  53851. }
  53852. /* switchBg(type){//add
  53853. let bg,;
  53854. if(type == 'gradient'){
  53855. bg
  53856. }else if(type == 'overlayColor'){
  53857. }
  53858. } */
  53859. addAnnotation(position, args = {}){
  53860. if(position instanceof Array){
  53861. args.position = new Vector3().fromArray(position);
  53862. } else if (position.x != null) {
  53863. args.position = position;
  53864. }
  53865. let annotation = new Annotation(args);
  53866. this.annotations.add(annotation);
  53867. return annotation;
  53868. }
  53869. getAnnotations () {
  53870. return this.annotations;
  53871. };
  53872. removeAnnotation(annotationToRemove) {
  53873. this.annotations.remove(annotationToRemove);
  53874. }
  53875. };
  53876. // http://epsg.io/
  53877. //see http://openlayers.org/
  53878. proj4.defs([
  53879. ['UTM10N', '+proj=utm +zone=10 +ellps=GRS80 +datum=NAD83 +units=m +no_defs'],
  53880. ['EPSG:6339', '+proj=utm +zone=10 +ellps=GRS80 +units=m +no_defs'],
  53881. ['EPSG:6340', '+proj=utm +zone=11 +ellps=GRS80 +units=m +no_defs'],
  53882. ['EPSG:6341', '+proj=utm +zone=12 +ellps=GRS80 +units=m +no_defs'],
  53883. ['EPSG:6342', '+proj=utm +zone=13 +ellps=GRS80 +units=m +no_defs'],
  53884. ['EPSG:6343', '+proj=utm +zone=14 +ellps=GRS80 +units=m +no_defs'],
  53885. ['EPSG:6344', '+proj=utm +zone=15 +ellps=GRS80 +units=m +no_defs'],
  53886. ['EPSG:6345', '+proj=utm +zone=16 +ellps=GRS80 +units=m +no_defs'],
  53887. ['EPSG:6346', '+proj=utm +zone=17 +ellps=GRS80 +units=m +no_defs'],
  53888. ['EPSG:6347', '+proj=utm +zone=18 +ellps=GRS80 +units=m +no_defs'],
  53889. ['EPSG:6348', '+proj=utm +zone=19 +ellps=GRS80 +units=m +no_defs'],
  53890. ['EPSG:26910', '+proj=utm +zone=10 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  53891. ['EPSG:26911', '+proj=utm +zone=11 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  53892. ['EPSG:26912', '+proj=utm +zone=12 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  53893. ['EPSG:26913', '+proj=utm +zone=13 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  53894. ['EPSG:26914', '+proj=utm +zone=14 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  53895. ['EPSG:26915', '+proj=utm +zone=15 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  53896. ['EPSG:26916', '+proj=utm +zone=16 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  53897. ['EPSG:26917', '+proj=utm +zone=17 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  53898. ['EPSG:26918', '+proj=utm +zone=18 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  53899. ['EPSG:26919', '+proj=utm +zone=19 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs '],
  53900. ]);
  53901. class MapView{
  53902. constructor (viewer) {
  53903. this.viewer = viewer;
  53904. this.webMapService = 'WMTS';
  53905. this.mapProjectionName = 'EPSG:3857'; //navvis也是这个
  53906. this.mapProjection = proj4.defs(this.mapProjectionName);
  53907. this.sceneProjection = null;
  53908. this.extentsLayer = null;
  53909. this.cameraLayer = null;
  53910. this.toolLayer = null;
  53911. this.sourcesLayer = null;
  53912. this.sourcesLabelLayer = null;
  53913. this.images360Layer = null;
  53914. this.enabled = false;
  53915. this.createAnnotationStyle = (text) => {
  53916. return [
  53917. new ol.style.Style({
  53918. image: new ol.style.Circle({
  53919. radius: 10,
  53920. stroke: new ol.style.Stroke({
  53921. color: [255, 255, 255, 0.5],
  53922. width: 2
  53923. }),
  53924. fill: new ol.style.Fill({
  53925. color: [0, 0, 0, 0.5]
  53926. })
  53927. })
  53928. })
  53929. ];
  53930. };
  53931. this.createLabelStyle = (text) => {
  53932. let style = new ol.style.Style({
  53933. image: new ol.style.Circle({
  53934. radius: 6,
  53935. stroke: new ol.style.Stroke({
  53936. color: 'white',
  53937. width: 2
  53938. }),
  53939. fill: new ol.style.Fill({
  53940. color: 'green'
  53941. })
  53942. }),
  53943. text: new ol.style.Text({
  53944. font: '12px helvetica,sans-serif',
  53945. text: text,
  53946. fill: new ol.style.Fill({
  53947. color: '#000'
  53948. }),
  53949. stroke: new ol.style.Stroke({
  53950. color: '#fff',
  53951. width: 2
  53952. })
  53953. })
  53954. });
  53955. return style;
  53956. };
  53957. }
  53958. showSources (show) {
  53959. this.sourcesLayer.setVisible(show);
  53960. this.sourcesLabelLayer.setVisible(show);
  53961. }
  53962. init () {
  53963. if(typeof ol === "undefined"){
  53964. return;
  53965. }
  53966. this.elMap = $('#potree_map');
  53967. this.elMap.draggable({ handle: $('#potree_map_header') });
  53968. this.elMap.resizable();
  53969. this.elTooltip = $(`<div style="position: relative; z-index: 100"></div>`);
  53970. this.elMap.append(this.elTooltip);
  53971. let extentsLayer = this.getExtentsLayer();
  53972. let cameraLayer = this.getCameraLayer();
  53973. this.getToolLayer();
  53974. let sourcesLayer = this.getSourcesLayer();
  53975. this.images360Layer = this.getImages360Layer();
  53976. this.getSourcesLabelLayer();
  53977. this.getAnnotationsLayer();
  53978. let mousePositionControl = new ol.control.MousePosition({
  53979. coordinateFormat: ol.coordinate.createStringXY(5),
  53980. projection: 'EPSG:4326',
  53981. undefinedHTML: '&nbsp;'
  53982. });
  53983. let _this = this;
  53984. let DownloadSelectionControl = function (optOptions) {
  53985. let options = optOptions || {};
  53986. // TOGGLE TILES
  53987. let btToggleTiles = document.createElement('button');
  53988. btToggleTiles.innerHTML = 'T';
  53989. btToggleTiles.addEventListener('click', () => {
  53990. let visible = sourcesLayer.getVisible();
  53991. _this.showSources(!visible);
  53992. }, false);
  53993. btToggleTiles.style.float = 'left';
  53994. btToggleTiles.title = 'show / hide tiles';
  53995. // DOWNLOAD SELECTED TILES
  53996. let link = document.createElement('a');
  53997. link.href = '#';
  53998. link.download = 'list.txt';
  53999. link.style.float = 'left';
  54000. let button = document.createElement('button');
  54001. button.innerHTML = 'D';
  54002. link.appendChild(button);
  54003. let handleDownload = (e) => {
  54004. let features = selectedFeatures.getArray();
  54005. let url = [document.location.protocol, '//', document.location.host, document.location.pathname].join('');
  54006. if (features.length === 0) {
  54007. alert('No tiles were selected. Select area with ctrl + left mouse button!');
  54008. e.preventDefault();
  54009. e.stopImmediatePropagation();
  54010. return false;
  54011. } else if (features.length === 1) {
  54012. let feature = features[0];
  54013. if (feature.source) {
  54014. let cloudjsurl = feature.pointcloud.pcoGeometry.url;
  54015. let sourceurl = new URL(url + '/../' + cloudjsurl + '/../source/' + feature.source.name);
  54016. link.href = sourceurl.href;
  54017. link.download = feature.source.name;
  54018. }
  54019. } else {
  54020. let content = '';
  54021. for (let i = 0; i < features.length; i++) {
  54022. let feature = features[i];
  54023. if (feature.source) {
  54024. let cloudjsurl = feature.pointcloud.pcoGeometry.url;
  54025. let sourceurl = new URL(url + '/../' + cloudjsurl + '/../source/' + feature.source.name);
  54026. content += sourceurl.href + '\n';
  54027. }
  54028. }
  54029. let uri = 'data:application/octet-stream;base64,' + btoa(content);
  54030. link.href = uri;
  54031. link.download = 'list_of_files.txt';
  54032. }
  54033. };
  54034. button.addEventListener('click', handleDownload, false);
  54035. // assemble container
  54036. let element = document.createElement('div');
  54037. element.className = 'ol-unselectable ol-control';
  54038. element.appendChild(link);
  54039. element.appendChild(btToggleTiles);
  54040. element.style.bottom = '0.5em';
  54041. element.style.left = '0.5em';
  54042. element.title = 'Download file or list of selected tiles. Select tile with left mouse button or area using ctrl + left mouse.';
  54043. ol.control.Control.call(this, {
  54044. element: element,
  54045. target: options.target
  54046. });
  54047. };
  54048. ol.inherits(DownloadSelectionControl, ol.control.Control);
  54049. this.map = new ol.Map({
  54050. controls: ol.control.defaults({
  54051. attributionOptions: ({
  54052. collapsible: false
  54053. })
  54054. }).extend([
  54055. // this.controls.zoomToExtent,
  54056. new DownloadSelectionControl(),
  54057. mousePositionControl
  54058. ]),
  54059. layers: [
  54060. new ol.layer.Tile({source: new ol.source.OSM()}),
  54061. this.toolLayer,
  54062. this.annotationsLayer,
  54063. this.sourcesLayer,
  54064. this.sourcesLabelLayer,
  54065. this.images360Layer,
  54066. extentsLayer,
  54067. cameraLayer
  54068. ],
  54069. target: 'potree_map_content',
  54070. view: new ol.View({
  54071. center: this.olCenter,
  54072. zoom: 9
  54073. })
  54074. });
  54075. // DRAGBOX / SELECTION
  54076. this.dragBoxLayer = new ol.layer.Vector({
  54077. source: new ol.source.Vector({}),
  54078. style: new ol.style.Style({
  54079. stroke: new ol.style.Stroke({
  54080. color: 'rgba(0, 0, 255, 1)',
  54081. width: 2
  54082. })
  54083. })
  54084. });
  54085. this.map.addLayer(this.dragBoxLayer);
  54086. let select = new ol.interaction.Select();
  54087. this.map.addInteraction(select);
  54088. let selectedFeatures = select.getFeatures();
  54089. let dragBox = new ol.interaction.DragBox({
  54090. condition: ol.events.condition.platformModifierKeyOnly
  54091. });
  54092. this.map.addInteraction(dragBox);
  54093. // this.map.on('pointermove', evt => {
  54094. // let pixel = evt.pixel;
  54095. // let feature = this.map.forEachFeatureAtPixel(pixel, function (feature) {
  54096. // return feature;
  54097. // });
  54098. // // console.log(feature);
  54099. // // this.elTooltip.css("display", feature ? '' : 'none');
  54100. // this.elTooltip.css('display', 'none');
  54101. // if (feature && feature.onHover) {
  54102. // feature.onHover(evt);
  54103. // // overlay.setPosition(evt.coordinate);
  54104. // // tooltip.innerHTML = feature.get('name');
  54105. // }
  54106. // });
  54107. this.map.on('click', evt => {
  54108. let pixel = evt.pixel;
  54109. let feature = this.map.forEachFeatureAtPixel(pixel, function (feature) {
  54110. return feature;
  54111. });
  54112. if (feature && feature.onClick) {
  54113. feature.onClick(evt);
  54114. }
  54115. });
  54116. dragBox.on('boxend', (e) => {
  54117. // features that intersect the box are added to the collection of
  54118. // selected features, and their names are displayed in the "info"
  54119. // div
  54120. let extent = dragBox.getGeometry().getExtent();
  54121. this.getSourcesLayer().getSource().forEachFeatureIntersectingExtent(extent, (feature) => {
  54122. selectedFeatures.push(feature);
  54123. });
  54124. });
  54125. // clear selection when drawing a new box and when clicking on the map
  54126. dragBox.on('boxstart', (e) => {
  54127. selectedFeatures.clear();
  54128. });
  54129. this.map.on('click', () => {
  54130. selectedFeatures.clear();
  54131. });
  54132. this.viewer.addEventListener('scene_changed', e => {
  54133. this.setScene(e.scene);
  54134. });
  54135. this.onPointcloudAdded = e => {
  54136. this.load(e.pointcloud);
  54137. };
  54138. this.on360ImagesAdded = e => {
  54139. this.addImages360(e.images);
  54140. };
  54141. this.onAnnotationAdded = e => {
  54142. if (!this.sceneProjection) {
  54143. return;
  54144. }
  54145. let annotation = e.annotation;
  54146. let position = annotation.position;
  54147. let mapPos = this.toMap.forward([position.x, position.y]);
  54148. let feature = new ol.Feature({
  54149. geometry: new ol.geom.Point(mapPos),
  54150. name: annotation.title
  54151. });
  54152. feature.setStyle(this.createAnnotationStyle(annotation.title));
  54153. feature.onHover = evt => {
  54154. let coordinates = feature.getGeometry().getCoordinates();
  54155. let p = this.map.getPixelFromCoordinate(coordinates);
  54156. this.elTooltip.html(annotation.title);
  54157. this.elTooltip.css('display', '');
  54158. this.elTooltip.css('left', `${p[0]}px`);
  54159. this.elTooltip.css('top', `${p[1]}px`);
  54160. };
  54161. feature.onClick = evt => {
  54162. annotation.clickTitle();
  54163. };
  54164. this.getAnnotationsLayer().getSource().addFeature(feature);
  54165. };
  54166. this.setScene(this.viewer.scene);
  54167. }
  54168. setScene (scene) {
  54169. if (this.scene === scene) {
  54170. return;
  54171. };
  54172. if (this.scene) {
  54173. this.scene.removeEventListener('pointcloud_added', this.onPointcloudAdded);
  54174. this.scene.removeEventListener('360_images_added', this.on360ImagesAdded);
  54175. this.scene.annotations.removeEventListener('annotation_added', this.onAnnotationAdded);
  54176. }
  54177. this.scene = scene;
  54178. this.scene.addEventListener('pointcloud_added', this.onPointcloudAdded);
  54179. this.scene.addEventListener('360_images_added', this.on360ImagesAdded);
  54180. this.scene.annotations.addEventListener('annotation_added', this.onAnnotationAdded);
  54181. for (let pointcloud of this.viewer.scene.pointclouds) {
  54182. this.load(pointcloud);
  54183. }
  54184. this.viewer.scene.annotations.traverseDescendants(annotation => {
  54185. this.onAnnotationAdded({annotation: annotation});
  54186. });
  54187. for(let images of this.viewer.scene.images360){
  54188. this.on360ImagesAdded({images: images});
  54189. }
  54190. }
  54191. getExtentsLayer () {
  54192. if (this.extentsLayer) {
  54193. return this.extentsLayer;
  54194. }
  54195. this.gExtent = new ol.geom.LineString([[0, 0], [0, 0]]);
  54196. let feature = new ol.Feature(this.gExtent);
  54197. let featureVector = new ol.source.Vector({
  54198. features: [feature]
  54199. });
  54200. this.extentsLayer = new ol.layer.Vector({
  54201. source: featureVector,
  54202. style: new ol.style.Style({
  54203. fill: new ol.style.Fill({
  54204. color: 'rgba(255, 255, 255, 0.2)'
  54205. }),
  54206. stroke: new ol.style.Stroke({
  54207. color: '#0000ff',
  54208. width: 2
  54209. }),
  54210. image: new ol.style.Circle({
  54211. radius: 3,
  54212. fill: new ol.style.Fill({
  54213. color: '#0000ff'
  54214. })
  54215. })
  54216. })
  54217. });
  54218. return this.extentsLayer;
  54219. }
  54220. getAnnotationsLayer () {
  54221. if (this.annotationsLayer) {
  54222. return this.annotationsLayer;
  54223. }
  54224. this.annotationsLayer = new ol.layer.Vector({
  54225. source: new ol.source.Vector({
  54226. }),
  54227. style: new ol.style.Style({
  54228. fill: new ol.style.Fill({
  54229. color: 'rgba(255, 0, 0, 1)'
  54230. }),
  54231. stroke: new ol.style.Stroke({
  54232. color: 'rgba(255, 0, 0, 1)',
  54233. width: 2
  54234. })
  54235. })
  54236. });
  54237. return this.annotationsLayer;
  54238. }
  54239. getCameraLayer () {
  54240. if (this.cameraLayer) {
  54241. return this.cameraLayer;
  54242. }
  54243. // CAMERA LAYER
  54244. this.gCamera = new ol.geom.LineString([[0, 0], [0, 0], [0, 0], [0, 0]]);
  54245. let feature = new ol.Feature(this.gCamera);
  54246. let featureVector = new ol.source.Vector({
  54247. features: [feature]
  54248. });
  54249. this.cameraLayer = new ol.layer.Vector({
  54250. source: featureVector,
  54251. style: new ol.style.Style({
  54252. stroke: new ol.style.Stroke({
  54253. color: '#0000ff',
  54254. width: 2
  54255. })
  54256. })
  54257. });
  54258. return this.cameraLayer;
  54259. }
  54260. getToolLayer () {
  54261. if (this.toolLayer) {
  54262. return this.toolLayer;
  54263. }
  54264. this.toolLayer = new ol.layer.Vector({
  54265. source: new ol.source.Vector({
  54266. }),
  54267. style: new ol.style.Style({
  54268. fill: new ol.style.Fill({
  54269. color: 'rgba(255, 0, 0, 1)'
  54270. }),
  54271. stroke: new ol.style.Stroke({
  54272. color: 'rgba(255, 0, 0, 1)',
  54273. width: 2
  54274. })
  54275. })
  54276. });
  54277. return this.toolLayer;
  54278. }
  54279. getImages360Layer(){
  54280. if(this.images360Layer){
  54281. return this.images360Layer;
  54282. }
  54283. let style = new ol.style.Style({
  54284. image: new ol.style.Circle({
  54285. radius: 4,
  54286. stroke: new ol.style.Stroke({
  54287. color: [255, 0, 0, 1],
  54288. width: 2
  54289. }),
  54290. fill: new ol.style.Fill({
  54291. color: [255, 100, 100, 1]
  54292. })
  54293. })
  54294. });
  54295. let layer = new ol.layer.Vector({
  54296. source: new ol.source.Vector({}),
  54297. style: style,
  54298. });
  54299. this.images360Layer = layer;
  54300. return this.images360Layer;
  54301. }
  54302. getSourcesLayer () {
  54303. if (this.sourcesLayer) {
  54304. return this.sourcesLayer;
  54305. }
  54306. this.sourcesLayer = new ol.layer.Vector({
  54307. source: new ol.source.Vector({}),
  54308. style: new ol.style.Style({
  54309. fill: new ol.style.Fill({
  54310. color: 'rgba(0, 0, 150, 0.1)'
  54311. }),
  54312. stroke: new ol.style.Stroke({
  54313. color: 'rgba(0, 0, 150, 1)',
  54314. width: 1
  54315. })
  54316. })
  54317. });
  54318. return this.sourcesLayer;
  54319. }
  54320. getSourcesLabelLayer () {
  54321. if (this.sourcesLabelLayer) {
  54322. return this.sourcesLabelLayer;
  54323. }
  54324. this.sourcesLabelLayer = new ol.layer.Vector({
  54325. source: new ol.source.Vector({
  54326. }),
  54327. style: new ol.style.Style({
  54328. fill: new ol.style.Fill({
  54329. color: 'rgba(255, 0, 0, 0.1)'
  54330. }),
  54331. stroke: new ol.style.Stroke({
  54332. color: 'rgba(255, 0, 0, 1)',
  54333. width: 2
  54334. })
  54335. }),
  54336. minResolution: 0.01,
  54337. maxResolution: 20
  54338. });
  54339. return this.sourcesLabelLayer;
  54340. }
  54341. setSceneProjection (sceneProjection) {
  54342. this.sceneProjection = sceneProjection;
  54343. this.toMap = proj4(this.sceneProjection, this.mapProjection);
  54344. this.toScene = proj4(this.mapProjection, this.sceneProjection);
  54345. };
  54346. getMapExtent () {
  54347. let bb = this.viewer.getBoundingBox();
  54348. let bottomLeft = this.toMap.forward([bb.min.x, bb.min.y]);
  54349. let bottomRight = this.toMap.forward([bb.max.x, bb.min.y]);
  54350. let topRight = this.toMap.forward([bb.max.x, bb.max.y]);
  54351. let topLeft = this.toMap.forward([bb.min.x, bb.max.y]);
  54352. let extent = {
  54353. bottomLeft: bottomLeft,
  54354. bottomRight: bottomRight,
  54355. topRight: topRight,
  54356. topLeft: topLeft
  54357. };
  54358. return extent;
  54359. };
  54360. getMapCenter () {
  54361. let mapExtent = this.getMapExtent();
  54362. let mapCenter = [
  54363. (mapExtent.bottomLeft[0] + mapExtent.topRight[0]) / 2,
  54364. (mapExtent.bottomLeft[1] + mapExtent.topRight[1]) / 2
  54365. ];
  54366. return mapCenter;
  54367. };
  54368. updateToolDrawings () {
  54369. this.toolLayer.getSource().clear();
  54370. let profiles = this.viewer.profileTool.profiles;
  54371. for (let i = 0; i < profiles.length; i++) {
  54372. let profile = profiles[i];
  54373. let coordinates = [];
  54374. for (let j = 0; j < profile.points.length; j++) {
  54375. let point = profile.points[j];
  54376. let pointMap = this.toMap.forward([point.x, point.y]);
  54377. coordinates.push(pointMap);
  54378. }
  54379. let line = new ol.geom.LineString(coordinates);
  54380. let feature = new ol.Feature(line);
  54381. this.toolLayer.getSource().addFeature(feature);
  54382. }
  54383. let measurements = this.viewer.measuringTool.measurements;
  54384. for (let i = 0; i < measurements.length; i++) {
  54385. let measurement = measurements[i];
  54386. let coordinates = [];
  54387. for (let j = 0; j < measurement.points.length; j++) {
  54388. let point = measurement.points[j].position;
  54389. let pointMap = this.toMap.forward([point.x, point.y]);
  54390. coordinates.push(pointMap);
  54391. }
  54392. if (measurement.closed && measurement.points.length > 0) {
  54393. coordinates.push(coordinates[0]);
  54394. }
  54395. let line = new ol.geom.LineString(coordinates);
  54396. let feature = new ol.Feature(line);
  54397. this.toolLayer.getSource().addFeature(feature);
  54398. }
  54399. }
  54400. addImages360(images){
  54401. let transform = this.toMap.forward;
  54402. let layer = this.getImages360Layer();
  54403. for(let pano of images.panos){
  54404. let p = transform([pano.position.x, pano.position.y]);
  54405. let feature = new ol.Feature({
  54406. 'geometry': new ol.geom.Point(p),
  54407. });
  54408. feature.onClick = () => {
  54409. //images.focus(pano);
  54410. images.flyToPano({
  54411. pano
  54412. });
  54413. };
  54414. layer.getSource().addFeature(feature);
  54415. }
  54416. }
  54417. async load (pointcloud) {
  54418. if (!pointcloud) {
  54419. return;
  54420. }
  54421. /* if (!pointcloud.projection) {
  54422. return;
  54423. }
  54424. */
  54425. if (!this.sceneProjection) {
  54426. try {
  54427. this.setSceneProjection(proj4.defs("NAVVIS:TMERC") || pointcloud.projection);
  54428. }catch (e) {
  54429. console.log('Failed projection:', e);
  54430. if (pointcloud.fallbackProjection) {
  54431. try {
  54432. console.log('Trying fallback projection...');
  54433. this.setSceneProjection(pointcloud.fallbackProjection);
  54434. console.log('Set projection from fallback');
  54435. }catch (e) {
  54436. console.log('Failed fallback projection:', e);
  54437. return;
  54438. }
  54439. }else {
  54440. return;
  54441. };
  54442. }
  54443. }
  54444. let mapExtent = this.getMapExtent();
  54445. let mapCenter = this.getMapCenter();
  54446. let view = this.map.getView();
  54447. view.setCenter(mapCenter);
  54448. this.gExtent.setCoordinates([
  54449. mapExtent.bottomLeft,
  54450. mapExtent.bottomRight,
  54451. mapExtent.topRight,
  54452. mapExtent.topLeft,
  54453. mapExtent.bottomLeft
  54454. ]);
  54455. view.fit(this.gExtent, [300, 300], {
  54456. constrainResolution: false
  54457. });
  54458. if (pointcloud.pcoGeometry.type == 'ept'){
  54459. return;
  54460. }
  54461. let url = `${pointcloud.pcoGeometry.url}/../sources.json`;
  54462. //let response = await fetch(url);
  54463. fetch(url).then(async (response) => {
  54464. let data = await response.json();
  54465. let sources = data.sources;
  54466. for (let i = 0; i < sources.length; i++) {
  54467. let source = sources[i];
  54468. let name = source.name;
  54469. let bounds = source.bounds;
  54470. let mapBounds = {
  54471. min: this.toMap.forward([bounds.min[0], bounds.min[1]]),
  54472. max: this.toMap.forward([bounds.max[0], bounds.max[1]])
  54473. };
  54474. let mapCenter = [
  54475. (mapBounds.min[0] + mapBounds.max[0]) / 2,
  54476. (mapBounds.min[1] + mapBounds.max[1]) / 2
  54477. ];
  54478. let p1 = this.toMap.forward([bounds.min[0], bounds.min[1]]);
  54479. let p2 = this.toMap.forward([bounds.max[0], bounds.min[1]]);
  54480. let p3 = this.toMap.forward([bounds.max[0], bounds.max[1]]);
  54481. let p4 = this.toMap.forward([bounds.min[0], bounds.max[1]]);
  54482. // let feature = new ol.Feature({
  54483. // 'geometry': new ol.geom.LineString([p1, p2, p3, p4, p1])
  54484. // });
  54485. let feature = new ol.Feature({
  54486. 'geometry': new ol.geom.Polygon([[p1, p2, p3, p4, p1]])
  54487. });
  54488. feature.source = source;
  54489. feature.pointcloud = pointcloud;
  54490. this.getSourcesLayer().getSource().addFeature(feature);
  54491. feature = new ol.Feature({
  54492. geometry: new ol.geom.Point(mapCenter),
  54493. name: name
  54494. });
  54495. feature.setStyle(this.createLabelStyle(name));
  54496. this.sourcesLabelLayer.getSource().addFeature(feature);
  54497. }
  54498. }).catch(() => {
  54499. });
  54500. }
  54501. toggle () {
  54502. if (this.elMap.is(':visible')) {
  54503. this.elMap.css('display', 'none');
  54504. this.enabled = false;
  54505. } else {
  54506. this.elMap.css('display', 'block');
  54507. this.enabled = true;
  54508. }
  54509. }
  54510. update (delta) {
  54511. if (!this.sceneProjection) {
  54512. return;
  54513. }
  54514. let pm = $('#potree_map');
  54515. if (!this.enabled) {
  54516. return;
  54517. }
  54518. // resize
  54519. let mapSize = this.map.getSize();
  54520. let resized = (pm.width() !== mapSize[0] || pm.height() !== mapSize[1]);
  54521. if (resized) {
  54522. this.map.updateSize();
  54523. }
  54524. //
  54525. let camera = this.viewer.scene.getActiveCamera();
  54526. let scale = this.map.getView().getResolution();
  54527. let campos = camera.position;
  54528. let camdir = camera.getWorldDirection(new Vector3());
  54529. let sceneLookAt = camdir.clone().multiplyScalar(30 * scale).add(campos);
  54530. let geoPos = camera.position;
  54531. let geoLookAt = sceneLookAt;
  54532. let mapPos = new Vector2$1().fromArray(this.toMap.forward([geoPos.x, geoPos.y]));
  54533. let mapLookAt = new Vector2$1().fromArray(this.toMap.forward([geoLookAt.x, geoLookAt.y]));
  54534. let mapDir = new Vector2$1().subVectors(mapLookAt, mapPos).normalize();
  54535. mapLookAt = mapPos.clone().add(mapDir.clone().multiplyScalar(30 * scale));
  54536. let mapLength = mapPos.distanceTo(mapLookAt);
  54537. let mapSide = new Vector2$1(-mapDir.y, mapDir.x);
  54538. let p1 = mapPos.toArray();
  54539. let p2 = mapLookAt.clone().sub(mapSide.clone().multiplyScalar(0.3 * mapLength)).toArray();
  54540. let p3 = mapLookAt.clone().add(mapSide.clone().multiplyScalar(0.3 * mapLength)).toArray();
  54541. this.gCamera.setCoordinates([p1, p2, p3, p1]);
  54542. }
  54543. get sourcesVisible () {
  54544. return this.getSourcesLayer().getVisible();
  54545. }
  54546. set sourcesVisible (value) {
  54547. this.getSourcesLayer().setVisible(value);
  54548. }
  54549. }
  54550. let texLoader$1 = new TextureLoader();
  54551. texLoader$1.crossOrigin = "anonymous";
  54552. let createErrorMaterial = function() {
  54553. var t = new MeshBasicMaterial({
  54554. transparent: !0,
  54555. depthWrite: !1,
  54556. depthTest: !0,
  54557. opacity: 1,
  54558. side: DoubleSide
  54559. });
  54560. return t.color = new Color(3355443),
  54561. t
  54562. };
  54563. let tempVector = new Vector3, //sharedata
  54564. face1 = new Face3(0,1,2),
  54565. face2 = new Face3(2,3,0),
  54566. errorMaterial = createErrorMaterial(),
  54567. uv00 = new Vector2$1(0,0),
  54568. uv01 = new Vector2$1(0,1),
  54569. uv10 = new Vector2$1(1,0),
  54570. uv11 = new Vector2$1(1,1),
  54571. face1UV = [uv00, uv10, uv11],
  54572. face2UV = [uv11, uv01, uv00];
  54573. const HALF_WORLD_SIZE = 21e6;
  54574. const MAX_VERTICAL_DIST = 2;
  54575. const MAX_VERTICAL_DIST_TO_BEST = 1;
  54576. //高德坐标拾取工具 : https://lbs.amap.com/tools/picker
  54577. class MapLayer extends EventDispatcher{ // 包括了 MapLayerBase SceneLayer
  54578. constructor(viewer_, viewport){
  54579. super();
  54580. this.sceneGroup = new Object3D;
  54581. this.sceneGroup.name = "MapLayer";
  54582. this.loadingInProgress = 0;
  54583. this.maps = [];
  54584. this.frustum = new Frustum;
  54585. this.frustumMatrix = new Matrix4;
  54586. this.tileColor = /* i && i.tileColor ? i.tileColor : */new Color(16777215);
  54587. this.viewport = viewport;
  54588. this.changeViewer(viewer_);
  54589. //添加地图
  54590. var map = new TiledMapOpenStreetMap(this, this.tileColor );
  54591. this.addMap(map);
  54592. //map.setEnable(false)
  54593. /* this.on('needUpdate',()=>{
  54594. this.mapLayer.update()
  54595. })
  54596. */
  54597. }
  54598. addMapEntity(data, datasetId){
  54599. if(!data || !data[0]){
  54600. Potree.Log('平面图无数据','red');
  54601. return
  54602. }
  54603. var floorplan = new TiledMapFromEntity(this, this.tileColor, data[0] );//[0]?
  54604. if(floorplan){
  54605. floorplan.name += "_"+ datasetId;
  54606. this.addMap(floorplan);
  54607. floorplan.updateProjection();
  54608. floorplan.updateObjectGroup();
  54609. let visible = false;
  54610. if(datasetId in Potree.settings.floorplanEnables){
  54611. visible = Potree.settings.floorplanEnables[datasetId];
  54612. }else {
  54613. visible = Potree.settings.floorplanEnable;
  54614. }
  54615. if(visible){
  54616. this.needUpdate = true;
  54617. }else {
  54618. floorplan.setEnable(false);
  54619. }
  54620. this.dispatchEvent({type:'floorplanLoaded', floorplan});
  54621. }
  54622. return floorplan
  54623. }
  54624. getFloorplan(datasetId){
  54625. return this.maps.find(e=>e.name == 'floorplan'+"_"+ datasetId )
  54626. }
  54627. addMap(t){
  54628. this.maps.push(t);
  54629. //this.view.invalidateScene()
  54630. this.needUpdate = true;
  54631. }
  54632. removeMap(t){
  54633. var e = this.maps.indexOf(t);
  54634. if(e >= 0){
  54635. t.removeFromSceneGroup(this.sceneGroup);
  54636. this.maps.splice(e, 1);
  54637. }
  54638. /* this.view.invalidateScene() */
  54639. this.needUpdate = true;
  54640. this.viewer.dispatchEvent({
  54641. type:'content_changed'
  54642. });
  54643. }
  54644. changeViewer(viewer_){//add
  54645. this.viewer = viewer_;
  54646. }
  54647. initProjection(){
  54648. this.maps.forEach(map=>{
  54649. map.updateProjection();
  54650. map.updateObjectGroup();
  54651. });
  54652. }
  54653. visibilityChanged(){
  54654. if (!this.visible)
  54655. for (var t = 0, e = this.maps; t < e.length; t++){
  54656. e[t].removeFromSceneGroup(this.sceneGroup);
  54657. }
  54658. }
  54659. onAfterRenderViewport(e){
  54660. var n = this;
  54661. /* this.isVisibleInViewport(e) && (this.updateTimer || this.loadingInProgress || (this.updateTimer = window.setTimeout((function(){
  54662. n.update(e).then((function (t){
  54663. t && n.loadComplete.emit(!0)
  54664. }
  54665. )).catch(u.handleWarning)
  54666. }
  54667. ), 100))) */
  54668. }
  54669. update(){
  54670. this.needUpdate = false;
  54671. if(this.disabled || !this.maps.find(e=>!e.disabled) || !this.maps.find(e=>e.objectGroup.visible) )return //add
  54672. var e, n, i, r, o;
  54673. this.updateTimer = void 0,
  54674. e = this.viewport.camera,
  54675. n = e.projectionMatrix.clone(),
  54676. n.elements[0] /= 1.5,
  54677. n.elements[5] /= 1.5,
  54678. this.frustumMatrix.multiplyMatrices(n, e.matrixWorldInverse),
  54679. this.frustum.setFromProjectionMatrix(this.frustumMatrix),
  54680. this.frustum.planes[4].setComponents(0, 0, 0, 0),
  54681. this.frustum.planes[5].setComponents(0, 0, 0, 0),
  54682. i = !0;
  54683. for (r = 0; r < this.maps.length; r++){
  54684. var map = this.maps[r];
  54685. i = map.update(this.frustum, this.sceneGroup) && i;
  54686. }
  54687. return [2, i]
  54688. }
  54689. getAttributions(){
  54690. for (var t = {}, e = 0, n = this.maps; e < n.length; e++){
  54691. n[e].fillAttributions(t);
  54692. }
  54693. return t
  54694. }
  54695. updateProjection(){
  54696. for (var t = 0, e = this.maps; t < e.length; t++){
  54697. var n = e[t];
  54698. n.clearProjection(),
  54699. n.updateObjectGroup();
  54700. }
  54701. }
  54702. }
  54703. class TiledMapBase extends EventDispatcher{
  54704. constructor(/* t, */name, mapLayer, tileColor, projection){
  54705. super();
  54706. this.name = name;
  54707. //this.TransformService = t,
  54708. this.mapLayer = mapLayer,
  54709. this.tileColor = tileColor,
  54710. this.bias = 0;
  54711. this.zIndex = -1;
  54712. this.objectGroup = new Object3D;
  54713. this.objectGroup.name = name;
  54714. this.objectGroupAdded = !1,
  54715. this.baseTile = new MapTile(this,/* this.mapLayer, */this.objectGroup,this.tileColor),
  54716. this.isTileVisibleBox = new Box3,
  54717. this.isTileVisibleVec = new Vector3;
  54718. this.projection = projection;
  54719. this._zoomLevel = 0;//1-20
  54720. }
  54721. get zoomLevel(){
  54722. return this._zoomLevel
  54723. }
  54724. set zoomLevel(zoomLevel){
  54725. if(this._zoomLevel != zoomLevel){
  54726. this._zoomLevel = zoomLevel;
  54727. //this.dispatchEvent('zoomLevelChange',zoomLevel)
  54728. //if(this.name == 'map')console.log(zoomLevel,viewer.mapViewer.camera.zoom)
  54729. }
  54730. }
  54731. updateObjectGroup(){
  54732. this.position && this.objectGroup.position.copy(this.position),
  54733. this.quaternion && this.objectGroup.quaternion.copy(this.quaternion),
  54734. this.objectGroup.updateMatrixWorld(!0);
  54735. }
  54736. updateProjection(){
  54737. //this.transformMapToLocal || (this.transformMapToLocal = this.TransformService.getTransform(this.projection, this.TransformService.crsLocal))
  54738. if(!this.transformMapToLocal){
  54739. if(proj4.defs("NAVVIS:TMERC")){
  54740. if(this.projection == "EPSG:4550"){
  54741. this.transformMapToLocal = {
  54742. forward:(e)=>{
  54743. var a = viewer.transform.lonlatTo4550.inverse(e);
  54744. return viewer.transform.lonlatToLocal.forward(a)
  54745. },
  54746. };
  54747. }else {
  54748. this.transformMapToLocal = proj4(this.projection, "NAVVIS:TMERC");
  54749. }
  54750. //this.transformMapToLocal = proj4(this.projection, "NAVVIS:TMERC")
  54751. }
  54752. }
  54753. }
  54754. setEnable(enable){//add
  54755. if(!this.disabled == enable)return
  54756. if(enable){
  54757. console.log('setEnable',true);
  54758. }
  54759. this.disabled = !enable;
  54760. viewer.updateVisible(this.objectGroup, 'setEnable', enable);
  54761. if(!enable){
  54762. this.baseTile.remove();
  54763. }else {
  54764. this.mapLayer.needUpdate = true;
  54765. }
  54766. this.mapLayer.viewer.dispatchEvent({
  54767. type:'content_changed'
  54768. });
  54769. }
  54770. /* clearProjection(){
  54771. this.transformMapToLocal = void 0,
  54772. this.projection.name !== this.TransformService.NAVVIS_LOCAL && this.baseTile.remove()
  54773. } */
  54774. update(e, n){
  54775. var unavailable = (this.disabled || !this.objectGroup.visible);//地图即使不显示也要获得zoomlevel
  54776. if(this.name != 'map' && unavailable)return
  54777. this.updateProjection();
  54778. if(!this.transformMapToLocal)return
  54779. if (!this.isTileVisible(new Vector3(0,0,0), this.mapSizeM, e))
  54780. return this.removeFromSceneGroup(n), !0;
  54781. let viewport = this.mapLayer.viewport;
  54782. var i = new Vector3(-.5 * this.mapSizeM,0,0);
  54783. i.applyMatrix4(this.objectGroup.matrixWorld),
  54784. i.project(viewport.camera);
  54785. var o = new Vector3(.5 * this.mapSizeM,0,0);
  54786. o.applyMatrix4(this.objectGroup.matrixWorld),
  54787. o.project(viewport.camera);
  54788. var a = viewport.resolution.x
  54789. , s = viewport.resolution.y;
  54790. if (a <= 0 || s <= 0 || isNaN(i.x) || isNaN(o.x)) return !1;
  54791. i.sub(o),
  54792. i.x *= a / 2,
  54793. i.y *= s / 2;
  54794. var c = this.tileSizePx / i.length()
  54795. , level = Math.ceil(-Math.log(c) / Math.log(2) - this.bias);
  54796. level = Math.max(level, 0);
  54797. level = Math.min(level, void 0 === this.maxDepth ? 1 / 0 : this.maxDepth);
  54798. this.zoomLevel = level;//add
  54799. //console.log(level)
  54800. if(!unavailable){
  54801. this.addToSceneGroup(n);
  54802. return this.baseTile.update(this, e, level, this.mapSizeM, 0, 0, "")
  54803. }
  54804. }
  54805. isTileVisible(e, n, i){
  54806. if (n > HALF_WORLD_SIZE) return !0;
  54807. var r = .5 * n;
  54808. this.transformMapToLocal.forward(e);
  54809. this.isTileVisibleBox.makeEmpty();
  54810. this.isTileVisibleVec.set(e.x - r, e.y - r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  54811. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  54812. this.isTileVisibleVec.set(e.x - r, e.y + r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  54813. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  54814. this.isTileVisibleVec.set(e.x + r, e.y - r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  54815. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  54816. this.isTileVisibleVec.set(e.x + r, e.y + r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  54817. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  54818. return i.intersectsBox(this.isTileVisibleBox)
  54819. }
  54820. addToSceneGroup(t){
  54821. this.objectGroupAdded || (t.add(this.objectGroup),
  54822. this.objectGroupAdded = !0);
  54823. }
  54824. removeFromSceneGroup(t){
  54825. this.baseTile.remove(),
  54826. this.objectGroupAdded && (t.remove(this.objectGroup),
  54827. this.objectGroupAdded = !1);
  54828. }
  54829. }
  54830. class MapTile{
  54831. constructor(map,/* t, */ e, n){
  54832. this.map = map;
  54833. //this.mapLayer = t,
  54834. this.objectGroup = e,
  54835. this.tileColor = n,
  54836. this.meshAdded = !1,
  54837. this.textureLoaded = !1,
  54838. this.children = [];
  54839. }
  54840. update(e, n, i, r, o, a, s){
  54841. return !!this.doesNotContainTilesToBeDisplayed(e) || (0 === i ? this.updateTile(e, r, o, a) : this.updateSubTiles(e, n, i, r, o, a, s))
  54842. }
  54843. doesNotContainTilesToBeDisplayed(t){
  54844. return t.tilePresenceMap && t.tilePresenceMap.empty
  54845. }
  54846. updateTile(t, e, n, i){
  54847. if(!this.mesh){
  54848. this.createTileObject(t, e, n, i);
  54849. }
  54850. if(!this.meshAdded){
  54851. this.objectGroup.add(this.mesh);
  54852. this.meshAdded = !0;
  54853. }
  54854. if(this.textureLoaded){
  54855. this.removeChildren();
  54856. }
  54857. return this.textureLoaded
  54858. }
  54859. updateSubTiles(entity, n, level, o, a, s, c){
  54860. 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){
  54861. var h = c + p.toString(10);
  54862. //一级(512):0 1 2 3分别为左上、右上、左下、右下。二级(1024)就是把一级的每一块分裂,如00 01 02 03分别是0的左上、右上、左下、右下……
  54863. /* if(entity.name == 'floorplan'){
  54864. console.log(1)
  54865. } */
  54866. if (!entity.tilePresenceMap || entity.tilePresenceMap[h]){
  54867. //去掉判断,直接显示
  54868. var f = a + u[p]
  54869. , m = s + d[p];
  54870. tempVector.set(f, m, 0);
  54871. if (entity.isTileVisible(tempVector, .5 * o, n)){
  54872. this.children[p] || (this.children[p] = new MapTile(this.map, this.objectGroup,this.tileColor));
  54873. l = this.children[p].update(entity, n, level - 1, .5 * o, f, m, h) && l;
  54874. } else {
  54875. if (this.children[p]){
  54876. this.children[p].remove();
  54877. delete this.children[p];
  54878. }
  54879. }
  54880. }
  54881. }
  54882. return l && this.removeObject3D(),
  54883. l
  54884. }
  54885. createTileObject(t, e, n, a){
  54886. var s = this;
  54887. this.mesh = this.createMesh(t.transformMapToLocal, e, n, a),
  54888. this.textureLoaded = !1;
  54889. var c = t.mapSizeM / e
  54890. , l = Math.log(c) / Math.log(2)
  54891. , u = n / e + .5 * (c - 1)
  54892. , d = -a / e + .5 * (c - 1)
  54893. , p = t.getTileUrl(Math.round(l), Math.round(u), Math.round(d));
  54894. viewer.setObjectLayers(this.mesh, 'map' );
  54895. this.mesh.renderOrder = -(1e6 - l - 100 * (t.zIndex || 0));
  54896. var h = this.mesh.material;
  54897. var loadDone = ()=>{
  54898. this.map.mapLayer.loadingInProgress--;
  54899. if(this.map.mapLayer.loadingInProgress == 0){
  54900. this.map.mapLayer.dispatchEvent('loadDone');
  54901. }
  54902. };
  54903. h.map = texLoader$1.load(p, (tex)=>{
  54904. if(this.mesh){//如果还要显示的话
  54905. this.textureLoaded = true;
  54906. this.mesh.material.opacity = 1;
  54907. //this.mapLayer.view.invalidateScene()
  54908. this.map.mapLayer.viewer.dispatchEvent({
  54909. type:'content_changed'
  54910. });
  54911. this.map.mapLayer.needUpdate = true; //表示还要继续update(以removeChildren)
  54912. }else {
  54913. tex.dispose();
  54914. }
  54915. loadDone();
  54916. } , void 0, (()=>{//error
  54917. this.textureLoaded = !0;
  54918. if(this.mesh){
  54919. this.mesh.material.dispose(); //o.disposeMeshMaterial(this.mesh)
  54920. this.mesh.material = errorMaterial;
  54921. //this.map.mapLayer.view.invalidateScene())
  54922. this.map.mapLayer.viewer.dispatchEvent({
  54923. type:'content_changed'
  54924. });
  54925. }
  54926. loadDone();
  54927. }));
  54928. h.map.anisotropy = 0,
  54929. h.map.generateMipmaps = !1,
  54930. h.map.minFilter = LinearFilter,
  54931. h.map.magFilter = LinearFilter,
  54932. this.map.mapLayer.loadingInProgress++;
  54933. }
  54934. createMesh(t, e, n, o){
  54935. var a = new Geometry;
  54936. return tempVector.set(n - e / 2, o - e / 2, 0),
  54937. a.vertices.push(new Vector3().copy(t.forward(tempVector))),
  54938. tempVector.set(n + e / 2, o - e / 2, 0),
  54939. a.vertices.push(new Vector3().copy(t.forward(tempVector))),
  54940. tempVector.set(n + e / 2, o + e / 2, 0),
  54941. a.vertices.push(new Vector3().copy(t.forward(tempVector))),
  54942. tempVector.set(n - e / 2, o + e / 2, 0),
  54943. a.vertices.push(new Vector3().copy(t.forward(tempVector))),
  54944. a.faces.push(face1),
  54945. a.faces.push(face2),
  54946. a.faceVertexUvs[0].push(face1UV),
  54947. a.faceVertexUvs[0].push(face2UV),
  54948. new Mesh(a,this.createMaterial())
  54949. }
  54950. createMaterial(){
  54951. var t = new MeshBasicMaterial({
  54952. transparent: !0,
  54953. depthWrite: !1,
  54954. depthTest: !0,
  54955. opacity: 0,
  54956. side: DoubleSide
  54957. });
  54958. return t.color = this.tileColor ? this.tileColor : new Color(16777215),
  54959. t
  54960. }
  54961. remove(){
  54962. this.removeObject3D(),
  54963. this.removeChildren();
  54964. }
  54965. removeObject3D(){
  54966. if (this.mesh){
  54967. if (this.objectGroup.remove(this.mesh),
  54968. this.textureLoaded){
  54969. var t = this.mesh.material.map;
  54970. t && t.dispose();
  54971. }
  54972. this.mesh.material.dispose(); //o.disposeMeshMaterial(this.mesh),
  54973. this.mesh.geometry.dispose();
  54974. this.mesh = void 0;
  54975. }
  54976. this.meshAdded = !1,
  54977. this.textureLoaded = !1;
  54978. }
  54979. removeChildren(){
  54980. for (var t = 0, e = this.children; t < e.length; t++){
  54981. var n = e[t];
  54982. n && (n.removeObject3D(),
  54983. n.removeChildren());
  54984. }
  54985. this.children.length = 0;
  54986. }
  54987. }
  54988. 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");
  54989. //这里地图世界的中心是不是lon:0,lat:0
  54990. class TiledMapOpenStreetMap extends TiledMapBase{
  54991. constructor(mapLayer, tileColor){
  54992. super('map', mapLayer, tileColor, /* "EPSG:4550" */ "EPSG:3857" ); //EPSG projection
  54993. //this.baseUrl = "https://wprd03.is.autonavi.com/appmaptile?style=7&x=${x}&y=${y}&z=${z}",
  54994. //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
  54995. this.baseUrl = "https://wprd04.is.autonavi.com/appmaptile?lang=zh_cn&style=7&x=${x}&y=${y}&z=${z}"; //最高只到19
  54996. this.attribution = "© PopSmart, © 高德地图",
  54997. this.tileSizePx = 256;
  54998. this.mapSizeM = 40075017;
  54999. this.maxDepth = 19;//20
  55000. this.bias = 0.5;
  55001. }
  55002. getTileUrl(t, e, n){
  55003. return this.baseUrl.replace(/\${z}/, t.toString(10)).replace(/\${x}/, e.toString(10)).replace(/\${y}/, n.toString(10))
  55004. }
  55005. fillAttributions(t){
  55006. t[this.attribution] = {
  55007. score: 50
  55008. };
  55009. }
  55010. }
  55011. class TiledMapFromEntity extends TiledMapBase{
  55012. constructor(mapLayer, tileColor, data){
  55013. super('floorplan', mapLayer, tileColor, "NAVVIS:TMERC" /* "EPSG:3857" *//* "WGS84" */); //直接就是本地坐标,没有projec
  55014. let entity = this.tiledMapEntity = this.fillFromData(data);
  55015. let time = entity.updateTime || entity.createTime;
  55016. this.tileSizePx = entity.tileSizePx,
  55017. this.mapSizeM = entity.mapSizeM,
  55018. this.maxDepth = entity.maxDepth;
  55019. this.postStamp = time ? time.replace(/[^0-9]/ig,'') : (new Date).getTime();
  55020. //this.projection = n.crsLocal,
  55021. this.zIndex = 0,
  55022. this.tilePresenceMap = this.decodeBitStream(this.tiledMapEntity.quadtree); //包含tile分裂信息,如果写错了会造成tile显示不全
  55023. }
  55024. fillFromData(e){
  55025. let data = {};
  55026. data.id = e.id;
  55027. data.globalLocation = Potree.Utils.VectorFactory.fromArray3(e.location),
  55028. data.orientation = Potree.Utils.QuaternionFactory.fromArray(e.orientation);
  55029. if(Potree.fileServer){
  55030. data.filePath = `${Potree.settings.urls.prefix}${e.file_path}`;
  55031. }else {
  55032. data.filePath = `${Potree.settings.urls.prefix}/data/${Potree.settings.number}/${e.file_path}`;
  55033. }
  55034. //if(!data.filePath.includes('building_1'))data.filePath = data.filePath.replace('building','building_1')//暂时
  55035. data.fileName = '$DEPTH/$X/$Y.png',//e.file_name,
  55036. data.type = e.type,
  55037. data.mapSizeM = e.map_size_m,
  55038. data.tileSizePx = e.tile_size_px,
  55039. data.maxDepth = e.max_depth,
  55040. data.quadtree = e.quadtree,
  55041. data.floorId = e.floor_id,
  55042. data.bundleId = e.bundle_id;
  55043. //this.computeLocalCoordinates()
  55044. return data
  55045. }
  55046. computeLocalCoordinates(){
  55047. if(proj4.defs("NAVVIS:TMERC")){
  55048. this.tiledMapEntity.location = new Vector3().copy(viewer.transform.lonlatToLocal.forward(this.tiledMapEntity.globalLocation));
  55049. }
  55050. }
  55051. updateProjection() {
  55052. super.updateProjection();
  55053. if(!this.position){
  55054. this.computeLocalCoordinates();
  55055. }
  55056. /* this.projection = this.TransformService.crsLocal,
  55057. t.prototype.updateProjection.call(this) */
  55058. }
  55059. get position(){
  55060. return this.tiledMapEntity.location
  55061. /* enumerable: !0,
  55062. configurable: !0 */
  55063. }
  55064. get quaternion(){
  55065. return this.tiledMapEntity.orientation
  55066. /* enumerable: !0,
  55067. configurable: !0 */
  55068. }
  55069. getTileUrl(t, e, n) {
  55070. 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));
  55071. return i += "?t=" + this.postStamp
  55072. //this.RestService.addAuthorizationQueryParameter(i) //????
  55073. }
  55074. fillAttributions(t) {
  55075. t.NavVis = {
  55076. score: 100
  55077. };
  55078. }
  55079. decodeBitStream(t) {
  55080. if (!t)
  55081. return {
  55082. empty: !0
  55083. };
  55084. for (var e = {}, n = [e], i = 0; i < t.length; i++) {
  55085. var r = n.shift()
  55086. , o = parseInt(t.substr(i, 1), 16);
  55087. if (1 & o) {
  55088. var a = {};
  55089. r[0] = a,
  55090. n.push(a);
  55091. }
  55092. 2 & o && (a = {},
  55093. r[1] = a,
  55094. n.push(a)),
  55095. 4 & o && (a = {},
  55096. r[2] = a,
  55097. n.push(a)),
  55098. 8 & o && (a = {},
  55099. r[3] = a,
  55100. n.push(a));
  55101. }
  55102. var s = {
  55103. empty: !0
  55104. };
  55105. return this.computeHashes(s, e, ""),
  55106. s
  55107. }
  55108. computeHashes(t, e, n) {
  55109. for (var i = 0; i < 4; i++)
  55110. e[i] && (t[n + i.toString(10)] = !0,
  55111. t.empty = !1,
  55112. this.computeHashes(t, e[i], n + i.toString(10)));
  55113. }
  55114. }
  55115. /* {
  55116. "bundle_id": 1, //t-CwfhfqJ
  55117. "file_name": "$DEPTH/$X/$Y.png",
  55118. "file_path": "data/bundle_t-CwfhfqJ/building_1/map_tiles/11",
  55119. "floor_id": 11,
  55120. "id": 1,
  55121. "location": [
  55122. 113.5957510575092,
  55123. 22.366605927999239,
  55124. 0.0
  55125. ],
  55126. "map_size_m": 61.44,
  55127. "max_depth": 3,
  55128. "orientation": [
  55129. 0.7071067811865476,
  55130. 0.0,
  55131. 0.0,
  55132. 0.7071067811865475
  55133. ],
  55134. "quadtree": "fe5f7c7fcffff7f53",
  55135. "sceneCode": "t-CwfhfqJ",
  55136. "tile_size_px": 256,
  55137. "type": "TILED_PYRAMID"
  55138. }
  55139. */
  55140. var MathLight = {};
  55141. MathLight.RADIANS_PER_DEGREE = Math.PI / 180;
  55142. MathLight.DEGREES_PER_RADIAN = 180 / Math.PI;
  55143. MathLight.Vector3 = function(e, t, i) {
  55144. this.x = e || 0,
  55145. this.y = t || 0,
  55146. this.z = i || 0;
  55147. };
  55148. MathLight.Matrix4 = function() {
  55149. this.elements = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]),
  55150. arguments.length > 0 && console.error("MathLight.Matrix4: the constructor no longer reads arguments. use .set() instead.");
  55151. };
  55152. MathLight.Matrix4.prototype = {
  55153. identity: function() {
  55154. return this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1),
  55155. this
  55156. },
  55157. copy: function(e) {
  55158. return this.elements.set(e.elements),
  55159. this
  55160. },
  55161. applyToVector3: function(e) {
  55162. var t = e.x
  55163. , i = e.y
  55164. , n = e.z
  55165. , r = this.elements;
  55166. return e.x = r[0] * t + r[4] * i + r[8] * n + r[12],
  55167. e.y = r[1] * t + r[5] * i + r[9] * n + r[13],
  55168. e.z = r[2] * t + r[6] * i + r[10] * n + r[14],
  55169. this
  55170. },
  55171. getInverse: function(e, t) {
  55172. var i = this.elements
  55173. , n = e.elements
  55174. , r = n[0]
  55175. , o = n[1]
  55176. , a = n[2]
  55177. , s = n[3]
  55178. , l = n[4]
  55179. , c = n[5]
  55180. , h = n[6]
  55181. , u = n[7]
  55182. , d = n[8]
  55183. , p = n[9]
  55184. , f = n[10]
  55185. , g = n[11]
  55186. , m = n[12]
  55187. , v = n[13]
  55188. , A = n[14]
  55189. , y = n[15]
  55190. , C = p * A * u - v * f * u + v * h * g - c * A * g - p * h * y + c * f * y
  55191. , I = m * f * u - d * A * u - m * h * g + l * A * g + d * h * y - l * f * y
  55192. , E = d * v * u - m * p * u + m * c * g - l * v * g - d * c * y + l * p * y
  55193. , b = m * p * h - d * v * h - m * c * f + l * v * f + d * c * A - l * p * A
  55194. , w = r * C + o * I + a * E + s * b;
  55195. if (0 === w) {
  55196. var _ = "MathLight.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  55197. if (t)
  55198. throw new Error(_);
  55199. return console.warn(_),
  55200. this.identity()
  55201. }
  55202. var T = 1 / w;
  55203. return i[0] = C * T,
  55204. i[1] = (v * f * s - p * A * s - v * a * g + o * A * g + p * a * y - o * f * y) * T,
  55205. i[2] = (c * A * s - v * h * s + v * a * u - o * A * u - c * a * y + o * h * y) * T,
  55206. i[3] = (p * h * s - c * f * s - p * a * u + o * f * u + c * a * g - o * h * g) * T,
  55207. i[4] = I * T,
  55208. i[5] = (d * A * s - m * f * s + m * a * g - r * A * g - d * a * y + r * f * y) * T,
  55209. i[6] = (m * h * s - l * A * s - m * a * u + r * A * u + l * a * y - r * h * y) * T,
  55210. i[7] = (l * f * s - d * h * s + d * a * u - r * f * u - l * a * g + r * h * g) * T,
  55211. i[8] = E * T,
  55212. i[9] = (m * p * s - d * v * s - m * o * g + r * v * g + d * o * y - r * p * y) * T,
  55213. i[10] = (l * v * s - m * c * s + m * o * u - r * v * u - l * o * y + r * c * y) * T,
  55214. i[11] = (d * c * s - l * p * s - d * o * u + r * p * u + l * o * g - r * c * g) * T,
  55215. i[12] = b * T,
  55216. i[13] = (d * v * a - m * p * a + m * o * f - r * v * f - d * o * A + r * p * A) * T,
  55217. i[14] = (m * c * a - l * v * a - m * o * h + r * v * h + l * o * A - r * c * A) * T,
  55218. i[15] = (l * p * a - d * c * a + d * o * h - r * p * h - l * o * f + r * c * f) * T,
  55219. this
  55220. },
  55221. makeRotationFromQuaternion: function(e) {
  55222. var t = this.elements
  55223. , i = e.x
  55224. , n = e.y
  55225. , r = e.z
  55226. , o = e.w
  55227. , a = i + i
  55228. , s = n + n
  55229. , l = r + r
  55230. , c = i * a
  55231. , h = i * s
  55232. , u = i * l
  55233. , d = n * s
  55234. , p = n * l
  55235. , f = r * l
  55236. , g = o * a
  55237. , m = o * s
  55238. , v = o * l;
  55239. return t[0] = 1 - (d + f),
  55240. t[4] = h - v,
  55241. t[8] = u + m,
  55242. t[1] = h + v,
  55243. t[5] = 1 - (c + f),
  55244. t[9] = p - g,
  55245. t[2] = u - m,
  55246. t[6] = p + g,
  55247. t[10] = 1 - (c + d),
  55248. t[3] = 0,
  55249. t[7] = 0,
  55250. t[11] = 0,
  55251. t[12] = 0,
  55252. t[13] = 0,
  55253. t[14] = 0,
  55254. t[15] = 1,
  55255. this
  55256. }
  55257. };
  55258. MathLight.Quaternion = function(e, t, i, n) {
  55259. this._x = e || 0,
  55260. this._y = t || 0,
  55261. this._z = i || 0,
  55262. this._w = void 0 !== n ? n : 1;
  55263. };
  55264. MathLight.Quaternion.prototype = {
  55265. get x() {
  55266. return this._x
  55267. },
  55268. set x(e) {
  55269. this._x = e;
  55270. },
  55271. get y() {
  55272. return this._y
  55273. },
  55274. set y(e) {
  55275. this._y = e;
  55276. },
  55277. get z() {
  55278. return this._z
  55279. },
  55280. set z(e) {
  55281. this._z = e;
  55282. },
  55283. get w() {
  55284. return this._w
  55285. },
  55286. set w(e) {
  55287. this._w = e;
  55288. },
  55289. copy: function(e) {
  55290. this._x = e.x,
  55291. this._y = e.y,
  55292. this._z = e.z,
  55293. this._w = e.w;
  55294. },
  55295. inverse: function() {
  55296. return this.conjugate().normalize()
  55297. },
  55298. conjugate: function() {
  55299. return this._x *= -1,
  55300. this._y *= -1,
  55301. this._z *= -1,
  55302. this
  55303. },
  55304. length: function() {
  55305. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w)
  55306. },
  55307. normalize: function() {
  55308. var e = this.length();
  55309. return 0 === e ? (this._x = 0,
  55310. this._y = 0,
  55311. this._z = 0,
  55312. this._w = 1) : (e = 1 / e,
  55313. this._x = this._x * e,
  55314. this._y = this._y * e,
  55315. this._z = this._z * e,
  55316. this._w = this._w * e),
  55317. this
  55318. },
  55319. setFromAxisAngle: function(e, t) {
  55320. var i = t / 2
  55321. , n = Math.sin(i);
  55322. return this._x = e.x * n,
  55323. this._y = e.y * n,
  55324. this._z = e.z * n,
  55325. this._w = Math.cos(i),
  55326. this
  55327. },
  55328. setFromUnitVectors: function() {
  55329. var e, t, i = 1e-6;
  55330. return function(n, o) {
  55331. return void 0 === e && (e = new MathLight.Vector3),
  55332. t = MathLight.dot(n, o) + 1,
  55333. t < i ? (t = 0,
  55334. 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),
  55335. this._x = e.x,
  55336. this._y = e.y,
  55337. this._z = e.z,
  55338. this._w = t,
  55339. this.normalize()
  55340. }
  55341. }(),
  55342. multiply: function(e) {
  55343. return this.multiplyQuaternions(this, e)
  55344. },
  55345. premultiply: function(e) {
  55346. return this.multiplyQuaternions(e, this)
  55347. },
  55348. multiplyQuaternions: function(e, t) {
  55349. var i = e._x
  55350. , n = e._y
  55351. , r = e._z
  55352. , o = e._w
  55353. , a = t._x
  55354. , s = t._y
  55355. , l = t._z
  55356. , c = t._w;
  55357. return this._x = i * c + o * a + n * l - r * s,
  55358. this._y = n * c + o * s + r * a - i * l,
  55359. this._z = r * c + o * l + i * s - n * a,
  55360. this._w = o * c - i * a - n * s - r * l,
  55361. this
  55362. }
  55363. };
  55364. MathLight.convertWorkshopVector = function(e) {
  55365. return new MathLight.Vector3(-e.x,e.y,e.z)
  55366. };
  55367. MathLight.convertWorkshopQuaternion = function(e) {
  55368. 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))
  55369. };
  55370. MathLight.convertWorkshopOrthoZoom = function(e) {
  55371. //return e === -1 ? -1 : e / 16 * ($('#player').width() / $('#player').height()) / n.workshopApsect
  55372. return e === -1 ? -1 : e * ($("#player").width() / $("#player").height()) ;
  55373. };
  55374. MathLight.convertWorkshopPanoramaQuaternion = function(e) {
  55375. 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))
  55376. };
  55377. MathLight.normalize = function(e) {
  55378. var t = e.x * e.x + e.y * e.y + e.z * e.z
  55379. , i = Math.sqrt(t);
  55380. e.x /= i,
  55381. e.y /= i,
  55382. e.z /= i;
  55383. };
  55384. MathLight.dot = function(e, t) {
  55385. return e.x * t.x + e.y * t.y + e.z * t.z
  55386. };
  55387. MathLight.cross = function(e, t, i) {
  55388. var n = e.x
  55389. , r = e.y
  55390. , o = e.z;
  55391. i.x = r * t.z - o * t.y,
  55392. i.y = o * t.x - n * t.z,
  55393. i.z = n * t.y - r * t.x;
  55394. };
  55395. MathLight.setVector = function(e, t, i, n) {
  55396. e.x = t,
  55397. e.y = i,
  55398. e.z = n;
  55399. };
  55400. MathLight.copyVector = function(e, t) {
  55401. t.x = e.x,
  55402. t.y = e.y,
  55403. t.z = e.z;
  55404. };
  55405. MathLight.addVector = function(e, t) {
  55406. e.x += t.x,
  55407. e.y += t.y,
  55408. e.z += t.z;
  55409. };
  55410. MathLight.subVector = function(e, t) {
  55411. e.x -= t.x,
  55412. e.y -= t.y,
  55413. e.z -= t.z;
  55414. };
  55415. MathLight.applyQuaternionToVector = function(e, t) {
  55416. var i = t.x
  55417. , n = t.y
  55418. , r = t.z
  55419. , o = e.x
  55420. , a = e.y
  55421. , s = e.z
  55422. , l = e.w
  55423. , c = l * i + a * r - s * n
  55424. , h = l * n + s * i - o * r
  55425. , u = l * r + o * n - a * i
  55426. , d = -o * i - a * n - s * r;
  55427. t.x = c * l + d * -o + h * -s - u * -a,
  55428. t.y = h * l + d * -a + u * -o - c * -s,
  55429. t.z = u * l + d * -s + c * -a - h * -o;
  55430. };
  55431. MathLight.angleBetweenVectors = function(e, t) {
  55432. return Math.acos(MathLight.dot(e, t))
  55433. };
  55434. var cameraLight = {
  55435. clampVFOV: function(currentFov, maxHFov, width, height) {//限制currentFov, 使之造成的横向fov不大于指定值maxHFov
  55436. var r = cameraLight.getHFOVFromVFOV(currentFov, width, height);
  55437. return r > maxHFov ? cameraLight.getVFOVFromHFOV(maxHFov, width, height) : currentFov
  55438. },
  55439. getHFOVForCamera: function(camera, getRad) {
  55440. return cameraLight.getHFOVByScreenPrecent(camera.fov, camera.aspect, getRad)
  55441. },
  55442. //add
  55443. getHFOVByScreenPrecent: function(fov, percent, getRad) { //当fov为占比百分百时,percent代表在屏幕上从中心到边缘的占比
  55444. let rad = 2 * Math.atan(percent * Math.tan(fov * MathLight.RADIANS_PER_DEGREE / 2));
  55445. if(getRad)return rad
  55446. else return rad * MathLight.DEGREES_PER_RADIAN;
  55447. }
  55448. };
  55449. /**
  55450. * @author mschuetz / http://mschuetz.at
  55451. *
  55452. * adapted from THREE.OrbitControls by
  55453. *
  55454. * @author qiao / https://github.com/qiao
  55455. * @author mrdoob / http://mrdoob.com
  55456. * @author alteredq / http://alteredqualia.com/
  55457. * @author WestLangley / http://github.com/WestLangley
  55458. * @author erich666 / http://erichaines.com
  55459. *
  55460. *
  55461. *
  55462. */
  55463. class FirstPersonControls extends EventDispatcher {
  55464. constructor (viewer, viewport) {
  55465. super();
  55466. this.viewer = viewer;
  55467. this.renderer = viewer.renderer;
  55468. this.scene = viewer.scene;
  55469. this.rotationSpeed = 200;
  55470. this.moveSpeed = 10;
  55471. this.setCurrentViewport({hoverViewport:viewport, force:true}); //this.currentViewport = viewport
  55472. this.keys = {
  55473. FORWARD: ['W'.charCodeAt(0), 38],
  55474. BACKWARD: ['S'.charCodeAt(0), 40],
  55475. LEFT: ['A'.charCodeAt(0), 37],
  55476. RIGHT: ['D'.charCodeAt(0), 39],
  55477. UP: ['Q'.charCodeAt(0)],
  55478. DOWN: ['E'.charCodeAt(0)],
  55479. //SHIFT : [16],
  55480. ALT : [18],
  55481. Rotate_LEFT : ['L'.charCodeAt(0)],
  55482. Rotate_RIGHT : ['J'.charCodeAt(0)],
  55483. Rotate_UP : ['K'.charCodeAt(0)],
  55484. Rotate_DOWN : ['I'.charCodeAt(0)],
  55485. };
  55486. this.fadeFactor = 20;
  55487. this.yawDelta = 0;
  55488. this.pitchDelta = 0;
  55489. this.translationDelta = new Vector3(0, 0, 0);
  55490. this.translationWorldDelta = new Vector3(0, 0, 0);
  55491. this.tweens = [];
  55492. this.dollyStart = new Vector2$1;
  55493. this.dollyEnd = new Vector2$1;
  55494. //this.enableChangePos = true
  55495. this.viewer.addEventListener('camera_changed',(e)=>{
  55496. this.setFPCMoveSpeed(e.viewport);
  55497. });
  55498. let drag = (e) => {
  55499. if(!this.enabled)return
  55500. let viewport = e.dragViewport;
  55501. if(!viewport)return
  55502. let camera = viewport.camera;
  55503. let mode;
  55504. if(e.isTouch){
  55505. if(e.touches.length == 1){
  55506. mode = (!e.dragViewport || e.dragViewport.name == 'MainView') ? 'rotate' : 'pan';
  55507. }else if(e.touches.length == 2){
  55508. mode = 'scale';
  55509. }else {
  55510. mode = (!e.dragViewport || e.dragViewport.name == 'MainView') ? 'pan' : 'scale';
  55511. }
  55512. }else {
  55513. //mode = e.buttons === Buttons.LEFT && (!e.dragViewport || e.dragViewport.name == 'MainView') ? 'rotate' : 'pan'
  55514. mode = e.buttons === Buttons.LEFT && camera.type != 'OrthographicCamera' ? 'rotate' : 'pan';
  55515. }
  55516. //console.log('mode ', mode )
  55517. let moveSpeed = this.currentViewport.getMoveSpeed();
  55518. if (e.drag.startHandled === undefined) {///???????
  55519. e.drag.startHandled = true;
  55520. this.dispatchEvent({type: 'start'});
  55521. }
  55522. if (mode.includes('rotate')) {//旋转
  55523. //来自panoramaControl updateRotation
  55524. if(!this.pointerDragStart){
  55525. return this.pointerDragStart = e.pointer.clone()
  55526. }
  55527. let view = this.scene.view;
  55528. if(Potree.settings.rotAroundPoint && this.intersectStart && this.canMovePos(viewport) && !viewer.images360.isAtPano() && !this.viewer.inputHandler.pressedKeys[17]){//定点旋转: 以当前intersect的点为target旋转,不改点在屏幕中的位置
  55529. let distance = camera.position.distanceTo(this.intersectStart.location); //不按下ctrl的话
  55530. //按照orbitControl的方式旋转:
  55531. let rotationSpeed = 2.5;
  55532. this.yawDelta -= e.drag.pointerDelta.x * rotationSpeed;
  55533. this.pitchDelta += e.drag.pointerDelta.y * rotationSpeed;
  55534. //先更新一下相机:
  55535. this.update();
  55536. view.applyToCamera(camera);
  55537. //然后得到新的相机角度下,原先点在屏幕中的位置所对应的3d点现在的坐标。只需要平移一下新旧坐标差值即可。
  55538. let newPointerDir = viewer.inputHandler.getMouseDirection(this.intersectStart.pointer).direction.clone().multiplyScalar(distance);
  55539. let pivot = new Vector3().addVectors(camera.position, newPointerDir); //新的3d点
  55540. let moveVec = new Vector3().subVectors(pivot, this.intersectStart.location);
  55541. this.translationWorldDelta.copy(moveVec.negate());
  55542. //立即更新下,防止因update和此drag频率不同而打滑。
  55543. this.update();
  55544. view.applyToCamera(camera);
  55545. }else {
  55546. let _matrixWorld = camera.matrixWorld;
  55547. camera.matrixWorld = new Matrix4;//unproject 前先把相机置于原点
  55548. var e1 = new Vector3(this.pointerDragStart.x,this.pointerDragStart.y,-1).unproject(camera)
  55549. , t = new Vector3(e.pointer.x,e.pointer.y,-1).unproject(camera)
  55550. , i = Math.sqrt(e1.x * e1.x + e1.z * e1.z)
  55551. , n = Math.sqrt(t.x * t.x + t.z * t.z)
  55552. , o = Math.atan2(e1.y, i)
  55553. , a = Math.atan2(t.y, n);
  55554. this.pitchDelta += o - a; //上下旋转
  55555. e1.y = 0,
  55556. t.y = 0;
  55557. var s = Math.acos(e1.dot(t) / e1.length() / t.length());
  55558. if(!isNaN(s)){
  55559. var yawDelta = s; //左右旋转
  55560. this.pointerDragStart.x > e.pointer.x && (yawDelta *= -1);
  55561. this.yawDelta += yawDelta;
  55562. }
  55563. //console.log('rotate:', this.pitchDelta, e.pointer.toArray(), this.pointerDragStart.toArray())
  55564. this.pointerDragStart.copy(e.pointer);
  55565. camera.matrixWorld = _matrixWorld ;
  55566. }
  55567. }
  55568. if (mode.includes('pan')) {//平移
  55569. if(!this.canMovePos(viewport)){
  55570. return
  55571. }
  55572. if(camera.type == "OrthographicCamera"){
  55573. //console.log(e.drag.pointerDelta, e.pointer, e.drag.end)
  55574. let moveVec = Utils.getOrthoCameraMoveVec(e.drag.pointerDelta, camera );//最近一次移动向量
  55575. let pointclouds;
  55576. let Alignment = window.viewer.modules.Alignment;
  55577. let MergeEditor = window.viewer.modules.MergeEditor;
  55578. let handleState = Alignment.handleState;
  55579. let a = e.buttons === Buttons.LEFT && viewport.alignment && handleState && viewport.alignment[handleState];
  55580. if(Potree.settings.editType == 'pano'){//右键平移视图、左键操作点云
  55581. let PanoEditor = window.viewer.modules.PanoEditor;
  55582. if(a && PanoEditor.selectedPano){
  55583. if(!PanoEditor.selectedGroup || !PanoEditor.checkIfAllLinked({group:PanoEditor.selectedGroup}) ){
  55584. if(handleState == 'translate' && ( e.drag.intersectStart.pointclouds && Common.getMixedSet(PanoEditor.selectedClouds, e.drag.intersectStart.pointclouds).length || PanoEditor.selectedPano.hovered)//拖拽到点云上 或 circle
  55585. || handleState == 'rotate' )
  55586. {
  55587. pointclouds = PanoEditor.selectedClouds;
  55588. }
  55589. }else {
  55590. PanoEditor.dispatchEvent('needToDisConnect');
  55591. console.warn('选中的漫游点连通了整个数据集,不允许移动');
  55592. }
  55593. }
  55594. if(!pointclouds && e.buttons === Buttons.LEFT && viewport.rotateSide){
  55595. return PanoEditor.rotateSideCamera(-e.drag.pointerDelta.x)
  55596. }
  55597. }else if(Potree.settings.editType == 'merge'){
  55598. if(e.buttons === Buttons.LEFT && viewport.rotateSide){
  55599. return MergeEditor.rotateSideCamera(-e.drag.pointerDelta.x)
  55600. }
  55601. }else {
  55602. /* if(Alignment.selectedClouds && Alignment.selectedClouds.length){
  55603. pointclouds = a && e.drag.intersectStart.pointclouds && Common.getMixedSet(Alignment.selectedClouds, e.drag.intersectStart.pointclouds).length && Alignment.selectedClouds
  55604. }else{ */
  55605. pointclouds = a && e.drag.intersectStart.pointcloud && [e.drag.intersectStart.pointcloud];
  55606. //}
  55607. }
  55608. if(pointclouds){
  55609. this.dispatchEvent({
  55610. type : "transformPointcloud",
  55611. intersect: e.intersect.orthoIntersect,
  55612. intersectStart: e.drag.intersectStart.orthoIntersect,
  55613. moveVec,
  55614. pointclouds,
  55615. camera
  55616. });
  55617. }else {
  55618. this.translationWorldDelta.add(moveVec.negate());
  55619. }
  55620. }else {
  55621. if(e.drag.intersectStart){//如果拖拽着点云
  55622. if(e.drag.z == void 0){//拖拽开始
  55623. let pointerStartPos2d = e.drag.intersectStart.location.clone().project(camera);//识别到的点云点的位置
  55624. e.drag.z = pointerStartPos2d.z; //记录z,保持拖拽物体到屏幕距离不变,所以z深度不变
  55625. e.drag.projectionMatrixInverse = camera.projectionMatrixInverse.clone();
  55626. //防止吸附到最近点上(因为鼠标所在位置并非识别到的点云点的位置,需要得到鼠标所在位置的3d坐标。)
  55627. let pointerStartPos2dReal = new Vector3(this.pointerDragStart.x,this.pointerDragStart.y, e.drag.z);
  55628. e.drag.translateStartPos = pointerStartPos2dReal.clone().unproject(camera);
  55629. /* this.viewer.dispatchEvent({
  55630. type: 'dragPanBegin',
  55631. projectionMatrixInverse : e.drag.projectionMatrixInverse
  55632. }); */
  55633. //console.log('开始拖拽', e.pointer.clone())
  55634. }
  55635. //拖拽的过程中将projectionMatrixInverse替换成开始拖拽时的,因为near、far一直在变,会导致unproject计算出的3d坐标改变很大而闪烁。
  55636. var _projectionMatrixInverse = camera.projectionMatrixInverse;
  55637. camera.projectionMatrixInverse = e.drag.projectionMatrixInverse;
  55638. let newPos2d = new Vector3(e.pointer.x,e.pointer.y, e.drag.z );
  55639. let newPos3d = newPos2d.clone().unproject(camera);
  55640. let moveVec = newPos3d.clone().sub( e.drag.translateStartPos /* e.drag.intersectStart.location */ );//移动相机,保持鼠标下的位置永远不变,所以用鼠标下的新位置减去鼠标下的原始位置
  55641. camera.projectionMatrixInverse = _projectionMatrixInverse;
  55642. this.translationWorldDelta.copy(moveVec.negate()); //这里没法用add,原因未知,会跳动
  55643. //console.log('pan 1', this.translationWorldDelta.clone())
  55644. //四指松开剩三指时会偏移一下,暂不知道哪里的问题,或许跟开头防止点云吸附有关?
  55645. }else { //如果鼠标没有找到和点云的交点,就假设移动整个模型(也可以去扩大范围寻找最近点云)
  55646. /* let center = viewer.scene.pointclouds[0].position;
  55647. let radius = camera.position.distanceTo(center);
  55648. let ratio = radius * Math.tan(THREE.Math.degToRad(camera.fov)/2) / 1000 */
  55649. /* let speed = this.currentViewport.getMoveSpeed()
  55650. if(FirstPersonControls.boundPlane){
  55651. speed = FirstPersonControls.boundPlane.distanceToPoint(this.currentViewport.position)
  55652. speed = Math.max(1 , speed)
  55653. } */
  55654. let lastIntersect = viewport.lastIntersect ? (viewport.lastIntersect.location || viewport.lastIntersect) : viewer.bound.center; //该viewport的最近一次鼠标和点云的交点
  55655. let speed = camera.position.distanceTo(lastIntersect);
  55656. let fov = cameraLight.getHFOVForCamera(camera, true);
  55657. let ratio = speed * Math.tan(fov/2);
  55658. this.translationDelta.x -= e.drag.pointerDelta.x * ratio;
  55659. this.translationDelta.z -= e.drag.pointerDelta.y * ratio;
  55660. //console.log('pan2', e.drag.pointerDelta)
  55661. }
  55662. }
  55663. this.useAttenuation = false;
  55664. }
  55665. if(mode.includes('scale')){
  55666. this.dollyEnd.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  55667. //if(!this.dollyStart)return
  55668. var scale = this.dollyEnd.length() / this.dollyStart.length();
  55669. //console.log('scale ',scale)
  55670. let pointer = new Vector2$1().addVectors(e.touches[0].pointer, e.touches[1].pointer).multiplyScalar(0.5);//两个指头的中心点
  55671. dolly({
  55672. pointer,
  55673. scale, camera
  55674. });
  55675. this.dollyStart.copy(this.dollyEnd);
  55676. }
  55677. //最好按ctrl可以变为dollhouse的那种旋转
  55678. };
  55679. let drop = e => {
  55680. if(!this.enabled)return
  55681. this.dispatchEvent({type: 'end'});
  55682. };
  55683. let dolly = (e={})=>{
  55684. if(Potree.settings.displayMode == 'showPanos' && this.currentViewport == viewer.mainViewport/* this.currentViewport.unableChangePos */){//全景时
  55685. this.dispatchEvent({type:'dollyStopCauseUnable',delta:e.delta, scale:e.scale});
  55686. return
  55687. }
  55688. let camera = e.camera;
  55689. if(camera.type == "OrthographicCamera"){
  55690. let ratio;
  55691. if(e.delta != void 0){//滚轮缩放
  55692. if(e.delta == 0){//mac
  55693. return
  55694. }else if (e.delta < 0) {
  55695. ratio = 0.9;
  55696. } else if (e.delta > 0) {
  55697. ratio = 1.1;
  55698. }
  55699. }else {
  55700. ratio = e.scale; //触屏缩放
  55701. }
  55702. let zoom = camera.zoom * ratio;
  55703. let limit = camera.zoomLimit;
  55704. if(limit) zoom = MathUtils.clamp(zoom, limit.min,limit.max );
  55705. let pointerPos = new Vector3(e.pointer.x, e.pointer.y,0.5);
  55706. let oldPos = pointerPos.clone().unproject(camera);
  55707. if(camera.zoom != zoom){
  55708. camera.zoom = zoom;
  55709. camera.updateProjectionMatrix();
  55710. }
  55711. let newPos = pointerPos.clone().unproject(camera);
  55712. //定点缩放, 恢复一下鼠标所在位置的位置改变量
  55713. let moveVec = new Vector3().subVectors(newPos,oldPos);
  55714. this.translationWorldDelta.add(moveVec.negate());
  55715. this.useAttenuation = false;
  55716. }else {
  55717. let speed , direction;
  55718. if(e.delta != void 0){//滚轮缩放
  55719. speed = this.currentViewport.getMoveSpeed() * 15;
  55720. //var direction = this.currentViewport.view.direction.clone();
  55721. direction = this.viewer.inputHandler.getMouseDirection().direction; //定点缩放
  55722. if(e.delta == 0){//mac
  55723. return
  55724. }else if (e.delta < 0) {
  55725. speed *= -1;
  55726. }
  55727. }else {
  55728. const constantDis = this.currentViewport.getMoveSpeed() * 200; //constantDis = 10;//常量系数,当放大一倍时前进的距离。可以调整
  55729. speed = (e.scale-1)*constantDis; //触屏缩放
  55730. //pointer = new THREE.Vector2().addVectors().multiplyScalar(0.5);//两个指头的中心点
  55731. direction = this.viewer.inputHandler.getMouseDirection(e.pointer).direction; //定点缩放
  55732. }
  55733. this.useAttenuation = true;
  55734. var vec = direction.multiplyScalar(speed );
  55735. this.translationWorldDelta.copy(vec);
  55736. }
  55737. };
  55738. let scroll = (e) => {
  55739. if(!this.enabled || !e.hoverViewport)return
  55740. this.setCurrentViewport(e);
  55741. e.camera = e.hoverViewport.camera;
  55742. dolly(e);
  55743. };
  55744. let dblclick = (e) => {
  55745. if(!this.enabled)return
  55746. if(!Potree.settings.dblToFocusPoint)return;//调试时才可双击
  55747. if(Potree.settings.displayMode == 'showPointCloud'/* !viewer.images360.isAtPano() */) this.zoomToLocation(e.mouse);
  55748. };
  55749. this.viewer.addEventListener('global_drag', drag);
  55750. /* this.viewer.addEventListener('global_touchmove', (e)=>{
  55751. if(!this.enabled)return
  55752. if(e.touches.length>1){//单指的就触发上一句
  55753. //console.log('global_touchmove' )
  55754. drag(e)
  55755. }
  55756. }); */
  55757. this.viewer.addEventListener('global_drop', drop);
  55758. this.viewer.addEventListener('global_mousewheel', scroll);
  55759. this.viewer.addEventListener('global_dblclick', dblclick);
  55760. let prepareScale = (e)=>{//触屏的scale
  55761. this.dollyStart.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  55762. };
  55763. let prepareRotate = (e)=>{
  55764. this.pointerDragStart = e.pointer.clone();
  55765. this.intersectStart = e.intersect && e.intersect.location && {
  55766. location : e.intersect.location,
  55767. pointer : e.intersect.location.clone().project(e.dragViewport.camera) //intersect点在屏幕中的位置
  55768. };
  55769. //console.log('prepareRotate' )
  55770. };
  55771. let preparePan = (e)=>{//触屏的pan点云 还是会偏移
  55772. this.pointerDragStart = e.pointer.clone();
  55773. e.drag.z = void 0; //清空
  55774. drag(e); //触屏点击时更新的pointer直接用一次drag
  55775. //console.log('preparePan ' )
  55776. };
  55777. this.viewer.addEventListener('global_mousedown'/* 'startDragging' */, (e)=>{
  55778. if(!this.enabled)return
  55779. this.setCurrentViewport(e);
  55780. prepareRotate(e);
  55781. });
  55782. //注意,每次增减指头都会修改pointer,需要更新下状态
  55783. this.viewer.addEventListener('global_touchstart', (e)=>{
  55784. if(!this.enabled)return
  55785. if(e.touches.length==2){//只监听开头两个指头
  55786. prepareScale(e);
  55787. }else if(e.touches.length>=3){
  55788. preparePan(e);
  55789. }
  55790. });
  55791. this.viewer.addEventListener('global_touchend', (e)=>{
  55792. if(!this.enabled)return
  55793. if(e.touches.length==2){//停止平移,开始scale
  55794. prepareScale(e);
  55795. }else if(e.touches.length==1){//停止scale,开始rotate
  55796. prepareRotate(e);
  55797. }else if(e.touches.length>=3){//重新准备下平移(因为抬起的指头可能包含平移使用的数据),否则抬起时漂移
  55798. preparePan(e);
  55799. }
  55800. });
  55801. /* this.viewer.addEventListener('enableChangePos', (e)=>{
  55802. if(!this.enabled)return
  55803. this.enableChangePos = e.canLeavePano
  55804. }) */
  55805. }
  55806. canMovePos(viewport){
  55807. if(viewport == viewer.mainViewport && (Potree.settings.displayMode == 'showPanos'
  55808. || viewer.images360.bumping || viewer.images360.latestToPano))return false
  55809. else return true
  55810. }
  55811. setEnable(enabled){
  55812. this.enabled = enabled;
  55813. }
  55814. setFPCMoveSpeed(viewport){
  55815. if(viewport.camera.type == 'OrthographicCamera'){
  55816. let s = 1 / viewport.camera.zoom;
  55817. viewport.setMoveSpeed(s);
  55818. }else {
  55819. if(viewport == viewer.mainViewport && FirstPersonControls.boundPlane){
  55820. let s = FirstPersonControls.boundPlane.distanceToPoint(viewer.mainViewport.view.position);
  55821. s = Math.sqrt(s) / 10;
  55822. s = Math.max(FirstPersonControls.standardSpeed , s);
  55823. s *= Potree.config.moveSpeedAdujust;
  55824. viewer.setMoveSpeed(s);
  55825. }
  55826. }
  55827. }
  55828. setCurrentViewport(o={}){//add
  55829. if(!this.enabled && !o.force )return
  55830. if(o.hoverViewport && this.currentViewport != o.hoverViewport ){
  55831. this.currentViewport = o.hoverViewport;
  55832. //this.viewer.setMoveSpeed(this.currentViewport.radius/100);
  55833. this.setFPCMoveSpeed(this.currentViewport);
  55834. }
  55835. if(this.currentViewport.camera.type == 'OrthographicCamera'){
  55836. this.lockElevationOri = true;
  55837. this.lockRotation = true;
  55838. }else {
  55839. this.lockElevationOri = false;
  55840. this.lockRotation = false;
  55841. }
  55842. }
  55843. setScene (scene) {
  55844. this.scene = scene;
  55845. }
  55846. stop(){
  55847. this.yawDelta = 0;
  55848. this.pitchDelta = 0;
  55849. this.translationDelta.set(0, 0, 0);
  55850. }
  55851. zoomToLocation(mouse){
  55852. if(!this.enabled)return
  55853. let camera = this.scene.getActiveCamera();
  55854. /* let I = Utils.getMousePointCloudIntersection(
  55855. mouse,
  55856. camera,
  55857. this.viewer,
  55858. this.scene.pointclouds); */
  55859. var I = this.viewer.inputHandler.intersect;
  55860. if (!I) {
  55861. return;
  55862. }
  55863. let targetRadius = 0;
  55864. {
  55865. let minimumJumpDistance = 0.2;
  55866. let domElement = this.renderer.domElement;
  55867. let ray = Utils.mouseToRay(this.viewer.inputHandler.pointer, camera);
  55868. let {origin, direction} = this.viewer.inputHandler.getMouseDirection();
  55869. let raycaster = new Raycaster();
  55870. raycaster.ray.set(origin, direction);
  55871. let nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray);
  55872. let nodes2 = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, raycaster.ray);
  55873. let lastNode = nodes[nodes.length - 1];
  55874. let radius = lastNode.getBoundingSphere(new Sphere()).radius;
  55875. targetRadius = Math.min(this.scene.view.radius, radius);
  55876. targetRadius = Math.max(minimumJumpDistance, targetRadius);
  55877. }
  55878. let d = this.scene.view.direction.multiplyScalar(-1);
  55879. let cameraTargetPosition = new Vector3().addVectors(I.location, d.multiplyScalar(targetRadius));
  55880. // TODO Unused: let controlsTargetPosition = I.location;
  55881. let animationDuration = 600;
  55882. let easing = TWEEN.Easing.Quartic.Out;
  55883. { // animate
  55884. let value = {x: 0};
  55885. let tween = new TWEEN.Tween(value).to({x: 1}, animationDuration);
  55886. tween.easing(easing);
  55887. this.tweens.push(tween);
  55888. let startPos = this.scene.view.position.clone();
  55889. let targetPos = cameraTargetPosition.clone();
  55890. let startRadius = this.scene.view.radius;
  55891. let targetRadius = cameraTargetPosition.distanceTo(I.location);
  55892. tween.onUpdate(() => {
  55893. let t = value.x;
  55894. this.scene.view.position.x = (1 - t) * startPos.x + t * targetPos.x;
  55895. this.scene.view.position.y = (1 - t) * startPos.y + t * targetPos.y;
  55896. this.scene.view.position.z = (1 - t) * startPos.z + t * targetPos.z;
  55897. this.scene.view.radius = (1 - t) * startRadius + t * targetRadius;
  55898. this.viewer.setMoveSpeed(this.scene.view.radius / 2.5);
  55899. });
  55900. tween.onComplete(() => {
  55901. this.tweens = this.tweens.filter(e => e !== tween);
  55902. });
  55903. tween.start();
  55904. }
  55905. }
  55906. update (delta=1) {
  55907. if(!this.enabled)return
  55908. //console.log('update')
  55909. let view = this.currentViewport.view;
  55910. { // cancel move animations on user input
  55911. let changes = [ this.yawDelta,
  55912. this.pitchDelta,
  55913. this.translationDelta.length(),
  55914. this.translationWorldDelta.length() ];
  55915. let changeHappens = changes.some(e => Math.abs(e) > 0.001);
  55916. if (changeHappens && this.tweens.length > 0) {
  55917. this.tweens.forEach(e => e.stop());
  55918. this.tweens = [];
  55919. }
  55920. }
  55921. { // accelerate while input is given
  55922. let ih = this.viewer.inputHandler;
  55923. let moveForward = this.keys.FORWARD.some(e => ih.pressedKeys[e]);
  55924. let moveBackward = this.keys.BACKWARD.some(e => ih.pressedKeys[e]);
  55925. let moveLeft = this.keys.LEFT.some(e => ih.pressedKeys[e]);
  55926. let moveRight = this.keys.RIGHT.some(e => ih.pressedKeys[e]);
  55927. let moveUp = this.keys.UP.some(e => ih.pressedKeys[e]);
  55928. let moveDown = this.keys.DOWN.some(e => ih.pressedKeys[e]);
  55929. let rotateLeft = this.keys.Rotate_LEFT.some(e => ih.pressedKeys[e]);
  55930. let rotateRight = this.keys.Rotate_RIGHT.some(e => ih.pressedKeys[e]);
  55931. let rotateUp = this.keys.Rotate_UP.some(e => ih.pressedKeys[e]);
  55932. let rotateDown = this.keys.Rotate_DOWN.some(e => ih.pressedKeys[e]);
  55933. this.lockElevation = this.lockElevationOri || this.keys.ALT.some(e => ih.pressedKeys[e]);
  55934. if(!this.lockRotation){
  55935. if(rotateLeft){
  55936. this.yawDelta -= 0.01;
  55937. }else if(rotateRight){
  55938. this.yawDelta += 0.01;
  55939. }
  55940. if(rotateUp){
  55941. this.pitchDelta -= 0.01;
  55942. }else if(rotateDown){
  55943. this.pitchDelta += 0.01;
  55944. }
  55945. }
  55946. if(this.canMovePos(this.currentViewport) && !this.lockKey){
  55947. if(this.lockElevation){
  55948. let dir = view.direction;
  55949. dir.z = 0;
  55950. dir.normalize();
  55951. if (moveForward && moveBackward) {
  55952. this.translationWorldDelta.set(0, 0, 0);
  55953. } else if (moveForward) {
  55954. this.translationWorldDelta.copy(dir.multiplyScalar(this.currentViewport.getMoveSpeed()));
  55955. } else if (moveBackward) {
  55956. this.translationWorldDelta.copy(dir.multiplyScalar(-this.currentViewport.getMoveSpeed()));
  55957. }
  55958. }else {
  55959. if (moveForward && moveBackward) {
  55960. this.translationDelta.y = 0;
  55961. } else if (moveForward) {
  55962. this.translationDelta.y = this.currentViewport.getMoveSpeed();
  55963. } else if (moveBackward) {
  55964. this.translationDelta.y = -this.currentViewport.getMoveSpeed();
  55965. }
  55966. }
  55967. if (moveLeft && moveRight) {
  55968. this.translationDelta.x = 0;
  55969. } else if (moveLeft) {
  55970. this.translationDelta.x = -this.currentViewport.getMoveSpeed();
  55971. } else if (moveRight) {
  55972. this.translationDelta.x = this.currentViewport.getMoveSpeed();
  55973. }
  55974. if (moveUp && moveDown) {
  55975. this.translationWorldDelta.z = 0;
  55976. } else if (moveUp) {
  55977. this.translationWorldDelta.z = this.currentViewport.getMoveSpeed();
  55978. } else if (moveDown) {
  55979. this.translationWorldDelta.z = -this.currentViewport.getMoveSpeed();
  55980. }
  55981. if(moveUp || moveDown || moveForward || moveBackward){
  55982. this.useAttenuation = false;
  55983. }
  55984. }
  55985. }
  55986. { // apply rotation
  55987. let yaw = view.yaw;
  55988. let pitch = view.pitch;
  55989. yaw += this.yawDelta; /* * delta; */
  55990. pitch += this.pitchDelta;/* * delta; */
  55991. view.yaw = yaw;
  55992. view.pitch = pitch;
  55993. this.yawDelta = 0;
  55994. this.pitchDelta = 0;
  55995. }
  55996. if(this.translationWorldDelta.length()>0) {
  55997. // console.log('translationDelta')
  55998. }
  55999. { // apply translation
  56000. view.translate(
  56001. this.translationDelta.x, /* * delta, */
  56002. this.translationDelta.y, /* * delta, */
  56003. this.translationDelta.z, /* * delta */
  56004. );
  56005. this.translationDelta.set(0,0,0);
  56006. //if(this.translationWorldDelta.length())console.log(translationWorldDelta)
  56007. view.translateWorld(
  56008. this.translationWorldDelta.x /* * delta */,
  56009. this.translationWorldDelta.y /* * delta */,
  56010. this.translationWorldDelta.z /* * delta */
  56011. );
  56012. //this.translationWorldDelta.set(0,0,0)
  56013. }
  56014. { // set view target according to speed
  56015. //view.radius = 1 * this.currentViewport.getMoveSpeed();
  56016. /* if(viewer.bound) view.radius = view.position.distanceTo(viewer.bound.center)
  56017. let speed = view.radius/100;
  56018. this.viewer.setMoveSpeed(speed); */
  56019. //this.setMoveSpeed()
  56020. }
  56021. if(this.useAttenuation){ //只有滚轮缩放时开启
  56022. let attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  56023. /*this.yawDelta *= attenuation;
  56024. this.pitchDelta *= attenuation;
  56025. this.translationDelta.multiplyScalar(attenuation);*/
  56026. this.translationWorldDelta.multiplyScalar(attenuation);
  56027. }else {
  56028. this.translationWorldDelta.set(0,0,0);
  56029. }
  56030. }
  56031. };
  56032. class Viewport{
  56033. constructor( view, camera, prop={}){//目前不支持换camera
  56034. this.left = prop.left;
  56035. this.bottom = prop.bottom;
  56036. this.width = prop.width;
  56037. this.height = prop.height;
  56038. this.name = prop.name;
  56039. this.view = view;
  56040. this.camera = camera;
  56041. this.active = true;
  56042. this.unableChangePos = false;
  56043. this.noPointcloud;
  56044. //this.keys = [...] firstPersonCtl....
  56045. this.resolution = new Vector2$1;
  56046. this.resolution2 = new Vector2$1;
  56047. this.offset = new Vector2$1; //viewportOffset 范围从0-整个画布的像素
  56048. this.extraEnableLayers = prop.extraEnableLayers || [];//额外可展示的层
  56049. this.cameraLayers = prop.cameraLayers;
  56050. this.pixelRatio = prop.pixelRatio; //如果规定pixelRatio的话要传,这样就覆盖devicePicelRatio, 如magnifier
  56051. }
  56052. clone(){
  56053. return Common.CloneClassObject(this)
  56054. }
  56055. getMoveSpeed(){
  56056. return this.moveSpeed
  56057. }
  56058. setMoveSpeed(e){
  56059. this.moveSpeed = e;
  56060. }
  56061. layersAdd(name){
  56062. this.extraEnableLayers.includes(name) || this.extraEnableLayers.push(name);
  56063. }
  56064. layersRemove(name){
  56065. let index = this.extraEnableLayers.indexOf(name);
  56066. if(index > -1){
  56067. this.extraEnableLayers.splice(index, 1);
  56068. }
  56069. }
  56070. cameraChanged() {
  56071. var copy = ()=>{
  56072. this.previousState = {
  56073. projectionMatrix: this.camera.projectionMatrix.clone(),//worldMatrix在this.control时归零了所以不用了吧,用position和qua也一样
  56074. position: this.camera.position.clone(),
  56075. quaternion: this.camera.quaternion.clone()
  56076. };
  56077. };
  56078. let projectionChanged = true;
  56079. let positionChanged = true;
  56080. let quaternionChanged = true;
  56081. let getChanged = ()=>{
  56082. return {
  56083. projectionChanged,positionChanged,quaternionChanged,
  56084. changed:projectionChanged || positionChanged || quaternionChanged
  56085. }
  56086. };
  56087. if (this.previousState){
  56088. projectionChanged = !this.camera.projectionMatrix.equals(this.previousState.projectionMatrix);
  56089. positionChanged = !this.camera.position.equals(this.previousState.position);
  56090. quaternionChanged = !this.camera.quaternion.equals(this.previousState.quaternion);
  56091. }
  56092. copy();
  56093. return getChanged()
  56094. }
  56095. setResolution(w,h, wholeW=0, wholeH=0){
  56096. this.resolution.set(w,h);//是client的width height
  56097. this.resolution2.copy(this.resolution).multiplyScalar(this.pixelRatio || window.devicePixelRatio);
  56098. this.offset.set(wholeW,wholeH).multiply(new Vector2$1(this.left,this.bottom)).multiplyScalar(window.devicePixelRatio);
  56099. }
  56100. }
  56101. /**
  56102. * @author mschuetz / http://mschuetz.at
  56103. *
  56104. *
  56105. */
  56106. class InputHandler extends EventDispatcher {
  56107. constructor (viewer,scene) {
  56108. super();
  56109. this.viewer = viewer;
  56110. this.renderer = viewer.renderer;
  56111. this.domElement = this.renderer.domElement;
  56112. this.enabled = true;
  56113. this.scene = scene;
  56114. this.interactiveScenes = [];
  56115. this.interactiveObjects = new Set();
  56116. this.inputListeners = [];
  56117. this.blacklist = new Set();
  56118. this.drag = null;
  56119. this.mouse = new Vector2$1(0, 0);
  56120. //add:
  56121. this.pointer = new Vector2$1(0, 0); //交互点的屏幕坐标,有别于DOM坐标,在此存放NDC坐标。(NDC,三维常用坐标系,二维坐标,整个屏幕映射范围(-1,1),屏幕中心为原点,+Y朝上,+X朝右)
  56122. this.mouseDownMouse = new Vector2$1(0, 0);
  56123. this.selection = [];
  56124. this.hoveredElements = [];
  56125. this.pressedKeys = {};
  56126. this.wheelDelta = 0;
  56127. this.speed = 1;
  56128. this.logMessages = false;
  56129. if (this.domElement.tabIndex === -1) {
  56130. this.domElement.tabIndex = 2222;
  56131. }
  56132. this.lastPointerUpTime = 0;
  56133. this.touches = [];
  56134. this.hoverViewport = viewer.viewports[0];
  56135. this.domElement.addEventListener('contextmenu', (event) => { event.preventDefault(); }, false);
  56136. this.domElement.addEventListener('click', this.onMouseClick.bind(this), false);
  56137. this.domElement.addEventListener('mousedown', this.onMouseDown.bind(this), false);
  56138. window.addEventListener('mouseup', this.onMouseUp.bind(this), false);
  56139. this.domElement.addEventListener('mousemove', this.onMouseMove.bind(this), false);
  56140. //add
  56141. /* this.domElement.addEventListener("pointerout", this.onMouseUp.bind(this)),
  56142. this.domElement.addEventListener("pointercancel", this.onMouseUp.bind(this)),
  56143. */
  56144. this.domElement.addEventListener('mousewheel', this.onMouseWheel.bind(this), false);
  56145. this.domElement.addEventListener('DOMMouseScroll', this.onMouseWheel.bind(this), false); // Firefox
  56146. //this.domElement.addEventListener('dblclick', this.onDoubleClick.bind(this)); //因为双击时间间隔是跟随系统的所以不好判断
  56147. this.domElement.addEventListener('keydown', this.onKeyDown.bind(this));
  56148. window.addEventListener('keyup', this.onKeyUp.bind(this));
  56149. //window.addEventListener('focus',()=>{
  56150. window.addEventListener('blur',this.onKeyUp.bind(this)); //add
  56151. this.domElement.addEventListener('touchstart', this.onTouchStart.bind(this));
  56152. this.domElement.addEventListener('touchend', this.onTouchEnd.bind(this));
  56153. this.domElement.addEventListener('touchmove', this.onTouchMove.bind(this));
  56154. {
  56155. this.addEventListener('isMeasuring',(e)=>{
  56156. //console.log('isMeasuring',e.v,e.cause)
  56157. this.isMeasuring = e.v;
  56158. });
  56159. }
  56160. }
  56161. /* addInputListener (listener) {
  56162. this.inputListeners.push(listener);
  56163. }
  56164. removeInputListener (listener) {
  56165. this.inputListeners = this.inputListeners.filter(e => e !== listener);
  56166. }
  56167. getSortedListeners(){
  56168. return this.inputListeners.sort( (a, b) => {
  56169. let ia = (a.importance !== undefined) ? a.importance : 0;
  56170. let ib = (b.importance !== undefined) ? b.importance : 0;
  56171. return ib - ia;
  56172. });
  56173. } */
  56174. //统一跟第一个触碰的viewport相同
  56175. updateTouchesInfo(e){
  56176. var viewport, pointer, camera;
  56177. let oldTouches = this.touches;
  56178. let changedTouches = Array.from(e.changedTouches);
  56179. let touches = Array.from(e.touches);
  56180. this.touches = touches.map(touch=>{
  56181. let touch_ = oldTouches.find(a=>a.touch.identifier == touch.identifier);
  56182. let pointer = touch_ && touch_.pointer; //复制原先的值
  56183. return {
  56184. touch, pointer,
  56185. }
  56186. });
  56187. if(e.touches.length > 0){
  56188. let newTouches = touches.filter(e=>!
  56189. oldTouches.some(a=>a.touch.identifier == e.identifier) && !changedTouches.some(a=>a.identifier == e.identifier)
  56190. ); //从按钮处划过时e.touches中会出现this.touches和changedTouches中都没有的identifier
  56191. if(newTouches.length>0){
  56192. console.warn('has new',newTouches.map(e=>e.identifier));
  56193. }
  56194. newTouches.concat(changedTouches).forEach(touch=>{ //修改changedTouches的
  56195. let touch_ = this.touches.find(a=>a.touch.identifier == touch.identifier);
  56196. if(touch_){
  56197. let a = this.getPointerInViewport(touch.pageX, touch.pageY, this.dragViewport||viewport, new Vector2$1);
  56198. touch_.pointer = a.pointer.clone();
  56199. viewport = a.viewport; camera = a.camera;
  56200. }
  56201. });
  56202. //使用当前touches的平均
  56203. if(e.touches.length > 1){
  56204. let pageX = Common.average(e.touches, "pageX");
  56205. let pageY = Common.average(e.touches, "pageY");
  56206. let a = this.getPointerInViewport(pageX, pageY, viewport, new Vector2$1);
  56207. this.pointer.copy(a.pointer);
  56208. //console.log('updateTouchesInfo', this.pointer.clone())
  56209. }else {
  56210. this.pointer = this.touches[0].pointer.clone(); //更新,使用当前touches中的第一个
  56211. }
  56212. /* if(this.touches.find(e=>!e.pointer)){
  56213. console.error(' touches has no pointer', oldTouches.map(e=>e.touch.identifier),
  56214. Array.from(e.touches).map(e=>e.identifier), Array.from(e.changedTouches).map(e=>e.identifier) )
  56215. } */
  56216. //console.log(this.touches)
  56217. //console.log('更新pointer1',this.pointer.toArray())
  56218. return {viewport, camera/* , pointer:this.pointer */}
  56219. }
  56220. }
  56221. onTouchStart (e) {
  56222. if (this.logMessages) console.log(this.constructor.name + ': onTouchStart');
  56223. e.preventDefault();
  56224. /* if (e.touches.length === 1 || !this.drag) { //!this.drag代表一次性下了两个指头
  56225. let rect = this.domElement.getBoundingClientRect();
  56226. let x = e.touches[0].pageX
  56227. let y = e.touches[0].pageY
  56228. this.dealPointerDown(x,y,e,true)
  56229. }else{
  56230. this.updateTouchesInfo(e)
  56231. this.drag.end.copy(this.pointer)
  56232. } */
  56233. this.dealPointerDown(e,true);
  56234. this.viewer.dispatchEvent($.extend(
  56235. this.getEventDesc(e,true),
  56236. {
  56237. type: 'global_' + e.type,
  56238. changedTouches: e.changedTouches
  56239. }
  56240. ));
  56241. /* console.log('targetTouches :', Array.from(e.targetTouches).map(e=>'| identifier: '+ e.identifier),
  56242. 'changedTouches :', Array.from(e.changedTouches).map(e=>'| identifier: '+ e.identifier)
  56243. ) */
  56244. //console.log('')
  56245. }
  56246. onTouchMove (e) {
  56247. if (this.logMessages) console.log(this.constructor.name + ': onTouchMove');
  56248. e.preventDefault();
  56249. /* if (e.touches.length === 1) {
  56250. let rect = this.domElement.getBoundingClientRect();
  56251. let x = e.touches[0].pageX;
  56252. let y = e.touches[0].pageY;
  56253. }else{
  56254. this.updateTouchesInfo(e)
  56255. this.drag.pointerDelta.subVectors(this.pointer, this.drag.end)
  56256. this.drag.end.copy(this.pointer)
  56257. }
  56258. */
  56259. this.dealPointerMove(e, true);
  56260. this.viewer.dispatchEvent($.extend(
  56261. this.getEventDesc(e,true),
  56262. {
  56263. type: 'global_' + e.type,
  56264. changedTouches: e.changedTouches
  56265. }
  56266. ));
  56267. /* console.log('targetTouches :', Array.from(e.targetTouches).map(e=>'| identifier: '+ e.identifier),
  56268. 'changedTouches :', Array.from(e.changedTouches).map(e=>'| identifier: '+ e.identifier)
  56269. ) */
  56270. }
  56271. onTouchEnd (e) {
  56272. if (this.logMessages) console.log(this.constructor.name + ': onTouchEnd');
  56273. e.preventDefault();
  56274. //console.log('onTouchEnd')
  56275. this.updateTouchesInfo(e);
  56276. /* if (e.touches.length === 0) {
  56277. let rect = this.domElement.getBoundingClientRect();
  56278. let x = e.changedTouches[0].pageX //万一一次松开两个指头的怎么办
  56279. let y = e.changedTouches[0].pageY
  56280. this.dealPointerUp(x,y,e,true)
  56281. }else {
  56282. this.drag.end.copy(this.pointer)
  56283. } */
  56284. this.dealPointerUp(e,true);
  56285. this.viewer.dispatchEvent($.extend(
  56286. this.getEventDesc(e,true),
  56287. {
  56288. type: 'global_' + e.type,
  56289. }
  56290. ));
  56291. //console.log('touchend length '+e.touches.length, this.touches.length)
  56292. }
  56293. onKeyDown (e) {
  56294. if (this.logMessages) console.log(this.constructor.name + ': onKeyDown');
  56295. // DELETE
  56296. if (e.keyCode === KeyCodes.DELETE && this.selection.length > 0) {
  56297. this.dispatchEvent({
  56298. type: 'delete',
  56299. selection: this.selection
  56300. });
  56301. this.deselectAll();
  56302. }
  56303. this.dispatchEvent({
  56304. type: 'keydown',
  56305. keyCode: e.keyCode,
  56306. event: e
  56307. });
  56308. // for(let l of this.getSortedListeners()){
  56309. // l.dispatchEvent({
  56310. // type: "keydown",
  56311. // keyCode: e.keyCode,
  56312. // event: e
  56313. // });
  56314. // }
  56315. this.pressedKeys[e.keyCode] = true;
  56316. // e.preventDefault();
  56317. }
  56318. onKeyUp (e) {
  56319. if (this.logMessages) console.log(this.constructor.name + ': onKeyUp');
  56320. if(e.keyCode != void 0){
  56321. delete this.pressedKeys[e.keyCode];
  56322. }else {
  56323. this.pressedKeys = {};
  56324. }
  56325. e.preventDefault();
  56326. }
  56327. onDoubleClick (e) {
  56328. if (this.logMessages) console.log(this.constructor.name + ': onDoubleClick');
  56329. let consumed = false;
  56330. for (let hovered of this.hoveredElements) {
  56331. if (hovered._listeners && hovered._listeners['dblclick']) {
  56332. hovered.object.dispatchEvent({
  56333. type: 'dblclick',
  56334. mouse: this.mouse,
  56335. object: hovered.object
  56336. });
  56337. consumed = true;
  56338. break;
  56339. }
  56340. }
  56341. if (!consumed) {
  56342. /* for (let inputListener of this.getSortedListeners()) {
  56343. inputListener. */this.viewer.dispatchEvent({
  56344. type: 'global_dblclick',
  56345. mouse: this.mouse,
  56346. object: null
  56347. });
  56348. //}
  56349. }
  56350. this.needSingleClick = false;//add
  56351. e.preventDefault();
  56352. }
  56353. onMouseClick (e) {
  56354. if (this.logMessages) console.log(this.constructor.name + ': onMouseClick');
  56355. e.preventDefault();
  56356. }
  56357. dealPointerDown(e,isTouch){
  56358. e.preventDefault();
  56359. //重新获取一下pointer, 因点击了浏览器的按钮展开列表时 move回来不会触发onmousemove,所以pointer是旧的
  56360. if(isTouch){
  56361. var { camera, viewport } = this.updateTouchesInfo(e);
  56362. if(this.drag){
  56363. //因为触屏在按下前缺少pointermove所以要更新下
  56364. this.drag.end = this.pointer.clone();
  56365. }
  56366. }else {
  56367. var { camera, viewport } = this.getPointerInViewport(e.clientX, e.clientY );
  56368. }
  56369. this.dragViewport = this.hoverViewport = viewport;
  56370. if(isTouch || !Potree.settings.intersectWhenHover ){
  56371. this.hoveredElements = this.getHoveredElements();
  56372. this.intersect = this.getIntersect(viewport);
  56373. //this.intersect = this.getWholeIntersect()
  56374. }
  56375. if(!viewport)return
  56376. if(!isTouch || e.touches.length == 1){
  56377. let consumed = false;
  56378. let consume = () => { return consumed = true; };
  56379. //if (this.hoveredElements.length === 0) {
  56380. this.viewer.dispatchEvent($.extend(
  56381. this.getEventDesc(e,isTouch),
  56382. {
  56383. type: 'global_mousedown'
  56384. }
  56385. ));
  56386. for(let hovered of this.hoveredElements){
  56387. let object = hovered.object;
  56388. object.dispatchEvent({
  56389. type: 'mousedown',
  56390. viewer: this.viewer,
  56391. consume: consume
  56392. });
  56393. if(consumed){
  56394. break;
  56395. }
  56396. }
  56397. }
  56398. if (!this.drag) {
  56399. let target = (isTouch||e.button == MOUSE.LEFT) && this.hoveredElements.find(el => (//只有左键能拖拽
  56400. el.object._listeners &&
  56401. el.object._listeners['drag'] &&
  56402. el.object._listeners['drag'].length > 0));
  56403. if (target) {
  56404. this.startDragging(target.object, {location: target.point});
  56405. } else {
  56406. this.startDragging(null);
  56407. }
  56408. }
  56409. this.drag.intersectStart = this.intersect;
  56410. this.mouseDownMouse = this.mouse.clone();
  56411. this.pointerDownTime = Date.now();
  56412. }
  56413. onMouseDown (e) {
  56414. if (this.logMessages) console.log(this.constructor.name + ': onMouseDown');
  56415. this.dealPointerDown(e);
  56416. }
  56417. /* getWholeIntersect(hoveredElements, intersectPoint){//add
  56418. hoveredElements = hoveredElements || this.hoveredElements
  56419. intersectPoint = intersectPoint || this.intersectPoint
  56420. if(Potree.settings.intersectOnObjs && hoveredElements[0] && hoveredElements[0].object.isModel){
  56421. return {//模拟点云的intersectPoint的结构写法
  56422. hoveredElement : hoveredElements[0] ,
  56423. location: hoveredElements[0].point,
  56424. point: {normal: hoveredElements[0].face.normal },
  56425. distance: hoveredElements[0].distance,
  56426. object: hoveredElements[0].object
  56427. }
  56428. }else return intersectPoint
  56429. } */
  56430. getEventDesc(e,isTouch){//搜集dispatchEvent要给的一般数据
  56431. let o = {
  56432. viewer: this.viewer,
  56433. mouse: this.mouse,
  56434. pointer:this.pointer,
  56435. drag :this.drag,
  56436. isTouch,
  56437. dragViewport : this.dragViewport,
  56438. hoverViewport: this.hoverViewport,
  56439. // button: isTouch ? 0 : e.button,
  56440. //intersectPoint:this.intersectPoint,
  56441. hoveredElement: this.hoveredElements[0],
  56442. intersect: this.intersect//this.getWholeIntersect() , //可能包含mesh上的,针对融合页面
  56443. };
  56444. if(e){
  56445. o.isAtDomElement = e.target == this.domElement;
  56446. }
  56447. if(isTouch){
  56448. o.touches = this.touches;
  56449. }else if(e){
  56450. o.button = e.button;
  56451. o.buttons = e.buttons;
  56452. }
  56453. return o;
  56454. }
  56455. dealPointerUp(e,isTouch){
  56456. if(!this.drag){// 在canvas外mousedown
  56457. return
  56458. }
  56459. this.drag.end.copy(this.pointer);
  56460. if(isTouch && e.touches.length >= 1){
  56461. return
  56462. }
  56463. let now = Date.now();
  56464. if (this.logMessages) console.log(this.constructor.name + ': onMouseUp');
  56465. e.preventDefault();
  56466. let pressDistance = this.mouseDownMouse.distanceTo(this.mouse);
  56467. let pressTime = now - this.pointerDownTime;
  56468. let noMovement = this.drag.pointerDelta.length() == 0;//this.getNormalizedDrag().length() === 0;
  56469. let consumed = false;
  56470. let consume = () => { return consumed = true; };
  56471. //if (this.hoveredElements.length === 0) {
  56472. /* for (let inputListener of this.getSortedListeners()) {
  56473. inputListener */this.viewer.dispatchEvent($.extend(
  56474. this.getEventDesc(e,isTouch),
  56475. {
  56476. type: 'global_mouseup',
  56477. pressDistance,
  56478. consume,
  56479. }
  56480. ));
  56481. /* if(consumed){//??
  56482. break;
  56483. } */
  56484. //}
  56485. //}
  56486. if (this.hoveredElements.length > 0) {
  56487. let hovered = this.hoveredElements
  56488. .map(e => e.object)
  56489. .find(e => (e._listeners && e._listeners['mouseup']));
  56490. if(hovered){
  56491. hovered.dispatchEvent({
  56492. type: 'mouseup',
  56493. viewer: this.viewer,
  56494. consume: consume
  56495. });
  56496. }
  56497. }
  56498. if (this.drag) {
  56499. //拖拽结束
  56500. if (this.drag.object/* && e.button == THREE.MOUSE.LEFT */) {//add LEFT
  56501. if (this.logMessages) console.log(`${this.constructor.name}: drop ${this.drag.object.name}`);
  56502. this.drag.object.dispatchEvent($.extend(
  56503. this.getEventDesc(e,isTouch),
  56504. {
  56505. type: 'drop',
  56506. pressDistance,
  56507. }
  56508. ));
  56509. } else {
  56510. this.viewer.dispatchEvent($.extend(
  56511. this.getEventDesc(e,isTouch),
  56512. {
  56513. type: 'global_drop',
  56514. pressDistance
  56515. }
  56516. ));
  56517. }
  56518. // check for a click
  56519. if(pressDistance < Potree.config.clickMaxDragDis && pressTime<Potree.config.clickMaxPressTime){
  56520. let clickElement;
  56521. if(this.hoveredElements){
  56522. clickElement = this.hoveredElements.find(e=>e.object._listeners['click']);
  56523. if(clickElement){
  56524. //console.log('clickElement',clickElement)
  56525. if (this.logMessages) console.log(`${this.constructor.name}: click ${clickElement.name}`);
  56526. clickElement.object.dispatchEvent($.extend(
  56527. this.getEventDesc(e,isTouch),
  56528. {
  56529. type: 'click',
  56530. pressDistance
  56531. }
  56532. ));
  56533. }
  56534. }
  56535. let consumed = false;
  56536. let consume = () => { return consumed = true; };
  56537. let desc = this.getEventDesc(e,isTouch);
  56538. //if(!clickElement){
  56539. this.viewer.dispatchEvent($.extend(
  56540. desc,
  56541. {
  56542. type: 'global_click',
  56543. pressDistance,
  56544. clickElement,
  56545. consume
  56546. }
  56547. ));
  56548. //}
  56549. //增加 单击:
  56550. this.needSingleClick = true;
  56551. consumed || setTimeout(()=>{
  56552. if(this.needSingleClick){
  56553. this.viewer.dispatchEvent($.extend(
  56554. desc,
  56555. {
  56556. type: 'global_single_click',
  56557. pressDistance,
  56558. clickElement
  56559. }
  56560. ));
  56561. }
  56562. }, Potree.config.doubleClickTime+1);
  56563. //自行执行双击:
  56564. if(now - this.lastClickTime < Potree.config.doubleClickTime){
  56565. this.onDoubleClick(e);
  56566. }
  56567. this.lastClickTime = now;
  56568. }
  56569. this.drag = null;
  56570. }
  56571. this.dragViewport = null;
  56572. if(!consumed && !this.fixSelection){
  56573. if (e.button === MOUSE.LEFT) {
  56574. if (noMovement) {
  56575. let selectable = this.hoveredElements
  56576. .find(el => el.object._listeners && el.object._listeners['select']);
  56577. if (selectable) {
  56578. selectable = selectable.object;
  56579. if (this.isSelected(selectable)) {
  56580. this.selection
  56581. .filter(e => e !== selectable)
  56582. .forEach(e => this.toggleSelection(e));
  56583. } else {
  56584. this.deselectAll();
  56585. this.toggleSelection(selectable);
  56586. }
  56587. } else {
  56588. this.deselectAll();
  56589. }
  56590. }
  56591. } else if ((e.button === MOUSE.RIGHT) && noMovement) {
  56592. this.deselectAll();
  56593. }
  56594. }
  56595. }
  56596. onMouseUp (e) {
  56597. this.dealPointerUp( e );
  56598. }
  56599. getPointerInViewport(clientX, clientY, viewForceAt, pointer ){
  56600. let rect = this.domElement.getBoundingClientRect();
  56601. let x = clientX - rect.left;
  56602. let y = clientY - rect.top;
  56603. let camera;
  56604. let viewport;
  56605. pointer = pointer ||this.pointer;
  56606. //if(this.viewer.viewports || viewForceAt){
  56607. var getDimension = (view)=>{
  56608. var left = Math.ceil(this.domElement.clientWidth * view.left)
  56609. , bottom = Math.ceil(this.domElement.clientHeight * view.bottom)
  56610. , width = Math.ceil(this.domElement.clientWidth * view.width)
  56611. , height = Math.ceil(this.domElement.clientHeight * view.height)
  56612. , top = this.domElement.clientHeight - bottom - height;
  56613. return {left, bottom, width, height, top}
  56614. };
  56615. var getView = (view, left, bottom, width, height, top)=>{
  56616. this.mouse.set(x-left, y - top );
  56617. Utils.convertScreenPositionToNDC(pointer, this.mouse, width, height);
  56618. //console.log('更新pointer2',this.pointer.toArray())
  56619. camera = view.camera;
  56620. viewport = view;
  56621. };
  56622. if(viewForceAt){
  56623. let {left, bottom, width, height, top} = getDimension(viewForceAt);
  56624. getView(viewForceAt, left, bottom, width, height, top);
  56625. }else {
  56626. var length = this.viewer.viewports.length;
  56627. //var getif = false
  56628. for(var i=0;i<length;i++){
  56629. var view = this.viewer.viewports[i];
  56630. if(!view.active)continue
  56631. var {left, bottom, width, height, top} = getDimension(view);
  56632. if(x >= left && x <= left + width && y >= top && y <= top + height){
  56633. getView(view, left, bottom, width, height, top);
  56634. //getif = true
  56635. break;
  56636. }
  56637. }
  56638. }
  56639. return {
  56640. camera, viewport, pointer
  56641. }
  56642. }
  56643. ifBlockedByIntersect(point, margin=0, usePointcloud, cameraPos, pickWindowSize, pano){//某点是否被遮挡(不允许camera修改位置, 因为depthTex不好置换)
  56644. if(cameraPos){
  56645. usePointcloud = true; //只有使用点云才允许换位置
  56646. }
  56647. let intersect = this.getIntersect(this.hoverViewport, true, pickWindowSize, null, usePointcloud, {point, cameraPos, pano});
  56648. let cameraPos_ = (!usePointcloud && pano) ? pano.position : (cameraPos||this.hoverViewport.view.position);
  56649. if(intersect && intersect.distance+margin <= point.distanceTo(cameraPos_)){
  56650. return intersect //被遮挡
  56651. }
  56652. //点云模式,对没加载出的点云不准确。 尤其是需要修改相机位置时,因临时修改并不能使点云加载。
  56653. }
  56654. getIntersect(viewport, onlyGetIntersect, pickWindowSize, dontIntersect, usePointcloud, prop={}){
  56655. let intersectPoint;
  56656. let camera = viewport.camera;
  56657. let raycaster;
  56658. if(Potree.settings.displayMode == 'showPanos' && viewer.images360.currentPano.pointcloud.hasDepthTex && !usePointcloud && !this.isMeasuring && viewport == viewer.mainViewport ){
  56659. /* if(prop.point){
  56660. raycaster = new THREE.Raycaster()
  56661. var dir = new THREE.Vector3().subVectors(prop.point, camera.position).normalize()
  56662. raycaster.set(camera.position, dir) //var origin = new THREE.Vector3(pointer.x, pointer.y, -1).unproject(camera),
  56663. } */
  56664. let intersect;
  56665. if(prop.point){
  56666. let cameraPos = prop.pano ? prop.pano.position : camera.position;
  56667. let dir = new Vector3().subVectors(prop.point, cameraPos).normalize();
  56668. intersect = {dir};
  56669. }else {
  56670. intersect = Utils.getIntersect(camera, [viewer.images360.cube], this.pointer, raycaster);
  56671. }
  56672. intersectPoint = viewer.images360.depthSampler.sample(intersect, prop.pano, !!prop.point); //可能不准确, 因pano可能未加载depthTex
  56673. }else {
  56674. if(prop.point){
  56675. prop.cameraPos && camera.position.copy(prop.cameraPos);
  56676. camera.lookAt(prop.point);
  56677. camera.updateMatrixWorld();
  56678. prop.pointer = this.pointer.clone();
  56679. prop.mouse = this.mouse.clone();
  56680. this.pointer.set(0,0); //画布中心
  56681. this.mouse.set(Math.round(viewport.resolution.x/2), Math.round(viewport.resolution.y/2));
  56682. }
  56683. intersectPoint = (viewport.noPointcloud || dontIntersect)? null : Utils.getMousePointCloudIntersection(
  56684. viewport,
  56685. this.mouse,
  56686. this.pointer,
  56687. camera,
  56688. this.viewer,
  56689. this.viewer.scene.pointclouds,
  56690. {pickClipped: true, isMeasuring: this.isMeasuring, pickWindowSize, cameraChanged: !!prop.point }
  56691. );
  56692. //恢复
  56693. if(prop.point){
  56694. viewport.view.applyToCamera(camera);
  56695. this.pointer.copy(prop.pointer);
  56696. this.mouse.copy(prop.mouse);
  56697. }
  56698. }
  56699. //console.log(viewport.name , intersectPoint && intersectPoint.location )
  56700. let intersect;
  56701. let intersectOnModel, allElements;
  56702. if(Potree.settings.intersectOnObjs && !dontIntersect){
  56703. if(prop.point){
  56704. raycaster = new Raycaster();
  56705. var dir = new Vector3().subVectors(prop.point, camera.position).normalize();
  56706. raycaster.set(camera.position, dir); //var origin = new THREE.Vector3(pointer.x, pointer.y, -1).unproject(camera),
  56707. }
  56708. allElements = this.getHoveredElements(viewer.objs.children, true, raycaster);
  56709. if(allElements[0]){
  56710. intersectOnModel = {//模拟点云的intersectPoint的结构写法
  56711. hoveredElement : allElements[0] ,
  56712. location: allElements[0].point,
  56713. //point: {normal: allElements[0].face.normal },
  56714. normal: allElements[0].face.normal,
  56715. distance: allElements[0].distance,
  56716. object: allElements[0].object
  56717. };
  56718. }
  56719. }
  56720. if(intersectPoint && intersectOnModel){
  56721. if(intersectPoint.distance < intersectOnModel.distance){
  56722. intersect = intersectPoint;
  56723. }else {
  56724. intersect = intersectOnModel;
  56725. }
  56726. }else {
  56727. intersect = intersectOnModel || intersectPoint;
  56728. }
  56729. if(viewport.camera.type == 'OrthographicCamera'/* == 'mapViewport' */){
  56730. let pos3d = new Vector3(this.pointer.x,this.pointer.y,-1).unproject(viewport.camera); //z:-1朝外
  56731. if(!intersect){
  56732. intersect = {};
  56733. }
  56734. intersect.orthoIntersect = pos3d.clone();
  56735. }
  56736. //记录全部hover到的:
  56737. if(intersect){
  56738. intersect.allElements = allElements;
  56739. intersect.pointclouds = intersectPoint ? intersectPoint.pointclouds : [];
  56740. }
  56741. if(onlyGetIntersect){
  56742. return intersect
  56743. }
  56744. if (intersect) {
  56745. if(viewer.showCoordType){ //显示坐标位置时
  56746. let pos = intersect.point.position.toArray();
  56747. if(viewer.showCoordType == "local"){
  56748. }else if(viewer.showCoordType == "lonlat"){
  56749. pos = viewer.transform.lonlatToLocal.inverse(pos);
  56750. }else {
  56751. pos = viewer.transform.lonlatToLocal.inverse(pos);
  56752. pos = viewer.transform.lonlatTo4550.forward(pos);
  56753. }
  56754. viewer.dispatchEvent({
  56755. type : "coordinateChange", pos
  56756. });
  56757. }
  56758. }
  56759. //console.log('getIntersect', !!intersectPoint)
  56760. this.intersect = intersect;
  56761. intersect && (this.hoverViewport.lastIntersect = intersect);
  56762. return intersect
  56763. }
  56764. onMouseMove (e) {
  56765. return this.dealPointerMove( e )
  56766. }
  56767. dealPointerMove(e, isTouch){
  56768. if(isTouch){
  56769. var { camera, viewport } = this.updateTouchesInfo(e);
  56770. }else {
  56771. var { camera, viewport } = this.getPointerInViewport(e.clientX, e.clientY, this.dragViewport);
  56772. }
  56773. this.hoverViewport = viewport;
  56774. if(!viewport)return//刚变化viewport时会找不到
  56775. let isFlying = this.viewer.viewports.some(e=>e.view.isFlying()) || viewer.scene.cameraAnimations.some(c=>c.onUpdate);
  56776. let intersect;
  56777. if(e.onlyGetIntersect || Potree.settings.intersectWhenHover && (!this.drag || this.drag.object || viewport.alignment ) ){ //没有拖拽物体,但按下鼠标了的话,不intersect
  56778. let dontIntersect = this.drag && viewport.alignment/* && Potree.settings.editType == 'pano' */|| isFlying;/* viewer.images360.flying */ // flying 时可能卡顿
  56779. //console.log('dontIntersectPointcloud',dontIntersectPointcloud)
  56780. intersect = this.getIntersect(viewport, e.onlyGetIntersect, e.pickWindowSize, !!dontIntersect, e.whichPointcloud); //数据集多的时候卡顿
  56781. //console.log('intersectPoint', intersectPoint)
  56782. }
  56783. if(e.onlyGetIntersect){
  56784. /* if(Potree.settings.intersectOnObjs){
  56785. let hoveredElements = this.getHoveredElements() //应该不用发送mouseover事件吧
  56786. let intersect = this.getWholeIntersect(hoveredElements, intersectPoint)
  56787. return intersect
  56788. }
  56789. return intersectPoint */
  56790. return intersect
  56791. }
  56792. e.preventDefault();
  56793. /* if(intersectPoint && intersectPoint.pointcloud){
  56794. console.log(intersectPoint.pointcloud.name)
  56795. } */
  56796. if (this.drag) {//有拖拽(不一定拖拽了物体, 也不一定按下了鼠标)
  56797. this.drag.mouse = isTouch ? 1 : e.buttons;
  56798. //add:
  56799. //this.drag.pointer = this.pointer.clone();
  56800. //this.drag.hoverViewport = this.hoverViewport
  56801. this.drag.pointerDelta.subVectors(this.pointer, this.drag.end);
  56802. this.drag.end.copy(this.pointer);
  56803. if (this.drag.object && (e.buttons == Buttons.NONE || !this.drag.notPressMouse )){//如果是本不需要按鼠标的拖拽,但按下了鼠标,就不执行这段(改为拖拽场景,如添加测量时突然拖拽画面)
  56804. if (this.logMessages) console.log(this.constructor.name + ': drag: ' + this.drag.object.name);
  56805. this.drag.object.dispatchEvent($.extend(
  56806. this.getEventDesc(e,isTouch),
  56807. {
  56808. type: 'drag', //拖拽物体
  56809. }
  56810. ));
  56811. } else {
  56812. if (this.logMessages) console.log(this.constructor.name + ': drag: ');
  56813. let dragConsumed = false;
  56814. this.viewer.dispatchEvent($.extend(
  56815. this.getEventDesc(e,isTouch),
  56816. {
  56817. type: 'global_drag', //拖拽画面
  56818. consume: () => {dragConsumed = true;}
  56819. }
  56820. ));
  56821. }
  56822. }
  56823. if(!isTouch || e.touches.length == 1){
  56824. if((!this.drag || this.drag.notPressMouse || Potree.settings.intersectOnObjs && this.drag.object) && !isFlying){
  56825. /* let blacklist = this.drag && this.drag */
  56826. let hoveredElements = this.getHoveredElements( );
  56827. if(hoveredElements.length > 0){
  56828. let names = hoveredElements.map(h => h.object.name).join(", ");
  56829. if (this.logMessages) console.log(`${this.constructor.name}: onMouseMove; hovered: '${names}'`);
  56830. }
  56831. let curr = hoveredElements.map(a => a.object).find(a => true);//只取第一个
  56832. let prev = this.lastMouseoverElement; //this.hoveredElements.map(a => a.object).find(a => true);
  56833. if(curr !== prev){
  56834. if(curr){
  56835. if (this.logMessages) console.log(`${this.constructor.name}: mouseover: ${curr.name}`);
  56836. curr.dispatchEvent({
  56837. type: 'mouseover',
  56838. object: curr,
  56839. });
  56840. }
  56841. if(prev){
  56842. if (this.logMessages) console.log(`${this.constructor.name}: mouseleave: ${prev.name}`);
  56843. prev.dispatchEvent({
  56844. type: 'mouseleave',
  56845. object: prev,
  56846. });
  56847. }
  56848. this.lastMouseoverElement = curr;
  56849. }
  56850. if(hoveredElements.length > 0){
  56851. let object = hoveredElements
  56852. .map(e => e.object)
  56853. .find(e => (e._listeners && e._listeners['mousemove']));
  56854. if(object){
  56855. object.dispatchEvent({
  56856. type: 'mousemove',
  56857. object: object
  56858. });
  56859. }
  56860. }
  56861. this.hoveredElements = hoveredElements;
  56862. }
  56863. //this.intersect = this.getWholeIntersect()
  56864. this.viewer.dispatchEvent($.extend(
  56865. this.getEventDesc(e,isTouch),
  56866. {
  56867. type: 'global_mousemove',
  56868. }
  56869. ));
  56870. }
  56871. }
  56872. onMouseWheel(e){
  56873. if(!this.enabled) return;
  56874. if(this.logMessages) console.log(this.constructor.name + ": onMouseWheel");
  56875. e.preventDefault();
  56876. let delta = 0;
  56877. if (e.wheelDelta !== undefined) { // WebKit / Opera / Explorer 9
  56878. delta = e.wheelDelta;
  56879. } else if (e.detail !== undefined) { // Firefox
  56880. delta = -e.detail;
  56881. }
  56882. let ndelta = Math.sign(delta);
  56883. // this.wheelDelta += Math.sign(delta);
  56884. if(!this.hoverViewport){//调试手机版时会无
  56885. var { viewport } = this.getPointerInViewport(e.clientX, e.clientY );
  56886. this.hoverViewport = viewport;
  56887. }
  56888. if (this.hoveredElement) {
  56889. this.hoveredElement.object.dispatchEvent($.extend(
  56890. this.getEventDesc(e,isTouch),
  56891. {
  56892. type: 'mousewheel',
  56893. delta: ndelta,
  56894. object: this.hoveredElement.object
  56895. }
  56896. ));
  56897. } else {
  56898. this.viewer.dispatchEvent($.extend(
  56899. this.getEventDesc(e),
  56900. {
  56901. type: 'global_mousewheel',
  56902. delta: ndelta,
  56903. }
  56904. ));
  56905. }
  56906. }
  56907. startDragging (object, args = null) {
  56908. let name = object ? object.name : "no name";
  56909. if (this.logMessages) console.log(`${this.constructor.name}: startDragging: '${name}'`);
  56910. this.drag = {
  56911. start: this.pointer.clone(),
  56912. end: this.pointer.clone(),
  56913. pointerDelta: new Vector2$1(0, 0),
  56914. object: object,
  56915. hoverViewport: this.hoverViewport, //会变化
  56916. dragViewport: this.hoverViewport, //不变
  56917. };
  56918. if (args) {
  56919. for (let key of Object.keys(args)) {
  56920. this.drag[key] = args[key];
  56921. }
  56922. }
  56923. if(object){
  56924. object.dispatchEvent($.extend(
  56925. this.getEventDesc(),
  56926. {
  56927. type: 'startDragging'
  56928. }
  56929. ));
  56930. }
  56931. }
  56932. /* getMousePointCloudIntersection (mouse) {
  56933. return Utils.getMousePointCloudIntersection(
  56934. this.mouse,
  56935. this.scene.getActiveCamera(),
  56936. this.viewer,
  56937. this.scene.pointclouds);
  56938. } */
  56939. toggleSelection (object) {
  56940. let oldSelection = this.selection;
  56941. let index = this.selection.indexOf(object);
  56942. if (index === -1) {
  56943. this.selection.push(object);
  56944. object.dispatchEvent({
  56945. type: 'select'
  56946. });
  56947. } else {
  56948. this.selection.splice(index, 1);
  56949. object.dispatchEvent({
  56950. type: 'deselect'
  56951. });
  56952. }
  56953. this.dispatchEvent({
  56954. type: 'selection_changed',
  56955. oldSelection: oldSelection,
  56956. selection: this.selection
  56957. });
  56958. }
  56959. deselect(object){
  56960. let oldSelection = this.selection;
  56961. let index = this.selection.indexOf(object);
  56962. if(index >= 0){
  56963. this.selection.splice(index, 1);
  56964. object.dispatchEvent({
  56965. type: 'deselect'
  56966. });
  56967. this.dispatchEvent({
  56968. type: 'selection_changed',
  56969. oldSelection: oldSelection,
  56970. selection: this.selection
  56971. });
  56972. }
  56973. }
  56974. deselectAll () {
  56975. for (let object of this.selection) {
  56976. object.dispatchEvent({
  56977. type: 'deselect'
  56978. });
  56979. }
  56980. let oldSelection = this.selection;
  56981. if (this.selection.length > 0) {
  56982. this.selection = [];
  56983. this.dispatchEvent({
  56984. type: 'selection_changed',
  56985. oldSelection: oldSelection,
  56986. selection: this.selection
  56987. });
  56988. }
  56989. }
  56990. isSelected (object) {
  56991. let index = this.selection.indexOf(object);
  56992. return index !== -1;
  56993. }
  56994. registerInteractiveObject(object){
  56995. this.interactiveObjects.add(object);
  56996. }
  56997. removeInteractiveObject(object){
  56998. this.interactiveObjects.delete(object);
  56999. }
  57000. registerInteractiveScene (scene) {
  57001. let index = this.interactiveScenes.indexOf(scene);
  57002. if (index === -1) {
  57003. this.interactiveScenes.push(scene);
  57004. }
  57005. }
  57006. unregisterInteractiveScene (scene) {
  57007. let index = this.interactiveScenes.indexOf(scene);
  57008. if (index > -1) {
  57009. this.interactiveScenes.splice(index, 1);
  57010. }
  57011. }
  57012. getHoveredElement () {
  57013. let hoveredElements = this.getHoveredElements();
  57014. if (hoveredElements.length > 0) {
  57015. return hoveredElements[0];
  57016. } else {
  57017. return null;
  57018. }
  57019. }
  57020. getHoveredElements (interactables, dontCheckDis, raycaster) {
  57021. if(!interactables){
  57022. let scenes = this.hoverViewport.interactiveScenes || this.interactiveScenes.concat(this.scene);
  57023. let interactableListeners = ['mouseup', 'mousemove', 'mouseover', 'mouseleave', 'drag', 'drop', 'click', 'select', 'deselect'];
  57024. interactables = [];
  57025. for (let scene of scenes) {
  57026. scene.traverseVisible(node => {//检测加了侦听的object
  57027. if (node._listeners && node.visible && !this.blacklist.has(node) ) {
  57028. let hasInteractableListener = interactableListeners.filter((e) => {
  57029. return node._listeners[e] !== undefined;
  57030. }).length > 0;
  57031. if (hasInteractableListener) {
  57032. interactables.push(node);
  57033. }
  57034. }
  57035. });
  57036. }
  57037. }
  57038. let camera = this.hoverViewport.camera;
  57039. if(!raycaster){
  57040. let ray = Utils.mouseToRay(this.pointer, camera );
  57041. raycaster = new Raycaster();
  57042. raycaster.ray.set(ray.origin, ray.direction);
  57043. raycaster.camera = camera; //add
  57044. }
  57045. if(camera.type == "OrthographicCamera"){//使无论多远,threshold区域都是一样宽的
  57046. raycaster.params.Line.threshold = 20/camera.zoom;
  57047. }else {
  57048. raycaster.params.Line.threshold = 0.2;
  57049. }
  57050. raycaster.params.Line2 = {threshold :20 }; //拓宽的lineWidth
  57051. //raycaster.layers.enableAll()//add
  57052. viewer.setCameraLayers(raycaster, //设置能识别到的layers(如空间模型里只有mapViewer能识别到marker)
  57053. ['sceneObjects','mapObjects','measure', 'transformationTool', 'model'],
  57054. this.hoverViewport && this.hoverViewport.extraEnableLayers
  57055. );
  57056. viewer.dispatchEvent( {type:'raycaster', viewport: this.hoverViewport});//add
  57057. let intersections = raycaster.intersectObjects(interactables.filter(o => o.visible), true); //原本是false 检测不到children
  57058. let intersectionsCopy = intersections.slice();
  57059. if(this.intersect && this.intersect.distance != void 0 && !dontCheckDis){//add
  57060. intersections = intersections.filter(e=>{
  57061. let material = e.object.material;
  57062. return (e.object.pickDontCheckDis || material.depthTest == false || material.depthWrite == false) && !material.useDepth //!material.depthTestWhenPick
  57063. || ( material.useDepth ? e.distance < this.intersect.distance + material.uniforms.occlusionDistance.value : e.distance < this.intersect.distance )
  57064. });
  57065. }
  57066. intersections = intersections.map(e=>{//add 转化为interactables
  57067. var object = e.object;
  57068. do{
  57069. if(interactables.includes(object)) {
  57070. e.oriObject = e.object;
  57071. e.object = object;
  57072. break
  57073. }
  57074. object = object.parent;
  57075. }while(object)
  57076. return e
  57077. });
  57078. //add for测量线,在检测到sphere时优先选中sphere而非线
  57079. //intersections = intersections.sort(function(a,b){return b.object.renderOrder-a.object.renderOrder}) // 降序
  57080. intersections = intersections.sort(function(a,b){
  57081. let order2 = b.object.pickOrder || 0;
  57082. let order1 = a.object.pickOrder || 0;
  57083. return order2-order1
  57084. }); // 降序
  57085. //console.log('getHoveredElement ', intersections)
  57086. return intersections;
  57087. }
  57088. /* setScene (scene) {
  57089. this.deselectAll();
  57090. this.scene = scene;
  57091. } */
  57092. update (delta) {
  57093. }
  57094. /*getNormalizedDrag () {
  57095. if (!this.drag) {
  57096. return new THREE.Vector2(0, 0);
  57097. }
  57098. let diff = new THREE.Vector2().subVectors(this.drag.end, this.drag.start);
  57099. diff.x = diff.x / this.domElement.clientWidth;
  57100. diff.y = diff.y / this.domElement.clientHeight;
  57101. return diff;
  57102. }
  57103. getNormalizedLastDrag () {
  57104. if (!this.drag) {
  57105. return new THREE.Vector2(0, 0);
  57106. }
  57107. let mouseDelta = this.drag.mouseDelta.clone();
  57108. mouseDelta.x = mouseDelta.x / this.domElement.clientWidth;
  57109. mouseDelta.y = mouseDelta.y / this.domElement.clientHeight;
  57110. return mouseDelta;
  57111. } */
  57112. getMouseDirection(pointer) {//add
  57113. pointer = pointer || this.pointer;
  57114. let camera = this.hoverViewport.camera;
  57115. var t = new Vector3(pointer.x, pointer.y, -1).unproject(camera),
  57116. i = new Vector3(pointer.x, pointer.y, 1).unproject(camera);
  57117. return {origin: t, direction:i.clone().sub(t).normalize() }
  57118. }
  57119. }
  57120. class ViewerBase extends EventDispatcher{
  57121. constructor(domElement, args = {}){
  57122. super();
  57123. this.name = args.name;
  57124. this.renderArea = domElement;
  57125. this.oldResolution = new Vector2$1();
  57126. this.screenSizeInfo = {
  57127. W:0, H:0, pixelRatio:1 , windowWidth:0, windowHeight:0
  57128. };
  57129. this.initContext(args);
  57130. this.addEventListener('content_changed', ()=>{//画面改变,需要渲染
  57131. this.needRender = true;
  57132. });
  57133. }
  57134. initContext(args){
  57135. //console.log(`initializing three.js ${THREE.REVISION}`);
  57136. let width = this.renderArea.clientWidth;
  57137. let height = this.renderArea.clientHeight;
  57138. let contextAttributes = {
  57139. alpha: true,
  57140. depth: true,
  57141. stencil: false,
  57142. antialias: true,
  57143. preserveDrawingBuffer: true,
  57144. powerPreference: "high-performance",
  57145. };
  57146. let canvas = document.createElement("canvas");
  57147. let context = canvas.getContext('webgl', contextAttributes );
  57148. this.renderer = new WebGLRenderer({
  57149. alpha: true, //支持透明
  57150. premultipliedAlpha: false,
  57151. canvas: canvas,
  57152. context: context,
  57153. });
  57154. this.renderer.sortObjects = true; //原先false 打开了renderOrder才奏效
  57155. //this.renderer.setSize(width, height);
  57156. this.renderer.autoClear = args.autoClear || false;
  57157. //args.clearColor = args.clearColor || '#aa0033'
  57158. args.clearColor && this.renderer.setClearColor(args.clearColor);
  57159. this.renderArea.appendChild(this.renderer.domElement);
  57160. this.renderer.domElement.tabIndex = '2222';
  57161. this.renderer.domElement.style.position = 'absolute';
  57162. this.renderer.domElement.addEventListener('mousedown', () => {
  57163. this.renderer.domElement.focus();
  57164. });
  57165. //this.renderer.domElement.focus();
  57166. // NOTE: If extension errors occur, pass the string into this.renderer.extensions.get(x) before enabling
  57167. // enable frag_depth extension for the interpolation shader, if available
  57168. let gl = this.renderer.getContext();
  57169. gl.getExtension('EXT_frag_depth');
  57170. gl.getExtension('WEBGL_depth_texture');
  57171. gl.getExtension('WEBGL_color_buffer_float'); // Enable explicitly for more portability, EXT_color_buffer_float is the proper name in WebGL 2
  57172. if(gl.createVertexArray == null){
  57173. let extVAO = gl.getExtension('OES_vertex_array_object');
  57174. if(!extVAO){
  57175. throw new Error("OES_vertex_array_object extension not supported");
  57176. }
  57177. gl.createVertexArray = extVAO.createVertexArrayOES.bind(extVAO);
  57178. gl.bindVertexArray = extVAO.bindVertexArrayOES.bind(extVAO);
  57179. }
  57180. /* let oldClear = gl.clear;
  57181. gl.clear = (bits)=>{
  57182. console.error('clear')
  57183. }
  57184. */
  57185. }
  57186. updateScreenSize(o={}) { //有可能需要让viewport来判断,当窗口大小不变但viewport大小变时
  57187. var render = false, ratio, w, h;
  57188. //记录应当render的大小
  57189. if (o.width != void 0 && o.height != void 0) {
  57190. w = o.width;
  57191. h = o.height;
  57192. render = true;
  57193. ratio = 1;
  57194. }else {
  57195. w = this.renderArea.clientWidth;
  57196. h = this.renderArea.clientHeight;
  57197. if(w !== this.screenSizeInfo.W || h !== this.screenSizeInfo.H || o.forceUpdateSize || this.screenSizeInfo.pixelRatio != window.devicePixelRatio){
  57198. this.screenSizeInfo.W = w;
  57199. this.screenSizeInfo.H = h;
  57200. render = true;
  57201. this.screenSizeInfo.pixelRatio = window.devicePixelRatio; //如果player放在小窗口了,也要监测devicePixelRatio,因为缩放时client宽高不会改变
  57202. //config.isMobile ? (ratio = Math.min(window.devicePixelRatio, 2)) : (ratio = window.devicePixelRatio)
  57203. ratio = window.devicePixelRatio;
  57204. }
  57205. }
  57206. if (render) {
  57207. this.setSize(w, h, ratio);
  57208. }
  57209. }
  57210. /* updateScreenSize(o={}) { //容易出错。。
  57211. var render = false, ratio, w, h;
  57212. //记录应当render的大小
  57213. if (o.width != void 0 && o.height != void 0) {
  57214. w = o.width
  57215. h = o.height
  57216. render = true
  57217. ratio = 1
  57218. }else {
  57219. w = this.renderArea.clientWidth;
  57220. h = this.renderArea.clientHeight
  57221. let refreshWin = ()=>{
  57222. this.screenSizeInfo.windowWidth = window.innerWidth
  57223. this.screenSizeInfo.windowHeight = window.innerHeight
  57224. }
  57225. let prepareToRender = ()=>{
  57226. w = this.renderArea.clientWidth;
  57227. h = this.renderArea.clientHeight
  57228. this.screenSizeInfo.W = w
  57229. this.screenSizeInfo.H = h
  57230. refreshWin() //render后才refreshWin
  57231. render = true
  57232. this.screenSizeInfo.pixelRatio = window.devicePixelRatio //如果player放在小窗口了,也要监测devicePixelRatio,因为缩放时client宽高不会改变
  57233. //config.isMobile ? (ratio = Math.min(window.devicePixelRatio, 2)) : (ratio = window.devicePixelRatio)
  57234. ratio = window.devicePixelRatio
  57235. //console.log('setSize11', w)
  57236. o.forceUpdateSize = false ;//防止再次render
  57237. }
  57238. let ifNeedUpdate = ()=>{
  57239. w = this.renderArea.clientWidth;
  57240. h = this.renderArea.clientHeight
  57241. return o.forceUpdateSize || w !== this.screenSizeInfo.W || h !== this.screenSizeInfo.H || this.screenSizeInfo.pixelRatio != window.devicePixelRatio
  57242. }
  57243. if(ifNeedUpdate()){
  57244. //当只有一个有效viewport时,且因为改变整个窗口大小而触发的话,延时
  57245. let canInterval = !o.forceUpdateSize && this.viewports.filter(e=>e.active).length==1 && (this.screenSizeInfo.windowWidth != window.innerWidth || this.screenSizeInfo.windowHeight != window.innerHeight )
  57246. if(canInterval){
  57247. Common.intervalTool.isWaiting('updateScreenSize', ()=>{ //延时update,防止崩溃 , 未到时间就拦截(第一次直接执行)
  57248. if(ifNeedUpdate()){
  57249. prepareToRender()
  57250. return true
  57251. }
  57252. }, 500)
  57253. }else{
  57254. //console.log('soon', window.innerWidth, this.screenSizeInfo.windowWidth)
  57255. prepareToRender()
  57256. }
  57257. }
  57258. }
  57259. if (render) {
  57260. this.setSize(w, h, ratio);
  57261. }
  57262. } */
  57263. setSize(width, height, devicePixelRatio, onlyForTarget){
  57264. //console.log('setSize', width)
  57265. if(!onlyForTarget){//onlyForTarget表示不更改当前renderer,只是为了rendertarget才要改变viewport
  57266. this.renderer.setSize(width, height, null, devicePixelRatio); // resize之后会自动clear(似乎因为setScissor ),所以一定要立刻绘制,所以setSize要在cameraChanged、update之前
  57267. }
  57268. this.composer && this.composer.setSize(width, height);
  57269. if(this.viewports){
  57270. this.viewports.forEach((view,i)=>{
  57271. if(!view.active)return
  57272. var width_ = width * view.width;
  57273. var height_ = height * view.height;
  57274. if(height_ == 0)return //avoid NAN
  57275. view.setResolution(Math.ceil(width_), Math.ceil(height_), width, height ); //本来应该是floor,但是这样奇数时会少一个像素,导致向左移一个像素且宽度少1。现在则多绘制1个像素,超出的1个像素应该不会绘制出来(但不知道其他地方是否有偏差,比如pick时)
  57276. let aspect = width_ / height_; //camera的参数精确些,不用视口的归整的resolution像素值,否则hasChange无法为true, 导致canvasResize了但map没update从而闪烁
  57277. view.camera.aspect = aspect;
  57278. if(view.camera.type == "OrthographicCamera"){
  57279. /* //不改宽度 同4dkk
  57280. var heightHalf = view.camera.right / aspect
  57281. view.camera.top = heightHalf
  57282. view.camera.bottom = -heightHalf */
  57283. //高宽都改 使大小不随视口大小改变 navvis (直接和视口大小一致即可,通过zoom来定大小)
  57284. view.camera.left = -width_/2;
  57285. view.camera.right = width_/2;
  57286. view.camera.bottom = -height_/2;
  57287. view.camera.top = height_/2;
  57288. }else {
  57289. }
  57290. view.camera.updateProjectionMatrix();
  57291. });
  57292. }
  57293. if(!onlyForTarget){//因为onlyForTarget不传递devicePixelRatio所以不发送了
  57294. this.emitResizeMsg({viewport:this.viewports[0], deviceRatio:devicePixelRatio});
  57295. }
  57296. }
  57297. emitResizeMsg(e){//切换viewport渲染时就发送一次, 通知一些材质更新resolution。
  57298. if(!e.viewport.resolution.equals(this.oldResolution)){
  57299. this.dispatchEvent($.extend(e, {type:'resize'}));
  57300. this.oldResolution.copy(e.viewport.resolution);
  57301. }
  57302. }
  57303. cameraChanged() {//判断相机是否改变
  57304. var changed = false;
  57305. /* if(this.needRender){
  57306. this.needRender = false
  57307. return true
  57308. } */
  57309. for(let i=0,j=this.viewports.length;i<j;i++){
  57310. let changeInfo = this.viewports[i].cameraChanged();
  57311. if(changeInfo.changed){
  57312. changed = true;
  57313. //if(!this.changeTime ||this.changeTime<100){
  57314. this.dispatchEvent({
  57315. type: "camera_changed",
  57316. camera: this.viewports[i].camera,
  57317. viewport : this.viewports[i],
  57318. changeInfo
  57319. });
  57320. //this.changeTime = (this.changeTime || 0) +1
  57321. //}
  57322. }
  57323. }
  57324. return changed
  57325. }
  57326. makeScreenshot( size, viewports, compressRatio){//暂时不要指定viewports渲染,但也可以
  57327. let {width, height} = size;
  57328. /* let oldBudget = Potree.pointBudget;
  57329. Potree.pointBudget = Math.max(10 * 1000 * 1000, 2 * oldBudget);
  57330. let result = Potree.updatePointClouds(this.scene.pointclouds, camera, size );
  57331. Potree.pointBudget = oldBudget;
  57332. this.dispatchEvent({ //resize everything such as lines targets
  57333. type: 'resize',
  57334. resolution: new THREE.Vector2(width,height),
  57335. });*/
  57336. let target = new WebGLRenderTarget(width, height, {
  57337. format: RGBAFormat,
  57338. });
  57339. this.setSize(width, height,1,true);
  57340. this.render({
  57341. target ,
  57342. //camera ,
  57343. viewports: viewports || this.viewports,
  57344. screenshot : true,
  57345. width ,
  57346. height,
  57347. resize :true //需要resize
  57348. });
  57349. let dataUrl = Potree.Utils.renderTargetToDataUrl(target, width, height, this.renderer, compressRatio);
  57350. /* let pixelCount = width * height;
  57351. let buffer = new Uint8Array(4 * pixelCount);
  57352. this.renderer.readRenderTargetPixels(target, 0, 0, width, height, buffer);
  57353. let dataUrl = Potree.Utils.pixelsArrayToDataUrl(buffer, width, height, compressRatio) */
  57354. target.dispose();
  57355. //resize back
  57356. //this.updateScreenSize({forceUpdateSize:true})
  57357. return {
  57358. width,
  57359. height,
  57360. dataUrl
  57361. };
  57362. }
  57363. }
  57364. 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";
  57365. const prefixFragment ="precision highp float;\nprecision highp int;\n\nuniform mat4 viewMatrix;\nuniform vec3 cameraPosition;\n";
  57366. let shader = {
  57367. uniforms: {
  57368. opacity: {
  57369. type: "f",
  57370. value: 1
  57371. },
  57372. progress: {
  57373. type: "f",
  57374. value: 0
  57375. },
  57376. pano0Map: {
  57377. type: "t",
  57378. value: null
  57379. },
  57380. pano1Map: {
  57381. type: "t",
  57382. value: null
  57383. },
  57384. depthMap0: {
  57385. type: "t",
  57386. value: null
  57387. },
  57388. depthMap1: {
  57389. type: "t",
  57390. value: null
  57391. },
  57392. pano0Position: {
  57393. type: "v3",
  57394. value: new Vector3
  57395. },
  57396. pano0Matrix: {
  57397. type: "m4",
  57398. value: new Matrix4
  57399. },
  57400. pano1Position: {
  57401. type: "v3",
  57402. value: new Vector3
  57403. },
  57404. pano1Matrix: {
  57405. type: "m4",
  57406. value: new Matrix4
  57407. },
  57408. /* pano1Matrix2: {
  57409. type: "m4",
  57410. value: new THREE.Matrix4
  57411. },
  57412. */
  57413. inverseProjectionMatrix: {
  57414. value: new Matrix4
  57415. },
  57416. /* projectionMatrix:{//需要再写一遍吗
  57417. value: new THREE.Matrix4
  57418. }, */
  57419. viewport: {
  57420. value: new Vector4
  57421. },
  57422. //如 {x: 0, y: 0, z: 428, w: 969} xy应该是offset, zw是宽高
  57423. cameraHeight0: {
  57424. type: "f",
  57425. value: 1
  57426. },
  57427. cameraHeight1: {
  57428. type: "f",
  57429. value: 1
  57430. },
  57431. },
  57432. vertexShader: prefixVertex + `
  57433. uniform vec3 pano0Position;
  57434. uniform mat4 pano0Matrix;
  57435. uniform vec3 pano1Position;
  57436. uniform mat4 pano1Matrix;
  57437. //uniform mat4 pano1Matrix2;
  57438. varying vec2 vUv;
  57439. varying vec3 vWorldPosition0;
  57440. varying vec3 vWorldPosition1;
  57441. varying vec3 vWorldPosition12;
  57442. vec3 transformAxis( vec3 direction ) //navvis->4dkk
  57443. {
  57444. float y = direction.y;
  57445. direction.y = direction.z;
  57446. direction.z = -y;
  57447. return direction;
  57448. }
  57449. void main() {
  57450. vUv = uv;
  57451. vec4 worldPosition = modelMatrix * vec4(position, 1.0);
  57452. vec3 positionLocalToPanoCenter0 = worldPosition.xyz - pano0Position;
  57453. vWorldPosition0 = (vec4(positionLocalToPanoCenter0, 1.0) * pano0Matrix).xyz;
  57454. vWorldPosition0.x *= -1.0;
  57455. vWorldPosition0 = transformAxis(vWorldPosition0);
  57456. vec3 positionLocalToPanoCenter1 = worldPosition.xyz - pano1Position;
  57457. vWorldPosition1 = (vec4(positionLocalToPanoCenter1, 1.0) * pano1Matrix).xyz;
  57458. vWorldPosition1.x *= -1.0;
  57459. vWorldPosition1 = transformAxis(vWorldPosition1);
  57460. /*
  57461. vec3 positionLocalToPanoCenter12 = worldPosition.xyz - pano1Position;
  57462. vWorldPosition12 = (vec4(positionLocalToPanoCenter12, 1.0) * pano1Matrix2).xyz;
  57463. vWorldPosition12.x *= -1.0;
  57464. vWorldPosition12 = transformAxis(vWorldPosition12);
  57465. */
  57466. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  57467. }
  57468. `,
  57469. fragmentShader: prefixFragment + `
  57470. #define PI 3.141592653
  57471. uniform float modelAlpha;
  57472. uniform float opacity;
  57473. uniform float progress;
  57474. uniform int blackout;
  57475. uniform vec3 pano0Position;
  57476. uniform vec3 pano1Position;
  57477. uniform float maxDistance;
  57478. uniform float minDistance;
  57479. uniform float minOpa;
  57480. uniform float cameraHeight0;
  57481. uniform float cameraHeight1;
  57482. /* uniform sampler2D pano0Map;
  57483. uniform sampler2D pano1Map; */
  57484. uniform samplerCube pano0Map;
  57485. uniform samplerCube pano1Map;
  57486. varying vec2 vUv;
  57487. varying vec3 vWorldPosition0;
  57488. varying vec3 vWorldPosition1;
  57489. //varying vec3 vWorldPosition12;
  57490. /* vec2 getSamplerCoord( vec3 direction )
  57491. {
  57492. direction = normalize(direction);
  57493. float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;
  57494. float ty=acos(direction.z)/PI;
  57495. return vec2(tx,ty);
  57496. } */
  57497. vec2 getSamplerCoord2( vec3 direction )
  57498. {
  57499. direction = normalize(direction);
  57500. float tx=atan(direction.x,direction.z)/(PI*2.0)+0.5;
  57501. float ty=acos(direction.y)/PI;
  57502. return vec2(tx,ty);
  57503. }
  57504. #extension GL_EXT_frag_depth : enable
  57505. #if defined(GL_EXT_frag_depth) && defined(hasDepthTex)
  57506. uniform sampler2D depthMap0;
  57507. uniform sampler2D depthMap1;
  57508. uniform mat4 inverseProjectionMatrix;
  57509. uniform mat4 projectionMatrix;
  57510. uniform vec4 viewport;
  57511. vec2 getDepth(vec3 dir, sampler2D depthMap, float height, vec4 eyePos){
  57512. vec2 depthValue = vec2(0.0, 0.0);
  57513. vec2 uv2 = getSamplerCoord2(/* vWorldPosition12 */dir.xyz); //暂时只用基于目标漫游点的方向
  57514. uv2.x -= 0.25; //全景图和Cube的水平采样起始坐标相差90度,这里矫正 0.25 个采样偏移
  57515. vec4 depth = texture2D(depthMap, uv2);
  57516. //float distance = depth.r + 256. * (depth.g + 256. * depth.b);
  57517. //distance *= 255. * .001; // distance is now in meters
  57518. //更改
  57519. float distance = (depth.g + depth.r / 256.) * 255.; //为什么要乘以255
  57520. if(distance == 0.0){//漫游点底部识别不到的区域,给一个地板高度
  57521. if(uv2.y > 0.75)distance = height / dir.y;
  57522. else distance = 100000.0;//给个超级远的值
  57523. }
  57524. depthValue.x = distance;
  57525. // return r[1] + r[0] / 256
  57526. distance += .1; // add a safety margin
  57527. vec4 eyePos2 = vec4(normalize(eyePos.xyz) * distance, 1.);
  57528. vec4 clipPos2 = projectionMatrix * eyePos2;
  57529. vec4 ndcPos2 = clipPos2 * 1. / clipPos2.w;
  57530. depthValue.y = 0.5 * ((gl_DepthRange.far - gl_DepthRange.near) * ndcPos2.z
  57531. + gl_DepthRange.near + gl_DepthRange.far);
  57532. return depthValue;
  57533. }
  57534. //注:未加载好的话,depth为0,导致第一次漫游过去的时候许多mesh会立刻被遮挡,所以要确保加载完
  57535. #endif
  57536. void main()
  57537. {
  57538. /* vec2 samplerCoord0 = getSamplerCoord(vWorldPosition0.xyz);
  57539. vec2 samplerCoord1 = getSamplerCoord(vWorldPosition1.xyz);
  57540. vec4 colorFromPano0=texture2D(pano0Map,samplerCoord0);
  57541. vec4 colorFromPano1=texture2D(pano1Map,samplerCoord1); */
  57542. vec4 colorFromPano0 = vec4(0.0,0.0,0.0,0.0);
  57543. if(progress < 1.0){//通常是1
  57544. colorFromPano0=textureCube(pano0Map,vWorldPosition0.xyz);
  57545. }
  57546. vec4 colorFromPano1=textureCube(pano1Map,vWorldPosition1.xyz);
  57547. gl_FragColor=mix(colorFromPano0,colorFromPano1,progress);
  57548. //深度图修改深度
  57549. #if defined(GL_EXT_frag_depth) && defined(hasDepthTex)
  57550. vec4 ndcPos;
  57551. ndcPos.xy = ((2.0 * gl_FragCoord.xy) - (2.0 * viewport.xy)) / (viewport.zw) - 1.;
  57552. ndcPos.z = (2.0 * gl_FragCoord.z - gl_DepthRange.near - gl_DepthRange.far) /
  57553. (gl_DepthRange.far - gl_DepthRange.near);
  57554. ndcPos.w = 1.0;
  57555. vec4 clipPos = ndcPos / gl_FragCoord.w;
  57556. vec4 eyePos = inverseProjectionMatrix * clipPos;
  57557. vec2 depth0 = vec2(0.0,0.0);
  57558. if(progress < 1.0){
  57559. depth0 = getDepth(vWorldPosition0, depthMap0, cameraHeight0, eyePos);
  57560. }
  57561. vec2 depth1 = getDepth(vWorldPosition1, depthMap1, cameraHeight1, eyePos);
  57562. /* if(progress < 1.0 && depth1.x == 0.0 && depth0.x > 0.0){
  57563. gl_FragDepthEXT = depth0.y;
  57564. }else{ */
  57565. gl_FragDepthEXT = mix(depth0.y,depth1.y,progress);
  57566. //}
  57567. #endif
  57568. }
  57569. `
  57570. };
  57571. class ModelTextureMaterial extends RawShaderMaterial {
  57572. constructor( ){
  57573. let defines = {};
  57574. super({
  57575. fragmentShader: shader.fragmentShader,
  57576. vertexShader: shader.vertexShader,
  57577. uniforms: UniformsUtils.clone(shader.uniforms),
  57578. side:DoubleSide,
  57579. name: "ModelTextureMaterial",
  57580. defines
  57581. });
  57582. let setSize = (e)=>{
  57583. let viewport = e.viewport;
  57584. let viewportOffset = viewport.offset || new Vector2();
  57585. let resolution = viewport.resolution2;
  57586. this.uniforms.viewport.value.set(viewportOffset.x, viewportOffset.y, resolution.x, resolution.y);
  57587. };
  57588. let viewport = viewer.mainViewport;
  57589. setSize({viewport});
  57590. viewer.addEventListener('resize',(e)=>{
  57591. setSize(e);
  57592. });
  57593. //var supportExtDepth = !!Features.EXT_DEPTH.isSupported()
  57594. {
  57595. //add
  57596. viewer.addEventListener('camera_changed', (e)=>{
  57597. //this.uniforms.projectionMatrix.value.copy(e.camera.projectionMatrix)
  57598. this.uniforms.inverseProjectionMatrix.value.copy(e.camera.projectionMatrixInverse);
  57599. });
  57600. }
  57601. //-------------------------------------
  57602. }
  57603. /**
  57604. *
  57605. * @param {Panorama} pano0
  57606. * @param {Panorama} pano1
  57607. * @param {boolean} flag
  57608. 更新全景图的材质uniforms
  57609. */
  57610. setProjectedPanos(pano0, pano1, progressValue ){
  57611. progressValue!=void 0 && (this.uniforms.progress.value = progressValue);
  57612. //pano0.ensureSkyboxReadyForRender();
  57613. if(pano0){
  57614. this.uniforms.pano0Map.value = pano0.getSkyboxTexture();//pano0.texture
  57615. this.uniforms.pano0Position.value.copy(pano0.position);
  57616. this.uniforms.pano0Matrix.value.copy(pano0.panoMatrix/* pano0.mesh.matrixWorld */ );
  57617. this.uniforms.cameraHeight0.value = pano0.floorPosition.distanceTo(pano0.position);
  57618. //pano1.ensureSkyboxReadyForRender();
  57619. }
  57620. this.uniforms.pano1Map.value = pano1.getSkyboxTexture();//pano1.texture;
  57621. this.uniforms.pano1Position.value.copy(pano1.position);
  57622. this.uniforms.pano1Matrix.value.copy(pano1.panoMatrix /* pano1.mesh.matrixWorld */ );
  57623. this.uniforms.cameraHeight1.value = pano1.floorPosition.distanceTo(pano1.position);
  57624. this.pano0 = pano0;
  57625. this.pano1 = pano1;
  57626. this.updateDepthTex(pano0);
  57627. this.updateDepthTex(pano1);
  57628. //console.log('setProjectedPanos', pano0&&pano0.id, pano1&&pano1.id)
  57629. this.needsUpdate = true;
  57630. }
  57631. updateDepthTex(pano){
  57632. if( !Potree.settings.useDepthTex || !pano || !pano.depthTex || pano!=this.pano0 && pano!=this.pano1)return
  57633. //console.log('updateDepthTex', pano.id, this.pano0 && this.pano0.id, this.pano1 && this.pano1.id)
  57634. this.uniforms.depthMap0.value = this.pano0 && this.pano0.depthTex;
  57635. this.uniforms.depthMap1.value = this.pano1 && this.pano1.depthTex;
  57636. this.updateDepthTexEnable();
  57637. }
  57638. updateDepthTexEnable(){
  57639. let hasDepthTex = this.pano0 && this.pano1 && this.pano0.pointcloud.hasDepthTex && this.pano1.pointcloud.hasDepthTex; //暂时不知道一个有图一个没图怎么写所以
  57640. Common.addOrRemoveDefine(this, 'hasDepthTex', hasDepthTex?'add':'remove' );
  57641. }
  57642. /* EnableDepthTex(){//开启DepthTex
  57643. if(this.defines['hasDepthTex']){
  57644. return
  57645. }
  57646. this.defines['hasDepthTex'] = ''
  57647. this.needsUpdate = true;
  57648. } */
  57649. }
  57650. var TileUtils = {};
  57651. TileUtils.TILE_SIZE = 512,
  57652. TileUtils.FACES_PER_PANO = 6,
  57653. TileUtils.LocationOnTile = {
  57654. Center: 0,
  57655. UpperLeft: 1,
  57656. UpperRight: 2,
  57657. LowerRight: 3,
  57658. LowerLeft: 4
  57659. },
  57660. /*
  57661. * 获取某tile在cube中的方向 direction (向量起点在cube中心,终点在tile图的指定位置)。spherical通过先求uv,再直接得到dir
  57662. * @param {*} size 面分辨率
  57663. * @param {*} cubeFace 所在面
  57664. * @param {*} Center 在tile上的目标位置,默认为中心,其他位置就是四个顶点
  57665. * @param {*} c 似乎是在tile的缩进百分比,根据所在面的不同,分别向不同方向缩进,但都是向tile的中心
  57666. * @param {*} dir 所求方向
  57667. */
  57668. TileUtils.getTileVector = function() {//获取某tile在cube中的方向 direction (向量起点在cube中心,终点在tile图的中心)
  57669. return function(size, tileSize, cubeFace, tileX, tileY, Center, c, dir) {//c似乎是缩进百分比
  57670. Center = Center || TileUtils.LocationOnTile.Center;
  57671. //假设该cube边长为2:
  57672. var u = size / tileSize
  57673. , d = tileX / u;
  57674. tileY = -tileY + (u - 1);
  57675. var p = tileY / u
  57676. , f = tileSize / size
  57677. , g = 2 * f //一个tile的宽度 (乘以2是因为cube边长是2)
  57678. , m = g / 2
  57679. , v = 2 * d - 1 + m
  57680. , A = 2 * p - 1 + m;
  57681. switch (Center) {//计算在tile中指定位置带来的偏移
  57682. case TileUtils.LocationOnTile.UpperLeft: //1
  57683. v -= m,
  57684. A += m,
  57685. v += c * g; //似乎是向内缩进
  57686. break;
  57687. case TileUtils.LocationOnTile.UpperRight:
  57688. v += m,
  57689. A += m,
  57690. A -= c * g;
  57691. break;
  57692. case TileUtils.LocationOnTile.LowerRight:
  57693. v += m,
  57694. A -= m,
  57695. v -= c * g;
  57696. break;
  57697. case TileUtils.LocationOnTile.LowerLeft:
  57698. v -= m,
  57699. A -= m,
  57700. A += c * g;
  57701. break;
  57702. case TileUtils.LocationOnTile.Center: //0
  57703. }
  57704. switch (cubeFace) {
  57705. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  57706. MathLight.setVector(dir, -1, A, -v);
  57707. break;
  57708. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  57709. MathLight.setVector(dir, 1, A, v);
  57710. break;
  57711. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Y: //顶面
  57712. MathLight.setVector(dir, -v, 1, -A);
  57713. break;
  57714. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  57715. MathLight.setVector(dir, -v, -1, A);
  57716. break;
  57717. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  57718. MathLight.setVector(dir, -v, A, 1);
  57719. break;
  57720. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  57721. MathLight.setVector(dir, v, A, -1);
  57722. }
  57723. MathLight.normalize(dir);
  57724. }
  57725. }(),
  57726. /*
  57727. * 获取该tile在第几个面(简易装载法)
  57728. */
  57729. TileUtils.getFaceForTile = function(size, index) {//获取该tile在第几个面
  57730. var tileSize = TileUtils.TILE_SIZE;
  57731. size < TileUtils.TILE_SIZE && (tileSize = size);
  57732. var n = Math.floor(size / tileSize)
  57733. , sum = n * n; //得每个面tile总数
  57734. return Math.floor(index / sum)
  57735. }
  57736. ,
  57737. TileUtils.getTileLocation = function(size, t, result) {
  57738. var tileSize = TileUtils.TILE_SIZE;
  57739. size < TileUtils.TILE_SIZE && (tileSize = size);
  57740. var r = TileUtils.getFaceForTile(size, t)
  57741. , a = Math.floor(size / tileSize)
  57742. , s = a * a
  57743. , l = t - r * s;
  57744. result.tileX = l % a;
  57745. result.tileY = Math.floor(l / a);
  57746. result.face = r;
  57747. result.faceTileIndex = l;
  57748. return result
  57749. }
  57750. ,
  57751. /*
  57752. * 求size分辨率需要多少张tile
  57753. */
  57754. TileUtils.getTileCountForSize = function(e) {
  57755. if (e <= TileUtils.TILE_SIZE)
  57756. return TileUtils.FACES_PER_PANO;
  57757. var t = Math.floor(e / TileUtils.TILE_SIZE)
  57758. , i = t * t
  57759. , n = i * TileUtils.FACES_PER_PANO;
  57760. return n
  57761. }
  57762. ,
  57763. TileUtils.getRelativeDirection = function() {
  57764. var e = new MathLight.Matrix4
  57765. , t = new MathLight.Quaternion;
  57766. return function(i, n) {//i是pano.quaternion, n是camera的direction
  57767. t.copy(i),
  57768. t.inverse(),
  57769. e.makeRotationFromQuaternion(t),
  57770. e.applyToVector3(n),
  57771. MathLight.normalize(n);
  57772. }
  57773. }(),
  57774. /*
  57775. * 根据方向寻找合适的tile加载
  57776. */
  57777. TileUtils.matchingTilesInDirection = function() {
  57778. var e = new MathLight.Vector3
  57779. , t = new MathLight.Vector3(0,0,-1)
  57780. , i = new MathLight.Quaternion
  57781. , n = function(e, t) {
  57782. e.push({
  57783. face: t.face,
  57784. faceTileIndex: t.faceTileIndex,
  57785. tileX: t.tileX,
  57786. tileY: t.tileY
  57787. });
  57788. }
  57789. , a = function() {
  57790. var e = {
  57791. face: -1,
  57792. faceTileIndex: -1,
  57793. tileX: -1,
  57794. tileY: -1
  57795. };
  57796. return function(size, i, r) {
  57797. for (var a = TileUtils.getTileCountForSize(size), s = 0, l = 0; l < a; l++)
  57798. TileUtils.getTileLocation(size, l, e),
  57799. i && !i(e) || (s++,
  57800. r && n(r, e));
  57801. return s
  57802. }
  57803. }();
  57804. return function(pano, size, dir, hFov, vFov, result) {
  57805. var d = size < TileUtils.TILE_SIZE ? size : TileUtils.TILE_SIZE;
  57806. //TileUtils.getTileCountForSize(size);
  57807. if (!hFov && !vFov)
  57808. return a(size, null, result);
  57809. var p = !!vFov;
  57810. vFov = vFov || hFov,
  57811. vFov = Math.max(0, Math.min(vFov, 360)),
  57812. hFov = Math.max(0, Math.min(hFov, 360)),
  57813. MathLight.copyVector(dir, e),
  57814. TileUtils.getRelativeDirection(pano.quaternion4dkk, e);
  57815. if(p){//如果有vFov hFov
  57816. i.setFromUnitVectors(e, t);
  57817. var f = function(e) {
  57818. return TileUtils.isTileWithinFrustum(size, d, e.face, e.tileX, e.tileY, i, hFov, vFov)//在视野中的
  57819. };
  57820. return a(size, f, result)
  57821. }
  57822. var g = function(t) {//如果仅有hFov
  57823. return TileUtils.isTileWithinFOV(size, d, t.face, t.tileX, t.tileY, e, hFov)
  57824. };
  57825. return a(size, g, result)
  57826. }
  57827. }(),
  57828. /*
  57829. * 是否在屏幕范围内
  57830. */
  57831. TileUtils.isTileWithinFrustum = function() {
  57832. var e = new MathLight.Vector3
  57833. , t = 1e-5;
  57834. return function(i, n, a, s, l, c, h, u) {
  57835. 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++){
  57836. TileUtils.getTileVector(i, n, m, s, l, b, 0, e),//get e // size, tileSize, cubeFace, tileX, tileY, Center, c, dir
  57837. MathLight.applyQuaternionToVector(c, e);
  57838. if (e.z >= -t)//似乎是在相机背面
  57839. I++;
  57840. else {
  57841. var w = -1 / e.z
  57842. , _ = e.x * w
  57843. , T = e.y * w;
  57844. T > d ? v++ : T < p && A++, //这四种似乎代表在这个画框之外,如在左、在上、在下、在右
  57845. _ > f ? y++ : _ < g && C++,
  57846. E++;
  57847. }
  57848. }
  57849. return A !== E && v !== E && y !== E && C !== E //如果有一项和E相等代表要么是在相机背面要么是tile的四个顶点都画在画布的同一边,所以肯定不在画布上
  57850. }
  57851. }(),
  57852. /*
  57853. * 是否在FOV范围内
  57854. */
  57855. TileUtils.isTileWithinFOV = function() {
  57856. var e = new MathLight.Vector3
  57857. , t = new MathLight.Vector3(0,1,0)
  57858. , i = new MathLight.Vector3(1,0,0);
  57859. return function(panoSize, tileSize, face, tileX, tileY, direction, fov) {//direction是作用了pano.quaternion的camera.direction
  57860. var d = TileUtils.mapFaceToCubemapFace(face);
  57861. MathLight.cross(direction, t, i); //get i 好像没用到
  57862. TileUtils.getTileVector(panoSize, tileSize, d, tileX, tileY, TileUtils.LocationOnTile.Center, 0, e);
  57863. if (TileUtils.isWithinFOV(e, direction, fov, null))//先判断tile中心在不在FOV内
  57864. return !0;
  57865. for (var p = fov / 360, f = Math.floor(1 / p), g = 0, m = 0; m < f; m++) {
  57866. for (var v = TileUtils.LocationOnTile.UpperLeft; v <= TileUtils.LocationOnTile.LowerLeft; v++)
  57867. if (TileUtils.getTileVector(panoSize, tileSize, d, tileX, tileY, v, g, e),
  57868. TileUtils.isWithinFOV(e, direction, fov, null))
  57869. return !0;
  57870. g += p; //可能是考虑到有可能tile比fov覆盖了fov(虽然一般不可能,除非fov特别小),所以将tile分成若干段,取tile中的点再检测下
  57871. }
  57872. return !1
  57873. }
  57874. }(),
  57875. TileUtils.isWithinFOV = function() {
  57876. var e = new MathLight.Vector3
  57877. , t = new MathLight.Vector3;
  57878. return function(dir, cameraDir, fov, a) {
  57879. if (MathLight.copyVector(dir, t),
  57880. a) {
  57881. MathLight.copyVector(a, e),
  57882. MathLight.normalize(e);
  57883. var s = MathLight.dot(e, dir);
  57884. e.x *= s,
  57885. e.y *= s,
  57886. e.z *= s,
  57887. MathLight.subVector(t, e);
  57888. }
  57889. var l = fov / 2 * MathLight.RADIANS_PER_DEGREE
  57890. , c = Math.cos(l)
  57891. , h = MathLight.dot(t, cameraDir);
  57892. return h >= c
  57893. }
  57894. }(),
  57895. TileUtils.mapFaceToCubemapFace = function() {
  57896. var e = {
  57897. 0: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
  57898. 1: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
  57899. 2: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_X,
  57900. 3: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
  57901. 4: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
  57902. 5: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
  57903. };
  57904. return function(t) {
  57905. return e[t]
  57906. }
  57907. }();
  57908. var texLoader$2 = new TextureLoader();
  57909. const labelProp = {
  57910. sizeInfo: {minSize : 200 , maxSize : 250, nearBound : 0.8, farBound : 10},
  57911. backgroundColor:{r: 255, g: 255, b: 255, a: 0.4 },
  57912. textColor:{r: 0, g: 0, b: 0, a: 1 },
  57913. borderRadius: 15,
  57914. renderOrder:10
  57915. };
  57916. let standardMarkerMat;
  57917. let markerTex;
  57918. let getMarerMat = function(){
  57919. if(!markerTex) {
  57920. markerTex = {
  57921. default:texLoader$2.load( Potree.resourcePath+'/textures/marker.png' ),
  57922. ring:texLoader$2.load( Potree.resourcePath+'/textures/marker2.png' )
  57923. };
  57924. markerTex.default.anisotropy = 4; // 各向异性过滤 .防止倾斜模糊
  57925. markerTex.ring.anisotropy = 4;
  57926. //有可能被点云遮住吗。
  57927. }
  57928. return new DepthBasicMaterial({opacity:0.7, side: DoubleSide , map:markerTex.default ,transparent:true,
  57929. clipDistance: 2, occlusionDistance:1, //不能设置太短,因为过渡时深度不准确
  57930. //depthTest: !!Potree.settings.useDepthTex,
  57931. useDepth: !!Potree.settings.useDepthTex
  57932. //改为DepthBasicMaterial是因为原Basic的材质过渡时会先隐藏后出现
  57933. })
  57934. };
  57935. //显示全景图时marker没有被遮挡,如果需要,要换成depthBasicMaterial 或者直接把skybox的深度修改(拿到深度贴图后更如此)
  57936. let planeGeo$1 = new PlaneBufferGeometry(0.2,0.2);
  57937. let sg = new SphereGeometry(0.1, 8, 8);
  57938. let smHovered = new MeshBasicMaterial({/* side: THREE.BackSide, */color: 0xff0000});
  57939. let sm = new MeshBasicMaterial({/* side: THREE.BackSide */});
  57940. var rot90 = new Quaternion().setFromAxisAngle(new Vector3(0,0,1), Math.PI/2 ); //使用的是刚好适合全景图的,给cube贴图需要转90°
  57941. //var rot90 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1,0,0), -Math.PI/2 ); //4dkk->navvis
  57942. //var rot901 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,1,0), -Math.PI/2 ); //整张球幕图要旋转下
  57943. //rot90 = new THREE.Quaternion().multiplyQuaternions( rot901, rot90)
  57944. var old = null;
  57945. /*
  57946. 转成四维看看的axis:
  57947. var a = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,0,1), THREE.Math.degToRad(-90)) 因为四维的要绕y转90
  57948. 这里的quaternion.multiply(a);
  57949. 先乘再换顺序 w : q.w, x:q.x , y:-q.z, z:q.y
  57950. */
  57951. //暂时直接用4dkkconsole输出的数据
  57952. class Panorama extends EventDispatcher{
  57953. constructor(o, images360){//file, time, longitude, latitude, altitude, course, pitch, roll
  57954. super();
  57955. this.id = o.id; //唯一标识
  57956. this.images360 = images360;
  57957. this.visible = true; //for viewer updateVisible
  57958. this.enabled = true;//是否可以走
  57959. this.addEventListener('isVisible',(e)=>{//是否显示该点的mesh(不显示也能走)
  57960. //console.log('pano isVisible', this.id, e.visible)
  57961. viewer.updateVisible(this.marker, 'panoVisi', e.visible);
  57962. Potree.settings.showPanoMesh && (this.mesh.visible = e.visible);
  57963. if(e.reason == 'screenshot' || e.visible){
  57964. this.label && (this.label.visible = e.visible);//截图时隐藏下
  57965. }
  57966. viewer.updateVisible(this.label2, 'panoVisi', e.visible);
  57967. });
  57968. /*
  57969. 漫游点可见性:旧
  57970. level reason 类型
  57971. 2(最高)buildingChange(不在此楼层) unvisible
  57972. 1 modeIsShowPanos(漫游模式) visible //不记得为什么加这个了,所以重写
  57973. 0 pointcloudVisi(隐藏了数据集) unvisible
  57974. */
  57975. /*
  57976. 漫游点可见性:新
  57977. level reason 类型
  57978. 2(最高)buildingChange(不在此楼层) unvisible
  57979. 1 ifShowMarker(marker显示开关) unvisible
  57980. 0 pointcloudVisi(隐藏了数据集) unvisible
  57981. */
  57982. if(Potree.settings.editType == 'pano'){//漫游点拼合编辑
  57983. this.uuid = o.uuid; //因为有多个数据集 所以会重复
  57984. this.index = o.index; //下标, 用于visibles
  57985. this.pointcloud = viewer.scene.pointclouds.find(e=>e.panoUuid == o.uuid);
  57986. this.pointcloud.panos.push(this);
  57987. this.sid = this.pointcloud.dataset_id + '|' + this.uuid; //不会更改的标记 用于entity.panos里的标记
  57988. this.panosData = o;
  57989. //数据中原本的位置朝向
  57990. this.dataPosition = new Vector3().copy(o.pose.translation);
  57991. this.dataQuaternion = new Quaternion().copy(o.pose.rotation);
  57992. this.dataRotation = new Euler().setFromQuaternion(this.dataQuaternion);
  57993. //因为位置朝向随着点云位置改变,所以直接运用到点云上,这里清零
  57994. this.originPosition = new Vector3(); //{x: 0, y: 0, z: 0}
  57995. this.quaternion = new Quaternion(); //{w: 0, x: 0, y: 0, z: 1}
  57996. //this.quaternion4dkk = math.convertVisionQuaternion(this.quaternion)//4dkk内使用的quaternion
  57997. this.visibles = o.visibles;
  57998. const height = 1.4; //相机高度
  57999. this.originFloorPosition = this.originPosition.clone();
  58000. this.originFloorPosition.z -= height;
  58001. /* this.originPosition = new THREE.Vector3().copy(o.pose.translation) //{x: 0, y: 0, z: 0}
  58002. this.quaternion = new THREE.Quaternion().copy(o.pose.rotation) //{w: 0, x: 0, y: 0, z: 1}
  58003. //this.quaternion4dkk = math.convertVisionQuaternion(this.quaternion)//4dkk内使用的quaternion
  58004. this.visibles = o.visibles
  58005. this.pointcloud = viewer.scene.pointclouds.find(e=>e.dataset_id == o.uuid)
  58006. this.pointcloud.panos.push(this)
  58007. const height = 1.5; //相机高度
  58008. this.originFloorPosition = this.originPosition.clone()
  58009. this.originFloorPosition.z -= height
  58010. */
  58011. }else {
  58012. this.originPosition = new Vector3().fromArray(o.dataset_location);
  58013. this.originFloorPosition = new Vector3().fromArray(o.dataset_floor_location);
  58014. this.originID = parseInt(o.file_id);//"file_id":"00022"对应是原本的4dkk的id --来自vision.txt
  58015. this.pointcloud = viewer.scene.pointclouds.find(e=>e.dataset_id == o.dataset_id) || viewer.scene.pointclouds[0];
  58016. this.pointcloud.panos.push(this);
  58017. //this.sid = this.pointcloud.sceneCode + '|' + this.originID //不会更改的标记
  58018. this.sid = this.pointcloud.dataset_id + '|' + this.originID; //不会更改的标记
  58019. //全景图和Cube的水平采样起始坐标相差90度
  58020. /* if(from4dkk){
  58021. var qua = o.dataset_orientation
  58022. var quaternion = new THREE.Quaternion().fromArray(qua)
  58023. quaternion = new THREE.Quaternion().multiplyQuaternions(quaternion, rot901);//整张球幕图要旋转下 因为在4dkk里转过,还原。如果是tiles的不用
  58024. this.quaternion = new THREE.Quaternion(quaternion.x, -quaternion.z, quaternion.y, quaternion.w) //转化坐标
  58025. }else{ */
  58026. var qua = o.dataset_orientation;
  58027. qua = [qua[1], qua[2], qua[3], qua[0]];
  58028. this.quaternion = new Quaternion().fromArray(qua);
  58029. this.quaternion4dkk = math.convertVisionQuaternion(this.quaternion);//4dkk内使用的quaternion
  58030. this.quaternion2 = this.quaternion.clone();
  58031. this.quaternion = new Quaternion().multiplyQuaternions(this.quaternion, rot90);//全景图和Cube的水平采样起始坐标相差90度,cubeTex转90度
  58032. this.rotation4dkk = new Euler().setFromQuaternion(this.quaternion4dkk);
  58033. //}
  58034. //this.quaternion1 = Potree.Utils.QuaternionFactory.fromArray(o.dataset_orientation)
  58035. //同quaternion
  58036. //let xy = this.transform.forward([this.longitude, this.latitude]);
  58037. this.file = `https://4dkk.4dage.com/images/images${Potree.settings.number}/pan/high/${this.id}.jpg`;
  58038. }
  58039. this.rotation = new Euler().setFromQuaternion(this.quaternion);
  58040. this.build();
  58041. this.transformByPointcloud(); //初始化位移
  58042. {//tile
  58043. this.minimumTiledPanoLoaded = !1;
  58044. this.highestPartialTileRenderOpCompleted = 0;
  58045. this.highestFullTileRenderOpCompleted = 0;
  58046. this.shouldRedrawOnBaseLoaded = !1;
  58047. this.resolutionPromise = {};
  58048. this.tiledPanoRenderTarget = null;
  58049. this.zoomed = !1;
  58050. images360.panoRenderer.addEventListener(PanoRendererEvents.TileRenderSuccess, this.onTileRendered.bind(this));
  58051. images360.panoRenderer.addEventListener(PanoRendererEvents.PanoRenderComplete, this.onPanoRendered.bind(this));
  58052. images360.panoRenderer.addEventListener(PanoRendererEvents.TileRenderFailure, this.onTileRenderFail.bind(this));
  58053. images360.panoRenderer.addEventListener(PanoRendererEvents.UploadAttemptedForAllTiles, this.onUploadAttemptedForAllTiles.bind(this));
  58054. }
  58055. this.addEventListener('hoverOn', (e)=>{//from Map
  58056. if(!e.byMainView){
  58057. this.hoverOn(e);
  58058. }
  58059. });
  58060. this.addEventListener('hoverOff', (e)=>{
  58061. if(!e.byMainView){
  58062. this.hoverOff(e);
  58063. }
  58064. });
  58065. }
  58066. setEnable(enable){//是否可以走
  58067. viewer.updateVisible(this, 'isEnabled', enable); //令所有marker不可见
  58068. this.enabled = enable;
  58069. //如果当前在全景模式且在这个点,需要切换显示吗? 目前用不到
  58070. }
  58071. loadDepthImg(){
  58072. if(!this.pointcloud.hasDepthTex || this.depthTex || this.depthTexLoading)return
  58073. this.depthTexLoading = true;
  58074. let src = Potree.settings.number == 'SS-t-7DUfWAUZ3V' ? `${Potree.scriptPath}/data/${Potree.settings.number}/depthMap/${this.originID}.png`
  58075. : `https://laser-oss.4dkankan.com/${Potree.settings.webSite}/${this.pointcloud.sceneCode}/data/${this.pointcloud.sceneCode}/depthmap/${this.originID}.png`;
  58076. let texture = texLoader$2.load( src, ()=>{
  58077. this.depthTex = texture;
  58078. this.images360.dispatchEvent({type:'loadedDepthImg', pano:this, loaded:true});
  58079. this.depthTexLoading = false;
  58080. },(e)=>{//error
  58081. console.error('loadDepthImg失败, 数据集sceneCode'+ this.pointcloud.sceneCode, this.id );
  58082. this.pointcloud.hasDepthTex = false;
  58083. this.images360.dispatchEvent({type:'loadedDepthImg', pano:this, });
  58084. });
  58085. texture.wrapS = RepeatWrapping;
  58086. texture.flipY = false;
  58087. texture.magFilter = LinearFilter;
  58088. texture.minFilter = LinearFilter;
  58089. }
  58090. build(){
  58091. /* let mesh = new THREE.Mesh(sg, sm);
  58092. mesh.scale.set(1, 1, 1);
  58093. mesh.material.transparent = true;
  58094. mesh.material.opacity = 0.75;
  58095. mesh.pano = this;
  58096. mesh.name = 'panoSphere'
  58097. mesh.addEventListener('mouseover',(e)=>{
  58098. mesh.material = smHovered
  58099. })
  58100. mesh.addEventListener('mouseleave',(e)=>{
  58101. mesh.material = sm
  58102. })
  58103. mesh.addEventListener('click',(e)=>{
  58104. this.images360.focusPano(this)
  58105. })
  58106. this.mesh = mesh;
  58107. if(!Potree.settings.showPanoMesh) mesh.visible = false
  58108. this.images360.node.add(mesh)
  58109. */
  58110. { // orientation
  58111. //var {course, pitch, roll} = this;
  58112. //mesh.quaternion.copy(this.quaternion)
  58113. //add
  58114. //var quaternion = new THREE.Quaternion().multiplyQuaternions(this.quaternion, rot901);//改 为球目全
  58115. //quaternion.premultiply(rot90)
  58116. this.panoMatrix = new Matrix4().makeRotationFromQuaternion(this.quaternion);
  58117. this.oriPanoMatrix = this.panoMatrix.clone();
  58118. if(this.quaternion2)this.oriPanoMatrix2 = new Matrix4().makeRotationFromQuaternion(this.quaternion2);
  58119. //console.log(this.quaternion)
  58120. //this.quaternion = quaternion
  58121. }
  58122. let marker = new Mesh(planeGeo$1, getMarerMat() );
  58123. marker.up.set(0,0,1);
  58124. marker.lookAt(marker.up);
  58125. marker.scale.set(2,2,2);
  58126. this.addEventListener('changeMarkerTex',(e)=>{
  58127. marker.material.map = markerTex[e.name];
  58128. });
  58129. this.marker = marker;
  58130. if(Potree.settings.editType == 'pano'){
  58131. viewer.updateVisible(marker, 'panoEdit', false, 4);
  58132. }
  58133. this.images360.node.add(marker);
  58134. Potree.settings.isTest && this.createTextLabel();
  58135. this.createTextLabel2();
  58136. /* let mouseover = (e)=>{
  58137. if(!e.byMap){
  58138. pano.mapMarker.material = panoMarkerMats.selected
  58139. if(!e.byMainView) pano.dispatchEvent({type: "hoverOn", byMap:true})
  58140. this.needRender = true
  58141. }
  58142. }
  58143. let mouseleave = (e)=>{
  58144. if(!e.byMap){
  58145. pano.mapMarker.material = panoMarkerMats.default
  58146. if(!e.byMainView) pano.dispatchEvent({type: "hoverOff", byMap:true})
  58147. this.needRender = true
  58148. }
  58149. } */
  58150. marker.addEventListener('mouseover', this.hoverOn.bind(this));
  58151. marker.addEventListener('mouseleave', this.hoverOff.bind(this));
  58152. }
  58153. transformByPointcloud(){
  58154. let position = this.originPosition.clone().applyMatrix4(this.pointcloud.transformMatrix);//也可以用datasetPosTransform算
  58155. let floorPosition = this.originFloorPosition.clone().applyMatrix4(this.pointcloud.transformMatrix);
  58156. this.setPosition(position, floorPosition);
  58157. this.panoMatrix = new Matrix4().multiplyMatrices(this.pointcloud.rotateMatrix, this.oriPanoMatrix );
  58158. //this.panoMatrix2 = Potree.Utils.datasetRotTransform({fromDataset:true, pointcloud:this.pointcloud, matrix:this.oriPanoMatrix, getMatrix:true}) //和上一行结果一样
  58159. //quaternion也变下
  58160. if(this.oriPanoMatrix2){
  58161. this.panoMatrix2 = new Matrix4().multiplyMatrices(this.pointcloud.rotateMatrix, this.oriPanoMatrix2 );//供DepthImageSampler使用
  58162. this.panoMatrix2Inverse = this.panoMatrix2.clone().invert();
  58163. }
  58164. this.dispatchEvent('rePos');
  58165. }
  58166. setPosition(position, floorPosition){
  58167. this.position = position;
  58168. this.floorPosition = floorPosition;
  58169. //this.mesh.position.copy(this.position)
  58170. this.marker.position.copy(this.floorPosition);
  58171. this.marker.position.z+=0.04;//会被点云遮住
  58172. if(this.label){
  58173. if(Potree.settings.editType == 'pano'){
  58174. this.label.position.copy(this.position);
  58175. }else {
  58176. this.label.position.copy(this.floorPosition);
  58177. }
  58178. this.label.position.z+=0.14;
  58179. this.label.update();
  58180. }
  58181. if(this.label2){
  58182. if(Potree.settings.editType == 'pano'){
  58183. this.label2.position.copy(this.position);
  58184. }else {
  58185. this.label2.position.copy(this.floorPosition);
  58186. }
  58187. this.label2.position.copy(this.marker.position);
  58188. this.label2.update();
  58189. }
  58190. }
  58191. hoverOn(e={}) {
  58192. //console.log("hoverOn " + this.id )
  58193. transitions.start(lerp.property(this.marker.material, "opacity", 1), 250);
  58194. if(!e.byMap) this.dispatchEvent({type:'hoverOn', byMainView:true});
  58195. if(!e.byImages360) this.images360.dispatchEvent({type:'markerHover', hovered:true, pano:this});
  58196. }
  58197. hoverOff(e={}){
  58198. //console.log("hoverOff " + this.id )
  58199. transitions.start(lerp.property(this.marker.material, "opacity", 0.5), 250);
  58200. if(!e.byMap) this.dispatchEvent({type:'hoverOff', byMainView:true});
  58201. if(!e.byImages360) this.images360.dispatchEvent({type:'markerHover', hovered:false, pano:this});
  58202. }
  58203. setZoomed(zoomed){
  58204. this.zoomed = zoomed;
  58205. Potree.settings.displayMode == 'showPanos' && this.updateSkyboxForZoomLevel(); //放大后换成zoomTarget贴图
  58206. viewer.dispatchEvent({type:'panoSetZoom', zoomed});
  58207. }
  58208. enter(){
  58209. this.setZoomed(!1),
  58210. viewer.dispatchEvent({type:PanoramaEvents.Enter, oldPano:old, newPano:this } );
  58211. old = this;
  58212. //console.log("enter pano "+ this.id)
  58213. }
  58214. exit(){
  58215. /* if(this.tiled)
  58216. { */
  58217. this.clearWaitDeferreds();
  58218. this.minimumTiledPanoLoaded = !1;
  58219. this.tiledPanoRenderTarget = null;
  58220. this.setZoomed(!1);
  58221. this.images360.panoRenderer.deactivateTiledPano(this);
  58222. this.highestPartialTileRenderOpCompleted = 0;
  58223. this.highestFullTileRenderOpCompleted = 0;
  58224. /*}
  58225. else
  58226. {
  58227. this.solidSkybox.dispose();
  58228. this.solidSkybox.loaded = !1;
  58229. this.solidSkybox.version = 0;
  58230. } */
  58231. //console.log("exit pano "+ this.id)
  58232. viewer.dispatchEvent({type:PanoramaEvents.Exit, pano:this});
  58233. }
  58234. updateSkyboxForZoomLevel(){
  58235. if(this.minimumTiledPanoLoaded){
  58236. this.images360.updateProjectedPanos();
  58237. }
  58238. }
  58239. getSkyboxTexture(){
  58240. if(this.minimumTiledPanoLoaded)
  58241. {
  58242. if(this.zoomed && this.images360.qualityManager.maxRenderTargetSize > this.images360.qualityManager.maxNavPanoSize)//change 如果放大后和不放大都是2k就不用这个
  58243. {
  58244. return this.images360.panoRenderer.zoomRenderTarget.texture;
  58245. }
  58246. else
  58247. {
  58248. this.tiledPanoRenderTarget.texture.mapping = UVMapping;//add
  58249. return this.tiledPanoRenderTarget.texture;
  58250. }
  58251. }
  58252. else
  58253. {
  58254. return null;
  58255. }
  58256. }
  58257. isLoaded(e){
  58258. if (e && "string" == typeof e)
  58259. console.error("Wrong panoSize given to Panorama.isLoaded(); a tiled pano uses PanoSizeClass");
  58260. return !!this.minimumTiledPanoLoaded && (!e || this.highestFullTileRenderOpCompleted >= e)//改:原本是:this.highestPartialTileRenderOpCompleted >= e, 希望这代表全部加载完
  58261. }
  58262. getWaitDeferred(size){//获取不同size的tile贴图的promiss
  58263. var t = this.resolutionPromise[this.id];
  58264. t || (t = {}, this.resolutionPromise[this.id] = t);
  58265. var i = t[size];
  58266. return i || (i = {
  58267. deferred: $.Deferred(),
  58268. active: !1
  58269. },
  58270. t[size] = i),
  58271. i
  58272. }
  58273. clearWaitDeferreds(){
  58274. var e = this.resolutionPromise[this.id];
  58275. e || (e = {},
  58276. this.resolutionPromise[this.id] = e);
  58277. for (var t in e)
  58278. if (e.hasOwnProperty(t)) {
  58279. var i = e[t];
  58280. i.active = !1,
  58281. i.deferred = $.Deferred();
  58282. }
  58283. }
  58284. resetWaitDeferred(e){
  58285. var t = this.getWaitDeferred(e);
  58286. t.active = !1;
  58287. t.deferred = $.Deferred();
  58288. }
  58289. onTileRendered(ev){
  58290. ev.id === this.id && this.dispatchEvent({
  58291. type:PanoramaEvents.TileLoaded,
  58292. size:ev.panoSize, index:ev.tileIndex, count:ev.totalTiles
  58293. });
  58294. }
  58295. onPanoRendered(ev) {
  58296. if(ev.id === this.id)
  58297. {
  58298. this.minimumTiledPanoLoaded = !0;
  58299. this.updateSkyboxForZoomLevel();//更新贴图 setProjected
  58300. ev.panoSize > this.highestPartialTileRenderOpCompleted && (this.highestPartialTileRenderOpCompleted = ev.panoSize);//应该是更新最高获取到的Partial size
  58301. ev.updateFullComplete && ev.panoSize > this.highestFullTileRenderOpCompleted && (this.highestFullTileRenderOpCompleted = ev.panoSize); //应该是更新最高获取到的Full size
  58302. //this.dispatchEvent("load", ev.panoSize);
  58303. viewer.ifAllLoaded( this);
  58304. this.dispatchEvent({type:PanoramaEvents.LoadComplete, size:ev.panoSize, count:ev.totalTiles});
  58305. }
  58306. }
  58307. onTileRenderFail(ev) {
  58308. ev.id === this.id && this.dispatchEvent({type:PanoramaEvents.LoadFailed });
  58309. }
  58310. onUploadAttemptedForAllTiles(ev) {
  58311. if (ev.id === this.id) {
  58312. var n = this.images360.qualityManager.getPanoSize(PanoSizeClass.BASE);
  58313. if(ev.panoSize === n && this.shouldRedrawOnBaseLoaded) //shouldRedrawOnBaseLoaded一直是false。在4dkk里只有初始点在quickstart后变为true。
  58314. {
  58315. this.shouldRedrawOnBaseLoaded = !1;
  58316. this.panoRenderer.resetRenderStatus(this.id, !0, !1);
  58317. this.panoRenderer.renderPanoTiles(this.id, null, !0, !0);
  58318. }
  58319. }
  58320. }
  58321. createTextLabel(){
  58322. this.removeTextLabel();
  58323. this.label = new TextSprite(Object.assign({},
  58324. labelProp, {text: this.id }) //{text: `id:${this.id}, dataset:${this.pointcloud.name}, 4dkkId:${this.originID}`}
  58325. );
  58326. this.images360.node.add(this.label);
  58327. this.floorPosition && this.label.position.copy(this.floorPosition);
  58328. }
  58329. createTextLabel2(){
  58330. let labelProp2 = {
  58331. //sizeInfo: {minSize : 200 , maxSize : 250, nearBound : 0.8, farBound : 10},
  58332. backgroundColor:{r: 255, g: 255, b: 255, a: 0 },
  58333. textColor:{r:255 , g: 255, b: 255, a: 1 },
  58334. textBorderColor:{r:30 , g:30, b: 30, a: 1 },
  58335. textBorderThick:3,
  58336. dontFixOrient:true,
  58337. renderOrder:10,
  58338. fontsize:30,
  58339. };
  58340. this.label2 = new TextSprite(Object.assign({},
  58341. labelProp2, {text: /* this.originID */ parseInt(this.id)+1 }) //{text: `id:${this.id}, dataset:${this.pointcloud.name}, 4dkkId:${this.originID}`}
  58342. );
  58343. this.images360.node.add(this.label2);
  58344. this.floorPosition && this.label2.position.copy(this.floorPosition);
  58345. let s = 0.4;
  58346. this.label2.scale.set(s,s,s);
  58347. viewer.updateVisible(this.label2, 'notDisplay', false);
  58348. }
  58349. removeTextLabel(){
  58350. if(this.label){
  58351. this.label.parent.remove(this.label);
  58352. }
  58353. }
  58354. dispose(){
  58355. let i = viewer.images360.panos.indexOf(this);
  58356. if(i==-1)return
  58357. this.marker.parent.remove(this.marker);
  58358. this.removeTextLabel();
  58359. if(this.depthTex) this.depthTex.dispose();
  58360. viewer.images360.panos.splice(i,1);
  58361. this.dispatchEvent('dispose');
  58362. //删除tile贴图、depthTex等以后再写
  58363. }
  58364. };
  58365. Panorama.prototype.loadTiledPano = function() {
  58366. //var downloads = [] , t = [];
  58367. var downloaded = {} , eventAdded = {}, latestPartialRequest = {}; //每个pano对应一组这些
  58368. return function(size, dirs, fov, o, a, download) {
  58369. var dir = dirs.datasetsLocal.find(e=>e.datasetId == this.pointcloud.dataset_id).direction;
  58370. //var dir = dirs
  58371. null !== o && void 0 !== o || (o = !0),
  58372. null !== a && void 0 !== a || (a = !0);
  58373. var l = this.getWaitDeferred(size)
  58374. , c = l.deferred
  58375. , h = null
  58376. , u = null;
  58377. fov && ("number" == typeof fov ? h = fov : (h = fov.hFov, u = fov.vFov));
  58378. if (!this.isLoaded(size)) {
  58379. //console.log('loadTiledPano', this.id, size, fov)
  58380. if (!l.active) {
  58381. l.active = !0;
  58382. let name = this.id + ":" + size;
  58383. downloaded[name] = downloaded[name] || [];
  58384. /*
  58385. this.downloaded = downloaded
  58386. this.latestPartialRequest = latestPartialRequest
  58387. */
  58388. latestPartialRequest[name] = null;
  58389. if (fov) {
  58390. let tileArr = [];//add
  58391. var d = TileUtils.matchingTilesInDirection(this, size, dir, h, u, tileArr);
  58392. latestPartialRequest[name] = tileArr;
  58393. downloaded[name].forEach((e)=>{
  58394. let item = latestPartialRequest[name].find(a=>e.faceTileIndex == a.faceTileIndex && e.face == a.face);
  58395. if(item){
  58396. item.loaded = true;
  58397. }
  58398. });
  58399. if(!latestPartialRequest[name].some(e=>!e.loaded)){//所需要的全部加载成功
  58400. //let total = TileUtils.getTileCountForSize(size)
  58401. //this.onPanoRendered(this.id, size, total, !0);
  58402. c.resolve(size/* , total */);
  58403. this.resetWaitDeferred(size);
  58404. //console.log('该部分早已经加载好了'+size, this.id)
  58405. latestPartialRequest[name] = null;
  58406. }
  58407. //console.log("Loading partial pano: " + this.id + " with " + d + " tiles")
  58408. }
  58409. if(!eventAdded[this.id]) {
  58410. eventAdded[this.id] = !0;
  58411. this.addEventListener(PanoramaEvents.LoadComplete, function(ev/* e, t */) {//本次任务全部加载完毕
  58412. //console.warn('点位(可能部分)下载完成 ', 'id:'+this.id, 'size:'+ev.size )
  58413. var i = this.getWaitDeferred(ev.size).deferred;//"pending"为还未完成
  58414. i && "pending" === i.state() && this.highestPartialTileRenderOpCompleted >= ev.size && (i.resolve(ev.size, ev.count),
  58415. this.resetWaitDeferred(ev.size));//恢复active为false
  58416. }.bind(this));
  58417. this.addEventListener(PanoramaEvents.LoadFailed, function(ev) {
  58418. var t = this.getWaitDeferred(e).deferred;
  58419. t && "pending" === t.state() && this.highestPartialTileRenderOpCompleted >= ev.t && (t.reject(ev.t),
  58420. this.resetWaitDeferred(ev.t));//恢复active为false
  58421. }.bind(this));
  58422. this.addEventListener(PanoramaEvents.TileLoaded, function(ev/* t, i, n */) {//每张加载完时
  58423. //console.log('tileLoaded', 'id:'+this.id, 'size:'+ev.size, 'tileIndex:'+ev.index )
  58424. let tileIndex = ev.index;
  58425. let total = ev.count;
  58426. let size = ev.size;
  58427. let name = this.id + ":" + size;
  58428. downloaded[name] = downloaded[name] || []; //不是所有的加载都是从loadTiledPano获取的所以会有未定义的情况
  58429. let {faceTileIndex,face} = TileUtils.getTileLocation(size, tileIndex, {});
  58430. downloaded[name].push({faceTileIndex,face});
  58431. var r = this.getWaitDeferred(size).deferred;
  58432. if (r && "pending" === r.state()) {
  58433. r.notify(size, tileIndex, total);
  58434. if(latestPartialRequest[name]){
  58435. let item = latestPartialRequest[name].find(e=>e.faceTileIndex == faceTileIndex && e.face == face);
  58436. item && (item.loaded = true );
  58437. if(!latestPartialRequest[name].some(e=>!e.loaded)){//所需要的局部tiles全部加载成功
  58438. this.onPanoRendered(this.id, size, total, !0); //onPanoRendered还会触发 PanoramaEvents.LoadComplete
  58439. r.resolve(size, total);
  58440. this.resetWaitDeferred(size);
  58441. //console.log('该部分加载好了'+size, this.id)
  58442. latestPartialRequest[name] = null;
  58443. }
  58444. }
  58445. }
  58446. /* var r = this.getWaitDeferred(ev.size).deferred;
  58447. if (r && "pending" === r.state()) {
  58448. r.notify(ev.size, ev.index, ev.count);
  58449. var o = downloads[this.id + ":" + ev.size];
  58450. if(o){//如果有规定下载哪些tile,只需要下载这些tile则LoadComplete
  58451. o.tileCount++
  58452. if(o.tileCount === o.targetTileCount){//达到下载目标数
  58453. this.onPanoRendered(this.id, ev.size, ev.count, !0);
  58454. r.resolve(ev.size, ev.count);
  58455. this.resetWaitDeferred(ev.size)
  58456. }
  58457. }
  58458. } */
  58459. }.bind(this));
  58460. }
  58461. }
  58462. this.images360.tileDownloader.clearForceQueue(),
  58463. this.images360.tileDownloader.forceQueueTilesForPano(this, size, dir, h, u, download);
  58464. this.tiledPanoRenderTarget = this.images360.panoRenderer.activateTiledPano(this, this.images360.qualityManager.getMaxNavPanoSize(), o);
  58465. this.images360.panoRenderer.renderPanoTiles(this.id, dirs, a);
  58466. }else {
  58467. //console.log('早已经全加载好了' +size, this.id)
  58468. c.resolve(size);
  58469. }
  58470. return c.promise()
  58471. }
  58472. }();
  58473. class QualityManager {
  58474. constructor(e, t, i) {
  58475. this.maxNavPanoSize = -1;
  58476. this.maxZoomPanoSize = -1;
  58477. this.devicePixelDensity = e;
  58478. this.deviceScreenSize = t;
  58479. this.clientBandwidth = i;
  58480. this.panoSizeClassMap = {};
  58481. this.useHighResolutionPanos = !0; //是否能够使用2k及以上图
  58482. this.useUltraHighResolutionPanos = !1;
  58483. this.modelHasUltraHighPanos = !1;
  58484. this.qualityManager = this;
  58485. this.maxRenderTargetSize = browser.isMobile() ? 2048 : 4096; //add
  58486. this.init();
  58487. }
  58488. init(e ) {
  58489. //var metadata = store.getters['scene/metadata'] ;//有时候请求不到
  58490. //if(metadata.sceneSource == 11 || metadata.sceneScheme == 12){
  58491. /* if(config.tileClass == '1k'){
  58492. this.useHighResolutionPanos = false //xzw add 只加载1k
  58493. } */
  58494. this.buildPanoSizeClassMap(this.devicePixelDensity, this.deviceScreenSize, this.clientBandwidth);
  58495. this.ultraHighSize = this.getPanoSize(PanoSizeClass.ULTRAHIGH);
  58496. this.highSize = this.getPanoSize(PanoSizeClass.HIGH);
  58497. this.standardSize = this.getPanoSize(PanoSizeClass.STANDARD);
  58498. this.baseSize = this.getPanoSize(PanoSizeClass.BASE);
  58499. config$1.tiling.maxZoomPanoQuality && this.ultraHighSize <= config$1.tiling.maxZoomPanoQuality && (config$1.tiling.allowUltraHighResolution = !0);
  58500. this.highQualityThreshold = browser.valueFromHash("threshold2k", config$1.windowHeightHighQualityThreshold);
  58501. this.updateMaximums();
  58502. //e.on(ModelManagerEvents.ActiveModelChanged, this.onModelChanged.bind(this));
  58503. }
  58504. updateFromModel(e) {
  58505. //this.updateHighResolutionSettings(e)
  58506. this.updateUltraHighResolutionSettings(e);
  58507. }
  58508. /* updateHighResolutionSettings(e) {
  58509. this.useHighResolutionPanos = !0
  58510. this.updateMaximums()
  58511. } */
  58512. updateUltraHighResolutionSettings(e) {
  58513. if (config$1.tiling.allowUltraHighResolution && this.modelHasUltraHighPanos) {
  58514. this.useUltraHighResolutionPanos = !0;
  58515. } else {
  58516. this.useUltraHighResolutionPanos = !1;
  58517. }
  58518. this.updateMaximums();
  58519. }
  58520. enableUltraHighQualityMode() {
  58521. this.modelHasUltraHighPanos = !0;
  58522. this.updateUltraHighResolutionSettings(null);
  58523. }
  58524. ultraHighQualityModeEnabled() {
  58525. return this.modelHasUltraHighPanos
  58526. }
  58527. onModelChanged(e) {
  58528. this.updateFromModel(e.model),
  58529. this.updateMaximums();
  58530. }
  58531. updateMaximums() {
  58532. this.maxNavPanoSize = config$1.tiling.maxNavPanoQuality || this.detectMaxNavPanoSize(),
  58533. this.maxZoomPanoSize = config$1.tiling.maxZoomPanoQuality || this.detectMaxZoomPanoSize(),
  58534. this.maxZoomPanoSize < this.maxNavPanoSize && (this.maxNavPanoSize = this.maxZoomPanoSize);
  58535. }
  58536. buildPanoSizeClassMap() {
  58537. this.panoSizeClassMap[PanoSizeClass.BASE] = 512,
  58538. this.panoSizeClassMap[PanoSizeClass.STANDARD] = 1024,
  58539. this.panoSizeClassMap[PanoSizeClass.HIGH] = 2048,
  58540. this.panoSizeClassMap[PanoSizeClass.ULTRAHIGH] = 4096;
  58541. }
  58542. getPanoSize(e) {
  58543. return this.panoSizeClassMap[e]
  58544. }
  58545. getMaxPossiblePanoSize() {
  58546. return this.getPanoSize(PanoSizeClass.ULTRAHIGH)
  58547. }
  58548. getMaxPanoSize() {
  58549. return this.maxZoomPanoSize
  58550. }
  58551. getMaxNavPanoSize() {
  58552. return this.maxNavPanoSize
  58553. }
  58554. getMaxZoomPanoSize() {
  58555. return this.maxZoomPanoSize
  58556. }
  58557. detectMaxNavPanoSizeClass() {
  58558. //return this.useHighResolutionPanos ? browser.isMobile() ? PanoSizeClass.STANDARD : window.innerHeight < this.highQualityThreshold ? PanoSizeClass.STANDARD : PanoSizeClass.HIGH : PanoSizeClass.STANDARD
  58559. /* if(config.name == 'decor'){
  58560. return PanoSizeClass.STANDARD
  58561. }
  58562. return PanoSizeClass.HIGH */
  58563. switch(Potree.settings.navTileClass){
  58564. case '1k':
  58565. return PanoSizeClass.STANDARD;
  58566. break;
  58567. case '2k':
  58568. default:
  58569. return PanoSizeClass.HIGH;
  58570. }
  58571. }
  58572. detectMaxNavPanoSize() {
  58573. var e = this.detectMaxNavPanoSizeClass();
  58574. return this.getPanoSize(e)
  58575. }
  58576. detectMaxZoomPanoSize() {
  58577. if(this.zoomLevelResolution){
  58578. if(this.zoomLevelResolution == '4k' && this.useUltraHighResolutionPanos){
  58579. return this.getPanoSize(PanoSizeClass.ULTRAHIGH);
  58580. }else if(this.zoomLevelResolution == '1k' || !this.useHighResolutionPanos){
  58581. return this.getPanoSize(PanoSizeClass.STANDARD);
  58582. }else {
  58583. return this.getPanoSize(PanoSizeClass.HIGH);
  58584. }
  58585. }else {
  58586. if (this.useHighResolutionPanos) {
  58587. /* if (browser.isMobile()) {//手机版如果要2k的将这里去掉
  58588. if (settings.tiling.mobileHighQualityOverride) {
  58589. return this.getPanoSize(PanoSizeClass.HIGH);
  58590. } else {
  58591. return this.getPanoSize(PanoSizeClass.STANDARD);
  58592. }
  58593. } else */if (this.useUltraHighResolutionPanos ) {
  58594. return this.getPanoSize(PanoSizeClass.ULTRAHIGH);
  58595. } else {
  58596. return this.getPanoSize(PanoSizeClass.HIGH);
  58597. }
  58598. } else {
  58599. return this.getPanoSize(PanoSizeClass.STANDARD);
  58600. }
  58601. }
  58602. }
  58603. }
  58604. var h = Object.freeze({
  58605. None: 0,
  58606. DirectionalFOV: 1
  58607. });
  58608. var u = function () {
  58609. var e = function e(t, i) {
  58610. var n = e._panoSpaceDir,
  58611. r = e._fovThreshold,
  58612. o = e._fovThresholdNarrow,
  58613. a = Math.max(Math.min(n.dot(t.direction), 1), -1),
  58614. s = Math.max(Math.min(n.dot(i.direction), 1), -1);
  58615. return t._dot = a,
  58616. i._dot = s,
  58617. 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)
  58618. };
  58619. return e._panoSpaceDir = new Vector3,
  58620. e._fovThreshold = -1,
  58621. e._fovThresholdNarrow = -1,
  58622. e
  58623. }();
  58624. class TilePrioritizer {//优先级处理序列
  58625. constructor(e,t, i, o, a) {
  58626. this.qualityManager = e;
  58627. this.maxNavQuality = this.qualityManager.getMaxNavPanoSize();
  58628. this.maxZoomQuality = this.qualityManager.getMaxZoomPanoSize();
  58629. this.baseSize = t;
  58630. this.standardSize = i;
  58631. this.highSize = o;
  58632. this.ultraHighSize = a;
  58633. this.priorityCriteria = new TilePrioritizer.PriorityCriteria(null, new Vector3(0, 0, 0), new Vector3(0, 0, -1), new Vector3(0, 0, -1));
  58634. }
  58635. updateCriteria(e, t, i, n) {//由player更新
  58636. this.priorityCriteria.pano = e,
  58637. this.priorityCriteria.cameraPosition.copy(t),
  58638. //this.priorityCriteria.cameraDir.copy(i),
  58639. this.priorityCriteria.cameraDirs = i;
  58640. this.priorityCriteria.upcomingPanos = n,
  58641. this.maxNavQuality = this.qualityManager.getMaxNavPanoSize(),
  58642. this.maxZoomQuality = this.qualityManager.getMaxZoomPanoSize();
  58643. }
  58644. canDownloadSize(e) {
  58645. return this.maxNavQuality >= e || this.maxZoomQuality >= e && this.zoomingActive
  58646. }
  58647. /* populateNeighborPanos(e, t, i) {
  58648. i = i || [],
  58649. i.length = 0;
  58650. var n = t.getNeighbours(e);
  58651. for (var r in n)
  58652. if (n.hasOwnProperty(r)) {
  58653. var o = t.get(r);
  58654. if(!o){
  58655. console.log(1)
  58656. }
  58657. i.push(o)
  58658. }
  58659. return i
  58660. } */
  58661. populateScoredPanos(e, t, i, dirs, a) {
  58662. i = i || [],
  58663. i.length = 0;
  58664. var s = [Images360.filters.inPanoDirection(e.position, dirs, TilePrioritizer.DIRECTION_SCORE_STRICTNESS), Images360.filters.not(e)],
  58665. l = [Images360.scoreFunctions.distanceSquared(e), Images360.scoreFunctions.direction(e.position, dirs)],
  58666. c = Common.sortByScore(t, s, l);
  58667. if (c)
  58668. for (var h = 0; h < c.length && h < a; h++) {
  58669. var u = c[h].item;
  58670. i.push(u);
  58671. }
  58672. return i
  58673. }
  58674. queueTilesForPanos(e, t, i, n, r) {
  58675. for (var o = 0, a = 0; a < t.length; a++) {
  58676. var s = t[a],
  58677. l = this.queueTilesForPano(e, i, s, n);
  58678. if (o += l > 0 ? 1 : 0,
  58679. r && o >= r)
  58680. break
  58681. }
  58682. return o
  58683. }
  58684. /* queueTilesInDirectionForPanos(e, t, i, n, r, o, a, s) {//没用到
  58685. for (var l = 0, c = 0; c < i.length; c++) {
  58686. var h = i[c],
  58687. u = this.queueTilesInDirectionForPano(e, t, h, n, o, a);
  58688. if (l += u > 0 ? 1 : 0,
  58689. s && l >= s)
  58690. break
  58691. }
  58692. return l
  58693. }
  58694. */
  58695. canIncludeDescriptor(e) {
  58696. return e.status !== DownloadStatus.Downloading && e.status !== DownloadStatus.Downloaded
  58697. }
  58698. canIncludePano(e, t) {
  58699. return !e.isLoaded(t)
  58700. }
  58701. getFOVDotThreshold(e) {
  58702. return Math.cos(MathUtils.degToRad(e / 2))
  58703. }
  58704. setZoomingActive(e) {
  58705. e !== this.zoomingActive && (this.zoomingActive = e);
  58706. }
  58707. }
  58708. TilePrioritizer.PriorityCriteria = function (e, t, i, n, o) {
  58709. this.pano = e,
  58710. this.cameraPosition = (new Vector3).copy(t),
  58711. //this.cameraDir = (new THREE.Vector3).copy(i),
  58712. this.cameraDirs = [], //
  58713. this.panoSpaceDir = (new Vector3).copy(n),
  58714. this.upcomingPanos = o,
  58715. this.copy = function (e) {
  58716. this.pano = e.pano,
  58717. this.cameraPosition.copy(e.cameraPosition),
  58718. //this.cameraDir.copy(e.cameraDir),
  58719. this.cameraDirs = e.cameraDirs;
  58720. this.panoSpaceDir.copy(e.panoSpaceDir),
  58721. this.upcomingPanos = o;
  58722. },
  58723. this.zoomingActive = !1;
  58724. };
  58725. TilePrioritizer.DIRECTIONAL_FOV = 180;
  58726. TilePrioritizer.DIRECTIONAL_FOV_NARROW = 120;
  58727. TilePrioritizer.MAX_SCORED_PANOS_TOCONSIDER = 6;
  58728. TilePrioritizer.MAX_SCORED_PANOS_TOADD = 2;
  58729. TilePrioritizer.MAX_UPCOMING_PANOS_TOADD = 3;
  58730. TilePrioritizer.DIRECTION_SCORE_STRICTNESS = .75;
  58731. TilePrioritizer.appendQueue = function (e, t) {
  58732. if (e && t)
  58733. for (var i = 0; i < t.length; i++){
  58734. e.push(t[i]);
  58735. //console.log(t[i])
  58736. }
  58737. };
  58738. TilePrioritizer.sortPanoTiles = function (descriptors, pano, dir) {
  58739. if(dir.datasetsLocal) dir = dir.datasetsLocal.find(e=>e.datasetId == pano.pointcloud.dataset_id).direction;//add
  58740. u._panoSpaceDir.copy(dir);
  58741. TileUtils.getRelativeDirection(pano.quaternion4dkk, u._panoSpaceDir); //应该是将dir根据quaternion转化下
  58742. u._fovThresholdNarrow = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  58743. u._fovThreshold = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV);
  58744. descriptors.sort(u);
  58745. };
  58746. TilePrioritizer.insertSortedPanoTile = function (e, t, pano, dir) {
  58747. if(dir.datasetsLocal) dir = dir.datasetsLocal.find(e=>e.datasetId == pano.pointcloud.dataset_id).direction;//add
  58748. u._panoSpaceDir.copy(dir),
  58749. TileUtils.getRelativeDirection(pano.quaternion4dkk, u._panoSpaceDir),
  58750. u._fovThresholdNarrow = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV_NARROW),
  58751. u._fovThreshold = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV);
  58752. for (var o = -1, a = 0; a < e.length; a++) {
  58753. var s = u(t, e[a]);
  58754. if (s <= 0) {
  58755. o = a;
  58756. break
  58757. }
  58758. }
  58759. if (o === -1)
  58760. e[e.length] = t;
  58761. else {
  58762. for (var h = e.length; h > o; h--)
  58763. e[h] = e[h - 1];
  58764. e[o] = t;
  58765. }
  58766. };
  58767. TilePrioritizer.prototype.filterDepthTex = function (panos ) {//仅下载depthTex
  58768. if(!Potree.settings.useDepthTex || !this.priorityCriteria.pano)return
  58769. let cameraDirLocals = this.priorityCriteria.cameraDirs.vectorForward;
  58770. let t = [];
  58771. //获得视野范围内的邻近点位序列t
  58772. this.populateScoredPanos(this.priorityCriteria.pano, panos, t, cameraDirLocals , TilePrioritizer.MAX_SCORED_PANOS_TOCONSIDER);
  58773. t.forEach(p=>p.loadDepthImg());
  58774. };
  58775. TilePrioritizer.prototype.filterAndPrioritize = function () {//挑选出优先加载的 pano和tile (有点复杂,没看很懂)
  58776. var e = [],
  58777. t = [],
  58778. i = [];
  58779. return function (queue, panos, tileDownloader) {
  58780. //this.populateNeighborPanos(this.priorityCriteria.pano, panos, e);
  58781. /* let cameraDirLocals = this.priorityCriteria.cameraDirs.map(e=>{ //add
  58782. var dataset = viewer.scene.pointclouds.find(u=>u.dataset_id == e.datasetId)
  58783. var matrix = new THREE.Matrix4().copy(dataset.rotateMatrix)
  58784. var direction = math.convertVector.YupToZup(e.direction)
  58785. return {
  58786. datasetId:e.datasetId,
  58787. direction: direction.clone().applyMatrix4(matrix)
  58788. }
  58789. }) */
  58790. let cameraDirLocals = this.priorityCriteria.cameraDirs.vectorForward;
  58791. //获得视野范围内的邻近点位序列t
  58792. this.populateScoredPanos(this.priorityCriteria.pano, panos, t, cameraDirLocals , TilePrioritizer.MAX_SCORED_PANOS_TOCONSIDER);
  58793. t.forEach(p=>p.loadDepthImg()); //add
  58794. var s = this.baseSize //512
  58795. ,
  58796. l = this.standardSize //1024
  58797. ,
  58798. c = this.highSize //2048
  58799. ,
  58800. h = this.ultraHighSize; //4096
  58801. this.queueTilesForPano(queue, tileDownloader, this.priorityCriteria.pano, s); //把当前pano的512下载了
  58802. if (this.priorityCriteria.upcomingPanos) {// 添加即将走到的点(之前用于导览路线)512 tiles
  58803. this.queueTilesForPanos(queue, this.priorityCriteria.upcomingPanos, tileDownloader, s, TilePrioritizer.MAX_UPCOMING_PANOS_TOADD);
  58804. }
  58805. i.length = 0;
  58806. //把当前pano角度范围内的tile按照分辨率从低到高加入队列
  58807. if (this.canDownloadSize(l)) {//1024如果在限制范围内的话
  58808. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, l, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  58809. }
  58810. TilePrioritizer.sortPanoTiles(i, this.priorityCriteria.pano, this.priorityCriteria.cameraDirs); //排序
  58811. TilePrioritizer.appendQueue(queue, i);
  58812. //添加邻近点t 512的tiles
  58813. this.queueTilesForPanos(queue, t, tileDownloader, s, TilePrioritizer.MAX_SCORED_PANOS_TOADD);
  58814. i.length = 0;
  58815. //NARROW :
  58816. if (this.canDownloadSize(c)) {//2048
  58817. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, c, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  58818. }
  58819. if (this.canDownloadSize(h)) {//4096
  58820. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, h, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  58821. }
  58822. TilePrioritizer.sortPanoTiles(i, this.priorityCriteria.pano, this.priorityCriteria.cameraDirs);//排序
  58823. TilePrioritizer.appendQueue(queue, i);
  58824. i.length = 0;
  58825. if (this.canDownloadSize(l)) {//1024
  58826. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, l, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV);
  58827. }
  58828. if (this.canDownloadSize(c)) {//2048
  58829. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, c, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV);
  58830. }
  58831. if (this.canDownloadSize(h)) {//4096
  58832. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, h, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV);
  58833. }
  58834. TilePrioritizer.sortPanoTiles(i, this.priorityCriteria.pano, this.priorityCriteria.cameraDirs);//排序
  58835. TilePrioritizer.appendQueue(queue, i);
  58836. this.queueTilesForPanos(queue, e, tileDownloader, s); // 如果前面有populateNeighborPanos的话,这步就是加neibour
  58837. }
  58838. }();
  58839. TilePrioritizer.prototype.queueTilesInDirectionForPano = function () {
  58840. var e = {
  58841. filter: h.DirectionalFOV,
  58842. direction: new Vector3,
  58843. fov: 60
  58844. },
  58845. t = new Vector3;
  58846. return function (i, n, pano, o, a, dirs, c) {
  58847. var dir = dirs.datasetsLocal.find(e=>e.datasetId == pano.pointcloud.dataset_id).direction;//add
  58848. //var dir = dirs
  58849. t.copy(dir);
  58850. TileUtils.getRelativeDirection(pano.quaternion4dkk, t);
  58851. e.direction.copy(t);
  58852. e.fov = c;
  58853. return this.filterAndQueueTileDownloadDescriptors(i, n, pano, o, e)
  58854. }
  58855. }();
  58856. TilePrioritizer.prototype.filterAndQueueTileDownloadDescriptors = function () {
  58857. var e = [];
  58858. return function (t, i, n, r, o) {
  58859. var a = i.getTileDownloadDescriptors(n, r);
  58860. e.length = 0,
  58861. this.filterTileDownloadDescriptors(n, a, e, o);
  58862. for (var s = 0, l = 0; l < e.length; l++) {
  58863. var c = e[l];
  58864. if (c) {
  58865. t.push(c);
  58866. s++;
  58867. }
  58868. }
  58869. return s
  58870. }
  58871. }();
  58872. TilePrioritizer.prototype.filterTileDownloadDescriptors = function () {
  58873. new Vector3;
  58874. return function (e, t, i, n) {
  58875. var r, o;
  58876. switch (n.filter) {
  58877. case h.DirectionalFOV:
  58878. for (r = 0; r < t.length; r++)
  58879. o = t[r],
  58880. TileUtils.isTileWithinFOV(o.panoSize, o.tileSize, o.face, o.tileX, o.tileY, n.direction, n.fov) && i.push(o);
  58881. break;
  58882. default:
  58883. for (r = 0; r < t.length; r++)
  58884. o = t[r],
  58885. i.push(o);
  58886. }
  58887. for (r = 0; r < i.length; r++)
  58888. o = i[r],
  58889. this.canIncludeDescriptor(o) || (i[r] = null);
  58890. }
  58891. }();
  58892. TilePrioritizer.prototype.queueTilesForPano = function () {
  58893. var e = {
  58894. filter: h.None
  58895. };
  58896. return function (t, i, n, r) {
  58897. return this.filterAndQueueTileDownloadDescriptors(t, i, n, r, e)
  58898. }
  58899. }();
  58900. /* TilePrioritizer.prototype.queueTilesForPanosInDirection = function () { //没用到
  58901. var e = new THREE.Vector3;
  58902. return function (t, i, n, r, o, a, s, l) {
  58903. for (var h = 0, u = 0; u < n.length; u++) {
  58904. var d = n[u];
  58905. e.copy(d.position),
  58906. e.sub(o),
  58907. e.normalize();
  58908. var p = Math.max(Math.min(a.dot(e), 1), -1),
  58909. f = c.getFOVDotThreshold(s);
  58910. if (p >= f) {
  58911. var g = this.queueTilesInDirectionForPano(t, i, d, r, o, a, s);
  58912. if (h += g > 0 ? 1 : 0,
  58913. l && h >= l)
  58914. break
  58915. }
  58916. }
  58917. return h
  58918. }
  58919. }() */
  58920. //import { i18n } from "@/lang/index"
  58921. // 媒体名称
  58922. /* export const mediaTypes = {
  58923. image: i18n.t("common.photo"),
  58924. video: i18n.t("common.video"),
  58925. audio: i18n.t("common.voice"),
  58926. } */
  58927. // 媒体扩展类型
  58928. const mediaMimes = {
  58929. image: ["jpg", "png", "jpeg", "bmp", "gif"],
  58930. audio: ["mp3", "aac", "ogg", "wav" /* , "m4a" */],
  58931. video: ["mp4", "mov", "quicktime", "webm" /* "rmvb", "wmv" */], //ios:mov
  58932. };
  58933. // 媒体大小显示(MB)
  58934. const mediaMaxSize = {
  58935. image: 10,
  58936. video: 20,
  58937. audio: 5,
  58938. };
  58939. /**
  58940. * 获取媒体扩展类型
  58941. * @param {Stirng} filename 文件名称
  58942. */
  58943. const getMime = filename => {
  58944. if (!filename || filename.indexOf(".") === -1) {
  58945. return ""
  58946. }
  58947. return filename
  58948. .split(".")
  58949. .pop()
  58950. .toLowerCase()
  58951. };
  58952. /**
  58953. * 在路径中获取文件名
  58954. * @param {*} path
  58955. */
  58956. const getFilename = path => {
  58957. const segment = (path || "").split("/");
  58958. return segment[segment.length - 1]
  58959. };
  58960. /**
  58961. * 检测媒体文件是否超过预设限制
  58962. * @param {String} type 媒体类型
  58963. * @param {Number} size 文件大小
  58964. */
  58965. const checkSizeLimit = (type, size) => {
  58966. size = size / 1024 / 1024;
  58967. return size <= mediaMaxSize[type]
  58968. };
  58969. const checkSizeLimitFree = (size, limit) => {
  58970. size = size / 1024 / 1024;
  58971. return size <= limit
  58972. };
  58973. /**
  58974. * 检测媒体类型
  58975. * @param {String} type 媒体类型
  58976. * @param {String} filename 文件名称
  58977. */
  58978. const checkMediaMime = (type, filename) => {
  58979. const mime = getMime(filename);
  58980. const find = mediaMimes[type];
  58981. if (!find) {
  58982. return false
  58983. }
  58984. return find.indexOf(mime) !== -1
  58985. };
  58986. const checkMediaMimeByAccept = (accept, filename) => {
  58987. let mime = getMime(filename);
  58988. let type = accept;
  58989. if (type && type.indexOf("jpg") == -1 && type.indexOf("jpeg") != -1) {
  58990. type += ",image/jpg";
  58991. }
  58992. return (type || "").indexOf(mime) != -1
  58993. };
  58994. const base64ToBlob = base64 => {
  58995. let arr = base64.split(","),
  58996. mime = arr[0].match(/:(.*?);/)[1],
  58997. bstr = atob(arr[1]),
  58998. n = bstr.length,
  58999. u8arr = new Uint8Array(n);
  59000. while (n--) {
  59001. u8arr[n] = bstr.charCodeAt(n);
  59002. }
  59003. return new Blob([u8arr], { type: mime })
  59004. };
  59005. const base64ToDataURL = base64 => {
  59006. return window.URL.createObjectURL(base64ToBlob(base64))
  59007. };
  59008. const blobToBase64 = function(blob) {
  59009. return new Promise(resolve => {
  59010. var reader = new FileReader();
  59011. reader.onload = function() {
  59012. resolve(reader.result);
  59013. };
  59014. reader.readAsDataURL(blob);
  59015. })
  59016. };
  59017. /*
  59018. * @Author: Rindy
  59019. * @Date: 2019-08-06 16:25:08
  59020. * @LastEditors: Rindy
  59021. * @LastEditTime: 2021-08-27 12:33:49
  59022. * @Description: Request
  59023. */
  59024. //import { $alert, $confirm, $loginTips } from "@/components/shared/message"
  59025. //import { $waiting } from "@/components/shared/loading"
  59026. //import { checkLogin } from "@/api"
  59027. //import { LoginDetector } from "@/core/starter"
  59028. //import { i18n } from "@/lang"
  59029. //import { password } from "@/utils/string"
  59030. //import store from "../Store"
  59031. // 空函数
  59032. const noop = function() {};
  59033. // 请求回调队列
  59034. let postQueue = [];
  59035. /**
  59036. * @property {number} NEXT - 继续执行
  59037. * @property {number} SUCCESS - 成功
  59038. * @property {number} EXCEPTION - 异常错误
  59039. * @property {number} FAILURE_CODE_3001 - 缺少必要参数
  59040. * @property {number} FAILURE_CODE_3002 - 访问异常
  59041. * @property {number} FAILURE_CODE_3003 - 非法访问
  59042. * @property {number} FAILURE_CODE_3004 - 用户未登录
  59043. * @property {number} FAILURE_CODE_3005 - 验证码已过期
  59044. * @property {number} FAILURE_CODE_3006 - 验证码错误
  59045. * @property {number} FAILURE_CODE_3007 - 昵称已存在
  59046. * @property {number} FAILURE_CODE_3008 - 该手机已被注册
  59047. * @property {number} FAILURE_CODE_3009 - 两次输入的密码不一致
  59048. * @property {number} FAILURE_CODE_3010 - 昵称长度错误
  59049. * @property {number} FAILURE_CODE_3011 - 密码长度错误
  59050. * @property {number} FAILURE_CODE_3012 - 昵称包含敏感词
  59051. * @property {number} FAILURE_CODE_3013 - 手机号码格式错误
  59052. * @property {number} FAILURE_CODE_3014 - 账号或密码不正确
  59053. * @property {number} FAILURE_CODE_3015 - 用户不存在
  59054. * @property {number} FAILURE_CODE_3016 - 您没有权限,请联系管理员
  59055. * @property {number} FAILURE_CODE_3017 - 空文件
  59056. * @property {number} FAILURE_CODE_3018 - 需要上传或使用的文件不存在
  59057. * @property {number} FAILURE_CODE_5010 - 找不到该场景对应的相机
  59058. * @property {number} FAILURE_CODE_5012 - 数据不正常
  59059. * @property {number} FAILURE_CODE_5014 - 无权操作该场景
  59060. * @property {number} FAILURE_CODE_5005 - 场景不存在
  59061. */
  59062. const statusCode = {
  59063. NEXT: -999,
  59064. SUCCESS: 0,
  59065. EXCEPTION: -1,
  59066. FAILURE_CODE_3001: 3001,
  59067. FAILURE_CODE_3002: 3002,
  59068. FAILURE_CODE_3003: 3003,
  59069. FAILURE_CODE_3004: 3004,
  59070. FAILURE_CODE_3005: 3005,
  59071. FAILURE_CODE_3006: 3006,
  59072. FAILURE_CODE_3007: 3007,
  59073. FAILURE_CODE_3008: 3008,
  59074. FAILURE_CODE_3009: 3009,
  59075. FAILURE_CODE_3010: 3010,
  59076. FAILURE_CODE_3011: 3011,
  59077. FAILURE_CODE_3012: 3012,
  59078. FAILURE_CODE_3013: 3013,
  59079. FAILURE_CODE_3014: 3014,
  59080. FAILURE_CODE_3015: 3015,
  59081. FAILURE_CODE_3016: 3016,
  59082. FAILURE_CODE_3017: 3017,
  59083. FAILURE_CODE_3018: 3018,
  59084. FAILURE_CODE_5010: 5010,
  59085. FAILURE_CODE_5012: 5012,
  59086. FAILURE_CODE_5014: 5014,
  59087. FAILURE_CODE_5005: 5005,
  59088. };
  59089. /**
  59090. * 获取Token
  59091. * @function
  59092. */
  59093. function getToken() {
  59094. var urlToken = browser.urlHasValue("token", true);
  59095. if (urlToken) {
  59096. // 设置token共享给用户中心
  59097. localStorage.setItem("token", urlToken);
  59098. }
  59099. return urlToken || localStorage.getItem("token") || ""
  59100. }
  59101. /**
  59102. * 根据状态码的结果处理后续操作
  59103. * @function
  59104. * @param {number} code - 状态码
  59105. * @param {function} callback - 回调
  59106. */
  59107. function statusCodesHandler(code, callback) {
  59108. if (code == statusCode.EXCEPTION) {
  59109. return $alert({ content: i18n.t("tips.exception") })
  59110. }
  59111. if (
  59112. code == statusCode.FAILURE_CODE_3002 ||
  59113. code == statusCode.FAILURE_CODE_3003 ||
  59114. code == statusCode.FAILURE_CODE_3004
  59115. ) {
  59116. callback(code);
  59117. return showLoginTips()
  59118. }
  59119. if (code == statusCode.FAILURE_CODE_3001) {
  59120. callback(code);
  59121. return $alert({ content: i18n.t("tips.params_notfound") })
  59122. }
  59123. if (code == statusCode.FAILURE_CODE_3017) {
  59124. callback(code);
  59125. return $alert({ content: i18n.t("tips.file_notfound") })
  59126. }
  59127. if (code == statusCode.FAILURE_CODE_5005) {
  59128. /* if (!config.isEdit) {
  59129. return (location.href = config.pages.NotFound)
  59130. } */
  59131. callback(code);
  59132. return $alert({ content: i18n.t("tips.scene_notfound") })
  59133. }
  59134. if (code == statusCode.FAILURE_CODE_5010) {
  59135. callback(code);
  59136. return $alert({ content: i18n.t("tips.camera_notfound") })
  59137. }
  59138. if (code == statusCode.FAILURE_CODE_5012) {
  59139. callback(code);
  59140. return $alert({ content: i18n.t("tips.data_error") })
  59141. }
  59142. if (code == statusCode.FAILURE_CODE_5014) {
  59143. callback(code);
  59144. return $alert({ content: i18n.t("tips.auth_deny") })
  59145. }
  59146. return statusCode.NEXT
  59147. }
  59148. $.ajaxSetup({
  59149. headers: {},
  59150. beforeSend: function(xhr) {
  59151. const token = getToken();
  59152. if (token) {
  59153. xhr.setRequestHeader("token", token);
  59154. } else if (!token && this.url.indexOf("isLogin") != -1) {
  59155. showLoginTips();
  59156. }
  59157. /* if (config.oem == "localshow") {
  59158. // 本地版本兼容当前目录
  59159. if (this.url.indexOf("http") == -1 && this.url.indexOf("/") == 0) {
  59160. this.url = this.url.substr(1)
  59161. }
  59162. } */
  59163. // if(this.url.indexOf('http')==-1 && this.url.indexOf('/') !=0){
  59164. // this.url = '/'+this.url
  59165. // }
  59166. },
  59167. error: function(xhr, status, error) {
  59168. // 出错时默认的处理函数
  59169. if (this.url.indexOf("/scene.json") != -1 && xhr.status == 404) {
  59170. return $alert({ content: i18n.t("tips.scene_notfound") })
  59171. } else if (this.type === "POST") {
  59172. return $alert({ content: i18n.t("tips.network_error") })
  59173. }
  59174. },
  59175. success: function(result) {},
  59176. complete: function() {
  59177. // Post类型请求无论成功或失败都关闭等待提示
  59178. if (this.type === "POST") {
  59179. http.__loading && $waiting.hide();
  59180. }
  59181. http.__loading = true;
  59182. },
  59183. });
  59184. /**
  59185. * @namespace http
  59186. * @type {Object}
  59187. */
  59188. const http = {
  59189. statusCode,
  59190. __loading: true,
  59191. __request(xhr, method, url, data, done, fail) {
  59192. if (typeof done != "function") {
  59193. done = noop;
  59194. }
  59195. if (typeof fail != "function") {
  59196. fail = noop;
  59197. }
  59198. xhr.done(result => {
  59199. if (typeof result.code !== "undefined") {
  59200. const flag = statusCodesHandler(result.code, function(code) {
  59201. // 需要登录的状态
  59202. if (
  59203. code == statusCode.FAILURE_CODE_3001 ||
  59204. code == statusCode.FAILURE_CODE_3002 ||
  59205. code == statusCode.FAILURE_CODE_3003 ||
  59206. code == statusCode.FAILURE_CODE_3004
  59207. ) {
  59208. if (url.indexOf("isLogin") == -1 && url.indexOf("openSceneBykey") == -1) {
  59209. postQueue.push(function() {
  59210. http[method](url, data, done, fail);
  59211. });
  59212. }
  59213. }
  59214. fail();
  59215. });
  59216. if (flag === statusCode.NEXT) {
  59217. done(result, result.code == 0);
  59218. }
  59219. } else {
  59220. done(result);
  59221. }
  59222. });
  59223. xhr.fail(fail);
  59224. xhr.always(() => (xhr = null));
  59225. return xhr
  59226. },
  59227. /**
  59228. * Get请求
  59229. * @param {String} url 请求地址
  59230. * @param {Object?} data 请求参数
  59231. * @param {Function?} done 成功回调
  59232. * @param {Function?} fail 失败回调
  59233. */
  59234. get(url, data = {}, done, fail) {
  59235. if (/\.json/.test(url)) {
  59236. // json文件格式自动调用getJson方法
  59237. return this.getJson(url, data, done, fail)
  59238. }
  59239. return this.__request($.get(url, data), "get", url, data, done, fail)
  59240. },
  59241. /**
  59242. * Get Blob请求
  59243. * @param {String} url 请求地址
  59244. * @param {Object?} data 请求参数
  59245. * @param {Function?} done 成功回调
  59246. * @param {Function?} fail 失败回调
  59247. */
  59248. getText(url, data = {}, done, fail) {
  59249. return this.__request(
  59250. $.ajax({
  59251. url: url,
  59252. dataType: "text",
  59253. }),
  59254. "getText",
  59255. url,
  59256. data,
  59257. done,
  59258. fail
  59259. )
  59260. },
  59261. /**
  59262. * GetJson请求 读取json文件数据
  59263. * @param {String} url 请求地址
  59264. * @param {Object?} data 请求参数
  59265. * @param {Function?} done 成功回调
  59266. * @param {Function?} fail 失败回调
  59267. */
  59268. getJson(url, data = {}, done, fail) {
  59269. return this.__request($.getJSON(url, data), "get", url, data, done, fail)
  59270. },
  59271. /**
  59272. * Get Blob请求
  59273. * @param {String} url 请求地址
  59274. * @param {Object?} data 请求参数
  59275. * @param {Function?} done 成功回调
  59276. * @param {Function?} fail 失败回调
  59277. */
  59278. getBlob(url, data = {}, done, fail) {
  59279. return this.__request(
  59280. $.ajax({
  59281. url: url,
  59282. dataType: "blob",
  59283. }),
  59284. "getBlob",
  59285. url,
  59286. data,
  59287. done,
  59288. fail
  59289. )
  59290. },
  59291. /**
  59292. * Get Arraybuffer请求
  59293. * @param {String} url 请求地址
  59294. * @param {Object?} data 请求参数
  59295. * @param {Function?} done 成功回调
  59296. * @param {Function?} fail 失败回调
  59297. */
  59298. getArraybuffer(url, data = {}, done, fail) {
  59299. return this.__request(
  59300. $.ajax({
  59301. url: url,
  59302. dataType: "arraybuffer",
  59303. }),
  59304. "getArraybuffer",
  59305. url,
  59306. data,
  59307. done,
  59308. fail
  59309. )
  59310. },
  59311. /**
  59312. * Post 请求
  59313. * @param {String} url 请求地址
  59314. * @param {Object?} data 请求参数
  59315. * @param {Function?} done 成功回调
  59316. * @param {Function?} fail 失败回调
  59317. */
  59318. post(url, data = {}, done, fail) {
  59319. if (url.indexOf("isLogin") == -1) {
  59320. http.__loading && $waiting.show();
  59321. }
  59322. return this.__request($.post(url, data), "post", url, data, done, fail)
  59323. },
  59324. /**
  59325. * PostJson 请求
  59326. * @param {String} url 请求地址
  59327. * @param {Object?} data 请求参数
  59328. * @param {Function?} done 成功回调
  59329. * @param {Function?} fail 失败回调
  59330. */
  59331. postJson(url, data = {}, done, fail) {
  59332. http.__loading && $waiting.show();
  59333. return this.__request(
  59334. $.ajax({
  59335. type: "POST",
  59336. url: url,
  59337. contentType: "application/json",
  59338. data: JSON.stringify(data),
  59339. }),
  59340. "postJson",
  59341. url,
  59342. data,
  59343. done,
  59344. fail
  59345. )
  59346. },
  59347. /**
  59348. * Post 表单 支持文件上传
  59349. * @param {String} url 请求地址
  59350. * @param {FormData?} formData 请求参数
  59351. * @param {Function?} done 成功回调
  59352. * @param {Function?} fail 失败回调
  59353. */
  59354. postForm(url, formData, done, fail, onProgress) {
  59355. if (typeof onProgress === "function") {
  59356. return this.__request(
  59357. $.ajax({
  59358. type: "POST",
  59359. url: url,
  59360. processData: false,
  59361. contentType: false,
  59362. data: formData,
  59363. xhr: function() {
  59364. const xhr = new XMLHttpRequest();
  59365. xhr.upload.addEventListener("progress", function(e) {
  59366. onProgress((e.loaded / e.total) * 100 + "%");
  59367. });
  59368. return xhr
  59369. },
  59370. }),
  59371. "postForm",
  59372. url,
  59373. formData,
  59374. done,
  59375. fail
  59376. )
  59377. } else {
  59378. http.__loading && $waiting.show();
  59379. return this.__request(
  59380. $.ajax({
  59381. type: "POST",
  59382. url: url,
  59383. processData: false,
  59384. contentType: false,
  59385. data: formData,
  59386. }),
  59387. "postForm",
  59388. url,
  59389. formData,
  59390. done,
  59391. fail
  59392. )
  59393. }
  59394. },
  59395. /**
  59396. * 加载图片
  59397. * @param {String} url 请求地址
  59398. * @param {Number?} retry 重试次数,默认为3
  59399. */
  59400. loadImage(url, retry = 3) {
  59401. const def = $.Deferred();
  59402. const img = new Image();
  59403. /* if (process.env.VUE_APP_REGION == "AWS" && url.indexOf("x-oss-process=image") != -1) {
  59404. var arr = url.split("?")
  59405. url = arr[0] + encodeURIComponent("?" + arr[1].replace(/\//g, "@"))
  59406. } */
  59407. const load = () => {
  59408. console.warn("Retrying load image: " + url);
  59409. this.loadImage(url, retry - 1)
  59410. .done(def.resolve.bind(def))
  59411. .progress(def.notify.bind(def))
  59412. .fail(def.reject.bind(def));
  59413. };
  59414. img.onerror = function() {
  59415. retry > 0 ? setTimeout(() => load(), 1e3) : def.reject(`[${url}]加载失败`);
  59416. };
  59417. img.onload = function() {
  59418. def.resolve(img);
  59419. };
  59420. img.crossOrigin = "anonymous";
  59421. img.src = url;
  59422. return def
  59423. },
  59424. /**
  59425. * 上传文件
  59426. * @param {String} url 请求地址
  59427. * @param {Object?} data 请求参数
  59428. * @param {Function?} done 成功回调
  59429. * @param {Function?} fail 失败回调
  59430. */
  59431. uploadFile(url, data = {}, done, fail, onProgress) {
  59432. const form = new FormData();
  59433. // if (file.needTransfer) { //ie和苹果都不支持dataURLtoFile得传送,所以只能用blob
  59434. // form.append("file", common.dataURLtoBlob(file.file), file.name || file.file.name);
  59435. // } else {
  59436. // form.append("file", file.file, file.name || file.file.name);
  59437. // }
  59438. for (let key in data) {
  59439. if (key == "file") {
  59440. form.append("file", data[key], data.filename || data[key].name);
  59441. } else if (key != "filename") {
  59442. form.append(key, data[key]);
  59443. }
  59444. }
  59445. return this.postForm(url, form, done, fail, onProgress)
  59446. },
  59447. /**
  59448. * 上传文件
  59449. * @param {String} url 请求地址
  59450. * @param {Object?} data 请求参数 {file:'base64 string',filename:'image.jpg',...}
  59451. * @param {Function?} done 成功回调
  59452. * @param {Function?} fail 失败回调
  59453. */
  59454. uploadBlobFile(url, data = {}, done, fail) {
  59455. const form = new FormData();
  59456. for (let key in data) {
  59457. if (key === "file") {
  59458. form.append("file", base64ToBlob(data.file), data.filename);
  59459. } else if (key != "filename") {
  59460. form.append(key, data[key]);
  59461. }
  59462. }
  59463. return this.postForm(url, form, done, fail)
  59464. },
  59465. };
  59466. window.downloaded = {};
  59467. window.startdownloads = [];
  59468. class TileDownloader extends EventDispatcher{
  59469. constructor( ) {
  59470. super();
  59471. this.panos = null;
  59472. this.retryMinimumTime = 1e4;
  59473. this.panoLoadCallbacks = {};
  59474. this.downloadDescriptors = {};
  59475. this.priorityQueue = [];
  59476. this.forceQueue = [];
  59477. this.activeDownloads = [];
  59478. this.tilePrioritizer = null;
  59479. this.refreshInterval = null;
  59480. this.processPriorityQueue = !1;
  59481. this.concurrentDownloads = 6;//e.concurrentDownloads || 1;
  59482. this.downloadTestResults = {};
  59483. this.freeze = Object.freeze({
  59484. Testing: 1,
  59485. Success: 2,
  59486. Fail: 3
  59487. });
  59488. this.visible = true; //add 借用viewer.updateVisible来判断是否start
  59489. viewer.addEventListener('pageVisible', (e)=>{//不可见时不refreshUpdateInterval
  59490. //console.log('visibilitychange:', state)
  59491. viewer.updateVisible(this, 'pageVisible', e.v);
  59492. this.judgeStart();
  59493. });
  59494. }
  59495. setPanoData(e, t /* , i */) {
  59496. this.panos = e,
  59497. this.imagePanos = t;
  59498. // this.panoGroupId = i
  59499. }
  59500. start() {
  59501. this.downloadCubeTex = true;
  59502. if(!Potree.settings.useDepthTex){
  59503. viewer.updateVisible(this,'pano', true );
  59504. this.judgeStart();
  59505. }else {
  59506. this.refreshInterval || this.judgeStart();
  59507. }
  59508. }
  59509. stop() {
  59510. this.downloadCubeTex = false;
  59511. if(!Potree.settings.useDepthTex){
  59512. viewer.updateVisible(this,'pano', false );
  59513. this.judgeStart();
  59514. }
  59515. }
  59516. judgeStart(){//add
  59517. if(this.visible){
  59518. //console.log('judgeStart true')
  59519. this.started = true;
  59520. this.refreshUpdateInterval(0);
  59521. }else {
  59522. //console.log('judgeStart false')
  59523. this.started = false;
  59524. window.clearTimeout(this.refreshInterval);
  59525. }
  59526. }
  59527. refreshUpdateInterval(e) {
  59528. e || (e = 0),
  59529. this.refreshInterval = window.setTimeout(function() {
  59530. var e = this.update();
  59531. e ? this.refreshUpdateInterval(TileDownloader.ACTIVE_REFRESH_DELAY) : this.refreshUpdateInterval(TileDownloader.IDLE_REFRESH_DELAY);
  59532. }
  59533. .bind(this), e);
  59534. }
  59535. update() {
  59536. if(this.downloadCubeTex){ //可以下载贴图
  59537. var e = this.forceQueue.length > 0;
  59538. this.processQueueForDownloading(this.forceQueue);
  59539. if (this.processPriorityQueue) {
  59540. this.queuePrioritizedTilesForPanos(this.panos);
  59541. this.priorityQueue.length > 0 && (e = !0);
  59542. this.processQueueForDownloading(this.priorityQueue);
  59543. }
  59544. return e
  59545. }else {//仅下载depthTex
  59546. this.tilePrioritizer.filterDepthTex(this.panos);
  59547. }
  59548. }
  59549. queuePrioritizedTilesForPanos(e) {
  59550. this.tilePrioritizer && (this.clearQueue(this.priorityQueue),
  59551. this.tilePrioritizer.filterAndPrioritize(this.priorityQueue, e, this),
  59552. this.clearFromQueue(this.priorityQueue, DownloadStatus.None, !0), //去除state为DownloadStatus.None的(可能是去除已经在下载的)
  59553. this.setStatusOrRemoveForAllDescriptors(this.priorityQueue, DownloadStatus.Queued));
  59554. }
  59555. clearQueue(e) {//停止下载并清空
  59556. this.setStatusForAllDescriptors(e, DownloadStatus.None),
  59557. e.length = 0;
  59558. }
  59559. clearForceQueue() {
  59560. this.clearQueue(this.forceQueue);
  59561. }
  59562. clearFromQueue(e, t, i) {
  59563. for (var n = 0; n < e.length; n++) {
  59564. var r = e[n];
  59565. r && (t === r.status && !i || t !== r.status && i) && (e[n] = null);
  59566. }
  59567. }
  59568. setStatusForAllDescriptors(e, t) {
  59569. for (var i = 0; i < e.length; i++) {
  59570. var n = e[i];
  59571. n && (n.status = t);
  59572. }
  59573. }
  59574. setStatusOrRemoveForAllDescriptors(e, t) {
  59575. for (var i = 0; i < e.length; i++) {
  59576. var n = e[i];
  59577. n && (n.status !== t ? n.status = t : e[i] = null);
  59578. }
  59579. }
  59580. getTileDownloadDescriptors(pano, size) {//获取该pano的该size的全部的tile的descriptor
  59581. var i = this.getAllTileDownloadDescriptorsForPano(pano),
  59582. n = i[size];
  59583. return n || (n = this.buildDownloadDescriptorArray(size),//创建的全部是空的
  59584. i[size] = n,
  59585. this.initTileDownloadDescriptors(n, pano, size)),//绑定到该pano size
  59586. n
  59587. }
  59588. getAllTileDownloadDescriptorsForPano(pano) {//新建空Descriptors
  59589. var t = this.downloadDescriptors[pano.id];
  59590. return t || (t = {},
  59591. this.downloadDescriptors[pano.id] = t),
  59592. t
  59593. }
  59594. processQueueForDownloading(e, t) {//执行下载任务
  59595. this.cleanupActiveDownloads();
  59596. if (this.activeDownloads.length < this.concurrentDownloads || t) {
  59597. var i = t ? e.length : this.concurrentDownloads - this.activeDownloads.length;
  59598. for (var n = 0, r = 0; n < i && e.length > 0; r++) {
  59599. var o = e.shift();
  59600. if(o){
  59601. //add 为了防止1024的在512前下载完,这里强行等待512下载完毕再开始下载
  59602. if(o.panoSize > 512 && !this.isPanoDownloaded(o.pano, 512) ){
  59603. //console.log('512的还没下载好呢!')
  59604. e.push(o);
  59605. break;//一般512的都是连续下载的,所以后面就都不是512了直接中断
  59606. }
  59607. this.startDownload(o);
  59608. n++;
  59609. }
  59610. }
  59611. }
  59612. }
  59613. testDownload(panoSize, tileSize, callback) {
  59614. var n = this.downloadTestResults[panoSize];
  59615. if (n)
  59616. return void(n === this.freeze.Success ? callback(!0) : n === this.freeze.Fail && callback(!1));
  59617. this.downloadTestResults[panoSize] = this.freeze.Testing;
  59618. var r = this.panos[0],
  59619. o = this.getTileUrl({pano:r, panoSize, tileSize, tileIndex:0} /* r.id, panoSize, tileSize, 0 */),
  59620. a = function(t) {
  59621. this.downloadTestResults[panoSize] = this.freeze.Success,
  59622. callback(!0);
  59623. }
  59624. .bind(this),
  59625. s = function() {
  59626. this.downloadTestResults[panoSize] = this.freeze.Fail,
  59627. callback(!1);
  59628. }
  59629. .bind(this);
  59630. this.loadImage(o, 0, a, s);
  59631. }
  59632. startDownload(e) {//开始下载啦
  59633. //console.log('startDownload')
  59634. startdownloads.push(e);
  59635. e.status = DownloadStatus.Downloading;
  59636. var t = this.getTileUrl(e/* e.pano.id, e.panoSize, e.tileSize, e.tileIndex, e.pano.alignmentType */);//xzw add alignmentType
  59637. if(!t)return;
  59638. this.activeDownloads.push(e);
  59639. this.loadImage(t, TileDownloader.DOWNLOAD_RETRIES, this.downloadComplete.bind(this, e), this.downloadFailed.bind(this, e));
  59640. }
  59641. downloadFailed(e, t) {}
  59642. downloadComplete(e, t) {//下载成功时
  59643. //if (e.panoGroupId === this.panoGroupId) {
  59644. var i = this.getPanoLoadCallbacks(e.pano, e.panoSize);
  59645. e.status = DownloadStatus.Downloaded,
  59646. i && i.onProgress && i.onProgress(e.pano, e.panoSize);
  59647. var n = {
  59648. panoId: e.pano.id,
  59649. image: t,
  59650. tileSize: e.tileSize,
  59651. panoSize: e.panoSize,
  59652. tileIndex: e.tileIndex,
  59653. faceTileIndex: e.faceTileIndex,
  59654. totalTiles: e.totalTiles,
  59655. face: e.face,
  59656. tileX: e.tileX,
  59657. tileY: e.tileY,
  59658. direction: e.direction
  59659. };
  59660. downloaded[e.pano.id] || (downloaded[e.pano.id]={512:[],1024:[],2048:[]});
  59661. downloaded[e.pano.id][e.panoSize] || (downloaded[e.pano.id][e.panoSize] = []);
  59662. downloaded[e.pano.id][e.panoSize].push(e);
  59663. if(e.panoSize != 512 && downloaded[e.pano.id][512].length<6){
  59664. console.warn('没下完');
  59665. }
  59666. e.image = t,
  59667. this.dispatchEvent({type:TileDownloaderEvents.TileDownloadSuccess, desc:n} );
  59668. this.isPanoDownloaded(e.pano, e.panoSize) && (n = {
  59669. panoId: e.pano.id,
  59670. tileSize: e.tileSize,
  59671. panoSize: e.panoSize
  59672. },
  59673. this.dispatchEvent({type:TileDownloaderEvents.PanoDownloadComplete, desc:n}),
  59674. i && i.onLoad && i.onLoad(e.pano, e.panoSize));
  59675. //}
  59676. }
  59677. isPanoDownloaded(e, t) {
  59678. var i = this.getTileDownloadDescriptors(e, t);
  59679. if (i.length <= 0)
  59680. return !1;
  59681. for (var n = 0; n < i.length; n++) {
  59682. var r = i[n];
  59683. if (r.status !== DownloadStatus.Downloaded)
  59684. return !1
  59685. }
  59686. return !0
  59687. }
  59688. setPanoLoadCallbacks(e, t, i, n, r) {
  59689. var o = e.id + ":" + this.qualityManager.getPanoSize(t);
  59690. this.panoLoadCallbacks[o] = {
  59691. onLoad: i,
  59692. onFail: n,
  59693. onProgress: r
  59694. };
  59695. }
  59696. getPanoLoadCallbacks(e, t) {
  59697. var i = e.id + ":" + t;
  59698. return this.panoLoadCallbacks[i]
  59699. }
  59700. buildDownloadDescriptorArray(e) {
  59701. for (var t = TileUtils.getTileCountForSize(e), i = [], n = 0; n < t; n++) {
  59702. var r = this.buildDownloadDescriptor();
  59703. i.push(r);
  59704. }
  59705. return i
  59706. }
  59707. buildDownloadDescriptor() {//Descriptor!
  59708. var e = {
  59709. panoGroupId: null,
  59710. pano: null,
  59711. panoSize: -1,
  59712. tileSize: -1,
  59713. tileIndex: -1,
  59714. totalTiles: -1,
  59715. faceTileIndex: -1,
  59716. status: DownloadStatus.None,
  59717. url: null,
  59718. image: null,
  59719. direction: new Vector3, //该tile在cube中的方向
  59720. face: -1,
  59721. cubeFace: -1,
  59722. tileX: -1,
  59723. tileY: -1
  59724. };
  59725. return e
  59726. }
  59727. initTileDownloadDescriptors(e, t, i) {
  59728. for (var n = 0; n < e.length; n++) {
  59729. var r = e[n];
  59730. this.initTileDownloadDescriptor(r, t, i, n);
  59731. }
  59732. }
  59733. initTileDownloadDescriptor(desc, pano, size, index) {
  59734. var r = size >= TileUtils.TILE_SIZE ? TileUtils.TILE_SIZE : size;
  59735. desc.face = TileUtils.getFaceForTile(size, index);//根据顺序得到的face的index
  59736. desc.cubeFace = TileUtils.mapFaceToCubemapFace(desc.face);//为了贴图而转化的face index
  59737. //desc.panoGroupId = this.panoGroupId;//就是场景号
  59738. desc.pano = pano;
  59739. desc.panoSize = size;
  59740. desc.tileSize = r; //瓦片图size 512
  59741. desc.tileIndex = index;
  59742. desc.totalTiles = TileUtils.getTileCountForSize(size);
  59743. desc.status = DownloadStatus.None;
  59744. desc.image = null;
  59745. TileUtils.getTileLocation(desc.panoSize, desc.tileIndex, desc);//得到该tile在这个face中的具体位置(tileX等)
  59746. TileUtils.getTileVector(desc.panoSize, desc.tileSize, desc.cubeFace, desc.tileX, desc.tileY, TileUtils.LocationOnTile.Center, 0, desc.direction);
  59747. }
  59748. getTiles(d, sceneNum){
  59749. if(Potree.settings.isLocal2){//新的地址 scene_view_data/场景码/images/tiles
  59750. return `${Potree.settings.urls.prefix3}/scene_view_data/${sceneNum}/images/${d}`
  59751. }
  59752. return `${Potree.settings.urls.prefix3}/images/images${sceneNum}/${d}`
  59753. }
  59754. loadImage(e, t, i, n) {
  59755. //自己修改了ajax,把getImage改成了loadImg
  59756. http.loadImage(e, t).then(function(e) {
  59757. i(e);
  59758. }).fail(n);
  59759. }
  59760. }
  59761. TileDownloader.prototype.forceQueueTilesForPano = function() {//根据条件开始加载tile
  59762. var e = [],
  59763. t = [];
  59764. return function(pano, size, dir, hFov, vFov, download) {
  59765. e.length = 0;
  59766. for (var u = this.getTileDownloadDescriptors(pano, size), d = 0; d < u.length; d++) {
  59767. var p = u[d];
  59768. p.status !== DownloadStatus.None && p.status !== DownloadStatus.Queued || e.push(p);
  59769. }
  59770. if (dir && e.length > 0) {
  59771. TilePrioritizer.sortPanoTiles(e, pano, dir); //按最佳方向排序e
  59772. t.length = 0;
  59773. TileUtils.matchingTilesInDirection(pano, size, dir, hFov, vFov, t);//得到在符合视野标准的集合t
  59774. for (var f = 0, g = function(e) {
  59775. return e.face === m.face && e.faceTileIndex === m.faceTileIndex
  59776. }; f < e.length;) { //过滤掉不符合角度要求的
  59777. var m = e[f],
  59778. v = t.findIndex(g);
  59779. v < 0 ? e.splice(f, 1) : f++;
  59780. }
  59781. }
  59782. for (var A = 0; A < e.length; A++){
  59783. this.forceQueue.push(e[A]); //装载
  59784. }
  59785. /* if(e.length){
  59786. console.log(e)
  59787. } */
  59788. this.setStatusForAllDescriptors(this.forceQueue, DownloadStatus.ForceQueued);
  59789. this.clearFromQueue(this.priorityQueue, DownloadStatus.ForceQueued, !1);
  59790. download && this.processQueueForDownloading(this.forceQueue, !0);
  59791. }
  59792. }();
  59793. TileDownloader.prototype.cleanupActiveDownloads = function() {
  59794. var e = [];
  59795. return function() {
  59796. e.length = 0;
  59797. for (var t = 0; t < this.activeDownloads.length; t++) {
  59798. var i = this.activeDownloads[t];
  59799. i.status !== DownloadStatus.Downloaded && i.status !== DownloadStatus.Failed && e.push(i);
  59800. }
  59801. this.activeDownloads.length = 0,
  59802. this.activeDownloads.push.apply(this.activeDownloads, e);
  59803. }
  59804. }();
  59805. TileDownloader.prototype.getTileUrl = function() {
  59806. var e = {
  59807. 256: "256",
  59808. 512: "512",
  59809. 1024: "1k",
  59810. 2048: "2k",
  59811. 4096: "4k"
  59812. },
  59813. t = {
  59814. face: -1,
  59815. faceTileIndex: -1,
  59816. tileX: -1,
  59817. tileY: -1
  59818. };
  59819. return function(o={} ) {
  59820. var id = o.pano.originID, ////////
  59821. panoSize = o.panoSize,
  59822. tileSize = o.tileSize,
  59823. tileIndex = o.tileIndex,
  59824. sceneCode = o.pano.pointcloud.sceneCode;
  59825. var metadata = {sceneScheme:10};
  59826. TileUtils.getTileLocation(panoSize, tileIndex, t);
  59827. var s = Math.floor(panoSize / tileSize),
  59828. l = s * s,
  59829. h = Math.floor(tileIndex / l),
  59830. u = "",
  59831. d = '', g = '';
  59832. if(Potree.settings.isLocal){//原始规则
  59833. //1 === config.tiling.customCompression && (u = "_" + config.tiling["q" + e[panoSize]]);
  59834. //1 === o.tiling.customCompression && (u = "_" + o.tiling["q" + e[n]]);
  59835. d = "tiles/" + id + "/" + e[panoSize] + u + "_face" + h + "_" + t.tileX + "_" + t.tileY + ".jpg";
  59836. d = this.getTiles(d, sceneCode);
  59837. g = "?";
  59838. }else {//阿里云oss的规则 if (metadata.sceneScheme == 10)
  59839. d = 'tiles/4k/' + id + '_skybox' + h + '.jpg?x-oss-process=';
  59840. if (e[panoSize] == '512') {
  59841. d += 'image/resize,h_512';
  59842. } else {
  59843. //4k的图,移动端是1k,pc端是2k,放大才是4k
  59844. 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
  59845. d += 'image/resize,m_lfit,w_' + panoSize + '/crop,w_512,h_512,';
  59846. } else {
  59847. d = 'tiles/4k/' + id + '_skybox' + h + '.jpg?x-oss-process=image/crop,w_512,h_512,';
  59848. }
  59849. //起始位置
  59850. if (t.tileX == 0) {
  59851. d += 'x_0,';
  59852. } else {
  59853. d += 'x_' + (512 * t.tileX - 1) + ',';
  59854. }
  59855. if (t.tileY == 0) {
  59856. d += 'y_0';
  59857. } else {
  59858. d += 'y_' + (512 * t.tileY - 1);
  59859. }
  59860. }
  59861. d = this.getTiles(d, sceneCode);
  59862. g = "&";
  59863. }
  59864. d += g + 'time='+o.pano.pointcloud.timeStamp; //加后缀
  59865. return d;
  59866. }
  59867. }();
  59868. TileDownloader.tilegen = true;
  59869. TileDownloader.IDLE_REFRESH_DELAY = 500;
  59870. TileDownloader.ACTIVE_REFRESH_DELAY = 16;
  59871. TileDownloader.DOWNLOAD_RETRIES = 4;
  59872. function Node$1(e, t) {
  59873. this.tree = e, //所属树(TileTree)
  59874. this.parent = t,
  59875. this.children = [],
  59876. this.id = ++u$1;
  59877. }
  59878. function o(e, t, i, r, a, s, l, h) {
  59879. if (e) {
  59880. l = l || TileTree.TraversalType.PreOrder;
  59881. var u = r * c + i;
  59882. if (l === TileTree.TraversalType.PreOrder && (a && a(e, t, u, i, r),
  59883. s && s.push(e)),
  59884. e.children && 0 !== e.children.length) {
  59885. for (var d = r * c, p = i * c, f = 0; f < c; f++)
  59886. for (var g = 0; g < c; g++)
  59887. o(e.children[g * c + f], t + 1, p + f, d + g, a, s, l, h);
  59888. l === TileTree.TraversalType.PostOrder && (a && a(e, t, u, i, r),
  59889. s && s.push(e));
  59890. }
  59891. }
  59892. }
  59893. function Plant(seed) {
  59894. seed.root = Branch(seed, null, 0);
  59895. }
  59896. function Branch(seed, parent, level) {
  59897. if (level > seed.levels)
  59898. return null;
  59899. var node = new Node$1(seed, parent);
  59900. seed.allNodes.push(node);
  59901. for (var o = 0; o < h$1; o++)
  59902. node.children[o] = Branch(seed, node, level + 1);
  59903. return node
  59904. }
  59905. function l(parent, t, level, n, r) {
  59906. if (!parent)
  59907. return null;
  59908. if (0 === level)
  59909. return parent;
  59910. if (!parent.children || 0 === parent.children.length)
  59911. return null;
  59912. var o = Math.pow(c, level),
  59913. a = o / c,
  59914. s = n % a,
  59915. h = r % a,
  59916. u = Math.floor(r / a),
  59917. d = Math.floor(n / a),
  59918. p = u * c + d,
  59919. f = parent.children[p];
  59920. return l(f, t + 1, level - 1, s, h)
  59921. }
  59922. /* cube每个面都有一个分层树 用于代表瓦片图的细分?
  59923. 树4096的分为三层,每层有4个子节点。(最后一层的四个子节点都是null)
  59924. */
  59925. var c = 2,
  59926. h$1 = c * c; //4个子节点
  59927. var u$1 = 0;
  59928. class TileTree {
  59929. constructor(e, t) {
  59930. this.levels = t,
  59931. this.tileSize = e,
  59932. this.root = null,
  59933. this.allNodes = [],
  59934. Plant(this);
  59935. }
  59936. getSubNode(e, t, i) {
  59937. (!t || e < this.tileSize) && (t = 0),
  59938. (!i || e < this.tileSize) && (i = 0),
  59939. e < this.tileSize && (e = this.tileSize);
  59940. var level = TileTree.getLevelCountForSize(this.tileSize, e),
  59941. o = l(this.root, 0, level, t, i);
  59942. return o
  59943. }
  59944. breadthFirst(e) {//广度优先搜索
  59945. e = e || {};
  59946. var t = !!e.nullLevelEnd,
  59947. i = e.maxLevel,
  59948. n = e.minLevel,
  59949. r = e.callback,
  59950. o = e.saveVisited,
  59951. a = [],
  59952. s = {},
  59953. l = 0,
  59954. c = 0;
  59955. for (a.push(this.root),
  59956. a.push(s); a.length > 0 && !(i && l > i);) {
  59957. var h = a.shift();
  59958. if (h === s)
  59959. (!n || l >= n) && (r && t && r(null),
  59960. o && t && o.push(null)),
  59961. a.length > 0 && a.push(s),
  59962. l++,
  59963. c = 0;
  59964. else {
  59965. if (h.children)
  59966. for (var u = 0; u < h.children.length; u++) {
  59967. var d = h.children[u];
  59968. d && a.push(h.children[u]);
  59969. }
  59970. var p = this.getFaceIndexFromNode(h);
  59971. (!n || l >= n) && (r && r(h, l, p),
  59972. o && o.push(h)),
  59973. c++;
  59974. }
  59975. }
  59976. }
  59977. getFaceIndexFromNode(e) {
  59978. if (!e)
  59979. return -1;
  59980. for (var t = 1, i = e, n = 0, r = 0;;) {
  59981. var o = i.parent;
  59982. if (!o)
  59983. break;
  59984. for (var a = -1, s = 0; s < o.children.length; s++)
  59985. o.children[s] === i && (a = s);
  59986. var l = a % c,
  59987. h = Math.floor(a / c);
  59988. n = l * t + n,
  59989. r = h * t + r,
  59990. t *= c,
  59991. i = o;
  59992. }
  59993. return r * t + n
  59994. }
  59995. depthFirst(e, t, i) {
  59996. o(this.root, 0, 0, 0, e, t, i, this.tileSize);
  59997. }
  59998. }
  59999. TileTree.TraversalType = Object.freeze({
  60000. PreOrder: 0,
  60001. PostOrder: 1
  60002. });
  60003. TileTree.getLevelCountForSize = function(tileSize, size) {//512->0 2024->1
  60004. var i = 0;
  60005. for (size < tileSize && (size = tileSize);;) {
  60006. if (size /= c,
  60007. size < tileSize)
  60008. break;
  60009. i++;
  60010. }
  60011. return i
  60012. };
  60013. TileTree.getSizeForLevel = function(e, t) {
  60014. return Math.pow(c, t) * e
  60015. };
  60016. function createDescriptor() {
  60017. var e = {
  60018. renderTarget: null,
  60019. inUse: !1,
  60020. size: -1,
  60021. pano: null
  60022. };
  60023. return e
  60024. }
  60025. function c$1() {
  60026. if (!this.uploadIntervalCancelled) {
  60027. if (this.overlayTilesLoaded || !this.usingTileOverlay) {
  60028. b = !0,
  60029. this.updateUploadQueue(this.maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame),
  60030. this.peekNextFromUploadQueue() ? this.refreshUploadInterval(w) : this.uploadInterval = null;
  60031. } else {
  60032. this.refreshUploadInterval(this.uploadIntervalDelay);
  60033. }
  60034. }
  60035. }
  60036. var b = !1,
  60037. w = config$1.tiling.uploadIntervalDelay,
  60038. _ = config$1.tiling.initialIntervalDelay,
  60039. T = config$1.tiling.maxNonBaseUploadsPerFrame,
  60040. x$1 = config$1.tiling.maxBaseUploadsPerFrame,
  60041. S = {
  60042. Base: 0,
  60043. Remaining: 1
  60044. };/* ,
  60045. M = []; */
  60046. class PanoRenderer extends EventDispatcher{
  60047. constructor(viewer, tileDownloader, qualityManager) {
  60048. super();
  60049. this.tileDirectory = {};
  60050. this.activeRenderTargetDescriptors = {};
  60051. this.activePanos = [];
  60052. this.panoLODDescriptors = {};
  60053. this.panoDescriptors = {};
  60054. this.tileTrees = {};
  60055. this.forceQueue = [];
  60056. this.uploadQueues = {};
  60057. this.uploadInterval = null;
  60058. this.uploadIntervalCancelled = !1;
  60059. this.usingTileOverlay = !1;
  60060. this.overlayTilesLoaded = !1;
  60061. this.overlayTileBase = null;
  60062. this.overlayTilesBasic = {};
  60063. this.overlayTilesEnhanced = {};
  60064. this.zoomRenderTarget = null; //用于缩放的rendertarget
  60065. this.zoomPano = null;
  60066. this.zoomingActive = !1;
  60067. this.zoomPanoId = null;
  60068. this.zoomPanoRenderingDisabled = !1;
  60069. this.direction = [];//new THREE.Vector3;
  60070. this.maxBaseUploadsPerFrame = x$1;
  60071. this.maxNonBaseUploadsPerFrame = T;
  60072. this.M = [];//move M to here 似乎列表里会有两个
  60073. this.viewer = viewer;
  60074. this.tileDownloader = tileDownloader;
  60075. this.qualityManager = qualityManager;
  60076. this.initTime = performance.now();
  60077. this.bindEvents();
  60078. }
  60079. getActivePanoTextures(e) {
  60080. e = e || [];
  60081. for (var t = 0; t < M.length; t++) {
  60082. var i = M[t];
  60083. i.renderTarget && i.renderTarget.texture && e.push(i.renderTarget.texture);
  60084. }
  60085. }
  60086. hasQueuedTiles() {
  60087. var e = this.peekNextFromUploadQueue();
  60088. return null !== e && void 0 !== e
  60089. }
  60090. getActiveRenderTargetDescriptor(e) {
  60091. return this.activeRenderTargetDescriptors[e]
  60092. }
  60093. setActiveRenderTargetDescriptor(e, t) {
  60094. this.activeRenderTargetDescriptors[e] = t;
  60095. }
  60096. bindEvents() {
  60097. this.tileDownloader.addEventListener(TileDownloaderEvents.TileDownloadSuccess, this.onTileDownloaded.bind(this));
  60098. }
  60099. enableUltraHighQualityMode(e) {
  60100. if(config$1.tileClass == "2k"||config$1.tileClass == "1k")return this.enableHighQuality(e)//xzw add 濡傛灉鏈€澶氬彧瑕?k鐨勮瘽
  60101. if (!this.qualityManager.ultraHighQualityModeEnabled()) {
  60102. var t = this.qualityManager.getPanoSize(PanoSizeClass.ULTRAHIGH);
  60103. this.tileDownloader.testDownload(t, TileUtils.TILE_SIZE, function (t) {
  60104. t && (this.qualityManager.enableUltraHighQualityMode(),
  60105. this.setupZoomRenderTarget(),
  60106. e());
  60107. }
  60108. .bind(this));
  60109. }
  60110. }
  60111. activateTiledPano(pano, size, i) {
  60112. i && this.clearAllQueuedUploads();
  60113. for (var n = 0; n < TileUtils.FACES_PER_PANO; n++)
  60114. this.initTileTree(pano.id, n, this.qualityManager.getMaxPossiblePanoSize()); //得到this.tileTrees[pano.id],arr[6]
  60115. this.linkAllTilesAndNodes(pano);
  60116. var r = this.getActiveRenderTargetDescriptor(pano.id),
  60117. l = size;
  60118. l > this.qualityManager.getMaxNavPanoSize() && (l = this.qualityManager.getMaxNavPanoSize());
  60119. if ( !r || l !== r.size) {
  60120. r && this.deactiveDescripor(r.renderTarget);
  60121. r = this.activeDescripor(l);
  60122. if (!r) {
  60123. var ren = this.initTiledPano(l, !1);
  60124. r = this.initDescriptor(ren.width);
  60125. r.renderTarget = ren;
  60126. }
  60127. r.pano = pano;
  60128. this.resetPanoDescriptor(pano.id);
  60129. this.resetPanoLODDescriptors(pano.id);
  60130. this.resetRenderStatus(pano.id, !0, !0);
  60131. }
  60132. this.setActiveRenderTargetDescriptor(pano.id, r);
  60133. var h = i ? 0 : 1;
  60134. this.updateActivePanos(pano, h);
  60135. //console.log(`index:${this.viewer.index} ${r.renderTarget.texture.id} ${pano.id}`)
  60136. return r.renderTarget
  60137. }
  60138. deactivateTiledPano(e) {
  60139. var t = this.getActiveRenderTargetDescriptor(e.id);
  60140. if(this.isRenderTargetDescriptorValid(t)){
  60141. this.deactiveDescripor(t.renderTarget);
  60142. this.setActiveRenderTargetDescriptor(e.id, null);
  60143. }
  60144. var i = this.getUploadQueueForPano(e.id);
  60145. this.clearUploadQueue(i);
  60146. this.updateActivePanos();
  60147. }
  60148. getActivePanoCount() {
  60149. return this.activePanos.length
  60150. }
  60151. resetRenderStatus(e, t, i, n) {
  60152. var r = null;
  60153. n && (r = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, n) + 1);
  60154. for (var o = function (e, n, r, o) {
  60155. i && (n.tile.zoomUploaded = !1),
  60156. t && (n.tile.uploaded = !1);
  60157. }, a = 0; a < TileUtils.FACES_PER_PANO; a++) {
  60158. var s = this.getTileTree(e, a);
  60159. s.breadthFirst({
  60160. callback: o.bind(this, a),
  60161. minLevel: r
  60162. });
  60163. }
  60164. }
  60165. copyBaseRenderStatusToZoomed(e) {
  60166. for (var t = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, this.qualityManager.getMaxNavPanoSize()), i = function (e, t, i, n) {
  60167. t.tile.zoomUploaded = t.tile.uploaded,
  60168. t.zoomCovered = t.covered;
  60169. }, n = 0; n < TileUtils.FACES_PER_PANO; n++) {
  60170. var r = this.getTileTree(e, n);
  60171. r.breadthFirst({
  60172. callback: i.bind(this, n),
  60173. maxLevel: t
  60174. });
  60175. }
  60176. }
  60177. isRenderTargetDescriptorValid(e) {
  60178. return e && e.renderTarget
  60179. }
  60180. isPanoActive(e) {
  60181. var t = this.getActiveRenderTargetDescriptor(e);
  60182. return this.isRenderTargetDescriptorValid(t)
  60183. }
  60184. isPanoZoomed(e) {
  60185. return this.zoomingActive && this.zoomPanoId === e
  60186. }
  60187. initTileTree(e, t, i) {
  60188. var n = this.tileTrees[e];
  60189. n || (n = [],
  60190. this.tileTrees[e] = n);
  60191. var r = n[t];
  60192. if (!r) {
  60193. var o = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, i);
  60194. r = new TileTree(TileUtils.TILE_SIZE, o),
  60195. n[t] = r;
  60196. }
  60197. }
  60198. getTileTree(e, t) {
  60199. var i = this.tileTrees[e];
  60200. if (!i)
  60201. console.error("PanoRenderer.getTileTree() -> Tree array not yet initialized!");
  60202. var n = i[t];
  60203. if (!n)
  60204. console.error("PanoRenderer.getTileTree() -> Tree not yet initialized!");
  60205. return n
  60206. }
  60207. /*
  60208. * 创建tile的renderTarget, 包括pano.tiledPanoRenderTarget和zoomRenderTarget
  60209. * @param {number} size 当前的panoSize,每个面的分辨率
  60210. */
  60211. initTiledPano(size, t) {//创建 RenderTargetCube
  60212. var renderer = this.viewer.renderer;
  60213. var renderTarget, texture;
  60214. renderTarget = new WebGLCubeRenderTarget(size,{ //THREE.WebGLRenderTargetCube(size, size, {
  60215. stencilBuffer: !1
  60216. });
  60217. texture = new CubeTexture([]);
  60218. texture.image = [null, null, null, null, null, null];
  60219. texture.flipY = !0,
  60220. texture.format = RGBAFormat;
  60221. t ? (texture.generateMipmaps = !0,
  60222. texture.magFilter = LinearFilter,
  60223. texture.minFilter = LinearMipMapLinearFilter)
  60224. : (texture.generateMipmaps = !1,
  60225. texture.magFilter = LinearFilter,
  60226. texture.minFilter = LinearFilter);
  60227. renderer.setRenderTarget(renderTarget);
  60228. renderer.setRenderTarget(null);
  60229. var o = renderer.properties.get(texture);
  60230. o.__image__webglTextureCube = o.__webglTexture;
  60231. //window.tex[r.id] = {texture:r, index:this.viewer.index }
  60232. return renderTarget
  60233. }
  60234. getUploadQueueForPano(e) {
  60235. var t = this.uploadQueues[e];
  60236. return t || (t = [],
  60237. this.uploadQueues[e] = t),
  60238. t
  60239. }
  60240. isTileUploaded(e) {
  60241. return this.isPanoZoomed(e.panoId) ? e.zoomUploaded : e.uploaded
  60242. }
  60243. setUploaded(e, t) {
  60244. this.isPanoZoomed(e.panoId) ? e.zoomUploaded = t : e.uploaded = t;
  60245. }
  60246. queueTileUpload(e, t, i) {
  60247. var n = this.getActiveRenderTargetDescriptor(e.panoId);
  60248. if (this.isRenderTargetDescriptorValid(n) && e.downloaded && !this.isTileUploaded(e) && (!e.uploadQueued || i)
  60249. && (!(e.panoSize > this.qualityManager.getMaxNavPanoSize())|| this.zoomingActive)) {
  60250. var r = this.getUploadQueueForPano(e.panoId);
  60251. if(i){
  60252. this.uploadTile(e, !1);//提交
  60253. }else {
  60254. if(this.shoulPushToFrontOfQueue(e)){//如果是512的优先
  60255. this.forceQueue.push(e);
  60256. }else {
  60257. if(t && this.direction){
  60258. TilePrioritizer.insertSortedPanoTile(r, e, n.pano, this.direction);
  60259. }else r.push(e);
  60260. }
  60261. e.uploadQueued = !0;
  60262. this.uploadInterval || this.uploadIntervalCancelled || this.refreshUploadInterval(0);
  60263. }
  60264. }
  60265. }
  60266. shoulPushToFrontOfQueue(e) {
  60267. return 0 === TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, e.panoSize)
  60268. }
  60269. getTopUploadQueue() {
  60270. for (var e = null, t = null, i = S.Base; i <= S.Remaining; i++)
  60271. for (var n = 0; n < this.activePanos.length; n++)
  60272. if (e = this.activePanos[n],
  60273. t = this.getUploadQueueForPano(e.id),
  60274. t.length > 0)
  60275. switch (i) {
  60276. case S.Base:
  60277. if (0 === t[0].level)
  60278. return t;
  60279. break;
  60280. case S.Remaining:
  60281. return t
  60282. }
  60283. return null
  60284. }
  60285. peekNextFromUploadQueue() {
  60286. if (this.forceQueue.length > 0)
  60287. return this.forceQueue[0];
  60288. var e = this.getTopUploadQueue();
  60289. return e && e.length > 0 ? e[0] : null
  60290. }
  60291. clearAllQueuedUploads() {
  60292. this.clearAllUploadQueues(null, 0);
  60293. }
  60294. clearAllQueuedUploadsForPano(e) {
  60295. this.clearAllUploadQueues(e, 0);
  60296. }
  60297. clearAllUploadQueues(e, t) {
  60298. if (e)
  60299. this.clearUploadQueue(this.getUploadQueueForPano(e), t),
  60300. this.clearUploadQueue(this.forceQueue, t, e);
  60301. else {
  60302. for (var i = 0; i < this.activePanos.length; i++) {
  60303. var n = this.activePanos[i];
  60304. this.clearUploadQueue(this.getUploadQueueForPano(n.id), t);
  60305. }
  60306. this.clearUploadQueue(this.forceQueue, t);
  60307. }
  60308. }
  60309. clearUploadQueue(e, t, i) {
  60310. void 0 !== t && null !== t || (t = 0);
  60311. for (var n = 0; n < e.length;) {
  60312. var r = e[n];
  60313. (!i || i && i === r.tile.panoId) && r.level >= t ? (r.uploadQueued = !1,
  60314. e.splice(n, 1)) : n++;
  60315. }
  60316. //若报错, r.tile.panoId改为 r.panoId
  60317. }
  60318. updateUploadQueue(maxNPF,maxPF/* e, t */) {//参数是 maxNonBaseUploadsPerFrame and maxBaseUploadsPerFrame, 优先上传512
  60319. maxNPF || (maxNPF = 1);
  60320. for (var i = 0, n = 0;;) {
  60321. let old = this.forceQueue.slice(0);
  60322. if (n >= maxPF || i >= maxNPF)
  60323. break;
  60324. var r = this.getNextFromUploadQueue();
  60325. if (!r)
  60326. break;
  60327. //r.panoSize <2048 && console.log('panoId', r.panoId, 'panoSize', r.panoSize , old)
  60328. 0 !== r.level ? i++ : n++;
  60329. if (!(r.panoSize > this.qualityManager.getMaxNavPanoSize()) || this.zoomingActive) {
  60330. var o = this.getActiveRenderTargetDescriptor(r.panoId);
  60331. this.isRenderTargetDescriptorValid(o) && this.uploadTile(r, r.forceUpload);
  60332. }
  60333. }
  60334. }
  60335. updateDirection(e) {
  60336. if (e = e || this.direction) {
  60337. this.direction = e;
  60338. for (var t = 0; t < this.activePanos.length; t++) {
  60339. var i = this.activePanos[t],
  60340. n = this.getUploadQueueForPano(i.id);
  60341. TilePrioritizer.sortPanoTiles(n, i, this.direction);
  60342. }
  60343. }
  60344. }
  60345. anyUploaded(e) {
  60346. if (!e)
  60347. return !1;
  60348. if (e.tile && this.isTileUploaded(e.tile))
  60349. return !0;
  60350. if (e.children)
  60351. for (var t = 0; t < e.children.length; t++) {
  60352. var i = e.children[t];
  60353. if (this.anyUploaded(i))
  60354. return !0
  60355. }
  60356. return !1
  60357. }
  60358. setNodeCovered(e, t) {
  60359. this.isPanoZoomed(e.tile.panoId) ? e.zoomCovered = t : e.covered = t;
  60360. }
  60361. isNodeCovered(e) {
  60362. return !!e && (this.isPanoZoomed(e.tile.panoId) ? e.zoomCovered : e.covered)
  60363. }
  60364. addCoverageForNode(e) {
  60365. if (this.setNodeCovered(e, !0),
  60366. e.parent && e.covered) {
  60367. var t = e.parent;
  60368. this.nodeSubcovered(t) && this.addCoverageForNode(t, !0);
  60369. }
  60370. }
  60371. calcFullCoverage(e) {
  60372. var t = !1;
  60373. if (e.children)
  60374. for (var i = 0; i < e.children.length; i++) {
  60375. var n = e.children[i];
  60376. t = t || this.calcFullCoverage(n);
  60377. }
  60378. e.covered = e.tile.uploaded || t;
  60379. }
  60380. nodeSubcovered(e) {
  60381. if (!e.children)
  60382. return !1;
  60383. for (var t = 0; t < e.children.length; t++)
  60384. if (!e.children[t] || !this.isNodeCovered(e.children[t]))
  60385. return !1;
  60386. return !0
  60387. }
  60388. resetPanoDescriptor(e) {
  60389. this.getPanoDescriptor(e);
  60390. }
  60391. getPanoDescriptor(e) {
  60392. var t = this.panoDescriptors[e];
  60393. return t || (t = {},
  60394. this.panoDescriptors[e] = t),
  60395. t
  60396. }
  60397. resetPanoLODDescriptors(e) {
  60398. var t = this.getPanoLODDescriptors(e);
  60399. for (var i in t)
  60400. if (t.hasOwnProperty(i)) {
  60401. var n = t[i];
  60402. n.uploadCount = 0,
  60403. n.uploadAttempts = 0;
  60404. n.uploaded = [];
  60405. }
  60406. }
  60407. getPanoLODDescriptor(e, t) {
  60408. var i = this.getPanoLODDescriptors(e),
  60409. n = i[t];
  60410. return n || (n = {
  60411. uploadCount: 0,
  60412. uploadAttempts: 0,
  60413. uploaded:[],//add
  60414. },
  60415. i[t] = n),
  60416. n
  60417. }
  60418. getPanoLODDescriptors(e) {
  60419. var t = this.panoLODDescriptors[e];
  60420. return t || (t = {},
  60421. this.panoLODDescriptors[e] = t),
  60422. t
  60423. }
  60424. onTileDownloaded(o) {
  60425. var e = o.desc;
  60426. var t = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, e.panoSize),
  60427. i = this.getTileDirectoryEntry(e.panoId, e.face, t, e.faceTileIndex);
  60428. i.downloaded = !0;
  60429. i.image = e.image;
  60430. i.panoSize = e.panoSize;
  60431. i.tileX = e.tileX;
  60432. i.tileY = e.tileY;
  60433. i.totalTiles = e.totalTiles;
  60434. i.tileIndex = e.tileIndex;
  60435. i.faceTileIndex = e.faceTileIndex;
  60436. i.face = e.face;
  60437. i.cubeFace = TileUtils.mapFaceToCubemapFace(e.face);
  60438. i.panoId = e.panoId;
  60439. i.tileSize = e.tileSize;
  60440. i.direction = (new Vector3).copy(e.direction);
  60441. i.node = null;
  60442. i.level = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, i.panoSize);
  60443. if (this.isPanoActive(i.panoId)) {
  60444. var n = this.getTileTree(i.panoId, i.face);
  60445. var r = n.getSubNode(i.panoSize, i.tileX, i.tileY);
  60446. this.linkTileAndNode(i, r);
  60447. this.queueTileUpload(i, !0);
  60448. }
  60449. }
  60450. getTileDirectoryEntry(panoId, t, i, n) {
  60451. var r = this.tileDirectory[panoId];
  60452. r || (r = {}, this.tileDirectory[panoId] = r);
  60453. var o = 16384 * t + 1024 * i + n, //t:4096级别
  60454. a = r[o];
  60455. return a || (a = {
  60456. downloaded: !1,
  60457. uploaded: !1,
  60458. zoomUploaded: !1
  60459. },
  60460. r[o] = a),
  60461. a._key = panoId + ":" + t + ":" + i + ":" + n,//panoId : face : level : faceTileIndex
  60462. a._tileKey = o,
  60463. a
  60464. }
  60465. setZoomingActive(active, pano, i) {//设置当前正在zoom的pano
  60466. this.zoomPanoRenderingDisabled || active === this.zoomingActive && this.zoomPanoId === pano.id || (this.zoomingActive = active,
  60467. this.zoomPanoId = pano.id,
  60468. this.zoomingActive && (this.zoomPanoId !== pano.id || i) && this.updateZoomedPanoFromBase(pano));
  60469. }
  60470. updateZoomedPanoFromBase(pano) {//因更换pano所以将pano的rendertarget渲染到panoRenderer的zoomRenderTarget上
  60471. if (!this.zoomPanoRenderingDisabled && this.zoomRenderTarget) {
  60472. var t = this.getActiveRenderTargetDescriptor(pano.id);
  60473. if (t && t.renderTarget ) {
  60474. var i = Math.min(this.qualityManager.maxRenderTargetSize, this.qualityManager.getMaxZoomPanoSize()), //change
  60475. n = t.renderTarget,
  60476. r = t.size;
  60477. this.copyCubeMap(n.texture, this.zoomRenderTarget, r, r, i, i),
  60478. this.copyBaseRenderStatusToZoomed(pano.id);
  60479. }
  60480. }
  60481. }
  60482. add(e) {
  60483. this.M.push(e);
  60484. }
  60485. initDescriptor(size) {
  60486. var t = createDescriptor();
  60487. t.inUse = !0;
  60488. t.size = size;
  60489. this.add(t);
  60490. return t
  60491. }
  60492. activeDescripor(e) {
  60493. for (var t = 0; t < this.M.length; t++) {
  60494. var i = this.M[t];
  60495. if (!i.inUse && i.size === e){
  60496. i.inUse = !0;
  60497. return i
  60498. }
  60499. }
  60500. return null
  60501. }
  60502. deactiveDescripor(e) {
  60503. for (var t = 0; t < this.M.length; t++) {
  60504. var i = this.M[t];
  60505. if (i.renderTarget === e){
  60506. i.inUse = !1;
  60507. return !0
  60508. }
  60509. }
  60510. return !1
  60511. }
  60512. enableHighQuality(e){//xzw add 如果最多只要2k图的话enableUltraHighQualityMode替换成这个
  60513. if (!this.qualityManager.highQualityModeStarted) {
  60514. this.setupZoomRenderTarget();
  60515. e();
  60516. //this.qualityManager.updateHighResolutionSettings(e)////////?
  60517. this.qualityManager.highQualityModeStarted = true;
  60518. }
  60519. }
  60520. linkTileAndNode(e, t) {
  60521. t.tile = e,
  60522. e.node = t;
  60523. }
  60524. linkAllTilesAndNodes(e) {
  60525. var t = function (t, i, n, r, o) {
  60526. var a = this.getTileDirectoryEntry(e.id, i, r, o);
  60527. this.linkTileAndNode(a, n);
  60528. };
  60529. for (var i = 0; i < TileUtils.FACES_PER_PANO; i++) {
  60530. var n = this.getTileTree(e.id, i);
  60531. n.breadthFirst({
  60532. callback: t.bind(this, n, i)
  60533. });
  60534. }
  60535. }
  60536. //--------------sceneRenderer
  60537. initSizedTexture2D(e, t, i) {
  60538. var renderer = this.viewer.renderer,
  60539. o = renderer.getContext(),
  60540. a = renderer.state,
  60541. s = new Texture(null);
  60542. s.flipY = !1,
  60543. i !== !0 && (i = !1),
  60544. s.generateMipmaps = i;
  60545. var l = renderer.paramThreeToGL(s.format),
  60546. c = renderer.paramThreeToGL(s.type),
  60547. h = renderer.properties.get(s),
  60548. u = o.createTexture();
  60549. a.bindTexture(o.TEXTURE_2D, u),
  60550. o.pixelStorei(o.UNPACK_FLIP_Y_WEBGL, s.flipY),
  60551. o.texImage2D(o.TEXTURE_2D, 0, l, e, e, 0, l, c, null),
  60552. s.wrapS = t,
  60553. s.wrapT = t;
  60554. var d = renderer.paramThreeToGL(t);
  60555. return o.texParameteri(o.TEXTURE_2D, o.TEXTURE_WRAP_S, d),
  60556. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_WRAP_T, d),
  60557. i ? (s.magFilter = LinearFilter,
  60558. s.minFilter = LinearMipMapLinearFilter,
  60559. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MAG_FILTER, o.LINEAR),
  60560. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MIN_FILTER, o.LINEAR_MIPMAP_NEAREST),
  60561. o.generateMipmap(o.TEXTURE_2D)) : (s.magFilter = LinearFilter,
  60562. s.minFilter = LinearFilter,
  60563. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MAG_FILTER, o.LINEAR),
  60564. o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MIN_FILTER, o.LINEAR)),
  60565. a.bindTexture(o.TEXTURE_2D, null),
  60566. h.__webglTexture = u,
  60567. s
  60568. }
  60569. deallocateCubeTexture(e) {
  60570. var t = this.viewer.renderer,
  60571. i = t.getContext(),
  60572. renderer = t.properties.get(e);
  60573. i.deleteTexture(renderer.__image__webglTextureCube);
  60574. }
  60575. uploadTexture2D(img, tex, startX, startY, width, height) {
  60576. var renderer = this.viewer.renderer,
  60577. gl = renderer.getContext(),
  60578. webglState = renderer.state,
  60579. c = renderer.properties.get(tex);
  60580. webglState.bindTexture(gl.TEXTURE_2D, c.__webglTexture),
  60581. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, tex.flipY),
  60582. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, tex.premultiplyAlpha),
  60583. gl.pixelStorei(gl.UNPACK_ALIGNMENT, tex.unpackAlignment),
  60584. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, renderer.paramThreeToGL(tex.wrapS)),
  60585. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, renderer.paramThreeToGL(tex.wrapT)),
  60586. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, renderer.paramThreeToGL(tex.magFilter)),
  60587. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, renderer.paramThreeToGL(tex.minFilter)),
  60588. gl.texSubImage2D(gl.TEXTURE_2D, 0, startX, startY, gl.RGBA, gl.UNSIGNED_BYTE, img),
  60589. tex.generateMipmaps && gl.generateMipmap(gl.TEXTURE_2D),
  60590. webglState.bindTexture(gl.TEXTURE_2D, null);
  60591. }
  60592. getCubeOrientationForCubeFace(e, t) {
  60593. switch (e) {
  60594. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  60595. t.set(0, -Math.PI / 2, 0);
  60596. break;
  60597. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  60598. t.set(0, Math.PI / 2, 0);
  60599. break;
  60600. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
  60601. t.set(Math.PI / 2, Math.PI, 0);
  60602. break;
  60603. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  60604. t.set(-Math.PI / 2, Math.PI, 0);
  60605. break;
  60606. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  60607. t.set(0, -Math.PI, 0);
  60608. break;
  60609. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  60610. t.set(0, 0, 0);
  60611. }
  60612. }
  60613. }
  60614. PanoRenderer.prototype.setupZoomRenderTarget = function(){
  60615. var targets = {};
  60616. return function(){
  60617. if(this.qualityManager.maxRenderTargetSize == '2k' && this.qualityManager.getMaxNavPanoSize()=='2k')return; //不使用zoomTarget 直接用pano的tiledPanoRenderTarget,防崩溃
  60618. if (this.qualityManager.getMaxZoomPanoSize() >= this.qualityManager.getMaxNavPanoSize() /* && (config.tileClass != "2k" ||config.tileClass != "1k") */) {
  60619. //部分手机2k时copyCubeMap会重载 , 所以如果没有超出当前分辨率,就不使用zoomRenderTarget。但在微信依旧会重载,只是优化了些,safari几乎不会。
  60620. if (this.zoomRenderTarget && this.zoomRenderTarget.width === this.qualityManager.getMaxZoomPanoSize())
  60621. return;
  60622. var e = this.zoomRenderTarget;
  60623. var size = this.qualityManager.getMaxZoomPanoSize();
  60624. if(size > this.qualityManager.maxRenderTargetSize){
  60625. return
  60626. }
  60627. if(targets[size]){
  60628. this.zoomRenderTarget = targets[size];
  60629. }else {
  60630. this.zoomRenderTarget = this.initTiledPano(size, !1);
  60631. targets[size] = this.zoomRenderTarget;
  60632. }
  60633. if (e) {//将旧的zoomRenderTarget渲染到新zoomRenderTarget上
  60634. var t = e.width,
  60635. i = this.zoomRenderTarget.width;
  60636. this.copyCubeMap(e.texture, this.zoomRenderTarget, t, t, i, i),
  60637. e.texture.dispose(),
  60638. e.texture.loaded = !1,
  60639. e.texture.version = 0,
  60640. this.deallocateCubeTexture(e.texture),
  60641. e.texture = null;
  60642. }
  60643. this.zoomPanoRenderingDisabled = !1;
  60644. } else
  60645. this.zoomPanoRenderingDisabled = !0;
  60646. }
  60647. }();
  60648. PanoRenderer.prototype.updateActivePanos = function () {
  60649. var e = [];
  60650. return function (t, i) {
  60651. e.length = 0;
  60652. for (var n = 0; n < this.activePanos.length; n++) {
  60653. t && e.length === i && e.push(t);
  60654. var r = this.activePanos[n],
  60655. o = this.getActiveRenderTargetDescriptor(r.id);
  60656. t && r.id === t.id || !this.isRenderTargetDescriptorValid(o) || e.push(r);
  60657. }
  60658. t && i >= e.length && e.push(t),
  60659. this.activePanos.length = 0,
  60660. this.activePanos.push.apply(this.activePanos, e);
  60661. }
  60662. }();
  60663. PanoRenderer.prototype.renderPanoTiles = function () {
  60664. var e = [];
  60665. return function (panoId, i, n, r) {
  60666. this.zoomRenderTarget && this.zoomRenderTarget.width === this.qualityManager.getMaxZoomPanoSize() || this.zoomPanoRenderingDisabled || this.setupZoomRenderTarget(),//如果ZoomRenderTarget大小需要变动就重新创建
  60667. i = i || this.direction || Vectors.FORWARD; // [{1:Vectors.FORWARD}]?
  60668. var o = this.getActiveRenderTargetDescriptor(panoId);
  60669. if (!this.isRenderTargetDescriptorValid(o))
  60670. console.error("PanoRenderer.renderPanoTiles() -> Cannot render to a pano that is not activated.");
  60671. for (var a = 0; a < TileUtils.FACES_PER_PANO; a++) {
  60672. var s = this.getTileTree(panoId, a);
  60673. e.length = 0;
  60674. s.breadthFirst({//获取所有node? 85个
  60675. saveVisited: e
  60676. });
  60677. for (var l = 0; l < e.length; l++) {
  60678. var c = e[l];
  60679. this.queueTileUpload(c.tile, !1, r || 0 === l && n);//为什么第0个会直接uploadTile??
  60680. }
  60681. }
  60682. this.updateDirection(i);
  60683. }
  60684. }();
  60685. PanoRenderer.prototype.getNextFromUploadQueue = function () {
  60686. var e = function (e) {
  60687. var t = e.shift();
  60688. return t.uploadQueued = !1,
  60689. t
  60690. };
  60691. return function () {
  60692. if (this.forceQueue.length > 0)
  60693. return e(this.forceQueue);
  60694. var t = this.getTopUploadQueue();
  60695. return t && t.length > 0 ? e(t) : null
  60696. }
  60697. }();
  60698. PanoRenderer.prototype.refreshUploadInterval = function () {
  60699. var e = null;
  60700. return function (t) {
  60701. this.uploadIntervalCancelled || (e || (e = c$1.bind(this)),
  60702. null !== t && void 0 !== t || (t = w),
  60703. b || (t = _),
  60704. this.uploadInterval = window.setTimeout(e, t),
  60705. this.uploadIntervalDelay = t);
  60706. }
  60707. }();
  60708. PanoRenderer.prototype.update = function () {
  60709. var e = performance.now(),
  60710. t = 0;
  60711. return function () {
  60712. this.uploadIntervalCancelled = !0;
  60713. window.clearTimeout(this.uploadInterval);
  60714. this.uploadInterval = null;
  60715. var i = performance.now() - e;
  60716. //!(i > w || 0 === t) || !this.overlayTilesLoaded && this.usingTileOverlay || (this.updateUploadQueue(this.maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame),
  60717. //e = performance.now()),
  60718. if (!(i > w || 0 === t) || !this.overlayTilesLoaded && this.usingTileOverlay) {} else {
  60719. this.updateUploadQueue(this.maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame);
  60720. e = performance.now();
  60721. }
  60722. t++;
  60723. }
  60724. }();
  60725. PanoRenderer.prototype.uploadTile = function () {//重写
  60726. var collection = {},
  60727. overlayStyle = config$1.tiling.overlayStyle;
  60728. var failHistory = {};
  60729. return function (info, n) {
  60730. var id = info.panoId,
  60731. img = info.image,
  60732. tileSize = info.tileSize,
  60733. panoSize = info.panoSize,
  60734. tileIndex = info.tileIndex,
  60735. totalTiles = info.totalTiles,
  60736. tileX = info.tileX,
  60737. tileY = info.tileY,
  60738. p = !0,
  60739. g = !1,
  60740. ignore = false, //add
  60741. LodDescripor = (this.getPanoDescriptor(id), this.getPanoLODDescriptor(id, panoSize)),
  60742. activeDescripor = this.getActiveRenderTargetDescriptor(id),
  60743. renderTarget = activeDescripor.renderTarget,
  60744. size = activeDescripor.size;//当前要渲染的面的分辨率,也就是MaxNavPanoSize
  60745. if (this.isPanoZoomed(id) && this.zoomRenderTarget) {
  60746. renderTarget = this.zoomRenderTarget;
  60747. size = this.zoomRenderTarget.width; //this.qualityManager.getMaxZoomPanoSize(); //放大后可能2048或4096
  60748. }
  60749. let done = ()=>{
  60750. if(!LodDescripor.uploaded.includes(tileIndex)){//已经upload过(本来这时候直接返回,但发现缩放后这不会归零,导致清晰度不更新,所以还是redraw且emit吧)
  60751. //console.log('try to reupload and return',tileIndex)
  60752. LodDescripor.uploaded.push(tileIndex);
  60753. LodDescripor.uploadCount++;
  60754. }
  60755. this.dispatchEvent({type:PanoRendererEvents.TileRenderSuccess, id, panoSize, tileIndex, totalTiles});
  60756. LodDescripor.uploadCount === totalTiles && this.dispatchEvent({type:PanoRendererEvents.PanoRenderComplete, id, panoSize, totalTiles, updateFullComplete:true});
  60757. this.setUploaded(info, !0);
  60758. this.addCoverageForNode(info.node);
  60759. };
  60760. {//已经uploadTile过了不再uploadTile
  60761. if(!this.isRenderTargetDescriptorValid(activeDescripor)){
  60762. p = !1; g = !1;
  60763. }
  60764. if(!n){
  60765. this.anyUploaded(info.node) && (p = !1, g = !0,ignore = true ); //包括子集也uploadTile了
  60766. this.isTileUploaded(info) && (p = !1, g = !1,ignore = true ); //当前tile uploadTile了
  60767. }
  60768. }
  60769. if (p) {
  60770. /*if(failHistory[id+':'+ panoSize+ ':' +tileIndex]){
  60771. console.log('uploadTile retry',id, panoSize, tileIndex)
  60772. }
  60773. console.log('uploadTile 成功', id, panoSize, tileIndex) */
  60774. var C = tileX * tileSize,
  60775. I = tileY * tileSize,
  60776. E = tileSize / panoSize * size, // tile在renderTarget上渲染出的宽度
  60777. b = C / panoSize * size, // tile在renderTarget上渲染的startX
  60778. w = I / panoSize * size; // tile在renderTarget上渲染的startY
  60779. collection[tileSize] || (collection[tileSize] = this.initSizedTexture2D(tileSize, ClampToEdgeWrapping));
  60780. if(panoSize > this.qualityManager.maxRenderTargetSize ){ //4096 改
  60781. var tex = this.initSizedTexture2D(tileSize, ClampToEdgeWrapping);
  60782. var loaded = this.viewer.images360.isHighMapLoaded(info.cubeFace, tileX,tileY);
  60783. }else {
  60784. var tex = collection[tileSize];
  60785. }
  60786. this.uploadTexture2D(img, tex, 0, 0, tileSize, tileSize);//只替换tex对应的img,不新建
  60787. if(panoSize > this.qualityManager.maxRenderTargetSize){
  60788. loaded || this.viewer.images360.updateHighMap(tex, info.cubeFace, tileX,tileY);
  60789. }else {
  60790. if (1 === overlayStyle || 2 === overlayStyle) {
  60791. var T = 1 === overlayStyle ? this.overlayTilesBasic : this.overlayTilesEnhanced;
  60792. this.renderToCubeMap(tex, renderTarget, tileSize, tileSize, 0, 0, tileSize, tileSize, b, w, E, E, info.cubeFace);
  60793. this.renderToCubeMap(T[panoSize], renderTarget, tileSize, tileSize, 0, 0, tileSize, tileSize, b, w, E, E, info.cubeFace, NormalBlending, !0, .5);
  60794. } else {
  60795. this.renderToCubeMap(tex, renderTarget, tileSize, tileSize, 0, 0, tileSize, tileSize, b, w, E, E, info.cubeFace);
  60796. }
  60797. }
  60798. done();
  60799. }else if(ignore){
  60800. //console.log('finish because anyUploaded',id,panoSize,tileIndex)
  60801. done(); //改: 如果因为这部分更高清的贴图已加载所以才不绘制的话,直接完成
  60802. }else {
  60803. //console.log('uploadTile 失败', id, panoSize, tileIndex)
  60804. if(panoSize == 512){
  60805. //console.log("!!!!!!!!!!!!!")
  60806. }
  60807. failHistory[id+':'+ panoSize+ ':' +tileIndex] = true;
  60808. this.setUploaded(info, !1);
  60809. }
  60810. info.uploadAttempted || (LodDescripor.uploadAttempts++, this.dispatchEvent({type:PanoRendererEvents.TileUploadAttempted, id, panoSize, tileIndex, totalTiles})),
  60811. info.uploadAttempted = !0;
  60812. LodDescripor.uploadAttempts === totalTiles && this.dispatchEvent({type:PanoRendererEvents.UploadAttemptedForAllTiles, id, panoSize, totalTiles});
  60813. return g;
  60814. }
  60815. }();
  60816. /*
  60817. 注:tileY的方向同UV,从下到上
  60818. renderToCubeMap里的画布or镜头的xy范围是-0.5到0.5
  60819. */
  60820. PanoRenderer.prototype.renderToCubeMap = function() {
  60821. var inited = !1,
  60822. scene = null,
  60823. camera = null,
  60824. material = null,
  60825. geo = null,
  60826. plane = null,
  60827. l = 1;
  60828. return function(texture, renderTarget, tileWidth, tileHeight, startXinTile, startYinTile, widthinTile, heightinTile, startX, startY, width, height, cubeFace, E, b, w) {
  60829. var renderer = this.viewer.renderer;
  60830. inited || (camera = new OrthographicCamera(l / -2, l / 2, l / 2, l / -2, -200, 200),
  60831. camera.position.z = 150,
  60832. scene = new Scene,
  60833. scene.add(camera),
  60834. material = new ShaderMaterial({
  60835. uniforms: {
  60836. tDiffuse: {
  60837. type: "scene",
  60838. value: null
  60839. },
  60840. alpha: {
  60841. type: "startYinTile",
  60842. value: 1
  60843. }
  60844. },
  60845. vertexShader: Shaders['basicTextured.vs'],
  60846. fragmentShader: Shaders['basicTextured.fs'],
  60847. depthWrite: !1,
  60848. depthTest: !1,
  60849. side: DoubleSide
  60850. }),
  60851. geo = new PlaneBufferGeometry(l, l),
  60852. plane = new Mesh(geo, material),
  60853. plane.position.z = 0,
  60854. scene.add(plane),
  60855. inited = !0);
  60856. var uv = geo.getAttribute("uv");
  60857. uv.setDynamic(!0), //setUsage
  60858. uv.needsUpdate = !0;
  60859. var uvArr = uv.array,
  60860. S = startXinTile / tileWidth, //uv这几个值基本是固定的startXinTile:0,startYinTile:0,widthinTile:512,widthinTile:512,tileWidth:512,tileHeight:512 也就是说uv不会变、每张tile的有效范围是100%
  60861. M = startYinTile / tileHeight,
  60862. R = widthinTile / tileWidth,
  60863. P = heightinTile / tileHeight;
  60864. uvArr[0] = S,
  60865. uvArr[1] = M + P,
  60866. uvArr[2] = S + R,
  60867. uvArr[3] = M + P,
  60868. uvArr[4] = S,
  60869. uvArr[5] = M,
  60870. uvArr[6] = S + R,
  60871. uvArr[7] = M;
  60872. //修改posistion,使该plane只占据需要绘制的部分。类似拼图。
  60873. //startX startY width height 都是在画布上的大小,比如画布大小为2048*2048,此tile为16分之一,tileX是1,tileY是1,则startX=2048/4,startY=2048/4
  60874. var pos = geo.getAttribute("position");
  60875. pos.setDynamic(!0),
  60876. pos.needsUpdate = !0;
  60877. var posArr = pos.array,
  60878. D = startX / renderTarget.width - l / 2 // 起始x
  60879. ,
  60880. N = startY / renderTarget.height - l / 2 // 起始y
  60881. ,
  60882. B = width / renderTarget.width // 宽
  60883. ,
  60884. F = height / renderTarget.height; // 高
  60885. posArr[0] = D,
  60886. posArr[1] = N + F,
  60887. posArr[3] = D + B,
  60888. posArr[4] = N + F,
  60889. posArr[6] = D,
  60890. posArr[7] = N,
  60891. posArr[9] = D + B,
  60892. posArr[10] = N;
  60893. renderer.properties.get(scene);
  60894. material.uniforms.tDiffuse.value = texture;
  60895. material.blending = E || NoBlending,
  60896. material.transparent = !!b;
  60897. void 0 !== w && null !== w || (w = 1),
  60898. material.uniforms.alpha.value = w,
  60899. material.needUpdate = !0;
  60900. //renderTarget.activeCubeFace = cubeFace, //0-5 应该是指定渲染h中的面 失效
  60901. /* renderer.setScissorTest(!0)
  60902. //指定绘制区域,类似遮罩(相对于屏幕)
  60903. renderer.setScissor(startX,startY,width,height) //加上这个会不会快一些,尤其是spherical
  60904. //指定绘制视口位置和大小(相对于屏幕)
  60905. */
  60906. renderTarget.viewport.set(0, 0, renderTarget.width, renderTarget.height);
  60907. var V = renderer.autoClear;
  60908. var oldTarget = renderer.getRenderTarget();
  60909. renderer.autoClear = !1;
  60910. renderer.setRenderTarget(renderTarget, cubeFace);
  60911. renderer.render(scene, camera/* , renderTarget, !1 */);
  60912. renderer.setRenderTarget(oldTarget);
  60913. renderer.autoClear = V;
  60914. //renderer.setScissorTest(!1)
  60915. /* this.renderer.render(scene, camera, this.planeTargets[cubeFace], !1),//针对有的场景app第一个点图加载不成功的问题
  60916. console.log(`图index ${cubeFace} , ${startX}, ${startY}, ${width}, ${height}`)
  60917. this.targetList[cubeFace] || (this.targetList[cubeFace] = [])
  60918. this.targetList[cubeFace].push([startX,startY,width,height])*/
  60919. }
  60920. }();
  60921. /*
  60922. * 将texture渲染到zoomRenderTarget上(目的是复制贴图到zoomRenderTarget)
  60923. */
  60924. PanoRenderer.prototype.copyCubeMap = function() {//将texture渲染到zoomRenderTarget上
  60925. var inited = !1,
  60926. scene = null,
  60927. camera = null,
  60928. material = null,
  60929. geo = null,
  60930. mesh = null,
  60931. testCube = null, //add
  60932. c = new Euler;
  60933. return function(texture, renderTarget, tWidth, tHeight, rWidth, rHeight, m, v, A) {
  60934. if(rWidth > this.qualityManager.maxRenderTargetSize) return; //add
  60935. if (!inited) {
  60936. var w = 2;
  60937. camera = new OrthographicCamera(w / -2, w / 2, w / 2, w / -2, 0, 200),
  60938. camera.position.set(0, 0, 0),
  60939. scene = new Scene,
  60940. scene.add(camera);
  60941. material = new ShaderMaterial({
  60942. uniforms: {
  60943. tDiffuse: {
  60944. type: "t",
  60945. value: null
  60946. },
  60947. alpha: {
  60948. type: "f",
  60949. value: 1
  60950. }
  60951. },
  60952. vertexShader: Shaders['copyCubeMap.vs'],
  60953. fragmentShader:Shaders['copyCubeMap.fs'],
  60954. depthWrite: !1,
  60955. depthTest: !1,
  60956. side: DoubleSide
  60957. });
  60958. geo = new BoxGeometry(w, w, w),
  60959. mesh = new Mesh(geo, material),
  60960. scene.add(mesh);
  60961. inited = !0;
  60962. /* testCube = mesh.clone();
  60963. viewer.scene.scene.add(testCube);
  60964. viewer.setObjectLayers(testCube, 'sceneObjects')
  60965. */
  60966. }
  60967. let autoClear = this.viewer.renderer.autoClear;
  60968. let oldTarget = this.viewer.renderer.getRenderTarget();
  60969. this.viewer.renderer.autoClear = false;
  60970. material.uniforms.tDiffuse.value = texture;
  60971. material.blending = m || NoBlending;
  60972. material.transparent = !!v;
  60973. void 0 !== A && null !== A || (A = 1);
  60974. material.uniforms.alpha.value = A;
  60975. material.needUpdate = !0;
  60976. for (var C = 0; C < 6; C++){
  60977. this.getCubeOrientationForCubeFace(C, c);
  60978. mesh.rotation.copy(c);
  60979. mesh.matrixWorldNeedsUpdate = !0;
  60980. mesh.updateMatrixWorld();
  60981. renderTarget.viewport.set(0, 0, rWidth, rHeight);
  60982. this.viewer.renderer.setRenderTarget(renderTarget, C ); //renderTarget.activeCubeFace = C//失效
  60983. this.viewer.renderer.render(scene, camera);
  60984. }
  60985. //console.warn('copyCubeMap' + rWidth)
  60986. this.viewer.renderer.autoClear = autoClear;
  60987. this.viewer.renderer.setRenderTarget(oldTarget);
  60988. }
  60989. }();
  60990. class DepthImageSampler {
  60991. constructor(){
  60992. var canvas = document.createElement("canvas");
  60993. this.canvas = canvas;
  60994. this.context = canvas.getContext("2d");
  60995. /* document.getElementsByTagName('body')[0].appendChild(canvas);
  60996. canvas.style.position = 'fixed';
  60997. canvas.style.width = '1024px';
  60998. canvas.style.top = canvas.style.left = 0
  60999. canvas.style['z-index'] = 100
  61000. */
  61001. }
  61002. changeImg(img){
  61003. if(this.img == img)return
  61004. this.canvas.width = img.width;
  61005. this.canvas.height = img.height;
  61006. this.context.drawImage(img, 0, 0);
  61007. this.img = img;
  61008. }
  61009. getDepth(UVx, UVy) {//根据图片像素获取深度值
  61010. var x = Math.round(UVx * (this.canvas.width - 1))
  61011. , y = Math.round(UVy * (this.canvas.height - 1));
  61012. if (!(x < 0 || y < 0 || x >= this.width || y >= this.height)) {
  61013. var r = this.context.getImageData(x, y, 1, 1).data;
  61014. //console.log('color', r, x,y)
  61015. return r[1] + r[0] / 256
  61016. }
  61017. }
  61018. sample( intersect, currentPano, onlyPos ) {//通过和skybox的intersect得到真实的intersect的位置
  61019. if(!intersect)return
  61020. let location = new THREE.Vector3;
  61021. let normal;
  61022. currentPano = currentPano || viewer.images360.currentPano;
  61023. if(currentPano != this.currentPano){
  61024. if(!currentPano.depthTex/* || !currentPano.depthTex.image */) return //未加载
  61025. this.changeImg(currentPano.depthTex.image);
  61026. this.currentPano = currentPano;
  61027. }
  61028. let origin = currentPano.position;
  61029. let dir = intersect.dir || new THREE.Vector3().subVectors(intersect.point, origin).normalize();
  61030. //var uv = intersect.uv
  61031. //let dirInPano = math.getNormalDir(dir, currentPano)//转化为考虑漫游点旋转的方向
  61032. let dirInPano = dir.clone().applyMatrix4(currentPano.panoMatrix2Inverse).normalize(); //转化为考虑漫游点旋转的方向
  61033. let uv = math.getUVfromDir(dirInPano);//转化为uv
  61034. let distance = this.getDepth(uv.x, uv.y);
  61035. //console.log('depth', depth, uv.y)
  61036. if (!distance){
  61037. if(uv.y > 0.75){//漫游点底部识别不到的区域,给一个地板高度
  61038. //let height = origin.distanceTo(currentPano.floorPosition);
  61039. const margin = 0.1;
  61040. distance = (currentPano.floorPosition.z - origin.z - margin) / dir.z;
  61041. location.copy(dir).multiplyScalar(distance).add(origin);
  61042. let normal = new THREE.Vector3(0,0,1);
  61043. return {location, normal, distance}
  61044. }
  61045. else return !1; //应该是天空或模型外 , 因为很少有漫游点的地方还拍不到地板
  61046. }
  61047. //this.mainDepth = depth
  61048. location.copy(dir).multiplyScalar(distance).add(origin);
  61049. if(!onlyPos){
  61050. var pL = this.getNearbyPoint(origin, uv, -1, 0)
  61051. , pR = this.getNearbyPoint(origin, uv, 1, 0)
  61052. , pB = this.getNearbyPoint(origin, uv, 0, -1)
  61053. , pT = this.getNearbyPoint(origin, uv, 0, 1);
  61054. normal = this.planeFit(dir,location, pL,pR,pB,pT );
  61055. }
  61056. /* if(normal.x != normal.x ){
  61057. console.log('NAN', normal)
  61058. var pL = this.getNearbyPoint(origin, uv, -1, 0)
  61059. , pR = this.getNearbyPoint(origin, uv, 1, 0)
  61060. , pB = this.getNearbyPoint(origin, uv, 0, -1)
  61061. , pT = this.getNearbyPoint(origin, uv, 0, 1);
  61062. } */
  61063. //console.log('normal',normal)
  61064. return {location, normal, distance}
  61065. }
  61066. getNearbyPoint( origin, uv, x, y) { //获取附近的若干像素距离的点
  61067. let uv2 = uv.clone();
  61068. uv2.x += x/(this.canvas.width-1);
  61069. uv2.x = this.clampUV(uv2.x);
  61070. uv2.y += y/(this.canvas.height-1);
  61071. uv2.y = this.clampUV(uv2.y);
  61072. /* if(uv2.x < 0 || uv2.y < 0 || uv2.x > 1 || uv2.y > 1){
  61073. console.log('will nan')
  61074. } */
  61075. let dir = math.getDirFromUV(uv2);//从uv获取到方向
  61076. dir.applyMatrix4(viewer.images360.currentPano.panoMatrix2);
  61077. let depth = this.getDepth(uv2.x, uv2.y);
  61078. /* if(Math.abs(depth - this.mainDepth) > 0.3){
  61079. console.log('Math.abs(depth - this.mainDepth) > 0.3')
  61080. } */
  61081. //let dir = new THREE.Vector3().subVectors(intersect.point, origin).normalize()
  61082. let position = new THREE.Vector3().copy(dir).multiplyScalar(depth).add(origin);
  61083. //console.log('getNearbyPoint', uv2, depth, dir, position )
  61084. return position
  61085. }
  61086. clampUV(v){
  61087. return (v + 1) % 1; // 使输出在 0-1
  61088. }
  61089. planeFit(dir, position, pL,pR,pB,pT ) {//求平均法线
  61090. let normal = new THREE.Vector3;
  61091. let plane = new THREE.Plane;
  61092. function addNormal(p1, p2) {//根据临接的四个点,分别求法线,然后法线相加能得到平均法线
  61093. if(!p1 || !p2)return
  61094. plane.setFromCoplanarPoints(position, p1, p2);
  61095. //console.log('normalSub', plane.normal)
  61096. normal.addScaledVector(plane.normal, dir.dot(plane.normal) < 0 ? 1 : -1);//根据面的朝向判断加还是减
  61097. }
  61098. addNormal(pL, pB);
  61099. addNormal(pL, pT);
  61100. addNormal(pR, pB);
  61101. addNormal(pR, pT);
  61102. if(0 !== normal.x || 0 !== normal.y || 0 !== normal.z){
  61103. normal.normalize();
  61104. //console.log(normal)
  61105. return normal
  61106. }
  61107. /* 四个面拼成一个菱形 */
  61108. }
  61109. /* makeUvToPosMap(intersect, matrix1, vec1, vec2) {
  61110. var o = intersect.object.geometry
  61111. , a = o.attributes.position.array
  61112. , 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)
  61113. , 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)
  61114. , 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);
  61115. vec1.subVectors(s, c),
  61116. vec2.subVectors(l, c);
  61117. var u = o.attributes.uv.array
  61118. , d = new THREE.Vector2(u[2 * intersect.face.a],u[2 * intersect.face.a + 1])
  61119. , p = new THREE.Vector2(u[2 * intersect.face.b],u[2 * intersect.face.b + 1])
  61120. , h = new THREE.Vector2(u[2 * intersect.face.c],u[2 * intersect.face.c + 1])
  61121. , f = d.sub(p)
  61122. , g = h.sub(p);
  61123. matrix1.set(f.x, g.x, 0, f.y, g.y, 0, 0, 0, 1),
  61124. matrix1.getInverse(matrix1)
  61125. } */
  61126. /* getNearbyPoint( point, origin, uv, o, a, s, x, y) {
  61127. var add = new THREE.Vector3(x, y , 0 )
  61128. , depth = this.getDepth(uv.x + add.x, uv.y + add.y );
  61129. if (void 0 !== depth) {
  61130. var f = add.applyMatrix3(o);
  61131. return (new THREE.Vector3).addScaledVector(a, f.x).addScaledVector(s, f.y).add(point).sub(origin).normalize().multiplyScalar(depth).add(origin)
  61132. }
  61133. } */
  61134. }
  61135. /* var i = n(4)
  61136. , r = function() {
  61137. function t(t) {
  61138. }
  61139. return t.prototype.getDepth = function(t, e) {
  61140. var n = Math.round(t)
  61141. , i = Math.round(e);
  61142. if (!(n < 0 || i < 0 || n >= this.width || i >= this.height)) {
  61143. var r = this.context.getImageData(n, i, 1, 1).data;
  61144. return r[1] + r[0] / 256
  61145. }
  61146. }
  61147. ,
  61148. Object.defineProperty(t.prototype, "width", {
  61149. get: function() {
  61150. return this.context.canvas.width
  61151. },
  61152. enumerable: !0,
  61153. configurable: !0
  61154. }),
  61155. Object.defineProperty(t.prototype, "height", {
  61156. get: function() {
  61157. return this.context.canvas.height
  61158. },
  61159. enumerable: !0,
  61160. configurable: !0
  61161. }),
  61162. t
  61163. }();
  61164. e.CanvasDepthImage = r;
  61165. var o = function() {
  61166. function t() {}
  61167. return t.sample = function(e, n, r, o, a) {
  61168. var s = n.uv
  61169. , c = s.x * (e.width - 1)
  61170. , l = (1 - s.y) * (e.height - 1)
  61171. , u = e.getDepth(c, l);
  61172. if (!u)
  61173. return !1;
  61174. o.copy(n.point).sub(r).normalize().multiplyScalar(u).add(r);
  61175. var d = new i.Matrix3
  61176. , p = new i.Vector3
  61177. , h = new i.Vector3;
  61178. t.makeUvToPosMap(n, d, p, h);
  61179. var f = this.getNearbyPoint(e, n.point, r, s, d, p, h, -1, 0)
  61180. , g = this.getNearbyPoint(e, n.point, r, s, d, p, h, 1, 0)
  61181. , m = this.getNearbyPoint(e, n.point, r, s, d, p, h, 0, -1)
  61182. , v = this.getNearbyPoint(e, n.point, r, s, d, p, h, 0, 1);
  61183. return this.planeFit(o, r, f, g, m, v, a)
  61184. }
  61185. ,
  61186. t.makeUvToPosMap = function(t, e, n, r) {
  61187. var o = t.object.geometry
  61188. , a = o.attributes.position.array
  61189. , 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)
  61190. , 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)
  61191. , 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);
  61192. n.subVectors(s, c),
  61193. r.subVectors(l, c);
  61194. var u = o.attributes.uv.array
  61195. , d = new i.Vector2(u[2 * t.face.a],u[2 * t.face.a + 1])
  61196. , p = new i.Vector2(u[2 * t.face.b],u[2 * t.face.b + 1])
  61197. , h = new i.Vector2(u[2 * t.face.c],u[2 * t.face.c + 1])
  61198. , f = d.sub(p)
  61199. , g = h.sub(p);
  61200. e.set(f.x, g.x, 0, f.y, g.y, 0, 0, 0, 1),
  61201. e.getInverse(e)
  61202. }
  61203. ,
  61204. t.getNearbyPoint = function(t, e, n, r, o, a, s, c, l) {
  61205. var u = new i.Vector3(c / (t.width - 1),l / (t.height - 1))
  61206. , d = (r.x + u.x) * (t.width - 1)
  61207. , p = (1 - (r.y + u.y)) * (t.height - 1)
  61208. , h = t.getDepth(d, p);
  61209. if (void 0 !== h) {
  61210. var f = u.applyMatrix3(o);
  61211. return (new i.Vector3).addScaledVector(a, f.x).addScaledVector(s, f.y).add(e).sub(n).normalize().multiplyScalar(h).add(n)
  61212. }
  61213. }
  61214. ,
  61215. t.planeFit = function(t, e, n, r, o, a, s) {
  61216. s.set(0, 0, 0);
  61217. var c = t.clone().sub(e)
  61218. , l = new i.Plane;
  61219. function u(e, n) {
  61220. e && n && (l.setFromCoplanarPoints(t, e, n),
  61221. s.addScaledVector(l.normal, c.dot(l.normal) < 0 ? 1 : -1))
  61222. }
  61223. return u(n, o),
  61224. u(n, a),
  61225. u(r, o),
  61226. u(r, a),
  61227. (0 !== s.x || 0 !== s.y || 0 !== s.z) && (s.normalize(),
  61228. !0)
  61229. }
  61230. ,
  61231. t
  61232. }();
  61233. */
  61234. var rot90$1 = new Quaternion().setFromAxisAngle(new Vector3(0,0,1), Math.PI/2 ); //使用的是刚好适合全景图的,给cube贴图需要转90°
  61235. let raycaster = new Raycaster();
  61236. //let currentlyHovered = null;
  61237. let texLoader$3 = new TextureLoader();
  61238. let sm$1 = new MeshBasicMaterial({side: BackSide});
  61239. let tileArr = [];
  61240. let previousView = {
  61241. controls: null,
  61242. position: null,
  61243. target: null,
  61244. };
  61245. const HighMapCubeWidth = 1;
  61246. const directionFactor = 200; //原先10,几乎只往距离近的走了;设置太大楼梯上不去
  61247. class Images360 extends EventDispatcher{
  61248. constructor(viewer ){
  61249. super();
  61250. this.viewer = viewer;
  61251. this.selectingEnabled = true;
  61252. this.panos = [];
  61253. this.neighbourMap = {};
  61254. this.node = new Object3D();
  61255. this.node.name = 'ImagesNode';
  61256. //this.node2 = new THREE.Object3D();
  61257. this.cubePanos = [];
  61258. this.cube = new Mesh(new BoxBufferGeometry(1,1,1,1),new ModelTextureMaterial());
  61259. viewer.updateVisible(this.cube,'showSkybox', false );
  61260. this.cube.layers.set(Potree.config.renderLayers.skybox);
  61261. this.cube.name = 'skyboxCube';
  61262. viewer.scene.scene.add(this.cube);
  61263. this._visible = true;
  61264. this.currentPano = null;
  61265. this.mouseLastMoveTime = Date.now();
  61266. this.scrollZoomSpeed = 0.06;
  61267. this.zoomLevel = 1;
  61268. this.tileDownloader = new TileDownloader;
  61269. this.qualityManager = new QualityManager;
  61270. this.panoRenderer = new PanoRenderer(viewer, this.tileDownloader, this.qualityManager);
  61271. this.basePanoSize = this.qualityManager.getPanoSize(PanoSizeClass.BASE);
  61272. this.standardPanoSize = this.qualityManager.getPanoSize(PanoSizeClass.STANDARD);
  61273. this.highPanoSize = this.qualityManager.getPanoSize(PanoSizeClass.HIGH);
  61274. this.ultraHighPanoSize = this.qualityManager.getPanoSize(PanoSizeClass.ULTRAHIGH);
  61275. this.tileDownloader.processPriorityQueue = !1;
  61276. this.tileDownloader.tilePrioritizer = new TilePrioritizer(this.qualityManager, this.basePanoSize, this.standardPanoSize, this.highPanoSize, this.ultraHighPanoSize);
  61277. this.flying_ = false;
  61278. {//高分辨率cube 放大
  61279. this.addHighMapCube();
  61280. viewer.addEventListener(PanoramaEvents.Enter,(e)=>{
  61281. this.setHighMap(e.newPano);
  61282. });
  61283. viewer.addEventListener('panoSetZoom',(e)=>{
  61284. if(Potree.settings.displayMode == 'showPanos'){
  61285. e.zoomed ? this.showHighMap() : this.hideHighMap(); //add
  61286. }
  61287. });
  61288. }
  61289. this.depthSampler = new DepthImageSampler();
  61290. this.addEventListener('loadedDepthImg',(e)=>{
  61291. e.loaded && this.updateDepthTex(e.pano);
  61292. });
  61293. let scroll = (e)=>{
  61294. if(e.hoverViewport != viewer.mainViewport)return
  61295. /* if(Potree.settings.displayMode == 'showPanos' && Potree.settings.zoom.enabled){
  61296. } */
  61297. };
  61298. viewer.fpControls.addEventListener('dollyStopCauseUnable',(e)=>{
  61299. if(/* e.hoverViewport != viewer.mainViewport || */!Potree.settings.zoom.enabled)return
  61300. if(e.scale != void 0){//触屏
  61301. this.zoomBy(e.scale, e.pointer);
  61302. }else {//滚轮
  61303. let zoom;
  61304. if(e.delta > 0){
  61305. zoom = 1 + this.scrollZoomSpeed;
  61306. }else {
  61307. zoom = 1 - this.scrollZoomSpeed;
  61308. }
  61309. e.delta != 0 && this.zoomBy(zoom);
  61310. }
  61311. });
  61312. let click = (e) => {//不用"mouseup" 是因为 mouseup有drag object时也会触发
  61313. if(e.clickElement ||
  61314. Potree.settings.unableNavigate || this.flying || !e.isTouch && e.button != MOUSE.LEFT || e.drag && e.drag.object //拖拽结束时不算
  61315. || Potree.settings.editType == 'pano' && viewer.modules.PanoEditor.activeViewName != 'mainView'
  61316. || Potree.settings.editType == 'merge' && !e.intersectPoint || viewer.inputHandler.hoveredElements[0] && viewer.inputHandler.hoveredElements[0].isModel && e.intersectPoint.distance > viewer.inputHandler.hoveredElements[0].distance
  61317. ) return
  61318. if(Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge'){
  61319. if( e.hoverViewport == viewer.mapViewer.viewports[0]){
  61320. return viewer.mapViewer.dispatchEvent(e/* {type:'global_click',e } */)
  61321. }else if(e.hoverViewport != viewer.mainViewport){ //如数据集校准其他viewport
  61322. return
  61323. }
  61324. }
  61325. /* if(currentlyHovered && currentlyHovered.pano){
  61326. this.focusPano(currentlyHovered.pano);
  61327. }else{//add */
  61328. if(!Potree.settings.dblToFocusPoint/* && this.currentPano */){//双击不会focus点云 或者 已经focusPano了
  61329. this.flyToPanoClosestToMouse();
  61330. }
  61331. //}
  61332. };
  61333. viewer.addEventListener('global_click' , click);
  61334. viewer.addEventListener("global_mousemove", (e) => {
  61335. if(!Potree.settings.unableNavigate && Potree.settings.ifShowMarker && e.hoverViewport == viewer.mainViewport){//如果不显示marker,就在点击时再更新
  61336. this.updateClosestPano(e.intersectPoint);
  61337. }
  61338. });
  61339. this.addEventListener('markerHover',(e)=>{
  61340. this.updateClosestPano(e.pano, e.hovered);
  61341. });
  61342. if(!Potree.settings.isOfficial){
  61343. this.domRoot = viewer.renderer.domElement.parentElement;
  61344. let elUnfocus = $("<input type='button' value='unfocus'></input>");
  61345. elUnfocus.css({
  61346. position : "absolute",
  61347. right : '25%',
  61348. bottom: '20px',
  61349. zIndex: "10000",
  61350. fontSize:'1em', color:"black",
  61351. display:'none',
  61352. background:'rgba(255,255,255,0.8)',
  61353. });
  61354. elUnfocus.on("click", () => this.unfocus());
  61355. this.elUnfocus = elUnfocus;
  61356. this.domRoot.appendChild(elUnfocus[0]);
  61357. if(Potree.settings.editType != 'merge'){
  61358. let elHide = $("<input type='button' value='隐藏点云'></input>");
  61359. elHide.css({
  61360. position : "absolute",
  61361. right : '40%',
  61362. bottom: '20px',
  61363. zIndex: "10000",
  61364. fontSize:'1em' ,color:"black",
  61365. width : '100px',
  61366. background:'rgba(255,255,255,0.8)',
  61367. });
  61368. this.domRoot.appendChild(elHide[0]);
  61369. elHide.on("click", (e) => {
  61370. let visi = viewer.getObjVisiByReason(viewer.scene.pointclouds[0], 'force');
  61371. viewer.scene.pointclouds.forEach(e=>{
  61372. viewer.updateVisible(e, 'force', !visi);
  61373. });
  61374. elHide.val(!visi ? "隐藏点云" : "显示点云");
  61375. });
  61376. }
  61377. let elDisplayModel = $("<input type='button' value='>>全景'></input>");
  61378. elDisplayModel.css({
  61379. position : "absolute",
  61380. right : '65%',
  61381. bottom: '20px',
  61382. zIndex: "10000",
  61383. fontSize:'1em',color:"black",
  61384. width : '100px',
  61385. background:'rgba(255,255,255,0.8)',
  61386. });
  61387. this.domRoot.appendChild(elDisplayModel[0]);
  61388. elDisplayModel.on("click", (e) => {
  61389. if(Potree.settings.displayMode == 'showPointCloud' && this.panos.length == 0)return
  61390. Potree.settings.displayMode = Potree.settings.displayMode == 'showPointCloud' ? 'showPanos' : 'showPointCloud';
  61391. });
  61392. this.elDisplayModel = elDisplayModel;
  61393. }
  61394. {//切换模式
  61395. let displayMode = '';
  61396. let latestRequestMode = '';//因为可能延迟,所以记录下每次的请求模式,延迟后判断这个
  61397. Object.defineProperty(Potree.settings , "displayMode",{
  61398. get: function() {
  61399. return displayMode
  61400. },
  61401. set: (mode)=> {
  61402. latestRequestMode = mode;
  61403. console.warn('Request setMode: ' + mode);
  61404. if(mode != displayMode){
  61405. let config = Potree.config.displayMode[mode];
  61406. let config2;
  61407. let camera = viewer.scene.getActiveCamera();
  61408. if(mode == 'showPanos' && viewer.mainViewport.view.isFlying()){//飞完才能切换全景
  61409. let f = ()=>{
  61410. if(latestRequestMode == mode){//如果ui还是停在这个模式的话
  61411. Potree.settings.displayMode = mode;
  61412. }
  61413. viewer.mainViewport.view.removeEventListener('flyingDone', f);
  61414. };
  61415. viewer.mainViewport.view.addEventListener('flyingDone', f); //once
  61416. return
  61417. }
  61418. if(this.isAtPano() ){//this.currentPano
  61419. if(this.flying)config2 = config.transition;
  61420. else config2 = config.atPano;
  61421. }else {
  61422. config2 = config.atPano;
  61423. if(mode == 'showPanos'){//自动飞入一个pano
  61424. //要改成飞进最近的。。。
  61425. if(this.panos.length == 0)return
  61426. //this.modeChanging = true //主要是因为到全景图不会立刻成功
  61427. let wait = ()=>{
  61428. this.removeEventListener('flyToPanoDone',wait);
  61429. if(latestRequestMode == mode ){
  61430. Potree.settings.displayMode = mode;
  61431. }
  61432. };
  61433. this.flyToPano({
  61434. pano: this.findNearestPano(),
  61435. //dealDoneWhenCancel:true,
  61436. /* callback: ()=>{
  61437. setTimeout(()=>{ //防止循环,所以延迟
  61438. if(latestRequestMode == mode ){
  61439. Potree.settings.displayMode = mode
  61440. }
  61441. },1)
  61442. } */
  61443. });
  61444. this.addEventListener('flyToPanoDone',wait); //等待飞行完毕。flyToPano的callback可能不执行所以换这个。但也可能被cancel
  61445. return;
  61446. }else {
  61447. }
  61448. }
  61449. if(config2.showSkybox || config2.showPoint && config2.pointUsePanoTex){
  61450. this.tileDownloader.start();
  61451. }else {
  61452. this.tileDownloader.stop();
  61453. }
  61454. if(config2.showSkybox || config2.pointUsePanoTex){
  61455. let wait = ()=> {
  61456. setTimeout( ()=>{
  61457. if(latestRequestMode == mode ){
  61458. Potree.settings.displayMode = mode;
  61459. }
  61460. },1);
  61461. this.removeEventListener('loadedDepthImg', wait);
  61462. };
  61463. if(!this.currentPano.depthTex && this.currentPano.pointcloud.hasDepthTex){
  61464. this.addEventListener('loadedDepthImg', wait);
  61465. return this.currentPano.loadDepthImg()
  61466. }
  61467. //this.updateDepthTex()
  61468. if(this.checkAndWaitForPanoLoad(this.currentPano, this.basePanoSize, wait)){
  61469. return
  61470. }
  61471. }
  61472. viewer.scene.pointclouds.forEach(e=>{
  61473. viewer.updateVisible(e, 'displayMode', config2.showPoint, 2 );
  61474. });
  61475. if(config2.pointUsePanoTex){
  61476. viewer.scene.pointclouds.forEach(e=>{
  61477. e.material.setProjectedPanos(this.currentPano,this.currentPano, 1);
  61478. });
  61479. }else {
  61480. viewer.scene.pointclouds.forEach(e=>{
  61481. e.material.stopProjectedPanos();
  61482. });
  61483. }
  61484. viewer.updateVisible(this.cube,'showSkybox',config2.showSkybox );// this.cube.visible = config2.showSkybox
  61485. //this.cube.visible = config.atPano.showSkybox
  61486. if(this.cube.visible){
  61487. //this.cube.material.setProjectedPanos(this.currentPano, this.currentPano, 1)
  61488. this.setProjectedPanos({
  61489. progress:1,
  61490. ifSkybox: true,
  61491. ifPointcloud : false,
  61492. easeInOutRatio : 0,
  61493. pano0:this.currentPano,
  61494. pano1:this.currentPano
  61495. });
  61496. }else {
  61497. this.smoothZoomTo(1);
  61498. this.resetHighMap();
  61499. this.hideHighMap();
  61500. }
  61501. /* viewer.dispatchEvent({
  61502. type: "enableChangePos",
  61503. canLeavePano : config.canLeavePano ,
  61504. viewport:
  61505. }) */
  61506. //viewer.mainViewport.unableChangePos = !config.canLeavePano
  61507. displayMode = mode;
  61508. if(mode == 'showPanos'){
  61509. camera.far = viewer.farWhenShowPano; //修改far
  61510. Potree.settings.pointDensity = 'panorama';
  61511. if(Potree.config.displayMode.showPanos.transition.pointUsePanoTex){
  61512. viewer.scene.pointclouds.forEach(e=>{
  61513. e.material.pointSizeType = 'FIXED';
  61514. });
  61515. }
  61516. this.updateCube(this.currentPano);
  61517. }else {
  61518. if(camera.limitFar) camera.far = Potree.settings.cameraFar;//修改far
  61519. Potree.settings.pointDensity = Potree.settings.UserPointDensity;
  61520. //Potree.sdk && Potree.sdk.scene.changePointOpacity()
  61521. if(Potree.config.displayMode.showPanos.transition.pointUsePanoTex){
  61522. viewer.scene.pointclouds.forEach(e=>{
  61523. e.material.pointSizeType = Potree.config.material.pointSizeType;
  61524. });
  61525. }
  61526. }
  61527. camera.updateProjectionMatrix();
  61528. if(this.elDisplayModel){
  61529. this.elDisplayModel.val( mode == 'showPointCloud' ? ">>全景" : '>>点云');
  61530. }
  61531. /* this.panos.forEach(e=>{
  61532. viewer.updateVisible(e, 'modeIsShowPanos', mode == 'showPanos', 1, mode == 'showPanos' ? 'add':'cancel') //
  61533. }) */
  61534. this.dispatchEvent({type:'endChangeMode',mode});
  61535. console.log('setModeSuccess: ' + mode);
  61536. }else {
  61537. //this.dispatchEvent({type:'endChangeMode',mode})
  61538. }
  61539. }
  61540. });
  61541. Potree.settings.displayMode = 'showPointCloud';
  61542. }// 切换模式 end
  61543. {//
  61544. let currentPano = null;
  61545. Object.defineProperty(this , "currentPano",{
  61546. get: function() {
  61547. return currentPano
  61548. },
  61549. set: function(e) {
  61550. if(e != currentPano){
  61551. currentPano && currentPano.exit();
  61552. e && e.enter();
  61553. currentPano = e;
  61554. }
  61555. }
  61556. });
  61557. }
  61558. {//是否显示marker
  61559. let ifShowMarker = true;
  61560. Object.defineProperty(Potree.settings, "ifShowMarker",{
  61561. get: function() {
  61562. return ifShowMarker
  61563. },
  61564. set: (show)=>{
  61565. show = !!show;
  61566. if(show != ifShowMarker){
  61567. this.panos.forEach(pano=>{
  61568. viewer.updateVisible(pano, 'ifShowMarker', show, 1 );
  61569. });
  61570. //this.emit('markersDisplayChange', show)
  61571. ifShowMarker = show;
  61572. }
  61573. }
  61574. });
  61575. }
  61576. viewer.addEventListener("update", () => {
  61577. this.update(viewer);
  61578. });
  61579. //viewer.inputHandler.addInputListener(this);
  61580. var keys = {
  61581. FORWARD: ['W'.charCodeAt(0), 38],
  61582. BACKWARD: ['S'.charCodeAt(0), 40],
  61583. LEFT: ['A'.charCodeAt(0), 37],
  61584. RIGHT: ['D'.charCodeAt(0), 39],
  61585. };
  61586. viewer.inputHandler.addEventListener('keydown',(e)=>{
  61587. if(Potree.settings.displayMode == 'showPanos'){
  61588. for(let i in keys){
  61589. if(keys[i].some(a => a == e.keyCode)){
  61590. switch(i){
  61591. case 'FORWARD':
  61592. this.flyLocalDirection(Vectors.FORWARD.clone());
  61593. break;
  61594. case 'BACKWARD':
  61595. this.flyLocalDirection(Vectors.BACK.clone());
  61596. break;
  61597. case 'LEFT':
  61598. this.flyLocalDirection(Vectors.LEFT.clone());
  61599. break;
  61600. case 'RIGHT':
  61601. this.flyLocalDirection(Vectors.RIGHT.clone());
  61602. break;
  61603. }
  61604. break;
  61605. }
  61606. }
  61607. }
  61608. });
  61609. };
  61610. updateDepthTex(pano){
  61611. if(this.currentPano != pano || !pano.depthTex)return
  61612. //this.depthSampler.changeImg(pano.depthTex.image); //pick sampler要飞到了才能切换图,而skybox贴图是随着全景图切换而切换的
  61613. this.cube.material.updateDepthTex(pano); //确保一下
  61614. }
  61615. findNearestPano(pos){
  61616. pos = pos ? new Vector3().copy(pos) : this.position;
  61617. let result = Common.sortByScore(this.panos,[Images360.filters.isEnabled()],[e=>-e.position.distanceTo(pos)]);
  61618. let pano = result && result[0] && result[0].item;
  61619. return pano
  61620. }
  61621. /* set flying(v){//正在飞向pano
  61622. this.flying_ = !!v
  61623. //console.log('this.flying_ ', !!v )
  61624. //this.emit('flying', this.flying_)
  61625. let config = Potree.config.displayMode[Potree.settings.displayMode]
  61626. viewer.mainViewport.unableChangePos = !config.canLeavePano || !!v
  61627. }
  61628. get flying(){
  61629. return this.flying_
  61630. } */
  61631. flyLocalDirection(dir) {
  61632. var direction = this.getDirection(dir),
  61633. option1 = 1 === dir.y ? .4 : .75,
  61634. option2 = 1 === Math.abs(dir.x);
  61635. return this.flyDirection(direction, option1, option2)
  61636. }
  61637. getDirection(e) {
  61638. if(!e){
  61639. return viewer.scene.view.direction
  61640. }else {
  61641. return e = e ? e : (new Vector3).copy(Vectors.FORWARD),
  61642. e.applyQuaternion(viewer.scene.getActiveCamera().quaternion)
  61643. }
  61644. }
  61645. get position(){
  61646. return this.viewer.scene.view.position.clone()
  61647. }
  61648. get visible(){
  61649. return this._visible;
  61650. }
  61651. set visible(visible){
  61652. if(this._visible === visible){
  61653. return;
  61654. }
  61655. /* for(const image of this.panos){
  61656. image.mesh.visible = visible && (this.currentPano == null);
  61657. } */
  61658. //this.sphere.visible = visible && (this.currentPano != null);
  61659. this._visible = visible;
  61660. this.dispatchEvent({
  61661. type: "visibility_changed",
  61662. panos: this,
  61663. });
  61664. }
  61665. isAtPano(){//是否在某个漫游点上
  61666. return this.currentPano && viewer.scene.view.position.equals(this.currentPano.position)
  61667. }
  61668. updateProjectedPanos(){//更新材质贴图
  61669. //console.warn('updateProjectedPanos')
  61670. this.projectedPano0 && this.projectedPano1 && this.setProjectedPanos({pano0:this.projectedPano0, pano1:this.projectedPano1});
  61671. }
  61672. setProjectedPanos(o={}){//设置cube和点云的材质贴图
  61673. this.cube.material.setProjectedPanos(o.pano0, o.pano1, o.progress);
  61674. if(o.ifPointcloud){
  61675. viewer.scene.pointclouds.forEach(e=>{
  61676. e.material.setProjectedPanos(o.pano0, o.pano1, o.progress, o.easeInOutRatio);
  61677. });
  61678. }
  61679. //console.warn('setProjectedPanos ', o.pano0.id , o.pano1.id)
  61680. this.projectedPano0 = o.pano0;
  61681. this.projectedPano1 = o.pano1;
  61682. }
  61683. cancelFlyToPano(){//取消当前已有的飞行准备,前提是相机还未移动
  61684. if(viewer.mainViewport.view.isFlying())return
  61685. this.nextPano = null;
  61686. this.latestToPano = null;
  61687. //this.flying = false
  61688. }
  61689. flyToPano(toPano) { //飞向漫游点
  61690. if(!toPano)return
  61691. if(toPano instanceof Panorama){
  61692. toPano = {pano: toPano};
  61693. }
  61694. if(!toPano.pano.enabled)return
  61695. /* if(!this.currentPano){
  61696. return this.focusPano(toPano)
  61697. } */
  61698. let done = (makeIt, disturb)=>{
  61699. //console.log('flyToPano done ', toPano.pano.id, makeIt )
  61700. if(makeIt || disturb) { // disturb已经开始飞行但中途取消
  61701. toPano.callback && toPano.callback(makeIt);
  61702. //this.flying = false
  61703. this.cancelFlyToPano();
  61704. this.updateClosestPano(this.closestPano,false); //飞行结束后取消点击漫游点时得到的closestPano
  61705. }else {
  61706. console.log('makeit fail');
  61707. }
  61708. this.dispatchEvent({type:'flyToPanoDone', makeIt});
  61709. //this.dispatchEvent('cameraMoveDone')
  61710. toPano.deferred && toPano.deferred.resolve(makeIt); //测量线截图时发现,resolve需要写在flying=false 后才行。
  61711. };
  61712. if(this.currentPano == toPano.pano && this.isAtPano() && !toPano.target && !toPano.quaternion ){
  61713. this.dispatchEvent({type:'flyToPano', toPano});
  61714. return done(true);
  61715. }
  61716. if(this.latestToPano && this.latestToPano != toPano){
  61717. return done(false)
  61718. }
  61719. let target = toPano.target;
  61720. let easeName = toPano.easeName || 'easeInOutQuad'; // 'easeInOutSine'//'easeOutSine'
  61721. let config = Potree.config.displayMode[Potree.settings.displayMode];
  61722. var pointcloudVisi = config.atPano.showPoint; //viewer.scene.pointclouds[0].visible
  61723. var pano = toPano.pano;
  61724. let T = Potree.config.transitionsTime;
  61725. let maxTime = this.isAtPano() ? T.panoToPanoMax : T.flyIn;
  61726. var duration = toPano.duration == void 0 ? (T.flyMinTime+Math.min(T.flytimeDistanceMultiplier * this.position.distanceTo(pano.position), maxTime)) : toPano.duration;
  61727. toPano.duration = duration;
  61728. //console.warn("flyto "+pano.id + ' duration: ' + duration )
  61729. this.nextPano = pano;
  61730. this.latestToPano = toPano;
  61731. //this.flying = true //防止新的请求
  61732. {//不飞的话是否不要执行这段?
  61733. let wait = ()=> {
  61734. if(this.latestToPano != toPano)return //如果取消了
  61735. setTimeout(()=>{
  61736. if(this.latestToPano != toPano)return
  61737. this.flyToPano(toPano);
  61738. },1);
  61739. this.removeEventListener('loadedDepthImg', wait);
  61740. };
  61741. if(!pano.depthTex && pano.pointcloud.hasDepthTex){ //需要用到depthTex计算neighbour
  61742. this.addEventListener('loadedDepthImg', wait);
  61743. return pano.loadDepthImg()
  61744. }
  61745. if(config.atPano.showSkybox || config.atPano.pointUsePanoTex){
  61746. this.updateCube(this.currentPano, toPano.pano);
  61747. if(this.checkAndWaitForPanoLoad(pano, toPano.basePanoSize || this.basePanoSize, wait)){
  61748. return
  61749. }
  61750. }
  61751. }
  61752. viewer.updateVisible(this.cube,'showSkybox', config.atPano.showSkybox ); // this.cube.visible = config.atPano.showSkybox
  61753. /* this.cube.visible && this.cube.material.setProjectedPanos(this.currentPano, pano, 0)
  61754. if(config.transition.showPoint){
  61755. viewer.scene.pointclouds.forEach(e=>{
  61756. viewer.updateVisible(e, 'displayMode', true)
  61757. })
  61758. if(config.transition.pointUsePanoTex){
  61759. let easeInOutRatio = pointcloudVisi ? 0.3 : 0
  61760. viewer.scene.pointclouds.forEach(e=>{
  61761. e.material.setProjectedPanos(this.currentPano, pano, 0, easeInOutRatio)
  61762. })
  61763. }
  61764. } */
  61765. if(config.transition.showPoint){
  61766. viewer.scene.pointclouds.forEach(e=>{
  61767. viewer.updateVisible(e, 'displayMode', true);
  61768. });
  61769. }
  61770. if(config.transition.showSkybox || config.transition.pointUsePanoTex){
  61771. this.setProjectedPanos({
  61772. progress:0,
  61773. ifSkybox: this.cube.visible,
  61774. ifPointcloud : config.transition.pointUsePanoTex,
  61775. easeInOutRatio : pointcloudVisi ? 0.3 : 0,
  61776. pano0:this.currentPano,
  61777. pano1:pano
  61778. });
  61779. }
  61780. const endPosition = pano.position.clone();
  61781. {
  61782. toPano.duration = duration;
  61783. toPano.easeName = easeName;
  61784. this.beforeFlyToPano(toPano);
  61785. }
  61786. let fly = ()=>{
  61787. this.dispatchEvent({type:'flyToPano', toPano});
  61788. viewer.scene.view.setView({position:endPosition, target, quaternion:toPano.quaternion , duration,
  61789. callback:()=>{
  61790. if(!config.atPano.pointUsePanoTex){
  61791. viewer.scene.pointclouds.forEach(e=>{
  61792. e.material.stopProjectedPanos();
  61793. });
  61794. }
  61795. //this.currentPano.exit()
  61796. //pano.enter()
  61797. this.currentPano = pano;
  61798. this.nextPano = null;
  61799. if(Potree.settings.displayMode == 'showPanos'){
  61800. viewer.scene.pointclouds.forEach(e=>{
  61801. viewer.updateVisible(e, 'displayMode',pointcloudVisi);
  61802. });
  61803. }
  61804. done(true);
  61805. //this.updateCube(this.currentPano)
  61806. this.updateDepthTex(this.currentPano);
  61807. }, onUpdate:(progress)=>{
  61808. this.cube.material.uniforms.progress.value = progress;
  61809. viewer.scene.pointclouds.forEach(e=>{
  61810. e.material.uniforms.progress.value = progress;
  61811. });
  61812. },
  61813. cancelFun:()=>{ done(false, true); },
  61814. Easing:easeName
  61815. });
  61816. //duration > 0 && (this.flying = true) //再写一遍 防止cancel其他项目导致flying为false
  61817. };
  61818. if(Potree.settings.displayMode == 'showPanos'){
  61819. setTimeout(fly, 40); //更新geo后缓冲
  61820. }else {
  61821. fly();
  61822. }
  61823. //console.log('flyToPano:', toPano.pano.id)
  61824. }
  61825. beforeFlyToPano(toPano){
  61826. if(this.currentPano != toPano.pano) {
  61827. if(Potree.settings.displayMode == 'showPanos'){
  61828. this.resetHighMap();
  61829. }
  61830. this.smoothZoomTo(1, toPano.duration / 2);
  61831. }
  61832. }
  61833. /* focusPano(toPano ){
  61834. if(this.currentPano !== null){
  61835. return this.flyToPano(toPano);
  61836. }
  61837. if(toPano instanceof Panorama){
  61838. toPano = {pano: toPano}
  61839. }
  61840. let done = (makeIt)=>{
  61841. toPano.deferred && toPano.deferred.resolve(makeIt)
  61842. makeIt && toPano.callback && toPano.callback()
  61843. }
  61844. var pano = toPano.pano
  61845. let config = Potree.config.displayMode[Potree.settings.displayMode]
  61846. previousView = {
  61847. //controls: this.viewer.controls,
  61848. position: this.position,
  61849. target: viewer.scene.view.getPivot(),
  61850. };
  61851. //this.viewer.setControls(this.viewer.orbitControls);
  61852. this.viewer.orbitControls.doubleClockZoomEnabled = false;
  61853. for(let image of this.panos){
  61854. image.mesh.visible = false;
  61855. }
  61856. this.selectingEnabled = false;
  61857. //console.warn("flyto "+pano.file.split('/').pop() )
  61858. var dur = toPano.duration == void 0 ? 700 : toPano.duration
  61859. if(config.atPano.showSkybox){
  61860. if ( this.checkAndWaitForPanoLoad(pano, this.basePanoSize, ()=> {
  61861. setTimeout( ()=>{
  61862. this.focusPano(toPano)
  61863. },1)
  61864. })
  61865. ) {
  61866. return ;
  61867. }
  61868. }
  61869. this.cube.visible = config.atPano.showSkybox
  61870. //if(config.transition.showSkybox || config.transition.pointUsePanoTex){
  61871. this.setProjectedPanos({
  61872. progress:0,
  61873. ifSkybox: this.cube.visible,
  61874. ifPointcloud : config.atPano.pointUsePanoTex,
  61875. pano0:pano,
  61876. pano1:pano
  61877. })
  61878. //}
  61879. let newCamPos = pano.position.clone()
  61880. let target = newCamPos.clone().add(viewer.scene.view.direction)
  61881. viewer.scene.view.setView( {position:newCamPos, target, duration:dur ,
  61882. callback:()=>{//done
  61883. //pano.enter()
  61884. this.flying = false
  61885. this.currentPano = pano;
  61886. this.updateCube(this.currentPano)
  61887. done(true)
  61888. },onUpdate:(progress)=>{
  61889. },
  61890. cancelFun:()=>{this.flying = false}
  61891. })
  61892. this.flying = true
  61893. this.elUnfocus && (this.elUnfocus[0].style.display = "");
  61894. }
  61895. unfocus(o={}){
  61896. this.selectingEnabled = true;
  61897. Potree.settings.displayMode = 'showPointCloud'
  61898. if(!this.currentPano && !o.position){
  61899. return;
  61900. }
  61901. this.cube.visible = false
  61902. viewer.orbitControls.doubleClockZoomEnabled = true;
  61903. viewer.scene.view.setView($.extend({
  61904. position: previousView.position,
  61905. target:previousView.target,
  61906. duration:500
  61907. },o,{
  61908. callback:()=>{ //done
  61909. for(let pano of this.panos){
  61910. pano.mesh.visible = true;
  61911. //pano.marker.material.depthTest = true
  61912. }
  61913. o.callback && o.callback()
  61914. }
  61915. ,
  61916. cancelFun:()=>{this.flying = false},
  61917. }))
  61918. //this.currentPano.exit()
  61919. this.currentPano = null;
  61920. this.elUnfocus && (this.elUnfocus[0].style.display = "none");
  61921. } */
  61922. updateCube(pano0, pano1){
  61923. if(!viewer.scene.pointclouds.some(e=>!e.hasDepthTex)) return this.updateCube2(pano0, pano1) //都hasDepthTex的话
  61924. if(Potree.settings.displayMode != 'showPanos')return
  61925. let f = (bound, size)=>{
  61926. size = size || bound.getSize(new Vector3);
  61927. let center = bound.getCenter(new Vector3);
  61928. size.max(new Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth));
  61929. this.cube.scale.copy(size);
  61930. this.cube.position.copy(center);
  61931. };
  61932. let getDis = (bound1, bound2)=>{ //获取bound1边界到bound2边界距离
  61933. if(bound1.intersectsBox(bound2))return 0
  61934. let center1 = bound1.getCenter(new Vector3);
  61935. let center2 = bound2.getCenter(new Vector3);
  61936. let dis = center1.distanceTo(center2);
  61937. let dis1 = bound1.distanceToPoint(center2);
  61938. let dis2 = bound2.distanceToPoint(center1);
  61939. return dis1 + dis2 - dis
  61940. };
  61941. if(pano1){//过渡
  61942. if(pano0.pointcloud == pano1.pointcloud){//同一个数据集内的过渡
  61943. f(pano0.pointcloud.bound);
  61944. //console.log('updateCube1' )
  61945. }else {//非同一个数据集内的过渡
  61946. let bound = pano0.pointcloud.bound.clone().union(pano1.pointcloud.bound);
  61947. if(getDis(pano0.pointcloud.bound, pano1.pointcloud.bound) < 100){
  61948. f(bound);
  61949. }else {//如果两个数据集boundingbox距离大于这个距离,扩大一下,防止精度问题导致失真//对很远的数据集似乎没有什么用
  61950. let size = bound.getSize(new Vector3);
  61951. let max = Math.max(size.x, size.y, size.z);
  61952. size.set(max,max,max);
  61953. f(bound, size);
  61954. //console.log('updateCube2', size)
  61955. //far可能要修改下
  61956. }
  61957. }
  61958. }else {
  61959. f(pano0.pointcloud.bound); //假定一个数据集不会太大,否则会造成失真,且bump时移动距离看起来很小。或者可以考虑用固定大小
  61960. //console.log('updateCube3' )
  61961. }
  61962. }
  61963. /* updateCube(pano0, pano1){ //垂直上不分段、 每个pano只有5个方向的版本
  61964. if(Potree.settings.displayMode != 'showPanos')return
  61965. console.log('updateCube',pano0.id, pano1&&pano1.id)
  61966. let f = (bound, size)=>{
  61967. size = size || bound.getSize(new THREE.Vector3)
  61968. let center = bound.getCenter(new THREE.Vector3)
  61969. size.max(new THREE.Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth))
  61970. this.cube.scale.copy(size)
  61971. this.cube.position.copy(center)
  61972. }
  61973. this.cube.geometry.dispose();
  61974. if(pano1){//过渡
  61975. let add = (pano, dir, )=>{
  61976. let minZ, maxZ
  61977. minZ = pano.floorPosition.z
  61978. {//天花板高度值
  61979. //用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算)
  61980. let rotMat = new THREE.Matrix4().makeRotationX(THREE.Math.degToRad(40))// 角度不能小于天花板中空的半径,大概就是0.2*Math.PI=36度
  61981. let dir1 = new THREE.Vector3(0,0,1).applyMatrix4(rotMat)
  61982. let rotMat1 = new THREE.Matrix4().makeRotationZ(Math.PI*2 / 3);
  61983. let rotMat2 = new THREE.Matrix4().makeRotationZ(-Math.PI*2 / 3);
  61984. let dir2 = dir1.clone().applyMatrix4(rotMat1)
  61985. let dir3 = dir1.clone().applyMatrix4(rotMat2)
  61986. let zs = [dir1,dir2,dir3].map(dir_=>{
  61987. let intersect = this.depthSampler.sample( {dir: dir_}, pano, true )
  61988. let z = intersect ? intersect.location.z : pano.position.z
  61989. return z
  61990. })
  61991. zs.sort((a,b)=>{return b-a});//得最大值
  61992. maxZ = zs[0]
  61993. }
  61994. const angle = Math.PI/6 //每次转30度
  61995. let getDir = (angle_)=>{
  61996. let rotMat = new THREE.Matrix4().makeRotationZ(angle_)
  61997. return dir.clone().applyMatrix4(rotMat)
  61998. }
  61999. let dirs = [getDir(angle*2), getDir(angle),getDir(angle), dir.clone(), getDir(-angle), getDir(-angle*2)]; //总共五个方向,夹角总和180度
  62000. dirs.forEach(dir=>{//获取在这个方向上和墙体intersect的最远距离,使用中、上、下三个方向
  62001. //上下分别45度 刚好就是
  62002. let dir0 = dir.clone();// 水平方向
  62003. let dir1 = dir.clone().setZ(1).normalize() //上45度方向
  62004. let dir2 = dir.clone().setZ(-1).normalize() // 下45度方向
  62005. let disArr = [dir0,dir1,dir2].map(dir_ =>{
  62006. let intersect = this.depthSampler.sample( {dir: dir_}, pano, true )
  62007. let projectLen = intersect.distance ? dir_.dot(dir)*intersect.distance : 0 //得到project在dir的长度
  62008. return projectLen
  62009. })
  62010. disArr.sort((a,b)=>{return b-a});//得最大值
  62011. dir.multiplyScalar( disArr[0] );//得到水平方向上的最远向量
  62012. [minZ,maxZ].forEach(z=>{ //0-9
  62013. posArr.push(pano.position.clone().setZ(z).add(dir))
  62014. })
  62015. });
  62016. [minZ,maxZ].forEach(z=>{ // 10,11
  62017. posArr.push(pano.position.clone().setZ(z))
  62018. })
  62019. }
  62020. let posArr = [];
  62021. 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], //外侧四个面
  62022. [0,2,10],[2,4,10],[4,6,10],[6,8,10],//底部扇形
  62023. [1,3,11],[3,5,11],[5,7,11],[7,9,11],//顶部扇形
  62024. ]
  62025. //两点连线的水平向量
  62026. let vec = new THREE.Vector3().subVectors(pano0.position, pano1.position).setZ(0).normalize()
  62027. add(pano0, vec)
  62028. add(pano1, vec.negate())
  62029. let faceArr2 = faceArr.map(face=>face.map(i=>i+12))//加上pano2的部分
  62030. faceArr.push(...faceArr2)
  62031. //加上连接的部分,四个面
  62032. faceArr.push([0,1, 8+12],[1, 9+12, 8+12], [8,9,0+12],[9,1+12,0+12],
  62033. [0,8,0+12],[0,0+12,8+12], [1,9,1+12],[1,1+12,9+12],
  62034. )
  62035. let geo = MeshDraw.createGeometry(posArr, faceArr)
  62036. this.cube.geometry = geo
  62037. this.cube.scale.set(1,1,1);
  62038. this.cube.position.set(0,0,0)
  62039. }else{
  62040. if(this.hasUpdateOnePano)return
  62041. this.hasUpdateOnePano = true
  62042. this.cube.geometry = new THREE.BoxBufferGeometry(1,1,1,1)
  62043. f(pano0.pointcloud.bound)
  62044. }
  62045. } */
  62046. /* updateCube(pano0, pano1){//增加细分的版本,且垂直方向上也分多个
  62047. if(Potree.settings.displayMode != 'showPanos')return
  62048. console.log('updateCube',pano0.id, pano1&&pano1.id)
  62049. let f = (bound, size)=>{
  62050. size = size || bound.getSize(new THREE.Vector3)
  62051. let center = bound.getCenter(new THREE.Vector3)
  62052. size.max(new THREE.Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth))
  62053. this.cube.scale.copy(size)
  62054. this.cube.position.copy(center)
  62055. }
  62056. this.cube.geometry.dispose();
  62057. if(pano1){//过渡
  62058. let count1, count2;
  62059. let panoIndex = 0
  62060. let add = (pano, dir )=>{
  62061. let getPI = function(index, panoIndex_){
  62062. if(panoIndex_ == void 0) panoIndex_ = panoIndex
  62063. return (count1 * count2 + 2 ) * panoIndex_ + index + 2
  62064. }
  62065. let minZ, maxZ
  62066. minZ = pano.floorPosition.z
  62067. {//天花板高度值
  62068. //用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算)
  62069. let rotMat = new THREE.Matrix4().makeRotationX(THREE.Math.degToRad(40))// 角度不能小于天花板中空的半径,大概就是0.2*Math.PI=36度
  62070. let dir1 = new THREE.Vector3(0,0,1).applyMatrix4(rotMat)
  62071. let rotMat1 = new THREE.Matrix4().makeRotationZ(Math.PI*2 / 3);
  62072. let rotMat2 = new THREE.Matrix4().makeRotationZ(-Math.PI*2 / 3);
  62073. let dir2 = dir1.clone().applyMatrix4(rotMat1)
  62074. let dir3 = dir1.clone().applyMatrix4(rotMat2)
  62075. let zs = [dir1,dir2,dir3].map(dir_=>{
  62076. let intersect = this.depthSampler.sample( {dir: dir_}, pano, true )
  62077. let z = intersect ? intersect.location.z : pano.position.z
  62078. return z
  62079. })
  62080. zs.sort((a,b)=>{return b-a});//得最大值
  62081. maxZ = zs[0]
  62082. let min = pano.position.z + 1
  62083. if(maxZ < pano.position.z + 0.04){//户外
  62084. maxZ = pano.position.z + 50
  62085. }
  62086. maxZ = Math.max(min,maxZ)
  62087. console.log(pano.id, 'maxZ:',maxZ )
  62088. console.log(pano.id, 'minZ:',minZ )
  62089. }
  62090. [maxZ, minZ ].forEach(z=>{
  62091. posArr.push(pano.position.clone().setZ(z))
  62092. })
  62093. const angle = Math.PI/8
  62094. let getDir = (angle_)=>{
  62095. let rotMat = new THREE.Matrix4().makeRotationZ(angle_)
  62096. return dir.clone().applyMatrix4(rotMat)
  62097. }
  62098. 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度
  62099. count1 = dirs.length
  62100. dirs.forEach((dir, index)=>{//获取在这个方向上和墙体intersect的最远距离,使用中、上、下三个方向
  62101. let dirs_ = [
  62102. dir.clone().setZ(Math.tan(THREE.Math.degToRad(30))).normalize(),
  62103. dir.clone().setZ(Math.tan(THREE.Math.degToRad(15))).normalize(),
  62104. dir.clone(), // 水平方向
  62105. dir.clone().setZ(-Math.tan(THREE.Math.degToRad(15))).normalize(),
  62106. dir.clone().setZ(-Math.tan(THREE.Math.degToRad(30))).normalize(),
  62107. ];
  62108. count2 = dirs_.length
  62109. dirs_.forEach((dir_, i) =>{
  62110. let intersect = this.depthSampler.sample( {dir: dir_}, pano, true )
  62111. let location
  62112. if(!intersect){ //超级远
  62113. let distance = 100
  62114. location = dir_.clone().multiplyScalar(distance).add(pano.position)
  62115. intersect = {distance,location}
  62116. }
  62117. //intersect.distance
  62118. location = intersect.location.clone()
  62119. let shouldZ// = THREE.Math.clamp(intersect.location.z, minZ, maxZ);
  62120. let needShrink = false
  62121. if(i == 0){//最上方的点高度直接等于天花板
  62122. shouldZ = maxZ
  62123. if(location.z<maxZ)location.z = maxZ
  62124. else needShrink = true
  62125. }else if(i == count2-1){//最下方的点高度直接等于地板
  62126. shouldZ = minZ
  62127. if(location.z>minZ)location.z = minZ
  62128. else needShrink = true
  62129. }
  62130. if(needShrink ){//需要在保持dir_不变的情况下修改z
  62131. let len = (shouldZ - pano.position.z) / (intersect.location.z - pano.position.z) * intersect.distance
  62132. location = dir_.clone().multiplyScalar(len).add(pano.position)
  62133. }
  62134. posArr.push(location)
  62135. if(index!=0 && i!=0){//加入一块四方面
  62136. let curIndex = getPI(count2 * index + i);
  62137. faceArr.push([curIndex-1, curIndex-count2-1, curIndex-count2],
  62138. [curIndex-1, curIndex, curIndex-count2])
  62139. }
  62140. })
  62141. if(index!=0){
  62142. let top = -2;
  62143. let btm = -1
  62144. faceArr.push([getPI(count2*(index-1) ), getPI(count2*index ), getPI(top) ])//天花板扇形
  62145. faceArr.push([getPI(count2*index-1), getPI(count2*(index+1)-1), getPI(btm) ] )//地板扇形
  62146. }else{
  62147. //加入和另一个pano连接的其中一个侧边
  62148. let panoIndex2 = (panoIndex + 1) % 2;
  62149. for(let i=1;i<count2;i++){
  62150. faceArr.push([getPI(i-1), getPI(i), getPI((count1-1)*count2 +i, panoIndex2)],
  62151. [getPI(i-1), getPI((count1-1)*count2+i , panoIndex2) , getPI((count1-1)*count2+i-1 ,panoIndex2)])
  62152. }
  62153. faceArr.push([getPI(0), getPI((count1-1)*count2), getPI(0, panoIndex2)])//加入顶部的一半
  62154. faceArr.push([getPI(count2-1), getPI(count1*count2-1), getPI(count2-1, panoIndex2)])//加入底部的一半
  62155. }
  62156. });
  62157. panoIndex ++
  62158. }
  62159. let posArr = [];
  62160. let faceArr = []
  62161. //两点连线的水平向量
  62162. let vec = new THREE.Vector3().subVectors(pano0.position, pano1.position).setZ(0).normalize()
  62163. add(pano0, vec)
  62164. add(pano1, vec.negate())
  62165. let geo = MeshDraw.createGeometry(posArr, faceArr)
  62166. this.cube.geometry = geo
  62167. this.cube.scale.set(1,1,1);
  62168. this.cube.position.set(0,0,0)
  62169. }else{
  62170. this.cube.geometry = new THREE.BoxBufferGeometry(1,1,1,1)
  62171. f(pano0.pointcloud.bound)
  62172. }
  62173. } */
  62174. updateCube3(pano0, pano1){//增加细分的版本,且垂直方向上取中位数... 侧边只有一条
  62175. if(Potree.settings.displayMode != 'showPanos' || pano0 == pano1
  62176. || this.cubePanos.includes(pano0) && this.cubePanos.includes(pano1)
  62177. ) return
  62178. this.cubePanos = [pano0, pano1];
  62179. //console.log('updateCube',pano0.id, pano1&&pano1.id)
  62180. let f = (bound, size)=>{
  62181. size = size || bound.getSize(new Vector3);
  62182. let center = bound.getCenter(new Vector3);
  62183. size.max(new Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth));
  62184. this.cube.scale.copy(size);
  62185. this.cube.position.copy(center);
  62186. };
  62187. this.cube.geometry.dispose();
  62188. if(pano1){//过渡
  62189. const half = pano0.pointcloud.hasDepthTex && pano0.pointcloud.hasDepthTex ? ( browser.isMobile() ? 3 : 6 ) : (browser.isMobile() ? 2 : 3); //自行输入 (点云计算的慢,还不准)
  62190. let count1 = 2*half;//偶数个 dir 个数
  62191. //奇数个的好处:在窄空间内能探测到最远距离,坏处是前方有尖角。偶数个的坏处就是可能检测距离太近。
  62192. let panoIndex = 0;
  62193. let getIntersect = (pano, dir, origin)=>{
  62194. if(pano && pano.pointcloud.hasDepthTex ){
  62195. return this.depthSampler.sample( {dir }, pano, true )
  62196. }else {
  62197. origin = origin || pano.position;
  62198. return viewer.inputHandler.getIntersect(viewer.inputHandler.hoverViewport, true, null, null, true, {
  62199. point: origin.clone().add(dir),
  62200. cameraPos: origin
  62201. })
  62202. }
  62203. };
  62204. let getDir = (angle_, vec)=>{ //旋转获得水平向量
  62205. let rotMat = new Matrix4().makeRotationZ(angle_);
  62206. return vec.clone().applyMatrix4(rotMat)
  62207. };
  62208. let getFar = (dir, pano, origin)=>{//获取在这个方向上和墙体intersect的最远距离
  62209. let dirs_ = [
  62210. //注意:角度太大会碰到天花板或地板,越远越容易碰到, 在地下停车场就会伸展不开。 户外时需要更多向上的方向,所以上方向多一个
  62211. dir.clone().setZ(Math.tan(MathUtils.degToRad(30))).normalize(),
  62212. dir.clone().setZ(Math.tan(MathUtils.degToRad(7))).normalize(),
  62213. dir.clone(), // 水平方向
  62214. dir.clone().setZ(-Math.tan(MathUtils.degToRad(5))).normalize(),
  62215. //dir.clone().setZ(-Math.tan(THREE.Math.degToRad(30))).normalize(),
  62216. ];
  62217. let max = 50;
  62218. let count2 = dirs_.length;
  62219. let disArr = dirs_.map((dir_, i) =>{
  62220. let intersect = getIntersect(pano, dir_, origin);
  62221. let projectLen = intersect && intersect.distance ? dir_.dot(dir)*intersect.distance : max; //得到project在dir的长度
  62222. return projectLen
  62223. });
  62224. disArr.sort((a,b)=>{return b-a}); //从大到小
  62225. //console.log(pano ? pano.id : 'side','disArr', disArr)
  62226. let dis = disArr[Math.floor(count2/2-0.5)]; //对半、取前(中位数)
  62227. return dis
  62228. };
  62229. let add = (pano, vec )=>{
  62230. let getPI = function(index, panoIndex_){
  62231. if(panoIndex_ == void 0) panoIndex_ = panoIndex;
  62232. return (count1*2 + 2 ) * panoIndex_ + index + 2
  62233. };
  62234. let minZ, maxZ;
  62235. minZ = pano.floorPosition.z;
  62236. if(pano.ceilZ != void 0){
  62237. maxZ = pano.ceilZ;
  62238. }else {//天花板高度值
  62239. //用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算)
  62240. let rotMat = new Matrix4().makeRotationX(MathUtils.degToRad(40));// 角度不能小于天花板中空的半径,大概就是0.2*Math.PI=36度
  62241. let dir1 = new Vector3(0,0,1).applyMatrix4(rotMat);
  62242. let rotMat1 = new Matrix4().makeRotationZ(Math.PI*2 / 3);
  62243. let rotMat2 = new Matrix4().makeRotationZ(-Math.PI*2 / 3);
  62244. let dir2 = dir1.clone().applyMatrix4(rotMat1);
  62245. let dir3 = dir1.clone().applyMatrix4(rotMat2);
  62246. let zs = [dir1,dir2,dir3].map(dir_=>{
  62247. let intersect = getIntersect(pano, dir_);
  62248. let z = intersect ? intersect.location.z : pano.position.z+50;
  62249. return z
  62250. });
  62251. zs.sort((a,b)=>{return b-a});//得最大值
  62252. maxZ = zs[0];
  62253. let min = pano.position.z + 1;
  62254. maxZ = Math.max(min,maxZ);
  62255. pano.ceilZ = maxZ;
  62256. //console.log(pano.id, 'maxZ:',maxZ )
  62257. //console.log(pano.id, 'minZ:',minZ )
  62258. }
  62259. [maxZ, minZ ].forEach(z=>{
  62260. posArr.push(pano.position.clone().setZ(z));
  62261. });
  62262. const angle = Math.PI/(count1-1);
  62263. //在画面上线条从左往右数
  62264. let dirs = [];
  62265. for(let i=0;i<count1;i++){
  62266. dirs.push(getDir(Math.PI/2-i*angle, vec));//正的在左边
  62267. }
  62268. let sideDis = [];
  62269. dirs.forEach((dir, index)=>{
  62270. let dis = getFar(dir, pano);
  62271. if(index == 0 || index == count1-1){
  62272. sideDis.push(dis);
  62273. }
  62274. dir.multiplyScalar( dis );
  62275. [maxZ,minZ].forEach(z=>{
  62276. posArr.push(pano.position.clone().setZ(z).add(dir));
  62277. });
  62278. if(index!=0){//加入一块四方面
  62279. let m = index*2;
  62280. faceArr.push([getPI(m), getPI(m-1), getPI(m-2)],
  62281. [getPI(m), getPI(m+1), getPI(m-1)]);
  62282. let top = -2;
  62283. let btm = -1;
  62284. faceArr.push([getPI(m), getPI(m-2), getPI(top) ]);//天花板扇形
  62285. faceArr.push([getPI(btm), getPI(m-1), getPI(m+1) ] );//地板扇形
  62286. }
  62287. });
  62288. let panoIndex2 = (panoIndex + 1) % 2;
  62289. //let m = (count1-1)*2
  62290. /* faceArr.push([getPI(0), getPI(1), getPI(count1*2-1, panoIndex2)],
  62291. [getPI(0), getPI(count1*2-1,panoIndex2) , getPI(count1*2-2,panoIndex2)])
  62292. faceArr.push([getPI(0, panoIndex2), getPI(count1*2-2), getPI(0)])//加入顶部的一半
  62293. faceArr.push([getPI(1), getPI(count1*2-1), getPI(1, panoIndex2)])//加入底部的一半 */
  62294. //加入和另一个pano连接
  62295. let sideMid = count1*4+4; //侧边点start
  62296. //侧边的一半
  62297. faceArr.push([getPI(0), getPI(1), sideMid+panoIndex*2],
  62298. [sideMid+panoIndex*2, getPI(1) , sideMid+panoIndex*2+1 ],
  62299. [getPI(count1*2-2), sideMid+panoIndex2*2+1, getPI(count1*2-1)],
  62300. [getPI(count1*2-2), sideMid+panoIndex2*2, sideMid+panoIndex2*2+1 ]
  62301. );
  62302. faceArr.push([getPI(0), sideMid+panoIndex2*2, getPI(count1*2-2)],
  62303. [getPI(0),sideMid+panoIndex*2, sideMid+panoIndex2*2]
  62304. );//加入顶部的一半
  62305. faceArr.push([getPI(count1*2-1), sideMid+panoIndex2*2+1, getPI(1)],
  62306. [sideMid+panoIndex2*2+1, sideMid+panoIndex*2+1, getPI(1)]
  62307. );//加入底部的一半
  62308. panoIndex ++;
  62309. return sideDis;
  62310. };
  62311. let addSide = ()=>{//两个漫游点间两边各加一条侧线,为了适应四方形房间漫游点在对角方向的那种情况
  62312. //侧边为了取中点,没办法用全景图获取了,用点云
  62313. let sideMaxZ = (pano0.ceilZ + pano1.ceilZ)/2;
  62314. let sideMinZ = (pano0.floorPosition.z+pano1.floorPosition.z)/2;
  62315. let sideDis_ = [(sideDis0[0] + sideDis1[1])/2, (sideDis0[1] + sideDis1[0])/2];
  62316. let sideDis = [Math.min(sideDis0[0] , sideDis1[1]), Math.min(sideDis0[1] , sideDis1[0])];//
  62317. let mid = new Vector3().addVectors(pano0.position, pano1.position).multiplyScalar(0.5);
  62318. let sideDirs = [getDir(-Math.PI/2, vec), getDir(Math.PI/2, vec)];
  62319. if(pano0.pointcloud.hasDepthTex && pano0.pointcloud.hasDepthTex){
  62320. let panos = [pano0,pano1];
  62321. let vecs = [vec.negate(), vec];
  62322. let axis = [[-1,1],[1,-1]];
  62323. let dis2d = new Vector2$1().subVectors(pano0.position, pano1.position).length();//水平上的距离
  62324. let angles = [MathUtils.degToRad(45), MathUtils.degToRad(60)];
  62325. sideDirs.forEach((dir, index0)=>{
  62326. let disToSides = [];
  62327. panos.forEach((pano,index)=>{
  62328. let dirs = [getDir(axis[index0][index]*angles[0], vecs[index]), getDir(axis[index0][index]*angles[1], vecs[index])];//一侧的若干角度
  62329. dirs.forEach((dir_,i)=>{
  62330. let dis1 = getFar(dir_, pano);
  62331. //dir_.multiplyScalar( dis1 );
  62332. let disToPano2d = dis1 * Math.cos(angles[i]);
  62333. if(disToPano2d<dis2d){//超过的话都到另一半pano的半圆了,不计入
  62334. let disToSide = dis1 * Math.sin(angles[i]);
  62335. disToSides.push(disToSide);
  62336. }
  62337. });
  62338. });
  62339. let disToSide;
  62340. if(disToSides.length){
  62341. disToSides.sort((a,b)=>{return b-a});//从大到小
  62342. disToSide = disToSides[0];
  62343. console.log('disToSides', index0, disToSides);
  62344. }else {
  62345. disToSide = sideDis[index0];
  62346. }
  62347. dir.multiplyScalar( disToSide );
  62348. [sideMaxZ,sideMinZ].forEach(z=>{
  62349. posArr.push(mid.clone().setZ(z).add(dir)); //是直接使用最长dis的那个intersect点好还是mid
  62350. });
  62351. });
  62352. }else {
  62353. sideDirs.forEach((dir_ ,index)=>{
  62354. let dis = getFar(dir_, null, mid);
  62355. dir_.multiplyScalar( /* sideDis_[index] */ Math.max(dis, sideDis[index]) );
  62356. [sideMaxZ,sideMinZ].forEach(z=>{
  62357. posArr.push(mid.clone().setZ(z).add(dir_));
  62358. });
  62359. });
  62360. }
  62361. };
  62362. let posArr = [];
  62363. let faceArr = [];
  62364. //两点连线的水平向量
  62365. let vec = new Vector3().subVectors(pano0.position, pano1.position).setZ(0).normalize();
  62366. let sideDis0 = add(pano0, vec);
  62367. let sideDis1 = add(pano1, vec.negate());
  62368. addSide();
  62369. //MeshDraw.updateGeometry(this.cube.geometry, posArr, faceArr)
  62370. let geo = MeshDraw.createGeometry(posArr, faceArr);
  62371. this.cube.geometry = geo;
  62372. this.cube.scale.set(1,1,1);
  62373. this.cube.position.set(0,0,0);
  62374. //this.cube.scale.set(100,100,100);
  62375. //this.cube.position.copy(pano1.position).multiplyScalar(-100)
  62376. }else {
  62377. this.cube.geometry = new BoxBufferGeometry(1,1,1,1);
  62378. f(pano0.pointcloud.bound);
  62379. }
  62380. }
  62381. updateCube2(pano0, pano1){//增加细分的版本,且垂直方向上取中位数 侧边多条
  62382. if(Potree.settings.displayMode != 'showPanos' || pano0 == pano1
  62383. || this.cubePanos.includes(pano0) && this.cubePanos.includes(pano1)
  62384. ) return
  62385. this.cubePanos = [pano0, pano1];
  62386. //console.log('updateCube',pano0.id, pano1&&pano1.id)
  62387. let useBound = (bound, size)=>{
  62388. size = size || bound.getSize(new Vector3);
  62389. let center = bound.getCenter(new Vector3);
  62390. size.max(new Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth));
  62391. this.cube.geometry = new BoxBufferGeometry(1,1,1,1);
  62392. this.cube.scale.copy(size);
  62393. this.cube.position.copy(center);
  62394. };
  62395. this.cube.geometry.dispose();
  62396. if(pano1){//过渡
  62397. if(pano0.pointcloud != pano1.pointcloud){ //距离太远的数据集,过渡会畸变。所以扩大skybox
  62398. let dis = pano0.position.distanceTo(pano1.position);
  62399. if(dis > 100){
  62400. let bound = pano0.pointcloud.bound.clone().union(pano1.pointcloud.bound);
  62401. let size = bound.getSize(new Vector3);
  62402. let max = Math.max(size.x, size.y, size.z);
  62403. size.set(max,max,max);
  62404. return useBound(bound, size)
  62405. }
  62406. }
  62407. const half = pano0.pointcloud.hasDepthTex && pano0.pointcloud.hasDepthTex ? 6 : (browser.isMobile() ? 2 : 3); //自行输入 (点云计算的慢,还不准)
  62408. let count1 = 2*half;//偶数个 每个pano向 外dir 个数
  62409. //奇数个的好处:在窄空间内能探测到最远距离,坏处是前方有尖角。偶数个的坏处就是可能检测距离太近。
  62410. //let panoIndex = 0
  62411. let getIntersect = (pano, dir, origin)=>{
  62412. if(pano && pano.pointcloud.hasDepthTex ){
  62413. return this.depthSampler.sample( {dir }, pano, true )
  62414. }else {
  62415. origin = origin || pano.position;
  62416. return viewer.inputHandler.getIntersect(viewer.inputHandler.hoverViewport, true, null, null, true, {
  62417. point: origin.clone().add(dir),
  62418. cameraPos: origin
  62419. })
  62420. }
  62421. };
  62422. let getDir = (angle_, vec)=>{ //旋转获得水平向量
  62423. let rotMat = new Matrix4().makeRotationZ(angle_);
  62424. return vec.clone().applyMatrix4(rotMat)
  62425. };
  62426. let getFar = (dir, pano, origin)=>{//获取在这个方向上和墙体intersect的距离
  62427. //在垂直方向上分出多个方向,取一个最可能的接近真实的距离
  62428. let dirs_ = [
  62429. //注意:角度太大会碰到天花板或地板,越远越容易碰到, 在地下停车场就会伸展不开。 户外时需要更多向上的方向,所以上方向多一个
  62430. dir.clone().setZ(Math.tan(MathUtils.degToRad(30))).normalize(),
  62431. dir.clone().setZ(Math.tan(MathUtils.degToRad(7))).normalize(),
  62432. dir.clone(), // 水平方向
  62433. dir.clone().setZ(-Math.tan(MathUtils.degToRad(5))).normalize(),
  62434. //dir.clone().setZ(-Math.tan(THREE.Math.degToRad(30))).normalize(),
  62435. ];
  62436. let max = 50;
  62437. let count2 = dirs_.length;
  62438. let disArr = dirs_.map((dir_, i) =>{
  62439. let intersect = getIntersect(pano, dir_, origin);
  62440. let projectLen = intersect && intersect.distance ? dir_.dot(dir)*intersect.distance : max; //得到project在dir的长度
  62441. return projectLen //得水平距离
  62442. });
  62443. disArr.sort((a,b)=>{return b-a}); //从大到小
  62444. //console.log(pano ? pano.id : 'side','disArr', disArr)
  62445. let dis = disArr[Math.floor(count2/2-0.5)]; //对半、取前(中位数)
  62446. return dis
  62447. };
  62448. let sideCount = [];
  62449. let addPos = (pano, vec )=>{//添加这个pano这一侧向外半圆的顶点
  62450. //添加pano位置对应的最高点最低点:
  62451. let minZ, maxZ;
  62452. minZ = pano.floorPosition.z;
  62453. if(pano.ceilZ != void 0){
  62454. maxZ = pano.ceilZ;
  62455. }else {//天花板高度值
  62456. //用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算)
  62457. let rotMat = new Matrix4().makeRotationX(MathUtils.degToRad(40));// 角度不能小于天花板中空的半径,大概就是0.2*Math.PI=36度
  62458. let dir1 = new Vector3(0,0,1).applyMatrix4(rotMat);
  62459. let rotMat1 = new Matrix4().makeRotationZ(Math.PI*2 / 3);
  62460. let rotMat2 = new Matrix4().makeRotationZ(-Math.PI*2 / 3);
  62461. let dir2 = dir1.clone().applyMatrix4(rotMat1);
  62462. let dir3 = dir1.clone().applyMatrix4(rotMat2);
  62463. let skyHeight = 50;
  62464. let zs = [dir1,dir2,dir3].map(dir_=>{
  62465. let intersect = getIntersect(pano, dir_);
  62466. let z = intersect ? intersect.location.z : pano.position.z+skyHeight; //没有intersect代表可能是天空
  62467. return z
  62468. });
  62469. zs.sort((a,b)=>{return b-a});//得最大值 (不用中位数的原因:在屋檐处,如果仅有一个intersect是天空,因到了室外所以也用天空高度)
  62470. maxZ = zs[0];
  62471. let min = pano.position.z + 1; // 防止意外太低
  62472. maxZ = Math.max(min,maxZ);
  62473. pano.ceilZ = maxZ;
  62474. //console.log(pano.id, 'maxZ:',maxZ )
  62475. //console.log(pano.id, 'minZ:',minZ )
  62476. }
  62477. [maxZ, minZ ].forEach(z=>{
  62478. posArr.push(pano.position.clone().setZ(z));
  62479. });
  62480. //在画面上线条从左往右数
  62481. const angle = Math.PI/(count1-1);
  62482. const dirs = []; //平分这半边180度
  62483. for(let i=0;i<count1;i++){
  62484. dirs.push(getDir(Math.PI/2-i*angle, vec));//正的在左边
  62485. }
  62486. // let sideDis = []
  62487. dirs.forEach((dir, index)=>{
  62488. let dis = getFar(dir, pano);
  62489. // if(index == 0 || index == count1-1){
  62490. // sideDis.push(dis)
  62491. // }
  62492. dir.multiplyScalar( dis );
  62493. [maxZ,minZ].forEach(z=>{
  62494. posArr.push(pano.position.clone().setZ(z).add(dir)); //获取到外墙点
  62495. });
  62496. });
  62497. //panoIndex ++
  62498. //return sideDis;
  62499. };
  62500. let addSide = ()=>{//两个漫游点间两边各加一些侧线
  62501. //中点处的
  62502. let midMaxZ = (pano0.ceilZ + pano1.ceilZ)/2;
  62503. let midMinZ = (pano0.floorPosition.z+pano1.floorPosition.z)/2;
  62504. let mid = new Vector3().addVectors(pano0.position, pano1.position).multiplyScalar(0.5);
  62505. /* let sideDis_ = [(sideDis0[0] + sideDis1[1])/2, (sideDis0[1] + sideDis1[0])/2];
  62506. let sideDis = [Math.min(sideDis0[0] , sideDis1[1]), Math.min(sideDis0[1] , sideDis1[0])]//
  62507. */
  62508. if(pano0.pointcloud.hasDepthTex && pano0.pointcloud.hasDepthTex){
  62509. let panos = [pano0,pano1];
  62510. let vecs = [vec.clone().negate(), vec];
  62511. let axis = [[-1,1],[1,-1]];
  62512. let dis2d = new Vector2$1().subVectors(pano0.position, pano1.position).length();//水平上的距离
  62513. let angles = [MathUtils.degToRad(40), MathUtils.degToRad(70)]; //正的在左边 尽量能够平分中间这段墙体
  62514. axis.forEach((axis_, index0)=>{
  62515. let disToSides = [];
  62516. let accordingPano = index0 == 0 ? pano0 : pano1; //根据离该点在vec方向上的距离顺序来存顶点
  62517. panos.forEach((pano,index)=>{
  62518. let dirs = [getDir(axis_[index]*angles[0], vecs[index]), getDir(axis_[index]*angles[1], vecs[index])];//一侧的若干角度
  62519. dirs.forEach((dir_,i)=>{
  62520. let dis1 = getFar(dir_, pano);
  62521. let disToPano2d = dis1 * Math.cos(angles[i]);
  62522. if(disToPano2d<dis2d){//超过的话都到另一半pano的半圆了,不计入
  62523. let disToSide = dis1 * Math.sin(angles[i]);
  62524. if(pano != accordingPano){
  62525. disToPano2d = dis2d - disToPano2d; //反一下
  62526. }
  62527. dir_.multiplyScalar( dis1 );
  62528. disToSides.push({disToSide,disToPano2d, pano, dir_});
  62529. }
  62530. });
  62531. });
  62532. sideCount[index0] = disToSides.length; //记录侧边个数
  62533. if(disToSides.length){
  62534. //disToSides.sort((a,b)=>{return b-a});//从大到小
  62535. //由距离accordingPano的近到远:
  62536. disToSides.sort((a,b)=>{return a.disToPano2d-b.disToPano2d});
  62537. //console.log('disToSides', index0, disToSides)
  62538. disToSides.forEach(e=>{//求z
  62539. let ratio = e.disToPano2d / dis2d;
  62540. let r = accordingPano == pano0 ? (1-ratio) : ratio;
  62541. let sideMaxZ_ = pano0.ceilZ * r + pano1.ceilZ * (1-r);
  62542. let sideMinZ_ = pano0.floorPosition.z * r + pano1.floorPosition.z * (1-r);
  62543. [sideMaxZ_,sideMinZ_].forEach(z=>{
  62544. posArr.push(e.pano.position.clone().setZ(z).add(e.dir_)); //是直接使用最长dis的那个intersect点好还是mid
  62545. });
  62546. });
  62547. }
  62548. });
  62549. }else {
  62550. //这段针对点云时,仅测试才会执行到
  62551. sideCount = [1,1];
  62552. let sideDirs = [getDir(Math.PI/2, vec), getDir(-Math.PI/2, vec)];
  62553. sideDirs.forEach((dir_ ,index)=>{
  62554. let dis = getFar(dir_, null, mid); //直接从中点求两侧的距离
  62555. dir_.multiplyScalar( /* Math.max( */dis/* , sideDis[index]) */ );
  62556. [midMaxZ,midMinZ].forEach(z=>{
  62557. posArr.push(mid.clone().setZ(z).add(dir_));
  62558. });
  62559. });
  62560. }
  62561. //中心:
  62562. [midMaxZ,midMinZ].forEach(z=>{
  62563. posArr.push(mid.clone().setZ(z));
  62564. });
  62565. };
  62566. //positions存放顺序:pano的每边的 zMax和zMin 、count1个dir的点 ;侧边的点 ;连接处顶底的中点
  62567. let addFaces = ()=>{
  62568. let getPI = function(index, posType, panoIndex){//获取顶点序号
  62569. return 2 + (count1*2 + 2 ) * panoIndex + index*2 + (posType == 'top' ? 0 : 1)
  62570. };
  62571. let getSidePI = function(index, posType, panoIndex){//获取侧边顶点序号
  62572. if(panoIndex == 1) index += sideCount[0];
  62573. return getPI(index, posType, 2)-2
  62574. };
  62575. let getPanoPI = function(posType, panoIndex){//获取pano处对应的点序号
  62576. return getPI(-1, posType, panoIndex)
  62577. };
  62578. let topCenter = posArr.length-2; //最后添加的两个中心点
  62579. let btmCenter = posArr.length-1;
  62580. for(let i=0;i<2;i++){
  62581. for(let index=1; index<count1; index++){
  62582. //pano外侧半圆围墙
  62583. faceArr.push([getPI(index,'top',i), getPI(index-1,'btm',i), getPI(index-1,'top',i)],//加入一块四方面
  62584. [getPI(index,'top',i), getPI(index,'btm',i), getPI(index-1,'btm',i)]);
  62585. faceArr.push([getPI(index,'top',i), getPI(index-1,'top',i), getPanoPI('top',i)]);//天花板扇形
  62586. faceArr.push([getPI(index,'btm',i), getPI(index-1,'btm',i), getPanoPI('btm',i)]);//地板扇形
  62587. }
  62588. let j = (i + 1) % 2; //另一个pano
  62589. //侧边
  62590. for(let u=0; u<=sideCount[i]; u++){
  62591. //侧边每个四方的左上右上左下右下四个点
  62592. let pLT = u == 0 ? getPI(0,'top',i) : getSidePI(u-1, 'top',i);
  62593. let pRT = u == sideCount[i] ? getPI(count1-1,'top',j) : getSidePI(u, 'top',i);
  62594. let pLB = u == 0 ? getPI(0,'btm',i) : getSidePI(u-1, 'btm',i);
  62595. let pRB = u == sideCount[i] ? getPI(count1-1,'btm',j) : getSidePI(u, 'btm',i);
  62596. faceArr.push([pLT,pLB,pRB],[pLT,pRB,pRT]);//外侧四方面
  62597. faceArr.push([pLT,topCenter,pRT] ,[pLB,btmCenter,pRB] );//顶部和底部到整体中心的扇形(由于点的顺序是根据和两个pano的距离,因此到中心的夹角并没按顺序排列,所以可能会重叠)
  62598. if(i==0){//只需要算一次
  62599. //顶部和底部中心与两个pano边构成的三角形
  62600. if(u == 0){
  62601. faceArr.push([pLT,getPI(count1-1,'top',i),topCenter],
  62602. [pLB,getPI(count1-1,'btm',i),btmCenter],
  62603. );
  62604. }
  62605. //不能用else 因为当length==0时u==0也==sideCount[i],此时就是要两个面
  62606. if(u == sideCount[i]){
  62607. faceArr.push([pRT,getPI(0,'top',j),topCenter],
  62608. [pRB,getPI(0,'btm',j),btmCenter],
  62609. );
  62610. }
  62611. }
  62612. }
  62613. }
  62614. };
  62615. let posArr = [];
  62616. let faceArr = [];
  62617. //两点连线的水平向量
  62618. let vec = new Vector3().subVectors(pano0.position, pano1.position).setZ(0).normalize();
  62619. /* let sideDis0 = */addPos(pano0, vec);
  62620. /* let sideDis1 = */addPos(pano1, vec.clone().negate());
  62621. addSide();
  62622. addFaces();
  62623. //MeshDraw.updateGeometry(this.cube.geometry, posArr, faceArr)
  62624. let geo = MeshDraw.createGeometry(posArr, faceArr);
  62625. this.cube.geometry = geo;
  62626. this.cube.scale.set(1,1,1);
  62627. this.cube.position.set(0,0,0);
  62628. //this.cube.scale.set(100,100,100);
  62629. //this.cube.position.copy(pano1.position).multiplyScalar(-100)
  62630. }else {
  62631. useBound(pano0.pointcloud.bound);
  62632. }
  62633. }
  62634. /*
  62635. 注: 修改skybox,若不准的话,会遮住其他mesh,比如marker。尤其在没有深度贴图时。
  62636. */
  62637. /* updateCube(params){
  62638. let size = params.boundSize
  62639. this.cube.scale.set(Math.max(size.x, HighMapCubeWidth), Math.max(size.y, HighMapCubeWidth), Math.max(size.z, HighMapCubeWidth) )
  62640. this.cube.position.copy(params.center)
  62641. } */
  62642. bump(direction) {//撞墙弹回效果
  62643. if (!this.bumping && !this.latestToPano) {
  62644. let distance = Potree.settings.displayMode == 'showPanos' ? 0.3 : 0.2;//感觉点云模式比全景模式更明显,所以降低
  62645. let currentPos = this.position.clone();
  62646. let endPosition = new Vector3().addVectors(this.position, direction.clone().multiplyScalar(distance));
  62647. let duration = 150;
  62648. viewer.scene.view.setView({position:endPosition, duration,
  62649. callback:()=>{
  62650. viewer.scene.view.setView({position:currentPos, duration: duration*5,
  62651. callback: ()=>{
  62652. this.bumping = false;
  62653. //this.dispatchEvent('cameraMoveDone')
  62654. },
  62655. Easing:'easeInOutSine',
  62656. cancelFun:()=>{this.bumping = false;}
  62657. });
  62658. this.bumping = true;
  62659. },
  62660. cancelFun:()=>{this.bumping = false;},
  62661. Easing:'easeInOutSine'
  62662. });
  62663. this.bumping = true;
  62664. }
  62665. //备注:将4dkk中的‘前后方向变化fov、左右方向移动镜头’ 都改为移动镜头。 因为这里无法判断左右离壁距离。
  62666. }
  62667. /* load(pano, ){
  62668. return new Promise(resolve => {
  62669. let texture = texLoader.load(pano.file, resolve);
  62670. texture.wrapS = THREE.RepeatWrapping;
  62671. texture.repeat.x = -1;
  62672. texture.flipY = false//add
  62673. pano.texture = texture;
  62674. //add
  62675. texture.wrapS = texture.wrapT = THREE.ClampToEdgeWrapping;
  62676. texture.minFilter = THREE.LinearFilter;
  62677. texture.magFilter = THREE.LinearFilter;
  62678. texture.generateMipmaps = true;
  62679. });
  62680. } */
  62681. flyToPanoClosestToMouse() {
  62682. /* if (Date.now() - this.mouseLastMoveTime > 50) {
  62683. //this.intersect = this.getMouseIntersect();
  62684. this.intersect && this.updateClosestPano(this.intersect);
  62685. } */
  62686. if(!Potree.settings.ifShowMarker){//不显示marker的时候mousemove没更新鼠标最近点所以更新
  62687. this.updateClosestPano(viewer.inputHandler.intersectPoint);
  62688. }
  62689. //console.log('flyToPanoClosestToMouse',this.closestPano)
  62690. if (this.closestPano) {
  62691. let pano = this.closestPano;
  62692. return this.flyToPano({
  62693. pano
  62694. });
  62695. }
  62696. var direction = this.viewer.inputHandler.getMouseDirection().direction;
  62697. this.flyDirection(direction);
  62698. }
  62699. flyDirection(direction, option1, option2) {
  62700. var deferred = $.Deferred();
  62701. //this.history.invalidate();
  62702. var panoSet = this.closestPanoInDirection(direction, option1, option2);
  62703. if (panoSet) {
  62704. this.flyToPano({
  62705. pano: panoSet,
  62706. callback: deferred.resolve.bind(deferred, !0)
  62707. } );
  62708. } else {
  62709. this.bump(direction);
  62710. deferred.resolve(!1);
  62711. }
  62712. return deferred.promise();
  62713. }
  62714. closestPanoInDirection(direction, option1, option2) {
  62715. return this.rankedPanoInDirection(0, direction, option1, option2)
  62716. }
  62717. rankedPanoInDirection(t, direction, option1, option2){
  62718. var panoSet = {
  62719. pano: null,
  62720. candidates: [] //缓存顺序--如果需要打印的话
  62721. };
  62722. t || (t = 0);
  62723. option1 = void 0 !== option1 ? option1 : .75;
  62724. var o = option2 ? "angle" : "direction";
  62725. var floor = viewer.modules.SiteModel.currentFloor;
  62726. var entity = viewer.modules.SiteModel.inEntity;
  62727. var getHeightDis = (pano)=>{
  62728. if(floor && !floor.panos.includes(pano) && pano.position.z < this.position.z){ //若是上方的漫游点,就正常走。因为一般不会点击天花板。
  62729. return this.position.z - pano.position.z
  62730. }else {
  62731. return 0
  62732. }
  62733. };
  62734. var request = [//必要条件
  62735. Images360.filters.inPanoDirection( this.position, direction, option1),
  62736. //Images360.filters.isNeighbourPanoTo(this.currentPano),
  62737. Images360.filters.not(this.currentPano),
  62738. Images360.filters.isEnabled(),
  62739. /* (pano)=>{ //防止不小心穿越地板到下一层, 尽量走楼梯,实在没有楼梯或楼梯漫游点稀疏的话就通过楼层按钮。
  62740. let dis = getHeightDis(pano)
  62741. //console.log('getHeightDis',pano.id,dis)
  62742. if(dis < 3){//不能超过最大高度差( 最大高度差暂定为接近一层楼的高度。)(最好的解决方案是设置漫游可行)
  62743. return true
  62744. }else{
  62745. return this.isNeighbour(this.currentPano, pano)
  62746. }
  62747. } */
  62748. ];
  62749. var list = [//决胜项目
  62750. Images360.scoreFunctions.distanceSquared(this.position,1, true),
  62751. Images360.scoreFunctions[o]( this.position, direction,true),
  62752. (pano)=>{
  62753. let neighbour = this.isNeighbour(this.currentPano, pano);
  62754. //console.log('neighbour', pano.id, neighbour ? directionFactor*0.4 : 0)
  62755. return neighbour ? directionFactor*1 : 0;
  62756. }
  62757. /* (pano)=>{//尽量不穿越地板到下一层
  62758. let dis = getHeightDis(pano)
  62759. return -dis * directionFactor * 0.1;
  62760. }, */
  62761. /* (pano)=>{ //尽量在一个建筑内行走,这样不易穿墙
  62762. if(entity && !entity.panos.includes(pano) ){
  62763. return - directionFactor * 0.05; //- directionFactor * 0.2;
  62764. }else{ //不能设置太高,否则会走不进大房间的小房间中,因为容易穿过小房间的一个门到另一个门外
  62765. return 0
  62766. }
  62767. } */
  62768. ];
  62769. if(viewer.inputHandler.intersectPoint && this.currentPano ){//方便上下楼, 考虑panos之间的角度差
  62770. let pos1 = this.currentPano.floorPosition;
  62771. let vec1 = new Vector3().subVectors(viewer.inputHandler.intersectPoint.location, pos1 ).normalize();//应该只有atPano时才会执行到这吧?
  62772. list.push( function(pano) {
  62773. var pos2 = pano.floorPosition;
  62774. var vec2 = pos2.clone().sub(pos1).normalize();
  62775. //console.log('direction2', pano.id, vec2.dot(vec1) * directionFactor * 1 );
  62776. return vec2.dot(vec1) * directionFactor * 1
  62777. });
  62778. }
  62779. this.findRankedByScore(t,request,list,panoSet);
  62780. return panoSet.pano;
  62781. }
  62782. findRankedByScore(e, t, i, n) {
  62783. n && (n.candidates = null, //candidates 缓存顺序--如果需要打印的话
  62784. n.pano = null),
  62785. e || (e = 0);
  62786. var r = Common.sortByScore(this.panos, t, i);
  62787. //console.log('findRankedByScore', r && r.map(u=>u.item.id + '|' + u.score))
  62788. return !r || 0 === r.length || e >= r.length ? null : (n && (n.candidates = r,
  62789. n.pano = r[e].item),
  62790. r[e].item)
  62791. }
  62792. isNeighbour(pano0, pano1){//是否之间没有遮挡(在加载visibles之前,自己算) 最好pano0是currentPano
  62793. if(!pano0 || !pano1)return
  62794. let map0 = this.neighbourMap[pano0.id];
  62795. if(!map0){
  62796. map0 = {};
  62797. this.neighbourMap[pano0.id] = map0;
  62798. }
  62799. let map1 = this.neighbourMap[pano1.id];
  62800. if(!map1){
  62801. map1 = {};
  62802. this.neighbourMap[pano1.id] = map1;
  62803. }
  62804. let ifNeighbour = map0[pano1.id];//map0.get(pano1)
  62805. if(ifNeighbour == void 0){
  62806. ifNeighbour = true;
  62807. let margin = 0.1;
  62808. let usePointcloud = pano0.depthTex;
  62809. if(pano0.depthTex || pano1.depthTex){
  62810. let mainPano = pano0.depthTex ? pano0 : pano1;
  62811. let subPano = pano0.depthTex ? pano1 : pano0;
  62812. //暂时只判断到pano,不判断到marker的方向
  62813. let dir = new Vector3().subVectors(subPano.position, mainPano.position).normalize();
  62814. let intersectPoint = viewer.images360.depthSampler.sample({dir}, mainPano, true);
  62815. if(intersectPoint && intersectPoint.distance+margin <= pano0.position.distanceTo(pano1.position)){
  62816. ifNeighbour = false;
  62817. }
  62818. }else {
  62819. //使用点云判断(有深度贴图时不会执行到这)
  62820. ifNeighbour = !viewer.inputHandler.ifBlockedByIntersect(pano1.position, margin, true, pano0.position);
  62821. console.log('使用点云判断');
  62822. if(ifNeighbour){//点云模式下未加载的点云会判断为true
  62823. let dir = new Vector3().subVectors(pano1.position,pano0.position).normalize();
  62824. let dis = pano1.position.distanceTo(pano0.position);
  62825. let hfov = cameraLight.getHFOVForCamera(viewer.mainViewport.camera , true );
  62826. let max = Math.cos(MathUtils.degToRad(10));
  62827. let min = Math.cos(MathUtils.degToRad(80));
  62828. if(this.getDirection().dot(dir) < MathUtils.clamp(Math.cos(hfov/2/* THREE.Math.degToRad(40) */) * dis / 10, min, max )){//距离越远要求和视线角度越接近
  62829. ifNeighbour = undefined; //不确定
  62830. }
  62831. }
  62832. }
  62833. map0[pano1.id] = ifNeighbour;//map0.set(pano1, ifNeighbour)
  62834. map1[pano0.id] = ifNeighbour;//map1.set(pano0, ifNeighbour)
  62835. }
  62836. return ifNeighbour
  62837. }
  62838. updateClosestPano(intersect, state) {//hover到的pano 大多数时候是null
  62839. /* if(this.isAtPano() ){
  62840. filterFuncs.push(Images360.filters.not(this.currentPano));
  62841. //当静止在漫游点时closestPano只限制在每个漫游点附近,而在观看整个模型时,范围夸大,识别为离鼠标最近的漫游点。 (故而要排除flying时)
  62842. filterFuncs.push(Images360.filters.inFloorDirection(this.position, viewer.scene.view.direction, .25))//许钟文改
  62843. filterFuncs.push(Images360.filters.isCloseEnoughTo(intersect, 0.35));
  62844. filterFuncs.push(Images360.filters.isEnabled())
  62845. }else{
  62846. } */
  62847. var pano;
  62848. if(this.isAtPano() ){
  62849. if(intersect instanceof Panorama){
  62850. pano = state ? intersect : null;
  62851. }else {
  62852. return
  62853. }
  62854. }else {
  62855. if(this.flying)return;
  62856. var filterFuncs = [];
  62857. intersect = intersect && intersect.location;
  62858. if(!intersect)return
  62859. let sortFuncs = Potree.settings.editType != 'pano'? [Images360.sortFunctions.floorDisSquaredToPoint(intersect)] : [Images360.sortFunctions.disSquaredToPoint(intersect)];
  62860. pano = Common.find(this.panos, filterFuncs, sortFuncs);
  62861. }
  62862. if (pano != this.closestPano) {
  62863. pano && (this.isPanoHover = !0);
  62864. this.closestPanoChanging(this.closestPano, pano); // 高亮marker
  62865. //console.log('closestPano '+ (pano ? pano.id : 'null' ))
  62866. this.closestPano = pano;
  62867. } else {
  62868. this.isPanoHover = !1;
  62869. }
  62870. }
  62871. closestPanoChanging(oldPano, newPano){
  62872. if(!Potree.settings.ifShowMarker)return
  62873. oldPano && oldPano.hoverOff({byImages360:true});
  62874. newPano && newPano.hoverOn({byImages360:true});
  62875. }
  62876. getTileDirection(){//根据不同dataset的来存储
  62877. var vectorForward = viewer.scene.view.direction.clone();
  62878. var vectorForwards = viewer.scene.pointclouds.map(e=>{
  62879. var inv = new Matrix4().copy(e.rotateMatrix).invert();//乘上dataset的旋转的反转
  62880. var direction = vectorForward.clone().applyMatrix4(inv);
  62881. return {
  62882. datasetId: e.dataset_id,
  62883. direction: math.convertVector.ZupToYup(direction)
  62884. }
  62885. });
  62886. //return vectorForwards[0].direction
  62887. return {
  62888. datasetsLocal: vectorForwards,
  62889. vectorForward
  62890. }
  62891. }
  62892. update(){
  62893. let {viewer} = this;
  62894. /* if(currentlyHovered){
  62895. currentlyHovered.material = sm;
  62896. currentlyHovered = null;
  62897. }
  62898. if(this.selectingEnabled){
  62899. this.handleHovering();
  62900. } */
  62901. if(this.tileDownloader.started){
  62902. var vectorForwards = this.getTileDirection();
  62903. //vectorForwards = vectorForwards[0].direction
  62904. this.updateTileDownloader(tileArr, vectorForwards);
  62905. this.updatePanoRenderer(vectorForwards);
  62906. }
  62907. this.updateZoomPano();
  62908. }
  62909. updateTileDownloader(t, vectorForward) {
  62910. var i = this.nextPano || this.currentPano;
  62911. if(i){
  62912. this.tileDownloader.tilePrioritizer.updateCriteria(i, viewer.scene.view.position.clone() , vectorForward, t.length > 0 ? t : null),
  62913. this.tileDownloader.processPriorityQueue = !0;
  62914. }
  62915. }
  62916. updatePanoRenderer(vectorForward) {
  62917. var i = this.nextPano || this.currentPano;
  62918. if(i){
  62919. if (this.panoRenderer.hasQueuedTiles() && i) {
  62920. this.panoRenderer.updateDirection(vectorForward);
  62921. }
  62922. }
  62923. }
  62924. //等待部分加载完
  62925. checkAndWaitForTiledPanoLoad(pano, basePanoSize, callback1, callback2, progressCallback, iswait, isclear, l) {
  62926. if (!pano) {
  62927. console.error("Player.checkAndWaitForTiledPanoLoad() -> Cannot load texture for null pano.");
  62928. }
  62929. var vectorForward = this.getTileDirection();
  62930. if (!pano.isLoaded(basePanoSize)) {
  62931. iswait && viewer.waitForLoad(pano, function() {//发送loading
  62932. return pano.isLoaded(basePanoSize)
  62933. });
  62934. /* var fov = {//test for direction 预加载的边缘有一丢丢不准确,尤其在相机倾斜时(4dkk也是)。
  62935. hFov: cameraLight.getHFOVForCamera(viewer.scene.getActiveCamera() ),
  62936. vFov: viewer.scene.getActiveCamera().fov
  62937. }//原先是null,不要求方向 */
  62938. var fov = null; //若不为null的话,因为可能可见范围的tile下载过了从而无法触发下载,然后得不到下载成功的消息,怎么办
  62939. pano.loadTiledPano(/* 1024 */ basePanoSize , vectorForward, fov, isclear, l, null).done(function(e, t) {
  62940. callback1 && callback1(e, t);
  62941. }
  62942. .bind(this)).fail(function(msg) {
  62943. callback2 && callback2(msg);
  62944. }
  62945. .bind(this)).progress(function(e, t, i) {
  62946. progressCallback && progressCallback(e, t, i);
  62947. }
  62948. .bind(this));
  62949. return !0;
  62950. }
  62951. }
  62952. /* load(){//quickstart里的
  62953. var lowSize = this.qualityManager.getPanoSize(PanoSizeClass.BASE),
  62954. highSize = this.qualityManager.getPanoSize(PanoSizeClass.STANDARD),
  62955. d = cameraLight.getHFOVForCamera(this.quickStartcamera, $('#player').width(), $('#player').height()),
  62956. p = this.quickStartcamera.fov,
  62957. r = Vectors.FORWARD.clone().applyQuaternion(this.view.quaternion)
  62958. var promise1 = this.view.pano.loadTiledPano(highSize, r, {
  62959. hFov: d,
  62960. vFov: p
  62961. }, !1, !1 , !0 )
  62962. var promise2 = this.view.pano.loadTiledPano(lowSize, r.clone().negate(), null, !1, !1, !0)
  62963. this.loadPromise = this.pano.hasVideo ? promise2 : promise1;
  62964. //this.loadPromise = promise1;
  62965. }
  62966. */
  62967. fitPanoTowardPoint(o){ //寻找最适合的点位
  62968. var point = o.point, //相机最佳位置
  62969. target = o.target, //实际要看的位置
  62970. require = o.require || [],
  62971. rank = o.rank || [],
  62972. force = o.force,
  62973. getAll = o.getAll,
  62974. bestDistance = o.bestDistance || 0;
  62975. let camera = viewer.scene.getActiveCamera();
  62976. if(target){
  62977. var vec = new Vector3().subVectors(target,point).normalize();
  62978. }
  62979. //if(o.floor)require.push(Panorama.filters.atFloor(o.floor))
  62980. if(o.boundSphere){//只接受boundSphere
  62981. let aspect = 1;//size.x / size.y
  62982. let dis;
  62983. if(camera.aspect > aspect){//视野更宽则用bound的纵向来决定
  62984. dis = /* size.y */o.boundSphere.radius/* / 2 *// MathUtils.degToRad(camera.fov / 2);
  62985. }else {
  62986. let hfov = cameraLight.getHFOVForCamera(camera , true );
  62987. dis = /* size.x */ o.boundSphere.radius /* / 2 */ / (hfov / 2);
  62988. }
  62989. bestDistance = dis;//*0.8
  62990. }
  62991. let bestDisSquared = bestDistance * bestDistance;
  62992. rank.push((pano)=>{
  62993. let dis1 = Math.abs(pano.position.distanceToSquared(point) - bestDisSquared); //距离最佳位置
  62994. if(!target){
  62995. return -dis1
  62996. }else {
  62997. let dis2 = pano.position.distanceToSquared(target); //距离目标点
  62998. let vec2 = new Vector3().subVectors(target,pano.position).normalize();
  62999. let cos = vec.dot(vec2);
  63000. let result = (- dis1 - Math.pow(dis2 , 1.5)) / (cos + 2); // cos+2是为了调整到1-3, 尽量贴近最佳位置的角度;
  63001. //console.log(pano.id, dis1,dis2, cos, result)
  63002. return result
  63003. }
  63004. },(pano)=>{
  63005. if(pano.depthTex && o.checkIntersect){ //没加载好的话,不管了
  63006. let intersect = viewer.inputHandler.ifBlockedByIntersect(target, 0.1 , null, null, null, pano);
  63007. if(intersect){
  63008. //console.log('intersected', pano.id )
  63009. return -10000
  63010. }else return 0
  63011. }else return 0
  63012. });
  63013. /* var temp = {position:point}
  63014. rank.push(Panorama.scoreFunctions.distanceSquared(temp, -2)); */
  63015. var g = Common.sortByScore(this.panos, require, rank);
  63016. if(getAll)return g;
  63017. return g && g.length > 0 && g[0].item
  63018. }
  63019. //---------------scroll zoom ------------------------------------------
  63020. /* zoomIn = function() { //放大
  63021. this.zoomBy(1 + this.zoomSpeed);
  63022. }
  63023. zoomOut = function() {//缩小
  63024. this.zoomBy(1 - this.zoomSpeed);
  63025. } */
  63026. zoomBy(e, pointer) {//以倍数
  63027. this.zoomTo(this.zoomLevel * e, pointer);
  63028. }
  63029. zoomTo(zoomLevel, pointer) {//缩放到某绝对zoomLevel
  63030. let zoom = Potree.settings.zoom;
  63031. if (zoom.enabled) {
  63032. zoomLevel = MathUtils.clamp(zoomLevel, zoom.min, zoom.max);
  63033. //console.log(zoomLevel)
  63034. if(zoomLevel == this.zoomLevel) return;
  63035. /* if (zoomLevel > this.zoomLevel) {
  63036. this.emit(ZoomEvents.ZoomIn);
  63037. zoomLevel === settings.zoom.max && this.emit(ZoomEvents.ZoomMax);
  63038. } else if (zoomLevel < this.zoomLevel) {
  63039. this.emit(ZoomEvents.ZoomOut);
  63040. zoomLevel === settings.zoom.min && this.emit(ZoomEvents.ZoomMin);
  63041. } */
  63042. this.zoomLevel = zoomLevel;
  63043. //定点缩放:使当前鼠标所在的位置缩放后不变
  63044. let view = viewer.scene.view;
  63045. let originDir = viewer.scene.view.direction;
  63046. let oldPointerDir = viewer.inputHandler.getMouseDirection(pointer).direction;
  63047. viewer.setFOV(Potree.config.view.fov * (1 / this.zoomLevel));
  63048. let newPointerDir = viewer.inputHandler.getMouseDirection(pointer).direction;
  63049. view.direction = oldPointerDir; //获取一下鼠标所在位置的yaw 和 pitch
  63050. let oldPitch = view.pitch, oldYaw = view.yaw;
  63051. view.direction = newPointerDir;
  63052. let newPitch = view.pitch, newYaw = view.yaw;
  63053. view.direction = originDir; //还原
  63054. viewer.scene.view.pitch -= newPitch - oldPitch;
  63055. viewer.scene.view.yaw -= newYaw - oldYaw;
  63056. }
  63057. }
  63058. zoomFovTo( fov ) { //通过fov来算zoomLevel
  63059. let zoomLevel = this.baseFov / fov;
  63060. this.zoomTo( zoomLevel );
  63061. }
  63062. smoothZoomTo(aimLevel, dur=0) {
  63063. var currentLevel = this.zoomLevel;
  63064. if(currentLevel == aimLevel)return;
  63065. var fun = (progress)=>{
  63066. //progress > 1 && (progress = 1)
  63067. let level = currentLevel * (1 - progress) + aimLevel * progress;
  63068. this.zoomTo(level, !0);
  63069. };
  63070. transitions.start(fun, dur, null, null, 0 , easing['easeInOutQuad'] );
  63071. }
  63072. /* zoomDefault{
  63073. this.zoomTo(1, !0)
  63074. }
  63075. smoothZoomToDefault(e, t) {
  63076. var i, n = this.zoomLevel,
  63077. r = function(e) {
  63078. e > 1 && (e = 1),
  63079. i = n * (1 - e) + e,
  63080. this.zoomTo(i, !0)
  63081. }
  63082. .bind(this),
  63083. o = function() {
  63084. this.zoomDefault(),
  63085. t && window.setTimeout(t, 50)
  63086. }
  63087. .bind(this);
  63088. transitions.start(r, e, o, null, 0, easing[settings.transition.blendEasing])
  63089. } */
  63090. updateZoomPano() {
  63091. if (!this.panoRenderer.zoomPanoRenderingDisabled && Potree.settings.displayMode == 'showPanos') {
  63092. var currentPano = this.currentPano;
  63093. if (currentPano) {
  63094. var activationThreshold = Potree.settings.navTileClass == '2k' && Potree.settings.tileClass == '4k' ? 1.7 : Potree.settings.zoom.activationThreshold;//1.1
  63095. var t = this.zoomLevel > activationThreshold,
  63096. n = !(this.flying && this.nextPano && this.nextPano !== this.currentPano),
  63097. r = t && n;
  63098. this.tileDownloader.tilePrioritizer.setZoomingActive(r);
  63099. this.panoRenderer.setZoomingActive(r, currentPano, !0);
  63100. var o = (pano, zoomedFlag)=>{
  63101. this.panoRenderer.resetRenderStatus(pano.id, !1, !0, this.qualityManager.getMaxNavPanoSize());
  63102. this.panoRenderer.clearAllQueuedUploadsForPano(pano.id);
  63103. this.panoRenderer.renderPanoTiles(pano.id, null, !1, !1);
  63104. pano.setZoomed(zoomedFlag);
  63105. };
  63106. if (r && (!currentPano.zoomed || this.qualityManager.zoomLevelResolution && this.qualityManager.zoomLevelResolution != '4k')) {
  63107. currentPano.zoomed || o(currentPano, !0);
  63108. if(Potree.settings.navTileClass == '1k' && Potree.settings.tileClass != '1k' && this.zoomLevel < 2){
  63109. this.panoRenderer.enableHighQuality( function() {//开启2k
  63110. if(Potree.settings.tileClass != '4k') o(currentPano, !0);
  63111. }.bind(this));
  63112. }else {
  63113. this.panoRenderer.enableUltraHighQualityMode(function() {//开启4k getMaxZoomPanoSize
  63114. this.qualityManager.useUltraHighResolutionPanos && (Potree.settings.zoom.max = Potree.config.ultraHighQualityMaxZoom);
  63115. o(currentPano, !0);
  63116. }.bind(this));
  63117. }
  63118. } else {
  63119. !t && currentPano.zoomed && o(currentPano, !1);
  63120. }
  63121. if(r && Potree.settings.navTileClass == '1k' && Potree.settings.tileClass == '4k' ){ //目前只有手机端navTileClass == '1k'
  63122. var change = (zoomedFlag)=>{
  63123. this.qualityManager.updateMaximums();//更新maxZoomPanoSize
  63124. this.panoRenderer.setupZoomRenderTarget(); //更新renderTarget
  63125. //currentPano.setZoomed(t);//更新uniforms贴图
  63126. };
  63127. this.qualityManager.zoomLevelResolution = this.zoomLevel >= 2 ? '4k' : this.zoomLevel > 1.1 ? '2k' : '1k';
  63128. if(this.oldZoomLevel < 2 && this.zoomLevel >= 2){//1k/2k-4k
  63129. change();
  63130. o(currentPano, t);
  63131. }else if(this.oldZoomLevel <= Potree.settings.zoom.activationThreshold && this.zoomLevel > Potree.settings.zoom.activationThreshold){//1k-2k
  63132. change();
  63133. }else if(this.oldZoomLevel > 2 && this.zoomLevel <= 2){//4k-2k/1k
  63134. change();
  63135. o(currentPano, t);
  63136. }else if(this.oldZoomLevel > Potree.settings.zoom.activationThreshold && this.zoomLevel <= Potree.settings.zoom.activationThreshold){//2k-1k
  63137. change();
  63138. }
  63139. this.oldZoomLevel = this.zoomLevel;
  63140. }
  63141. }
  63142. }
  63143. }
  63144. //--------------------
  63145. addHighMapCube(){//创建8*8的tile cube 主要因手机版崩溃 要在电脑端测试得设置maxRenderTargetSize
  63146. if( Potree.settings.tileClass == '4k' && this.qualityManager.maxRenderTargetSize == 2048){
  63147. var geo = new PlaneGeometry(1, 1, 1, 1);
  63148. var cube = new Object3D;
  63149. for(var cubeIndex=0; cubeIndex<6; cubeIndex++){
  63150. var face = new Object3D;
  63151. for(var i=0;i<8;i++){
  63152. for(var j=0;j<8;j++){
  63153. var tile = new Mesh(geo, new MeshBasicMaterial({
  63154. //side:THREE.DoubleSide
  63155. }));
  63156. tile.position.set(i-3.5, j-3.5, -4);
  63157. tile.material.opacity = 0.4;
  63158. tile.material.transparent = true;
  63159. if(Potree.settings.isTest){
  63160. var colorHue = Math.random();
  63161. tile.material.color = (new Color()).setHSL(colorHue, 0.5, 0.9);
  63162. }
  63163. tile.visible = false;
  63164. face.add(tile);
  63165. }
  63166. }
  63167. switch(cubeIndex){
  63168. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  63169. face.rotation.set(0,Math.PI/2,0);
  63170. break;
  63171. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  63172. face.rotation.set(0,-Math.PI/2,0);
  63173. break;
  63174. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
  63175. var rot1 = new Quaternion().setFromAxisAngle(new Vector3(0,1,0),Math.PI);
  63176. var rot2 = new Quaternion().setFromAxisAngle(new Vector3(1,0,0),Math.PI/2);
  63177. face.quaternion.copy(rot1).multiply(rot2);
  63178. //face.rotation.set(Math.PI/2,0,0);
  63179. break;
  63180. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  63181. //face.rotation.set(-Math.PI/2,0,0);
  63182. var rot1 = new Quaternion().setFromAxisAngle(new Vector3(0,1,0),Math.PI);
  63183. var rot2 = new Quaternion().setFromAxisAngle(new Vector3(1,0,0),-Math.PI/2);
  63184. face.quaternion.copy(rot1).multiply(rot2);
  63185. break;
  63186. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  63187. face.rotation.set(0,Math.PI,0);
  63188. break;
  63189. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  63190. face.rotation.set(0,0,0);
  63191. }
  63192. face.scale.set(1,-1,1);
  63193. cube.add(face);
  63194. }
  63195. cube.name = 'highMapCube';
  63196. this.highMapCube = cube;
  63197. viewer.scene.scene.add(cube);
  63198. //cube.scale.set(0.01,0.01,0.01)
  63199. this.highMapCube.visible = false;
  63200. viewer.setObjectLayers(this.highMapCube, 'sceneObjects'/* 'skybox' */); //如果是skybox层,点云可见时会被遮住,depthTest为false呢? 但不会遮住场景物体
  63201. //console.warn('addHighMapCube')
  63202. }
  63203. }
  63204. isHighMapLoaded( cubeFace, tileX, tileY){
  63205. var tile = this.highMapCube.children[cubeFace].children[tileX*8+tileY];
  63206. return !!tile.material.map
  63207. }
  63208. updateHighMap(tex, cubeFace, tileX, tileY){
  63209. //console.warn('updateHighMap')
  63210. var tile = this.highMapCube.children[cubeFace].children[tileX*8+tileY];
  63211. tile.material.map = tex;
  63212. tile.material.opacity = 1;
  63213. tile.material.transparent = false;
  63214. tile.visible = true;
  63215. tile.material.needsUpdate = true; //发现每次开始放大但还未放大到4k时也会把之前加载过的4k加载
  63216. }
  63217. resetHighMap(){
  63218. if(!this.highMapCube) return
  63219. //console.warn('resetHighMap')
  63220. this.highMapCube.children.forEach(e=>e.children.forEach(tile=>{
  63221. if(tile.material.map){
  63222. tile.material.map.dispose();
  63223. tile.material.map.loaded = !1;
  63224. tile.material.map.version = 0;
  63225. var h = viewer.renderer.properties.get(tile.material.map);
  63226. viewer.renderer.getContext().deleteTexture(h.__webglTexture);
  63227. //类似app.sceneRenderer.deallocateCubeTexture(tile.material.map)
  63228. tile.material.map = null;
  63229. /* tile.material.opacity = 0.4;
  63230. tile.material.transparent = true */
  63231. tile.material.needsUpdate = true;
  63232. tile.visible = false;
  63233. }
  63234. }));
  63235. this.highMapCube.visible = false;
  63236. }
  63237. setHighMap(pano){
  63238. if(!this.highMapCube) return
  63239. this.highMapCube.position.copy(pano.position);
  63240. //可以利用第0个pano查看,其 rotation4dkk是(_x: 0, _y: -1.5707963267948966, _z: 0 )而手动旋转至(_x:1.5707963, _y: -1.57079, _z: 0)时才正确,说明要在4dkk的旋转基础上,绕x轴转90度,(也就是转成navvis坐标系), 然后得到YupToZup的函数写法的
  63241. this.highMapCube.quaternion.copy( math.convertQuaternion.YupToZup( pano.quaternion4dkk ) );
  63242. //乘上数据集整体的旋转:
  63243. let modelRotQua = new Quaternion().setFromRotationMatrix(pano.pointcloud.rotateMatrix);
  63244. this.highMapCube.quaternion.premultiply(modelRotQua);
  63245. }
  63246. showHighMap(){
  63247. if(!this.highMapCube) return
  63248. //console.warn('showHighMap')
  63249. this.highMapCube.visible = true;
  63250. }
  63251. hideHighMap(){
  63252. if(!this.highMapCube) return
  63253. //console.warn('hideHighMap')
  63254. this.highMapCube.visible = false;
  63255. }
  63256. //缩小后继续显示cube呢还是不显示? 不显示的话,就要把cube上的复制到renderTarget上……会不会又崩溃,or没加载的显示???
  63257. addPanoData(data, datasetId ){
  63258. //data[0].file_id = '00019'
  63259. if(data.data) data = data.data;
  63260. if(data.length == 0)console.error(datasetId + ' 没有漫游点');
  63261. //data = data.sort(function(a,b){return a.id-b.id})
  63262. data.forEach((info)=>{
  63263. //if(Potree.fileServer){
  63264. info.id = this.panos.length; //把info的id的一长串数字改简单点
  63265. //}
  63266. let pano = new Panorama( info, this );
  63267. /* pano.mesh.layers.set(Potree.config.renderLayers.marker)
  63268. pano.marker.layers.set(Potree.config.renderLayers.marker) */
  63269. pano.addEventListener('dispose',(e)=>{
  63270. if(this.closestPano == pano) this.closestPano = null;
  63271. });
  63272. this.panos.push(pano);
  63273. if(Potree.settings.editType == 'pano'){
  63274. Potree.settings.datasetsPanos[datasetId].panos.push(pano);
  63275. }
  63276. });
  63277. }
  63278. loadDone(){
  63279. viewer.setObjectLayers(this.node, 'sceneObjects');
  63280. //this.updateCube(/* viewer.bound */)
  63281. this.panos.forEach(e=>{
  63282. e.label && viewer.setObjectLayers(e.label, 'bothMapAndScene');
  63283. });
  63284. this.tileDownloader.setPanoData(this.panos, [] /* , Potree.settings.number */);
  63285. {
  63286. /* var panosBound = new THREE.Box3
  63287. this.panos.forEach(pano=>{
  63288. panosBound.expandByPoint(pano.position)
  63289. })
  63290. let center = panosBound.getCenter(new THREE.Vector3)
  63291. let minBound = (new THREE.Box3()).setFromCenterAndSize(center, new THREE.Vector3(1,1,1))
  63292. panosBound.union(minBound)
  63293. this.bound = {
  63294. bounding:panosBound,
  63295. size: panosBound.getSize(new THREE.Vector3),
  63296. center,
  63297. } */
  63298. let minSize = new Vector3(1,1,1);
  63299. this.bound = math.getBoundByPoints(this.panos.map(e=>e.position), minSize);
  63300. viewer.scene.pointclouds.forEach(pointcloud=>pointcloud.getPanosBound());
  63301. }
  63302. if(viewer.scene.pointclouds.some(e=>e.panos.length == 0)){
  63303. //console.warn('存在数据集没有pano');
  63304. viewer.hasNoPanoDataset = true;
  63305. }
  63306. }
  63307. getPano(value, typeName='id'){ //默认找的是id,也可以是sid、uuid
  63308. return this.panos.find(p=>p[typeName] == value)
  63309. }
  63310. };
  63311. //判断当前点是否加载了全景图
  63312. Images360.prototype.checkAndWaitForPanoLoad = function() {
  63313. var isLoadedPanos = {},
  63314. LoadedTimePanos = {},
  63315. loadedCallback = {}, //add
  63316. maxTime = 5e3;
  63317. var withinTime = function() {
  63318. for (var panoId in isLoadedPanos)
  63319. if (isLoadedPanos.hasOwnProperty(panoId) && isLoadedPanos[panoId]) {
  63320. var differTime = performance.now() - LoadedTimePanos[panoId];
  63321. if (differTime < maxTime)
  63322. return !0
  63323. }
  63324. return !1
  63325. };
  63326. return function(pano, basePanoSize, doneFun1, doneFun2, progressCallback, iswait, isclear, p ) {
  63327. loadedCallback[pano.id] = doneFun1;//add 因为有可能之前请求的没加doneFun1, 如果加载好就执行最新的doneFun1
  63328. if (withinTime()){//距离上次请求时间很近
  63329. return !0; //这里感觉应该是!1
  63330. }
  63331. var callback1 = (param1, param2)=>{
  63332. setTimeout(()=>{
  63333. isLoadedPanos[pano.id] = !1;
  63334. loadedCallback[pano.id] && loadedCallback[pano.id](param1, param2);
  63335. },1);
  63336. };
  63337. var callback2 = (param)=>{//没有看到有传doneFun2的
  63338. setTimeout(()=>{
  63339. isLoadedPanos[pano.id] = !1;
  63340. doneFun2 && doneFun2(param);
  63341. },1);
  63342. };
  63343. try {
  63344. null !== iswait && void 0 !== iswait || (iswait = !0);
  63345. isLoadedPanos[pano.id] = this.checkAndWaitForTiledPanoLoad(pano, basePanoSize, callback1, callback2, progressCallback, iswait, isclear, p );
  63346. //true代表没加载好
  63347. isLoadedPanos[pano.id] && (LoadedTimePanos[pano.id] = performance.now());
  63348. return isLoadedPanos[pano.id];
  63349. } catch (msg) {
  63350. isLoadedPanos[pano.id] = !1;
  63351. LoadedTimePanos[pano.id] = performance.now() - maxTime;
  63352. throw msg;
  63353. }
  63354. }
  63355. }();
  63356. Images360.filters = {
  63357. inPanoDirection : function(pos, dir, i) {
  63358. return function(pano) {
  63359. var r = pano.floorPosition.clone().sub(pos).normalize();
  63360. var o = pano.position.clone().sub(pos).normalize();
  63361. return r.dot(dir) > i || o.dot(dir) > i
  63362. }
  63363. },
  63364. inFloorDirection: function(pos, e, o) {//许钟文 改 for鱼眼
  63365. return function(n) {
  63366. var i = n.floorPosition.clone().sub(pos).setZ(0).normalize();//改成在xz方向上,否则点击墙面不会移动
  63367. return i.dot(e) > o
  63368. }
  63369. },
  63370. isNotBehindNormal: function(e, t) {
  63371. var i = new Vector3;
  63372. return t = t.clone(),
  63373. function(n) {
  63374. var r = i.copy(n.position).sub(e).normalize();
  63375. return r.dot(t) > 0
  63376. }
  63377. },
  63378. isCloseEnoughTo: function(e, t) {
  63379. return function(i) {//因为marker可能比地面高,所以识别范围要比marker看起来更近一些。(因为投影到地板的位置比marker更近)
  63380. return e.distanceTo(i.floorPosition) < t //许钟文
  63381. }
  63382. },
  63383. not: function(e) {
  63384. return function(t) {
  63385. return t !== e
  63386. }
  63387. } ,
  63388. isEnabled:function() {
  63389. return function(t) {
  63390. return t.enabled
  63391. }
  63392. },
  63393. isVisible:function() {
  63394. return function(t) {
  63395. return t.visible
  63396. }
  63397. }
  63398. };
  63399. Images360.scoreFunctions = {
  63400. direction: function(curPos, dir, ifLog) {
  63401. return function(pano) {
  63402. var pos1 = /* pano.floorPosition */ pano.position; //旧:改为权重放在marker上,这样对有斜坡的更准确,如上楼, 但这样近距离的pano角度就会向下了,以致于走不到
  63403. var n = pos1.clone().sub(curPos).normalize();
  63404. //ifLog && console.log('direction', pano.id, n.dot(dir) * directionFactor )
  63405. return n.dot(dir) * directionFactor
  63406. }
  63407. },
  63408. distanceSquared: function(pos1, r, ifLog) {
  63409. if(pos1.position)pos1 = pos1.position;
  63410. return function(pano) {//许钟文 改
  63411. var pos2 = pano.position.clone();
  63412. //ifLog && console.log('distanceSquared', pano.id, pos1.distanceToSquared(pos2) * -1 )
  63413. return pos1.distanceToSquared(pos2) * -1 * r;
  63414. }
  63415. },
  63416. angle: function(e, t) {
  63417. return function(i) {
  63418. var n = i.position.clone().sub(e).normalize();
  63419. return n.angleTo(t) * Potree.config.navigation.angleFactor
  63420. }
  63421. },
  63422. };
  63423. Images360.sortFunctions = {//排序函数,涉及到两个item相减
  63424. floorDisSquaredToPoint: function(e) {
  63425. return function(t, i) {
  63426. return t.floorPosition.distanceToSquared(e) - i.floorPosition.distanceToSquared(e)
  63427. }
  63428. },
  63429. disSquaredToPoint: function(e) {
  63430. return function(t, i) {
  63431. return t.position.distanceToSquared(e) - i.position.distanceToSquared(e)
  63432. }
  63433. },
  63434. };
  63435. /* var centerCross = new THREE.Mesh(new THREE.SphereGeometry(1, 4, 4),new THREE.MeshBasicMaterial({
  63436. transparent:true, color:"#ff0000", opacity:0.5
  63437. })); */
  63438. /* const mapHeight = -1000;//要比点云低。最低
  63439. const cameraHeight = 1000; //最高 */
  63440. const panosHeight = config$1.map.mapHeight + 100; //要比点云低 (marker)
  63441. const cursorHeight = 0;//比地图高就行
  63442. const routeLayerHeight = config$1.map.mapHeight + 105;
  63443. const texLoader$4 = new TextureLoader();
  63444. const planeGeo$2 = new PlaneBufferGeometry(1,1);
  63445. const markerSize = 1;
  63446. var initCameraFeildWidth = 50;
  63447. var panoMarkerMats;
  63448. class MapViewer extends ViewerBase{
  63449. constructor(dom){
  63450. super(dom, {
  63451. clearColor: Potree.config.mapBG,
  63452. name: 'mapViewer'
  63453. });
  63454. this.visible = true;
  63455. this.initScene();
  63456. this.mapLayer = new MapLayer(this, this.viewports[0]);
  63457. this.scene.add(this.mapLayer.sceneGroup);
  63458. this.mapLayer.sceneGroup.position.setZ(Potree.config.map.mapHeight);
  63459. this.mapRatio = 0.5;
  63460. this.splitDir = 'leftRight';
  63461. //this.scene.add(centerCross)
  63462. viewer.addEventListener("camera_changed", (e)=>{
  63463. if(e.viewport == viewer.mainViewport) this.updateCursor();
  63464. else this.updateWhenAtViewer();
  63465. });
  63466. //viewer.addEventListener("global_mousemove", this.updateWhenAtViewer.bind(this)) //鼠标移动时reticule也动,所以直接就needRender
  63467. viewer.reticule.addEventListener('update',(e)=>{
  63468. if(this.attachedToViewer)this.needRender = true;
  63469. });
  63470. viewer.scene.addEventListener("360_images_added", this.addPanos.bind(this));
  63471. viewer.addEventListener("loadPointCloudDone", this.initProjection.bind(this));
  63472. this.addEventListener('global_click',(e)=>{
  63473. if(!e.isTouch && e.button != MOUSE.LEFT)return
  63474. this.updateClosestPano(e.intersect);
  63475. });
  63476. this.addEventListener('add',(e)=>{//添加其他mesh
  63477. this.scene.add(e.object);
  63478. if(e.name == 'route'){
  63479. e.object.position.z = routeLayerHeight;
  63480. }
  63481. viewer.setObjectLayers(e.object, 'mapObjects' );
  63482. });
  63483. if(!Potree.settings.isOfficial){
  63484. let domRoot = viewer.renderer.domElement.parentElement;
  63485. let elAttach = $("<input type='button' value='map绑定'></input>");
  63486. elAttach.css({
  63487. position : "absolute",
  63488. right : '80%',
  63489. bottom: '20px',
  63490. zIndex: "10000",
  63491. fontSize:'1em', color:"black",
  63492. background:'rgba(255,255,255,0.8)',
  63493. });
  63494. let state = false;
  63495. elAttach.on("click", () => {
  63496. state = !state;
  63497. this.attachToMainViewer(state, 'measure');
  63498. elAttach.val(state ? 'map分离':'map绑定');
  63499. });
  63500. domRoot.appendChild(elAttach[0]);
  63501. }
  63502. }
  63503. waitLoadDone(callback){//确保加载完后执行
  63504. if(this.mapLayer.loadingInProgress == 0){
  63505. callback();
  63506. }else {
  63507. var f = ()=>{
  63508. callback();
  63509. this.mapLayer.removeEventListener('loadDone', f);
  63510. };
  63511. this.mapLayer.addEventListener('loadDone', f);
  63512. }
  63513. }
  63514. addListener(images360){
  63515. images360.addEventListener('flyToPano',e=>{
  63516. let toPano = e.toPano;
  63517. if(toPano.dontMoveMap) return
  63518. /* transitions.start(lerp.vector(this.view.position, toPano.pano.position.clone().setZ(cameraHeight),
  63519. (pos, progress)=>{
  63520. }), toPano.duration, null, 0, easing[toPano.easeName] ); */
  63521. let boundSize;// = new THREE.Vector2(10,10)
  63522. this.moveTo(toPano.pano.position.clone().setZ(Potree.config.map.cameraHeight), boundSize, toPano.duration, toPano.easeName);
  63523. });
  63524. }
  63525. initProjection(){
  63526. this.started = true;
  63527. this.mapLayer.initProjection();
  63528. }
  63529. initScene(){
  63530. let w = initCameraFeildWidth;
  63531. let width = this.renderArea.clientWidth;
  63532. let height = this.renderArea.clientHeight;
  63533. //let aspect = width / height
  63534. 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);
  63535. this.camera.zoom = width / w; //zoom越大视野越小
  63536. //this.camera.position.set(0,0,10);
  63537. this.camera.up.set(0,0,1);
  63538. //this.camera.lookAt(new THREE.Vector3())
  63539. //this.camera.updateMatrixWorld()
  63540. this.view = new View();
  63541. this.view.position.set(0,0,Potree.config.map.cameraHeight);
  63542. this.view.lookAt(0,0,0);
  63543. this.setViewLimit('standard');
  63544. let viewport = new Viewport( this.view, this.camera, {
  63545. left:0, bottom:0, width:1, height: 1, name:'mapViewport'
  63546. });
  63547. viewport.axis = ["x","y"];
  63548. viewport.axisSign = [1,1];
  63549. viewport.noPointcloud = true; //不要渲染点云
  63550. viewport.render = this.render.bind(this);//标志给mainView渲染
  63551. //viewport.unableDepth = true //depthBasicMaterial等在此viewport中不开启depth
  63552. this.viewports = [viewport];
  63553. this.controls = new FirstPersonControls(this, this.viewports[0]);
  63554. this.controls.setEnable(true);
  63555. this.scene = new Scene();
  63556. this.inputHandler = new InputHandler(this, this.scene);
  63557. this.inputHandler.name = 'mapInputHandler';
  63558. //this.inputHandler.addInputListener(this.controls);
  63559. this.inputHandler.registerInteractiveScene(this.scene);//interactiveScenes
  63560. this.viewports[0].interactiveScenes = this.inputHandler.interactiveScenes;//供viewer的inputHandler使用
  63561. var cursor = new Mesh(planeGeo$2, new MeshBasicMaterial({
  63562. transparent:true,
  63563. opacity:0.9,
  63564. depthTest : false, //防止透明冲突
  63565. map: texLoader$4.load(Potree.resourcePath+'/textures/pic_location128.png' )
  63566. }));
  63567. cursor.position.set(0,0,cursorHeight);
  63568. this.cursor = cursor;
  63569. this.scene.add(cursor);
  63570. viewer.setObjectLayers(this.scene, 'mapObjects' );
  63571. }
  63572. setViewLimit(state){//设置边界,当编辑空间模型等时要解禁
  63573. let setting = Potree.config.OrthoCameraLimit[state];
  63574. if(setting){
  63575. this.view.limitBound = new Box3().copy(setting.posBound);
  63576. this.camera.zoomLimit = $.extend({},setting.zoom);
  63577. }else {
  63578. this.view.limitBound = null;
  63579. this.camera.zoomLimit = null;
  63580. }
  63581. }
  63582. updateCursor(){
  63583. var scale = math.getScaleForConstantSize( {//规定下最小最大像素
  63584. minSize : 80, maxSize : 200, nearBound : initCameraFeildWidth*0.1 , farBound : initCameraFeildWidth*2,
  63585. camera:this.camera , position: this.cursor.getWorldPosition(new Vector3()),
  63586. resolution: this.viewports[0].resolution//2
  63587. });
  63588. this.cursor.scale.set(scale, scale, scale);//当地图缩放时
  63589. this.cursor.position.copy(viewer.mainViewport.camera.position).setZ(cursorHeight);//当场景镜头旋转移动时
  63590. this.cursor.rotation.z = viewer.mainViewport.view.yaw;
  63591. this.needRender = true;
  63592. }
  63593. addPanos(e){
  63594. var panosGroup = new Object3D;
  63595. panoMarkerMats = {
  63596. default: new MeshBasicMaterial({
  63597. transparent:true,
  63598. opacity: 0.5,
  63599. map: texLoader$4.load(Potree.resourcePath+'/textures/map_marker.png' ),
  63600. }),
  63601. selected: new MeshBasicMaterial({
  63602. transparent:true,
  63603. opacity: 1,
  63604. map: texLoader$4.load(Potree.resourcePath+'/textures/map_marker.png' ),
  63605. })
  63606. };
  63607. e.images.panos.forEach(pano=>{
  63608. pano.mapMarker = new Mesh(planeGeo$2, panoMarkerMats.default);
  63609. pano.mapMarker.position.copy(pano.position).setZ(0);
  63610. pano.mapMarker.scale.set(markerSize,markerSize,markerSize);
  63611. pano.mapMarker.name = 'mapMarker';
  63612. panosGroup.add(pano.mapMarker);
  63613. let mouseover = (e)=>{
  63614. if(!e.byMap){
  63615. pano.mapMarker.material = panoMarkerMats.selected;
  63616. if(!e.byMainView) pano.dispatchEvent({type: "hoverOn", byMap:true});
  63617. this.needRender = true;
  63618. }
  63619. };
  63620. let mouseleave = (e)=>{
  63621. if(!e.byMap){
  63622. pano.mapMarker.material = panoMarkerMats.default;
  63623. if(!e.byMainView) pano.dispatchEvent({type: "hoverOff", byMap:true});
  63624. this.needRender = true;
  63625. }
  63626. };
  63627. pano.mapMarker.addEventListener('mouseover', mouseover);
  63628. pano.mapMarker.addEventListener('mouseleave', mouseleave);
  63629. pano.addEventListener('hoverOn', mouseover);
  63630. pano.addEventListener('hoverOff', mouseleave);
  63631. let onclick = (e)=>{
  63632. viewer.images360.flyToPano(pano);
  63633. };
  63634. pano.mapMarker.addEventListener('click', onclick);
  63635. pano.addEventListener('isVisible',(e)=>{//是否显示该点的mesh(不显示也能走)
  63636. //console.log('panoMarker isVisible', pano.id, e.visible)
  63637. viewer.updateVisible(pano.mapMarker, 'panoVisible', e.visible );
  63638. this.needRender = true;
  63639. });
  63640. pano.addEventListener('rePos',(e)=>{
  63641. pano.mapMarker.position.copy(pano.position).setZ(0);
  63642. });
  63643. });
  63644. this.scene.add(panosGroup);
  63645. panosGroup.position.z = panosHeight;
  63646. this.panosGroup = panosGroup;
  63647. viewer.setObjectLayers(panosGroup, 'mapObjects' );
  63648. /* e.images.on('markersDisplayChange', (show)=>{
  63649. panosGroup.visible = show
  63650. this.needRender = true
  63651. }) */
  63652. //-------
  63653. //this.fitPanosToViewport()
  63654. this.initFitView();
  63655. }
  63656. updateClosestPano(intersect){
  63657. if(viewer.images360.flying)return;
  63658. intersect = intersect && intersect.orthoIntersect;
  63659. if(!intersect)return
  63660. intersect = intersect.clone().setZ(0);
  63661. const minDis = 20; //距离鼠标不能太远
  63662. var filterFuncs = [
  63663. (pano)=>{
  63664. return pano.position.clone().setZ(0).distanceTo(intersect) < minDis
  63665. },
  63666. Images360.filters.isEnabled(),
  63667. Images360.filters.isVisible(),//只走显示的点,否则会走到别的层
  63668. ];
  63669. var pano = Common.find(viewer.images360.panos, filterFuncs, [Images360.sortFunctions.floorDisSquaredToPoint(intersect)]);
  63670. if (pano && pano != viewer.images360.currentPano ) {
  63671. viewer.images360.flyToPano(pano);
  63672. }
  63673. }
  63674. fitPanosToViewport(){//使所有漫游点占满viewport
  63675. //var w = viewer.bound.boundSize.x;
  63676. var boundSize = viewer.images360.bound.size.clone().multiplyScalar(1.1);
  63677. boundSize.max(new Vector3(4,4,4));
  63678. let endPosition = viewer.images360.bound.center.clone();
  63679. this.moveTo(endPosition, boundSize, 0);
  63680. }
  63681. fitToPointcloud(pointcloud, duration=400){
  63682. var boundSize = pointcloud.bound.getSize(new Vector3);/* .multiplyScalar(1.1); */
  63683. boundSize.max(new Vector3(4,4,4));
  63684. let endPosition = pointcloud.bound.getCenter(new Vector3);
  63685. this.moveTo(endPosition, boundSize, duration); //给点duration去变化 否则地图放大后所占的还是很小
  63686. }
  63687. initFitView(){
  63688. let dis = 5 , px = 70; //地图上px像素长度代表的距离为dis //px是手动缩放到5m后发现是这个长度
  63689. let zoom = px / dis;
  63690. this.camera.zoom = zoom;
  63691. this.moveTo(viewer.images360.position/* viewer.images360.bound.center */);
  63692. this.camera.updateProjectionMatrix();
  63693. }
  63694. fitToDatasets(datasets){
  63695. let bound = new Box3;
  63696. datasets.forEach(e=>bound.union(e.bound));
  63697. let center = bound.getCenter(new Vector3);
  63698. let size = bound.getSize(new Vector3);
  63699. this.moveTo(center, size, 200 ); //给duration是为了顺应视口大小改变,缓冲
  63700. }
  63701. moveTo(endPosition, boundSize, duration=0, easeName){//前两个参数有xy即可
  63702. endPosition = new Vector3(endPosition.x,endPosition.y,Potree.config.map.cameraHeight);
  63703. this.view.moveOrthoCamera(this.viewports[0], {endPosition, boundSize }, duration, easeName);
  63704. /* let endZoom, startZoom = this.camera.zoom
  63705. //修改相机为bound中心,这样能看到全部(宽度范围内)
  63706. this.view.setView({ position:endPosition, duration,
  63707. callback:()=>{//done
  63708. },
  63709. onUpdate:(progress)=>{
  63710. if(boundSize){
  63711. let aspect = boundSize.x / boundSize.y
  63712. let w, h;
  63713. if(this.camera.aspect > aspect){//视野更宽则用bound的纵向来决定
  63714. h = boundSize.y
  63715. //w = h * this.camera.aspect
  63716. endZoom = this.viewports[0].resolution.y / h
  63717. }else{
  63718. w = boundSize.x;
  63719. //h = w / this.camera.aspect
  63720. endZoom = this.viewports[0].resolution.x / w
  63721. }
  63722. //onUpdate时更新endzoom是因为画布大小可能更改
  63723. this.camera.zoom = endZoom * progress + startZoom * (1 - progress)
  63724. this.camera.updateProjectionMatrix()
  63725. }
  63726. },
  63727. Easing:easeName
  63728. }) */
  63729. }
  63730. updateWhenAtViewer(e){
  63731. if(this.attachedToViewer){
  63732. if(this.started) this.mapLayer.update();
  63733. this.updateCursor();
  63734. this.needRender = true;
  63735. }
  63736. }
  63737. update(delta, areaSize ){
  63738. if(!this.visible && !this.attachedToViewer )return
  63739. if(this.attachedToViewer){
  63740. if(this.mapLayer.needUpdate){//必须更新。(较少触发)
  63741. this.updateWhenAtViewer();
  63742. }
  63743. return
  63744. }
  63745. this.updateScreenSize();
  63746. this.controls.update(delta);
  63747. this.view.applyToCamera(this.camera);
  63748. let changed = this.cameraChanged();
  63749. if(this.started && (changed || this.mapLayer.needUpdate))this.mapLayer.update();
  63750. if(changed /*|| || this.needRender */){
  63751. this.dispatchEvent({
  63752. type: "camera_changed",
  63753. camera: this.camera,
  63754. viewport : this.viewports[0]
  63755. });
  63756. this.needRender = true;
  63757. this.updateCursor();//更改大小
  63758. }
  63759. this.render();
  63760. }
  63761. attachToMainViewer(state, desc, mapRatio=0.5, options={}){//转移到viewer中。测量时展示or截图需要
  63762. if(!Potree.settings.isOfficial)this.renderArea.style.display = state ? 'none':'block';
  63763. if(state){
  63764. this.enabledOld = this.enabled;
  63765. this.enabled = true;
  63766. if(mapRatio != 'dontSet'){
  63767. this.changeSplitScreenDir(options.dir, mapRatio);
  63768. if(this.attachedToViewer){
  63769. //this.fitPanosToViewport()
  63770. viewer.updateScreenSize({forceUpdateSize:true});
  63771. return
  63772. }
  63773. viewer.viewports = [viewer.mainViewport, viewer.mapViewer.viewports[0] ];//因为mainViewer的相机变化会触发map的变化,所以先渲染mainViewer
  63774. }
  63775. if(desc == 'measure') this.inputHandler.registerInteractiveScene(viewer.measuringTool.scene);//虽然用的是viewer的inputHandler,但借用了this.inputHandler的interactiveScenes
  63776. else if(desc == 'split4Screens') {
  63777. this.inputHandler.registerInteractiveScene(viewer.scene.scene);
  63778. }
  63779. }else {
  63780. if(!this.attachedToViewer)return
  63781. viewer.mainViewport.left = 0;
  63782. viewer.mainViewport.bottom = 0;
  63783. viewer.mainViewport.width = 1;
  63784. viewer.mainViewport.height = 1;
  63785. this.viewports[0].width = 1;
  63786. this.viewports[0].bottom = 0;
  63787. this.viewports[0].height = 1;
  63788. this.viewports[0].left = 0;
  63789. this.inputHandler.unregisterInteractiveScene(viewer.measuringTool.scene);
  63790. this.inputHandler.unregisterInteractiveScene(viewer.scene.scene);
  63791. viewer.viewports = [viewer.mainViewport];
  63792. this.updateScreenSize({forceUpdateSize:true}); //更新相机projectionMatrix
  63793. }
  63794. //if(desc == 'measure')this.renderMeasure = state
  63795. this.attachedToViewer = state;
  63796. viewer.updateScreenSize({forceUpdateSize:true});
  63797. //mapRatio != 'dontSet' && !options.dontFit && this.moveTo(...)//要写在updateScreenSize后面,因为要根据视图大小来fit
  63798. if(options.moveToCurrentPos){
  63799. let boundSize = new Vector2$1(10,10);
  63800. let duration = 1000;
  63801. this.moveTo(viewer.images360.position.clone(), boundSize, duration);
  63802. }
  63803. this.needRender = true;
  63804. }
  63805. changeSplitScreenDir(dir, mapRatio){//左右 | 上下
  63806. //if(!dir || dir == this.dir)return
  63807. if(dir )this.splitDir = dir;
  63808. this.updateSplitSize(mapRatio);
  63809. /* if(this.attachedToViewer){ //如果已经分屏了,中途修改方向的话……
  63810. this.updateSplitSize()
  63811. } */
  63812. }
  63813. updateSplitSize(mapRatio){
  63814. if(mapRatio != void 0) this.mapRatio = mapRatio;
  63815. //console.log(this.mapRatio)
  63816. if(this.splitDir == 'leftRight'){//地图在左方
  63817. viewer.mainViewport.left = this.mapRatio;
  63818. viewer.mainViewport.width = 1-this.mapRatio;
  63819. this.viewports[0].width = this.mapRatio;
  63820. viewer.mainViewport.bottom = this.viewports[0].bottom = 0;
  63821. viewer.mainViewport.height = this.viewports[0].height = 1;
  63822. }else if(this.splitDir == 'upDown'){ //地图在下方
  63823. viewer.mainViewport.bottom = this.mapRatio;
  63824. viewer.mainViewport.height = 1-this.mapRatio;
  63825. this.viewports[0].height = this.mapRatio;
  63826. viewer.mainViewport.left = this.viewports[0].left = 0;
  63827. viewer.mainViewport.width = this.viewports[0].width = 1;
  63828. }
  63829. if(this.attachedToViewer){
  63830. viewer.updateScreenSize({forceUpdateSize:true});
  63831. }
  63832. }
  63833. render(params={}){
  63834. if(!this.visible && !this.attachedToViewer || !this.needRender && !params.force)return
  63835. let renderer = params.renderer || this.renderer;
  63836. if(params.target){
  63837. renderer.setRenderTarget(params.target);
  63838. }
  63839. /* if(params.resize){
  63840. this.emitResizeMsg(new THREE.Vector2(params.width,params.height, viewport:params.viewport))
  63841. } */
  63842. params.clear ? params.clear() : renderer.clear();
  63843. if(!this.attachedToViewer){
  63844. viewer.dispatchEvent({type: "render.begin", viewer: this, viewport:this.viewports[0], params });
  63845. }
  63846. viewer.setCameraLayers(this.camera, ['map','mapObjects' , 'bothMapAndScene' ]);
  63847. if(this.mapGradientBG){//渲染背景
  63848. viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg);
  63849. renderer.render(viewer.scene.scene, viewer.scene.cameraBG);
  63850. }
  63851. renderer.render(this.scene, this.camera);
  63852. renderer.render(viewer.scene.scene, this.camera);
  63853. //测量线等
  63854. //params.renderOverlay && params.renderOverlay({camera:this.camera, isMap:true, viewport: this.viewports[0] })//其余如reticule 等场景层
  63855. params.renderOverlay && params.renderOverlay( $.extend({}, params, { isMap:true }));
  63856. renderer.setRenderTarget(null);
  63857. this.needRender = false;
  63858. }
  63859. /* render(){
  63860. let camera = viewer.scene.getActiveCamera();
  63861. viewer.scene.view.position.x += 0.01
  63862. viewer.setCameraLayers(camera, ['sceneObjects','marker','reticule','skybox' ])
  63863. this.renderer.render(viewer.scene.scene, camera);
  63864. } */
  63865. }
  63866. //本地调试地图白屏是因为代码自动更新了 但没刷新
  63867. class CSVExporter {
  63868. static toString (points) {
  63869. let string = '';
  63870. let attributes = Object.keys(points.data)
  63871. .filter(a => a !== 'normal')
  63872. .sort((a, b) => {
  63873. if (a === 'position') return -1;
  63874. if (b === 'position') return 1;
  63875. if (a === 'rgba') return -1;
  63876. if (b === 'rgba') return 1;
  63877. });
  63878. let headerValues = [];
  63879. for (let attribute of attributes) {
  63880. let itemSize = points.data[attribute].length / points.numPoints;
  63881. if (attribute === 'position') {
  63882. headerValues = headerValues.concat(['x', 'y', 'z']);
  63883. } else if (attribute === 'rgba') {
  63884. headerValues = headerValues.concat(['r', 'g', 'b', 'a']);
  63885. } else if (itemSize > 1) {
  63886. for (let i = 0; i < itemSize; i++) {
  63887. headerValues.push(`${attribute}_${i}`);
  63888. }
  63889. } else {
  63890. headerValues.push(attribute);
  63891. }
  63892. }
  63893. string = headerValues.join(', ') + '\n';
  63894. for (let i = 0; i < points.numPoints; i++) {
  63895. let values = [];
  63896. for (let attribute of attributes) {
  63897. let itemSize = points.data[attribute].length / points.numPoints;
  63898. let value = points.data[attribute]
  63899. .subarray(itemSize * i, itemSize * i + itemSize)
  63900. .join(', ');
  63901. values.push(value);
  63902. }
  63903. string += values.join(', ') + '\n';
  63904. }
  63905. return string;
  63906. }
  63907. };
  63908. class LASExporter {
  63909. static toLAS (points) {
  63910. // TODO Unused: let string = '';
  63911. let boundingBox = points.boundingBox;
  63912. let offset = boundingBox.min.clone();
  63913. let diagonal = boundingBox.min.distanceTo(boundingBox.max);
  63914. let scale = new Vector3(0.001, 0.001, 0.001);
  63915. if (diagonal > 1000 * 1000) {
  63916. scale = new Vector3(0.01, 0.01, 0.01);
  63917. } else {
  63918. scale = new Vector3(0.001, 0.001, 0.001);
  63919. }
  63920. let setString = function (string, offset, buffer) {
  63921. let view = new Uint8Array(buffer);
  63922. for (let i = 0; i < string.length; i++) {
  63923. let charCode = string.charCodeAt(i);
  63924. view[offset + i] = charCode;
  63925. }
  63926. };
  63927. let buffer = new ArrayBuffer(227 + 28 * points.numPoints);
  63928. let view = new DataView(buffer);
  63929. let u8View = new Uint8Array(buffer);
  63930. // let u16View = new Uint16Array(buffer);
  63931. setString('LASF', 0, buffer);
  63932. u8View[24] = 1;
  63933. u8View[25] = 2;
  63934. // system identifier o:26 l:32
  63935. // generating software o:58 l:32
  63936. setString('Potree 1.7', 58, buffer);
  63937. // file creation day of year o:90 l:2
  63938. // file creation year o:92 l:2
  63939. // header size o:94 l:2
  63940. view.setUint16(94, 227, true);
  63941. // offset to point data o:96 l:4
  63942. view.setUint32(96, 227, true);
  63943. // number of letiable length records o:100 l:4
  63944. // point data record format 104 1
  63945. u8View[104] = 2;
  63946. // point data record length 105 2
  63947. view.setUint16(105, 28, true);
  63948. // number of point records 107 4
  63949. view.setUint32(107, points.numPoints, true);
  63950. // number of points by return 111 20
  63951. // x scale factor 131 8
  63952. view.setFloat64(131, scale.x, true);
  63953. // y scale factor 139 8
  63954. view.setFloat64(139, scale.y, true);
  63955. // z scale factor 147 8
  63956. view.setFloat64(147, scale.z, true);
  63957. // x offset 155 8
  63958. view.setFloat64(155, offset.x, true);
  63959. // y offset 163 8
  63960. view.setFloat64(163, offset.y, true);
  63961. // z offset 171 8
  63962. view.setFloat64(171, offset.z, true);
  63963. // max x 179 8
  63964. view.setFloat64(179, boundingBox.max.x, true);
  63965. // min x 187 8
  63966. view.setFloat64(187, boundingBox.min.x, true);
  63967. // max y 195 8
  63968. view.setFloat64(195, boundingBox.max.y, true);
  63969. // min y 203 8
  63970. view.setFloat64(203, boundingBox.min.y, true);
  63971. // max z 211 8
  63972. view.setFloat64(211, boundingBox.max.z, true);
  63973. // min z 219 8
  63974. view.setFloat64(219, boundingBox.min.z, true);
  63975. let boffset = 227;
  63976. for (let i = 0; i < points.numPoints; i++) {
  63977. let px = points.data.position[3 * i + 0];
  63978. let py = points.data.position[3 * i + 1];
  63979. let pz = points.data.position[3 * i + 2];
  63980. let ux = parseInt((px - offset.x) / scale.x);
  63981. let uy = parseInt((py - offset.y) / scale.y);
  63982. let uz = parseInt((pz - offset.z) / scale.z);
  63983. view.setUint32(boffset + 0, ux, true);
  63984. view.setUint32(boffset + 4, uy, true);
  63985. view.setUint32(boffset + 8, uz, true);
  63986. if (points.data.intensity) {
  63987. view.setUint16(boffset + 12, (points.data.intensity[i]), true);
  63988. }
  63989. let rt = 0;
  63990. if (points.data.returnNumber) {
  63991. rt += points.data.returnNumber[i];
  63992. }
  63993. if (points.data.numberOfReturns) {
  63994. rt += (points.data.numberOfReturns[i] << 3);
  63995. }
  63996. view.setUint8(boffset + 14, rt);
  63997. if (points.data.classification) {
  63998. view.setUint8(boffset + 15, points.data.classification[i]);
  63999. }
  64000. // scan angle rank
  64001. // user data
  64002. // point source id
  64003. if (points.data.pointSourceID) {
  64004. view.setUint16(boffset + 18, points.data.pointSourceID[i]);
  64005. }
  64006. if (points.data.rgba) {
  64007. let rgba = points.data.rgba;
  64008. view.setUint16(boffset + 20, (rgba[4 * i + 0] * 255), true);
  64009. view.setUint16(boffset + 22, (rgba[4 * i + 1] * 255), true);
  64010. view.setUint16(boffset + 24, (rgba[4 * i + 2] * 255), true);
  64011. }
  64012. boffset += 28;
  64013. }
  64014. return buffer;
  64015. }
  64016. }
  64017. function copyMaterial(source, target){
  64018. for(let name of Object.keys(target.uniforms)){
  64019. target.uniforms[name].value = source.uniforms[name].value;
  64020. }
  64021. target.gradientTexture = source.gradientTexture;
  64022. target.visibleNodesTexture = source.visibleNodesTexture;
  64023. target.classificationTexture = source.classificationTexture;
  64024. target.matcapTexture = source.matcapTexture;
  64025. target.activeAttributeName = source.activeAttributeName;
  64026. target.ranges = source.ranges;
  64027. //target.updateShaderSource();
  64028. }
  64029. class Batch{
  64030. constructor(geometry, material){
  64031. this.geometry = geometry;
  64032. this.material = material;
  64033. this.sceneNode = new Points(geometry, material);
  64034. this.geometryNode = {
  64035. estimatedSpacing: 1.0,
  64036. geometry: geometry,
  64037. };
  64038. }
  64039. getLevel(){
  64040. return 0;
  64041. }
  64042. }
  64043. class ProfileFakeOctree extends PointCloudTree{
  64044. constructor(octree){
  64045. super();
  64046. this.trueOctree = octree;
  64047. this.pcoGeometry = octree.pcoGeometry;
  64048. this.points = [];
  64049. this.visibleNodes = [];
  64050. //this.material = this.trueOctree.material;
  64051. this.material = new PointCloudMaterial$1();
  64052. //this.material.copy(this.trueOctree.material);
  64053. copyMaterial(this.trueOctree.material, this.material);
  64054. this.material.pointSizeType = PointSizeType.FIXED;
  64055. this.batchSize = 100 * 1000;
  64056. this.currentBatch = null;
  64057. }
  64058. getAttribute(name){
  64059. return this.trueOctree.getAttribute(name);
  64060. }
  64061. dispose(){
  64062. for(let node of this.visibleNodes){
  64063. node.geometry.dispose();
  64064. }
  64065. this.visibleNodes = [];
  64066. this.currentBatch = null;
  64067. this.points = [];
  64068. }
  64069. addPoints(data){
  64070. // since each call to addPoints can deliver very very few points,
  64071. // we're going to batch them into larger buffers for efficiency.
  64072. if(this.currentBatch === null){
  64073. this.currentBatch = this.createNewBatch(data);
  64074. }
  64075. this.points.push(data);
  64076. let updateRange = {
  64077. start: this.currentBatch.geometry.drawRange.count,
  64078. count: 0
  64079. };
  64080. let projectedBox = new Box3();
  64081. let truePos = new Vector3();
  64082. for(let i = 0; i < data.numPoints; i++){
  64083. if(updateRange.start + updateRange.count >= this.batchSize){
  64084. // current batch full, start new batch
  64085. for(let key of Object.keys(this.currentBatch.geometry.attributes)){
  64086. let attribute = this.currentBatch.geometry.attributes[key];
  64087. attribute.updateRange.offset = updateRange.start;
  64088. attribute.updateRange.count = updateRange.count;
  64089. attribute.needsUpdate = true;
  64090. }
  64091. this.currentBatch.geometry.computeBoundingBox();
  64092. this.currentBatch.geometry.computeBoundingSphere();
  64093. this.currentBatch = this.createNewBatch(data);
  64094. updateRange = {
  64095. start: 0,
  64096. count: 0
  64097. };
  64098. }
  64099. truePos.set(
  64100. data.data.position[3 * i + 0] + this.trueOctree.position.x,
  64101. data.data.position[3 * i + 1] + this.trueOctree.position.y,
  64102. data.data.position[3 * i + 2] + this.trueOctree.position.z,
  64103. );
  64104. let x = data.data.mileage[i];
  64105. let y = 0;
  64106. let z = truePos.z;
  64107. projectedBox.expandByPoint(new Vector3(x, y, z));
  64108. let index = updateRange.start + updateRange.count;
  64109. let geometry = this.currentBatch.geometry;
  64110. for(let attributeName of Object.keys(data.data)){
  64111. let source = data.data[attributeName];
  64112. let target = geometry.attributes[attributeName];
  64113. let numElements = target.itemSize;
  64114. for(let item = 0; item < numElements; item++){
  64115. target.array[numElements * index + item] = source[numElements * i + item];
  64116. }
  64117. }
  64118. {
  64119. let position = geometry.attributes.position;
  64120. position.array[3 * index + 0] = x;
  64121. position.array[3 * index + 1] = y;
  64122. position.array[3 * index + 2] = z;
  64123. }
  64124. updateRange.count++;
  64125. this.currentBatch.geometry.drawRange.count++;
  64126. }
  64127. for(let key of Object.keys(this.currentBatch.geometry.attributes)){
  64128. let attribute = this.currentBatch.geometry.attributes[key];
  64129. attribute.updateRange.offset = updateRange.start;
  64130. attribute.updateRange.count = updateRange.count;
  64131. attribute.needsUpdate = true;
  64132. }
  64133. data.projectedBox = projectedBox;
  64134. this.projectedBox = this.points.reduce( (a, i) => a.union(i.projectedBox), new Box3());
  64135. }
  64136. createNewBatch(data){
  64137. let geometry = new BufferGeometry();
  64138. // create new batches with batch_size elements of the same type as the attribute
  64139. for(let attributeName of Object.keys(data.data)){
  64140. let buffer = data.data[attributeName];
  64141. let numElements = buffer.length / data.numPoints; // 3 for pos, 4 for col, 1 for scalars
  64142. let constructor = buffer.constructor;
  64143. let normalized = false;
  64144. if(this.trueOctree.root.sceneNode){
  64145. if(this.trueOctree.root.sceneNode.geometry.attributes[attributeName]){
  64146. normalized = this.trueOctree.root.sceneNode.geometry.attributes[attributeName].normalized;
  64147. }
  64148. }
  64149. let batchBuffer = new constructor(numElements * this.batchSize);
  64150. let bufferAttribute = new BufferAttribute(batchBuffer, numElements, normalized);
  64151. bufferAttribute.potree = {
  64152. range: [0, 1],
  64153. };
  64154. geometry.setAttribute(attributeName, bufferAttribute);
  64155. }
  64156. geometry.drawRange.start = 0;
  64157. geometry.drawRange.count = 0;
  64158. let batch = new Batch(geometry, this.material);
  64159. this.visibleNodes.push(batch);
  64160. return batch;
  64161. }
  64162. computeVisibilityTextureData(){
  64163. let data = new Uint8Array(this.visibleNodes.length * 4);
  64164. let offsets = new Map();
  64165. for(let i = 0; i < this.visibleNodes.length; i++){
  64166. let node = this.visibleNodes[i];
  64167. offsets[node] = i;
  64168. }
  64169. return {
  64170. data: data,
  64171. offsets: offsets,
  64172. };
  64173. }
  64174. }
  64175. class ProfileWindow extends EventDispatcher {
  64176. constructor (viewer) {
  64177. super();
  64178. this.viewer = viewer;
  64179. this.elRoot = $('#profile_window');
  64180. this.renderArea = this.elRoot.find('#profileCanvasContainer');
  64181. this.svg = d3.select('svg#profileSVG');
  64182. this.mouseIsDown = false;
  64183. this.projectedBox = new Box3();
  64184. this.pointclouds = new Map();
  64185. this.numPoints = 0;
  64186. this.lastAddPointsTimestamp = undefined;
  64187. this.mouse = new Vector2$1(0, 0);
  64188. this.scale = new Vector3(1, 1, 1);
  64189. this.autoFitEnabled = true; // completely disable/enable
  64190. this.autoFit = false; // internal
  64191. let cwIcon = `${exports.resourcePath}/icons/arrow_cw.svg`;
  64192. $('#potree_profile_rotate_cw').attr('src', cwIcon);
  64193. let ccwIcon = `${exports.resourcePath}/icons/arrow_ccw.svg`;
  64194. $('#potree_profile_rotate_ccw').attr('src', ccwIcon);
  64195. let forwardIcon = `${exports.resourcePath}/icons/arrow_up.svg`;
  64196. $('#potree_profile_move_forward').attr('src', forwardIcon);
  64197. let backwardIcon = `${exports.resourcePath}/icons/arrow_down.svg`;
  64198. $('#potree_profile_move_backward').attr('src', backwardIcon);
  64199. let csvIcon = `${exports.resourcePath}/icons/file_csv_2d.svg`;
  64200. $('#potree_download_csv_icon').attr('src', csvIcon);
  64201. let lasIcon = `${exports.resourcePath}/icons/file_las_3d.svg`;
  64202. $('#potree_download_las_icon').attr('src', lasIcon);
  64203. let closeIcon = `${exports.resourcePath}/icons/close.svg`;
  64204. $('#closeProfileContainer').attr("src", closeIcon);
  64205. this.initTHREE();
  64206. this.initSVG();
  64207. this.initListeners();
  64208. this.pRenderer = new Renderer(this.renderer);
  64209. this.elRoot.i18n();
  64210. }
  64211. initListeners () {
  64212. $(window).resize(() => {
  64213. if (this.enabled) {
  64214. this.render();
  64215. }
  64216. });
  64217. this.renderArea.mousedown(e => {
  64218. this.mouseIsDown = true;
  64219. });
  64220. this.renderArea.mouseup(e => {
  64221. this.mouseIsDown = false;
  64222. });
  64223. let viewerPickSphereSizeHandler = () => {
  64224. let camera = this.viewer.scene.getActiveCamera();
  64225. let domElement = this.viewer.renderer.domElement;
  64226. let distance = this.viewerPickSphere.position.distanceTo(camera.position);
  64227. let pr = Utils.projectedRadius(1, camera, distance, domElement.clientWidth, domElement.clientHeight);
  64228. let scale = (10 / pr);
  64229. this.viewerPickSphere.scale.set(scale, scale, scale);
  64230. };
  64231. this.renderArea.mousemove(e => {
  64232. if (this.pointclouds.size === 0) {
  64233. return;
  64234. }
  64235. let rect = this.renderArea[0].getBoundingClientRect();
  64236. let x = e.clientX - rect.left;
  64237. let y = e.clientY - rect.top;
  64238. let newMouse = new Vector2$1(x, y);
  64239. if (this.mouseIsDown) {
  64240. // DRAG
  64241. this.autoFit = false;
  64242. this.lastDrag = new Date().getTime();
  64243. let cPos = [this.scaleX.invert(this.mouse.x), this.scaleY.invert(this.mouse.y)];
  64244. let ncPos = [this.scaleX.invert(newMouse.x), this.scaleY.invert(newMouse.y)];
  64245. this.camera.position.x -= ncPos[0] - cPos[0];
  64246. this.camera.position.z -= ncPos[1] - cPos[1];
  64247. this.render();
  64248. } else if (this.pointclouds.size > 0) {
  64249. // FIND HOVERED POINT
  64250. let radius = Math.abs(this.scaleX.invert(0) - this.scaleX.invert(40));
  64251. let mileage = this.scaleX.invert(newMouse.x);
  64252. let elevation = this.scaleY.invert(newMouse.y);
  64253. let closest = this.selectPoint(mileage, elevation, radius);
  64254. if (closest) {
  64255. let point = closest.point;
  64256. let position = new Float64Array([
  64257. point.position[0] + closest.pointcloud.position.x,
  64258. point.position[1] + closest.pointcloud.position.y,
  64259. point.position[2] + closest.pointcloud.position.z
  64260. ]);
  64261. this.elRoot.find('#profileSelectionProperties').fadeIn(200);
  64262. this.pickSphere.visible = true;
  64263. this.pickSphere.scale.set(0.5 * radius, 0.5 * radius, 0.5 * radius);
  64264. this.pickSphere.position.set(point.mileage, 0, position[2]);
  64265. this.viewerPickSphere.position.set(...position);
  64266. if(!this.viewer.scene.scene.children.includes(this.viewerPickSphere)){
  64267. this.viewer.scene.scene.add(this.viewerPickSphere);
  64268. if(!this.viewer.hasEventListener("update", viewerPickSphereSizeHandler)){
  64269. this.viewer.addEventListener("update", viewerPickSphereSizeHandler);
  64270. }
  64271. }
  64272. let info = this.elRoot.find('#profileSelectionProperties');
  64273. let html = '<table>';
  64274. for (let attributeName of Object.keys(point)) {
  64275. let value = point[attributeName];
  64276. let attribute = closest.pointcloud.getAttribute(attributeName);
  64277. let transform = value => value;
  64278. if(attribute && attribute.type.size > 4){
  64279. let range = attribute.initialRange;
  64280. let scale = 1 / (range[1] - range[0]);
  64281. let offset = range[0];
  64282. transform = value => value / scale + offset;
  64283. }
  64284. if (attributeName === 'position') {
  64285. let values = [...position].map(v => Utils.addCommas(v.toFixed(3)));
  64286. html += `
  64287. <tr>
  64288. <td>x</td>
  64289. <td>${values[0]}</td>
  64290. </tr>
  64291. <tr>
  64292. <td>y</td>
  64293. <td>${values[1]}</td>
  64294. </tr>
  64295. <tr>
  64296. <td>z</td>
  64297. <td>${values[2]}</td>
  64298. </tr>`;
  64299. } else if (attributeName === 'rgba') {
  64300. html += `
  64301. <tr>
  64302. <td>${attributeName}</td>
  64303. <td>${value.join(', ')}</td>
  64304. </tr>`;
  64305. } else if (attributeName === 'normal') {
  64306. continue;
  64307. } else if (attributeName === 'mileage') {
  64308. html += `
  64309. <tr>
  64310. <td>${attributeName}</td>
  64311. <td>${value.toFixed(3)}</td>
  64312. </tr>`;
  64313. } else {
  64314. html += `
  64315. <tr>
  64316. <td>${attributeName}</td>
  64317. <td>${transform(value)}</td>
  64318. </tr>`;
  64319. }
  64320. }
  64321. html += '</table>';
  64322. info.html(html);
  64323. this.selectedPoint = point;
  64324. } else {
  64325. // this.pickSphere.visible = false;
  64326. // this.selectedPoint = null;
  64327. this.viewer.scene.scene.add(this.viewerPickSphere);
  64328. let index = this.viewer.scene.scene.children.indexOf(this.viewerPickSphere);
  64329. if(index >= 0){
  64330. this.viewer.scene.scene.children.splice(index, 1);
  64331. }
  64332. this.viewer.removeEventListener("update", viewerPickSphereSizeHandler);
  64333. }
  64334. this.render();
  64335. }
  64336. this.mouse.copy(newMouse);
  64337. });
  64338. let onWheel = e => {
  64339. this.autoFit = false;
  64340. let delta = 0;
  64341. if (e.wheelDelta !== undefined) { // WebKit / Opera / Explorer 9
  64342. delta = e.wheelDelta;
  64343. } else if (e.detail !== undefined) { // Firefox
  64344. delta = -e.detail;
  64345. }
  64346. let ndelta = Math.sign(delta);
  64347. let cPos = [this.scaleX.invert(this.mouse.x), this.scaleY.invert(this.mouse.y)];
  64348. if (ndelta > 0) {
  64349. // + 10%
  64350. this.scale.multiplyScalar(1.1);
  64351. } else {
  64352. // - 10%
  64353. this.scale.multiplyScalar(100 / 110);
  64354. }
  64355. this.updateScales();
  64356. let ncPos = [this.scaleX.invert(this.mouse.x), this.scaleY.invert(this.mouse.y)];
  64357. this.camera.position.x -= ncPos[0] - cPos[0];
  64358. this.camera.position.z -= ncPos[1] - cPos[1];
  64359. this.render();
  64360. this.updateScales();
  64361. };
  64362. $(this.renderArea)[0].addEventListener('mousewheel', onWheel, false);
  64363. $(this.renderArea)[0].addEventListener('DOMMouseScroll', onWheel, false); // Firefox
  64364. $('#closeProfileContainer').click(() => {
  64365. this.hide();
  64366. });
  64367. let getProfilePoints = () => {
  64368. let points = new Points$1();
  64369. for(let [pointcloud, entry] of this.pointclouds){
  64370. for(let pointSet of entry.points){
  64371. let originPos = pointSet.data.position;
  64372. let trueElevationPosition = new Float32Array(originPos);
  64373. for(let i = 0; i < pointSet.numPoints; i++){
  64374. trueElevationPosition[3 * i + 2] += pointcloud.position.z;
  64375. }
  64376. pointSet.data.position = trueElevationPosition;
  64377. points.add(pointSet);
  64378. pointSet.data.position = originPos;
  64379. }
  64380. }
  64381. return points;
  64382. };
  64383. $('#potree_download_csv_icon').click(() => {
  64384. let points = getProfilePoints();
  64385. let string = CSVExporter.toString(points);
  64386. let blob = new Blob([string], {type: "text/string"});
  64387. $('#potree_download_profile_ortho_link').attr('href', URL.createObjectURL(blob));
  64388. });
  64389. $('#potree_download_las_icon').click(() => {
  64390. let points = getProfilePoints();
  64391. let buffer = LASExporter.toLAS(points);
  64392. let blob = new Blob([buffer], {type: "application/octet-binary"});
  64393. $('#potree_download_profile_link').attr('href', URL.createObjectURL(blob));
  64394. });
  64395. }
  64396. selectPoint (mileage, elevation, radius) {
  64397. let closest = {
  64398. distance: Infinity,
  64399. pointcloud: null,
  64400. points: null,
  64401. index: null
  64402. };
  64403. let pointBox = new Box2(
  64404. new Vector2$1(mileage - radius, elevation - radius),
  64405. new Vector2$1(mileage + radius, elevation + radius));
  64406. let numTested = 0;
  64407. let numSkipped = 0;
  64408. let numTestedPoints = 0;
  64409. let numSkippedPoints = 0;
  64410. for (let [pointcloud, entry] of this.pointclouds) {
  64411. for(let points of entry.points){
  64412. let collisionBox = new Box2(
  64413. new Vector2$1(points.projectedBox.min.x, points.projectedBox.min.z),
  64414. new Vector2$1(points.projectedBox.max.x, points.projectedBox.max.z)
  64415. );
  64416. let intersects = collisionBox.intersectsBox(pointBox);
  64417. if(!intersects){
  64418. numSkipped++;
  64419. numSkippedPoints += points.numPoints;
  64420. continue;
  64421. }
  64422. numTested++;
  64423. numTestedPoints += points.numPoints;
  64424. for (let i = 0; i < points.numPoints; i++) {
  64425. let m = points.data.mileage[i] - mileage;
  64426. let e = points.data.position[3 * i + 2] - elevation + pointcloud.position.z;
  64427. let r = Math.sqrt(m * m + e * e);
  64428. const withinDistance = r < radius && r < closest.distance;
  64429. let unfilteredClass = true;
  64430. if(points.data.classification){
  64431. const classification = pointcloud.material.classification;
  64432. const pointClassID = points.data.classification[i];
  64433. const pointClassValue = classification[pointClassID];
  64434. if(pointClassValue && (!pointClassValue.visible || pointClassValue.color.w === 0)){
  64435. unfilteredClass = false;
  64436. }
  64437. }
  64438. if (withinDistance && unfilteredClass) {
  64439. closest = {
  64440. distance: r,
  64441. pointcloud: pointcloud,
  64442. points: points,
  64443. index: i
  64444. };
  64445. }
  64446. }
  64447. }
  64448. }
  64449. //console.log(`nodes: ${numTested}, ${numSkipped} || points: ${numTestedPoints}, ${numSkippedPoints}`);
  64450. if (closest.distance < Infinity) {
  64451. let points = closest.points;
  64452. let point = {};
  64453. let attributes = Object.keys(points.data);
  64454. for (let attribute of attributes) {
  64455. let attributeData = points.data[attribute];
  64456. let itemSize = attributeData.length / points.numPoints;
  64457. let value = attributeData.subarray(itemSize * closest.index, itemSize * closest.index + itemSize);
  64458. if (value.length === 1) {
  64459. point[attribute] = value[0];
  64460. } else {
  64461. point[attribute] = value;
  64462. }
  64463. }
  64464. closest.point = point;
  64465. return closest;
  64466. } else {
  64467. return null;
  64468. }
  64469. }
  64470. initTHREE () {
  64471. this.renderer = new WebGLRenderer({alpha: true, premultipliedAlpha: false});
  64472. this.renderer.setClearColor(0x000000, 0);
  64473. this.renderer.setSize(10, 10);
  64474. this.renderer.autoClear = false;
  64475. this.renderArea.append($(this.renderer.domElement));
  64476. this.renderer.domElement.tabIndex = '2222';
  64477. $(this.renderer.domElement).css('width', '100%');
  64478. $(this.renderer.domElement).css('height', '100%');
  64479. {
  64480. let gl = this.renderer.getContext();
  64481. if(gl.createVertexArray == null){
  64482. let extVAO = gl.getExtension('OES_vertex_array_object');
  64483. if(!extVAO){
  64484. throw new Error("OES_vertex_array_object extension not supported");
  64485. }
  64486. gl.createVertexArray = extVAO.createVertexArrayOES.bind(extVAO);
  64487. gl.bindVertexArray = extVAO.bindVertexArrayOES.bind(extVAO);
  64488. }
  64489. }
  64490. this.camera = new OrthographicCamera(-1000, 1000, 1000, -1000, -1000, 1000);
  64491. /* */
  64492. if(window.axisYup){
  64493. }else {
  64494. this.camera.up.set(0, 0, 1);
  64495. this.camera.rotation.order = "ZXY";
  64496. this.camera.rotation.x = Math.PI / 2.0;
  64497. }
  64498. this.scene = new Scene();
  64499. this.profileScene = new Scene();
  64500. let sg = new SphereGeometry(1, 16, 16);
  64501. let sm = new MeshNormalMaterial();
  64502. this.pickSphere = new Mesh(sg, sm);
  64503. this.scene.add(this.pickSphere);
  64504. this.viewerPickSphere = new Mesh(sg, sm);
  64505. }
  64506. initSVG () {
  64507. let width = this.renderArea[0].clientWidth;
  64508. let height = this.renderArea[0].clientHeight;
  64509. let marginLeft = this.renderArea[0].offsetLeft;
  64510. this.svg.selectAll('*').remove();
  64511. this.scaleX = d3.scale.linear()
  64512. .domain([this.camera.left + this.camera.position.x, this.camera.right + this.camera.position.x])
  64513. .range([0, width]);
  64514. this.scaleY = d3.scale.linear()
  64515. .domain([this.camera.bottom + this.camera.position.z, this.camera.top + this.camera.position.z])
  64516. .range([height, 0]);
  64517. this.xAxis = d3.svg.axis()
  64518. .scale(this.scaleX)
  64519. .orient('bottom')
  64520. .innerTickSize(-height)
  64521. .outerTickSize(1)
  64522. .tickPadding(10)
  64523. .ticks(width / 50);
  64524. this.yAxis = d3.svg.axis()
  64525. .scale(this.scaleY)
  64526. .orient('left')
  64527. .innerTickSize(-width)
  64528. .outerTickSize(1)
  64529. .tickPadding(10)
  64530. .ticks(height / 20);
  64531. this.elXAxis = this.svg.append('g')
  64532. .attr('class', 'x axis')
  64533. .attr('transform', `translate(${marginLeft}, ${height})`)
  64534. .call(this.xAxis);
  64535. this.elYAxis = this.svg.append('g')
  64536. .attr('class', 'y axis')
  64537. .attr('transform', `translate(${marginLeft}, 0)`)
  64538. .call(this.yAxis);
  64539. }
  64540. addPoints (pointcloud, points) {
  64541. if(points.numPoints === 0){
  64542. return;
  64543. }
  64544. let entry = this.pointclouds.get(pointcloud);
  64545. if(!entry){
  64546. entry = new ProfileFakeOctree(pointcloud);
  64547. this.pointclouds.set(pointcloud, entry);
  64548. this.profileScene.add(entry);
  64549. let materialChanged = () => {
  64550. this.render();
  64551. };
  64552. materialChanged();
  64553. pointcloud.material.addEventListener('material_property_changed', materialChanged);
  64554. this.addEventListener("on_reset_once", () => {
  64555. pointcloud.material.removeEventListener('material_property_changed', materialChanged);
  64556. });
  64557. }
  64558. entry.addPoints(points);
  64559. this.projectedBox.union(entry.projectedBox);
  64560. if (this.autoFit && this.autoFitEnabled) {
  64561. let width = this.renderArea[0].clientWidth;
  64562. let height = this.renderArea[0].clientHeight;
  64563. let size = this.projectedBox.getSize(new Vector3());
  64564. let sx = width / size.x;
  64565. let sy = height / size.z;
  64566. let scale = Math.min(sx, sy);
  64567. let center = this.projectedBox.getCenter(new Vector3());
  64568. this.scale.set(scale, scale, 1);
  64569. this.camera.position.copy(center);
  64570. //console.log("camera: ", this.camera.position.toArray().join(", "));
  64571. }
  64572. //console.log(entry);
  64573. this.render();
  64574. let numPoints = 0;
  64575. for (let [key, value] of this.pointclouds.entries()) {
  64576. numPoints += value.points.reduce( (a, i) => a + i.numPoints, 0);
  64577. }
  64578. $(`#profile_num_points`).html(Utils.addCommas(numPoints));
  64579. }
  64580. reset () {
  64581. this.lastReset = new Date().getTime();
  64582. this.dispatchEvent({type: "on_reset_once"});
  64583. this.removeEventListeners("on_reset_once");
  64584. this.autoFit = true;
  64585. this.projectedBox = new Box3();
  64586. for(let [key, entry] of this.pointclouds){
  64587. entry.dispose();
  64588. }
  64589. this.pointclouds.clear();
  64590. this.mouseIsDown = false;
  64591. this.mouse.set(0, 0);
  64592. if(this.autoFitEnabled){
  64593. this.scale.set(1, 1, 1);
  64594. }
  64595. this.pickSphere.visible = false;
  64596. this.elRoot.find('#profileSelectionProperties').hide();
  64597. this.render();
  64598. }
  64599. show () {
  64600. this.elRoot.fadeIn();
  64601. this.enabled = true;
  64602. }
  64603. hide () {
  64604. this.elRoot.fadeOut();
  64605. this.enabled = false;
  64606. }
  64607. updateScales () {
  64608. let width = this.renderArea[0].clientWidth;
  64609. let height = this.renderArea[0].clientHeight;
  64610. let left = (-width / 2) / this.scale.x;
  64611. let right = (+width / 2) / this.scale.x;
  64612. let top = (+height / 2) / this.scale.y;
  64613. let bottom = (-height / 2) / this.scale.y;
  64614. this.camera.left = left;
  64615. this.camera.right = right;
  64616. this.camera.top = top;
  64617. this.camera.bottom = bottom;
  64618. this.camera.updateProjectionMatrix();
  64619. this.scaleX.domain([this.camera.left + this.camera.position.x, this.camera.right + this.camera.position.x])
  64620. .range([0, width]);
  64621. this.scaleY.domain([this.camera.bottom + this.camera.position.z, this.camera.top + this.camera.position.z])
  64622. .range([height, 0]);
  64623. let marginLeft = this.renderArea[0].offsetLeft;
  64624. this.xAxis.scale(this.scaleX)
  64625. .orient('bottom')
  64626. .innerTickSize(-height)
  64627. .outerTickSize(1)
  64628. .tickPadding(10)
  64629. .ticks(width / 50);
  64630. this.yAxis.scale(this.scaleY)
  64631. .orient('left')
  64632. .innerTickSize(-width)
  64633. .outerTickSize(1)
  64634. .tickPadding(10)
  64635. .ticks(height / 20);
  64636. this.elXAxis
  64637. .attr('transform', `translate(${marginLeft}, ${height})`)
  64638. .call(this.xAxis);
  64639. this.elYAxis
  64640. .attr('transform', `translate(${marginLeft}, 0)`)
  64641. .call(this.yAxis);
  64642. }
  64643. requestScaleUpdate(){
  64644. let threshold = 100;
  64645. let allowUpdate = ((this.lastReset === undefined) || (this.lastScaleUpdate === undefined))
  64646. || ((new Date().getTime() - this.lastReset) > threshold && (new Date().getTime() - this.lastScaleUpdate) > threshold);
  64647. if(allowUpdate){
  64648. this.updateScales();
  64649. this.lastScaleUpdate = new Date().getTime();
  64650. this.scaleUpdatePending = false;
  64651. }else if(!this.scaleUpdatePending) {
  64652. setTimeout(this.requestScaleUpdate.bind(this), 100);
  64653. this.scaleUpdatePending = true;
  64654. }
  64655. }
  64656. render () {
  64657. let width = this.renderArea[0].clientWidth;
  64658. let height = this.renderArea[0].clientHeight;
  64659. let {renderer, pRenderer, camera, profileScene, scene} = this;
  64660. let {scaleX, pickSphere} = this;
  64661. renderer.setSize(width, height);
  64662. renderer.setClearColor(0x000000, 0);
  64663. renderer.clear(true, true, false);
  64664. for(let pointcloud of this.pointclouds.keys()){
  64665. let source = pointcloud.material;
  64666. let target = this.pointclouds.get(pointcloud).material;
  64667. copyMaterial(source, target);
  64668. target.size = 2;
  64669. }
  64670. pRenderer.render(profileScene, camera, null);
  64671. let radius = Math.abs(scaleX.invert(0) - scaleX.invert(5));
  64672. if (radius === 0) {
  64673. pickSphere.visible = false;
  64674. } else {
  64675. pickSphere.scale.set(radius, radius, radius);
  64676. pickSphere.visible = true;
  64677. }
  64678. renderer.render(scene, camera);
  64679. this.requestScaleUpdate();
  64680. }
  64681. };
  64682. class ProfileWindowController {
  64683. constructor (viewer) {
  64684. this.viewer = viewer;
  64685. this.profileWindow = viewer.profileWindow;
  64686. this.profile = null;
  64687. this.numPoints = 0;
  64688. this.threshold = 60 * 1000;
  64689. this.rotateAmount = 10;
  64690. this.scheduledRecomputeTime = null;
  64691. this.enabled = true;
  64692. this.requests = [];
  64693. this._recompute = () => { this.recompute(); };
  64694. this.viewer.addEventListener("scene_changed", e => {
  64695. e.oldScene.removeEventListener("pointcloud_added", this._recompute);
  64696. e.scene.addEventListener("pointcloud_added", this._recompute);
  64697. });
  64698. this.viewer.scene.addEventListener("pointcloud_added", this._recompute);
  64699. $("#potree_profile_rotate_amount").val(parseInt(this.rotateAmount));
  64700. $("#potree_profile_rotate_amount").on("input", (e) => {
  64701. const str = $("#potree_profile_rotate_amount").val();
  64702. if(!isNaN(str)){
  64703. const value = parseFloat(str);
  64704. this.rotateAmount = value;
  64705. $("#potree_profile_rotate_amount").css("background-color", "");
  64706. }else {
  64707. $("#potree_profile_rotate_amount").css("background-color", "#ff9999");
  64708. }
  64709. });
  64710. const rotate = (radians) => {
  64711. const profile = this.profile;
  64712. const points = profile.points;
  64713. const start = points[0];
  64714. const end = points[points.length - 1];
  64715. const center = start.clone().add(end).multiplyScalar(0.5);
  64716. const mMoveOrigin = new Matrix4().makeTranslation(-center.x, -center.y, -center.z);
  64717. const mRotate = new Matrix4().makeRotationZ(radians);
  64718. const mMoveBack = new Matrix4().makeTranslation(center.x, center.y, center.z);
  64719. //const transform = mMoveOrigin.multiply(mRotate).multiply(mMoveBack);
  64720. const transform = mMoveBack.multiply(mRotate).multiply(mMoveOrigin);
  64721. const rotatedPoints = points.map( point => point.clone().applyMatrix4(transform) );
  64722. this.profileWindow.autoFitEnabled = false;
  64723. for(let i = 0; i < points.length; i++){
  64724. profile.setPosition(i, rotatedPoints[i]);
  64725. }
  64726. };
  64727. $("#potree_profile_rotate_cw").click( () => {
  64728. const radians = MathUtils.degToRad(this.rotateAmount);
  64729. rotate(-radians);
  64730. });
  64731. $("#potree_profile_rotate_ccw").click( () => {
  64732. const radians = MathUtils.degToRad(this.rotateAmount);
  64733. rotate(radians);
  64734. });
  64735. $("#potree_profile_move_forward").click( () => {
  64736. const profile = this.profile;
  64737. const points = profile.points;
  64738. const start = points[0];
  64739. const end = points[points.length - 1];
  64740. const dir = end.clone().sub(start).normalize();
  64741. const up = new Vector3(0, 0, 1);
  64742. const forward = up.cross(dir);
  64743. const move = forward.clone().multiplyScalar(profile.width / 2);
  64744. this.profileWindow.autoFitEnabled = false;
  64745. for(let i = 0; i < points.length; i++){
  64746. profile.setPosition(i, points[i].clone().add(move));
  64747. }
  64748. });
  64749. $("#potree_profile_move_backward").click( () => {
  64750. const profile = this.profile;
  64751. const points = profile.points;
  64752. const start = points[0];
  64753. const end = points[points.length - 1];
  64754. const dir = end.clone().sub(start).normalize();
  64755. const up = new Vector3(0, 0, 1);
  64756. const forward = up.cross(dir);
  64757. const move = forward.clone().multiplyScalar(-profile.width / 2);
  64758. this.profileWindow.autoFitEnabled = false;
  64759. for(let i = 0; i < points.length; i++){
  64760. profile.setPosition(i, points[i].clone().add(move));
  64761. }
  64762. });
  64763. }
  64764. setProfile (profile) {
  64765. if (this.profile !== null && this.profile !== profile) {
  64766. this.profile.removeEventListener('marker_moved', this._recompute);
  64767. this.profile.removeEventListener('marker_added', this._recompute);
  64768. this.profile.removeEventListener('marker_removed', this._recompute);
  64769. this.profile.removeEventListener('width_changed', this._recompute);
  64770. }
  64771. this.profile = profile;
  64772. {
  64773. this.profile.addEventListener('marker_moved', this._recompute);
  64774. this.profile.addEventListener('marker_added', this._recompute);
  64775. this.profile.addEventListener('marker_removed', this._recompute);
  64776. this.profile.addEventListener('width_changed', this._recompute);
  64777. }
  64778. this.recompute();
  64779. }
  64780. reset () {
  64781. this.profileWindow.reset();
  64782. this.numPoints = 0;
  64783. if (this.profile) {
  64784. for (let request of this.requests) {
  64785. request.cancel();
  64786. }
  64787. }
  64788. }
  64789. progressHandler (pointcloud, progress) {
  64790. for (let segment of progress.segments) {
  64791. this.profileWindow.addPoints(pointcloud, segment.points);
  64792. this.numPoints += segment.points.numPoints;
  64793. }
  64794. }
  64795. cancel () {
  64796. for (let request of this.requests) {
  64797. request.cancel();
  64798. // request.finishLevelThenCancel();
  64799. }
  64800. this.requests = [];
  64801. };
  64802. finishLevelThenCancel(){
  64803. for (let request of this.requests) {
  64804. request.finishLevelThenCancel();
  64805. }
  64806. this.requests = [];
  64807. }
  64808. recompute () {
  64809. if (!this.profile) {
  64810. return;
  64811. }
  64812. if (this.scheduledRecomputeTime !== null && this.scheduledRecomputeTime > new Date().getTime()) {
  64813. return;
  64814. } else {
  64815. this.scheduledRecomputeTime = new Date().getTime() + 100;
  64816. }
  64817. this.scheduledRecomputeTime = null;
  64818. this.reset();
  64819. for (let pointcloud of this.viewer.scene.pointclouds.filter(p => p.visible)) {
  64820. let request = pointcloud.getPointsInProfile(this.profile, null, {
  64821. 'onProgress': (event) => {
  64822. if (!this.enabled) {
  64823. return;
  64824. }
  64825. this.progressHandler(pointcloud, event.points);
  64826. if (this.numPoints > this.threshold) {
  64827. this.finishLevelThenCancel();
  64828. }
  64829. },
  64830. 'onFinish': (event) => {
  64831. if (!this.enabled) {
  64832. }
  64833. },
  64834. 'onCancel': () => {
  64835. if (!this.enabled) {
  64836. }
  64837. }
  64838. });
  64839. this.requests.push(request);
  64840. }
  64841. }
  64842. };
  64843. /**
  64844. *
  64845. * @author sigeom sa / http://sigeom.ch
  64846. * @author Ioda-Net Sàrl / https://www.ioda-net.ch/
  64847. * @author Markus Schütz / http://potree.org
  64848. *
  64849. */
  64850. class GeoJSONExporter{
  64851. static measurementToFeatures (measurement) {
  64852. let coords = measurement.points.map(e => e.position.toArray());
  64853. let features = [];
  64854. if (coords.length === 1) {
  64855. let feature = {
  64856. type: 'Feature',
  64857. geometry: {
  64858. type: 'Point',
  64859. coordinates: coords[0]
  64860. },
  64861. properties: {
  64862. name: measurement.name
  64863. }
  64864. };
  64865. features.push(feature);
  64866. } else if (coords.length > 1 && !measurement.closed) {
  64867. let object = {
  64868. 'type': 'Feature',
  64869. 'geometry': {
  64870. 'type': 'LineString',
  64871. 'coordinates': coords
  64872. },
  64873. 'properties': {
  64874. name: measurement.name
  64875. }
  64876. };
  64877. features.push(object);
  64878. } else if (coords.length > 1 && measurement.closed) {
  64879. let object = {
  64880. 'type': 'Feature',
  64881. 'geometry': {
  64882. 'type': 'Polygon',
  64883. 'coordinates': [[...coords, coords[0]]]
  64884. },
  64885. 'properties': {
  64886. name: measurement.name
  64887. }
  64888. };
  64889. features.push(object);
  64890. }
  64891. if (measurement.showDistances) {
  64892. measurement.edgeLabels.forEach((label) => {
  64893. let labelPoint = {
  64894. type: 'Feature',
  64895. geometry: {
  64896. type: 'Point',
  64897. coordinates: label.position.toArray()
  64898. },
  64899. properties: {
  64900. distance: label.text
  64901. }
  64902. };
  64903. features.push(labelPoint);
  64904. });
  64905. }
  64906. if (measurement.showArea) {
  64907. let point = measurement.areaLabel.position;
  64908. let labelArea = {
  64909. type: 'Feature',
  64910. geometry: {
  64911. type: 'Point',
  64912. coordinates: point.toArray()
  64913. },
  64914. properties: {
  64915. area: measurement.areaLabel.text
  64916. }
  64917. };
  64918. features.push(labelArea);
  64919. }
  64920. return features;
  64921. }
  64922. static toString (measurements) {
  64923. if (!(measurements instanceof Array)) {
  64924. measurements = [measurements];
  64925. }
  64926. measurements = measurements.filter(m => m instanceof Measure);
  64927. let features = [];
  64928. for (let measure of measurements) {
  64929. let f = GeoJSONExporter.measurementToFeatures(measure);
  64930. features = features.concat(f);
  64931. }
  64932. let geojson = {
  64933. 'type': 'FeatureCollection',
  64934. 'features': features
  64935. };
  64936. return JSON.stringify(geojson, null, '\t');
  64937. }
  64938. }
  64939. /**
  64940. *
  64941. * @author sigeom sa / http://sigeom.ch
  64942. * @author Ioda-Net Sàrl / https://www.ioda-net.ch/
  64943. * @author Markus Schuetz / http://potree.org
  64944. *
  64945. */
  64946. class DXFExporter {
  64947. static measurementPointSection (measurement) {
  64948. let position = measurement.points[0].position;
  64949. if (!position) {
  64950. return '';
  64951. }
  64952. let dxfSection = `0
  64953. CIRCLE
  64954. 8
  64955. layer_point
  64956. 10
  64957. ${position.x}
  64958. 20
  64959. ${position.y}
  64960. 30
  64961. ${position.z}
  64962. 40
  64963. 1.0
  64964. `;
  64965. return dxfSection;
  64966. }
  64967. static measurementPolylineSection (measurement) {
  64968. // bit code for polygons/polylines:
  64969. // https://www.autodesk.com/techpubs/autocad/acad2000/dxf/polyline_dxf_06.htm
  64970. let geomCode = 8;
  64971. if (measurement.closed) {
  64972. geomCode += 1;
  64973. }
  64974. let dxfSection = `0
  64975. POLYLINE
  64976. 8
  64977. layer_polyline
  64978. 62
  64979. 1
  64980. 66
  64981. 1
  64982. 10
  64983. 0.0
  64984. 20
  64985. 0.0
  64986. 30
  64987. 0.0
  64988. 70
  64989. ${geomCode}
  64990. `;
  64991. let xMax = 0.0;
  64992. let yMax = 0.0;
  64993. let zMax = 0.0;
  64994. for (let point of measurement.points) {
  64995. point = point.position;
  64996. xMax = Math.max(xMax, point.x);
  64997. yMax = Math.max(yMax, point.y);
  64998. zMax = Math.max(zMax, point.z);
  64999. dxfSection += `0
  65000. VERTEX
  65001. 8
  65002. 0
  65003. 10
  65004. ${point.x}
  65005. 20
  65006. ${point.y}
  65007. 30
  65008. ${point.z}
  65009. 70
  65010. 32
  65011. `;
  65012. }
  65013. dxfSection += `0
  65014. SEQEND
  65015. `;
  65016. return dxfSection;
  65017. }
  65018. static measurementSection (measurement) {
  65019. // if(measurement.points.length <= 1){
  65020. // return "";
  65021. // }
  65022. if (measurement.points.length === 0) {
  65023. return '';
  65024. } else if (measurement.points.length === 1) {
  65025. return DXFExporter.measurementPointSection(measurement);
  65026. } else if (measurement.points.length >= 2) {
  65027. return DXFExporter.measurementPolylineSection(measurement);
  65028. }
  65029. }
  65030. static toString(measurements){
  65031. if (!(measurements instanceof Array)) {
  65032. measurements = [measurements];
  65033. }
  65034. measurements = measurements.filter(m => m instanceof Measure);
  65035. let points = measurements.filter(m => (m instanceof Measure))
  65036. .map(m => m.points)
  65037. .reduce((a, v) => a.concat(v))
  65038. .map(p => p.position);
  65039. let min = new Vector3(Infinity, Infinity, Infinity);
  65040. let max = new Vector3(-Infinity, -Infinity, -Infinity);
  65041. for (let point of points) {
  65042. min.min(point);
  65043. max.max(point);
  65044. }
  65045. let dxfHeader = `999
  65046. DXF created from potree
  65047. 0
  65048. SECTION
  65049. 2
  65050. HEADER
  65051. 9
  65052. $ACADVER
  65053. 1
  65054. AC1006
  65055. 9
  65056. $INSBASE
  65057. 10
  65058. 0.0
  65059. 20
  65060. 0.0
  65061. 30
  65062. 0.0
  65063. 9
  65064. $EXTMIN
  65065. 10
  65066. ${min.x}
  65067. 20
  65068. ${min.y}
  65069. 30
  65070. ${min.z}
  65071. 9
  65072. $EXTMAX
  65073. 10
  65074. ${max.x}
  65075. 20
  65076. ${max.y}
  65077. 30
  65078. ${max.z}
  65079. 0
  65080. ENDSEC
  65081. `;
  65082. let dxfBody = `0
  65083. SECTION
  65084. 2
  65085. ENTITIES
  65086. `;
  65087. for (let measurement of measurements) {
  65088. dxfBody += DXFExporter.measurementSection(measurement);
  65089. }
  65090. dxfBody += `0
  65091. ENDSEC
  65092. `;
  65093. let dxf = dxfHeader + dxfBody + '0\nEOF';
  65094. return dxf;
  65095. }
  65096. }
  65097. class MeasurePanel{
  65098. constructor(viewer, measurement, propertiesPanel){
  65099. this.viewer = viewer;
  65100. this.measurement = measurement;
  65101. this.propertiesPanel = propertiesPanel;
  65102. this._update = () => { this.update(); };
  65103. }
  65104. createCoordinatesTable(points){
  65105. let table = $(`
  65106. <table class="measurement_value_table">
  65107. <tr>
  65108. <th>x</th>
  65109. <th>y</th>
  65110. <th>z</th>
  65111. <th></th>
  65112. </tr>
  65113. </table>
  65114. `);
  65115. let copyIconPath = Potree.resourcePath + '/icons/copy.svg';
  65116. for (let point of points) {
  65117. let x = Utils.addCommas(point.x.toFixed(3));
  65118. let y = Utils.addCommas(point.y.toFixed(3));
  65119. let z = Utils.addCommas(point.z.toFixed(3));
  65120. let row = $(`
  65121. <tr>
  65122. <td><span>${x}</span></td>
  65123. <td><span>${y}</span></td>
  65124. <td><span>${z}</span></td>
  65125. <td align="right" style="width: 25%">
  65126. <img name="copy" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  65127. </td>
  65128. </tr>
  65129. `);
  65130. this.elCopy = row.find("img[name=copy]");
  65131. this.elCopy.click( () => {
  65132. let msg = point.toArray().map(c => c.toFixed(3)).join(", ");
  65133. Utils.clipboardCopy(msg);
  65134. this.viewer.postMessage(
  65135. `Copied value to clipboard: <br>'${msg}'`,
  65136. {duration: 3000});
  65137. });
  65138. table.append(row);
  65139. }
  65140. return table;
  65141. };
  65142. createAttributesTable(){
  65143. let elTable = $('<table class="measurement_value_table"></table>');
  65144. let point = this.measurement.points[0];
  65145. /* for(let attributeName of Object.keys(point)){
  65146. if(attributeName === "position"){
  65147. }else if(attributeName === "rgba"){
  65148. let color = point.rgba;
  65149. let text = color.join(', ');
  65150. elTable.append($(`
  65151. <tr>
  65152. <td>rgb</td>
  65153. <td>${text}</td>
  65154. </tr>
  65155. `));
  65156. }else{
  65157. let value = point[attributeName];
  65158. let text = value.join(', ');
  65159. elTable.append($(`
  65160. <tr>
  65161. <td>${attributeName}</td>
  65162. <td>${text}</td>
  65163. </tr>
  65164. `));
  65165. }
  65166. } */
  65167. return elTable;
  65168. }
  65169. update(){
  65170. }
  65171. };
  65172. class DistancePanel extends MeasurePanel{
  65173. constructor(viewer, measurement, propertiesPanel){
  65174. super(viewer, measurement, propertiesPanel);
  65175. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65176. this.elContent = $(`
  65177. <div class="measurement_content selectable">
  65178. <span class="coordinates_table_container"></span>
  65179. <br>
  65180. <table id="distances_table" class="measurement_value_table"></table>
  65181. <!-- ACTIONS -->
  65182. <div style="display: flex; margin-top: 12px">
  65183. <span>
  65184. <input type="button" name="make_profile" value="profile from measure" />
  65185. </span>
  65186. <span style="flex-grow: 1"></span>
  65187. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65188. </div>
  65189. </div>
  65190. `);
  65191. this.elRemove = this.elContent.find("img[name=remove]");
  65192. this.elRemove.click( () => {
  65193. this.viewer.scene.removeMeasurement(measurement);
  65194. });
  65195. this.elMakeProfile = this.elContent.find("input[name=make_profile]");
  65196. this.elMakeProfile.click( () => {
  65197. //measurement.points;
  65198. const profile = new Profile();
  65199. profile.name = measurement.name;
  65200. profile.width = measurement.getTotalDistance() / 50;
  65201. for(const point of measurement.points){
  65202. profile.addMarker(point.position.clone());
  65203. }
  65204. this.viewer.scene.addProfile(profile);
  65205. });
  65206. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65207. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65208. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65209. this.update();
  65210. }
  65211. update(){
  65212. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65213. elCoordiantesContainer.empty();
  65214. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points));
  65215. let positions = this.measurement.points;
  65216. let distances = [];
  65217. for (let i = 0; i < positions.length - 1; i++) {
  65218. let d = positions[i].distanceTo(positions[i + 1]);
  65219. distances.push(d.toFixed(3));
  65220. }
  65221. let totalDistance = this.measurement.getTotalDistance().toFixed(3);
  65222. let elDistanceTable = this.elContent.find(`#distances_table`);
  65223. elDistanceTable.empty();
  65224. for (let i = 0; i < distances.length; i++) {
  65225. let label = (i === 0) ? 'Distances: ' : '';
  65226. let distance = distances[i];
  65227. let elDistance = $(`
  65228. <tr>
  65229. <th>${label}</th>
  65230. <td style="width: 100%; padding-left: 10px">${distance}</td>
  65231. </tr>`);
  65232. elDistanceTable.append(elDistance);
  65233. }
  65234. let elTotal = $(`
  65235. <tr>
  65236. <th>Total: </td><td style="width: 100%; padding-left: 10px">${totalDistance}</th>
  65237. </tr>`);
  65238. elDistanceTable.append(elTotal);
  65239. }
  65240. };
  65241. class PointPanel extends MeasurePanel{
  65242. constructor(viewer, measurement, propertiesPanel){
  65243. super(viewer, measurement, propertiesPanel);
  65244. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65245. this.elContent = $(`
  65246. <div class="measurement_content selectable">
  65247. <span class="coordinates_table_container"></span>
  65248. <br>
  65249. <span class="attributes_table_container"></span>
  65250. <!-- ACTIONS -->
  65251. <div style="display: flex; margin-top: 12px">
  65252. <span></span>
  65253. <span style="flex-grow: 1"></span>
  65254. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65255. </div>
  65256. </div>
  65257. `);
  65258. this.elRemove = this.elContent.find("img[name=remove]");
  65259. this.elRemove.click( () => {
  65260. this.viewer.scene.removeMeasurement(measurement);
  65261. });
  65262. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65263. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65264. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65265. this.update();
  65266. }
  65267. update(){
  65268. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65269. elCoordiantesContainer.empty();
  65270. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points));
  65271. let elAttributesContainer = this.elContent.find('.attributes_table_container');
  65272. elAttributesContainer.empty();
  65273. elAttributesContainer.append(this.createAttributesTable());
  65274. }
  65275. };
  65276. class AreaPanel extends MeasurePanel{
  65277. constructor(viewer, measurement, propertiesPanel){
  65278. super(viewer, measurement, propertiesPanel);
  65279. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65280. this.elContent = $(`
  65281. <div class="measurement_content selectable">
  65282. <span class="coordinates_table_container"></span>
  65283. <br>
  65284. <span style="font-weight: bold">Area: </span>
  65285. <span id="measurement_area"></span>
  65286. <!-- ACTIONS -->
  65287. <div style="display: flex; margin-top: 12px">
  65288. <span></span>
  65289. <span style="flex-grow: 1"></span>
  65290. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65291. </div>
  65292. </div>
  65293. `);
  65294. this.elRemove = this.elContent.find("img[name=remove]");
  65295. this.elRemove.click( () => {
  65296. this.viewer.scene.removeMeasurement(measurement);
  65297. });
  65298. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65299. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65300. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65301. this.update();
  65302. }
  65303. update(){
  65304. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65305. elCoordiantesContainer.empty();
  65306. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points));
  65307. let elArea = this.elContent.find(`#measurement_area`);
  65308. elArea.html(this.measurement.area.value.toFixed(3));
  65309. }
  65310. };
  65311. class AnglePanel extends MeasurePanel{
  65312. constructor(viewer, measurement, propertiesPanel){
  65313. super(viewer, measurement, propertiesPanel);
  65314. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65315. this.elContent = $(`
  65316. <div class="measurement_content selectable">
  65317. <span class="coordinates_table_container"></span>
  65318. <br>
  65319. <table class="measurement_value_table">
  65320. <tr>
  65321. <th>\u03b1</th>
  65322. <th>\u03b2</th>
  65323. <th>\u03b3</th>
  65324. </tr>
  65325. <tr>
  65326. <td align="center" id="angle_cell_alpha" style="width: 33%"></td>
  65327. <td align="center" id="angle_cell_betta" style="width: 33%"></td>
  65328. <td align="center" id="angle_cell_gamma" style="width: 33%"></td>
  65329. </tr>
  65330. </table>
  65331. <!-- ACTIONS -->
  65332. <div style="display: flex; margin-top: 12px">
  65333. <span></span>
  65334. <span style="flex-grow: 1"></span>
  65335. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65336. </div>
  65337. </div>
  65338. `);
  65339. this.elRemove = this.elContent.find("img[name=remove]");
  65340. this.elRemove.click( () => {
  65341. this.viewer.scene.removeMeasurement(measurement);
  65342. });
  65343. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65344. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65345. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65346. this.update();
  65347. }
  65348. update(){
  65349. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65350. elCoordiantesContainer.empty();
  65351. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position)));
  65352. let angles = [];
  65353. for(let i = 0; i < this.measurement.points.length; i++){
  65354. angles.push(this.measurement.getAngle(i) * (180.0 / Math.PI));
  65355. }
  65356. angles = angles.map(a => a.toFixed(1) + '\u00B0');
  65357. let elAlpha = this.elContent.find(`#angle_cell_alpha`);
  65358. let elBetta = this.elContent.find(`#angle_cell_betta`);
  65359. let elGamma = this.elContent.find(`#angle_cell_gamma`);
  65360. elAlpha.html(angles[0]);
  65361. elBetta.html(angles[1]);
  65362. elGamma.html(angles[2]);
  65363. }
  65364. };
  65365. class CirclePanel extends MeasurePanel{
  65366. constructor(viewer, measurement, propertiesPanel){
  65367. super(viewer, measurement, propertiesPanel);
  65368. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65369. this.elContent = $(`
  65370. <div class="measurement_content selectable">
  65371. <span class="coordinates_table_container"></span>
  65372. <br>
  65373. <table id="infos_table" class="measurement_value_table"></table>
  65374. <!-- ACTIONS -->
  65375. <div style="display: flex; margin-top: 12px">
  65376. <span></span>
  65377. <span style="flex-grow: 1"></span>
  65378. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65379. </div>
  65380. </div>
  65381. `);
  65382. this.elRemove = this.elContent.find("img[name=remove]");
  65383. this.elRemove.click( () => {
  65384. this.viewer.scene.removeMeasurement(measurement);
  65385. });
  65386. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65387. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65388. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65389. this.update();
  65390. }
  65391. update(){
  65392. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65393. elCoordiantesContainer.empty();
  65394. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position)));
  65395. const elInfos = this.elContent.find(`#infos_table`);
  65396. if(this.measurement.points.length !== 3){
  65397. elInfos.empty();
  65398. return;
  65399. }
  65400. const A = this.measurement.points[0].position;
  65401. const B = this.measurement.points[1].position;
  65402. const C = this.measurement.points[2].position;
  65403. const center = Potree.Utils.computeCircleCenter(A, B, C);
  65404. const radius = center.distanceTo(A);
  65405. const circumference = 2 * Math.PI * radius;
  65406. const format = (number) => {
  65407. return Potree.Utils.addCommas(number.toFixed(3));
  65408. };
  65409. const txtCenter = `${format(center.x)} ${format(center.y)} ${format(center.z)}`;
  65410. const txtRadius = format(radius);
  65411. const txtCircumference = format(circumference);
  65412. const thStyle = `style="text-align: left"`;
  65413. const tdStyle = `style="width: 100%; padding: 5px;"`;
  65414. elInfos.html(`
  65415. <tr>
  65416. <th ${thStyle}>Center: </th>
  65417. <td ${tdStyle}></td>
  65418. </tr>
  65419. <tr>
  65420. <td ${tdStyle} colspan="2">
  65421. ${txtCenter}
  65422. </td>
  65423. </tr>
  65424. <tr>
  65425. <th ${thStyle}>Radius: </th>
  65426. <td ${tdStyle}>${txtRadius}</td>
  65427. </tr>
  65428. <tr>
  65429. <th ${thStyle}>Circumference: </th>
  65430. <td ${tdStyle}>${txtCircumference}</td>
  65431. </tr>
  65432. `);
  65433. }
  65434. };
  65435. class HeightPanel extends MeasurePanel{
  65436. constructor(viewer, measurement, propertiesPanel){
  65437. super(viewer, measurement, propertiesPanel);
  65438. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65439. this.elContent = $(`
  65440. <div class="measurement_content selectable">
  65441. <span class="coordinates_table_container"></span>
  65442. <br>
  65443. <span id="height_label">Height: </span><br>
  65444. <!-- ACTIONS -->
  65445. <div style="display: flex; margin-top: 12px">
  65446. <span></span>
  65447. <span style="flex-grow: 1"></span>
  65448. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65449. </div>
  65450. </div>
  65451. `);
  65452. this.elRemove = this.elContent.find("img[name=remove]");
  65453. this.elRemove.click( () => {
  65454. this.viewer.scene.removeMeasurement(measurement);
  65455. });
  65456. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65457. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65458. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65459. this.update();
  65460. }
  65461. update(){
  65462. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65463. elCoordiantesContainer.empty();
  65464. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position)));
  65465. {
  65466. let points = this.measurement.points;
  65467. let sorted = points.slice().sort((a, b) => a.position.z - b.position.z);
  65468. let lowPoint = sorted[0].position.clone();
  65469. let highPoint = sorted[sorted.length - 1].position.clone();
  65470. let min = lowPoint.z;
  65471. let max = highPoint.z;
  65472. let height = max - min;
  65473. height = height.toFixed(3);
  65474. this.elHeightLabel = this.elContent.find(`#height_label`);
  65475. this.elHeightLabel.html(`<b>Height:</b> ${height}`);
  65476. }
  65477. }
  65478. };
  65479. class VolumePanel extends MeasurePanel{
  65480. constructor(viewer, measurement, propertiesPanel){
  65481. super(viewer, measurement, propertiesPanel);
  65482. let copyIconPath = Potree.resourcePath + '/icons/copy.svg';
  65483. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65484. let lblLengthText = new Map([
  65485. [BoxVolume, "length"],
  65486. [SphereVolume, "rx"],
  65487. ]).get(measurement.constructor);
  65488. let lblWidthText = new Map([
  65489. [BoxVolume, "width"],
  65490. [SphereVolume, "ry"],
  65491. ]).get(measurement.constructor);
  65492. let lblHeightText = new Map([
  65493. [BoxVolume, "height"],
  65494. [SphereVolume, "rz"],
  65495. ]).get(measurement.constructor);
  65496. this.elContent = $(`
  65497. <div class="measurement_content selectable">
  65498. <span class="coordinates_table_container"></span>
  65499. <table class="measurement_value_table">
  65500. <tr>
  65501. <th>\u03b1</th>
  65502. <th>\u03b2</th>
  65503. <th>\u03b3</th>
  65504. <th></th>
  65505. </tr>
  65506. <tr>
  65507. <td align="center" id="angle_cell_alpha" style="width: 33%"></td>
  65508. <td align="center" id="angle_cell_betta" style="width: 33%"></td>
  65509. <td align="center" id="angle_cell_gamma" style="width: 33%"></td>
  65510. <td align="right" style="width: 25%">
  65511. <img name="copyRotation" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  65512. </td>
  65513. </tr>
  65514. </table>
  65515. <table class="measurement_value_table">
  65516. <tr>
  65517. <th>${lblLengthText}</th>
  65518. <th>${lblWidthText}</th>
  65519. <th>${lblHeightText}</th>
  65520. <th></th>
  65521. </tr>
  65522. <tr>
  65523. <td align="center" id="cell_length" style="width: 33%"></td>
  65524. <td align="center" id="cell_width" style="width: 33%"></td>
  65525. <td align="center" id="cell_height" style="width: 33%"></td>
  65526. <td align="right" style="width: 25%">
  65527. <img name="copyScale" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  65528. </td>
  65529. </tr>
  65530. </table>
  65531. <br>
  65532. <span style="font-weight: bold">Volume: </span>
  65533. <span id="measurement_volume"></span>
  65534. <!--
  65535. <li>
  65536. <label style="whitespace: nowrap">
  65537. <input id="volume_show" type="checkbox"/>
  65538. <span>show volume</span>
  65539. </label>
  65540. </li>-->
  65541. <li>
  65542. <label style="whitespace: nowrap">
  65543. <input id="volume_clip" type="checkbox"/>
  65544. <span>make clip volume</span>
  65545. </label>
  65546. </li>
  65547. <li style="margin-top: 10px">
  65548. <input name="download_volume" type="button" value="prepare download" style="width: 100%" />
  65549. <div name="download_message"></div>
  65550. </li>
  65551. <!-- ACTIONS -->
  65552. <li style="display: grid; grid-template-columns: auto auto; grid-column-gap: 5px; margin-top: 10px">
  65553. <input id="volume_reset_orientation" type="button" value="reset orientation"/>
  65554. <input id="volume_make_uniform" type="button" value="make uniform"/>
  65555. </li>
  65556. <div style="display: flex; margin-top: 12px">
  65557. <span></span>
  65558. <span style="flex-grow: 1"></span>
  65559. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65560. </div>
  65561. </div>
  65562. `);
  65563. { // download
  65564. this.elDownloadButton = this.elContent.find("input[name=download_volume]");
  65565. if(this.propertiesPanel.viewer.server){
  65566. this.elDownloadButton.click(() => this.download());
  65567. } else {
  65568. this.elDownloadButton.hide();
  65569. }
  65570. }
  65571. this.elCopyRotation = this.elContent.find("img[name=copyRotation]");
  65572. this.elCopyRotation.click( () => {
  65573. let rotation = this.measurement.rotation.toArray().slice(0, 3);
  65574. let msg = rotation.map(c => c.toFixed(3)).join(", ");
  65575. Utils.clipboardCopy(msg);
  65576. this.viewer.postMessage(
  65577. `Copied value to clipboard: <br>'${msg}'`,
  65578. {duration: 3000});
  65579. });
  65580. this.elCopyScale = this.elContent.find("img[name=copyScale]");
  65581. this.elCopyScale.click( () => {
  65582. let scale = this.measurement.scale.toArray();
  65583. let msg = scale.map(c => c.toFixed(3)).join(", ");
  65584. Utils.clipboardCopy(msg);
  65585. this.viewer.postMessage(
  65586. `Copied value to clipboard: <br>'${msg}'`,
  65587. {duration: 3000});
  65588. });
  65589. this.elRemove = this.elContent.find("img[name=remove]");
  65590. this.elRemove.click( () => {
  65591. this.viewer.scene.removeVolume(measurement);
  65592. });
  65593. this.elContent.find("#volume_reset_orientation").click(() => {
  65594. measurement.rotation.set(0, 0, 0);
  65595. });
  65596. this.elContent.find("#volume_make_uniform").click(() => {
  65597. let mean = (measurement.scale.x + measurement.scale.y + measurement.scale.z) / 3;
  65598. measurement.scale.set(mean, mean, mean);
  65599. });
  65600. this.elCheckClip = this.elContent.find('#volume_clip');
  65601. this.elCheckClip.click(event => {
  65602. this.measurement.clip = event.target.checked;
  65603. });
  65604. this.elCheckShow = this.elContent.find('#volume_show');
  65605. this.elCheckShow.click(event => {
  65606. this.measurement.visible = event.target.checked;
  65607. });
  65608. this.propertiesPanel.addVolatileListener(measurement, "position_changed", this._update);
  65609. this.propertiesPanel.addVolatileListener(measurement, "orientation_changed", this._update);
  65610. this.propertiesPanel.addVolatileListener(measurement, "scale_changed", this._update);
  65611. this.propertiesPanel.addVolatileListener(measurement, "clip_changed", this._update);
  65612. this.update();
  65613. }
  65614. async download(){
  65615. let clipBox = this.measurement;
  65616. let regions = [];
  65617. //for(let clipBox of boxes){
  65618. {
  65619. let toClip = clipBox.matrixWorld;
  65620. let px = new Vector3(+0.5, 0, 0).applyMatrix4(toClip);
  65621. let nx = new Vector3(-0.5, 0, 0).applyMatrix4(toClip);
  65622. let py = new Vector3(0, +0.5, 0).applyMatrix4(toClip);
  65623. let ny = new Vector3(0, -0.5, 0).applyMatrix4(toClip);
  65624. let pz = new Vector3(0, 0, +0.5).applyMatrix4(toClip);
  65625. let nz = new Vector3(0, 0, -0.5).applyMatrix4(toClip);
  65626. let pxN = new Vector3().subVectors(nx, px).normalize();
  65627. let nxN = pxN.clone().multiplyScalar(-1);
  65628. let pyN = new Vector3().subVectors(ny, py).normalize();
  65629. let nyN = pyN.clone().multiplyScalar(-1);
  65630. let pzN = new Vector3().subVectors(nz, pz).normalize();
  65631. let nzN = pzN.clone().multiplyScalar(-1);
  65632. let planes = [
  65633. new Plane().setFromNormalAndCoplanarPoint(pxN, px),
  65634. new Plane().setFromNormalAndCoplanarPoint(nxN, nx),
  65635. new Plane().setFromNormalAndCoplanarPoint(pyN, py),
  65636. new Plane().setFromNormalAndCoplanarPoint(nyN, ny),
  65637. new Plane().setFromNormalAndCoplanarPoint(pzN, pz),
  65638. new Plane().setFromNormalAndCoplanarPoint(nzN, nz),
  65639. ];
  65640. let planeQueryParts = [];
  65641. for(let plane of planes){
  65642. let part = [plane.normal.toArray(), plane.constant].join(",");
  65643. part = `[${part}]`;
  65644. planeQueryParts.push(part);
  65645. }
  65646. let region = "[" + planeQueryParts.join(",") + "]";
  65647. regions.push(region);
  65648. }
  65649. let regionsArg = regions.join(",");
  65650. let pointcloudArgs = [];
  65651. for(let pointcloud of this.viewer.scene.pointclouds){
  65652. if(!pointcloud.visible){
  65653. continue;
  65654. }
  65655. let offset = pointcloud.pcoGeometry.offset.clone();
  65656. let negateOffset = new Matrix4().makeTranslation(...offset.multiplyScalar(-1).toArray());
  65657. let matrixWorld = pointcloud.matrixWorld;
  65658. let transform = new Matrix4().multiplyMatrices(matrixWorld, negateOffset);
  65659. let path = `${window.location.pathname}/../${pointcloud.pcoGeometry.url}`;
  65660. let arg = {
  65661. path: path,
  65662. transform: transform.elements,
  65663. };
  65664. let argString = JSON.stringify(arg);
  65665. pointcloudArgs.push(argString);
  65666. }
  65667. let pointcloudsArg = pointcloudArgs.join(",");
  65668. let elMessage = this.elContent.find("div[name=download_message]");
  65669. let error = (message) => {
  65670. elMessage.html(`<div style="color: #ff0000">ERROR: ${message}</div>`);
  65671. };
  65672. let info = (message) => {
  65673. elMessage.html(`${message}`);
  65674. };
  65675. let handle = null;
  65676. { // START FILTER
  65677. let url = `${viewer.server}/create_regions_filter?pointclouds=[${pointcloudsArg}]&regions=[${regionsArg}]`;
  65678. //console.log(url);
  65679. info("estimating results ...");
  65680. let response = await fetch(url);
  65681. let jsResponse = await response.json();
  65682. //console.log(jsResponse);
  65683. if(!jsResponse.handle){
  65684. error(jsResponse.message);
  65685. return;
  65686. }else {
  65687. handle = jsResponse.handle;
  65688. }
  65689. }
  65690. { // WAIT, CHECK PROGRESS, HANDLE FINISH
  65691. let url = `${viewer.server}/check_regions_filter?handle=${handle}`;
  65692. let sleep = (function(duration){
  65693. return new Promise( (res, rej) => {
  65694. setTimeout(() => {
  65695. res();
  65696. }, duration);
  65697. });
  65698. });
  65699. let handleFiltering = (jsResponse) => {
  65700. let {progress, estimate} = jsResponse;
  65701. let progressFract = progress["processed points"] / estimate.points;
  65702. let progressPercents = parseInt(progressFract * 100);
  65703. info(`progress: ${progressPercents}%`);
  65704. };
  65705. let handleFinish = (jsResponse) => {
  65706. let message = "downloads ready: <br>";
  65707. message += "<ul>";
  65708. for(let i = 0; i < jsResponse.pointclouds.length; i++){
  65709. let url = `${viewer.server}/download_regions_filter_result?handle=${handle}&index=${i}`;
  65710. message += `<li><a href="${url}">result_${i}.las</a> </li>\n`;
  65711. }
  65712. let reportURL = `${viewer.server}/download_regions_filter_report?handle=${handle}`;
  65713. message += `<li> <a href="${reportURL}">report.json</a> </li>\n`;
  65714. message += "</ul>";
  65715. info(message);
  65716. };
  65717. let handleUnexpected = (jsResponse) => {
  65718. let message = `Unexpected Response. <br>status: ${jsResponse.status} <br>message: ${jsResponse.message}`;
  65719. info(message);
  65720. };
  65721. let handleError = (jsResponse) => {
  65722. let message = `ERROR: ${jsResponse.message}`;
  65723. error(message);
  65724. throw new Error(message);
  65725. };
  65726. let start = Date.now();
  65727. while(true){
  65728. let response = await fetch(url);
  65729. let jsResponse = await response.json();
  65730. if(jsResponse.status === "ERROR"){
  65731. handleError(jsResponse);
  65732. }else if(jsResponse.status === "FILTERING"){
  65733. handleFiltering(jsResponse);
  65734. }else if(jsResponse.status === "FINISHED"){
  65735. handleFinish(jsResponse);
  65736. break;
  65737. }else {
  65738. handleUnexpected(jsResponse);
  65739. }
  65740. let durationS = (Date.now() - start) / 1000;
  65741. let sleepAmountMS = durationS < 10 ? 100 : 1000;
  65742. await sleep(sleepAmountMS);
  65743. }
  65744. }
  65745. }
  65746. update(){
  65747. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65748. elCoordiantesContainer.empty();
  65749. elCoordiantesContainer.append(this.createCoordinatesTable([this.measurement.position]));
  65750. {
  65751. let angles = this.measurement.rotation.toVector3();
  65752. angles = angles.toArray();
  65753. //angles = [angles.z, angles.x, angles.y];
  65754. angles = angles.map(v => 180 * v / Math.PI);
  65755. angles = angles.map(a => a.toFixed(1) + '\u00B0');
  65756. let elAlpha = this.elContent.find(`#angle_cell_alpha`);
  65757. let elBetta = this.elContent.find(`#angle_cell_betta`);
  65758. let elGamma = this.elContent.find(`#angle_cell_gamma`);
  65759. elAlpha.html(angles[0]);
  65760. elBetta.html(angles[1]);
  65761. elGamma.html(angles[2]);
  65762. }
  65763. {
  65764. let dimensions = this.measurement.scale.toArray();
  65765. dimensions = dimensions.map(v => Utils.addCommas(v.toFixed(2)));
  65766. let elLength = this.elContent.find(`#cell_length`);
  65767. let elWidth = this.elContent.find(`#cell_width`);
  65768. let elHeight = this.elContent.find(`#cell_height`);
  65769. elLength.html(dimensions[0]);
  65770. elWidth.html(dimensions[1]);
  65771. elHeight.html(dimensions[2]);
  65772. }
  65773. {
  65774. let elVolume = this.elContent.find(`#measurement_volume`);
  65775. let volume = this.measurement.getVolume();
  65776. elVolume.html(Utils.addCommas(volume.toFixed(2)));
  65777. }
  65778. this.elCheckClip.prop("checked", this.measurement.clip);
  65779. this.elCheckShow.prop("checked", this.measurement.visible);
  65780. }
  65781. };
  65782. class ProfilePanel extends MeasurePanel{
  65783. constructor(viewer, measurement, propertiesPanel){
  65784. super(viewer, measurement, propertiesPanel);
  65785. let removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  65786. this.elContent = $(`
  65787. <div class="measurement_content selectable">
  65788. <span class="coordinates_table_container"></span>
  65789. <br>
  65790. <span style="display:flex">
  65791. <span style="display:flex; align-items: center; padding-right: 10px">Width: </span>
  65792. <input id="sldProfileWidth" name="sldProfileWidth" value="5.06" style="flex-grow: 1; width:100%">
  65793. </span>
  65794. <br>
  65795. <li style="margin-top: 10px">
  65796. <input name="download_profile" type="button" value="prepare download" style="width: 100%" />
  65797. <div name="download_message"></div>
  65798. </li>
  65799. <br>
  65800. <input type="button" id="show_2d_profile" value="show 2d profile" style="width: 100%"/>
  65801. <!-- ACTIONS -->
  65802. <div style="display: flex; margin-top: 12px">
  65803. <span></span>
  65804. <span style="flex-grow: 1"></span>
  65805. <img name="remove" class="button-icon" src="${removeIconPath}" style="width: 16px; height: 16px"/>
  65806. </div>
  65807. </div>
  65808. `);
  65809. this.elRemove = this.elContent.find("img[name=remove]");
  65810. this.elRemove.click( () => {
  65811. this.viewer.scene.removeProfile(measurement);
  65812. });
  65813. { // download
  65814. this.elDownloadButton = this.elContent.find(`input[name=download_profile]`);
  65815. if(this.propertiesPanel.viewer.server){
  65816. this.elDownloadButton.click(() => this.download());
  65817. } else {
  65818. this.elDownloadButton.hide();
  65819. }
  65820. }
  65821. { // width spinner
  65822. let elWidthSlider = this.elContent.find(`#sldProfileWidth`);
  65823. elWidthSlider.spinner({
  65824. min: 0, max: 10 * 1000 * 1000, step: 0.01,
  65825. numberFormat: 'n',
  65826. start: () => {},
  65827. spin: (event, ui) => {
  65828. let value = elWidthSlider.spinner('value');
  65829. measurement.setWidth(value);
  65830. },
  65831. change: (event, ui) => {
  65832. let value = elWidthSlider.spinner('value');
  65833. measurement.setWidth(value);
  65834. },
  65835. stop: (event, ui) => {
  65836. let value = elWidthSlider.spinner('value');
  65837. measurement.setWidth(value);
  65838. },
  65839. incremental: (count) => {
  65840. let value = elWidthSlider.spinner('value');
  65841. let step = elWidthSlider.spinner('option', 'step');
  65842. let delta = value * 0.05;
  65843. let increments = Math.max(1, parseInt(delta / step));
  65844. return increments;
  65845. }
  65846. });
  65847. elWidthSlider.spinner('value', measurement.getWidth());
  65848. elWidthSlider.spinner('widget').css('width', '100%');
  65849. let widthListener = (event) => {
  65850. let value = elWidthSlider.spinner('value');
  65851. if (value !== measurement.getWidth()) {
  65852. elWidthSlider.spinner('value', measurement.getWidth());
  65853. }
  65854. };
  65855. this.propertiesPanel.addVolatileListener(measurement, "width_changed", widthListener);
  65856. }
  65857. let elShow2DProfile = this.elContent.find(`#show_2d_profile`);
  65858. elShow2DProfile.click(() => {
  65859. this.propertiesPanel.viewer.profileWindow.show();
  65860. this.propertiesPanel.viewer.profileWindowController.setProfile(measurement);
  65861. });
  65862. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  65863. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  65864. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  65865. this.update();
  65866. }
  65867. update(){
  65868. let elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  65869. elCoordiantesContainer.empty();
  65870. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points));
  65871. }
  65872. async download(){
  65873. let profile = this.measurement;
  65874. let regions = [];
  65875. {
  65876. let segments = profile.getSegments();
  65877. let width = profile.width;
  65878. for(let segment of segments){
  65879. let start = segment.start.clone().multiply(new Vector3(1, 1, 0));
  65880. let end = segment.end.clone().multiply(new Vector3(1, 1, 0));
  65881. let center = new Vector3().addVectors(start, end).multiplyScalar(0.5);
  65882. let startEndDir = new Vector3().subVectors(end, start).normalize();
  65883. let endStartDir = new Vector3().subVectors(start, end).normalize();
  65884. let upDir = new Vector3(0, 0, 1);
  65885. let rightDir = new Vector3().crossVectors(startEndDir, upDir);
  65886. let leftDir = new Vector3().crossVectors(endStartDir, upDir);
  65887. console.log(leftDir);
  65888. let right = rightDir.clone().multiplyScalar(width * 0.5).add(center);
  65889. let left = leftDir.clone().multiplyScalar(width * 0.5).add(center);
  65890. let planes = [
  65891. new Plane().setFromNormalAndCoplanarPoint(startEndDir, start),
  65892. new Plane().setFromNormalAndCoplanarPoint(endStartDir, end),
  65893. new Plane().setFromNormalAndCoplanarPoint(leftDir, right),
  65894. new Plane().setFromNormalAndCoplanarPoint(rightDir, left),
  65895. ];
  65896. let planeQueryParts = [];
  65897. for(let plane of planes){
  65898. let part = [plane.normal.toArray(), plane.constant].join(",");
  65899. part = `[${part}]`;
  65900. planeQueryParts.push(part);
  65901. }
  65902. let region = "[" + planeQueryParts.join(",") + "]";
  65903. regions.push(region);
  65904. }
  65905. }
  65906. let regionsArg = regions.join(",");
  65907. let pointcloudArgs = [];
  65908. for(let pointcloud of this.viewer.scene.pointclouds){
  65909. if(!pointcloud.visible){
  65910. continue;
  65911. }
  65912. let offset = pointcloud.pcoGeometry.offset.clone();
  65913. let negateOffset = new Matrix4().makeTranslation(...offset.multiplyScalar(-1).toArray());
  65914. let matrixWorld = pointcloud.matrixWorld;
  65915. let transform = new Matrix4().multiplyMatrices(matrixWorld, negateOffset);
  65916. let path = `${window.location.pathname}/../${pointcloud.pcoGeometry.url}`;
  65917. let arg = {
  65918. path: path,
  65919. transform: transform.elements,
  65920. };
  65921. let argString = JSON.stringify(arg);
  65922. pointcloudArgs.push(argString);
  65923. }
  65924. let pointcloudsArg = pointcloudArgs.join(",");
  65925. let elMessage = this.elContent.find("div[name=download_message]");
  65926. let error = (message) => {
  65927. elMessage.html(`<div style="color: #ff0000">ERROR: ${message}</div>`);
  65928. };
  65929. let info = (message) => {
  65930. elMessage.html(`${message}`);
  65931. };
  65932. let handle = null;
  65933. { // START FILTER
  65934. let url = `${viewer.server}/create_regions_filter?pointclouds=[${pointcloudsArg}]&regions=[${regionsArg}]`;
  65935. //console.log(url);
  65936. info("estimating results ...");
  65937. let response = await fetch(url);
  65938. let jsResponse = await response.json();
  65939. //console.log(jsResponse);
  65940. if(!jsResponse.handle){
  65941. error(jsResponse.message);
  65942. return;
  65943. }else {
  65944. handle = jsResponse.handle;
  65945. }
  65946. }
  65947. { // WAIT, CHECK PROGRESS, HANDLE FINISH
  65948. let url = `${viewer.server}/check_regions_filter?handle=${handle}`;
  65949. let sleep = (function(duration){
  65950. return new Promise( (res, rej) => {
  65951. setTimeout(() => {
  65952. res();
  65953. }, duration);
  65954. });
  65955. });
  65956. let handleFiltering = (jsResponse) => {
  65957. let {progress, estimate} = jsResponse;
  65958. let progressFract = progress["processed points"] / estimate.points;
  65959. let progressPercents = parseInt(progressFract * 100);
  65960. info(`progress: ${progressPercents}%`);
  65961. };
  65962. let handleFinish = (jsResponse) => {
  65963. let message = "downloads ready: <br>";
  65964. message += "<ul>";
  65965. for(let i = 0; i < jsResponse.pointclouds.length; i++){
  65966. let url = `${viewer.server}/download_regions_filter_result?handle=${handle}&index=${i}`;
  65967. message += `<li><a href="${url}">result_${i}.las</a> </li>\n`;
  65968. }
  65969. let reportURL = `${viewer.server}/download_regions_filter_report?handle=${handle}`;
  65970. message += `<li> <a href="${reportURL}">report.json</a> </li>\n`;
  65971. message += "</ul>";
  65972. info(message);
  65973. };
  65974. let handleUnexpected = (jsResponse) => {
  65975. let message = `Unexpected Response. <br>status: ${jsResponse.status} <br>message: ${jsResponse.message}`;
  65976. info(message);
  65977. };
  65978. let handleError = (jsResponse) => {
  65979. let message = `ERROR: ${jsResponse.message}`;
  65980. error(message);
  65981. throw new Error(message);
  65982. };
  65983. let start = Date.now();
  65984. while(true){
  65985. let response = await fetch(url);
  65986. let jsResponse = await response.json();
  65987. if(jsResponse.status === "ERROR"){
  65988. handleError(jsResponse);
  65989. }else if(jsResponse.status === "FILTERING"){
  65990. handleFiltering(jsResponse);
  65991. }else if(jsResponse.status === "FINISHED"){
  65992. handleFinish(jsResponse);
  65993. break;
  65994. }else {
  65995. handleUnexpected(jsResponse);
  65996. }
  65997. let durationS = (Date.now() - start) / 1000;
  65998. let sleepAmountMS = durationS < 10 ? 100 : 1000;
  65999. await sleep(sleepAmountMS);
  66000. }
  66001. }
  66002. }
  66003. };
  66004. class CameraPanel{
  66005. constructor(viewer, propertiesPanel){
  66006. this.viewer = viewer;
  66007. this.propertiesPanel = propertiesPanel;
  66008. this._update = () => { this.update(); };
  66009. let copyIconPath = Potree.resourcePath + '/icons/copy.svg';
  66010. this.elContent = $(`
  66011. <div class="propertypanel_content">
  66012. <table>
  66013. <tr>
  66014. <th colspan="3">position</th>
  66015. <th></th>
  66016. </tr>
  66017. <tr>
  66018. <td align="center" id="camera_position_x" style="width: 25%"></td>
  66019. <td align="center" id="camera_position_y" style="width: 25%"></td>
  66020. <td align="center" id="camera_position_z" style="width: 25%"></td>
  66021. <td align="right" id="copy_camera_position" style="width: 25%">
  66022. <img name="copyPosition" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  66023. </td>
  66024. </tr>
  66025. <tr>
  66026. <th colspan="3">target</th>
  66027. <th></th>
  66028. </tr>
  66029. <tr>
  66030. <td align="center" id="camera_target_x" style="width: 25%"></td>
  66031. <td align="center" id="camera_target_y" style="width: 25%"></td>
  66032. <td align="center" id="camera_target_z" style="width: 25%"></td>
  66033. <td align="right" id="copy_camera_target" style="width: 25%">
  66034. <img name="copyTarget" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  66035. </td>
  66036. </tr>
  66037. </table>
  66038. </div>
  66039. `);
  66040. this.elCopyPosition = this.elContent.find("img[name=copyPosition]");
  66041. this.elCopyPosition.click( () => {
  66042. let pos = this.viewer.scene.getActiveCamera().position.toArray();
  66043. let msg = pos.map(c => c.toFixed(3)).join(", ");
  66044. Utils.clipboardCopy(msg);
  66045. this.viewer.postMessage(
  66046. `Copied value to clipboard: <br>'${msg}'`,
  66047. {duration: 3000});
  66048. });
  66049. this.elCopyTarget = this.elContent.find("img[name=copyTarget]");
  66050. this.elCopyTarget.click( () => {
  66051. let pos = this.viewer.scene.view.getPivot().toArray();
  66052. let msg = pos.map(c => c.toFixed(3)).join(", ");
  66053. Utils.clipboardCopy(msg);
  66054. this.viewer.postMessage(
  66055. `Copied value to clipboard: <br>'${msg}'`,
  66056. {duration: 3000});
  66057. });
  66058. this.propertiesPanel.addVolatileListener(viewer, "camera_changed", this._update);
  66059. this.update();
  66060. }
  66061. update(){
  66062. //console.log("updating camera panel");
  66063. let camera = this.viewer.scene.getActiveCamera();
  66064. let view = this.viewer.scene.view;
  66065. let pos = camera.position.toArray().map(c => Utils.addCommas(c.toFixed(3)));
  66066. this.elContent.find("#camera_position_x").html(pos[0]);
  66067. this.elContent.find("#camera_position_y").html(pos[1]);
  66068. this.elContent.find("#camera_position_z").html(pos[2]);
  66069. let target = view.getPivot().toArray().map(c => Utils.addCommas(c.toFixed(3)));
  66070. this.elContent.find("#camera_target_x").html(target[0]);
  66071. this.elContent.find("#camera_target_y").html(target[1]);
  66072. this.elContent.find("#camera_target_z").html(target[2]);
  66073. }
  66074. };
  66075. class AnnotationPanel{
  66076. constructor(viewer, propertiesPanel, annotation){
  66077. this.viewer = viewer;
  66078. this.propertiesPanel = propertiesPanel;
  66079. this.annotation = annotation;
  66080. this._update = () => { this.update(); };
  66081. let copyIconPath = `${Potree.resourcePath}/icons/copy.svg`;
  66082. this.elContent = $(`
  66083. <div class="propertypanel_content">
  66084. <table>
  66085. <tr>
  66086. <th colspan="3">position</th>
  66087. <th></th>
  66088. </tr>
  66089. <tr>
  66090. <td align="center" id="annotation_position_x" style="width: 25%"></td>
  66091. <td align="center" id="annotation_position_y" style="width: 25%"></td>
  66092. <td align="center" id="annotation_position_z" style="width: 25%"></td>
  66093. <td align="right" id="copy_annotation_position" style="width: 25%">
  66094. <img name="copyPosition" title="copy" class="button-icon" src="${copyIconPath}" style="width: 16px; height: 16px"/>
  66095. </td>
  66096. </tr>
  66097. </table>
  66098. <div>
  66099. <div class="heading">Title</div>
  66100. <div id="annotation_title" contenteditable="true">
  66101. Annotation Title
  66102. </div>
  66103. <div class="heading">Description</div>
  66104. <div id="annotation_description" contenteditable="true">
  66105. A longer description of this annotation.
  66106. Can be multiple lines long. TODO: the user should be able
  66107. to modify title and description.
  66108. </div>
  66109. </div>
  66110. </div>
  66111. `);
  66112. this.elCopyPosition = this.elContent.find("img[name=copyPosition]");
  66113. this.elCopyPosition.click( () => {
  66114. let pos = this.annotation.position.toArray();
  66115. let msg = pos.map(c => c.toFixed(3)).join(", ");
  66116. Utils.clipboardCopy(msg);
  66117. this.viewer.postMessage(
  66118. `Copied value to clipboard: <br>'${msg}'`,
  66119. {duration: 3000});
  66120. });
  66121. this.elTitle = this.elContent.find("#annotation_title").html(annotation.title);
  66122. this.elDescription = this.elContent.find("#annotation_description").html(annotation.description);
  66123. this.elTitle[0].addEventListener("input", () => {
  66124. const title = this.elTitle.html();
  66125. annotation.title = title;
  66126. }, false);
  66127. this.elDescription[0].addEventListener("input", () => {
  66128. const description = this.elDescription.html();
  66129. annotation.description = description;
  66130. }, false);
  66131. this.update();
  66132. }
  66133. update(){
  66134. const {annotation, elContent, elTitle, elDescription} = this;
  66135. let pos = annotation.position.toArray().map(c => Utils.addCommas(c.toFixed(3)));
  66136. elContent.find("#annotation_position_x").html(pos[0]);
  66137. elContent.find("#annotation_position_y").html(pos[1]);
  66138. elContent.find("#annotation_position_z").html(pos[2]);
  66139. elTitle.html(annotation.title);
  66140. elDescription.html(annotation.description);
  66141. }
  66142. };
  66143. class CameraAnimationPanel{
  66144. constructor(viewer, propertiesPanel, animation){
  66145. this.viewer = viewer;
  66146. this.propertiesPanel = propertiesPanel;
  66147. this.animation = animation;
  66148. this.elContent = $(`
  66149. <div class="propertypanel_content">
  66150. <span id="animation_keyframes"></span>
  66151. <span>
  66152. <span style="display:flex">
  66153. <span style="display:flex; align-items: center; padding-right: 10px">Duration: </span>
  66154. <input name="spnDuration" value="5.0" style="flex-grow: 1; width:100%">
  66155. </span>
  66156. <span>Time: </span><span id="lblTime"></span> <div id="sldTime"></div>
  66157. <input name="play" type="button" value="play"/>
  66158. </span>
  66159. </div>
  66160. `);
  66161. const elPlay = this.elContent.find("input[name=play]");
  66162. elPlay.click( () => {
  66163. animation.play();
  66164. });
  66165. const elSlider = this.elContent.find('#sldTime');
  66166. elSlider.slider({
  66167. value: 0,
  66168. min: 0,
  66169. max: 1,
  66170. step: 0.001,
  66171. slide: (event, ui) => {
  66172. animation.set(ui.value);
  66173. animation.updateFrustum();
  66174. }
  66175. });
  66176. let elDuration = this.elContent.find(`input[name=spnDuration]`);
  66177. elDuration.spinner({
  66178. min: 0, max: 300, step: 0.01,
  66179. numberFormat: 'n',
  66180. start: () => {},
  66181. spin: (event, ui) => {
  66182. let value = elDuration.spinner('value');
  66183. animation.setDuration(value);
  66184. },
  66185. change: (event, ui) => {
  66186. let value = elDuration.spinner('value');
  66187. animation.setDuration(value);
  66188. },
  66189. stop: (event, ui) => {
  66190. let value = elDuration.spinner('value');
  66191. animation.setDuration(value);
  66192. },
  66193. incremental: (count) => {
  66194. let value = elDuration.spinner('value');
  66195. let step = elDuration.spinner('option', 'step');
  66196. let delta = value * 0.05;
  66197. let increments = Math.max(1, parseInt(delta / step));
  66198. return increments;
  66199. }
  66200. });
  66201. elDuration.spinner('value', animation.getDuration());
  66202. elDuration.spinner('widget').css('width', '100%');
  66203. const elKeyframes = this.elContent.find("#animation_keyframes");
  66204. const updateKeyframes = () => {
  66205. elKeyframes.empty();
  66206. //let index = 0;
  66207. // <span style="flex-grow: 0;">
  66208. // <img name="add" src="${Potree.resourcePath}/icons/add.svg" style="width: 1.5em; height: 1.5em"/>
  66209. // </span>
  66210. const addNewKeyframeItem = (index) => {
  66211. let elNewKeyframe = $(`
  66212. <div style="display: flex; margin: 0.2em 0em">
  66213. <span style="flex-grow: 1"></span>
  66214. <input type="button" name="add" value="insert control point" />
  66215. <span style="flex-grow: 1"></span>
  66216. </div>
  66217. `);
  66218. const elAdd = elNewKeyframe.find("input[name=add]");
  66219. elAdd.click( () => {
  66220. animation.createControlPoint(index);
  66221. animation.changeCallback();
  66222. });
  66223. elKeyframes.append(elNewKeyframe);
  66224. };
  66225. const addKeyframeItem = (index) => {
  66226. let elKeyframe = $(`
  66227. <div style="display: flex; margin: 0.2em 0em">
  66228. <span style="flex-grow: 0;">
  66229. <img name="assign" src="${Potree.resourcePath}/icons/assign.svg" style="width: 1.5em; height: 1.5em"/>
  66230. </span>
  66231. <span style="flex-grow: 0;">
  66232. <img name="move" src="${Potree.resourcePath}/icons/circled_dot.svg" style="width: 1.5em; height: 1.5em"/>
  66233. </span>
  66234. <span style="flex-grow: 0; width: 1.5em; height: 1.5em"></span>
  66235. <span style="flex-grow: 0; font-size: 1.5em">keyframe</span>
  66236. <span style="flex-grow: 1"></span>
  66237. <span style="flex-grow: 0;">
  66238. <img name="delete" src="${Potree.resourcePath}/icons/remove.svg" style="width: 1.5em; height: 1.5em"/>
  66239. </span>
  66240. </div>
  66241. `);
  66242. const elAssign = elKeyframe.find("img[name=assign]");
  66243. const elMove = elKeyframe.find("img[name=move]");
  66244. const elDelete = elKeyframe.find("img[name=delete]");
  66245. elAssign.click( () => {
  66246. animation.posCurve.points[index].copy(viewer.scene.view.position);
  66247. animation.targetCurve.points[index].copy(viewer.scene.view.getPivot());
  66248. animation.changeCallback();
  66249. });
  66250. elMove.click( () => {
  66251. viewer.scene.view.position.copy(animation.posCurve.points[index]);
  66252. viewer.scene.view.lookAt(animation.targetCurve.points[index]);
  66253. });
  66254. elDelete.click( () => {
  66255. animation.removeControlPoint(index);
  66256. animation.changeCallback();
  66257. });
  66258. elKeyframes.append(elKeyframe);
  66259. };
  66260. let index = 0;
  66261. addNewKeyframeItem(index);
  66262. animation.posCurve.points.forEach(e=>{
  66263. addKeyframeItem(index);
  66264. index++;
  66265. addNewKeyframeItem(index);
  66266. });
  66267. };
  66268. updateKeyframes();
  66269. animation.addEventListener("controlpoint_added", updateKeyframes);
  66270. animation.addEventListener("controlpoint_removed", updateKeyframes);
  66271. // this._update = () => { this.update(); };
  66272. // this.update();
  66273. }
  66274. update(){
  66275. }
  66276. };
  66277. class PropertiesPanel{
  66278. constructor(container, viewer){
  66279. this.container = container;
  66280. this.viewer = viewer;
  66281. this.object = null;
  66282. this.cleanupTasks = [];
  66283. this.scene = null;
  66284. }
  66285. setScene(scene){
  66286. this.scene = scene;
  66287. }
  66288. set(object){
  66289. if(this.object === object){
  66290. return;
  66291. }
  66292. this.object = object;
  66293. for(let task of this.cleanupTasks){
  66294. task();
  66295. }
  66296. this.cleanupTasks = [];
  66297. this.container.empty();
  66298. if(object instanceof PointCloudTree){
  66299. this.setPointCloud(object);
  66300. }else if(object instanceof Measure || object instanceof Profile || object instanceof Volume){
  66301. this.setMeasurement(object);
  66302. }else if(object instanceof Camera){
  66303. this.setCamera(object);
  66304. }else if(object instanceof Annotation){
  66305. this.setAnnotation(object);
  66306. }else if(object instanceof CameraAnimation){
  66307. this.setCameraAnimation(object);
  66308. }
  66309. }
  66310. //
  66311. // Used for events that should be removed when the property object changes.
  66312. // This is for listening to materials, scene, point clouds, etc.
  66313. // not required for DOM listeners, since they are automatically cleared by removing the DOM subtree.
  66314. //
  66315. addVolatileListener(target, type, callback){
  66316. target.addEventListener(type, callback);
  66317. this.cleanupTasks.push(() => {
  66318. target.removeEventListener(type, callback);
  66319. });
  66320. }
  66321. setPointCloud(pointcloud){
  66322. let material = pointcloud.material;
  66323. let panel = $(`
  66324. <div class="scene_content selectable">
  66325. <ul class="pv-menu-list">
  66326. <li>
  66327. <span data-i18n="appearance.point_size"></span>:&nbsp;<span id="lblPointSize"></span> <div id="sldPointSize"></div>
  66328. </li>
  66329. <li>
  66330. <span data-i18n="appearance.min_point_size"></span>:&nbsp;<span id="lblMinPointSize"></span> <div id="sldMinPointSize"></div>
  66331. </li>
  66332. <!-- SIZE TYPE -->
  66333. <li>
  66334. <label for="optPointSizing" class="pv-select-label" data-i18n="appearance.point_size_type">Point Sizing </label>
  66335. <select id="optPointSizing" name="optPointSizing">
  66336. <option>FIXED</option>
  66337. <option>ATTENUATED</option>
  66338. <option>ADAPTIVE</option>
  66339. </select>
  66340. </li>
  66341. <!-- SHAPE -->
  66342. <li>
  66343. <label for="optShape" class="pv-select-label" data-i18n="appearance.point_shape"></label><br>
  66344. <select id="optShape" name="optShape">
  66345. <option>SQUARE</option>
  66346. <option>CIRCLE</option>
  66347. <option>PARABOLOID</option>
  66348. </select>
  66349. </li>
  66350. <li id="materials_backface_container">
  66351. <label><input id="set_backface_culling" type="checkbox" /><span data-i18n="appearance.backface_culling"></span></label>
  66352. </li>
  66353. <!-- OPACITY -->
  66354. <li><span data-i18n="appearance.point_opacity"></span>:<span id="lblOpacity"></span><div id="sldOpacity"></div></li>
  66355. <div class="divider">
  66356. <span>Attribute</span>
  66357. </div>
  66358. <li>
  66359. <select id="optMaterial" name="optMaterial"></select>
  66360. </li>
  66361. <div id="materials.composite_weight_container">
  66362. <div class="divider">
  66363. <span>Attribute Weights</span>
  66364. </div>
  66365. <li>RGB: <span id="lblWeightRGB"></span> <div id="sldWeightRGB"></div> </li>
  66366. <li>Intensity: <span id="lblWeightIntensity"></span> <div id="sldWeightIntensity"></div> </li>
  66367. <li>Elevation: <span id="lblWeightElevation"></span> <div id="sldWeightElevation"></div> </li>
  66368. <li>Classification: <span id="lblWeightClassification"></span> <div id="sldWeightClassification"></div> </li>
  66369. <li>Return Number: <span id="lblWeightReturnNumber"></span> <div id="sldWeightReturnNumber"></div> </li>
  66370. <li>Source ID: <span id="lblWeightSourceID"></span> <div id="sldWeightSourceID"></div> </li>
  66371. </div>
  66372. <div id="materials.rgb_container">
  66373. <div class="divider">
  66374. <span>RGB</span>
  66375. </div>
  66376. <li>Gamma: <span id="lblRGBGamma"></span> <div id="sldRGBGamma"></div> </li>
  66377. <li>Brightness: <span id="lblRGBBrightness"></span> <div id="sldRGBBrightness"></div> </li>
  66378. <li>Contrast: <span id="lblRGBContrast"></span> <div id="sldRGBContrast"></div> </li>
  66379. </div>
  66380. <div id="materials.extra_container">
  66381. <div class="divider">
  66382. <span>Extra Attribute</span>
  66383. </div>
  66384. <li><span data-i18n="appearance.extra_range"></span>: <span id="lblExtraRange"></span> <div id="sldExtraRange"></div></li>
  66385. <li>Gamma: <span id="lblExtraGamma"></span> <div id="sldExtraGamma"></div></li>
  66386. <li>Brightness: <span id="lblExtraBrightness"></span> <div id="sldExtraBrightness"></div></li>
  66387. <li>Contrast: <span id="lblExtraContrast"></span> <div id="sldExtraContrast"></div></li>
  66388. </div>
  66389. <div id="materials.matcap_container">
  66390. <div class="divider">
  66391. <span>MATCAP</span>
  66392. </div>
  66393. <li>
  66394. <div id="matcap_scheme_selection" style="display: flex; flex-wrap: wrap;"> </div>
  66395. </li>
  66396. </div>
  66397. <div id="materials.color_container">
  66398. <div class="divider">
  66399. <span>Color</span>
  66400. </div>
  66401. <input id="materials.color.picker" />
  66402. </div>
  66403. <div id="materials.elevation_container">
  66404. <div class="divider">
  66405. <span>Elevation</span>
  66406. </div>
  66407. <li><span data-i18n="appearance.elevation_range"></span>: <span id="lblHeightRange"></span> <div id="sldHeightRange"></div> </li>
  66408. <li>
  66409. <selectgroup id="gradient_repeat_option">
  66410. <option id="gradient_repeat_clamp" value="CLAMP">Clamp</option>
  66411. <option id="gradient_repeat_repeat" value="REPEAT">Repeat</option>
  66412. <option id="gradient_repeat_mirrored_repeat" value="MIRRORED_REPEAT">Mirrored Repeat</option>
  66413. </selectgroup>
  66414. </li>
  66415. <li>
  66416. <span>Gradient Scheme:</span>
  66417. <div id="elevation_gradient_scheme_selection" style="display: flex; padding: 1em 0em">
  66418. </div>
  66419. </li>
  66420. </div>
  66421. <div id="materials.transition_container">
  66422. <div class="divider">
  66423. <span>Transition</span>
  66424. </div>
  66425. <li>transition: <span id="lblTransition"></span> <div id="sldTransition"></div> </li>
  66426. </div>
  66427. <div id="materials.intensity_container">
  66428. <div class="divider">
  66429. <span>Intensity</span>
  66430. </div>
  66431. <li>Range: <span id="lblIntensityRange"></span> <div id="sldIntensityRange"></div> </li>
  66432. <li>Gamma: <span id="lblIntensityGamma"></span> <div id="sldIntensityGamma"></div> </li>
  66433. <li>Brightness: <span id="lblIntensityBrightness"></span> <div id="sldIntensityBrightness"></div> </li>
  66434. <li>Contrast: <span id="lblIntensityContrast"></span> <div id="sldIntensityContrast"></div> </li>
  66435. </div>
  66436. <div id="materials.gpstime_container">
  66437. <div class="divider">
  66438. <span>GPS Time</span>
  66439. </div>
  66440. </div>
  66441. <div id="materials.index_container">
  66442. <div class="divider">
  66443. <span>Indices</span>
  66444. </div>
  66445. </div>
  66446. </ul>
  66447. </div>
  66448. `);
  66449. panel.i18n();
  66450. this.container.append(panel);
  66451. { // POINT SIZE
  66452. let sldPointSize = panel.find(`#sldPointSize`);
  66453. let lblPointSize = panel.find(`#lblPointSize`);
  66454. sldPointSize.slider({
  66455. value: material.size,
  66456. min: 0,
  66457. max: 3,
  66458. step: 0.01,
  66459. slide: function (event, ui) { material.size = ui.value; }
  66460. });
  66461. let update = (e) => {
  66462. lblPointSize.html(material.size.toFixed(2));
  66463. sldPointSize.slider({value: material.size});
  66464. };
  66465. this.addVolatileListener(material, "point_size_changed", update);
  66466. update();
  66467. }
  66468. { // MINIMUM POINT SIZE
  66469. let sldMinPointSize = panel.find(`#sldMinPointSize`);
  66470. let lblMinPointSize = panel.find(`#lblMinPointSize`);
  66471. sldMinPointSize.slider({
  66472. value: material.size,
  66473. min: 0,
  66474. max: 3,
  66475. step: 0.01,
  66476. slide: function (event, ui) { material.minSize = ui.value; }
  66477. });
  66478. let update = (e) => {
  66479. lblMinPointSize.html(material.minSize.toFixed(2));
  66480. sldMinPointSize.slider({value: material.minSize});
  66481. };
  66482. this.addVolatileListener(material, "point_size_changed", update);
  66483. update();
  66484. }
  66485. { // POINT SIZING
  66486. let strSizeType = Object.keys(PointSizeType)[material.pointSizeType];
  66487. let opt = panel.find(`#optPointSizing`);
  66488. opt.selectmenu();
  66489. opt.val(strSizeType).selectmenu('refresh');
  66490. opt.selectmenu({
  66491. change: (event, ui) => {
  66492. material.pointSizeType = PointSizeType[ui.item.value];
  66493. }
  66494. });
  66495. }
  66496. { // SHAPE
  66497. let opt = panel.find(`#optShape`);
  66498. opt.selectmenu({
  66499. change: (event, ui) => {
  66500. let value = ui.item.value;
  66501. material.shape = PointShape[value];
  66502. }
  66503. });
  66504. let update = () => {
  66505. let typename = Object.keys(PointShape)[material.shape];
  66506. opt.selectmenu().val(typename).selectmenu('refresh');
  66507. };
  66508. this.addVolatileListener(material, "point_shape_changed", update);
  66509. update();
  66510. }
  66511. { // BACKFACE CULLING
  66512. let opt = panel.find(`#set_backface_culling`);
  66513. opt.click(() => {
  66514. material.backfaceCulling = opt.prop("checked");
  66515. });
  66516. let update = () => {
  66517. let value = material.backfaceCulling;
  66518. opt.prop("checked", value);
  66519. };
  66520. this.addVolatileListener(material, "backface_changed", update);
  66521. update();
  66522. let blockBackface = $('#materials_backface_container');
  66523. blockBackface.css('display', 'none');
  66524. const pointAttributes = pointcloud.pcoGeometry.pointAttributes;
  66525. const hasNormals = pointAttributes.hasNormals ? pointAttributes.hasNormals() : false;
  66526. if(hasNormals) {
  66527. blockBackface.css('display', 'block');
  66528. }
  66529. /*
  66530. opt.checkboxradio({
  66531. clicked: (event, ui) => {
  66532. // let value = ui.item.value;
  66533. let value = ui.item.checked;
  66534. console.log(value);
  66535. material.backfaceCulling = value; // $('#set_freeze').prop("checked");
  66536. }
  66537. });
  66538. */
  66539. }
  66540. { // OPACITY
  66541. let sldOpacity = panel.find(`#sldOpacity`);
  66542. let lblOpacity = panel.find(`#lblOpacity`);
  66543. sldOpacity.slider({
  66544. value: material.opacity,
  66545. min: 0,
  66546. max: 1,
  66547. step: 0.001,
  66548. slide: function (event, ui) {
  66549. material.opacity = ui.value;
  66550. }
  66551. });
  66552. let update = (e) => {
  66553. lblOpacity.html(material.opacity.toFixed(2));
  66554. sldOpacity.slider({value: material.opacity});
  66555. };
  66556. this.addVolatileListener(material, "opacity_changed", update);
  66557. update();
  66558. }
  66559. {
  66560. const attributes = pointcloud.pcoGeometry.pointAttributes.attributes;
  66561. let options = [];
  66562. options.push(...attributes.map(a => a.name));
  66563. const intensityIndex = options.indexOf("intensity");
  66564. if(intensityIndex >= 0){
  66565. options.splice(intensityIndex + 1, 0, "intensity gradient");
  66566. }
  66567. options.push(
  66568. "elevation",
  66569. "color",
  66570. 'matcap',
  66571. 'indices',
  66572. 'level of detail',
  66573. 'composite'
  66574. );
  66575. const blacklist = [
  66576. "POSITION_CARTESIAN",
  66577. "position",
  66578. ];
  66579. options = options.filter(o => !blacklist.includes(o));
  66580. let attributeSelection = panel.find('#optMaterial');
  66581. for(let option of options){
  66582. let elOption = $(`<option>${option}</option>`);
  66583. attributeSelection.append(elOption);
  66584. }
  66585. let updateMaterialPanel = (event, ui) => {
  66586. let selectedValue = attributeSelection.selectmenu().val();
  66587. material.activeAttributeName = selectedValue;
  66588. let attribute = pointcloud.getAttribute(selectedValue);
  66589. if(selectedValue === "intensity gradient"){
  66590. attribute = pointcloud.getAttribute("intensity");
  66591. }
  66592. const isIntensity = attribute ? ["intensity", "intensity gradient"].includes(attribute.name) : false;
  66593. if(isIntensity){
  66594. if(pointcloud.material.intensityRange[0] === Infinity){
  66595. pointcloud.material.intensityRange = attribute.range;
  66596. }
  66597. const [min, max] = attribute.range;
  66598. panel.find('#sldIntensityRange').slider({
  66599. range: true,
  66600. min: min, max: max, step: 0.01,
  66601. values: [min, max],
  66602. slide: (event, ui) => {
  66603. let min = ui.values[0];
  66604. let max = ui.values[1];
  66605. material.intensityRange = [min, max];
  66606. }
  66607. });
  66608. } else if(attribute){
  66609. let [min, max] = attribute.range;
  66610. let selectedRange = material.getRange(attribute.name);
  66611. if(!selectedRange){
  66612. selectedRange = [...attribute.range];
  66613. }
  66614. let minMaxAreNumbers = typeof min === "number" && typeof max === "number";
  66615. /* min = 0 ;max = 50
  66616. selectedRange[0] =min; selectedRange[1] = max; */
  66617. if(minMaxAreNumbers){
  66618. panel.find('#sldExtraRange').slider({
  66619. range: true,
  66620. min: min,
  66621. max: max,
  66622. step: 0.01,
  66623. values: selectedRange,
  66624. slide: (event, ui) => {
  66625. let [a, b] = ui.values;
  66626. material.setRange(attribute.name, [a, b]);
  66627. }
  66628. });
  66629. }
  66630. }
  66631. let blockWeights = $('#materials\\.composite_weight_container');
  66632. let blockElevation = $('#materials\\.elevation_container');
  66633. let blockRGB = $('#materials\\.rgb_container');
  66634. let blockExtra = $('#materials\\.extra_container');
  66635. let blockColor = $('#materials\\.color_container');
  66636. let blockIntensity = $('#materials\\.intensity_container');
  66637. let blockIndex = $('#materials\\.index_container');
  66638. let blockTransition = $('#materials\\.transition_container');
  66639. let blockGps = $('#materials\\.gpstime_container');
  66640. let blockMatcap = $('#materials\\.matcap_container');
  66641. blockIndex.css('display', 'none');
  66642. blockIntensity.css('display', 'none');
  66643. blockElevation.css('display', 'none');
  66644. blockRGB.css('display', 'none');
  66645. blockExtra.css('display', 'none');
  66646. blockColor.css('display', 'none');
  66647. blockWeights.css('display', 'none');
  66648. blockTransition.css('display', 'none');
  66649. blockMatcap.css('display', 'none');
  66650. blockGps.css('display', 'none');
  66651. if (selectedValue === 'composite') {
  66652. blockWeights.css('display', 'block');
  66653. blockElevation.css('display', 'block');
  66654. blockRGB.css('display', 'block');
  66655. blockIntensity.css('display', 'block');
  66656. } else if (selectedValue === 'elevation') {
  66657. blockElevation.css('display', 'block');
  66658. } else if (selectedValue === 'RGB and Elevation') {
  66659. blockRGB.css('display', 'block');
  66660. blockElevation.css('display', 'block');
  66661. } else if (selectedValue === 'rgba') {
  66662. blockRGB.css('display', 'block');
  66663. } else if (selectedValue === 'color') {
  66664. blockColor.css('display', 'block');
  66665. } else if (selectedValue === 'intensity') {
  66666. blockIntensity.css('display', 'block');
  66667. } else if (selectedValue === 'intensity gradient') {
  66668. blockIntensity.css('display', 'block');
  66669. } else if (selectedValue === "indices" ){
  66670. blockIndex.css('display', 'block');
  66671. } else if (selectedValue === "matcap" ){
  66672. blockMatcap.css('display', 'block');
  66673. } else if (selectedValue === "classification" ){
  66674. // add classification color selctor?
  66675. } else if (selectedValue === "gps-time" ){
  66676. blockGps.css('display', 'block');
  66677. } else if(selectedValue === "number of returns"){
  66678. } else if(selectedValue === "return number"){
  66679. } else if(["source id", "point source id"].includes(selectedValue)){
  66680. } else {
  66681. blockExtra.css('display', 'block');
  66682. }
  66683. };
  66684. attributeSelection.selectmenu({change: updateMaterialPanel});
  66685. let update = () => {
  66686. attributeSelection.val(material.activeAttributeName).selectmenu('refresh');
  66687. };
  66688. this.addVolatileListener(material, "point_color_type_changed", update);
  66689. this.addVolatileListener(material, "active_attribute_changed", update);
  66690. update();
  66691. updateMaterialPanel();
  66692. }
  66693. {
  66694. const schemes = Object.keys(Potree.Gradients).map(name => ({name: name, values: Gradients[name]}));
  66695. let elSchemeContainer = panel.find("#elevation_gradient_scheme_selection");
  66696. for(let scheme of schemes){
  66697. let elScheme = $(`
  66698. <span style="flex-grow: 1;">
  66699. </span>
  66700. `);
  66701. const svg = Potree.Utils.createSvgGradient(scheme.values);
  66702. svg.setAttributeNS(null, "class", `button-icon`);
  66703. elScheme.append($(svg));
  66704. elScheme.click( () => {
  66705. material.gradient = Gradients[scheme.name];
  66706. });
  66707. elSchemeContainer.append(elScheme);
  66708. }
  66709. }
  66710. {
  66711. let matcaps = [
  66712. {name: "Normals", icon: `${Potree.resourcePath}/icons/matcap/check_normal+y.jpg`},
  66713. {name: "Basic 1", icon: `${Potree.resourcePath}/icons/matcap/basic_1.jpg`},
  66714. {name: "Basic 2", icon: `${Potree.resourcePath}/icons/matcap/basic_2.jpg`},
  66715. {name: "Basic Dark", icon: `${Potree.resourcePath}/icons/matcap/basic_dark.jpg`},
  66716. {name: "Basic Side", icon: `${Potree.resourcePath}/icons/matcap/basic_side.jpg`},
  66717. {name: "Ceramic Dark", icon: `${Potree.resourcePath}/icons/matcap/ceramic_dark.jpg`},
  66718. {name: "Ceramic Lightbulb", icon: `${Potree.resourcePath}/icons/matcap/ceramic_lightbulb.jpg`},
  66719. {name: "Clay Brown", icon: `${Potree.resourcePath}/icons/matcap/clay_brown.jpg`},
  66720. {name: "Clay Muddy", icon: `${Potree.resourcePath}/icons/matcap/clay_muddy.jpg`},
  66721. {name: "Clay Studio", icon: `${Potree.resourcePath}/icons/matcap/clay_studio.jpg`},
  66722. {name: "Resin", icon: `${Potree.resourcePath}/icons/matcap/resin.jpg`},
  66723. {name: "Skin", icon: `${Potree.resourcePath}/icons/matcap/skin.jpg`},
  66724. {name: "Jade", icon: `${Potree.resourcePath}/icons/matcap/jade.jpg`},
  66725. {name: "Metal_ Anisotropic", icon: `${Potree.resourcePath}/icons/matcap/metal_anisotropic.jpg`},
  66726. {name: "Metal Carpaint", icon: `${Potree.resourcePath}/icons/matcap/metal_carpaint.jpg`},
  66727. {name: "Metal Lead", icon: `${Potree.resourcePath}/icons/matcap/metal_lead.jpg`},
  66728. {name: "Metal Shiny", icon: `${Potree.resourcePath}/icons/matcap/metal_shiny.jpg`},
  66729. {name: "Pearl", icon: `${Potree.resourcePath}/icons/matcap/pearl.jpg`},
  66730. {name: "Toon", icon: `${Potree.resourcePath}/icons/matcap/toon.jpg`},
  66731. {name: "Check Rim Light", icon: `${Potree.resourcePath}/icons/matcap/check_rim_light.jpg`},
  66732. {name: "Check Rim Dark", icon: `${Potree.resourcePath}/icons/matcap/check_rim_dark.jpg`},
  66733. {name: "Contours 1", icon: `${Potree.resourcePath}/icons/matcap/contours_1.jpg`},
  66734. {name: "Contours 2", icon: `${Potree.resourcePath}/icons/matcap/contours_2.jpg`},
  66735. {name: "Contours 3", icon: `${Potree.resourcePath}/icons/matcap/contours_3.jpg`},
  66736. {name: "Reflection Check Horizontal", icon: `${Potree.resourcePath}/icons/matcap/reflection_check_horizontal.jpg`},
  66737. {name: "Reflection Check Vertical", icon: `${Potree.resourcePath}/icons/matcap/reflection_check_vertical.jpg`},
  66738. ];
  66739. let elMatcapContainer = panel.find("#matcap_scheme_selection");
  66740. for(let matcap of matcaps){
  66741. let elMatcap = $(`
  66742. <img src="${matcap.icon}" class="button-icon" style="width: 25%;" />
  66743. `);
  66744. elMatcap.click( () => {
  66745. material.matcap = matcap.icon.substring(matcap.icon.lastIndexOf('/'));
  66746. });
  66747. elMatcapContainer.append(elMatcap);
  66748. }
  66749. }
  66750. {
  66751. panel.find('#sldRGBGamma').slider({
  66752. value: material.rgbGamma,
  66753. min: 0, max: 4, step: 0.01,
  66754. slide: (event, ui) => {material.rgbGamma = ui.value;}
  66755. });
  66756. panel.find('#sldRGBContrast').slider({
  66757. value: material.rgbContrast,
  66758. min: -1, max: 1, step: 0.01,
  66759. slide: (event, ui) => {material.rgbContrast = ui.value;}
  66760. });
  66761. panel.find('#sldRGBBrightness').slider({
  66762. value: material.rgbBrightness,
  66763. min: -1, max: 1, step: 0.01,
  66764. slide: (event, ui) => {material.rgbBrightness = ui.value;}
  66765. });
  66766. panel.find('#sldExtraGamma').slider({
  66767. value: material.extraGamma,
  66768. min: 0, max: 4, step: 0.01,
  66769. slide: (event, ui) => {material.extraGamma = ui.value;}
  66770. });
  66771. panel.find('#sldExtraBrightness').slider({
  66772. value: material.extraBrightness,
  66773. min: -1, max: 1, step: 0.01,
  66774. slide: (event, ui) => {material.extraBrightness = ui.value;}
  66775. });
  66776. panel.find('#sldExtraContrast').slider({
  66777. value: material.extraContrast,
  66778. min: -1, max: 1, step: 0.01,
  66779. slide: (event, ui) => {material.extraContrast = ui.value;}
  66780. });
  66781. panel.find('#sldHeightRange').slider({
  66782. range: true,
  66783. min: 0, max: 1000, step: 0.01,
  66784. values: [0, 1000],
  66785. slide: (event, ui) => {
  66786. material.heightMin = ui.values[0];
  66787. material.heightMax = ui.values[1];
  66788. }
  66789. });
  66790. panel.find('#sldIntensityGamma').slider({
  66791. value: material.intensityGamma,
  66792. min: 0, max: 4, step: 0.01,
  66793. slide: (event, ui) => {material.intensityGamma = ui.value;}
  66794. });
  66795. panel.find('#sldIntensityContrast').slider({
  66796. value: material.intensityContrast,
  66797. min: -1, max: 1, step: 0.01,
  66798. slide: (event, ui) => {material.intensityContrast = ui.value;}
  66799. });
  66800. panel.find('#sldIntensityBrightness').slider({
  66801. value: material.intensityBrightness,
  66802. min: -1, max: 1, step: 0.01,
  66803. slide: (event, ui) => {material.intensityBrightness = ui.value;}
  66804. });
  66805. panel.find('#sldWeightRGB').slider({
  66806. value: material.weightRGB,
  66807. min: 0, max: 1, step: 0.01,
  66808. slide: (event, ui) => {material.weightRGB = ui.value;}
  66809. });
  66810. panel.find('#sldWeightIntensity').slider({
  66811. value: material.weightIntensity,
  66812. min: 0, max: 1, step: 0.01,
  66813. slide: (event, ui) => {material.weightIntensity = ui.value;}
  66814. });
  66815. panel.find('#sldWeightElevation').slider({
  66816. value: material.weightElevation,
  66817. min: 0, max: 1, step: 0.01,
  66818. slide: (event, ui) => {material.weightElevation = ui.value;}
  66819. });
  66820. panel.find('#sldWeightClassification').slider({
  66821. value: material.weightClassification,
  66822. min: 0, max: 1, step: 0.01,
  66823. slide: (event, ui) => {material.weightClassification = ui.value;}
  66824. });
  66825. panel.find('#sldWeightReturnNumber').slider({
  66826. value: material.weightReturnNumber,
  66827. min: 0, max: 1, step: 0.01,
  66828. slide: (event, ui) => {material.weightReturnNumber = ui.value;}
  66829. });
  66830. panel.find('#sldWeightSourceID').slider({
  66831. value: material.weightSourceID,
  66832. min: 0, max: 1, step: 0.01,
  66833. slide: (event, ui) => {material.weightSourceID = ui.value;}
  66834. });
  66835. panel.find(`#materials\\.color\\.picker`).spectrum({
  66836. flat: true,
  66837. showInput: true,
  66838. preferredFormat: 'rgb',
  66839. cancelText: '',
  66840. chooseText: 'Apply',
  66841. color: `#${material.color.getHexString()}`,
  66842. move: color => {
  66843. let cRGB = color.toRgb();
  66844. let tc = new Color().setRGB(cRGB.r / 255, cRGB.g / 255, cRGB.b / 255);
  66845. material.color = tc;
  66846. },
  66847. change: color => {
  66848. let cRGB = color.toRgb();
  66849. let tc = new Color().setRGB(cRGB.r / 255, cRGB.g / 255, cRGB.b / 255);
  66850. material.color = tc;
  66851. }
  66852. });
  66853. this.addVolatileListener(material, "color_changed", () => {
  66854. panel.find(`#materials\\.color\\.picker`)
  66855. .spectrum('set', `#${material.color.getHexString()}`);
  66856. });
  66857. let updateHeightRange = function () {
  66858. let aPosition = pointcloud.getAttribute("position");
  66859. let bMin, bMax;
  66860. if(aPosition){
  66861. // for new format 2.0 and loader that contain precomputed min/max of attributes
  66862. let min = aPosition.range[0][2];
  66863. let max = aPosition.range[1][2];
  66864. let width = max - min;
  66865. bMin = min - 0.2 * width;
  66866. bMax = max + 0.2 * width;
  66867. }else {
  66868. // for format up until exlusive 2.0
  66869. let box = [pointcloud.pcoGeometry.tightBoundingBox, pointcloud.getBoundingBoxWorld()]
  66870. .find(v => v !== undefined);
  66871. pointcloud.updateMatrixWorld(true);
  66872. box = Utils.computeTransformedBoundingBox(box, pointcloud.matrixWorld);
  66873. let bWidth = box.max.z - box.min.z;
  66874. bMin = box.min.z - 0.2 * bWidth;
  66875. bMax = box.max.z + 0.2 * bWidth;
  66876. }
  66877. let range = material.elevationRange;
  66878. panel.find('#lblHeightRange').html(`${range[0].toFixed(2)} to ${range[1].toFixed(2)}`);
  66879. panel.find('#sldHeightRange').slider({min: bMin, max: bMax, values: range});
  66880. };
  66881. let updateExtraRange = function () {
  66882. let attributeName = material.activeAttributeName;
  66883. let attribute = pointcloud.getAttribute(attributeName);
  66884. if(attribute == null){
  66885. return;
  66886. }
  66887. let range = material.getRange(attributeName);
  66888. if(range == null){
  66889. range = attribute.range;
  66890. }
  66891. // currently only supporting scalar ranges.
  66892. // rgba, normals, positions, etc have vector ranges, however
  66893. let isValidRange = (typeof range[0] === "number") && (typeof range[1] === "number");
  66894. if(!isValidRange){
  66895. return;
  66896. }
  66897. if(range){
  66898. let msg = `${range[0].toFixed(2)} to ${range[1].toFixed(2)}`;
  66899. panel.find('#lblExtraRange').html(msg);
  66900. }else {
  66901. panel.find("could not deduce range");
  66902. }
  66903. };
  66904. let updateIntensityRange = function () {
  66905. let range = material.intensityRange;
  66906. panel.find('#lblIntensityRange').html(`${parseInt(range[0])} to ${parseInt(range[1])}`);
  66907. };
  66908. {
  66909. updateHeightRange();
  66910. panel.find(`#sldHeightRange`).slider('option', 'min');
  66911. panel.find(`#sldHeightRange`).slider('option', 'max');
  66912. }
  66913. {
  66914. let elGradientRepeat = panel.find("#gradient_repeat_option");
  66915. elGradientRepeat.selectgroup({title: "Gradient"});
  66916. elGradientRepeat.find("input").click( (e) => {
  66917. this.viewer.setElevationGradientRepeat(ElevationGradientRepeat[e.target.value]);
  66918. });
  66919. let current = Object.keys(ElevationGradientRepeat)
  66920. .filter(key => ElevationGradientRepeat[key] === this.viewer.elevationGradientRepeat);
  66921. elGradientRepeat.find(`input[value=${current}]`).trigger("click");
  66922. }
  66923. let onIntensityChange = () => {
  66924. let gamma = material.intensityGamma;
  66925. let contrast = material.intensityContrast;
  66926. let brightness = material.intensityBrightness;
  66927. updateIntensityRange();
  66928. panel.find('#lblIntensityGamma').html(gamma.toFixed(2));
  66929. panel.find('#lblIntensityContrast').html(contrast.toFixed(2));
  66930. panel.find('#lblIntensityBrightness').html(brightness.toFixed(2));
  66931. panel.find('#sldIntensityGamma').slider({value: gamma});
  66932. panel.find('#sldIntensityContrast').slider({value: contrast});
  66933. panel.find('#sldIntensityBrightness').slider({value: brightness});
  66934. };
  66935. let onRGBChange = () => {
  66936. let gamma = material.rgbGamma;
  66937. let contrast = material.rgbContrast;
  66938. let brightness = material.rgbBrightness;
  66939. panel.find('#lblRGBGamma').html(gamma.toFixed(2));
  66940. panel.find('#lblRGBContrast').html(contrast.toFixed(2));
  66941. panel.find('#lblRGBBrightness').html(brightness.toFixed(2));
  66942. panel.find('#sldRGBGamma').slider({value: gamma});
  66943. panel.find('#sldRGBContrast').slider({value: contrast});
  66944. panel.find('#sldRGBBrightness').slider({value: brightness});
  66945. };
  66946. this.addVolatileListener(material, "material_property_changed", updateExtraRange);
  66947. this.addVolatileListener(material, "material_property_changed", updateHeightRange);
  66948. this.addVolatileListener(material, "material_property_changed", onIntensityChange);
  66949. this.addVolatileListener(material, "material_property_changed", onRGBChange);
  66950. updateExtraRange();
  66951. updateHeightRange();
  66952. onIntensityChange();
  66953. onRGBChange();
  66954. }
  66955. }
  66956. setMeasurement(object){
  66957. let TYPE = {
  66958. DISTANCE: {panel: DistancePanel},
  66959. AREA: {panel: AreaPanel},
  66960. POINT: {panel: PointPanel},
  66961. ANGLE: {panel: AnglePanel},
  66962. HEIGHT: {panel: HeightPanel},
  66963. PROFILE: {panel: ProfilePanel},
  66964. VOLUME: {panel: VolumePanel},
  66965. CIRCLE: {panel: CirclePanel},
  66966. OTHER: {panel: PointPanel},
  66967. };
  66968. let getType = (measurement) => {
  66969. if (measurement instanceof Measure) {
  66970. if (measurement.showDistances && !measurement.showArea && !measurement.showAngles) {
  66971. return TYPE.DISTANCE;
  66972. } else if (measurement.showDistances && measurement.showArea && !measurement.showAngles) {
  66973. return TYPE.AREA;
  66974. } else if (measurement.maxMarkers === 1) {
  66975. return TYPE.POINT;
  66976. } else if (!measurement.showDistances && !measurement.showArea && measurement.showAngles) {
  66977. return TYPE.ANGLE;
  66978. } else if (measurement.showHeight) {
  66979. return TYPE.HEIGHT;
  66980. } else if (measurement.showCircle) {
  66981. return TYPE.CIRCLE;
  66982. } else {
  66983. return TYPE.OTHER;
  66984. }
  66985. } else if (measurement instanceof Profile) {
  66986. return TYPE.PROFILE;
  66987. } else if (measurement instanceof Volume) {
  66988. return TYPE.VOLUME;
  66989. }
  66990. };
  66991. //this.container.html("measurement");
  66992. let type = getType(object);
  66993. let Panel = type.panel;
  66994. let panel = new Panel(this.viewer, object, this);
  66995. this.container.append(panel.elContent);
  66996. }
  66997. setCamera(camera){
  66998. let panel = new CameraPanel(this.viewer, this);
  66999. this.container.append(panel.elContent);
  67000. }
  67001. setAnnotation(annotation){
  67002. let panel = new AnnotationPanel(this.viewer, this, annotation);
  67003. this.container.append(panel.elContent);
  67004. }
  67005. setCameraAnimation(animation){
  67006. let panel = new CameraAnimationPanel(this.viewer, this, animation);
  67007. this.container.append(panel.elContent);
  67008. }
  67009. }
  67010. function addCommas(nStr){
  67011. nStr += '';
  67012. let x = nStr.split('.');
  67013. let x1 = x[0];
  67014. let x2 = x.length > 1 ? '.' + x[1] : '';
  67015. let rgx = /(\d+)(\d{3})/;
  67016. while (rgx.test(x1)) {
  67017. x1 = x1.replace(rgx, '$1' + ',' + '$2');
  67018. }
  67019. return x1 + x2;
  67020. };
  67021. function format(value){
  67022. return addCommas(value.toFixed(3));
  67023. };
  67024. class HierarchicalSlider{
  67025. constructor(params = {}){
  67026. this.element = document.createElement("div");
  67027. this.labels = [];
  67028. this.sliders = [];
  67029. this.range = params.range != null ? params.range : [0, 1];
  67030. this.slide = params.slide != null ? params.slide : null;
  67031. this.step = params.step != null ? params.step : 0.0001;
  67032. let levels = params.levels != null ? params.levels : 1;
  67033. for(let level = 0; level < levels; level++){
  67034. this.addLevel();
  67035. }
  67036. }
  67037. setRange(range){
  67038. this.range = [...range];
  67039. { // root slider
  67040. let slider = this.sliders[0];
  67041. $(slider).slider({
  67042. min: range[0],
  67043. max: range[1],
  67044. });
  67045. }
  67046. for(let i = 1; i < this.sliders.length; i++){
  67047. let parentSlider = this.sliders[i - 1];
  67048. let slider = this.sliders[i];
  67049. let parentValues = $(parentSlider).slider("option", "values");
  67050. let childRange = [...parentValues];
  67051. $(slider).slider({
  67052. min: childRange[0],
  67053. max: childRange[1],
  67054. });
  67055. }
  67056. this.updateLabels();
  67057. }
  67058. setValues(values){
  67059. for(let slider of this.sliders){
  67060. $(slider).slider({
  67061. values: [...values],
  67062. });
  67063. }
  67064. this.updateLabels();
  67065. }
  67066. addLevel(){
  67067. const elLevel = document.createElement("li");
  67068. const elRange = document.createTextNode("Range: ");
  67069. const label = document.createElement("span");
  67070. const slider = document.createElement("div");
  67071. let level = this.sliders.length;
  67072. let [min, max] = [0, 0];
  67073. if(this.sliders.length === 0){
  67074. [min, max] = this.range;
  67075. }else {
  67076. let parentSlider = this.sliders[this.sliders.length - 1];
  67077. [min, max] = $(parentSlider).slider("option", "values");
  67078. }
  67079. $(slider).slider({
  67080. range: true,
  67081. min: min,
  67082. max: max,
  67083. step: this.step,
  67084. values: [min, max],
  67085. slide: (event, ui) => {
  67086. // set all descendants to same range
  67087. let levels = this.sliders.length;
  67088. for(let i = level + 1; i < levels; i++){
  67089. let descendant = this.sliders[i];
  67090. $(descendant).slider({
  67091. range: true,
  67092. min: ui.values[0],
  67093. max: ui.values[1],
  67094. values: [...ui.values],
  67095. });
  67096. }
  67097. if(this.slide){
  67098. let values = [...ui.values];
  67099. this.slide({
  67100. target: this,
  67101. range: this.range,
  67102. values: values,
  67103. });
  67104. }
  67105. this.updateLabels();
  67106. },
  67107. });
  67108. elLevel.append(elRange, label, slider);
  67109. this.sliders.push(slider);
  67110. this.labels.push(label);
  67111. this.element.append(elLevel);
  67112. this.updateLabels();
  67113. }
  67114. removeLevel(){
  67115. }
  67116. updateSliders(){
  67117. }
  67118. updateLabels(){
  67119. let levels = this.sliders.length;
  67120. for(let i = 0; i < levels; i++){
  67121. let slider = this.sliders[i];
  67122. let label = this.labels[i];
  67123. let [min, max] = $(slider).slider("option", "values");
  67124. let strMin = format(min);
  67125. let strMax = format(max);
  67126. let strLabel = `${strMin} to ${strMax}`;
  67127. label.innerHTML = strLabel;
  67128. }
  67129. }
  67130. }
  67131. class OrientedImageControls extends EventDispatcher{
  67132. constructor(viewer){
  67133. super();
  67134. this.viewer = viewer;
  67135. this.renderer = viewer.renderer;
  67136. this.originalCam = viewer.scene.getActiveCamera();
  67137. this.shearCam = viewer.scene.getActiveCamera().clone();
  67138. this.shearCam.rotation.set(this.originalCam.rotation.toArray());
  67139. this.shearCam.updateProjectionMatrix();
  67140. this.shearCam.updateProjectionMatrix = () => {
  67141. return this.shearCam.projectionMatrix;
  67142. };
  67143. this.image = null;
  67144. this.fadeFactor = 20;
  67145. this.fovDelta = 0;
  67146. this.fovMin = 0.1;
  67147. this.fovMax = 120;
  67148. this.shear = [0, 0];
  67149. // const style = ``;
  67150. this.elUp = $(`<input type="button" value="🡅" style="position: absolute; top: 10px; left: calc(50%); z-index: 1000" />`);
  67151. this.elRight = $(`<input type="button" value="🡆" style="position: absolute; top: calc(50%); right: 10px; z-index: 1000" />`);
  67152. this.elDown = $(`<input type="button" value="🡇" style="position: absolute; bottom: 10px; left: calc(50%); z-index: 1000" />`);
  67153. this.elLeft = $(`<input type="button" value="🡄" style="position: absolute; top: calc(50%); left: 10px; z-index: 1000" />`);
  67154. this.elExit = $(`<input type="button" value="Back to 3D view" style="position: absolute; bottom: 10px; right: 10px; z-index: 1000" />`);
  67155. this.elExit.click( () => {
  67156. this.release();
  67157. });
  67158. this.elUp.click(() => {
  67159. const fovY = viewer.getFOV();
  67160. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  67161. this.shear[1] += 0.1 * top;
  67162. });
  67163. this.elRight.click(() => {
  67164. const fovY = viewer.getFOV();
  67165. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  67166. this.shear[0] += 0.1 * top;
  67167. });
  67168. this.elDown.click(() => {
  67169. const fovY = viewer.getFOV();
  67170. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  67171. this.shear[1] -= 0.1 * top;
  67172. });
  67173. this.elLeft.click(() => {
  67174. const fovY = viewer.getFOV();
  67175. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  67176. this.shear[0] -= 0.1 * top;
  67177. });
  67178. this.scene = null;
  67179. this.sceneControls = new Scene();
  67180. let scroll = (e) => {
  67181. this.fovDelta += -e.delta * 1.0;
  67182. };
  67183. this.addEventListener('mousewheel', scroll);
  67184. //this.addEventListener("mousemove", onMove);
  67185. }
  67186. hasSomethingCaptured(){
  67187. return this.image !== null;
  67188. }
  67189. capture(image){
  67190. if(this.hasSomethingCaptured()){
  67191. return;
  67192. }
  67193. this.image = image;
  67194. this.originalFOV = this.viewer.getFOV();
  67195. this.originalControls = this.viewer.getControls();
  67196. this.viewer.setControls(this);
  67197. this.viewer.scene.overrideCamera = this.shearCam;
  67198. const elCanvas = this.viewer.renderer.domElement;
  67199. const elRoot = $(elCanvas.parentElement);
  67200. this.shear = [0, 0];
  67201. elRoot.append(this.elUp);
  67202. elRoot.append(this.elRight);
  67203. elRoot.append(this.elDown);
  67204. elRoot.append(this.elLeft);
  67205. elRoot.append(this.elExit);
  67206. }
  67207. release(){
  67208. this.image = null;
  67209. this.viewer.scene.overrideCamera = null;
  67210. this.elUp.detach();
  67211. this.elRight.detach();
  67212. this.elDown.detach();
  67213. this.elLeft.detach();
  67214. this.elExit.detach();
  67215. this.viewer.setFOV(this.originalFOV);
  67216. this.viewer.setControls(this.originalControls);
  67217. }
  67218. setScene (scene) {
  67219. this.scene = scene;
  67220. }
  67221. update (delta) {
  67222. // const view = this.scene.view;
  67223. // let prevTotal = this.shearCam.projectionMatrix.elements.reduce( (a, i) => a + i, 0);
  67224. //const progression = Math.min(1, this.fadeFactor * delta);
  67225. //const attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  67226. const progression = 1;
  67227. const attenuation = 0;
  67228. const oldFov = this.viewer.getFOV();
  67229. let fovProgression = progression * this.fovDelta;
  67230. let newFov = oldFov * ((1 + fovProgression / 10));
  67231. newFov = Math.max(this.fovMin, newFov);
  67232. newFov = Math.min(this.fovMax, newFov);
  67233. let diff = newFov / oldFov;
  67234. const mouse = this.viewer.inputHandler.mouse;
  67235. const canvasSize = this.viewer.renderer.getSize(new Vector2$1());
  67236. const uv = [
  67237. (mouse.x / canvasSize.x),
  67238. ((canvasSize.y - mouse.y) / canvasSize.y)
  67239. ];
  67240. const fovY = newFov;
  67241. const aspect = canvasSize.x / canvasSize.y;
  67242. const top = Math.tan(MathUtils.degToRad(fovY / 2));
  67243. const height = 2 * top;
  67244. const width = aspect * height;
  67245. const shearRangeX = [
  67246. this.shear[0] - 0.5 * width,
  67247. this.shear[0] + 0.5 * width,
  67248. ];
  67249. const shearRangeY = [
  67250. this.shear[1] - 0.5 * height,
  67251. this.shear[1] + 0.5 * height,
  67252. ];
  67253. const shx = (1 - uv[0]) * shearRangeX[0] + uv[0] * shearRangeX[1];
  67254. const shy = (1 - uv[1]) * shearRangeY[0] + uv[1] * shearRangeY[1];
  67255. const shu = (1 - diff);
  67256. const newShear = [
  67257. (1 - shu) * this.shear[0] + shu * shx,
  67258. (1 - shu) * this.shear[1] + shu * shy,
  67259. ];
  67260. this.shear = newShear;
  67261. this.viewer.setFOV(newFov);
  67262. const {originalCam, shearCam} = this;
  67263. originalCam.fov = newFov;
  67264. originalCam.updateMatrixWorld();
  67265. originalCam.updateProjectionMatrix();
  67266. shearCam.copy(originalCam);
  67267. shearCam.rotation.set(...originalCam.rotation.toArray());
  67268. shearCam.updateMatrixWorld();
  67269. shearCam.projectionMatrix.copy(originalCam.projectionMatrix);
  67270. const [sx, sy] = this.shear;
  67271. const mShear = new Matrix4().set(
  67272. 1, 0, sx, 0,
  67273. 0, 1, sy, 0,
  67274. 0, 0, 1, 0,
  67275. 0, 0, 0, 1,
  67276. );
  67277. const proj = shearCam.projectionMatrix;
  67278. proj.multiply(mShear);
  67279. shearCam.projectionMatrixInverse.copy(proj).invert();
  67280. let total = shearCam.projectionMatrix.elements.reduce( (a, i) => a + i, 0);
  67281. this.fovDelta *= attenuation;
  67282. }
  67283. };
  67284. // https://support.pix4d.com/hc/en-us/articles/205675256-How-are-yaw-pitch-roll-defined
  67285. // https://support.pix4d.com/hc/en-us/articles/202558969-How-are-omega-phi-kappa-defined
  67286. function createMaterial(){
  67287. let vertexShader = `
  67288. uniform float uNear;
  67289. varying vec2 vUV;
  67290. varying vec4 vDebug;
  67291. void main(){
  67292. vDebug = vec4(0.0, 1.0, 0.0, 1.0);
  67293. vec4 modelViewPosition = modelViewMatrix * vec4(position, 1.0);
  67294. // make sure that this mesh is at least in front of the near plane
  67295. modelViewPosition.xyz += normalize(modelViewPosition.xyz) * uNear;
  67296. gl_Position = projectionMatrix * modelViewPosition;
  67297. vUV = uv;
  67298. }
  67299. `;
  67300. let fragmentShader = `
  67301. uniform sampler2D tColor;
  67302. uniform float uOpacity;
  67303. varying vec2 vUV;
  67304. varying vec4 vDebug;
  67305. void main(){
  67306. vec4 color = texture2D(tColor, vUV);
  67307. gl_FragColor = color;
  67308. gl_FragColor.a = uOpacity;
  67309. }
  67310. `;
  67311. const material = new ShaderMaterial( {
  67312. uniforms: {
  67313. // time: { value: 1.0 },
  67314. // resolution: { value: new THREE.Vector2() }
  67315. tColor: {value: new Texture() },
  67316. uNear: {value: 0.0},
  67317. uOpacity: {value: 1.0},
  67318. },
  67319. vertexShader: vertexShader,
  67320. fragmentShader: fragmentShader,
  67321. side: DoubleSide,
  67322. } );
  67323. material.side = DoubleSide;
  67324. return material;
  67325. }
  67326. const planeGeometry = new PlaneGeometry(1, 1);
  67327. const lineGeometry = new Geometry();
  67328. lineGeometry.vertices.push(
  67329. new Vector3(-0.5, -0.5, 0),
  67330. new Vector3( 0.5, -0.5, 0),
  67331. new Vector3( 0.5, 0.5, 0),
  67332. new Vector3(-0.5, 0.5, 0),
  67333. new Vector3(-0.5, -0.5, 0),
  67334. );
  67335. class OrientedImage{
  67336. constructor(id){
  67337. this.id = id;
  67338. this.fov = 1.0;
  67339. this.position = new Vector3();
  67340. this.rotation = new Vector3();
  67341. this.width = 0;
  67342. this.height = 0;
  67343. this.fov = 1.0;
  67344. const material = createMaterial();
  67345. const lineMaterial = new LineBasicMaterial( { color: 0x00ff00 } );
  67346. this.mesh = new Mesh(planeGeometry, material);
  67347. this.line = new Line(lineGeometry, lineMaterial);
  67348. this.texture = null;
  67349. this.mesh.orientedImage = this;
  67350. }
  67351. set(position, rotation, dimension, fov){
  67352. let radians = rotation.map(MathUtils.degToRad);
  67353. this.position.set(...position);
  67354. this.mesh.position.set(...position);
  67355. this.rotation.set(...radians);
  67356. this.mesh.rotation.set(...radians);
  67357. [this.width, this.height] = dimension;
  67358. this.mesh.scale.set(this.width / this.height, 1, 1);
  67359. this.fov = fov;
  67360. this.updateTransform();
  67361. }
  67362. updateTransform(){
  67363. let {mesh, line, fov} = this;
  67364. mesh.updateMatrixWorld();
  67365. const dir = mesh.getWorldDirection();
  67366. const alpha = MathUtils.degToRad(fov / 2);
  67367. const d = -0.5 / Math.tan(alpha);
  67368. const move = dir.clone().multiplyScalar(d);
  67369. mesh.position.add(move);
  67370. line.position.copy(mesh.position);
  67371. line.scale.copy(mesh.scale);
  67372. line.rotation.copy(mesh.rotation);
  67373. }
  67374. };
  67375. class OrientedImages extends EventDispatcher{
  67376. constructor(){
  67377. super();
  67378. this.node = null;
  67379. this.cameraParams = null;
  67380. this.imageParams = null;
  67381. this.images = null;
  67382. this._visible = true;
  67383. }
  67384. set visible(visible){
  67385. if(this._visible === visible){
  67386. return;
  67387. }
  67388. for(const image of this.images){
  67389. image.mesh.visible = visible;
  67390. image.line.visible = visible;
  67391. }
  67392. this._visible = visible;
  67393. this.dispatchEvent({
  67394. type: "visibility_changed",
  67395. images: this,
  67396. });
  67397. }
  67398. get visible(){
  67399. return this._visible;
  67400. }
  67401. };
  67402. class OrientedImageLoader{
  67403. static async loadCameraParams(path){
  67404. const res = await fetch(path);
  67405. const text = await res.text();
  67406. const parser = new DOMParser();
  67407. const doc = parser.parseFromString(text, "application/xml");
  67408. const width = parseInt(doc.getElementsByTagName("width")[0].textContent);
  67409. const height = parseInt(doc.getElementsByTagName("height")[0].textContent);
  67410. const f = parseFloat(doc.getElementsByTagName("f")[0].textContent);
  67411. let a = (height / 2) / f;
  67412. let fov = 2 * MathUtils.radToDeg(Math.atan(a));
  67413. const params = {
  67414. path: path,
  67415. width: width,
  67416. height: height,
  67417. f: f,
  67418. fov: fov,
  67419. };
  67420. return params;
  67421. }
  67422. static async loadImageParams(path){
  67423. const response = await fetch(path);
  67424. if(!response.ok){
  67425. console.error(`failed to load ${path}`);
  67426. return;
  67427. }
  67428. const content = await response.text();
  67429. const lines = content.split(/\r?\n/);
  67430. const imageParams = [];
  67431. for(let i = 1; i < lines.length; i++){
  67432. const line = lines[i];
  67433. if(line.startsWith("#")){
  67434. continue;
  67435. }
  67436. const tokens = line.split(/\s+/);
  67437. if(tokens.length < 6){
  67438. continue;
  67439. }
  67440. const params = {
  67441. id: tokens[0],
  67442. x: Number.parseFloat(tokens[1]),
  67443. y: Number.parseFloat(tokens[2]),
  67444. z: Number.parseFloat(tokens[3]),
  67445. omega: Number.parseFloat(tokens[4]),
  67446. phi: Number.parseFloat(tokens[5]),
  67447. kappa: Number.parseFloat(tokens[6]),
  67448. };
  67449. // const whitelist = ["47518.jpg"];
  67450. // if(whitelist.includes(params.id)){
  67451. // imageParams.push(params);
  67452. // }
  67453. imageParams.push(params);
  67454. }
  67455. // debug
  67456. //return [imageParams[50]];
  67457. return imageParams;
  67458. }
  67459. static async load(cameraParamsPath, imageParamsPath, viewer){
  67460. const tStart = performance.now();
  67461. const [cameraParams, imageParams] = await Promise.all([
  67462. OrientedImageLoader.loadCameraParams(cameraParamsPath),
  67463. OrientedImageLoader.loadImageParams(imageParamsPath),
  67464. ]);
  67465. const orientedImageControls = new OrientedImageControls(viewer);
  67466. const raycaster = new Raycaster();
  67467. const tEnd = performance.now();
  67468. console.log(tEnd - tStart);
  67469. // const sp = new THREE.PlaneGeometry(1, 1);
  67470. // const lg = new THREE.Geometry();
  67471. // lg.vertices.push(
  67472. // new THREE.Vector3(-0.5, -0.5, 0),
  67473. // new THREE.Vector3( 0.5, -0.5, 0),
  67474. // new THREE.Vector3( 0.5, 0.5, 0),
  67475. // new THREE.Vector3(-0.5, 0.5, 0),
  67476. // new THREE.Vector3(-0.5, -0.5, 0),
  67477. // );
  67478. const {width, height} = cameraParams;
  67479. const orientedImages = [];
  67480. const sceneNode = new Object3D();
  67481. sceneNode.name = "oriented_images";
  67482. for(const params of imageParams){
  67483. // const material = createMaterial();
  67484. // const lm = new THREE.LineBasicMaterial( { color: 0x00ff00 } );
  67485. // const mesh = new THREE.Mesh(sp, material);
  67486. const {x, y, z, omega, phi, kappa} = params;
  67487. // const [rx, ry, rz] = [omega, phi, kappa]
  67488. // .map(THREE.Math.degToRad);
  67489. // mesh.position.set(x, y, z);
  67490. // mesh.scale.set(width / height, 1, 1);
  67491. // mesh.rotation.set(rx, ry, rz);
  67492. // {
  67493. // mesh.updateMatrixWorld();
  67494. // const dir = mesh.getWorldDirection();
  67495. // const alpha = THREE.Math.degToRad(cameraParams.fov / 2);
  67496. // const d = -0.5 / Math.tan(alpha);
  67497. // const move = dir.clone().multiplyScalar(d);
  67498. // mesh.position.add(move);
  67499. // }
  67500. // sceneNode.add(mesh);
  67501. // const line = new THREE.Line(lg, lm);
  67502. // line.position.copy(mesh.position);
  67503. // line.scale.copy(mesh.scale);
  67504. // line.rotation.copy(mesh.rotation);
  67505. // sceneNode.add(line);
  67506. let orientedImage = new OrientedImage(params.id);
  67507. // orientedImage.setPosition(x, y, z);
  67508. // orientedImage.setRotation(omega, phi, kappa);
  67509. // orientedImage.setDimension(width, height);
  67510. let position = [x, y, z];
  67511. let rotation = [omega, phi, kappa];
  67512. let dimension = [width, height];
  67513. orientedImage.set(position, rotation, dimension, cameraParams.fov);
  67514. sceneNode.add(orientedImage.mesh);
  67515. sceneNode.add(orientedImage.line);
  67516. orientedImages.push(orientedImage);
  67517. }
  67518. let hoveredElement = null;
  67519. let clipVolume = null;
  67520. const onMouseMove = (evt) => {
  67521. const tStart = performance.now();
  67522. if(hoveredElement){
  67523. hoveredElement.line.material.color.setRGB(0, 1, 0);
  67524. }
  67525. evt.preventDefault();
  67526. //var array = getMousePosition( container, evt.clientX, evt.clientY );
  67527. const rect = viewer.renderer.domElement.getBoundingClientRect();
  67528. const [x, y] = [evt.clientX, evt.clientY];
  67529. const array = [
  67530. ( x - rect.left ) / rect.width,
  67531. ( y - rect.top ) / rect.height
  67532. ];
  67533. const onClickPosition = new Vector2$1(...array);
  67534. //const intersects = getIntersects(onClickPosition, scene.children);
  67535. const camera = viewer.scene.getActiveCamera();
  67536. const mouse = new Vector3(
  67537. + ( onClickPosition.x * 2 ) - 1,
  67538. - ( onClickPosition.y * 2 ) + 1 );
  67539. const objects = orientedImages.map(i => i.mesh);
  67540. raycaster.setFromCamera( mouse, camera );
  67541. const intersects = raycaster.intersectObjects( objects );
  67542. let selectionChanged = false;
  67543. if ( intersects.length > 0){
  67544. //console.log(intersects);
  67545. const intersection = intersects[0];
  67546. const orientedImage = intersection.object.orientedImage;
  67547. orientedImage.line.material.color.setRGB(1, 0, 0);
  67548. selectionChanged = hoveredElement !== orientedImage;
  67549. hoveredElement = orientedImage;
  67550. }else {
  67551. hoveredElement = null;
  67552. }
  67553. let shouldRemoveClipVolume = clipVolume !== null && hoveredElement === null;
  67554. let shouldAddClipVolume = clipVolume === null && hoveredElement !== null;
  67555. if(clipVolume !== null && (hoveredElement === null || selectionChanged)){
  67556. // remove existing
  67557. viewer.scene.removePolygonClipVolume(clipVolume);
  67558. clipVolume = null;
  67559. }
  67560. if(shouldAddClipVolume || selectionChanged){
  67561. const img = hoveredElement;
  67562. const fov = cameraParams.fov;
  67563. const aspect = cameraParams.width / cameraParams.height;
  67564. const near = 1.0;
  67565. const far = 1000 * 1000;
  67566. const camera = new PerspectiveCamera(fov, aspect, near, far);
  67567. camera.rotation.order = viewer.scene.getActiveCamera().rotation.order;
  67568. camera.rotation.copy(img.mesh.rotation);
  67569. {
  67570. const mesh = img.mesh;
  67571. const dir = mesh.getWorldDirection();
  67572. const pos = mesh.position;
  67573. const alpha = MathUtils.degToRad(fov / 2);
  67574. const d = 0.5 / Math.tan(alpha);
  67575. const newCamPos = pos.clone().add(dir.clone().multiplyScalar(d));
  67576. const newCamDir = pos.clone().sub(newCamPos);
  67577. const newCamTarget = new Vector3().addVectors(
  67578. newCamPos,
  67579. newCamDir.clone().multiplyScalar(viewer.getMoveSpeed()));
  67580. camera.position.copy(newCamPos);
  67581. }
  67582. let volume = new Potree.PolygonClipVolume(camera);
  67583. let m0 = new Mesh();
  67584. let m1 = new Mesh();
  67585. let m2 = new Mesh();
  67586. let m3 = new Mesh();
  67587. m0.position.set(-1, -1, 0);
  67588. m1.position.set( 1, -1, 0);
  67589. m2.position.set( 1, 1, 0);
  67590. m3.position.set(-1, 1, 0);
  67591. volume.markers.push(m0, m1, m2, m3);
  67592. volume.initialized = true;
  67593. viewer.scene.addPolygonClipVolume(volume);
  67594. clipVolume = volume;
  67595. }
  67596. const tEnd = performance.now();
  67597. //console.log(tEnd - tStart);
  67598. };
  67599. const moveToImage = (image) => {
  67600. console.log("move to image " + image.id);
  67601. const mesh = image.mesh;
  67602. const newCamPos = image.position.clone();
  67603. const newCamTarget = mesh.position.clone();
  67604. viewer.scene.view.setView(newCamPos, newCamTarget, 500, () => {
  67605. orientedImageControls.capture(image);
  67606. });
  67607. if(image.texture === null){
  67608. const target = image;
  67609. const tmpImagePath = `${Potree.resourcePath}/images/loading.jpg`;
  67610. new TextureLoader().load(tmpImagePath,
  67611. (texture) => {
  67612. if(target.texture === null){
  67613. target.texture = texture;
  67614. target.mesh.material.uniforms.tColor.value = texture;
  67615. mesh.material.needsUpdate = true;
  67616. }
  67617. }
  67618. );
  67619. const imagePath = `${imageParamsPath}/../${target.id}`;
  67620. new TextureLoader().load(imagePath,
  67621. (texture) => {
  67622. target.texture = texture;
  67623. target.mesh.material.uniforms.tColor.value = texture;
  67624. mesh.material.needsUpdate = true;
  67625. }
  67626. );
  67627. }
  67628. };
  67629. const onMouseClick = (evt) => {
  67630. if(orientedImageControls.hasSomethingCaptured()){
  67631. return;
  67632. }
  67633. if(hoveredElement){
  67634. moveToImage(hoveredElement);
  67635. }
  67636. };
  67637. viewer.renderer.domElement.addEventListener( 'mousemove', onMouseMove, false );
  67638. viewer.renderer.domElement.addEventListener( 'mousedown', onMouseClick, false );
  67639. viewer.addEventListener("update", () => {
  67640. for(const image of orientedImages){
  67641. const world = image.mesh.matrixWorld;
  67642. const {width, height} = image;
  67643. const aspect = width / height;
  67644. const camera = viewer.scene.getActiveCamera();
  67645. const imgPos = image.mesh.getWorldPosition(new Vector3());
  67646. const camPos = camera.position;
  67647. const d = camPos.distanceTo(imgPos);
  67648. const minSize = 1; // in degrees of fov
  67649. const a = MathUtils.degToRad(minSize);
  67650. let r = d * Math.tan(a);
  67651. r = Math.max(r, 1);
  67652. image.mesh.scale.set(r * aspect, r, 1);
  67653. image.line.scale.set(r * aspect, r, 1);
  67654. image.mesh.material.uniforms.uNear.value = camera.near;
  67655. }
  67656. });
  67657. const images = new OrientedImages();
  67658. images.node = sceneNode;
  67659. images.cameraParamsPath = cameraParamsPath;
  67660. images.imageParamsPath = imageParamsPath;
  67661. images.cameraParams = cameraParams;
  67662. images.imageParams = imageParams;
  67663. images.images = orientedImages;
  67664. Potree.debug.moveToImage = moveToImage;
  67665. return images;
  67666. }
  67667. }
  67668. // This is a generated file. Do not edit.
  67669. var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/;
  67670. 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]/;
  67671. 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]/;
  67672. var unicode = {
  67673. Space_Separator: Space_Separator,
  67674. ID_Start: ID_Start,
  67675. ID_Continue: ID_Continue
  67676. };
  67677. var util = {
  67678. isSpaceSeparator (c) {
  67679. return typeof c === 'string' && unicode.Space_Separator.test(c)
  67680. },
  67681. isIdStartChar (c) {
  67682. return typeof c === 'string' && (
  67683. (c >= 'a' && c <= 'z') ||
  67684. (c >= 'A' && c <= 'Z') ||
  67685. (c === '$') || (c === '_') ||
  67686. unicode.ID_Start.test(c)
  67687. )
  67688. },
  67689. isIdContinueChar (c) {
  67690. return typeof c === 'string' && (
  67691. (c >= 'a' && c <= 'z') ||
  67692. (c >= 'A' && c <= 'Z') ||
  67693. (c >= '0' && c <= '9') ||
  67694. (c === '$') || (c === '_') ||
  67695. (c === '\u200C') || (c === '\u200D') ||
  67696. unicode.ID_Continue.test(c)
  67697. )
  67698. },
  67699. isDigit (c) {
  67700. return typeof c === 'string' && /[0-9]/.test(c)
  67701. },
  67702. isHexDigit (c) {
  67703. return typeof c === 'string' && /[0-9A-Fa-f]/.test(c)
  67704. },
  67705. };
  67706. let source;
  67707. let parseState;
  67708. let stack;
  67709. let pos;
  67710. let line;
  67711. let column;
  67712. let token;
  67713. let key;
  67714. let root;
  67715. var parse = function parse (text, reviver) {
  67716. source = String(text);
  67717. parseState = 'start';
  67718. stack = [];
  67719. pos = 0;
  67720. line = 1;
  67721. column = 0;
  67722. token = undefined;
  67723. key = undefined;
  67724. root = undefined;
  67725. do {
  67726. token = lex();
  67727. // This code is unreachable.
  67728. // if (!parseStates[parseState]) {
  67729. // throw invalidParseState()
  67730. // }
  67731. parseStates[parseState]();
  67732. } while (token.type !== 'eof')
  67733. if (typeof reviver === 'function') {
  67734. return internalize({'': root}, '', reviver)
  67735. }
  67736. return root
  67737. };
  67738. function internalize (holder, name, reviver) {
  67739. const value = holder[name];
  67740. if (value != null && typeof value === 'object') {
  67741. for (const key in value) {
  67742. const replacement = internalize(value, key, reviver);
  67743. if (replacement === undefined) {
  67744. delete value[key];
  67745. } else {
  67746. value[key] = replacement;
  67747. }
  67748. }
  67749. }
  67750. return reviver.call(holder, name, value)
  67751. }
  67752. let lexState;
  67753. let buffer;
  67754. let doubleQuote;
  67755. let sign$1;
  67756. let c$2;
  67757. function lex () {
  67758. lexState = 'default';
  67759. buffer = '';
  67760. doubleQuote = false;
  67761. sign$1 = 1;
  67762. for (;;) {
  67763. c$2 = peek();
  67764. // This code is unreachable.
  67765. // if (!lexStates[lexState]) {
  67766. // throw invalidLexState(lexState)
  67767. // }
  67768. const token = lexStates[lexState]();
  67769. if (token) {
  67770. return token
  67771. }
  67772. }
  67773. }
  67774. function peek () {
  67775. if (source[pos]) {
  67776. return String.fromCodePoint(source.codePointAt(pos))
  67777. }
  67778. }
  67779. function read () {
  67780. const c = peek();
  67781. if (c === '\n') {
  67782. line++;
  67783. column = 0;
  67784. } else if (c) {
  67785. column += c.length;
  67786. } else {
  67787. column++;
  67788. }
  67789. if (c) {
  67790. pos += c.length;
  67791. }
  67792. return c
  67793. }
  67794. const lexStates = {
  67795. default () {
  67796. switch (c$2) {
  67797. case '\t':
  67798. case '\v':
  67799. case '\f':
  67800. case ' ':
  67801. case '\u00A0':
  67802. case '\uFEFF':
  67803. case '\n':
  67804. case '\r':
  67805. case '\u2028':
  67806. case '\u2029':
  67807. read();
  67808. return
  67809. case '/':
  67810. read();
  67811. lexState = 'comment';
  67812. return
  67813. case undefined:
  67814. read();
  67815. return newToken('eof')
  67816. }
  67817. if (util.isSpaceSeparator(c$2)) {
  67818. read();
  67819. return
  67820. }
  67821. // This code is unreachable.
  67822. // if (!lexStates[parseState]) {
  67823. // throw invalidLexState(parseState)
  67824. // }
  67825. return lexStates[parseState]()
  67826. },
  67827. comment () {
  67828. switch (c$2) {
  67829. case '*':
  67830. read();
  67831. lexState = 'multiLineComment';
  67832. return
  67833. case '/':
  67834. read();
  67835. lexState = 'singleLineComment';
  67836. return
  67837. }
  67838. throw invalidChar(read())
  67839. },
  67840. multiLineComment () {
  67841. switch (c$2) {
  67842. case '*':
  67843. read();
  67844. lexState = 'multiLineCommentAsterisk';
  67845. return
  67846. case undefined:
  67847. throw invalidChar(read())
  67848. }
  67849. read();
  67850. },
  67851. multiLineCommentAsterisk () {
  67852. switch (c$2) {
  67853. case '*':
  67854. read();
  67855. return
  67856. case '/':
  67857. read();
  67858. lexState = 'default';
  67859. return
  67860. case undefined:
  67861. throw invalidChar(read())
  67862. }
  67863. read();
  67864. lexState = 'multiLineComment';
  67865. },
  67866. singleLineComment () {
  67867. switch (c$2) {
  67868. case '\n':
  67869. case '\r':
  67870. case '\u2028':
  67871. case '\u2029':
  67872. read();
  67873. lexState = 'default';
  67874. return
  67875. case undefined:
  67876. read();
  67877. return newToken('eof')
  67878. }
  67879. read();
  67880. },
  67881. value () {
  67882. switch (c$2) {
  67883. case '{':
  67884. case '[':
  67885. return newToken('punctuator', read())
  67886. case 'n':
  67887. read();
  67888. literal('ull');
  67889. return newToken('null', null)
  67890. case 't':
  67891. read();
  67892. literal('rue');
  67893. return newToken('boolean', true)
  67894. case 'f':
  67895. read();
  67896. literal('alse');
  67897. return newToken('boolean', false)
  67898. case '-':
  67899. case '+':
  67900. if (read() === '-') {
  67901. sign$1 = -1;
  67902. }
  67903. lexState = 'sign';
  67904. return
  67905. case '.':
  67906. buffer = read();
  67907. lexState = 'decimalPointLeading';
  67908. return
  67909. case '0':
  67910. buffer = read();
  67911. lexState = 'zero';
  67912. return
  67913. case '1':
  67914. case '2':
  67915. case '3':
  67916. case '4':
  67917. case '5':
  67918. case '6':
  67919. case '7':
  67920. case '8':
  67921. case '9':
  67922. buffer = read();
  67923. lexState = 'decimalInteger';
  67924. return
  67925. case 'I':
  67926. read();
  67927. literal('nfinity');
  67928. return newToken('numeric', Infinity)
  67929. case 'N':
  67930. read();
  67931. literal('aN');
  67932. return newToken('numeric', NaN)
  67933. case '"':
  67934. case "'":
  67935. doubleQuote = (read() === '"');
  67936. buffer = '';
  67937. lexState = 'string';
  67938. return
  67939. }
  67940. throw invalidChar(read())
  67941. },
  67942. identifierNameStartEscape () {
  67943. if (c$2 !== 'u') {
  67944. throw invalidChar(read())
  67945. }
  67946. read();
  67947. const u = unicodeEscape();
  67948. switch (u) {
  67949. case '$':
  67950. case '_':
  67951. break
  67952. default:
  67953. if (!util.isIdStartChar(u)) {
  67954. throw invalidIdentifier()
  67955. }
  67956. break
  67957. }
  67958. buffer += u;
  67959. lexState = 'identifierName';
  67960. },
  67961. identifierName () {
  67962. switch (c$2) {
  67963. case '$':
  67964. case '_':
  67965. case '\u200C':
  67966. case '\u200D':
  67967. buffer += read();
  67968. return
  67969. case '\\':
  67970. read();
  67971. lexState = 'identifierNameEscape';
  67972. return
  67973. }
  67974. if (util.isIdContinueChar(c$2)) {
  67975. buffer += read();
  67976. return
  67977. }
  67978. return newToken('identifier', buffer)
  67979. },
  67980. identifierNameEscape () {
  67981. if (c$2 !== 'u') {
  67982. throw invalidChar(read())
  67983. }
  67984. read();
  67985. const u = unicodeEscape();
  67986. switch (u) {
  67987. case '$':
  67988. case '_':
  67989. case '\u200C':
  67990. case '\u200D':
  67991. break
  67992. default:
  67993. if (!util.isIdContinueChar(u)) {
  67994. throw invalidIdentifier()
  67995. }
  67996. break
  67997. }
  67998. buffer += u;
  67999. lexState = 'identifierName';
  68000. },
  68001. sign () {
  68002. switch (c$2) {
  68003. case '.':
  68004. buffer = read();
  68005. lexState = 'decimalPointLeading';
  68006. return
  68007. case '0':
  68008. buffer = read();
  68009. lexState = 'zero';
  68010. return
  68011. case '1':
  68012. case '2':
  68013. case '3':
  68014. case '4':
  68015. case '5':
  68016. case '6':
  68017. case '7':
  68018. case '8':
  68019. case '9':
  68020. buffer = read();
  68021. lexState = 'decimalInteger';
  68022. return
  68023. case 'I':
  68024. read();
  68025. literal('nfinity');
  68026. return newToken('numeric', sign$1 * Infinity)
  68027. case 'N':
  68028. read();
  68029. literal('aN');
  68030. return newToken('numeric', NaN)
  68031. }
  68032. throw invalidChar(read())
  68033. },
  68034. zero () {
  68035. switch (c$2) {
  68036. case '.':
  68037. buffer += read();
  68038. lexState = 'decimalPoint';
  68039. return
  68040. case 'e':
  68041. case 'E':
  68042. buffer += read();
  68043. lexState = 'decimalExponent';
  68044. return
  68045. case 'x':
  68046. case 'X':
  68047. buffer += read();
  68048. lexState = 'hexadecimal';
  68049. return
  68050. }
  68051. return newToken('numeric', sign$1 * 0)
  68052. },
  68053. decimalInteger () {
  68054. switch (c$2) {
  68055. case '.':
  68056. buffer += read();
  68057. lexState = 'decimalPoint';
  68058. return
  68059. case 'e':
  68060. case 'E':
  68061. buffer += read();
  68062. lexState = 'decimalExponent';
  68063. return
  68064. }
  68065. if (util.isDigit(c$2)) {
  68066. buffer += read();
  68067. return
  68068. }
  68069. return newToken('numeric', sign$1 * Number(buffer))
  68070. },
  68071. decimalPointLeading () {
  68072. if (util.isDigit(c$2)) {
  68073. buffer += read();
  68074. lexState = 'decimalFraction';
  68075. return
  68076. }
  68077. throw invalidChar(read())
  68078. },
  68079. decimalPoint () {
  68080. switch (c$2) {
  68081. case 'e':
  68082. case 'E':
  68083. buffer += read();
  68084. lexState = 'decimalExponent';
  68085. return
  68086. }
  68087. if (util.isDigit(c$2)) {
  68088. buffer += read();
  68089. lexState = 'decimalFraction';
  68090. return
  68091. }
  68092. return newToken('numeric', sign$1 * Number(buffer))
  68093. },
  68094. decimalFraction () {
  68095. switch (c$2) {
  68096. case 'e':
  68097. case 'E':
  68098. buffer += read();
  68099. lexState = 'decimalExponent';
  68100. return
  68101. }
  68102. if (util.isDigit(c$2)) {
  68103. buffer += read();
  68104. return
  68105. }
  68106. return newToken('numeric', sign$1 * Number(buffer))
  68107. },
  68108. decimalExponent () {
  68109. switch (c$2) {
  68110. case '+':
  68111. case '-':
  68112. buffer += read();
  68113. lexState = 'decimalExponentSign';
  68114. return
  68115. }
  68116. if (util.isDigit(c$2)) {
  68117. buffer += read();
  68118. lexState = 'decimalExponentInteger';
  68119. return
  68120. }
  68121. throw invalidChar(read())
  68122. },
  68123. decimalExponentSign () {
  68124. if (util.isDigit(c$2)) {
  68125. buffer += read();
  68126. lexState = 'decimalExponentInteger';
  68127. return
  68128. }
  68129. throw invalidChar(read())
  68130. },
  68131. decimalExponentInteger () {
  68132. if (util.isDigit(c$2)) {
  68133. buffer += read();
  68134. return
  68135. }
  68136. return newToken('numeric', sign$1 * Number(buffer))
  68137. },
  68138. hexadecimal () {
  68139. if (util.isHexDigit(c$2)) {
  68140. buffer += read();
  68141. lexState = 'hexadecimalInteger';
  68142. return
  68143. }
  68144. throw invalidChar(read())
  68145. },
  68146. hexadecimalInteger () {
  68147. if (util.isHexDigit(c$2)) {
  68148. buffer += read();
  68149. return
  68150. }
  68151. return newToken('numeric', sign$1 * Number(buffer))
  68152. },
  68153. string () {
  68154. switch (c$2) {
  68155. case '\\':
  68156. read();
  68157. buffer += escape$1();
  68158. return
  68159. case '"':
  68160. if (doubleQuote) {
  68161. read();
  68162. return newToken('string', buffer)
  68163. }
  68164. buffer += read();
  68165. return
  68166. case "'":
  68167. if (!doubleQuote) {
  68168. read();
  68169. return newToken('string', buffer)
  68170. }
  68171. buffer += read();
  68172. return
  68173. case '\n':
  68174. case '\r':
  68175. throw invalidChar(read())
  68176. case '\u2028':
  68177. case '\u2029':
  68178. separatorChar(c$2);
  68179. break
  68180. case undefined:
  68181. throw invalidChar(read())
  68182. }
  68183. buffer += read();
  68184. },
  68185. start () {
  68186. switch (c$2) {
  68187. case '{':
  68188. case '[':
  68189. return newToken('punctuator', read())
  68190. // This code is unreachable since the default lexState handles eof.
  68191. // case undefined:
  68192. // return newToken('eof')
  68193. }
  68194. lexState = 'value';
  68195. },
  68196. beforePropertyName () {
  68197. switch (c$2) {
  68198. case '$':
  68199. case '_':
  68200. buffer = read();
  68201. lexState = 'identifierName';
  68202. return
  68203. case '\\':
  68204. read();
  68205. lexState = 'identifierNameStartEscape';
  68206. return
  68207. case '}':
  68208. return newToken('punctuator', read())
  68209. case '"':
  68210. case "'":
  68211. doubleQuote = (read() === '"');
  68212. lexState = 'string';
  68213. return
  68214. }
  68215. if (util.isIdStartChar(c$2)) {
  68216. buffer += read();
  68217. lexState = 'identifierName';
  68218. return
  68219. }
  68220. throw invalidChar(read())
  68221. },
  68222. afterPropertyName () {
  68223. if (c$2 === ':') {
  68224. return newToken('punctuator', read())
  68225. }
  68226. throw invalidChar(read())
  68227. },
  68228. beforePropertyValue () {
  68229. lexState = 'value';
  68230. },
  68231. afterPropertyValue () {
  68232. switch (c$2) {
  68233. case ',':
  68234. case '}':
  68235. return newToken('punctuator', read())
  68236. }
  68237. throw invalidChar(read())
  68238. },
  68239. beforeArrayValue () {
  68240. if (c$2 === ']') {
  68241. return newToken('punctuator', read())
  68242. }
  68243. lexState = 'value';
  68244. },
  68245. afterArrayValue () {
  68246. switch (c$2) {
  68247. case ',':
  68248. case ']':
  68249. return newToken('punctuator', read())
  68250. }
  68251. throw invalidChar(read())
  68252. },
  68253. end () {
  68254. // This code is unreachable since it's handled by the default lexState.
  68255. // if (c === undefined) {
  68256. // read()
  68257. // return newToken('eof')
  68258. // }
  68259. throw invalidChar(read())
  68260. },
  68261. };
  68262. function newToken (type, value) {
  68263. return {
  68264. type,
  68265. value,
  68266. line,
  68267. column,
  68268. }
  68269. }
  68270. function literal (s) {
  68271. for (const c of s) {
  68272. const p = peek();
  68273. if (p !== c) {
  68274. throw invalidChar(read())
  68275. }
  68276. read();
  68277. }
  68278. }
  68279. function escape$1 () {
  68280. const c = peek();
  68281. switch (c) {
  68282. case 'b':
  68283. read();
  68284. return '\b'
  68285. case 'f':
  68286. read();
  68287. return '\f'
  68288. case 'n':
  68289. read();
  68290. return '\n'
  68291. case 'r':
  68292. read();
  68293. return '\r'
  68294. case 't':
  68295. read();
  68296. return '\t'
  68297. case 'v':
  68298. read();
  68299. return '\v'
  68300. case '0':
  68301. read();
  68302. if (util.isDigit(peek())) {
  68303. throw invalidChar(read())
  68304. }
  68305. return '\0'
  68306. case 'x':
  68307. read();
  68308. return hexEscape()
  68309. case 'u':
  68310. read();
  68311. return unicodeEscape()
  68312. case '\n':
  68313. case '\u2028':
  68314. case '\u2029':
  68315. read();
  68316. return ''
  68317. case '\r':
  68318. read();
  68319. if (peek() === '\n') {
  68320. read();
  68321. }
  68322. return ''
  68323. case '1':
  68324. case '2':
  68325. case '3':
  68326. case '4':
  68327. case '5':
  68328. case '6':
  68329. case '7':
  68330. case '8':
  68331. case '9':
  68332. throw invalidChar(read())
  68333. case undefined:
  68334. throw invalidChar(read())
  68335. }
  68336. return read()
  68337. }
  68338. function hexEscape () {
  68339. let buffer = '';
  68340. let c = peek();
  68341. if (!util.isHexDigit(c)) {
  68342. throw invalidChar(read())
  68343. }
  68344. buffer += read();
  68345. c = peek();
  68346. if (!util.isHexDigit(c)) {
  68347. throw invalidChar(read())
  68348. }
  68349. buffer += read();
  68350. return String.fromCodePoint(parseInt(buffer, 16))
  68351. }
  68352. function unicodeEscape () {
  68353. let buffer = '';
  68354. let count = 4;
  68355. while (count-- > 0) {
  68356. const c = peek();
  68357. if (!util.isHexDigit(c)) {
  68358. throw invalidChar(read())
  68359. }
  68360. buffer += read();
  68361. }
  68362. return String.fromCodePoint(parseInt(buffer, 16))
  68363. }
  68364. const parseStates = {
  68365. start () {
  68366. if (token.type === 'eof') {
  68367. throw invalidEOF()
  68368. }
  68369. push();
  68370. },
  68371. beforePropertyName () {
  68372. switch (token.type) {
  68373. case 'identifier':
  68374. case 'string':
  68375. key = token.value;
  68376. parseState = 'afterPropertyName';
  68377. return
  68378. case 'punctuator':
  68379. // This code is unreachable since it's handled by the lexState.
  68380. // if (token.value !== '}') {
  68381. // throw invalidToken()
  68382. // }
  68383. pop();
  68384. return
  68385. case 'eof':
  68386. throw invalidEOF()
  68387. }
  68388. // This code is unreachable since it's handled by the lexState.
  68389. // throw invalidToken()
  68390. },
  68391. afterPropertyName () {
  68392. // This code is unreachable since it's handled by the lexState.
  68393. // if (token.type !== 'punctuator' || token.value !== ':') {
  68394. // throw invalidToken()
  68395. // }
  68396. if (token.type === 'eof') {
  68397. throw invalidEOF()
  68398. }
  68399. parseState = 'beforePropertyValue';
  68400. },
  68401. beforePropertyValue () {
  68402. if (token.type === 'eof') {
  68403. throw invalidEOF()
  68404. }
  68405. push();
  68406. },
  68407. beforeArrayValue () {
  68408. if (token.type === 'eof') {
  68409. throw invalidEOF()
  68410. }
  68411. if (token.type === 'punctuator' && token.value === ']') {
  68412. pop();
  68413. return
  68414. }
  68415. push();
  68416. },
  68417. afterPropertyValue () {
  68418. // This code is unreachable since it's handled by the lexState.
  68419. // if (token.type !== 'punctuator') {
  68420. // throw invalidToken()
  68421. // }
  68422. if (token.type === 'eof') {
  68423. throw invalidEOF()
  68424. }
  68425. switch (token.value) {
  68426. case ',':
  68427. parseState = 'beforePropertyName';
  68428. return
  68429. case '}':
  68430. pop();
  68431. }
  68432. // This code is unreachable since it's handled by the lexState.
  68433. // throw invalidToken()
  68434. },
  68435. afterArrayValue () {
  68436. // This code is unreachable since it's handled by the lexState.
  68437. // if (token.type !== 'punctuator') {
  68438. // throw invalidToken()
  68439. // }
  68440. if (token.type === 'eof') {
  68441. throw invalidEOF()
  68442. }
  68443. switch (token.value) {
  68444. case ',':
  68445. parseState = 'beforeArrayValue';
  68446. return
  68447. case ']':
  68448. pop();
  68449. }
  68450. // This code is unreachable since it's handled by the lexState.
  68451. // throw invalidToken()
  68452. },
  68453. end () {
  68454. // This code is unreachable since it's handled by the lexState.
  68455. // if (token.type !== 'eof') {
  68456. // throw invalidToken()
  68457. // }
  68458. },
  68459. };
  68460. function push () {
  68461. let value;
  68462. switch (token.type) {
  68463. case 'punctuator':
  68464. switch (token.value) {
  68465. case '{':
  68466. value = {};
  68467. break
  68468. case '[':
  68469. value = [];
  68470. break
  68471. }
  68472. break
  68473. case 'null':
  68474. case 'boolean':
  68475. case 'numeric':
  68476. case 'string':
  68477. value = token.value;
  68478. break
  68479. // This code is unreachable.
  68480. // default:
  68481. // throw invalidToken()
  68482. }
  68483. if (root === undefined) {
  68484. root = value;
  68485. } else {
  68486. const parent = stack[stack.length - 1];
  68487. if (Array.isArray(parent)) {
  68488. parent.push(value);
  68489. } else {
  68490. parent[key] = value;
  68491. }
  68492. }
  68493. if (value !== null && typeof value === 'object') {
  68494. stack.push(value);
  68495. if (Array.isArray(value)) {
  68496. parseState = 'beforeArrayValue';
  68497. } else {
  68498. parseState = 'beforePropertyName';
  68499. }
  68500. } else {
  68501. const current = stack[stack.length - 1];
  68502. if (current == null) {
  68503. parseState = 'end';
  68504. } else if (Array.isArray(current)) {
  68505. parseState = 'afterArrayValue';
  68506. } else {
  68507. parseState = 'afterPropertyValue';
  68508. }
  68509. }
  68510. }
  68511. function pop () {
  68512. stack.pop();
  68513. const current = stack[stack.length - 1];
  68514. if (current == null) {
  68515. parseState = 'end';
  68516. } else if (Array.isArray(current)) {
  68517. parseState = 'afterArrayValue';
  68518. } else {
  68519. parseState = 'afterPropertyValue';
  68520. }
  68521. }
  68522. // This code is unreachable.
  68523. // function invalidParseState () {
  68524. // return new Error(`JSON5: invalid parse state '${parseState}'`)
  68525. // }
  68526. // This code is unreachable.
  68527. // function invalidLexState (state) {
  68528. // return new Error(`JSON5: invalid lex state '${state}'`)
  68529. // }
  68530. function invalidChar (c) {
  68531. if (c === undefined) {
  68532. return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
  68533. }
  68534. return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)
  68535. }
  68536. function invalidEOF () {
  68537. return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
  68538. }
  68539. // This code is unreachable.
  68540. // function invalidToken () {
  68541. // if (token.type === 'eof') {
  68542. // return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
  68543. // }
  68544. // const c = String.fromCodePoint(token.value.codePointAt(0))
  68545. // return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)
  68546. // }
  68547. function invalidIdentifier () {
  68548. column -= 5;
  68549. return syntaxError(`JSON5: invalid identifier character at ${line}:${column}`)
  68550. }
  68551. function separatorChar (c) {
  68552. console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`);
  68553. }
  68554. function formatChar (c) {
  68555. const replacements = {
  68556. "'": "\\'",
  68557. '"': '\\"',
  68558. '\\': '\\\\',
  68559. '\b': '\\b',
  68560. '\f': '\\f',
  68561. '\n': '\\n',
  68562. '\r': '\\r',
  68563. '\t': '\\t',
  68564. '\v': '\\v',
  68565. '\0': '\\0',
  68566. '\u2028': '\\u2028',
  68567. '\u2029': '\\u2029',
  68568. };
  68569. if (replacements[c]) {
  68570. return replacements[c]
  68571. }
  68572. if (c < ' ') {
  68573. const hexString = c.charCodeAt(0).toString(16);
  68574. return '\\x' + ('00' + hexString).substring(hexString.length)
  68575. }
  68576. return c
  68577. }
  68578. function syntaxError (message) {
  68579. const err = new SyntaxError(message);
  68580. err.lineNumber = line;
  68581. err.columnNumber = column;
  68582. return err
  68583. }
  68584. var stringify = function stringify (value, replacer, space) {
  68585. const stack = [];
  68586. let indent = '';
  68587. let propertyList;
  68588. let replacerFunc;
  68589. let gap = '';
  68590. let quote;
  68591. if (
  68592. replacer != null &&
  68593. typeof replacer === 'object' &&
  68594. !Array.isArray(replacer)
  68595. ) {
  68596. space = replacer.space;
  68597. quote = replacer.quote;
  68598. replacer = replacer.replacer;
  68599. }
  68600. if (typeof replacer === 'function') {
  68601. replacerFunc = replacer;
  68602. } else if (Array.isArray(replacer)) {
  68603. propertyList = [];
  68604. for (const v of replacer) {
  68605. let item;
  68606. if (typeof v === 'string') {
  68607. item = v;
  68608. } else if (
  68609. typeof v === 'number' ||
  68610. v instanceof String ||
  68611. v instanceof Number
  68612. ) {
  68613. item = String(v);
  68614. }
  68615. if (item !== undefined && propertyList.indexOf(item) < 0) {
  68616. propertyList.push(item);
  68617. }
  68618. }
  68619. }
  68620. if (space instanceof Number) {
  68621. space = Number(space);
  68622. } else if (space instanceof String) {
  68623. space = String(space);
  68624. }
  68625. if (typeof space === 'number') {
  68626. if (space > 0) {
  68627. space = Math.min(10, Math.floor(space));
  68628. gap = ' '.substr(0, space);
  68629. }
  68630. } else if (typeof space === 'string') {
  68631. gap = space.substr(0, 10);
  68632. }
  68633. return serializeProperty('', {'': value})
  68634. function serializeProperty (key, holder) {
  68635. let value = holder[key];
  68636. if (value != null) {
  68637. if (typeof value.toJSON5 === 'function') {
  68638. value = value.toJSON5(key);
  68639. } else if (typeof value.toJSON === 'function') {
  68640. value = value.toJSON(key);
  68641. }
  68642. }
  68643. if (replacerFunc) {
  68644. value = replacerFunc.call(holder, key, value);
  68645. }
  68646. if (value instanceof Number) {
  68647. value = Number(value);
  68648. } else if (value instanceof String) {
  68649. value = String(value);
  68650. } else if (value instanceof Boolean) {
  68651. value = value.valueOf();
  68652. }
  68653. switch (value) {
  68654. case null: return 'null'
  68655. case true: return 'true'
  68656. case false: return 'false'
  68657. }
  68658. if (typeof value === 'string') {
  68659. return quoteString(value, false)
  68660. }
  68661. if (typeof value === 'number') {
  68662. return String(value)
  68663. }
  68664. if (typeof value === 'object') {
  68665. return Array.isArray(value) ? serializeArray(value) : serializeObject(value)
  68666. }
  68667. return undefined
  68668. }
  68669. function quoteString (value) {
  68670. const quotes = {
  68671. "'": 0.1,
  68672. '"': 0.2,
  68673. };
  68674. const replacements = {
  68675. "'": "\\'",
  68676. '"': '\\"',
  68677. '\\': '\\\\',
  68678. '\b': '\\b',
  68679. '\f': '\\f',
  68680. '\n': '\\n',
  68681. '\r': '\\r',
  68682. '\t': '\\t',
  68683. '\v': '\\v',
  68684. '\0': '\\0',
  68685. '\u2028': '\\u2028',
  68686. '\u2029': '\\u2029',
  68687. };
  68688. let product = '';
  68689. for (let i = 0; i < value.length; i++) {
  68690. const c = value[i];
  68691. switch (c) {
  68692. case "'":
  68693. case '"':
  68694. quotes[c]++;
  68695. product += c;
  68696. continue
  68697. case '\0':
  68698. if (util.isDigit(value[i + 1])) {
  68699. product += '\\x00';
  68700. continue
  68701. }
  68702. }
  68703. if (replacements[c]) {
  68704. product += replacements[c];
  68705. continue
  68706. }
  68707. if (c < ' ') {
  68708. let hexString = c.charCodeAt(0).toString(16);
  68709. product += '\\x' + ('00' + hexString).substring(hexString.length);
  68710. continue
  68711. }
  68712. product += c;
  68713. }
  68714. const quoteChar = quote || Object.keys(quotes).reduce((a, b) => (quotes[a] < quotes[b]) ? a : b);
  68715. product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]);
  68716. return quoteChar + product + quoteChar
  68717. }
  68718. function serializeObject (value) {
  68719. if (stack.indexOf(value) >= 0) {
  68720. throw TypeError('Converting circular structure to JSON5')
  68721. }
  68722. stack.push(value);
  68723. let stepback = indent;
  68724. indent = indent + gap;
  68725. let keys = propertyList || Object.keys(value);
  68726. let partial = [];
  68727. for (const key of keys) {
  68728. const propertyString = serializeProperty(key, value);
  68729. if (propertyString !== undefined) {
  68730. let member = serializeKey(key) + ':';
  68731. if (gap !== '') {
  68732. member += ' ';
  68733. }
  68734. member += propertyString;
  68735. partial.push(member);
  68736. }
  68737. }
  68738. let final;
  68739. if (partial.length === 0) {
  68740. final = '{}';
  68741. } else {
  68742. let properties;
  68743. if (gap === '') {
  68744. properties = partial.join(',');
  68745. final = '{' + properties + '}';
  68746. } else {
  68747. let separator = ',\n' + indent;
  68748. properties = partial.join(separator);
  68749. final = '{\n' + indent + properties + ',\n' + stepback + '}';
  68750. }
  68751. }
  68752. stack.pop();
  68753. indent = stepback;
  68754. return final
  68755. }
  68756. function serializeKey (key) {
  68757. if (key.length === 0) {
  68758. return quoteString(key, true)
  68759. }
  68760. const firstChar = String.fromCodePoint(key.codePointAt(0));
  68761. if (!util.isIdStartChar(firstChar)) {
  68762. return quoteString(key, true)
  68763. }
  68764. for (let i = firstChar.length; i < key.length; i++) {
  68765. if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) {
  68766. return quoteString(key, true)
  68767. }
  68768. }
  68769. return key
  68770. }
  68771. function serializeArray (value) {
  68772. if (stack.indexOf(value) >= 0) {
  68773. throw TypeError('Converting circular structure to JSON5')
  68774. }
  68775. stack.push(value);
  68776. let stepback = indent;
  68777. indent = indent + gap;
  68778. let partial = [];
  68779. for (let i = 0; i < value.length; i++) {
  68780. const propertyString = serializeProperty(String(i), value);
  68781. partial.push((propertyString !== undefined) ? propertyString : 'null');
  68782. }
  68783. let final;
  68784. if (partial.length === 0) {
  68785. final = '[]';
  68786. } else {
  68787. if (gap === '') {
  68788. let properties = partial.join(',');
  68789. final = '[' + properties + ']';
  68790. } else {
  68791. let separator = ',\n' + indent;
  68792. let properties = partial.join(separator);
  68793. final = '[\n' + indent + properties + ',\n' + stepback + ']';
  68794. }
  68795. }
  68796. stack.pop();
  68797. indent = stepback;
  68798. return final
  68799. }
  68800. };
  68801. const JSON5 = {
  68802. parse,
  68803. stringify,
  68804. };
  68805. var lib = JSON5;
  68806. class Sidebar{
  68807. constructor(viewer){
  68808. this.viewer = viewer;
  68809. this.measuringTool = viewer.measuringTool;
  68810. this.profileTool = viewer.profileTool;
  68811. this.volumeTool = viewer.volumeTool;
  68812. this.dom = $("#sidebar_root");
  68813. }
  68814. createToolIcon(icon, title, callback){
  68815. let element = $(`
  68816. <img src="${icon}"
  68817. style="width: 32px; height: 32px"
  68818. class="button-icon"
  68819. data-i18n="${title}" />
  68820. `);
  68821. element.click(callback);
  68822. return element;
  68823. }
  68824. init(){
  68825. if(Potree.settings.editType == 'merge'){
  68826. this.initMergeBar();
  68827. this.initToolbar();
  68828. this.initScene();
  68829. this.initNavigation();
  68830. }else {
  68831. this.initAccordion();
  68832. this.initAppearance();
  68833. this.initToolbar();
  68834. this.initScene();
  68835. this.initNavigation();
  68836. this.initFilters();
  68837. this.initClippingTool();
  68838. this.initSettings();
  68839. if(Potree.settings.editType != 'pano'){
  68840. this.initAlignment();
  68841. this.initClipModel();
  68842. this.initSiteModel();
  68843. this.initParitcle();
  68844. }else {
  68845. this.initPanosEdit();
  68846. }
  68847. }
  68848. $('#potree_version_number').html(Potree.version.major + "." + Potree.version.minor + Potree.version.suffix);
  68849. }
  68850. initAlignment(){
  68851. let Alignment = viewer.modules.Alignment;
  68852. var pannel = $('#alignment');
  68853. var buttons = pannel.find('[name="transform"] button');
  68854. var applyToPointcloud = (fun, value)=>{
  68855. return function(){
  68856. var selected = $('#alignment li[name="selectPointCloud"] input:checked' );
  68857. Array.from(selected).forEach(e=>{
  68858. var pointcloud = viewer.scene.pointclouds.find(p=>p.name == e.name);
  68859. fun(pointcloud, value);
  68860. });
  68861. }
  68862. };
  68863. //逆时针是正数
  68864. buttons.eq(0).on('click', applyToPointcloud(Alignment.rotate, 10));
  68865. //viewer.scene.pointclouds[0].rotation.z += THREE.Math.degToRad(10)
  68866. buttons.eq(1).on('click' ,applyToPointcloud(Alignment.rotate, 1));
  68867. buttons.eq(2).on('click', applyToPointcloud(Alignment.rotate, 0.1));
  68868. buttons.eq(3).on('click', applyToPointcloud(Alignment.rotate, -10));
  68869. buttons.eq(4).on('click',applyToPointcloud(Alignment.rotate, -1));
  68870. buttons.eq(5).on('click',applyToPointcloud(Alignment.rotate, -0.1));
  68871. buttons.eq(6).on('click', applyToPointcloud(Alignment.translate, new Vector3(-1,0,0)));
  68872. buttons.eq(7).on('click', applyToPointcloud(Alignment.translate, new Vector3(1,0,0)));
  68873. buttons.eq(8).on('click', applyToPointcloud(Alignment.translate, new Vector3(0,-1,0)));
  68874. buttons.eq(9).on('click', applyToPointcloud(Alignment.translate, new Vector3(0,1,0)));
  68875. buttons.eq(10).on('click', applyToPointcloud(Alignment.translate, new Vector3(0,0,-1)));
  68876. buttons.eq(11).on('click', applyToPointcloud(Alignment.translate, new Vector3(0,0,1)));
  68877. pannel.find('#startAlignment').on('click', ()=>{
  68878. Alignment.enter();
  68879. });
  68880. pannel.find('#exitAlignment').on('click', ()=>{
  68881. Alignment.save();
  68882. Alignment.leave();
  68883. });
  68884. pannel.find('#rotTool').on('click', ()=>{
  68885. Alignment.switchHandle('rotate');
  68886. });
  68887. pannel.find('#moveTool').on('click', ()=>{
  68888. Alignment.switchHandle('translate');
  68889. });
  68890. }
  68891. initMergeBar(){//多元融合模块
  68892. var pannel = $('#mergeModel');
  68893. var buttons = pannel.find('button');
  68894. let MergeEditor = viewer.modules.MergeEditor;
  68895. let loading = false;
  68896. pannel.find('ul[name="model"] li button').on('click',(e)=>{
  68897. if(loading)return console.log('还在加载', loading)
  68898. let $elem = $(e.target);
  68899. let parent = $elem.parent();
  68900. let name = parent.attr('name');
  68901. if($elem.attr('name') == 'select'){
  68902. return Potree.selectModel(name)
  68903. }
  68904. if($elem.text() == '添加'){
  68905. let startTime = Date.now();
  68906. Potree.addModel(name,()=>{
  68907. loading = false;
  68908. $elem.text('删除');
  68909. let now = Date.now();
  68910. console.log('加载完毕', name, '用时', (now-startTime)/1000, 's');
  68911. });
  68912. loading = name;
  68913. }else {
  68914. Potree.removeModel(name);
  68915. $elem.text('添加');
  68916. }
  68917. });
  68918. pannel.find('li button[name="splitScreen"]').on('click',(e)=>{
  68919. let $elem = $(e.target);
  68920. if($elem.text() == '分屏'){
  68921. $elem.text('恢复');
  68922. MergeEditor.enterSplit();
  68923. }else {
  68924. $elem.text('分屏');
  68925. MergeEditor.leaveSplit();
  68926. }
  68927. });
  68928. let addingTag = false;
  68929. pannel.find('li button[name="tag"]').on('click',(e)=>{
  68930. let $elem = $(e.target);
  68931. viewer.tagTool.startInsertion();
  68932. });
  68933. }
  68934. addAlignmentButton(pointcloud){
  68935. var pannel = $('#alignment li[name="selectPointCloud"]>div');
  68936. var option = $(` <input name="${pointcloud.name}" class="editCheckbox" type="checkbox" >
  68937. <label for="showingLabels">${pointcloud.name}</label>`);
  68938. pannel.append(option);
  68939. /* option.find("input").on('change',function(){
  68940. })
  68941. */
  68942. }
  68943. initClipModel(){
  68944. let Clip = viewer.modules.Clip;
  68945. var pannel = $('#clipModel');
  68946. var buttons = pannel.find('button');
  68947. buttons.eq(0).on('click', Clip.enter.bind(Clip));
  68948. buttons.eq(1).on('click', Clip.download.bind(Clip));
  68949. buttons.eq(2).on('click', Clip.leave.bind(Clip));
  68950. }
  68951. initSiteModel(){
  68952. let SiteModel = viewer.modules.SiteModel;
  68953. var pannel = $('#siteModel');
  68954. pannel.find('button[name="start"] ').on('click', SiteModel.enter.bind(SiteModel));
  68955. pannel.find('button[name="exit"] ').on('click', SiteModel.leave.bind(SiteModel));
  68956. pannel.find('button[name="building"] ').on('click', SiteModel.startInsertion.bind(SiteModel,'building'));
  68957. pannel.find('button[name="floor"] ').on('click', ()=>{
  68958. SiteModel.addFloor(SiteModel.buildings[0], 'top');
  68959. } );
  68960. pannel.find('button[name="room"] ').on('click', ()=>{
  68961. SiteModel.startInsertion('room', SiteModel.buildings[0].buildChildren[0]);
  68962. });
  68963. pannel.find('button[name="digHole"] ').on('click', ()=>{
  68964. SiteModel.selected && SiteModel.startInsertion('hole', SiteModel.selected);
  68965. });
  68966. pannel.find('button[name="selectBuilding"] ').on('click', ()=>{
  68967. SiteModel.selectEntity(SiteModel.buildings[0] );
  68968. } );
  68969. pannel.find('button[name="selectFloor"] ').on('click', ()=>{
  68970. SiteModel.selectEntity(SiteModel.buildings[0].buildChildren[0]);
  68971. } );
  68972. pannel.find('button[name="selectRoom"] ').on('click', ()=>{
  68973. SiteModel.selectEntity(SiteModel.buildings[0].buildChildren[0].buildChildren[0]);
  68974. });
  68975. pannel.find('button[name="removeFirstBuilding"] ').on('click', ()=>{
  68976. SiteModel.removeEntity(SiteModel.buildings[0]);
  68977. });
  68978. pannel.find('button[name="removeFirstFloor"] ').on('click', ()=>{
  68979. SiteModel.removeEntity(SiteModel.buildings[0].buildChildren[0]);
  68980. });
  68981. pannel.find('button[name="removeFirstRoom"] ').on('click', ()=>{
  68982. SiteModel.removeEntity(SiteModel.buildings[0].buildChildren[0].buildChildren[0]);
  68983. });
  68984. pannel.find('button[name="removeFirstHole"] ').on('click', ()=>{
  68985. SiteModel.selected.removeHole(SiteModel.selected.holes[0]);
  68986. });
  68987. pannel.find('button[name="removeFirstMarker"] ').on('click', ()=>{
  68988. //SiteModel.removeMarker(SiteModel.selected.markers[0])
  68989. SiteModel.selected.removeMarker(0);
  68990. });
  68991. }
  68992. initParitcle(){
  68993. let ParticleEditor = viewer.modules.ParticleEditor;
  68994. var pannel = $('#particle');
  68995. pannel.find('button[name="addFire"] ').on('click', ()=>{
  68996. ParticleEditor.startInsertion('fire+smoke');
  68997. });
  68998. pannel.find('button[name="addExplode"] ').on('click', ()=>{
  68999. ParticleEditor.startInsertion('explode');
  69000. });
  69001. }
  69002. initPanosEdit(){
  69003. let PanoEditor = viewer.modules.PanoEditor;
  69004. let Alignment = viewer.modules.Alignment;
  69005. var pannel = $('#panos');
  69006. pannel.find('button[name="save"] ').on('click', ()=>{
  69007. console.log('saveData',PanoEditor.exportSavingData());
  69008. });
  69009. pannel.find('button[name="translate"] ').on('click', ()=>{
  69010. Alignment.switchHandle('translate');
  69011. });
  69012. pannel.find('button[name="rotate"] ').on('click', ()=>{
  69013. Alignment.switchHandle('rotate');
  69014. });
  69015. pannel.find('button[name="topView"] ').on('click', ()=>{
  69016. PanoEditor.switchView('top');
  69017. });
  69018. pannel.find('button[name="sideView"] ').on('click', ()=>{
  69019. PanoEditor.switchView('right');
  69020. });
  69021. pannel.find('button[name="3DView"] ').on('click', ()=>{
  69022. PanoEditor.switchView('mainView');
  69023. });
  69024. pannel.find('button[name="addLink"] ').on('click', ()=>{
  69025. PanoEditor.setLinkOperateState('addLink', true);
  69026. });
  69027. pannel.find('button[name="removeLink"] ').on('click', ()=>{
  69028. PanoEditor.setLinkOperateState('removeLink', true);
  69029. });
  69030. pannel.find('button[name="getCloser"] ').on('click', ()=>{
  69031. PanoEditor.setZoomInState(true);
  69032. });
  69033. }
  69034. initToolbar(){
  69035. // ANGLE
  69036. let elToolbar = $('#tools');
  69037. elToolbar.append(this.createToolIcon(
  69038. Potree.resourcePath + '/icons/angle.png',
  69039. '[title]tt.angle_measurement',
  69040. () => {
  69041. $('#menu_measurements').next().slideDown();
  69042. let measurement = this.measuringTool.startInsertion({
  69043. showDistances: false,
  69044. showAngles: true,
  69045. showArea: false,
  69046. closed: true,
  69047. maxMarkers: 3,
  69048. minMarkers:3,
  69049. measureType: 'Angle'});
  69050. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69051. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69052. $.jstree.reference(jsonNode.id).deselect_all();
  69053. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69054. }
  69055. ));
  69056. // POINT
  69057. elToolbar.append(this.createToolIcon(
  69058. Potree.resourcePath + '/icons/point.svg',
  69059. '[title]tt.point_measurement',
  69060. () => {
  69061. $('#menu_measurements').next().slideDown();
  69062. let measurement = this.measuringTool.startInsertion({
  69063. showDistances: false,
  69064. showAngles: false,
  69065. showCoordinates: true,
  69066. showEdges:false,
  69067. showArea: false,
  69068. closed: true,
  69069. maxMarkers: 1,
  69070. minMarkers:1,
  69071. measureType: 'Point'});
  69072. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69073. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69074. $.jstree.reference(jsonNode.id).deselect_all();
  69075. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69076. }
  69077. ));
  69078. // DISTANCE
  69079. elToolbar.append(this.createToolIcon(
  69080. Potree.resourcePath + '/icons/distance.svg',
  69081. '[title]tt.distance_measurement',
  69082. () => {
  69083. $('#menu_measurements').next().slideDown();
  69084. let measurement = this.measuringTool.startInsertion({
  69085. showDistances: true,
  69086. showArea: false,
  69087. closed: false,
  69088. minMarkers:2,
  69089. maxMarkers: 2,
  69090. measureType: 'Distance'
  69091. });
  69092. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69093. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69094. $.jstree.reference(jsonNode.id).deselect_all();
  69095. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69096. }
  69097. ));
  69098. // HEIGHT
  69099. elToolbar.append(this.createToolIcon(
  69100. Potree.resourcePath + '/icons/height.svg',
  69101. '[title]tt.height_measurement',
  69102. () => {
  69103. $('#menu_measurements').next().slideDown();
  69104. let measurement = this.measuringTool.startInsertion({
  69105. showDistances: true,//false,
  69106. showHeight: true,
  69107. showArea: false,
  69108. closed: false,
  69109. maxMarkers: 2,
  69110. minMarkers:2,
  69111. //showGuideLine: true: true
  69112. measureType: 'Ver Distance',
  69113. });
  69114. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69115. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69116. $.jstree.reference(jsonNode.id).deselect_all();
  69117. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69118. }
  69119. ));
  69120. // CIRCLE
  69121. elToolbar.append(this.createToolIcon(
  69122. Potree.resourcePath + '/icons/circle.svg',
  69123. '[title]tt.circle_measurement',
  69124. () => {
  69125. $('#menu_measurements').next().slideDown();
  69126. let measurement = this.measuringTool.startInsertion({
  69127. showDistances: false,
  69128. showHeight: false,
  69129. showArea: false,
  69130. showCircle: true,
  69131. showEdges: false,
  69132. closed: false,
  69133. maxMarkers: 3,
  69134. minMarkers:3,
  69135. measureType: 'Circle'
  69136. });
  69137. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69138. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69139. $.jstree.reference(jsonNode.id).deselect_all();
  69140. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69141. }
  69142. ));
  69143. // AZIMUTH
  69144. elToolbar.append(this.createToolIcon(
  69145. Potree.resourcePath + '/icons/azimuth.svg',
  69146. 'Azimuth',
  69147. () => {
  69148. $('#menu_measurements').next().slideDown();
  69149. let measurement = this.measuringTool.startInsertion({
  69150. showDistances: false,
  69151. showHeight: false,
  69152. showArea: false,
  69153. showCircle: false,
  69154. showEdges: false,
  69155. showAzimuth: true,
  69156. closed: false,
  69157. maxMarkers: 2,
  69158. minMarkers:2,
  69159. measureType: 'Azimuth'});
  69160. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69161. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69162. $.jstree.reference(jsonNode.id).deselect_all();
  69163. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69164. }
  69165. ));
  69166. // AREA
  69167. elToolbar.append(this.createToolIcon(
  69168. Potree.resourcePath + '/icons/area.svg',
  69169. '[title]tt.area_measurement',
  69170. () => {
  69171. $('#menu_measurements').next().slideDown();
  69172. let measurement = this.measuringTool.startInsertion({
  69173. showDistances: true,
  69174. showArea: true,
  69175. closed: true,
  69176. minMarkers:3,
  69177. //showGuideLine: true: true,
  69178. measureType: 'Area'});
  69179. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69180. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69181. $.jstree.reference(jsonNode.id).deselect_all();
  69182. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69183. }
  69184. ));
  69185. //Hor AREA
  69186. elToolbar.append(this.createToolIcon(
  69187. Potree.resourcePath + '/icons/area.svg',
  69188. '[title]tt.Hor Area',
  69189. () => {
  69190. $('#menu_measurements').next().slideDown();
  69191. let measurement = this.measuringTool.startInsertion({
  69192. showDistances: true,
  69193. showArea: true,
  69194. closed: true,
  69195. minMarkers:3,
  69196. measureType: 'Hor Area'});
  69197. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69198. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69199. $.jstree.reference(jsonNode.id).deselect_all();
  69200. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69201. }
  69202. ));
  69203. // Ver Area
  69204. elToolbar.append(this.createToolIcon(
  69205. Potree.resourcePath + '/icons/area.svg',
  69206. '[title]tt.Ver Area',
  69207. () => {
  69208. $('#menu_measurements').next().slideDown();
  69209. let measurement = this.measuringTool.startInsertion({
  69210. showDistances: true,
  69211. showArea: true,
  69212. closed: true,
  69213. minMarkers:3,
  69214. measureType: 'Ver Area'});
  69215. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69216. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69217. $.jstree.reference(jsonNode.id).deselect_all();
  69218. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69219. }
  69220. ));
  69221. // rect area freedom direction
  69222. elToolbar.append(this.createToolIcon(
  69223. Potree.resourcePath + '/icons/area.svg',
  69224. '[title]tt.area_freedom_rect',
  69225. () => {
  69226. $('#menu_measurements').next().slideDown();
  69227. let measurement = this.measuringTool.startInsertion({
  69228. showDistances: true,
  69229. showArea: true,
  69230. closed: true,
  69231. minMarkers:4,
  69232. maxMarkers:4,
  69233. //showGuideLine: true: true,
  69234. isRect:true,
  69235. measureType: 'Rect Area'});
  69236. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69237. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69238. $.jstree.reference(jsonNode.id).deselect_all();
  69239. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69240. }
  69241. ));
  69242. // rect area horizontal
  69243. elToolbar.append(this.createToolIcon(
  69244. Potree.resourcePath + '/icons/area.svg',
  69245. '[title]tt.area_horizontal_rect',
  69246. () => {
  69247. $('#menu_measurements').next().slideDown();
  69248. let measurement = this.measuringTool.startInsertion({
  69249. showDistances: true,
  69250. showArea: true,
  69251. closed: true,
  69252. minMarkers:4,
  69253. maxMarkers:4,
  69254. //showGuideLine: true: true,
  69255. isRect:true,
  69256. faceDirection:"horizontal",
  69257. measureType: 'Hor Rect Area'});
  69258. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69259. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69260. $.jstree.reference(jsonNode.id).deselect_all();
  69261. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69262. }
  69263. ));
  69264. // rect area vertical
  69265. elToolbar.append(this.createToolIcon(
  69266. Potree.resourcePath + '/icons/area.svg',
  69267. '[title]tt.area_vertical_rect',
  69268. () => {
  69269. $('#menu_measurements').next().slideDown();
  69270. let measurement = this.measuringTool.startInsertion({
  69271. showDistances: true,
  69272. showArea: true,
  69273. closed: true,
  69274. minMarkers:4,
  69275. maxMarkers:4,
  69276. //showGuideLine: true: true,
  69277. isRect:true,
  69278. faceDirection:"vertical",
  69279. measureType: 'Ver Rect Area'});
  69280. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69281. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  69282. $.jstree.reference(jsonNode.id).deselect_all();
  69283. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69284. }
  69285. ));
  69286. // VOLUME
  69287. elToolbar.append(this.createToolIcon(
  69288. Potree.resourcePath + '/icons/volume.svg',
  69289. '[title]tt.volume_measurement',
  69290. () => {
  69291. let volume = this.volumeTool.startInsertion();
  69292. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69293. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === volume.uuid);
  69294. $.jstree.reference(jsonNode.id).deselect_all();
  69295. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69296. }
  69297. ));
  69298. // SPHERE VOLUME
  69299. elToolbar.append(this.createToolIcon(
  69300. Potree.resourcePath + '/icons/sphere_distances.svg',
  69301. '[title]tt.volume_measurement',
  69302. () => {
  69303. let volume = this.volumeTool.startInsertion({type: SphereVolume});
  69304. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69305. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === volume.uuid);
  69306. $.jstree.reference(jsonNode.id).deselect_all();
  69307. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69308. }
  69309. ));
  69310. // PROFILE
  69311. elToolbar.append(this.createToolIcon(
  69312. Potree.resourcePath + '/icons/profile.svg',
  69313. '[title]tt.height_profile',
  69314. () => {
  69315. $('#menu_measurements').next().slideDown(); ;
  69316. let profile = this.profileTool.startInsertion();
  69317. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69318. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === profile.uuid);
  69319. $.jstree.reference(jsonNode.id).deselect_all();
  69320. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69321. }
  69322. ));
  69323. // ANNOTATION
  69324. elToolbar.append(this.createToolIcon(
  69325. Potree.resourcePath + '/icons/annotation.svg',
  69326. '[title]tt.annotation',
  69327. () => {
  69328. $('#menu_measurements').next().slideDown(); ;
  69329. let annotation = this.viewer.annotationTool.startInsertion();
  69330. let annotationsRoot = $("#jstree_scene").jstree().get_json("annotations");
  69331. let jsonNode = annotationsRoot.children.find(child => child.data.uuid === annotation.uuid);
  69332. $.jstree.reference(jsonNode.id).deselect_all();
  69333. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69334. }
  69335. ));
  69336. // REMOVE ALL
  69337. elToolbar.append(this.createToolIcon(
  69338. Potree.resourcePath + '/icons/reset_tools.svg',
  69339. '[title]tt.remove_all_measurement',
  69340. () => {
  69341. this.viewer.scene.removeAllMeasurements();
  69342. }
  69343. ));
  69344. { // SHOW / HIDE Measurements
  69345. let elShow = $("#measurement_options_show");
  69346. elShow.selectgroup({title: "Show/Hide labels"});
  69347. elShow.find("input").click( (e) => {
  69348. const show = e.target.value === "SHOW";
  69349. this.measuringTool.showLabels = show;
  69350. });
  69351. let currentShow = this.measuringTool.showLabels ? "SHOW" : "HIDE";
  69352. elShow.find(`input[value=${currentShow}]`).trigger("click");
  69353. }
  69354. }
  69355. initScene(){
  69356. let elScene = $("#menu_scene");
  69357. let elObjects = elScene.next().find("#scene_objects");
  69358. let elProperties = elScene.next().find("#scene_object_properties");
  69359. {
  69360. let elExport = elScene.next().find("#scene_export");
  69361. let geoJSONIcon = `${Potree.resourcePath}/icons/file_geojson.svg`;
  69362. let dxfIcon = `${Potree.resourcePath}/icons/file_dxf.svg`;
  69363. let potreeIcon = `${Potree.resourcePath}/icons/file_potree.svg`;
  69364. elExport.append(`
  69365. Export: <br>
  69366. <a href="#" download="measure.json"><img name="geojson_export_button" src="${geoJSONIcon}" class="button-icon" style="height: 24px" /></a>
  69367. <a href="#" download="measure.dxf"><img name="dxf_export_button" src="${dxfIcon}" class="button-icon" style="height: 24px" /></a>
  69368. <a href="#" download="potree.json5"><img name="potree_export_button" src="${potreeIcon}" class="button-icon" style="height: 24px" /></a>
  69369. `);
  69370. let elDownloadJSON = elExport.find("img[name=geojson_export_button]").parent();
  69371. elDownloadJSON.click( (event) => {
  69372. let scene = this.viewer.scene;
  69373. let measurements = [...scene.measurements, ...scene.profiles, ...scene.volumes];
  69374. if(measurements.length > 0){
  69375. let geoJson = GeoJSONExporter.toString(measurements);
  69376. let url = window.URL.createObjectURL(new Blob([geoJson], {type: 'data:application/octet-stream'}));
  69377. elDownloadJSON.attr('href', url);
  69378. }else {
  69379. this.viewer.postError("nothing to export");
  69380. event.preventDefault();
  69381. }
  69382. });
  69383. let elDownloadDXF = elExport.find("img[name=dxf_export_button]").parent();
  69384. elDownloadDXF.click( (event) => {
  69385. let scene = this.viewer.scene;
  69386. let measurements = [...scene.measurements, ...scene.profiles, ...scene.volumes];
  69387. if(measurements.length > 0){
  69388. let dxf = DXFExporter.toString(measurements);
  69389. let url = window.URL.createObjectURL(new Blob([dxf], {type: 'data:application/octet-stream'}));
  69390. elDownloadDXF.attr('href', url);
  69391. }else {
  69392. this.viewer.postError("no measurements to export");
  69393. event.preventDefault();
  69394. }
  69395. });
  69396. let elDownloadPotree = elExport.find("img[name=potree_export_button]").parent();
  69397. elDownloadPotree.click( (event) => {
  69398. let data = Potree.saveProject(this.viewer);
  69399. let dataString = lib.stringify(data, null, "\t");
  69400. let url = window.URL.createObjectURL(new Blob([dataString], {type: 'data:application/octet-stream'}));
  69401. elDownloadPotree.attr('href', url);
  69402. });
  69403. }
  69404. let propertiesPanel = new PropertiesPanel(elProperties, this.viewer);
  69405. propertiesPanel.setScene(this.viewer.scene);
  69406. localStorage.removeItem('jstree');
  69407. let tree = $(`<div id="jstree_scene"></div>`);
  69408. elObjects.append(tree);
  69409. tree.jstree({
  69410. 'plugins': ["checkbox", "state"],
  69411. 'core': {
  69412. "dblclick_toggle": false,
  69413. "state": {
  69414. "checked" : true
  69415. },
  69416. 'check_callback': true,
  69417. "expand_selected_onload": true
  69418. },
  69419. "checkbox" : {
  69420. "keep_selected_style": true,
  69421. "three_state": false,
  69422. "whole_node": false,
  69423. "tie_selection": false,
  69424. },
  69425. });
  69426. let createNode = (parent, text, icon, object) => {
  69427. let nodeID = tree.jstree('create_node', parent, {
  69428. "text": text,
  69429. "icon": icon,
  69430. "data": object
  69431. },
  69432. "last", false, false);
  69433. if(object.visible){
  69434. tree.jstree('check_node', nodeID);
  69435. }else {
  69436. tree.jstree('uncheck_node', nodeID);
  69437. }
  69438. return nodeID;
  69439. };
  69440. let pcID = tree.jstree('create_node', "#", { "text": "<b>Point Clouds</b>", "id": "pointclouds"}, "last", false, false);
  69441. let measurementID = tree.jstree('create_node', "#", { "text": "<b>Measurements</b>", "id": "measurements" }, "last", false, false);
  69442. let annotationsID = tree.jstree('create_node', "#", { "text": "<b>Annotations</b>", "id": "annotations" }, "last", false, false);
  69443. let otherID = tree.jstree('create_node', "#", { "text": "<b>Other</b>", "id": "other" }, "last", false, false);
  69444. let vectorsID = tree.jstree('create_node', "#", { "text": "<b>Vectors</b>", "id": "vectors" }, "last", false, false);
  69445. let imagesID = tree.jstree('create_node', "#", { "text": "<b> Images</b>", "id": "images" }, "last", false, false);
  69446. tree.jstree("check_node", pcID);
  69447. tree.jstree("check_node", measurementID);
  69448. tree.jstree("check_node", annotationsID);
  69449. tree.jstree("check_node", otherID);
  69450. tree.jstree("check_node", vectorsID);
  69451. tree.jstree("check_node", imagesID);
  69452. tree.on('create_node.jstree', (e, data) => {
  69453. tree.jstree("open_all");
  69454. });
  69455. tree.on("select_node.jstree", (e, data) => {
  69456. let object = data.node.data;
  69457. propertiesPanel.set(object);
  69458. this.viewer.inputHandler.deselectAll();
  69459. if(object instanceof Volume){
  69460. this.viewer.inputHandler.toggleSelection(object);
  69461. }
  69462. $(this.viewer.renderer.domElement).focus();
  69463. });
  69464. tree.on("deselect_node.jstree", (e, data) => {
  69465. propertiesPanel.set(null);
  69466. });
  69467. tree.on("delete_node.jstree", (e, data) => {
  69468. propertiesPanel.set(null);
  69469. });
  69470. tree.on('dblclick','.jstree-anchor', (e) => {
  69471. let instance = $.jstree.reference(e.target);
  69472. let node = instance.get_node(e.target);
  69473. let object = node.data;
  69474. // ignore double click on checkbox
  69475. if(e.target.classList.contains("jstree-checkbox")){
  69476. return;
  69477. }
  69478. if(object instanceof PointCloudTree){
  69479. let box = this.viewer.getBoundingBox([object]);
  69480. let node = new Object3D();
  69481. node.boundingBox = box;
  69482. this.viewer.zoomTo(node, 1, 500);
  69483. }else if(object instanceof Measure){
  69484. let points = object.points.map(p => p.position);
  69485. let box = new Box3().setFromPoints(points);
  69486. if(box.getSize(new Vector3()).length() == 0){
  69487. box.min = box.max.clone();//禁止相同
  69488. box.expandByVector(new Vector3(1,1,1));
  69489. }
  69490. let node = new Object3D();
  69491. node.boundingBox = box;
  69492. this.viewer.zoomTo(node, 2, 500);
  69493. }else if(object instanceof Profile){
  69494. let points = object.points;
  69495. let box = new Box3().setFromPoints(points);
  69496. if(box.getSize(new Vector3()).length() > 0){
  69497. let node = new Object3D();
  69498. node.boundingBox = box;
  69499. this.viewer.zoomTo(node, 1, 500);
  69500. }
  69501. }else if(object instanceof Volume){
  69502. let box = object.boundingBox.clone().applyMatrix4(object.matrixWorld);
  69503. if(box.getSize(new Vector3()).length() > 0){
  69504. let node = new Object3D();
  69505. node.boundingBox = box;
  69506. this.viewer.zoomTo(node, 1, 500);
  69507. }
  69508. }else if(object instanceof Annotation){
  69509. object.moveHere(this.viewer.scene.getActiveCamera());
  69510. }else if(object instanceof PolygonClipVolume){
  69511. let dir = object.camera.getWorldDirection(new Vector3());
  69512. let target;
  69513. if(object.camera instanceof OrthographicCamera){
  69514. dir.multiplyScalar(object.camera.right);
  69515. target = new Vector3().addVectors(object.camera.position, dir);
  69516. this.viewer.setCameraMode(CameraMode.ORTHOGRAPHIC);
  69517. }else if(object.camera instanceof PerspectiveCamera){
  69518. dir.multiplyScalar(this.viewer.scene.view.radius);
  69519. target = new Vector3().addVectors(object.camera.position, dir);
  69520. this.viewer.setCameraMode(CameraMode.PERSPECTIVE);
  69521. }
  69522. this.viewer.scene.view.position.copy(object.camera.position);
  69523. this.viewer.scene.view.lookAt(target);
  69524. }else if(object.type === "SpotLight"){
  69525. let distance = (object.distance > 0) ? object.distance / 4 : 5 * 1000;
  69526. let position = object.position;
  69527. let target = new Vector3().addVectors(
  69528. position,
  69529. object.getWorldDirection(new Vector3()).multiplyScalar(distance));
  69530. this.viewer.scene.view.position.copy(object.position);
  69531. this.viewer.scene.view.lookAt(target);
  69532. }else if(object instanceof Object3D){
  69533. let box = new Box3().setFromObject(object);
  69534. if(box.getSize(new Vector3()).length() > 0){
  69535. let node = new Object3D();
  69536. node.boundingBox = box;
  69537. this.viewer.zoomTo(node, 1, 500);
  69538. }
  69539. }else if(object instanceof OrientedImage){
  69540. // TODO zoom to images
  69541. // let box = new THREE.Box3().setFromObject(object);
  69542. // if(box.getSize(new THREE.Vector3()).length() > 0){
  69543. // let node = new THREE.Object3D();
  69544. // node.boundingBox = box;
  69545. // this.viewer.zoomTo(node, 1, 500);
  69546. // }
  69547. }else if(object instanceof Images360){
  69548. // TODO
  69549. }else if(object instanceof Geopackage){
  69550. // TODO
  69551. }
  69552. });
  69553. tree.on("uncheck_node.jstree", (e, data) => {
  69554. let object = data.node.data;
  69555. if(object){
  69556. object.visible = false;
  69557. }
  69558. });
  69559. tree.on("check_node.jstree", (e, data) => {
  69560. let object = data.node.data;
  69561. if(object){
  69562. object.visible = true;
  69563. }
  69564. });
  69565. let onPointCloudAdded = (e) => {
  69566. let pointcloud = e.pointcloud;
  69567. let cloudIcon = `${Potree.resourcePath}/icons/cloud.svg`;
  69568. let node = createNode(pcID, pointcloud.name, cloudIcon, pointcloud);
  69569. pointcloud.addEventListener("visibility_changed", () => {
  69570. if(pointcloud.visible){
  69571. tree.jstree('check_node', node);
  69572. }else {
  69573. tree.jstree('uncheck_node', node);
  69574. }
  69575. });
  69576. };
  69577. let onMeasurementAdded = (e) => {
  69578. let measurement = e.measurement;
  69579. let icon = Utils.getMeasurementIcon(measurement);
  69580. createNode(measurementID, measurement.name, icon, measurement);
  69581. };
  69582. let onVolumeAdded = (e) => {
  69583. let volume = e.volume;
  69584. let icon = Utils.getMeasurementIcon(volume);
  69585. let node = createNode(measurementID, volume.name, icon, volume);
  69586. volume.addEventListener("visibility_changed", () => {
  69587. if(volume.visible){
  69588. tree.jstree('check_node', node);
  69589. }else {
  69590. tree.jstree('uncheck_node', node);
  69591. }
  69592. });
  69593. };
  69594. let onProfileAdded = (e) => {
  69595. let profile = e.profile;
  69596. let icon = Utils.getMeasurementIcon(profile);
  69597. createNode(measurementID, profile.name, icon, profile);
  69598. };
  69599. let onAnnotationAdded = (e) => {
  69600. let annotation = e.annotation;
  69601. let annotationIcon = `${Potree.resourcePath}/icons/annotation.svg`;
  69602. let parentID = this.annotationMapping.get(annotation.parent);
  69603. let annotationID = createNode(parentID, annotation.title, annotationIcon, annotation);
  69604. this.annotationMapping.set(annotation, annotationID);
  69605. annotation.addEventListener("annotation_changed", (e) => {
  69606. let annotationsRoot = $("#jstree_scene").jstree().get_json("annotations");
  69607. let jsonNode = annotationsRoot.children.find(child => child.data.uuid === annotation.uuid);
  69608. $.jstree.reference(jsonNode.id).rename_node(jsonNode.id, annotation.title);
  69609. });
  69610. };
  69611. let onCameraAnimationAdded = (e) => {
  69612. const animation = e.animation;
  69613. const animationIcon = `${Potree.resourcePath}/icons/camera_animation.svg`;
  69614. createNode(otherID, "animation", animationIcon, animation);
  69615. };
  69616. let onOrientedImagesAdded = (e) => {
  69617. const images = e.images;
  69618. const imagesIcon = `${Potree.resourcePath}/icons/picture.svg`;
  69619. const node = createNode(imagesID, "images", imagesIcon, images);
  69620. images.addEventListener("visibility_changed", () => {
  69621. if(images.visible){
  69622. tree.jstree('check_node', node);
  69623. }else {
  69624. tree.jstree('uncheck_node', node);
  69625. }
  69626. });
  69627. };
  69628. let onImages360Added = (e) => {
  69629. const images = e.images;
  69630. const imagesIcon = `${Potree.resourcePath}/icons/picture.svg`;
  69631. const node = createNode(imagesID, "360° images", imagesIcon, images);
  69632. images.addEventListener("visibility_changed", () => {
  69633. if(images.visible){
  69634. tree.jstree('check_node', node);
  69635. }else {
  69636. tree.jstree('uncheck_node', node);
  69637. }
  69638. });
  69639. };
  69640. const onGeopackageAdded = (e) => {
  69641. const geopackage = e.geopackage;
  69642. const geopackageIcon = `${Potree.resourcePath}/icons/triangle.svg`;
  69643. const tree = $(`#jstree_scene`);
  69644. const parentNode = "vectors";
  69645. for(const layer of geopackage.node.children){
  69646. const name = layer.name;
  69647. let shpPointsID = tree.jstree('create_node', parentNode, {
  69648. "text": name,
  69649. "icon": geopackageIcon,
  69650. "object": layer,
  69651. "data": layer,
  69652. },
  69653. "last", false, false);
  69654. tree.jstree(layer.visible ? "check_node" : "uncheck_node", shpPointsID);
  69655. }
  69656. };
  69657. this.viewer.scene.addEventListener("pointcloud_added", onPointCloudAdded);
  69658. this.viewer.scene.addEventListener("measurement_added", onMeasurementAdded);
  69659. this.viewer.scene.addEventListener("profile_added", onProfileAdded);
  69660. this.viewer.scene.addEventListener("volume_added", onVolumeAdded);
  69661. this.viewer.scene.addEventListener("camera_animation_added", onCameraAnimationAdded);
  69662. this.viewer.scene.addEventListener("oriented_images_added", onOrientedImagesAdded);
  69663. this.viewer.scene.addEventListener("360_images_added", onImages360Added);
  69664. this.viewer.scene.addEventListener("geopackage_added", onGeopackageAdded);
  69665. this.viewer.scene.addEventListener("polygon_clip_volume_added", onVolumeAdded);
  69666. this.viewer.scene.annotations.addEventListener("annotation_added", onAnnotationAdded);
  69667. let onMeasurementRemoved = (e) => {
  69668. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69669. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.measurement.uuid);
  69670. tree.jstree("delete_node", jsonNode.id);
  69671. };
  69672. let onVolumeRemoved = (e) => {
  69673. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69674. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.volume.uuid);
  69675. tree.jstree("delete_node", jsonNode.id);
  69676. };
  69677. let onPolygonClipVolumeRemoved = (e) => {
  69678. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69679. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.volume.uuid);
  69680. tree.jstree("delete_node", jsonNode.id);
  69681. };
  69682. let onProfileRemoved = (e) => {
  69683. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69684. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.profile.uuid);
  69685. tree.jstree("delete_node", jsonNode.id);
  69686. };
  69687. this.viewer.scene.addEventListener("measurement_removed", onMeasurementRemoved);
  69688. this.viewer.scene.addEventListener("volume_removed", onVolumeRemoved);
  69689. this.viewer.scene.addEventListener("polygon_clip_volume_removed", onPolygonClipVolumeRemoved);
  69690. this.viewer.scene.addEventListener("profile_removed", onProfileRemoved);
  69691. {
  69692. let annotationIcon = `${Potree.resourcePath}/icons/annotation.svg`;
  69693. this.annotationMapping = new Map();
  69694. this.annotationMapping.set(this.viewer.scene.annotations, annotationsID);
  69695. this.viewer.scene.annotations.traverseDescendants(annotation => {
  69696. let parentID = this.annotationMapping.get(annotation.parent);
  69697. let annotationID = createNode(parentID, annotation.title, annotationIcon, annotation);
  69698. this.annotationMapping.set(annotation, annotationID);
  69699. });
  69700. }
  69701. const scene = this.viewer.scene;
  69702. for(let pointcloud of scene.pointclouds){
  69703. onPointCloudAdded({pointcloud: pointcloud});
  69704. }
  69705. for(let measurement of scene.measurements){
  69706. onMeasurementAdded({measurement: measurement});
  69707. }
  69708. for(let volume of [...scene.volumes, ...scene.polygonClipVolumes]){
  69709. onVolumeAdded({volume: volume});
  69710. }
  69711. for(let animation of scene.cameraAnimations){
  69712. onCameraAnimationAdded({animation: animation});
  69713. }
  69714. for(let images of scene.orientedImages){
  69715. onOrientedImagesAdded({images: images});
  69716. }
  69717. for(let images of scene.images360){
  69718. onImages360Added({images: images});
  69719. }
  69720. for(const geopackage of scene.geopackages){
  69721. onGeopackageAdded({geopackage: geopackage});
  69722. }
  69723. for(let profile of scene.profiles){
  69724. onProfileAdded({profile: profile});
  69725. }
  69726. {
  69727. createNode(otherID, "Camera", null, new Camera());
  69728. }
  69729. this.viewer.addEventListener("scene_changed", (e) => {
  69730. propertiesPanel.setScene(e.scene);
  69731. e.oldScene.removeEventListener("pointcloud_added", onPointCloudAdded);
  69732. e.oldScene.removeEventListener("measurement_added", onMeasurementAdded);
  69733. e.oldScene.removeEventListener("profile_added", onProfileAdded);
  69734. e.oldScene.removeEventListener("volume_added", onVolumeAdded);
  69735. e.oldScene.removeEventListener("polygon_clip_volume_added", onVolumeAdded);
  69736. e.oldScene.removeEventListener("measurement_removed", onMeasurementRemoved);
  69737. e.scene.addEventListener("pointcloud_added", onPointCloudAdded);
  69738. e.scene.addEventListener("measurement_added", onMeasurementAdded);
  69739. e.scene.addEventListener("profile_added", onProfileAdded);
  69740. e.scene.addEventListener("volume_added", onVolumeAdded);
  69741. e.scene.addEventListener("polygon_clip_volume_added", onVolumeAdded);
  69742. e.scene.addEventListener("measurement_removed", onMeasurementRemoved);
  69743. });
  69744. }
  69745. initClippingTool(){
  69746. this.viewer.addEventListener("cliptask_changed", (event) => {
  69747. console.log("TODO");
  69748. });
  69749. this.viewer.addEventListener("clipmethod_changed", (event) => {
  69750. console.log("TODO");
  69751. });
  69752. {
  69753. let elClipTask = $("#cliptask_options");
  69754. elClipTask.selectgroup({title: "Clip Task"});
  69755. elClipTask.find("input").click( (e) => {
  69756. this.viewer.setClipTask(ClipTask[e.target.value]);
  69757. });
  69758. let currentClipTask = Object.keys(ClipTask)
  69759. .filter(key => ClipTask[key] === this.viewer.clipTask);
  69760. elClipTask.find(`input[value=${currentClipTask}]`).trigger("click");
  69761. }
  69762. {
  69763. let elClipMethod = $("#clipmethod_options");
  69764. elClipMethod.selectgroup({title: "Clip Method"});
  69765. elClipMethod.find("input").click( (e) => {
  69766. this.viewer.setClipMethod(ClipMethod[e.target.value]);
  69767. });
  69768. let currentClipMethod = Object.keys(ClipMethod)
  69769. .filter(key => ClipMethod[key] === this.viewer.clipMethod);
  69770. elClipMethod.find(`input[value=${currentClipMethod}]`).trigger("click");
  69771. }
  69772. let clippingToolBar = $("#clipping_tools");
  69773. // CLIP VOLUME
  69774. clippingToolBar.append(this.createToolIcon(
  69775. Potree.resourcePath + '/icons/clip_volume.svg',
  69776. '[title]tt.clip_volume',
  69777. () => {
  69778. let item = this.volumeTool.startInsertion({clip: true});
  69779. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69780. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === item.uuid);
  69781. $.jstree.reference(jsonNode.id).deselect_all();
  69782. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69783. }
  69784. ));
  69785. // CLIP POLYGON
  69786. clippingToolBar.append(this.createToolIcon(
  69787. Potree.resourcePath + "/icons/clip-polygon.svg",
  69788. "[title]tt.clip_polygon",
  69789. () => {
  69790. let item = this.viewer.clippingTool.startInsertion({type: "polygon"});
  69791. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69792. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === item.uuid);
  69793. $.jstree.reference(jsonNode.id).deselect_all();
  69794. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69795. }
  69796. ));
  69797. {// SCREEN BOX SELECT
  69798. let boxSelectTool = new ScreenBoxSelectTool(this.viewer);
  69799. clippingToolBar.append(this.createToolIcon(
  69800. Potree.resourcePath + "/icons/clip-screen.svg",
  69801. "[title]tt.screen_clip_box",
  69802. () => {
  69803. if(!(this.viewer.scene.getActiveCamera() instanceof OrthographicCamera)){
  69804. this.viewer.postMessage(`Switch to Orthographic Camera Mode before using the Screen-Box-Select tool.`,
  69805. {duration: 2000});
  69806. return;
  69807. }
  69808. let item = boxSelectTool.startInsertion();
  69809. let measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  69810. let jsonNode = measurementsRoot.children.find(child => child.data.uuid === item.uuid);
  69811. $.jstree.reference(jsonNode.id).deselect_all();
  69812. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  69813. }
  69814. ));
  69815. }
  69816. { // REMOVE CLIPPING TOOLS
  69817. clippingToolBar.append(this.createToolIcon(
  69818. Potree.resourcePath + "/icons/remove.svg",
  69819. "[title]tt.remove_all_clipping_volumes",
  69820. () => {
  69821. this.viewer.scene.removeAllClipVolumes();
  69822. }
  69823. ));
  69824. }
  69825. }
  69826. initFilters(){
  69827. this.initClassificationList();
  69828. this.initReturnFilters();
  69829. this.initGPSTimeFilters();
  69830. this.initPointSourceIDFilters();
  69831. }
  69832. initReturnFilters(){
  69833. let elReturnFilterPanel = $('#return_filter_panel');
  69834. { // RETURN NUMBER
  69835. let sldReturnNumber = elReturnFilterPanel.find('#sldReturnNumber');
  69836. let lblReturnNumber = elReturnFilterPanel.find('#lblReturnNumber');
  69837. sldReturnNumber.slider({
  69838. range: true,
  69839. min: 0, max: 7, step: 1,
  69840. values: [0, 7],
  69841. slide: (event, ui) => {
  69842. this.viewer.setFilterReturnNumberRange(ui.values[0], ui.values[1]);
  69843. }
  69844. });
  69845. let onReturnNumberChanged = (event) => {
  69846. let [from, to] = this.viewer.filterReturnNumberRange;
  69847. lblReturnNumber[0].innerHTML = `${from} to ${to}`;
  69848. sldReturnNumber.slider({values: [from, to]});
  69849. };
  69850. this.viewer.addEventListener('filter_return_number_range_changed', onReturnNumberChanged);
  69851. onReturnNumberChanged();
  69852. }
  69853. { // NUMBER OF RETURNS
  69854. let sldNumberOfReturns = elReturnFilterPanel.find('#sldNumberOfReturns');
  69855. let lblNumberOfReturns = elReturnFilterPanel.find('#lblNumberOfReturns');
  69856. sldNumberOfReturns.slider({
  69857. range: true,
  69858. min: 0, max: 7, step: 1,
  69859. values: [0, 7],
  69860. slide: (event, ui) => {
  69861. this.viewer.setFilterNumberOfReturnsRange(ui.values[0], ui.values[1]);
  69862. }
  69863. });
  69864. let onNumberOfReturnsChanged = (event) => {
  69865. let [from, to] = this.viewer.filterNumberOfReturnsRange;
  69866. lblNumberOfReturns[0].innerHTML = `${from} to ${to}`;
  69867. sldNumberOfReturns.slider({values: [from, to]});
  69868. };
  69869. this.viewer.addEventListener('filter_number_of_returns_range_changed', onNumberOfReturnsChanged);
  69870. onNumberOfReturnsChanged();
  69871. }
  69872. }
  69873. initGPSTimeFilters(){
  69874. let elGPSTimeFilterPanel = $('#gpstime_filter_panel');
  69875. {
  69876. let slider = new HierarchicalSlider({
  69877. levels: 4,
  69878. slide: (event) => {
  69879. this.viewer.setFilterGPSTimeRange(...event.values);
  69880. },
  69881. });
  69882. let initialized = false;
  69883. let initialize = () => {
  69884. let elRangeContainer = $("#gpstime_multilevel_range_container");
  69885. elRangeContainer[0].prepend(slider.element);
  69886. let extent = this.viewer.getGpsTimeExtent();
  69887. slider.setRange(extent);
  69888. slider.setValues(extent);
  69889. initialized = true;
  69890. };
  69891. this.viewer.addEventListener("update", (e) => {
  69892. let extent = this.viewer.getGpsTimeExtent();
  69893. let gpsTimeAvailable = extent[0] !== Infinity;
  69894. if(!initialized && gpsTimeAvailable){
  69895. initialize();
  69896. }
  69897. slider.setRange(extent);
  69898. });
  69899. }
  69900. {
  69901. const txtGpsTime = elGPSTimeFilterPanel.find("#txtGpsTime");
  69902. const btnFindGpsTime = elGPSTimeFilterPanel.find("#btnFindGpsTime");
  69903. let targetTime = null;
  69904. txtGpsTime.on("input", (e) => {
  69905. const str = txtGpsTime.val();
  69906. if(!isNaN(str)){
  69907. const value = parseFloat(str);
  69908. targetTime = value;
  69909. txtGpsTime.css("background-color", "");
  69910. }else {
  69911. targetTime = null;
  69912. txtGpsTime.css("background-color", "#ff9999");
  69913. }
  69914. });
  69915. btnFindGpsTime.click( () => {
  69916. if(targetTime !== null){
  69917. viewer.moveToGpsTimeVicinity(targetTime);
  69918. }
  69919. });
  69920. }
  69921. }
  69922. initPointSourceIDFilters() {
  69923. let elPointSourceIDFilterPanel = $('#pointsourceid_filter_panel');
  69924. {
  69925. let slider = new HierarchicalSlider({
  69926. levels: 4,
  69927. range: [0, 65535],
  69928. precision: 1,
  69929. slide: (event) => {
  69930. let values = event.values;
  69931. this.viewer.setFilterPointSourceIDRange(values[0], values[1]);
  69932. }
  69933. });
  69934. let initialized = false;
  69935. let initialize = () => {
  69936. elPointSourceIDFilterPanel[0].prepend(slider.element);
  69937. initialized = true;
  69938. };
  69939. this.viewer.addEventListener("update", (e) => {
  69940. let extent = this.viewer.filterPointSourceIDRange;
  69941. if(!initialized){
  69942. initialize();
  69943. slider.setValues(extent);
  69944. }
  69945. });
  69946. }
  69947. // let lblPointSourceID = elPointSourceIDFilterPanel.find("#lblPointSourceID");
  69948. // let elPointSourceID = elPointSourceIDFilterPanel.find("#spnPointSourceID");
  69949. // let slider = new ZoomableSlider();
  69950. // elPointSourceID[0].appendChild(slider.element);
  69951. // slider.update();
  69952. // slider.change( () => {
  69953. // let range = slider.chosenRange;
  69954. // this.viewer.setFilterPointSourceIDRange(range[0], range[1]);
  69955. // });
  69956. // let onPointSourceIDExtentChanged = (event) => {
  69957. // let range = this.viewer.filterPointSourceIDExtent;
  69958. // slider.setVisibleRange(range);
  69959. // };
  69960. // let onPointSourceIDChanged = (event) => {
  69961. // let range = this.viewer.filterPointSourceIDRange;
  69962. // let precision = 1;
  69963. // let from = `${Utils.addCommas(range[0].toFixed(precision))}`;
  69964. // let to = `${Utils.addCommas(range[1].toFixed(precision))}`;
  69965. // lblPointSourceID[0].innerHTML = `${from} to ${to}`;
  69966. // slider.setRange(range);
  69967. // };
  69968. // this.viewer.addEventListener('filter_point_source_id_range_changed', onPointSourceIDChanged);
  69969. // this.viewer.addEventListener('filter_point_source_id_extent_changed', onPointSourceIDExtentChanged);
  69970. }
  69971. initClassificationList(){
  69972. let elClassificationList = $('#classificationList');
  69973. let addClassificationItem = (code, name) => {
  69974. const classification = this.viewer.classifications[code];
  69975. const inputID = 'chkClassification_' + code;
  69976. const colorPickerID = 'colorPickerClassification_' + code;
  69977. const checked = classification.visible ? "checked" : "";
  69978. let element = $(`
  69979. <li>
  69980. <label style="whitespace: nowrap; display: flex">
  69981. <input id="${inputID}" type="checkbox" ${checked}/>
  69982. <span style="flex-grow: 1">${name}</span>
  69983. <input id="${colorPickerID}" style="zoom: 0.5" />
  69984. </label>
  69985. </li>
  69986. `);
  69987. const elInput = element.find('input');
  69988. const elColorPicker = element.find(`#${colorPickerID}`);
  69989. elInput.click(event => {
  69990. this.viewer.setClassificationVisibility(code, event.target.checked);
  69991. });
  69992. let defaultColor = classification.color.map(c => c * 255).join(", ");
  69993. defaultColor = `rgb(${defaultColor})`;
  69994. elColorPicker.spectrum({
  69995. // flat: true,
  69996. color: defaultColor,
  69997. showInput: true,
  69998. preferredFormat: 'rgb',
  69999. cancelText: '',
  70000. chooseText: 'Apply',
  70001. move: color => {
  70002. let rgb = color.toRgb();
  70003. const c = [rgb.r / 255, rgb.g / 255, rgb.b / 255, 1];
  70004. classification.color = c;
  70005. },
  70006. change: color => {
  70007. let rgb = color.toRgb();
  70008. const c = [rgb.r / 255, rgb.g / 255, rgb.b / 255, 1];
  70009. classification.color = c;
  70010. }
  70011. });
  70012. elClassificationList.append(element);
  70013. };
  70014. const addToggleAllButton = () => { // toggle all button
  70015. const element = $(`
  70016. <li>
  70017. <label style="whitespace: nowrap">
  70018. <input id="toggleClassificationFilters" type="checkbox" checked/>
  70019. <span>show/hide all</span>
  70020. </label>
  70021. </li>
  70022. `);
  70023. let elInput = element.find('input');
  70024. elInput.click(event => {
  70025. this.viewer.toggleAllClassificationsVisibility();
  70026. });
  70027. elClassificationList.append(element);
  70028. };
  70029. const addInvertButton = () => {
  70030. const element = $(`
  70031. <li>
  70032. <input type="button" value="invert" />
  70033. </li>
  70034. `);
  70035. let elInput = element.find('input');
  70036. elInput.click( () => {
  70037. const classifications = this.viewer.classifications;
  70038. for(let key of Object.keys(classifications)){
  70039. let value = classifications[key];
  70040. this.viewer.setClassificationVisibility(key, !value.visible);
  70041. }
  70042. });
  70043. elClassificationList.append(element);
  70044. };
  70045. const populate = () => {
  70046. addToggleAllButton();
  70047. for (let classID in this.viewer.classifications) {
  70048. addClassificationItem(classID, this.viewer.classifications[classID].name);
  70049. }
  70050. addInvertButton();
  70051. };
  70052. populate();
  70053. this.viewer.addEventListener("classifications_changed", () => {
  70054. elClassificationList.empty();
  70055. populate();
  70056. });
  70057. this.viewer.addEventListener("classification_visibility_changed", () => {
  70058. { // set checked state of classification buttons
  70059. for(const classID of Object.keys(this.viewer.classifications)){
  70060. const classValue = this.viewer.classifications[classID];
  70061. let elItem = elClassificationList.find(`#chkClassification_${classID}`);
  70062. elItem.prop("checked", classValue.visible);
  70063. }
  70064. }
  70065. { // set checked state of toggle button based on state of all other buttons
  70066. let numVisible = 0;
  70067. let numItems = 0;
  70068. for(const key of Object.keys(this.viewer.classifications)){
  70069. if(this.viewer.classifications[key].visible){
  70070. numVisible++;
  70071. }
  70072. numItems++;
  70073. }
  70074. const allVisible = numVisible === numItems;
  70075. let elToggle = elClassificationList.find("#toggleClassificationFilters");
  70076. elToggle.prop("checked", allVisible);
  70077. }
  70078. });
  70079. }
  70080. initAccordion(){
  70081. $('.accordion > h3').each(function(){
  70082. let header = $(this);
  70083. let content = $(this).next();
  70084. //header.addClass('accordion-header ui-widget');
  70085. //content.addClass('accordion-content ui-widget');
  70086. content.hide();
  70087. header.click(() => {
  70088. content.slideToggle();
  70089. });
  70090. });
  70091. let languages = [
  70092. ["EN", "en"],
  70093. ["FR", "fr"],
  70094. ["DE", "de"],
  70095. ["JP", "jp"],
  70096. ["ES", "es"],
  70097. ["SE", "se"],
  70098. ["ZH", "zh"]
  70099. ];
  70100. let elLanguages = $('#potree_languages');
  70101. for(let i = 0; i < languages.length; i++){
  70102. let [key, value] = languages[i];
  70103. let element = $(`<a>${key}</a>`);
  70104. element.click(() => this.viewer.setLanguage(value));
  70105. if(i === 0){
  70106. element.css("margin-left", "30px");
  70107. }
  70108. elLanguages.append(element);
  70109. if(i < languages.length - 1){
  70110. elLanguages.append($(document.createTextNode(' - ')));
  70111. }
  70112. }
  70113. // to close all, call
  70114. // $(".accordion > div").hide()
  70115. // to open the, for example, tool menu, call:
  70116. // $("#menu_tools").next().show()
  70117. }
  70118. initAppearance(){
  70119. const sldPointBudget = this.dom.find('#sldPointBudget');
  70120. sldPointBudget.slider({
  70121. value: this.viewer.getPointBudget(),
  70122. min: 100 * 1000,
  70123. max: 10 * 1000 * 1000,
  70124. step: 1000,
  70125. slide: (event, ui) => { this.viewer.setPointBudget(ui.value); }
  70126. });
  70127. this.dom.find('#sldFOV').slider({
  70128. value: this.viewer.getFOV(),
  70129. min: 20,
  70130. max: 100,
  70131. step: 1,
  70132. slide: (event, ui) => { this.viewer.setFOV(ui.value); }
  70133. });
  70134. $('#sldEDLRadius').slider({
  70135. value: this.viewer.getEDLRadius(),
  70136. min: 1,
  70137. max: 4,
  70138. step: 0.01,
  70139. slide: (event, ui) => { this.viewer.setEDLRadius(ui.value); }
  70140. });
  70141. $('#sldEDLStrength').slider({
  70142. value: this.viewer.getEDLStrength(),
  70143. min: 0,
  70144. max: 5,
  70145. step: 0.01,
  70146. slide: (event, ui) => { this.viewer.setEDLStrength(ui.value); }
  70147. });
  70148. $('#sldEDLOpacity').slider({
  70149. value: this.viewer.getEDLOpacity(),
  70150. min: 0,
  70151. max: 1,
  70152. step: 0.01,
  70153. slide: (event, ui) => { this.viewer.setEDLOpacity(ui.value); }
  70154. });
  70155. this.viewer.addEventListener('point_budget_changed', (event) => {
  70156. $('#lblPointBudget')[0].innerHTML = Utils.addCommas(this.viewer.getPointBudget());
  70157. sldPointBudget.slider({value: this.viewer.getPointBudget()});
  70158. });
  70159. this.viewer.addEventListener('fov_changed', (event) => {
  70160. $('#lblFOV')[0].innerHTML = parseInt(this.viewer.getFOV());
  70161. $('#sldFOV').slider({value: this.viewer.getFOV()});
  70162. });
  70163. this.viewer.addEventListener('use_edl_changed', (event) => {
  70164. $('#chkEDLEnabled')[0].checked = this.viewer.getEDLEnabled();
  70165. });
  70166. this.viewer.addEventListener('edl_radius_changed', (event) => {
  70167. $('#lblEDLRadius')[0].innerHTML = this.viewer.getEDLRadius().toFixed(1);
  70168. $('#sldEDLRadius').slider({value: this.viewer.getEDLRadius()});
  70169. });
  70170. this.viewer.addEventListener('edl_strength_changed', (event) => {
  70171. $('#lblEDLStrength')[0].innerHTML = this.viewer.getEDLStrength().toFixed(1);
  70172. $('#sldEDLStrength').slider({value: this.viewer.getEDLStrength()});
  70173. });
  70174. this.viewer.addEventListener('background_changed', (event) => {
  70175. $("input[name=background][value='" + this.viewer.getBackground() + "']").prop('checked', true);
  70176. });
  70177. $('#lblPointBudget')[0].innerHTML = Utils.addCommas(this.viewer.getPointBudget());
  70178. $('#lblFOV')[0].innerHTML = parseInt(this.viewer.getFOV());
  70179. $('#lblEDLRadius')[0].innerHTML = this.viewer.getEDLRadius().toFixed(1);
  70180. $('#lblEDLStrength')[0].innerHTML = this.viewer.getEDLStrength().toFixed(1);
  70181. $('#chkEDLEnabled')[0].checked = this.viewer.getEDLEnabled();
  70182. {
  70183. let elBackground = $(`#background_options`);
  70184. elBackground.selectgroup();
  70185. elBackground.find("input").click( (e) => {
  70186. this.viewer.setBackground(e.target.value);
  70187. });
  70188. let currentBackground = this.viewer.getBackground();
  70189. try{
  70190. $(`input[name=background_options][value=${currentBackground}]`).trigger("click");
  70191. }catch(e){}
  70192. }
  70193. $('#chkEDLEnabled').click( () => {
  70194. this.viewer.setEDLEnabled($('#chkEDLEnabled').prop("checked"));
  70195. });
  70196. }
  70197. initNavigation(){
  70198. let elNavigation = $('#navigation');
  70199. let sldMoveSpeed = $('#sldMoveSpeed');
  70200. let lblMoveSpeed = $('#lblMoveSpeed');
  70201. elNavigation.append(this.createToolIcon(
  70202. Potree.resourcePath + '/icons/earth_controls_1.png',
  70203. '[title]tt.earth_control',
  70204. () => { this.viewer.setControls(this.viewer.earthControls); }
  70205. ));
  70206. elNavigation.append(this.createToolIcon(
  70207. Potree.resourcePath + '/icons/fps_controls.svg',
  70208. '[title]tt.flight_control',
  70209. () => {
  70210. this.viewer.setControls(this.viewer.fpControls);
  70211. this.viewer.fpControls.lockElevation = false;
  70212. }
  70213. ));
  70214. elNavigation.append(this.createToolIcon(
  70215. Potree.resourcePath + '/icons/helicopter_controls.svg',
  70216. '[title]tt.heli_control',
  70217. () => {
  70218. this.viewer.setControls(this.viewer.fpControls);
  70219. this.viewer.fpControls.lockElevation = true;
  70220. }
  70221. ));
  70222. elNavigation.append(this.createToolIcon(
  70223. Potree.resourcePath + '/icons/orbit_controls.svg',
  70224. '[title]tt.orbit_control',
  70225. () => { this.viewer.setControls(this.viewer.orbitControls); }
  70226. ));
  70227. elNavigation.append(this.createToolIcon(
  70228. Potree.resourcePath + '/icons/focus.svg',
  70229. '[title]tt.focus_control',
  70230. () => { this.viewer.fitToScreen(); }
  70231. ));
  70232. elNavigation.append(this.createToolIcon(
  70233. Potree.resourcePath + "/icons/navigation_cube.svg",
  70234. "[title]tt.navigation_cube_control",
  70235. () => {this.viewer.toggleNavigationCube();}
  70236. ));
  70237. elNavigation.append(this.createToolIcon(
  70238. Potree.resourcePath + "/images/compas.svg",
  70239. "[title]tt.compass",
  70240. () => {
  70241. const visible = !this.viewer.compass.isVisible();
  70242. this.viewer.compass.setVisible(visible);
  70243. }
  70244. ));
  70245. elNavigation.append(this.createToolIcon(
  70246. Potree.resourcePath + "/icons/camera_animation.svg",
  70247. "[title]tt.camera_animation",
  70248. () => {
  70249. const animation = CameraAnimation.defaultFromView(this.viewer);
  70250. viewer.scene.addCameraAnimation(animation);
  70251. }
  70252. ));
  70253. elNavigation.append("<br>");
  70254. elNavigation.append(this.createToolIcon(
  70255. Potree.resourcePath + "/icons/left.svg",
  70256. "[title]tt.left_view_control",
  70257. () => {this.viewer.setLeftView();}
  70258. ));
  70259. elNavigation.append(this.createToolIcon(
  70260. Potree.resourcePath + "/icons/right.svg",
  70261. "[title]tt.right_view_control",
  70262. () => {this.viewer.setRightView();}
  70263. ));
  70264. elNavigation.append(this.createToolIcon(
  70265. Potree.resourcePath + "/icons/front.svg",
  70266. "[title]tt.front_view_control",
  70267. () => {this.viewer.setFrontView();}
  70268. ));
  70269. elNavigation.append(this.createToolIcon(
  70270. Potree.resourcePath + "/icons/back.svg",
  70271. "[title]tt.back_view_control",
  70272. () => {this.viewer.setBackView();}
  70273. ));
  70274. elNavigation.append(this.createToolIcon(
  70275. Potree.resourcePath + "/icons/top.svg",
  70276. "[title]tt.top_view_control",
  70277. () => {this.viewer.setTopView();}
  70278. ));
  70279. elNavigation.append(this.createToolIcon(
  70280. Potree.resourcePath + "/icons/bottom.svg",
  70281. "[title]tt.bottom_view_control",
  70282. () => {this.viewer.setBottomView();}
  70283. ));
  70284. let elCameraProjection = $(`
  70285. <selectgroup id="camera_projection_options">
  70286. <option id="camera_projection_options_perspective" value="PERSPECTIVE">Perspective</option>
  70287. <option id="camera_projection_options_orthigraphic" value="ORTHOGRAPHIC">Orthographic</option>
  70288. </selectgroup>
  70289. `);
  70290. elNavigation.append(elCameraProjection);
  70291. elCameraProjection.selectgroup({title: "Camera Projection"});
  70292. elCameraProjection.find("input").click( (e) => {
  70293. this.viewer.setCameraMode(CameraMode[e.target.value]);
  70294. });
  70295. let cameraMode = Object.keys(CameraMode)
  70296. .filter(key => CameraMode[key] === this.viewer.scene.cameraMode);
  70297. elCameraProjection.find(`input[value=${cameraMode}]`).trigger("click");
  70298. let speedRange = new Vector2$1(1, 10 * 1000);
  70299. let toLinearSpeed = (value) => {
  70300. return Math.pow(value, 4) * speedRange.y + speedRange.x;
  70301. };
  70302. let toExpSpeed = (value) => {
  70303. return Math.pow((value - speedRange.x) / speedRange.y, 1 / 4);
  70304. };
  70305. sldMoveSpeed.slider({
  70306. value: toExpSpeed(this.viewer.getMoveSpeed()),
  70307. min: 0,
  70308. max: 1,
  70309. step: 0.01,
  70310. slide: (event, ui) => { this.viewer.setMoveSpeed(toLinearSpeed(ui.value)); }
  70311. });
  70312. this.viewer.addEventListener('move_speed_changed', (event) => {
  70313. lblMoveSpeed.html(this.viewer.getMoveSpeed().toFixed(1));
  70314. sldMoveSpeed.slider({value: toExpSpeed(this.viewer.getMoveSpeed())});
  70315. });
  70316. lblMoveSpeed.html(this.viewer.getMoveSpeed().toFixed(1));
  70317. }
  70318. initSettings(){
  70319. {
  70320. $('#sldMinNodeSize').slider({
  70321. value: this.viewer.getMinNodeSize(),
  70322. min: 0,
  70323. max: 1000,
  70324. step: 0.01,
  70325. slide: (event, ui) => { this.viewer.setMinNodeSize(ui.value); }
  70326. });
  70327. this.viewer.addEventListener('minnodesize_changed', (event) => {
  70328. $('#lblMinNodeSize').html(parseInt(this.viewer.getMinNodeSize()));
  70329. $('#sldMinNodeSize').slider({value: this.viewer.getMinNodeSize()});
  70330. });
  70331. $('#lblMinNodeSize').html(parseInt(this.viewer.getMinNodeSize()));
  70332. }
  70333. {
  70334. let elSplatQuality = $("#splat_quality_options");
  70335. elSplatQuality.selectgroup({title: "Splat Quality"});
  70336. elSplatQuality.find("input").click( (e) => {
  70337. if(e.target.value === "standard"){
  70338. this.viewer.useHQ = false;
  70339. }else if(e.target.value === "hq"){
  70340. this.viewer.useHQ = true;
  70341. }
  70342. });
  70343. let currentQuality = this.viewer.useHQ ? "hq" : "standard";
  70344. elSplatQuality.find(`input[value=${currentQuality}]`).trigger("click");
  70345. }
  70346. $('#show_bounding_box').click(() => {
  70347. this.viewer.setShowBoundingBox($('#show_bounding_box').prop("checked"));
  70348. });
  70349. $('#set_freeze').click(() => {
  70350. this.viewer.setFreeze($('#set_freeze').prop("checked"));
  70351. });
  70352. }
  70353. }
  70354. class AnnotationTool extends EventDispatcher{
  70355. constructor (viewer) {
  70356. super();
  70357. this.viewer = viewer;
  70358. this.renderer = viewer.renderer;
  70359. this.sg = new SphereGeometry(0.1);
  70360. this.sm = new MeshNormalMaterial();
  70361. this.s = new Mesh(this.sg, this.sm);
  70362. }
  70363. startInsertion (args = {}) {
  70364. let domElement = this.viewer.renderer.domElement;
  70365. let annotation = new Annotation({
  70366. position: [589748.270, 231444.540, 753.675],
  70367. title: "Annotation Title",
  70368. description: `Annotation Description`,
  70369. radius: 1,//add
  70370. cameraPosition: [589748.270, 231444.540, 753.675],//add
  70371. });
  70372. this.dispatchEvent({type: 'start_inserting_annotation', annotation: annotation});
  70373. const annotations = this.viewer.scene.annotations;
  70374. annotations.add(annotation);
  70375. let callbacks = {
  70376. cancel: null,
  70377. finish: null,
  70378. };
  70379. let insertionCallback = (e) => {
  70380. if (e.button === MOUSE.LEFT) {
  70381. callbacks.finish();
  70382. } else if (e.button === MOUSE.RIGHT) {
  70383. callbacks.cancel();
  70384. }
  70385. };
  70386. callbacks.cancel = e => {
  70387. annotations.remove(annotation);
  70388. domElement.removeEventListener('mouseup', insertionCallback, true);
  70389. };
  70390. callbacks.finish = e => {
  70391. domElement.removeEventListener('mouseup', insertionCallback, true);
  70392. };
  70393. domElement.addEventListener('mouseup', insertionCallback, true);
  70394. let drag = (e) => {
  70395. let camera = e.viewer.scene.getActiveCamera();
  70396. /* let I = Utils.getMousePointCloudIntersection(
  70397. e.drag.end,
  70398. camera,
  70399. e.viewer,
  70400. e.viewer.scene.pointclouds,
  70401. {pickClipped: true}); */
  70402. let I = e.viewer.inputHandler.intersectPoint;
  70403. if (I) {
  70404. this.s.position.copy(I.location);
  70405. annotation.position.copy(I.location);
  70406. annotation.cameraTarget.copy(I.location);//add
  70407. annotation.cameraPosition.copy(camera.position);//add
  70408. }
  70409. };
  70410. let drop = (e) => {
  70411. viewer.scene.scene.remove(this.s);
  70412. this.s.removeEventListener("drag", drag);
  70413. this.s.removeEventListener("drop", drop);
  70414. };
  70415. this.s.addEventListener('drag', drag);
  70416. this.s.addEventListener('drop', drop);
  70417. this.viewer.scene.scene.add(this.s);
  70418. this.viewer.inputHandler.startDragging(this.s);
  70419. return annotation;
  70420. }
  70421. update(){
  70422. // let camera = this.viewer.scene.getActiveCamera();
  70423. // let domElement = this.renderer.domElement;
  70424. // let measurements = this.viewer.scene.measurements;
  70425. // const renderAreaSize = this.renderer.getSize(new THREE.Vector2());
  70426. // let clientWidth = renderAreaSize.width;
  70427. // let clientHeight = renderAreaSize.height;
  70428. }
  70429. render(){
  70430. //this.viewer.renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  70431. }
  70432. };
  70433. const renderOrders = {
  70434. line: 0 ,
  70435. spot: 15, //高过模型
  70436. };
  70437. const planeGeo$3 = new PlaneGeometry(1,1);
  70438. let texLoader$5 = new TextureLoader();
  70439. let lineMat = new LineBasicMaterial({
  70440. color: '#ffffff',
  70441. });
  70442. let spotMat;
  70443. const defaultLineLength = 0.6;
  70444. const defaultSpotScale = 0.4;
  70445. class Tag extends Object3D{
  70446. constructor(o){
  70447. super();
  70448. this.lineLength = o.lineLength != void 0 ? o.lineLength : defaultLineLength;
  70449. this.position.copy(o.position);
  70450. this.normal = o.normal != void 0 ? o.normal : new Vector3(0,0,-1);
  70451. this.root = o.root;
  70452. //this.matrixAutoUpdate = false
  70453. this.build();
  70454. /* this.spot.addEventListener('mouseover',()=>{
  70455. }) */
  70456. }
  70457. build(){
  70458. if(!spotMat){
  70459. spotMat = new MeshBasicMaterial({
  70460. transparent:true,
  70461. map: texLoader$5.load(Potree.resourcePath+'/textures/spot_default.png' ),
  70462. });
  70463. }
  70464. let endPos = this.normal.clone().multiplyScalar(this.lineLength);
  70465. this.line = LineDraw.createLine([
  70466. new Vector3(0,0,0),
  70467. endPos
  70468. ], {mat:lineMat});
  70469. let group = new Object3D();
  70470. this.spot = new Mesh(planeGeo$3, spotMat);
  70471. this.spot.scale.set(defaultSpotScale,defaultSpotScale,defaultSpotScale);
  70472. this.titleLabel = new TextSprite({root: group, text:'1', sizeInfo:{width2d:200},
  70473. textColor:{r:255,g:255,b:255,a:1.0},
  70474. backgroundColor:{r:0,g:0,b:0,a:0.8},
  70475. borderRadius: 6,
  70476. fontsize:13, fontWeight:'',//thick
  70477. renderOrder : renderOrders.spot, pickOrder:renderOrders.spot,
  70478. }); //更新sprite时,实际更新的是root: spot的矩阵
  70479. this.spot.renderOrder = renderOrders.spot;
  70480. /* const mainLabelProp = {
  70481. backgroundColor: {r: defaultColor.r*255, g: defaultColor.g*255, b: defaultColor.b*255, a:config.measure.default.opacity},
  70482. textColor: {r: textColor.r*255, g: textColor.g*255, b: textColor.b*255, a: 1.0},
  70483. fontsize:16,
  70484. useDepth : true ,
  70485. renderOrder : 5, pickOrder:5,
  70486. } */
  70487. this.titleLabel.position.set(0,0.4,0);
  70488. this.titleLabel.sprite.material.depthTest = this.titleLabel.sprite.material.depthWrite = true;
  70489. group.position.copy(endPos);
  70490. group.add(this.spot);
  70491. group.add(this.titleLabel);
  70492. this.add(group);
  70493. this.add(this.line);
  70494. viewer.scene.tags.add(this);
  70495. }
  70496. updateMatrixWorld(force){ //重写,只为了将root当做parent
  70497. this.updateMatrix();
  70498. this.matrixWorld.multiplyMatrices( this.root.matrixWorld, this.matrix );
  70499. const children = this.children;
  70500. for ( let i = 0, l = children.length; i < l; i ++ ) {
  70501. children[ i ].updateMatrixWorld( force );
  70502. }
  70503. }
  70504. updateWorldMatrix( updateParents, updateChildren ) {//重写,只为了将root当做parent
  70505. if ( updateParents === true && this.root !== null ) {
  70506. this.root.updateWorldMatrix( true, false );
  70507. }
  70508. if ( this.matrixAutoUpdate ) this.updateMatrix();
  70509. this.matrixWorld.multiplyMatrices( this.root.matrixWorld, this.matrix );
  70510. if ( updateChildren === true ) {
  70511. const children = this.children;
  70512. for ( let i = 0, l = children.length; i < l; i ++ ) {
  70513. children[ i ].updateWorldMatrix( false, true );
  70514. }
  70515. }
  70516. }
  70517. }
  70518. class TagTool extends EventDispatcher{
  70519. constructor (viewer) {
  70520. super();
  70521. this.viewer = viewer;
  70522. this.viewer.addEventListener('start_inserting_tag', e => {
  70523. this.viewer.dispatchEvent({
  70524. type: 'cancel_insertions'
  70525. });
  70526. });
  70527. }
  70528. startInsertion (args = {}, callback, cancelFun) {
  70529. let deferred = $.Deferred();
  70530. this.viewer.dispatchEvent({
  70531. type: 'start_inserting_tag'
  70532. });
  70533. let cancel = ()=>{
  70534. end();
  70535. };
  70536. let end = ()=>{
  70537. this.viewer.removeEventListener('global_click', click);
  70538. };
  70539. let click = (e)=>{
  70540. var worldPos = e.intersect && (/* e.intersect.orthoIntersect || */e.intersect.location);
  70541. if(!worldPos){
  70542. return
  70543. }
  70544. let localPos = Potree.Utils.datasetPosTransform({ toDataset: true, pointcloud:e.intersect.pointcloud, object:e.intersect.object, position:worldPos });
  70545. let tag = new Tag({
  70546. title: '1', position: localPos, normal:e.intersect.normal,
  70547. root: e.intersect.pointcloud || e.intersect.object}
  70548. );
  70549. //pointcloud里加一个normal 的非float32
  70550. end();
  70551. e.consume && e.consume();
  70552. deferred.resolve(tag);
  70553. return {stopContinue:true}
  70554. };
  70555. this.viewer.addEventListener('global_click', click, 10);
  70556. return deferred.promise()
  70557. }
  70558. }
  70559. class NavigationCube extends Object3D {
  70560. constructor(viewer){
  70561. super();
  70562. this.viewer = viewer;
  70563. let createPlaneMaterial = (img) => {
  70564. let material = new MeshBasicMaterial( {
  70565. depthTest: true,
  70566. depthWrite: true,
  70567. side: DoubleSide
  70568. });
  70569. new TextureLoader().load(
  70570. exports.resourcePath + '/textures/navigation/' + img,
  70571. function(texture) {
  70572. texture.anisotropy = viewer.renderer.capabilities.getMaxAnisotropy();
  70573. material.map = texture;
  70574. material.needsUpdate = true;
  70575. });
  70576. return material;
  70577. };
  70578. let planeGeometry = new PlaneGeometry(1, 1);
  70579. this.front = new Mesh(planeGeometry, createPlaneMaterial('F.png'));
  70580. this.front.position.y = -0.5;
  70581. this.front.rotation.x = Math.PI / 2.0;
  70582. this.front.updateMatrixWorld();
  70583. this.front.name = "F";
  70584. this.add(this.front);
  70585. this.back = new Mesh(planeGeometry, createPlaneMaterial('B.png'));
  70586. this.back.position.y = 0.5;
  70587. this.back.rotation.x = Math.PI / 2.0;
  70588. this.back.updateMatrixWorld();
  70589. this.back.name = "B";
  70590. this.add(this.back);
  70591. this.left = new Mesh(planeGeometry, createPlaneMaterial('L.png'));
  70592. this.left.position.x = -0.5;
  70593. this.left.rotation.y = Math.PI / 2.0;
  70594. this.left.updateMatrixWorld();
  70595. this.left.name = "L";
  70596. this.add(this.left);
  70597. this.right = new Mesh(planeGeometry, createPlaneMaterial('R.png'));
  70598. this.right.position.x = 0.5;
  70599. this.right.rotation.y = Math.PI / 2.0;
  70600. this.right.updateMatrixWorld();
  70601. this.right.name = "R";
  70602. this.add(this.right);
  70603. this.bottom = new Mesh(planeGeometry, createPlaneMaterial('D.png'));
  70604. this.bottom.position.z = -0.5;
  70605. this.bottom.updateMatrixWorld();
  70606. this.bottom.name = "D";
  70607. this.add(this.bottom);
  70608. this.top = new Mesh(planeGeometry, createPlaneMaterial('U.png'));
  70609. this.top.position.z = 0.5;
  70610. this.top.updateMatrixWorld();
  70611. this.top.name = "U";
  70612. this.add(this.top);
  70613. this.width = 150; // in px
  70614. this.camera = new OrthographicCamera(-1, 1, 1, -1, -1, 1);
  70615. this.camera.position.copy(new Vector3(0, 0, 0));
  70616. this.camera.lookAt(new Vector3(0, 1, 0));
  70617. this.camera.updateMatrixWorld();
  70618. this.camera.rotation.order = "ZXY";
  70619. let onMouseDown = (event) => {
  70620. if (!this.visible) {
  70621. return;
  70622. }
  70623. this.pickedFace = null;
  70624. let mouse = new Vector2$1();
  70625. mouse.x = event.clientX - (window.innerWidth - this.width);
  70626. mouse.y = event.clientY;
  70627. if(mouse.x < 0 || mouse.y > this.width) return;
  70628. mouse.x = (mouse.x / this.width) * 2 - 1;
  70629. mouse.y = -(mouse.y / this.width) * 2 + 1;
  70630. let raycaster = new Raycaster();
  70631. raycaster.setFromCamera(mouse, this.camera);
  70632. raycaster.ray.origin.sub(this.camera.getWorldDirection(new Vector3()));
  70633. let intersects = raycaster.intersectObjects(this.children);
  70634. let minDistance = 1000;
  70635. for (let i = 0; i < intersects.length; i++) {
  70636. if(intersects[i].distance < minDistance) {
  70637. this.pickedFace = intersects[i].object.name;
  70638. minDistance = intersects[i].distance;
  70639. }
  70640. }
  70641. if(this.pickedFace) {
  70642. this.viewer.setView(this.pickedFace);
  70643. }
  70644. };
  70645. this.viewer.renderer.domElement.addEventListener('mousedown', onMouseDown, false);
  70646. }
  70647. update(rotation) {
  70648. this.camera.rotation.copy(rotation);
  70649. this.camera.updateMatrixWorld();
  70650. }
  70651. }
  70652. /**
  70653. * @author mschuetz / http://mschuetz.at
  70654. *
  70655. * adapted from THREE.OrbitControls by
  70656. *
  70657. * @author qiao / https://github.com/qiao
  70658. * @author mrdoob / http://mrdoob.com
  70659. * @author alteredq / http://alteredqualia.com/
  70660. * @author WestLangley / http://github.com/WestLangley
  70661. * @author erich666 / http://erichaines.com
  70662. *
  70663. *
  70664. *
  70665. */
  70666. let minRadius = 2;
  70667. class OrbitControls extends EventDispatcher{
  70668. constructor(viewer){
  70669. super();
  70670. this.viewer = viewer;
  70671. this.renderer = viewer.renderer;
  70672. this.scene = null;
  70673. this.sceneControls = new Scene();
  70674. this.rotationSpeed = 3; //旋转速度
  70675. this.fadeFactor = 100;
  70676. this.yawDelta = 0;
  70677. this.pitchDelta = 0;
  70678. this.panDelta = new Vector2$1(0, 0);
  70679. this.radiusDelta = 0;
  70680. this.doubleClockZoomEnabled = true;
  70681. this.tweens = [];
  70682. this.dollyStart = new Vector2$1;
  70683. this.dollyEnd = new Vector2$1;
  70684. this.keys = {
  70685. FORWARD: ['W'.charCodeAt(0), 38],
  70686. BACKWARD: ['S'.charCodeAt(0), 40],
  70687. LEFT: ['A'.charCodeAt(0), 37],
  70688. RIGHT: ['D'.charCodeAt(0), 39],
  70689. UP: ['Q'.charCodeAt(0)],
  70690. DOWN: ['E'.charCodeAt(0)],
  70691. };
  70692. let drag = (e) => {
  70693. if(!this.enabled)return
  70694. let viewport = e.dragViewport;
  70695. if(!viewport || viewport.camera.type == "OrthographicCamera" )return
  70696. //let camera = viewport.camera
  70697. if (e.drag.object !== null) {
  70698. return;
  70699. }
  70700. let mode;
  70701. if(e.isTouch){
  70702. if(e.touches.length == 1){
  70703. mode = 'rotate';
  70704. }else {
  70705. mode = 'scale-pan';
  70706. }
  70707. }else {
  70708. mode = e.buttons === Buttons.LEFT ? 'rotate' : 'pan';
  70709. }
  70710. if (e.drag.startHandled === undefined) {
  70711. e.drag.startHandled = true;
  70712. this.dispatchEvent({type: 'start'});
  70713. }
  70714. let ndrag = e.drag.pointerDelta.clone();//.add(new THREE.Vector2(1,1)).multiplyScalar(0.5)
  70715. ndrag.y *= -1;
  70716. if (mode == 'rotate') {
  70717. this.yawDelta += ndrag.x * this.rotationSpeed;
  70718. this.pitchDelta += ndrag.y * this.rotationSpeed;
  70719. } else if(mode == 'pan'){
  70720. this.panDelta.x += ndrag.x;
  70721. this.panDelta.y += ndrag.y;
  70722. }else if(mode == 'scale-pan'){ //add
  70723. this.dollyEnd.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  70724. var scale = this.dollyEnd.length() / this.dollyStart.length();
  70725. this.dollyStart.copy(this.dollyEnd);
  70726. this.radiusDelta = (1-scale) * this.scene.view.radius;
  70727. //------------------------
  70728. //平移
  70729. let pointer = new Vector2$1().addVectors(e.touches[0].pointer, e.touches[1].pointer).multiplyScalar(0.5);//两个指头的中心点
  70730. let delta = new Vector2$1().subVectors(pointer, this.lastScalePointer);
  70731. delta.y *= -1;
  70732. this.panDelta.add(delta);
  70733. this.lastScalePointer = pointer.clone();
  70734. //console.log('scale ',scale, this.radiusDelta)
  70735. }
  70736. this.stopTweens();
  70737. };
  70738. let drop = e => {
  70739. if(!this.enabled)return
  70740. this.dispatchEvent({type: 'end'});
  70741. };
  70742. let scroll = (e) => {
  70743. if(!this.enabled)return
  70744. let resolvedRadius = this.scene.view.radius + this.radiusDelta;
  70745. if(resolvedRadius < 0.1 && e.delta>0)return; //防止缩放太小,导致很慢
  70746. this.radiusDelta += -e.delta * resolvedRadius * 0.1;
  70747. this.stopTweens();
  70748. };
  70749. let dblclick = (e) => {
  70750. if(!this.enabled)return
  70751. if(this.doubleClockZoomEnabled){
  70752. this.zoomToLocation(e.mouse);
  70753. }
  70754. };
  70755. let previousTouch = null;
  70756. let touchStart = e => {
  70757. previousTouch = e;
  70758. };
  70759. let touchEnd = e => {
  70760. previousTouch = e;
  70761. };
  70762. let touchMove = e => {
  70763. if(!this.enabled)return
  70764. if (e.touches.length === 2 && previousTouch.touches.length === 2){
  70765. let prev = previousTouch;
  70766. let curr = e;
  70767. let prevDX = prev.touches[0].pageX - prev.touches[1].pageX;
  70768. let prevDY = prev.touches[0].pageY - prev.touches[1].pageY;
  70769. let prevDist = Math.sqrt(prevDX * prevDX + prevDY * prevDY);
  70770. let currDX = curr.touches[0].pageX - curr.touches[1].pageX;
  70771. let currDY = curr.touches[0].pageY - curr.touches[1].pageY;
  70772. let currDist = Math.sqrt(currDX * currDX + currDY * currDY);
  70773. let delta = currDist / prevDist;
  70774. let resolvedRadius = this.scene.view.radius + this.radiusDelta;
  70775. let newRadius = resolvedRadius / delta;
  70776. this.radiusDelta = newRadius - resolvedRadius;
  70777. this.stopTweens();
  70778. }else if(e.touches.length === 3 && previousTouch.touches.length === 3){
  70779. let prev = previousTouch;
  70780. let curr = e;
  70781. let prevMeanX = (prev.touches[0].pageX + prev.touches[1].pageX + prev.touches[2].pageX) / 3;
  70782. let prevMeanY = (prev.touches[0].pageY + prev.touches[1].pageY + prev.touches[2].pageY) / 3;
  70783. let currMeanX = (curr.touches[0].pageX + curr.touches[1].pageX + curr.touches[2].pageX) / 3;
  70784. let currMeanY = (curr.touches[0].pageY + curr.touches[1].pageY + curr.touches[2].pageY) / 3;
  70785. let delta = {
  70786. x: (currMeanX - prevMeanX) / this.renderer.domElement.clientWidth,
  70787. y: (currMeanY - prevMeanY) / this.renderer.domElement.clientHeight
  70788. };
  70789. this.panDelta.x += delta.x;
  70790. this.panDelta.y += delta.y;
  70791. this.stopTweens();
  70792. }
  70793. previousTouch = e;
  70794. };
  70795. this.addEventListener('touchstart', touchStart);
  70796. this.addEventListener('touchend', touchEnd);
  70797. this.addEventListener('touchmove', touchMove);
  70798. this.viewer.addEventListener('global_drag', drag);
  70799. this.viewer.addEventListener('global_drop', drop);
  70800. this.viewer.addEventListener('global_mousewheel', scroll);
  70801. this.viewer.addEventListener('global_dblclick', dblclick);
  70802. this.viewer.addEventListener('global_touchmove', (e)=>{
  70803. if(e.touches.length>1){//单指的就触发上一句
  70804. //console.log('global_touchmove' )
  70805. drag(e);
  70806. }
  70807. });
  70808. let prepareScale = (e)=>{//触屏的scale
  70809. this.dollyStart.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  70810. this.lastScalePointer = new Vector2$1().addVectors(e.touches[0].pointer, e.touches[1].pointer).multiplyScalar(0.5);//两个指头的中心点
  70811. };
  70812. this.viewer.addEventListener('global_touchstart', (e)=>{
  70813. if(this.enabled && e.touches.length==2){//只监听开头两个指头
  70814. prepareScale(e);
  70815. }
  70816. });
  70817. /* this.viewer.addEventListener('global_touchend', (e)=>{
  70818. if(!this.enabled)return
  70819. if(e.touches.length==1){//停止scale,开始rotate
  70820. prepareRotate(e)
  70821. //this.pointerDragStart = null
  70822. //console.log('只剩一个', e.pointer.toArray())
  70823. }
  70824. }) */
  70825. this.viewer.addEventListener('focusOnObject',(o)=>{
  70826. if(o.position && o.CamTarget){
  70827. let distance = o.position.distanceTo(o.CamTarget);
  70828. if(distance < minRadius) minRadius = distance * 0.5; //融合页面当focus一个很小的物体时,需要将minRadius也调小
  70829. }
  70830. });
  70831. }
  70832. setScene (scene) {
  70833. this.scene = scene;
  70834. }
  70835. setEnable(enabled){
  70836. this.enabled = enabled;
  70837. }
  70838. stop(){
  70839. this.yawDelta = 0;
  70840. this.pitchDelta = 0;
  70841. this.radiusDelta = 0;
  70842. this.panDelta.set(0, 0);
  70843. }
  70844. /* zoomToLocation(mouse){
  70845. if(!this.enabled)return
  70846. let camera = this.scene.getActiveCamera();
  70847. let I = Utils.getMousePointCloudIntersection(
  70848. null, mouse, this.viewer.inputHandler.pointer,
  70849. camera,
  70850. this.viewer,
  70851. this.scene.pointclouds,
  70852. {pickClipped: true});
  70853. if (I === null) {
  70854. return;
  70855. }
  70856. let targetRadius = 0;
  70857. {
  70858. let minimumJumpDistance = 0.2;
  70859. let domElement = this.renderer.domElement;
  70860. let ray = Utils.mouseToRay(this.viewer.inputHandler.pointer , camera, domElement.clientWidth, domElement.clientHeight);
  70861. let nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray);
  70862. let lastNode = nodes[nodes.length - 1];
  70863. let radius = lastNode.getBoundingSphere(new THREE.Sphere()).radius;
  70864. targetRadius = Math.min(this.scene.view.radius, radius);
  70865. targetRadius = Math.max(minimumJumpDistance, targetRadius);
  70866. }
  70867. let d = this.scene.view.direction.multiplyScalar(-1);
  70868. let cameraTargetPosition = new THREE.Vector3().addVectors(I.location, d.multiplyScalar(targetRadius));
  70869. // TODO Unused: let controlsTargetPosition = I.location;
  70870. let animationDuration = 600;
  70871. let easing = TWEEN.Easing.Quartic.Out;
  70872. { // animate
  70873. let value = {x: 0};
  70874. let tween = new TWEEN.Tween(value).to({x: 1}, animationDuration);
  70875. tween.easing(easing);
  70876. this.tweens.push(tween);
  70877. let startPos = this.scene.view.position.clone();
  70878. let targetPos = cameraTargetPosition.clone();
  70879. let startRadius = this.scene.view.radius;
  70880. let targetRadius = cameraTargetPosition.distanceTo(I.location);
  70881. tween.onUpdate(() => {
  70882. let t = value.x;
  70883. this.scene.view.position.x = (1 - t) * startPos.x + t * targetPos.x;
  70884. this.scene.view.position.y = (1 - t) * startPos.y + t * targetPos.y;
  70885. this.scene.view.position.z = (1 - t) * startPos.z + t * targetPos.z;
  70886. this.scene.view.radius = (1 - t) * startRadius + t * targetRadius;
  70887. this.viewer.setMoveSpeed(this.scene.view.radius);
  70888. });
  70889. tween.onComplete(() => {
  70890. this.tweens = this.tweens.filter(e => e !== tween);
  70891. });
  70892. tween.start();
  70893. }
  70894. } */
  70895. zoomToLocation(mouse){
  70896. let I = viewer.inputHandler.intersect;
  70897. if(!I)return
  70898. let object = I.object || I.pointcloud;
  70899. I = I.location;
  70900. if(!I || !object)return;
  70901. let dis = this.scene.view.position.distanceTo(I);
  70902. let bound = object.boundingBox.clone().applyMatrix4(object.matrixWorld);
  70903. let size = bound.getSize(new Vector3);
  70904. let len = size.length();
  70905. let distance = MathUtils.clamp(dis, 0.1, Math.max(len * 0.1, 3) );
  70906. minRadius = distance;
  70907. viewer.focusOnObject({ position:I }, 'point', null, {distance});
  70908. }
  70909. stopTweens () {
  70910. this.tweens.forEach(e => e.stop());
  70911. this.tweens = [];
  70912. }
  70913. update (delta) {
  70914. if(!this.enabled)return
  70915. let view = this.scene.view;
  70916. { // accelerate while input is given
  70917. let ih = this.viewer.inputHandler;
  70918. let moveForward = this.keys.FORWARD.some(e => ih.pressedKeys[e]);
  70919. let moveBackward = this.keys.BACKWARD.some(e => ih.pressedKeys[e]);
  70920. let moveLeft = this.keys.LEFT.some(e => ih.pressedKeys[e]);
  70921. let moveRight = this.keys.RIGHT.some(e => ih.pressedKeys[e]);
  70922. let moveUp = this.keys.UP.some(e => ih.pressedKeys[e]);
  70923. let moveDown = this.keys.DOWN.some(e => ih.pressedKeys[e]);
  70924. let px = 0 , py = 0, pz = 0;
  70925. if(moveForward){
  70926. py = 1;
  70927. }else if(moveBackward){
  70928. py = -1;
  70929. }
  70930. if(moveLeft){
  70931. px = -1;
  70932. }else if(moveRight){
  70933. px = 1;
  70934. }
  70935. if(moveUp){
  70936. pz = 1;
  70937. }else if(moveDown){
  70938. pz = -1;
  70939. }
  70940. (px!=0 || py!=0 || pz!=0) && view.translate(px, py, pz, true);
  70941. }
  70942. { // apply rotation
  70943. let progression = Math.min(1, this.fadeFactor * delta);
  70944. let yaw = view.yaw;
  70945. let pitch = view.pitch;
  70946. let pivot = view.getPivot();
  70947. yaw -= progression * this.yawDelta;
  70948. pitch -= progression * this.pitchDelta;
  70949. view.yaw = yaw;
  70950. view.pitch = pitch;
  70951. let V = this.scene.view.direction.multiplyScalar(-view.radius);
  70952. let position = new Vector3().addVectors(pivot, V);
  70953. view.position.copy(position);
  70954. }
  70955. { // apply pan
  70956. /* let progression = Math.min(1, this.fadeFactor * delta);
  70957. let panDistance = progression * view.radius * 3; */
  70958. let camera = this.scene.getActiveCamera();
  70959. let panDistance = 2 * view.radius * Math.tan(MathUtils.degToRad(camera.fov / 2));//参照4dkk。 平移target(也就是平移镜头位置),但还是难以保证跟手(navvis也不一定跟手,但是很奇怪在居中时中心点居然是跟手的,可能计算方式不同)
  70960. //计算了下确实是这么算的。 平移pivot。
  70961. let px = -this.panDelta.x * panDistance;
  70962. let py = this.panDelta.y * panDistance;
  70963. view.pan(px, py);
  70964. }
  70965. { // apply zoom
  70966. let progression = 1;//Math.min(1, this.fadeFactor * delta);
  70967. // let radius = view.radius + progression * this.radiusDelta * view.radius * 0.1;
  70968. let radius = view.radius + progression * this.radiusDelta;
  70969. let V = view.direction.multiplyScalar(-radius);
  70970. let position = new Vector3().addVectors(view.getPivot(), V);
  70971. if(this.constantlyForward) {// 到达中心点后还能继续向前移动,也就是能推进中心点
  70972. if(radius < minRadius){
  70973. radius = minRadius;
  70974. }
  70975. }
  70976. view.radius = radius;
  70977. view.position.copy(position);
  70978. }
  70979. {
  70980. let speed = view.radius;
  70981. this.viewer.setMoveSpeed(speed);
  70982. }
  70983. { // decelerate over time
  70984. /* let progression = Math.min(1, this.fadeFactor * delta);
  70985. let attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  70986. this.yawDelta *= attenuation;
  70987. this.pitchDelta *= attenuation;
  70988. this.panDelta.multiplyScalar(attenuation);
  70989. // this.radiusDelta *= attenuation;
  70990. this.radiusDelta -= progression * this.radiusDelta; */
  70991. //取消衰减,直接stop
  70992. this.stop();
  70993. }
  70994. }
  70995. };
  70996. class EarthControls extends EventDispatcher {
  70997. constructor (viewer) {
  70998. super(viewer);
  70999. this.viewer = viewer;
  71000. this.renderer = viewer.renderer;
  71001. this.scene = null;
  71002. this.sceneControls = new Scene();
  71003. this.rotationSpeed = 10;
  71004. this.fadeFactor = 20;
  71005. this.wheelDelta = 0;
  71006. this.zoomDelta = new Vector3();
  71007. this.camStart = null;
  71008. this.tweens = [];
  71009. {
  71010. let sg = new SphereGeometry(1, 16, 16);
  71011. let sm = new MeshNormalMaterial();
  71012. this.pivotIndicator = new Mesh(sg, sm);
  71013. this.pivotIndicator.visible = false;
  71014. this.sceneControls.add(this.pivotIndicator);
  71015. }
  71016. let drag = (e) => {
  71017. if (e.drag.object !== null) {
  71018. return;
  71019. }
  71020. if (!this.pivot) {
  71021. return;
  71022. }
  71023. if (e.drag.startHandled === undefined) {
  71024. e.drag.startHandled = true;
  71025. this.dispatchEvent({type: 'start'});
  71026. }
  71027. let camStart = this.camStart;
  71028. let camera = this.scene.getActiveCamera();
  71029. let view = this.viewer.scene.view;
  71030. // let camera = this.viewer.scene.camera;
  71031. let Buttons = e.drag.end;
  71032. let domElement = this.viewer.renderer.domElement;
  71033. if (e.drag.Buttons === Buttons.LEFT) {
  71034. let ray = Utils.ButtonsToRay(this.viewer.inputHandler.pointer/* Buttons */, camera, domElement.clientWidth, domElement.clientHeight);
  71035. let plane = new Plane().setFromNormalAndCoplanarPoint(
  71036. new Vector3(0, 0, 1),
  71037. this.pivot);
  71038. let distanceToPlane = ray.distanceToPlane(plane);
  71039. if (distanceToPlane > 0) {
  71040. let I = new Vector3().addVectors(
  71041. camStart.position,
  71042. ray.direction.clone().multiplyScalar(distanceToPlane));
  71043. let movedBy = new Vector3().subVectors(
  71044. I, this.pivot);
  71045. let newCamPos = camStart.position.clone().sub(movedBy);
  71046. view.position.copy(newCamPos);
  71047. {
  71048. let distance = newCamPos.distanceTo(this.pivot);
  71049. view.radius = distance;
  71050. let speed = view.radius / 2.5;
  71051. this.viewer.setMoveSpeed(speed);
  71052. }
  71053. }
  71054. } else if (e.drag.Buttons === Buttons.RIGHT) {
  71055. let ndrag = {
  71056. x: e.drag.ButtonsDelta.x / this.renderer.domElement.clientWidth,
  71057. y: e.drag.ButtonsDelta.y / this.renderer.domElement.clientHeight
  71058. };
  71059. let yawDelta = -ndrag.x * this.rotationSpeed * 0.5;
  71060. let pitchDelta = -ndrag.y * this.rotationSpeed * 0.2;
  71061. let originalPitch = view.pitch;
  71062. let tmpView = view.clone();
  71063. tmpView.pitch = tmpView.pitch + pitchDelta;
  71064. pitchDelta = tmpView.pitch - originalPitch;
  71065. let pivotToCam = new Vector3().subVectors(view.position, this.pivot);
  71066. let pivotToCamTarget = new Vector3().subVectors(view.getPivot(), this.pivot);
  71067. let side = view.getSide();
  71068. pivotToCam.applyAxisAngle(side, pitchDelta);
  71069. pivotToCamTarget.applyAxisAngle(side, pitchDelta);
  71070. pivotToCam.applyAxisAngle(new Vector3(0, 0, 1), yawDelta);
  71071. pivotToCamTarget.applyAxisAngle(new Vector3(0, 0, 1), yawDelta);
  71072. let newCam = new Vector3().addVectors(this.pivot, pivotToCam);
  71073. // TODO: Unused: let newCamTarget = new THREE.Vector3().addVectors(this.pivot, pivotToCamTarget);
  71074. view.position.copy(newCam);
  71075. view.yaw += yawDelta;
  71076. view.pitch += pitchDelta;
  71077. }
  71078. };
  71079. let onButtonsDown = e => {
  71080. let I = Utils.getButtonsPointCloudIntersection(
  71081. e.Buttons,
  71082. this.scene.getActiveCamera(),
  71083. this.viewer,
  71084. this.scene.pointclouds,
  71085. {pickClipped: false});
  71086. if (I) {
  71087. this.pivot = I.location;
  71088. this.camStart = this.scene.getActiveCamera().clone();
  71089. this.pivotIndicator.visible = true;
  71090. this.pivotIndicator.position.copy(I.location);
  71091. }
  71092. };
  71093. let drop = e => {
  71094. this.dispatchEvent({type: 'end'});
  71095. };
  71096. let onButtonsUp = e => {
  71097. this.camStart = null;
  71098. this.pivot = null;
  71099. this.pivotIndicator.visible = false;
  71100. };
  71101. let scroll = (e) => {
  71102. this.wheelDelta += e.delta;
  71103. };
  71104. let dblclick = (e) => {
  71105. this.zoomToLocation(e.Buttons);
  71106. };
  71107. this.addEventListener('drag', drag);
  71108. this.addEventListener('drop', drop);
  71109. this.addEventListener('Buttonswheel', scroll);
  71110. this.addEventListener('Buttonsdown', onButtonsDown);
  71111. this.addEventListener('Buttonsup', onButtonsUp);
  71112. this.addEventListener('dblclick', dblclick);
  71113. }
  71114. setScene (scene) {
  71115. this.scene = scene;
  71116. }
  71117. stop(){
  71118. this.wheelDelta = 0;
  71119. this.zoomDelta.set(0, 0, 0);
  71120. }
  71121. zoomToLocation(Buttons){
  71122. let camera = this.scene.getActiveCamera();
  71123. let I = Utils.getButtonsPointCloudIntersection(
  71124. Buttons,
  71125. camera,
  71126. this.viewer,
  71127. this.scene.pointclouds);
  71128. if (I === null) {
  71129. return;
  71130. }
  71131. let targetRadius = 0;
  71132. {
  71133. let minimumJumpDistance = 0.2;
  71134. let domElement = this.renderer.domElement;
  71135. let ray = Utils.ButtonsToRay(this.viewer.inputHandler.pointer, camera, domElement.clientWidth, domElement.clientHeight);
  71136. let nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray);
  71137. let lastNode = nodes[nodes.length - 1];
  71138. let radius = lastNode.getBoundingSphere(new Sphere()).radius;
  71139. targetRadius = Math.min(this.scene.view.radius, radius);
  71140. targetRadius = Math.max(minimumJumpDistance, targetRadius);
  71141. }
  71142. let d = this.scene.view.direction.multiplyScalar(-1);
  71143. let cameraTargetPosition = new Vector3().addVectors(I.location, d.multiplyScalar(targetRadius));
  71144. // TODO Unused: let controlsTargetPosition = I.location;
  71145. let animationDuration = 600;
  71146. let easing = TWEEN.Easing.Quartic.Out;
  71147. { // animate
  71148. let value = {x: 0};
  71149. let tween = new TWEEN.Tween(value).to({x: 1}, animationDuration);
  71150. tween.easing(easing);
  71151. this.tweens.push(tween);
  71152. let startPos = this.scene.view.position.clone();
  71153. let targetPos = cameraTargetPosition.clone();
  71154. let startRadius = this.scene.view.radius;
  71155. let targetRadius = cameraTargetPosition.distanceTo(I.location);
  71156. tween.onUpdate(() => {
  71157. let t = value.x;
  71158. this.scene.view.position.x = (1 - t) * startPos.x + t * targetPos.x;
  71159. this.scene.view.position.y = (1 - t) * startPos.y + t * targetPos.y;
  71160. this.scene.view.position.z = (1 - t) * startPos.z + t * targetPos.z;
  71161. this.scene.view.radius = (1 - t) * startRadius + t * targetRadius;
  71162. this.viewer.setMoveSpeed(this.scene.view.radius / 2.5);
  71163. });
  71164. tween.onComplete(() => {
  71165. this.tweens = this.tweens.filter(e => e !== tween);
  71166. });
  71167. tween.start();
  71168. }
  71169. }
  71170. update (delta) {
  71171. let view = this.scene.view;
  71172. let fade = Math.pow(0.5, this.fadeFactor * delta);
  71173. let progression = 1 - fade;
  71174. let camera = this.scene.getActiveCamera();
  71175. // compute zoom
  71176. if (this.wheelDelta !== 0) {
  71177. let I = Utils.getButtonsPointCloudIntersection(
  71178. this.viewer.inputHandler.Buttons,
  71179. this.scene.getActiveCamera(),
  71180. this.viewer,
  71181. this.scene.pointclouds);
  71182. if (I) {
  71183. let resolvedPos = new Vector3().addVectors(view.position, this.zoomDelta);
  71184. let distance = I.location.distanceTo(resolvedPos);
  71185. let jumpDistance = distance * 0.2 * this.wheelDelta;
  71186. let targetDir = new Vector3().subVectors(I.location, view.position);
  71187. targetDir.normalize();
  71188. resolvedPos.add(targetDir.multiplyScalar(jumpDistance));
  71189. this.zoomDelta.subVectors(resolvedPos, view.position);
  71190. {
  71191. let distance = resolvedPos.distanceTo(I.location);
  71192. view.radius = distance;
  71193. let speed = view.radius / 2.5;
  71194. this.viewer.setMoveSpeed(speed);
  71195. }
  71196. }
  71197. }
  71198. // apply zoom
  71199. if (this.zoomDelta.length() !== 0) {
  71200. let p = this.zoomDelta.clone().multiplyScalar(progression);
  71201. let newPos = new Vector3().addVectors(view.position, p);
  71202. view.position.copy(newPos);
  71203. }
  71204. if (this.pivotIndicator.visible) {
  71205. let distance = this.pivotIndicator.position.distanceTo(view.position);
  71206. let pixelwidth = this.renderer.domElement.clientwidth;
  71207. let pixelHeight = this.renderer.domElement.clientHeight;
  71208. let pr = Utils.projectedRadius(1, camera, distance, pixelwidth, pixelHeight);
  71209. let scale = (10 / pr);
  71210. this.pivotIndicator.scale.set(scale, scale, scale);
  71211. }
  71212. // decelerate over time
  71213. {
  71214. this.zoomDelta.multiplyScalar(fade);
  71215. this.wheelDelta = 0;
  71216. }
  71217. }
  71218. };
  71219. /**
  71220. * @author chrisl / Geodan
  71221. *
  71222. * adapted from Potree.FirstPersonControls by
  71223. *
  71224. * @author mschuetz / http://mschuetz.at
  71225. *
  71226. * and THREE.DeviceOrientationControls by
  71227. *
  71228. * @author richt / http://richt.me
  71229. * @author WestLangley / http://github.com/WestLangley
  71230. *
  71231. *
  71232. *
  71233. */
  71234. class DeviceOrientationControls extends EventDispatcher{
  71235. constructor(viewer){
  71236. super();
  71237. this.viewer = viewer;
  71238. this.renderer = viewer.renderer;
  71239. this.scene = null;
  71240. this.sceneControls = new Scene();
  71241. this.screenOrientation = window.orientation || 0;
  71242. let deviceOrientationChange = e => {
  71243. this.deviceOrientation = e;
  71244. };
  71245. let screenOrientationChange = e => {
  71246. this.screenOrientation = window.orientation || 0;
  71247. };
  71248. if ('ondeviceorientationabsolute' in window) {
  71249. window.addEventListener('deviceorientationabsolute', deviceOrientationChange);
  71250. } else if ('ondeviceorientation' in window) {
  71251. window.addEventListener('deviceorientation', deviceOrientationChange);
  71252. } else {
  71253. console.warn("No device orientation found.");
  71254. }
  71255. // window.addEventListener('deviceorientation', deviceOrientationChange);
  71256. window.addEventListener('orientationchange', screenOrientationChange);
  71257. }
  71258. setScene (scene) {
  71259. this.scene = scene;
  71260. }
  71261. update (delta) {
  71262. let computeQuaternion = function (alpha, beta, gamma, orient) {
  71263. let quaternion = new Quaternion();
  71264. let zee = new Vector3(0, 0, 1);
  71265. let euler = new Euler();
  71266. let q0 = new Quaternion();
  71267. euler.set(beta, gamma, alpha, 'ZXY');
  71268. quaternion.setFromEuler(euler);
  71269. quaternion.multiply(q0.setFromAxisAngle(zee, -orient));
  71270. return quaternion;
  71271. };
  71272. if (typeof this.deviceOrientation !== 'undefined') {
  71273. let alpha = this.deviceOrientation.alpha ? MathUtils.degToRad(this.deviceOrientation.alpha) : 0;
  71274. let beta = this.deviceOrientation.beta ? MathUtils.degToRad(this.deviceOrientation.beta) : 0;
  71275. let gamma = this.deviceOrientation.gamma ? MathUtils.degToRad(this.deviceOrientation.gamma) : 0;
  71276. let orient = this.screenOrientation ? MathUtils.degToRad(this.screenOrientation) : 0;
  71277. let quaternion = computeQuaternion(alpha, beta, gamma, orient);
  71278. viewer.scene.cameraP.quaternion.set(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
  71279. }
  71280. }
  71281. };
  71282. const _taskCache = new WeakMap();
  71283. class DRACOLoader extends Loader {
  71284. constructor( manager ) {
  71285. super( manager );
  71286. this.decoderPath = '';
  71287. this.decoderConfig = {};
  71288. this.decoderBinary = null;
  71289. this.decoderPending = null;
  71290. this.workerLimit = 4;
  71291. this.workerPool = [];
  71292. this.workerNextTaskID = 1;
  71293. this.workerSourceURL = '';
  71294. this.defaultAttributeIDs = {
  71295. position: 'POSITION',
  71296. normal: 'NORMAL',
  71297. color: 'COLOR',
  71298. uv: 'TEX_COORD'
  71299. };
  71300. this.defaultAttributeTypes = {
  71301. position: 'Float32Array',
  71302. normal: 'Float32Array',
  71303. color: 'Float32Array',
  71304. uv: 'Float32Array'
  71305. };
  71306. }
  71307. setDecoderPath( path ) {
  71308. this.decoderPath = path;
  71309. return this;
  71310. }
  71311. setDecoderConfig( config ) {
  71312. this.decoderConfig = config;
  71313. return this;
  71314. }
  71315. setWorkerLimit( workerLimit ) {
  71316. this.workerLimit = workerLimit;
  71317. return this;
  71318. }
  71319. load( url, onLoad, onProgress, onError ) {
  71320. const loader = new FileLoader( this.manager );
  71321. loader.setPath( this.path );
  71322. loader.setResponseType( 'arraybuffer' );
  71323. loader.setRequestHeader( this.requestHeader );
  71324. loader.setWithCredentials( this.withCredentials );
  71325. loader.load( url, ( buffer ) => {
  71326. const taskConfig = {
  71327. attributeIDs: this.defaultAttributeIDs,
  71328. attributeTypes: this.defaultAttributeTypes,
  71329. useUniqueIDs: false
  71330. };
  71331. this.decodeGeometry( buffer, taskConfig )
  71332. .then( onLoad )
  71333. .catch( onError );
  71334. }, onProgress, onError );
  71335. }
  71336. /** @deprecated Kept for backward-compatibility with previous DRACOLoader versions. */
  71337. decodeDracoFile( buffer, callback, attributeIDs, attributeTypes ) {
  71338. const taskConfig = {
  71339. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  71340. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  71341. useUniqueIDs: !! attributeIDs
  71342. };
  71343. this.decodeGeometry( buffer, taskConfig ).then( callback );
  71344. }
  71345. decodeGeometry( buffer, taskConfig ) {
  71346. // TODO: For backward-compatibility, support 'attributeTypes' objects containing
  71347. // references (rather than names) to typed array constructors. These must be
  71348. // serialized before sending them to the worker.
  71349. for ( const attribute in taskConfig.attributeTypes ) {
  71350. const type = taskConfig.attributeTypes[ attribute ];
  71351. if ( type.BYTES_PER_ELEMENT !== undefined ) {
  71352. taskConfig.attributeTypes[ attribute ] = type.name;
  71353. }
  71354. }
  71355. //
  71356. const taskKey = JSON.stringify( taskConfig );
  71357. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  71358. // again from this thread.
  71359. if ( _taskCache.has( buffer ) ) {
  71360. const cachedTask = _taskCache.get( buffer );
  71361. if ( cachedTask.key === taskKey ) {
  71362. return cachedTask.promise;
  71363. } else if ( buffer.byteLength === 0 ) {
  71364. // Technically, it would be possible to wait for the previous task to complete,
  71365. // transfer the buffer back, and decode again with the second configuration. That
  71366. // is complex, and I don't know of any reason to decode a Draco buffer twice in
  71367. // different ways, so this is left unimplemented.
  71368. throw new Error(
  71369. 'THREE.DRACOLoader: Unable to re-decode a buffer with different ' +
  71370. 'settings. Buffer has already been transferred.'
  71371. );
  71372. }
  71373. }
  71374. //
  71375. let worker;
  71376. const taskID = this.workerNextTaskID ++;
  71377. const taskCost = buffer.byteLength;
  71378. // Obtain a worker and assign a task, and construct a geometry instance
  71379. // when the task completes.
  71380. const geometryPending = this._getWorker( taskID, taskCost )
  71381. .then( ( _worker ) => {
  71382. worker = _worker;
  71383. return new Promise( ( resolve, reject ) => {
  71384. worker._callbacks[ taskID ] = { resolve, reject };
  71385. worker.postMessage( { type: 'decode', id: taskID, taskConfig, buffer }, [ buffer ] );
  71386. // this.debug();
  71387. } );
  71388. } )
  71389. .then( ( message ) => this._createGeometry( message.geometry ) );
  71390. // Remove task from the task list.
  71391. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  71392. geometryPending
  71393. .catch( () => true )
  71394. .then( () => {
  71395. if ( worker && taskID ) {
  71396. this._releaseTask( worker, taskID );
  71397. // this.debug();
  71398. }
  71399. } );
  71400. // Cache the task result.
  71401. _taskCache.set( buffer, {
  71402. key: taskKey,
  71403. promise: geometryPending
  71404. } );
  71405. return geometryPending;
  71406. }
  71407. _createGeometry( geometryData ) {
  71408. const geometry = new BufferGeometry();
  71409. if ( geometryData.index ) {
  71410. geometry.setIndex( new BufferAttribute( geometryData.index.array, 1 ) );
  71411. }
  71412. for ( let i = 0; i < geometryData.attributes.length; i ++ ) {
  71413. const attribute = geometryData.attributes[ i ];
  71414. const name = attribute.name;
  71415. const array = attribute.array;
  71416. const itemSize = attribute.itemSize;
  71417. geometry.setAttribute( name, new BufferAttribute( array, itemSize ) );
  71418. }
  71419. return geometry;
  71420. }
  71421. _loadLibrary( url, responseType ) {
  71422. const loader = new FileLoader( this.manager );
  71423. loader.setPath( this.decoderPath );
  71424. loader.setResponseType( responseType );
  71425. loader.setWithCredentials( this.withCredentials );
  71426. return new Promise( ( resolve, reject ) => {
  71427. loader.load( url, resolve, undefined, reject );
  71428. } );
  71429. }
  71430. preload() {
  71431. this._initDecoder();
  71432. return this;
  71433. }
  71434. _initDecoder() {
  71435. if ( this.decoderPending ) return this.decoderPending;
  71436. const useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  71437. const librariesPending = [];
  71438. if ( useJS ) {
  71439. librariesPending.push( this._loadLibrary( 'draco_decoder.js', 'text' ) );
  71440. } else {
  71441. librariesPending.push( this._loadLibrary( 'draco_wasm_wrapper.js', 'text' ) );
  71442. librariesPending.push( this._loadLibrary( 'draco_decoder.wasm', 'arraybuffer' ) );
  71443. }
  71444. this.decoderPending = Promise.all( librariesPending )
  71445. .then( ( libraries ) => {
  71446. const jsContent = libraries[ 0 ];
  71447. if ( ! useJS ) {
  71448. this.decoderConfig.wasmBinary = libraries[ 1 ];
  71449. }
  71450. const fn = DRACOWorker.toString();
  71451. const body = [
  71452. '/* draco decoder */',
  71453. jsContent,
  71454. '',
  71455. '/* worker */',
  71456. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  71457. ].join( '\n' );
  71458. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  71459. } );
  71460. return this.decoderPending;
  71461. }
  71462. _getWorker( taskID, taskCost ) {
  71463. return this._initDecoder().then( () => {
  71464. if ( this.workerPool.length < this.workerLimit ) {
  71465. const worker = new Worker( this.workerSourceURL );
  71466. worker._callbacks = {};
  71467. worker._taskCosts = {};
  71468. worker._taskLoad = 0;
  71469. worker.postMessage( { type: 'init', decoderConfig: this.decoderConfig } );
  71470. worker.onmessage = function ( e ) {
  71471. const message = e.data;
  71472. switch ( message.type ) {
  71473. case 'decode':
  71474. worker._callbacks[ message.id ].resolve( message );
  71475. break;
  71476. case 'error':
  71477. worker._callbacks[ message.id ].reject( message );
  71478. break;
  71479. default:
  71480. console.error( 'THREE.DRACOLoader: Unexpected message, "' + message.type + '"' );
  71481. }
  71482. };
  71483. this.workerPool.push( worker );
  71484. } else {
  71485. this.workerPool.sort( function ( a, b ) {
  71486. return a._taskLoad > b._taskLoad ? - 1 : 1;
  71487. } );
  71488. }
  71489. const worker = this.workerPool[ this.workerPool.length - 1 ];
  71490. worker._taskCosts[ taskID ] = taskCost;
  71491. worker._taskLoad += taskCost;
  71492. return worker;
  71493. } );
  71494. }
  71495. _releaseTask( worker, taskID ) {
  71496. worker._taskLoad -= worker._taskCosts[ taskID ];
  71497. delete worker._callbacks[ taskID ];
  71498. delete worker._taskCosts[ taskID ];
  71499. }
  71500. debug() {
  71501. console.log( 'Task load: ', this.workerPool.map( ( worker ) => worker._taskLoad ) );
  71502. }
  71503. dispose() {
  71504. for ( let i = 0; i < this.workerPool.length; ++ i ) {
  71505. this.workerPool[ i ].terminate();
  71506. }
  71507. this.workerPool.length = 0;
  71508. return this;
  71509. }
  71510. }
  71511. /* WEB WORKER */
  71512. function DRACOWorker() {
  71513. let decoderConfig;
  71514. let decoderPending;
  71515. onmessage = function ( e ) {
  71516. const message = e.data;
  71517. switch ( message.type ) {
  71518. case 'init':
  71519. decoderConfig = message.decoderConfig;
  71520. decoderPending = new Promise( function ( resolve/*, reject*/ ) {
  71521. decoderConfig.onModuleLoaded = function ( draco ) {
  71522. // Module is Promise-like. Wrap before resolving to avoid loop.
  71523. resolve( { draco: draco } );
  71524. };
  71525. DracoDecoderModule( decoderConfig ); // eslint-disable-line no-undef
  71526. } );
  71527. break;
  71528. case 'decode':
  71529. const buffer = message.buffer;
  71530. const taskConfig = message.taskConfig;
  71531. decoderPending.then( ( module ) => {
  71532. const draco = module.draco;
  71533. const decoder = new draco.Decoder();
  71534. const decoderBuffer = new draco.DecoderBuffer();
  71535. decoderBuffer.Init( new Int8Array( buffer ), buffer.byteLength );
  71536. try {
  71537. const geometry = decodeGeometry( draco, decoder, decoderBuffer, taskConfig );
  71538. const buffers = geometry.attributes.map( ( attr ) => attr.array.buffer );
  71539. if ( geometry.index ) buffers.push( geometry.index.array.buffer );
  71540. self.postMessage( { type: 'decode', id: message.id, geometry }, buffers );
  71541. } catch ( error ) {
  71542. console.error( error );
  71543. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  71544. } finally {
  71545. draco.destroy( decoderBuffer );
  71546. draco.destroy( decoder );
  71547. }
  71548. } );
  71549. break;
  71550. }
  71551. };
  71552. function decodeGeometry( draco, decoder, decoderBuffer, taskConfig ) {
  71553. const attributeIDs = taskConfig.attributeIDs;
  71554. const attributeTypes = taskConfig.attributeTypes;
  71555. let dracoGeometry;
  71556. let decodingStatus;
  71557. const geometryType = decoder.GetEncodedGeometryType( decoderBuffer );
  71558. if ( geometryType === draco.TRIANGULAR_MESH ) {
  71559. dracoGeometry = new draco.Mesh();
  71560. decodingStatus = decoder.DecodeBufferToMesh( decoderBuffer, dracoGeometry );
  71561. } else if ( geometryType === draco.POINT_CLOUD ) {
  71562. dracoGeometry = new draco.PointCloud();
  71563. decodingStatus = decoder.DecodeBufferToPointCloud( decoderBuffer, dracoGeometry );
  71564. } else {
  71565. throw new Error( 'THREE.DRACOLoader: Unexpected geometry type.' );
  71566. }
  71567. if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {
  71568. throw new Error( 'THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );
  71569. }
  71570. const geometry = { index: null, attributes: [] };
  71571. // Gather all vertex attributes.
  71572. for ( const attributeName in attributeIDs ) {
  71573. const attributeType = self[ attributeTypes[ attributeName ] ];
  71574. let attribute;
  71575. let attributeID;
  71576. // A Draco file may be created with default vertex attributes, whose attribute IDs
  71577. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  71578. // a Draco file may contain a custom set of attributes, identified by known unique
  71579. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  71580. if ( taskConfig.useUniqueIDs ) {
  71581. attributeID = attributeIDs[ attributeName ];
  71582. attribute = decoder.GetAttributeByUniqueId( dracoGeometry, attributeID );
  71583. } else {
  71584. attributeID = decoder.GetAttributeId( dracoGeometry, draco[ attributeIDs[ attributeName ] ] );
  71585. if ( attributeID === - 1 ) continue;
  71586. attribute = decoder.GetAttribute( dracoGeometry, attributeID );
  71587. }
  71588. geometry.attributes.push( decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) );
  71589. }
  71590. // Add index.
  71591. if ( geometryType === draco.TRIANGULAR_MESH ) {
  71592. geometry.index = decodeIndex( draco, decoder, dracoGeometry );
  71593. }
  71594. draco.destroy( dracoGeometry );
  71595. return geometry;
  71596. }
  71597. function decodeIndex( draco, decoder, dracoGeometry ) {
  71598. const numFaces = dracoGeometry.num_faces();
  71599. const numIndices = numFaces * 3;
  71600. const byteLength = numIndices * 4;
  71601. const ptr = draco._malloc( byteLength );
  71602. decoder.GetTrianglesUInt32Array( dracoGeometry, byteLength, ptr );
  71603. const index = new Uint32Array( draco.HEAPF32.buffer, ptr, numIndices ).slice();
  71604. draco._free( ptr );
  71605. return { array: index, itemSize: 1 };
  71606. }
  71607. function decodeAttribute( draco, decoder, dracoGeometry, attributeName, attributeType, attribute ) {
  71608. const numComponents = attribute.num_components();
  71609. const numPoints = dracoGeometry.num_points();
  71610. const numValues = numPoints * numComponents;
  71611. const byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
  71612. const dataType = getDracoDataType( draco, attributeType );
  71613. const ptr = draco._malloc( byteLength );
  71614. decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, dataType, byteLength, ptr );
  71615. const array = new attributeType( draco.HEAPF32.buffer, ptr, numValues ).slice();
  71616. draco._free( ptr );
  71617. return {
  71618. name: attributeName,
  71619. array: array,
  71620. itemSize: numComponents
  71621. };
  71622. }
  71623. function getDracoDataType( draco, attributeType ) {
  71624. switch ( attributeType ) {
  71625. case Float32Array: return draco.DT_FLOAT32;
  71626. case Int8Array: return draco.DT_INT8;
  71627. case Int16Array: return draco.DT_INT16;
  71628. case Int32Array: return draco.DT_INT32;
  71629. case Uint8Array: return draco.DT_UINT8;
  71630. case Uint16Array: return draco.DT_UINT16;
  71631. case Uint32Array: return draco.DT_UINT32;
  71632. }
  71633. }
  71634. }
  71635. /**
  71636. * @author Deepkolos / https://github.com/deepkolos
  71637. */
  71638. class WorkerPool$1 {
  71639. constructor( pool = 4 ) {
  71640. this.pool = pool;
  71641. this.queue = [];
  71642. this.workers = [];
  71643. this.workersResolve = [];
  71644. this.workerStatus = 0;
  71645. }
  71646. _initWorker( workerId ) {
  71647. if ( ! this.workers[ workerId ] ) {
  71648. const worker = this.workerCreator();
  71649. worker.addEventListener( 'message', this._onMessage.bind( this, workerId ) );
  71650. this.workers[ workerId ] = worker;
  71651. }
  71652. }
  71653. _getIdleWorker() {
  71654. for ( let i = 0; i < this.pool; i ++ )
  71655. if ( ! ( this.workerStatus & ( 1 << i ) ) ) return i;
  71656. return - 1;
  71657. }
  71658. _onMessage( workerId, msg ) {
  71659. const resolve = this.workersResolve[ workerId ];
  71660. resolve && resolve( msg );
  71661. if ( this.queue.length ) {
  71662. const { resolve, msg, transfer } = this.queue.shift();
  71663. this.workersResolve[ workerId ] = resolve;
  71664. this.workers[ workerId ].postMessage( msg, transfer );
  71665. } else {
  71666. this.workerStatus ^= 1 << workerId;
  71667. }
  71668. }
  71669. setWorkerCreator( workerCreator ) {
  71670. this.workerCreator = workerCreator;
  71671. }
  71672. setWorkerLimit( pool ) {
  71673. this.pool = pool;
  71674. }
  71675. postMessage( msg, transfer ) {
  71676. return new Promise( ( resolve ) => {
  71677. const workerId = this._getIdleWorker();
  71678. if ( workerId !== - 1 ) {
  71679. this._initWorker( workerId );
  71680. this.workerStatus |= 1 << workerId;
  71681. this.workersResolve[ workerId ] = resolve;
  71682. this.workers[ workerId ].postMessage( msg, transfer );
  71683. } else {
  71684. this.queue.push( { resolve, msg, transfer } );
  71685. }
  71686. } );
  71687. }
  71688. dispose() {
  71689. this.workers.forEach( ( worker ) => worker.terminate() );
  71690. this.workersResolve.length = 0;
  71691. this.workers.length = 0;
  71692. this.queue.length = 0;
  71693. this.workerStatus = 0;
  71694. }
  71695. }
  71696. 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,..._]))}
  71697. var KTX = /*#__PURE__*/Object.freeze({
  71698. __proto__: null,
  71699. KHR_DF_CHANNEL_RGBSDA_ALPHA: Q,
  71700. KHR_DF_CHANNEL_RGBSDA_BLUE: q,
  71701. KHR_DF_CHANNEL_RGBSDA_DEPTH: J,
  71702. KHR_DF_CHANNEL_RGBSDA_GREEN: Y,
  71703. KHR_DF_CHANNEL_RGBSDA_RED: R,
  71704. KHR_DF_CHANNEL_RGBSDA_STENCIL: G,
  71705. KHR_DF_FLAG_ALPHA_PREMULTIPLIED: p,
  71706. KHR_DF_FLAG_ALPHA_STRAIGHT: _$1,
  71707. KHR_DF_KHR_DESCRIPTORTYPE_BASICFORMAT: s,
  71708. KHR_DF_MODEL_ASTC: c$3,
  71709. KHR_DF_MODEL_ETC1: f,
  71710. KHR_DF_MODEL_ETC1S: h$2,
  71711. KHR_DF_MODEL_ETC2: U$1,
  71712. KHR_DF_MODEL_RGBSDA: l$1,
  71713. KHR_DF_MODEL_UNSPECIFIED: o$1,
  71714. KHR_DF_PRIMARIES_ACES: W,
  71715. KHR_DF_PRIMARIES_ACESCC: N,
  71716. KHR_DF_PRIMARIES_ADOBERGB: j,
  71717. KHR_DF_PRIMARIES_BT2020: z,
  71718. KHR_DF_PRIMARIES_BT601_EBU: P,
  71719. KHR_DF_PRIMARIES_BT601_SMPTE: C,
  71720. KHR_DF_PRIMARIES_BT709: F,
  71721. KHR_DF_PRIMARIES_CIEXYZ: M$1,
  71722. KHR_DF_PRIMARIES_DISPLAYP3: X,
  71723. KHR_DF_PRIMARIES_NTSC1953: H,
  71724. KHR_DF_PRIMARIES_PAL525: K,
  71725. KHR_DF_PRIMARIES_UNSPECIFIED: E,
  71726. KHR_DF_SAMPLE_DATATYPE_EXPONENT: tt,
  71727. KHR_DF_SAMPLE_DATATYPE_FLOAT: Z,
  71728. KHR_DF_SAMPLE_DATATYPE_LINEAR: et,
  71729. KHR_DF_SAMPLE_DATATYPE_SIGNED: $$1,
  71730. KHR_DF_TRANSFER_ACESCC: O,
  71731. KHR_DF_TRANSFER_ACESCCT: T$1,
  71732. KHR_DF_TRANSFER_ADOBERGB: V,
  71733. KHR_DF_TRANSFER_BT1886: w$1,
  71734. KHR_DF_TRANSFER_DCIP3: k,
  71735. KHR_DF_TRANSFER_HLG_EOTF: B,
  71736. KHR_DF_TRANSFER_HLG_OETF: D,
  71737. KHR_DF_TRANSFER_ITU: u$2,
  71738. KHR_DF_TRANSFER_LINEAR: y,
  71739. KHR_DF_TRANSFER_NTSC: b$1,
  71740. KHR_DF_TRANSFER_PAL625_EOTF: S$1,
  71741. KHR_DF_TRANSFER_PAL_OETF: v,
  71742. KHR_DF_TRANSFER_PQ_EOTF: L,
  71743. KHR_DF_TRANSFER_PQ_OETF: A,
  71744. KHR_DF_TRANSFER_SLOG: d,
  71745. KHR_DF_TRANSFER_SLOG2: m,
  71746. KHR_DF_TRANSFER_SRGB: x$2,
  71747. KHR_DF_TRANSFER_ST240: I,
  71748. KHR_DF_TRANSFER_UNSPECIFIED: g,
  71749. KHR_DF_VENDORID_KHRONOS: a$1,
  71750. KHR_DF_VERSION: r,
  71751. KHR_SUPERCOMPRESSION_BASISLZ: e$1,
  71752. KHR_SUPERCOMPRESSION_NONE: t,
  71753. KHR_SUPERCOMPRESSION_ZLIB: i$2,
  71754. KHR_SUPERCOMPRESSION_ZSTD: n$1,
  71755. KTX2Container: Si,
  71756. VK_FORMAT_A1R5G5B5_UNORM_PACK16: Ut,
  71757. VK_FORMAT_A2B10G10R10_SINT_PACK32: qt,
  71758. VK_FORMAT_A2B10G10R10_SNORM_PACK32: Rt,
  71759. VK_FORMAT_A2B10G10R10_UINT_PACK32: Yt,
  71760. VK_FORMAT_A2B10G10R10_UNORM_PACK32: jt,
  71761. VK_FORMAT_A2R10G10B10_SINT_PACK32: Xt,
  71762. VK_FORMAT_A2R10G10B10_SNORM_PACK32: Ht,
  71763. VK_FORMAT_A2R10G10B10_UINT_PACK32: Kt,
  71764. VK_FORMAT_A2R10G10B10_UNORM_PACK32: Nt,
  71765. VK_FORMAT_A4B4G4R4_UNORM_PACK16_EXT: vi,
  71766. VK_FORMAT_A4R4G4B4_UNORM_PACK16_EXT: ki,
  71767. VK_FORMAT_ASTC_10x10_SFLOAT_BLOCK_EXT: Bi,
  71768. VK_FORMAT_ASTC_10x10_SRGB_BLOCK: Xn,
  71769. VK_FORMAT_ASTC_10x10_UNORM_BLOCK: Kn,
  71770. VK_FORMAT_ASTC_10x5_SFLOAT_BLOCK_EXT: mi,
  71771. VK_FORMAT_ASTC_10x5_SRGB_BLOCK: zn,
  71772. VK_FORMAT_ASTC_10x5_UNORM_BLOCK: Cn,
  71773. VK_FORMAT_ASTC_10x6_SFLOAT_BLOCK_EXT: wi,
  71774. VK_FORMAT_ASTC_10x6_SRGB_BLOCK: Wn,
  71775. VK_FORMAT_ASTC_10x6_UNORM_BLOCK: Mn,
  71776. VK_FORMAT_ASTC_10x8_SFLOAT_BLOCK_EXT: Di,
  71777. VK_FORMAT_ASTC_10x8_SRGB_BLOCK: Hn,
  71778. VK_FORMAT_ASTC_10x8_UNORM_BLOCK: Nn,
  71779. VK_FORMAT_ASTC_12x10_SFLOAT_BLOCK_EXT: Li,
  71780. VK_FORMAT_ASTC_12x10_SRGB_BLOCK: Rn,
  71781. VK_FORMAT_ASTC_12x10_UNORM_BLOCK: jn,
  71782. VK_FORMAT_ASTC_12x12_SFLOAT_BLOCK_EXT: Ai,
  71783. VK_FORMAT_ASTC_12x12_SRGB_BLOCK: qn,
  71784. VK_FORMAT_ASTC_12x12_UNORM_BLOCK: Yn,
  71785. VK_FORMAT_ASTC_4x4_SFLOAT_BLOCK_EXT: _i,
  71786. VK_FORMAT_ASTC_4x4_SRGB_BLOCK: wn,
  71787. VK_FORMAT_ASTC_4x4_UNORM_BLOCK: mn,
  71788. VK_FORMAT_ASTC_5x4_SFLOAT_BLOCK_EXT: pi,
  71789. VK_FORMAT_ASTC_5x4_SRGB_BLOCK: Bn,
  71790. VK_FORMAT_ASTC_5x4_UNORM_BLOCK: Dn,
  71791. VK_FORMAT_ASTC_5x5_SFLOAT_BLOCK_EXT: gi,
  71792. VK_FORMAT_ASTC_5x5_SRGB_BLOCK: An,
  71793. VK_FORMAT_ASTC_5x5_UNORM_BLOCK: Ln,
  71794. VK_FORMAT_ASTC_6x5_SFLOAT_BLOCK_EXT: yi,
  71795. VK_FORMAT_ASTC_6x5_SRGB_BLOCK: vn,
  71796. VK_FORMAT_ASTC_6x5_UNORM_BLOCK: kn,
  71797. VK_FORMAT_ASTC_6x6_SFLOAT_BLOCK_EXT: xi,
  71798. VK_FORMAT_ASTC_6x6_SRGB_BLOCK: In,
  71799. VK_FORMAT_ASTC_6x6_UNORM_BLOCK: Sn,
  71800. VK_FORMAT_ASTC_8x5_SFLOAT_BLOCK_EXT: ui,
  71801. VK_FORMAT_ASTC_8x5_SRGB_BLOCK: Tn,
  71802. VK_FORMAT_ASTC_8x5_UNORM_BLOCK: On,
  71803. VK_FORMAT_ASTC_8x6_SFLOAT_BLOCK_EXT: bi,
  71804. VK_FORMAT_ASTC_8x6_SRGB_BLOCK: En,
  71805. VK_FORMAT_ASTC_8x6_UNORM_BLOCK: Vn,
  71806. VK_FORMAT_ASTC_8x8_SFLOAT_BLOCK_EXT: di,
  71807. VK_FORMAT_ASTC_8x8_SRGB_BLOCK: Pn,
  71808. VK_FORMAT_ASTC_8x8_UNORM_BLOCK: Fn,
  71809. VK_FORMAT_B10G11R11_UFLOAT_PACK32: Me,
  71810. VK_FORMAT_B10X6G10X6R10X6G10X6_422_UNORM_4PACK16: $n,
  71811. VK_FORMAT_B12X4G12X4R12X4G12X4_422_UNORM_4PACK16: si,
  71812. VK_FORMAT_B4G4R4A4_UNORM_PACK16: at,
  71813. VK_FORMAT_B5G5R5A1_UNORM_PACK16: ft,
  71814. VK_FORMAT_B5G6R5_UNORM_PACK16: ot,
  71815. VK_FORMAT_B8G8R8A8_SINT: Mt,
  71816. VK_FORMAT_B8G8R8A8_SNORM: Ct,
  71817. VK_FORMAT_B8G8R8A8_SRGB: Wt,
  71818. VK_FORMAT_B8G8R8A8_UINT: zt,
  71819. VK_FORMAT_B8G8R8A8_UNORM: Pt,
  71820. VK_FORMAT_B8G8R8_SINT: St,
  71821. VK_FORMAT_B8G8R8_SNORM: kt,
  71822. VK_FORMAT_B8G8R8_SRGB: It,
  71823. VK_FORMAT_B8G8R8_UINT: vt,
  71824. VK_FORMAT_B8G8R8_UNORM: At,
  71825. VK_FORMAT_BC1_RGBA_SRGB_BLOCK: Qe,
  71826. VK_FORMAT_BC1_RGBA_UNORM_BLOCK: Je,
  71827. VK_FORMAT_BC1_RGB_SRGB_BLOCK: Ge,
  71828. VK_FORMAT_BC1_RGB_UNORM_BLOCK: qe,
  71829. VK_FORMAT_BC2_SRGB_BLOCK: $e,
  71830. VK_FORMAT_BC2_UNORM_BLOCK: Ze,
  71831. VK_FORMAT_BC3_SRGB_BLOCK: en,
  71832. VK_FORMAT_BC3_UNORM_BLOCK: tn,
  71833. VK_FORMAT_BC4_SNORM_BLOCK: sn,
  71834. VK_FORMAT_BC4_UNORM_BLOCK: nn,
  71835. VK_FORMAT_BC5_SNORM_BLOCK: rn,
  71836. VK_FORMAT_BC5_UNORM_BLOCK: an,
  71837. VK_FORMAT_BC6H_SFLOAT_BLOCK: ln,
  71838. VK_FORMAT_BC6H_UFLOAT_BLOCK: on,
  71839. VK_FORMAT_BC7_SRGB_BLOCK: Un,
  71840. VK_FORMAT_BC7_UNORM_BLOCK: fn,
  71841. VK_FORMAT_D16_UNORM: Ne,
  71842. VK_FORMAT_D16_UNORM_S8_UINT: je,
  71843. VK_FORMAT_D24_UNORM_S8_UINT: Re,
  71844. VK_FORMAT_D32_SFLOAT: Ke,
  71845. VK_FORMAT_D32_SFLOAT_S8_UINT: Ye,
  71846. VK_FORMAT_E5B9G9R9_UFLOAT_PACK32: We,
  71847. VK_FORMAT_EAC_R11G11_SNORM_BLOCK: dn,
  71848. VK_FORMAT_EAC_R11G11_UNORM_BLOCK: bn,
  71849. VK_FORMAT_EAC_R11_SNORM_BLOCK: un,
  71850. VK_FORMAT_EAC_R11_UNORM_BLOCK: xn,
  71851. VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: pn,
  71852. VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: _n,
  71853. VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: yn,
  71854. VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK: gn,
  71855. VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: hn,
  71856. VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: cn,
  71857. VK_FORMAT_G10X6B10X6G10X6R10X6_422_UNORM_4PACK16: Zn,
  71858. VK_FORMAT_G12X4B12X4G12X4R12X4_422_UNORM_4PACK16: ii,
  71859. VK_FORMAT_PVRTC1_2BPP_SRGB_BLOCK_IMG: fi,
  71860. VK_FORMAT_PVRTC1_2BPP_UNORM_BLOCK_IMG: ai,
  71861. VK_FORMAT_PVRTC1_4BPP_SRGB_BLOCK_IMG: Ui,
  71862. VK_FORMAT_PVRTC1_4BPP_UNORM_BLOCK_IMG: ri,
  71863. VK_FORMAT_PVRTC2_2BPP_SRGB_BLOCK_IMG: ci,
  71864. VK_FORMAT_PVRTC2_2BPP_UNORM_BLOCK_IMG: oi,
  71865. VK_FORMAT_PVRTC2_4BPP_SRGB_BLOCK_IMG: hi,
  71866. VK_FORMAT_PVRTC2_4BPP_UNORM_BLOCK_IMG: li,
  71867. VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16: Qn,
  71868. VK_FORMAT_R10X6G10X6_UNORM_2PACK16: Jn,
  71869. VK_FORMAT_R10X6_UNORM_PACK16: Gn,
  71870. VK_FORMAT_R12X4G12X4B12X4A12X4_UNORM_4PACK16: ni,
  71871. VK_FORMAT_R12X4G12X4_UNORM_2PACK16: ei,
  71872. VK_FORMAT_R12X4_UNORM_PACK16: ti,
  71873. VK_FORMAT_R16G16B16A16_SFLOAT: pe,
  71874. VK_FORMAT_R16G16B16A16_SINT: _e,
  71875. VK_FORMAT_R16G16B16A16_SNORM: ce,
  71876. VK_FORMAT_R16G16B16A16_UINT: he,
  71877. VK_FORMAT_R16G16B16A16_UNORM: Ue,
  71878. VK_FORMAT_R16G16B16_SFLOAT: fe,
  71879. VK_FORMAT_R16G16B16_SINT: le,
  71880. VK_FORMAT_R16G16B16_SNORM: re,
  71881. VK_FORMAT_R16G16B16_UINT: oe,
  71882. VK_FORMAT_R16G16B16_UNORM: ae,
  71883. VK_FORMAT_R16G16_SFLOAT: se,
  71884. VK_FORMAT_R16G16_SINT: ie,
  71885. VK_FORMAT_R16G16_SNORM: ee,
  71886. VK_FORMAT_R16G16_UINT: ne,
  71887. VK_FORMAT_R16G16_UNORM: te,
  71888. VK_FORMAT_R16_SFLOAT: $t,
  71889. VK_FORMAT_R16_SINT: Zt,
  71890. VK_FORMAT_R16_SNORM: Jt,
  71891. VK_FORMAT_R16_UINT: Qt,
  71892. VK_FORMAT_R16_UNORM: Gt,
  71893. VK_FORMAT_R32G32B32A32_SFLOAT: Ae,
  71894. VK_FORMAT_R32G32B32A32_SINT: Le,
  71895. VK_FORMAT_R32G32B32A32_UINT: Be,
  71896. VK_FORMAT_R32G32B32_SFLOAT: De,
  71897. VK_FORMAT_R32G32B32_SINT: we,
  71898. VK_FORMAT_R32G32B32_UINT: me,
  71899. VK_FORMAT_R32G32_SFLOAT: de,
  71900. VK_FORMAT_R32G32_SINT: be,
  71901. VK_FORMAT_R32G32_UINT: ue,
  71902. VK_FORMAT_R32_SFLOAT: xe,
  71903. VK_FORMAT_R32_SINT: ye,
  71904. VK_FORMAT_R32_UINT: ge,
  71905. VK_FORMAT_R4G4B4A4_UNORM_PACK16: st,
  71906. VK_FORMAT_R4G4_UNORM_PACK8: it,
  71907. VK_FORMAT_R5G5B5A1_UNORM_PACK16: lt,
  71908. VK_FORMAT_R5G6B5_UNORM_PACK16: rt,
  71909. VK_FORMAT_R64G64B64A64_SFLOAT: ze,
  71910. VK_FORMAT_R64G64B64A64_SINT: Ce,
  71911. VK_FORMAT_R64G64B64A64_UINT: Pe,
  71912. VK_FORMAT_R64G64B64_SFLOAT: Fe,
  71913. VK_FORMAT_R64G64B64_SINT: Ee,
  71914. VK_FORMAT_R64G64B64_UINT: Ve,
  71915. VK_FORMAT_R64G64_SFLOAT: Te,
  71916. VK_FORMAT_R64G64_SINT: Oe,
  71917. VK_FORMAT_R64G64_UINT: Ie,
  71918. VK_FORMAT_R64_SFLOAT: Se,
  71919. VK_FORMAT_R64_SINT: ve,
  71920. VK_FORMAT_R64_UINT: ke,
  71921. VK_FORMAT_R8G8B8A8_SINT: Et,
  71922. VK_FORMAT_R8G8B8A8_SNORM: Tt,
  71923. VK_FORMAT_R8G8B8A8_SRGB: Ft,
  71924. VK_FORMAT_R8G8B8A8_UINT: Vt,
  71925. VK_FORMAT_R8G8B8A8_UNORM: Ot,
  71926. VK_FORMAT_R8G8B8_SINT: Bt,
  71927. VK_FORMAT_R8G8B8_SNORM: wt,
  71928. VK_FORMAT_R8G8B8_SRGB: Lt,
  71929. VK_FORMAT_R8G8B8_UINT: Dt,
  71930. VK_FORMAT_R8G8B8_UNORM: mt,
  71931. VK_FORMAT_R8G8_SINT: bt,
  71932. VK_FORMAT_R8G8_SNORM: xt,
  71933. VK_FORMAT_R8G8_SRGB: dt,
  71934. VK_FORMAT_R8G8_UINT: ut,
  71935. VK_FORMAT_R8G8_UNORM: yt,
  71936. VK_FORMAT_R8_SINT: pt,
  71937. VK_FORMAT_R8_SNORM: ht,
  71938. VK_FORMAT_R8_SRGB: gt,
  71939. VK_FORMAT_R8_UINT: _t,
  71940. VK_FORMAT_R8_UNORM: ct,
  71941. VK_FORMAT_S8_UINT: Xe,
  71942. VK_FORMAT_UNDEFINED: nt,
  71943. VK_FORMAT_X8_D24_UNORM_PACK32: He,
  71944. read: Pi,
  71945. write: Mi
  71946. });
  71947. /**
  71948. * Loader for KTX 2.0 GPU Texture containers.
  71949. *
  71950. * KTX 2.0 is a container format for various GPU texture formats. The loader
  71951. * supports Basis Universal GPU textures, which can be quickly transcoded to
  71952. * a wide variety of GPU texture compression formats, as well as some
  71953. * uncompressed DataTexture and Data3DTexture formats.
  71954. *
  71955. * References:
  71956. * - KTX: http://github.khronos.org/KTX-Specification/
  71957. * - DFD: https://www.khronos.org/registry/DataFormat/specs/1.3/dataformat.1.3.html#basicdescriptor
  71958. */
  71959. const {
  71960. read: read$1,
  71961. KHR_DF_FLAG_ALPHA_PREMULTIPLIED,
  71962. KHR_DF_TRANSFER_SRGB,
  71963. VK_FORMAT_UNDEFINED,
  71964. VK_FORMAT_R16_SFLOAT,
  71965. VK_FORMAT_R16G16_SFLOAT,
  71966. VK_FORMAT_R16G16B16A16_SFLOAT,
  71967. VK_FORMAT_R32_SFLOAT,
  71968. VK_FORMAT_R32G32_SFLOAT,
  71969. VK_FORMAT_R32G32B32A32_SFLOAT,
  71970. VK_FORMAT_R8_SRGB,
  71971. VK_FORMAT_R8_UNORM,
  71972. VK_FORMAT_R8G8_SRGB,
  71973. VK_FORMAT_R8G8_UNORM,
  71974. VK_FORMAT_R8G8B8A8_SRGB,
  71975. VK_FORMAT_R8G8B8A8_UNORM,
  71976. } = KTX; // eslint-disable-line no-undef
  71977. const _taskCache$1 = new WeakMap();
  71978. let _activeLoaders = 0;
  71979. class KTX2Loader extends Loader {
  71980. constructor( manager ) {
  71981. super( manager );
  71982. this.transcoderPath = '';
  71983. this.transcoderBinary = null;
  71984. this.transcoderPending = null;
  71985. this.workerPool = new WorkerPool$1();
  71986. this.workerSourceURL = '';
  71987. this.workerConfig = null;
  71988. if ( typeof MSC_TRANSCODER !== 'undefined' ) {
  71989. console.warn(
  71990. 'THREE.KTX2Loader: Please update to latest "basis_transcoder".'
  71991. + ' "msc_basis_transcoder" is no longer supported in three.js r125+.'
  71992. );
  71993. }
  71994. }
  71995. setTranscoderPath( path ) {
  71996. this.transcoderPath = path;
  71997. return this;
  71998. }
  71999. setWorkerLimit( num ) {
  72000. this.workerPool.setWorkerLimit( num );
  72001. return this;
  72002. }
  72003. detectSupport( renderer ) {
  72004. this.workerConfig = {
  72005. astcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_astc' ),
  72006. etc1Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc1' ),
  72007. etc2Supported: renderer.extensions.has( 'WEBGL_compressed_texture_etc' ),
  72008. dxtSupported: renderer.extensions.has( 'WEBGL_compressed_texture_s3tc' ),
  72009. bptcSupported: renderer.extensions.has( 'EXT_texture_compression_bptc' ),
  72010. pvrtcSupported: renderer.extensions.has( 'WEBGL_compressed_texture_pvrtc' )
  72011. || renderer.extensions.has( 'WEBKIT_WEBGL_compressed_texture_pvrtc' )
  72012. };
  72013. if ( renderer.capabilities.isWebGL2 ) {
  72014. // https://github.com/mrdoob/three.js/pull/22928
  72015. this.workerConfig.etc1Supported = false;
  72016. }
  72017. return this;
  72018. }
  72019. init() {
  72020. if ( ! this.transcoderPending ) {
  72021. // Load transcoder wrapper.
  72022. const jsLoader = new FileLoader( this.manager );
  72023. jsLoader.setPath( this.transcoderPath );
  72024. jsLoader.setWithCredentials( this.withCredentials );
  72025. const jsContent = jsLoader.loadAsync( 'basis_transcoder.js' );
  72026. // Load transcoder WASM binary.
  72027. const binaryLoader = new FileLoader( this.manager );
  72028. binaryLoader.setPath( this.transcoderPath );
  72029. binaryLoader.setResponseType( 'arraybuffer' );
  72030. binaryLoader.setWithCredentials( this.withCredentials );
  72031. const binaryContent = binaryLoader.loadAsync( 'basis_transcoder.wasm' );
  72032. this.transcoderPending = Promise.all( [ jsContent, binaryContent ] )
  72033. .then( ( [ jsContent, binaryContent ] ) => {
  72034. const fn = KTX2Loader.BasisWorker.toString();
  72035. const body = [
  72036. '/* constants */',
  72037. 'let _EngineFormat = ' + JSON.stringify( KTX2Loader.EngineFormat ),
  72038. 'let _TranscoderFormat = ' + JSON.stringify( KTX2Loader.TranscoderFormat ),
  72039. 'let _BasisFormat = ' + JSON.stringify( KTX2Loader.BasisFormat ),
  72040. '/* basis_transcoder.js */',
  72041. jsContent,
  72042. '/* worker */',
  72043. fn.substring( fn.indexOf( '{' ) + 1, fn.lastIndexOf( '}' ) )
  72044. ].join( '\n' );
  72045. this.workerSourceURL = URL.createObjectURL( new Blob( [ body ] ) );
  72046. this.transcoderBinary = binaryContent;
  72047. this.workerPool.setWorkerCreator( () => {
  72048. const worker = new Worker( this.workerSourceURL );
  72049. const transcoderBinary = this.transcoderBinary.slice( 0 );
  72050. worker.postMessage( { type: 'init', config: this.workerConfig, transcoderBinary }, [ transcoderBinary ] );
  72051. return worker;
  72052. } );
  72053. } );
  72054. if ( _activeLoaders > 0 ) {
  72055. // Each instance loads a transcoder and allocates workers, increasing network and memory cost.
  72056. console.warn(
  72057. 'THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues.'
  72058. + ' Use a single KTX2Loader instance, or call .dispose() on old instances.'
  72059. );
  72060. }
  72061. _activeLoaders ++;
  72062. }
  72063. return this.transcoderPending;
  72064. }
  72065. load( url, onLoad, onProgress, onError ) {
  72066. if ( this.workerConfig === null ) {
  72067. throw new Error( 'THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.' );
  72068. }
  72069. const loader = new FileLoader( this.manager );
  72070. loader.setResponseType( 'arraybuffer' );
  72071. loader.setWithCredentials( this.withCredentials );
  72072. loader.load( url, ( buffer ) => {
  72073. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  72074. // again from this thread.
  72075. if ( _taskCache$1.has( buffer ) ) {
  72076. const cachedTask = _taskCache$1.get( buffer );
  72077. return cachedTask.promise.then( onLoad ).catch( onError );
  72078. }
  72079. this._createTexture( buffer )
  72080. .then( ( texture ) => onLoad ? onLoad( texture ) : null )
  72081. .catch( onError );
  72082. }, onProgress, onError );
  72083. }
  72084. _createTextureFrom( transcodeResult ) {
  72085. const { mipmaps, width, height, format, type, error, dfdTransferFn, dfdFlags } = transcodeResult;
  72086. if ( type === 'error' ) return Promise.reject( error );
  72087. const texture = new CompressedTexture( mipmaps, width, height, format, UnsignedByteType );
  72088. texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter;
  72089. texture.magFilter = LinearFilter;
  72090. texture.generateMipmaps = false;
  72091. texture.needsUpdate = true;
  72092. texture.encoding = dfdTransferFn === KHR_DF_TRANSFER_SRGB ? sRGBEncoding : LinearEncoding;
  72093. texture.premultiplyAlpha = !! ( dfdFlags & KHR_DF_FLAG_ALPHA_PREMULTIPLIED );
  72094. return texture;
  72095. }
  72096. /**
  72097. * @param {ArrayBuffer} buffer
  72098. * @param {object?} config
  72099. * @return {Promise<CompressedTexture|DataTexture|Data3DTexture>}
  72100. */
  72101. _createTexture( buffer, config = {} ) {
  72102. const container = read$1( new Uint8Array( buffer ) );
  72103. if ( container.vkFormat !== VK_FORMAT_UNDEFINED ) {
  72104. return createDataTexture( container );
  72105. }
  72106. //
  72107. const taskConfig = config;
  72108. const texturePending = this.init().then( () => {
  72109. return this.workerPool.postMessage( { type: 'transcode', buffer, taskConfig: taskConfig }, [ buffer ] );
  72110. } ).then( ( e ) => this._createTextureFrom( e.data ) );
  72111. // Cache the task result.
  72112. _taskCache$1.set( buffer, { promise: texturePending } );
  72113. return texturePending;
  72114. }
  72115. dispose() {
  72116. this.workerPool.dispose();
  72117. if ( this.workerSourceURL ) URL.revokeObjectURL( this.workerSourceURL );
  72118. _activeLoaders --;
  72119. return this;
  72120. }
  72121. }
  72122. /* CONSTANTS */
  72123. KTX2Loader.BasisFormat = {
  72124. ETC1S: 0,
  72125. UASTC_4x4: 1,
  72126. };
  72127. KTX2Loader.TranscoderFormat = {
  72128. ETC1: 0,
  72129. ETC2: 1,
  72130. BC1: 2,
  72131. BC3: 3,
  72132. BC4: 4,
  72133. BC5: 5,
  72134. BC7_M6_OPAQUE_ONLY: 6,
  72135. BC7_M5: 7,
  72136. PVRTC1_4_RGB: 8,
  72137. PVRTC1_4_RGBA: 9,
  72138. ASTC_4x4: 10,
  72139. ATC_RGB: 11,
  72140. ATC_RGBA_INTERPOLATED_ALPHA: 12,
  72141. RGBA32: 13,
  72142. RGB565: 14,
  72143. BGR565: 15,
  72144. RGBA4444: 16,
  72145. };
  72146. KTX2Loader.EngineFormat = {
  72147. RGBAFormat: RGBAFormat,
  72148. RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
  72149. RGBA_BPTC_Format: RGBA_BPTC_Format,
  72150. RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
  72151. RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
  72152. RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format$1,
  72153. RGB_ETC1_Format: RGB_ETC1_Format,
  72154. RGB_ETC2_Format: RGB_ETC2_Format,
  72155. RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
  72156. RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format,
  72157. };
  72158. /* WEB WORKER */
  72159. KTX2Loader.BasisWorker = function () {
  72160. let config;
  72161. let transcoderPending;
  72162. let BasisModule;
  72163. const EngineFormat = _EngineFormat; // eslint-disable-line no-undef
  72164. const TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef
  72165. const BasisFormat = _BasisFormat; // eslint-disable-line no-undef
  72166. self.addEventListener( 'message', function ( e ) {
  72167. const message = e.data;
  72168. switch ( message.type ) {
  72169. case 'init':
  72170. config = message.config;
  72171. init( message.transcoderBinary );
  72172. break;
  72173. case 'transcode':
  72174. transcoderPending.then( () => {
  72175. try {
  72176. const { width, height, hasAlpha, mipmaps, format, dfdTransferFn, dfdFlags } = transcode( message.buffer );
  72177. const buffers = [];
  72178. for ( let i = 0; i < mipmaps.length; ++ i ) {
  72179. buffers.push( mipmaps[ i ].data.buffer );
  72180. }
  72181. self.postMessage( { type: 'transcode', id: message.id, width, height, hasAlpha, mipmaps, format, dfdTransferFn, dfdFlags }, buffers );
  72182. } catch ( error ) {
  72183. console.error( error );
  72184. self.postMessage( { type: 'error', id: message.id, error: error.message } );
  72185. }
  72186. } );
  72187. break;
  72188. }
  72189. } );
  72190. function init( wasmBinary ) {
  72191. transcoderPending = new Promise( ( resolve ) => {
  72192. BasisModule = { wasmBinary, onRuntimeInitialized: resolve };
  72193. BASIS( BasisModule ); // eslint-disable-line no-undef
  72194. } ).then( () => {
  72195. BasisModule.initializeBasis();
  72196. if ( BasisModule.KTX2File === undefined ) {
  72197. console.warn( 'THREE.KTX2Loader: Please update Basis Universal transcoder.' );
  72198. }
  72199. } );
  72200. }
  72201. function transcode( buffer ) {
  72202. const ktx2File = new BasisModule.KTX2File( new Uint8Array( buffer ) );
  72203. function cleanup() {
  72204. ktx2File.close();
  72205. ktx2File.delete();
  72206. }
  72207. if ( ! ktx2File.isValid() ) {
  72208. cleanup();
  72209. throw new Error( 'THREE.KTX2Loader: Invalid or unsupported .ktx2 file' );
  72210. }
  72211. const basisFormat = ktx2File.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S;
  72212. const width = ktx2File.getWidth();
  72213. const height = ktx2File.getHeight();
  72214. const levels = ktx2File.getLevels();
  72215. const hasAlpha = ktx2File.getHasAlpha();
  72216. const dfdTransferFn = ktx2File.getDFDTransferFunc();
  72217. const dfdFlags = ktx2File.getDFDFlags();
  72218. const { transcoderFormat, engineFormat } = getTranscoderFormat( basisFormat, width, height, hasAlpha );
  72219. if ( ! width || ! height || ! levels ) {
  72220. cleanup();
  72221. throw new Error( 'THREE.KTX2Loader: Invalid texture' );
  72222. }
  72223. if ( ! ktx2File.startTranscoding() ) {
  72224. cleanup();
  72225. throw new Error( 'THREE.KTX2Loader: .startTranscoding failed' );
  72226. }
  72227. const mipmaps = [];
  72228. for ( let mip = 0; mip < levels; mip ++ ) {
  72229. const levelInfo = ktx2File.getImageLevelInfo( mip, 0, 0 );
  72230. const mipWidth = levelInfo.origWidth;
  72231. const mipHeight = levelInfo.origHeight;
  72232. const dst = new Uint8Array( ktx2File.getImageTranscodedSizeInBytes( mip, 0, 0, transcoderFormat ) );
  72233. const status = ktx2File.transcodeImage(
  72234. dst,
  72235. mip,
  72236. 0,
  72237. 0,
  72238. transcoderFormat,
  72239. 0,
  72240. - 1,
  72241. - 1,
  72242. );
  72243. if ( ! status ) {
  72244. cleanup();
  72245. throw new Error( 'THREE.KTX2Loader: .transcodeImage failed.' );
  72246. }
  72247. mipmaps.push( { data: dst, width: mipWidth, height: mipHeight } );
  72248. }
  72249. cleanup();
  72250. return { width, height, hasAlpha, mipmaps, format: engineFormat, dfdTransferFn, dfdFlags };
  72251. }
  72252. //
  72253. // Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC),
  72254. // device capabilities, and texture dimensions. The list below ranks the formats separately
  72255. // for ETC1S and UASTC.
  72256. //
  72257. // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at
  72258. // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently
  72259. // chooses RGBA32 only as a last resort and does not expose that option to the caller.
  72260. const FORMAT_OPTIONS = [
  72261. {
  72262. if: 'astcSupported',
  72263. basisFormat: [ BasisFormat.UASTC_4x4 ],
  72264. transcoderFormat: [ TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4 ],
  72265. engineFormat: [ EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format ],
  72266. priorityETC1S: Infinity,
  72267. priorityUASTC: 1,
  72268. needsPowerOfTwo: false,
  72269. },
  72270. {
  72271. if: 'bptcSupported',
  72272. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  72273. transcoderFormat: [ TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5 ],
  72274. engineFormat: [ EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format ],
  72275. priorityETC1S: 3,
  72276. priorityUASTC: 2,
  72277. needsPowerOfTwo: false,
  72278. },
  72279. {
  72280. if: 'dxtSupported',
  72281. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  72282. transcoderFormat: [ TranscoderFormat.BC1, TranscoderFormat.BC3 ],
  72283. engineFormat: [ EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format ],
  72284. priorityETC1S: 4,
  72285. priorityUASTC: 5,
  72286. needsPowerOfTwo: false,
  72287. },
  72288. {
  72289. if: 'etc2Supported',
  72290. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  72291. transcoderFormat: [ TranscoderFormat.ETC1, TranscoderFormat.ETC2 ],
  72292. engineFormat: [ EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format ],
  72293. priorityETC1S: 1,
  72294. priorityUASTC: 3,
  72295. needsPowerOfTwo: false,
  72296. },
  72297. {
  72298. if: 'etc1Supported',
  72299. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  72300. transcoderFormat: [ TranscoderFormat.ETC1 ],
  72301. engineFormat: [ EngineFormat.RGB_ETC1_Format ],
  72302. priorityETC1S: 2,
  72303. priorityUASTC: 4,
  72304. needsPowerOfTwo: false,
  72305. },
  72306. {
  72307. if: 'pvrtcSupported',
  72308. basisFormat: [ BasisFormat.ETC1S, BasisFormat.UASTC_4x4 ],
  72309. transcoderFormat: [ TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA ],
  72310. engineFormat: [ EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format ],
  72311. priorityETC1S: 5,
  72312. priorityUASTC: 6,
  72313. needsPowerOfTwo: true,
  72314. },
  72315. ];
  72316. const ETC1S_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  72317. return a.priorityETC1S - b.priorityETC1S;
  72318. } );
  72319. const UASTC_OPTIONS = FORMAT_OPTIONS.sort( function ( a, b ) {
  72320. return a.priorityUASTC - b.priorityUASTC;
  72321. } );
  72322. function getTranscoderFormat( basisFormat, width, height, hasAlpha ) {
  72323. let transcoderFormat;
  72324. let engineFormat;
  72325. const options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS;
  72326. for ( let i = 0; i < options.length; i ++ ) {
  72327. const opt = options[ i ];
  72328. if ( ! config[ opt.if ] ) continue;
  72329. if ( ! opt.basisFormat.includes( basisFormat ) ) continue;
  72330. if ( hasAlpha && opt.transcoderFormat.length < 2 ) continue;
  72331. if ( opt.needsPowerOfTwo && ! ( isPowerOfTwo( width ) && isPowerOfTwo( height ) ) ) continue;
  72332. transcoderFormat = opt.transcoderFormat[ hasAlpha ? 1 : 0 ];
  72333. engineFormat = opt.engineFormat[ hasAlpha ? 1 : 0 ];
  72334. return { transcoderFormat, engineFormat };
  72335. }
  72336. console.warn( 'THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32.' );
  72337. transcoderFormat = TranscoderFormat.RGBA32;
  72338. engineFormat = EngineFormat.RGBAFormat;
  72339. return { transcoderFormat, engineFormat };
  72340. }
  72341. function isPowerOfTwo( value ) {
  72342. if ( value <= 2 ) return true;
  72343. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  72344. }
  72345. };
  72346. //
  72347. // DataTexture and Data3DTexture parsing.
  72348. const FORMAT_MAP = {
  72349. [ VK_FORMAT_R32G32B32A32_SFLOAT ]: RGBAFormat,
  72350. [ VK_FORMAT_R16G16B16A16_SFLOAT ]: RGBAFormat,
  72351. [ VK_FORMAT_R8G8B8A8_UNORM ]: RGBAFormat,
  72352. [ VK_FORMAT_R8G8B8A8_SRGB ]: RGBAFormat,
  72353. [ VK_FORMAT_R32G32_SFLOAT ]: RGFormat,
  72354. [ VK_FORMAT_R16G16_SFLOAT ]: RGFormat,
  72355. [ VK_FORMAT_R8G8_UNORM ]: RGFormat,
  72356. [ VK_FORMAT_R8G8_SRGB ]: RGFormat,
  72357. [ VK_FORMAT_R32_SFLOAT ]: RedFormat,
  72358. [ VK_FORMAT_R16_SFLOAT ]: RedFormat,
  72359. [ VK_FORMAT_R8_SRGB ]: RedFormat,
  72360. [ VK_FORMAT_R8_UNORM ]: RedFormat,
  72361. };
  72362. const TYPE_MAP = {
  72363. [ VK_FORMAT_R32G32B32A32_SFLOAT ]: FloatType,
  72364. [ VK_FORMAT_R16G16B16A16_SFLOAT ]: HalfFloatType,
  72365. [ VK_FORMAT_R8G8B8A8_UNORM ]: UnsignedByteType,
  72366. [ VK_FORMAT_R8G8B8A8_SRGB ]: UnsignedByteType,
  72367. [ VK_FORMAT_R32G32_SFLOAT ]: FloatType,
  72368. [ VK_FORMAT_R16G16_SFLOAT ]: HalfFloatType,
  72369. [ VK_FORMAT_R8G8_UNORM ]: UnsignedByteType,
  72370. [ VK_FORMAT_R8G8_SRGB ]: UnsignedByteType,
  72371. [ VK_FORMAT_R32_SFLOAT ]: FloatType,
  72372. [ VK_FORMAT_R16_SFLOAT ]: HalfFloatType,
  72373. [ VK_FORMAT_R8_SRGB ]: UnsignedByteType,
  72374. [ VK_FORMAT_R8_UNORM ]: UnsignedByteType,
  72375. };
  72376. const ENCODING_MAP = {
  72377. [ VK_FORMAT_R8G8B8A8_SRGB ]: sRGBEncoding,
  72378. [ VK_FORMAT_R8G8_SRGB ]: sRGBEncoding,
  72379. [ VK_FORMAT_R8_SRGB ]: sRGBEncoding,
  72380. };
  72381. function createDataTexture( container ) {
  72382. const { vkFormat, pixelWidth, pixelHeight, pixelDepth } = container;
  72383. if ( FORMAT_MAP[ vkFormat ] === undefined ) {
  72384. throw new Error( 'THREE.KTX2Loader: Unsupported vkFormat.' );
  72385. }
  72386. //
  72387. let view;
  72388. const levelData = container.levels[ 0 ].levelData;
  72389. if ( TYPE_MAP[ vkFormat ] === FloatType ) {
  72390. view = new Float32Array(
  72391. levelData.buffer,
  72392. levelData.byteOffset,
  72393. levelData.byteLength / Float32Array.BYTES_PER_ELEMENT
  72394. );
  72395. } else if ( TYPE_MAP[ vkFormat ] === HalfFloatType ) {
  72396. view = new Uint16Array(
  72397. levelData.buffer,
  72398. levelData.byteOffset,
  72399. levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT
  72400. );
  72401. } else {
  72402. view = levelData;
  72403. }
  72404. //
  72405. const texture = pixelDepth === 0
  72406. ? new DataTexture( view, pixelWidth, pixelHeight )
  72407. : new Data3DTexture( view, pixelWidth, pixelHeight, pixelDepth );
  72408. texture.type = TYPE_MAP[ vkFormat ];
  72409. texture.format = FORMAT_MAP[ vkFormat ];
  72410. texture.encoding = ENCODING_MAP[ vkFormat ] || LinearEncoding;
  72411. texture.needsUpdate = true;
  72412. //
  72413. return Promise.resolve( texture );
  72414. }
  72415. // This file is part of meshoptimizer library and is distributed under the terms of MIT License.
  72416. // Copyright (C) 2016-2020, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
  72417. var MeshoptDecoder = (function() {
  72418. "use strict";
  72419. // Built with clang version 11.0.0 (https://github.com/llvm/llvm-project.git 0160ad802e899c2922bc9b29564080c22eb0908c)
  72420. // Built from meshoptimizer 0.14
  72421. 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";
  72422. 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";
  72423. // Uses bulk-memory and simd extensions
  72424. 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]);
  72425. // Used to unpack wasm
  72426. 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]);
  72427. if (typeof WebAssembly !== 'object') {
  72428. // This module requires WebAssembly to function
  72429. return {
  72430. supported: false,
  72431. };
  72432. }
  72433. var wasm = wasm_base;
  72434. if (WebAssembly.validate(detector)) {
  72435. wasm = wasm_simd;
  72436. console.log("Warning: meshopt_decoder is using experimental SIMD support");
  72437. }
  72438. var instance;
  72439. var promise =
  72440. WebAssembly.instantiate(unpack(wasm), {})
  72441. .then(function(result) {
  72442. instance = result.instance;
  72443. instance.exports.__wasm_call_ctors();
  72444. });
  72445. function unpack(data) {
  72446. var result = new Uint8Array(data.length);
  72447. for (var i = 0; i < data.length; ++i) {
  72448. var ch = data.charCodeAt(i);
  72449. result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
  72450. }
  72451. var write = 0;
  72452. for (var i = 0; i < data.length; ++i) {
  72453. result[write++] = (result[i] < 60) ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
  72454. }
  72455. return result.buffer.slice(0, write);
  72456. }
  72457. function decode(fun, target, count, size, source, filter) {
  72458. var sbrk = instance.exports.sbrk;
  72459. var count4 = (count + 3) & ~3; // pad for SIMD filter
  72460. var tp = sbrk(count4 * size);
  72461. var sp = sbrk(source.length);
  72462. var heap = new Uint8Array(instance.exports.memory.buffer);
  72463. heap.set(source, sp);
  72464. var res = fun(tp, count, size, sp, source.length);
  72465. if (res == 0 && filter) {
  72466. filter(tp, count4, size);
  72467. }
  72468. target.set(heap.subarray(tp, tp + count * size));
  72469. sbrk(tp - sbrk(0));
  72470. if (res != 0) {
  72471. throw new Error("Malformed buffer data: " + res);
  72472. }
  72473. };
  72474. var filters = {
  72475. // legacy index-based enums for glTF
  72476. 0: "",
  72477. 1: "meshopt_decodeFilterOct",
  72478. 2: "meshopt_decodeFilterQuat",
  72479. 3: "meshopt_decodeFilterExp",
  72480. // string-based enums for glTF
  72481. NONE: "",
  72482. OCTAHEDRAL: "meshopt_decodeFilterOct",
  72483. QUATERNION: "meshopt_decodeFilterQuat",
  72484. EXPONENTIAL: "meshopt_decodeFilterExp",
  72485. };
  72486. var decoders = {
  72487. // legacy index-based enums for glTF
  72488. 0: "meshopt_decodeVertexBuffer",
  72489. 1: "meshopt_decodeIndexBuffer",
  72490. 2: "meshopt_decodeIndexSequence",
  72491. // string-based enums for glTF
  72492. ATTRIBUTES: "meshopt_decodeVertexBuffer",
  72493. TRIANGLES: "meshopt_decodeIndexBuffer",
  72494. INDICES: "meshopt_decodeIndexSequence",
  72495. };
  72496. return {
  72497. ready: promise,
  72498. supported: true,
  72499. decodeVertexBuffer: function(target, count, size, source, filter) {
  72500. decode(instance.exports.meshopt_decodeVertexBuffer, target, count, size, source, instance.exports[filters[filter]]);
  72501. },
  72502. decodeIndexBuffer: function(target, count, size, source) {
  72503. decode(instance.exports.meshopt_decodeIndexBuffer, target, count, size, source);
  72504. },
  72505. decodeIndexSequence: function(target, count, size, source) {
  72506. decode(instance.exports.meshopt_decodeIndexSequence, target, count, size, source);
  72507. },
  72508. decodeGltfBuffer: function(target, count, size, source, mode, filter) {
  72509. decode(instance.exports[decoders[mode]], target, count, size, source, instance.exports[filters[filter]]);
  72510. }
  72511. };
  72512. })();
  72513. var DDSLoader = function ( manager ) {
  72514. CompressedTextureLoader.call( this, manager );
  72515. };
  72516. DDSLoader.prototype = Object.assign( Object.create( CompressedTextureLoader.prototype ), {
  72517. constructor: DDSLoader,
  72518. parse: function ( buffer, loadMipmaps ) {
  72519. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  72520. // Adapted from @toji's DDS utils
  72521. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  72522. // All values and structures referenced from:
  72523. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  72524. var DDS_MAGIC = 0x20534444;
  72525. // var DDSD_CAPS = 0x1;
  72526. // var DDSD_HEIGHT = 0x2;
  72527. // var DDSD_WIDTH = 0x4;
  72528. // var DDSD_PITCH = 0x8;
  72529. // var DDSD_PIXELFORMAT = 0x1000;
  72530. var DDSD_MIPMAPCOUNT = 0x20000;
  72531. // var DDSD_LINEARSIZE = 0x80000;
  72532. // var DDSD_DEPTH = 0x800000;
  72533. // var DDSCAPS_COMPLEX = 0x8;
  72534. // var DDSCAPS_MIPMAP = 0x400000;
  72535. // var DDSCAPS_TEXTURE = 0x1000;
  72536. var DDSCAPS2_CUBEMAP = 0x200;
  72537. var DDSCAPS2_CUBEMAP_POSITIVEX = 0x400;
  72538. var DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800;
  72539. var DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000;
  72540. var DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000;
  72541. var DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000;
  72542. var DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000;
  72543. // var DDSCAPS2_VOLUME = 0x200000;
  72544. // var DDPF_ALPHAPIXELS = 0x1;
  72545. // var DDPF_ALPHA = 0x2;
  72546. var DDPF_FOURCC = 0x4;
  72547. // var DDPF_RGB = 0x40;
  72548. // var DDPF_YUV = 0x200;
  72549. // var DDPF_LUMINANCE = 0x20000;
  72550. function fourCCToInt32( value ) {
  72551. return value.charCodeAt( 0 ) +
  72552. ( value.charCodeAt( 1 ) << 8 ) +
  72553. ( value.charCodeAt( 2 ) << 16 ) +
  72554. ( value.charCodeAt( 3 ) << 24 );
  72555. }
  72556. function int32ToFourCC( value ) {
  72557. return String.fromCharCode(
  72558. value & 0xff,
  72559. ( value >> 8 ) & 0xff,
  72560. ( value >> 16 ) & 0xff,
  72561. ( value >> 24 ) & 0xff
  72562. );
  72563. }
  72564. function loadARGBMip( buffer, dataOffset, width, height ) {
  72565. var dataLength = width * height * 4;
  72566. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  72567. var byteArray = new Uint8Array( dataLength );
  72568. var dst = 0;
  72569. var src = 0;
  72570. for ( var y = 0; y < height; y ++ ) {
  72571. for ( var x = 0; x < width; x ++ ) {
  72572. var b = srcBuffer[ src ]; src ++;
  72573. var g = srcBuffer[ src ]; src ++;
  72574. var r = srcBuffer[ src ]; src ++;
  72575. var a = srcBuffer[ src ]; src ++;
  72576. byteArray[ dst ] = r; dst ++; //r
  72577. byteArray[ dst ] = g; dst ++; //g
  72578. byteArray[ dst ] = b; dst ++; //b
  72579. byteArray[ dst ] = a; dst ++; //a
  72580. }
  72581. }
  72582. return byteArray;
  72583. }
  72584. var FOURCC_DXT1 = fourCCToInt32( 'DXT1' );
  72585. var FOURCC_DXT3 = fourCCToInt32( 'DXT3' );
  72586. var FOURCC_DXT5 = fourCCToInt32( 'DXT5' );
  72587. var FOURCC_ETC1 = fourCCToInt32( 'ETC1' );
  72588. var headerLengthInt = 31; // The header length in 32 bit ints
  72589. // Offsets into the header array
  72590. var off_magic = 0;
  72591. var off_size = 1;
  72592. var off_flags = 2;
  72593. var off_height = 3;
  72594. var off_width = 4;
  72595. var off_mipmapCount = 7;
  72596. var off_pfFlags = 20;
  72597. var off_pfFourCC = 21;
  72598. var off_RGBBitCount = 22;
  72599. var off_RBitMask = 23;
  72600. var off_GBitMask = 24;
  72601. var off_BBitMask = 25;
  72602. var off_ABitMask = 26;
  72603. // var off_caps = 27;
  72604. var off_caps2 = 28;
  72605. // var off_caps3 = 29;
  72606. // var off_caps4 = 30;
  72607. // Parse header
  72608. var header = new Int32Array( buffer, 0, headerLengthInt );
  72609. if ( header[ off_magic ] !== DDS_MAGIC ) {
  72610. console.error( 'THREE.DDSLoader.parse: Invalid magic number in DDS header.' );
  72611. return dds;
  72612. }
  72613. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  72614. console.error( 'THREE.DDSLoader.parse: Unsupported format, must contain a FourCC code.' );
  72615. return dds;
  72616. }
  72617. var blockBytes;
  72618. var fourCC = header[ off_pfFourCC ];
  72619. var isRGBAUncompressed = false;
  72620. switch ( fourCC ) {
  72621. case FOURCC_DXT1:
  72622. blockBytes = 8;
  72623. dds.format = RGB_S3TC_DXT1_Format;
  72624. break;
  72625. case FOURCC_DXT3:
  72626. blockBytes = 16;
  72627. dds.format = RGBA_S3TC_DXT3_Format;
  72628. break;
  72629. case FOURCC_DXT5:
  72630. blockBytes = 16;
  72631. dds.format = RGBA_S3TC_DXT5_Format$1;
  72632. break;
  72633. case FOURCC_ETC1:
  72634. blockBytes = 8;
  72635. dds.format = RGB_ETC1_Format;
  72636. break;
  72637. default:
  72638. if ( header[ off_RGBBitCount ] === 32
  72639. && header[ off_RBitMask ] & 0xff0000
  72640. && header[ off_GBitMask ] & 0xff00
  72641. && header[ off_BBitMask ] & 0xff
  72642. && header[ off_ABitMask ] & 0xff000000 ) {
  72643. isRGBAUncompressed = true;
  72644. blockBytes = 64;
  72645. dds.format = RGBAFormat;
  72646. } else {
  72647. console.error( 'THREE.DDSLoader.parse: Unsupported FourCC code ', int32ToFourCC( fourCC ) );
  72648. return dds;
  72649. }
  72650. }
  72651. dds.mipmapCount = 1;
  72652. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  72653. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  72654. }
  72655. var caps2 = header[ off_caps2 ];
  72656. dds.isCubemap = caps2 & DDSCAPS2_CUBEMAP ? true : false;
  72657. if ( dds.isCubemap && (
  72658. ! ( caps2 & DDSCAPS2_CUBEMAP_POSITIVEX ) ||
  72659. ! ( caps2 & DDSCAPS2_CUBEMAP_NEGATIVEX ) ||
  72660. ! ( caps2 & DDSCAPS2_CUBEMAP_POSITIVEY ) ||
  72661. ! ( caps2 & DDSCAPS2_CUBEMAP_NEGATIVEY ) ||
  72662. ! ( caps2 & DDSCAPS2_CUBEMAP_POSITIVEZ ) ||
  72663. ! ( caps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ )
  72664. ) ) {
  72665. console.error( 'THREE.DDSLoader.parse: Incomplete cubemap faces' );
  72666. return dds;
  72667. }
  72668. dds.width = header[ off_width ];
  72669. dds.height = header[ off_height ];
  72670. var dataOffset = header[ off_size ] + 4;
  72671. // Extract mipmaps buffers
  72672. var faces = dds.isCubemap ? 6 : 1;
  72673. for ( var face = 0; face < faces; face ++ ) {
  72674. var width = dds.width;
  72675. var height = dds.height;
  72676. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  72677. if ( isRGBAUncompressed ) {
  72678. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  72679. var dataLength = byteArray.length;
  72680. } else {
  72681. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  72682. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  72683. }
  72684. var mipmap = { 'data': byteArray, 'width': width, 'height': height };
  72685. dds.mipmaps.push( mipmap );
  72686. dataOffset += dataLength;
  72687. width = Math.max( width >> 1, 1 );
  72688. height = Math.max( height >> 1, 1 );
  72689. }
  72690. }
  72691. return dds;
  72692. }
  72693. } );
  72694. var GLTFLoader = ( function () {
  72695. function GLTFLoader( manager, renderer, urlPrefix) {
  72696. Loader.call( this, manager );
  72697. /* this.dracoLoader = null;
  72698. this.ddsLoader = null;
  72699. this.ktx2Loader = null;
  72700. this.meshoptDecoder = null; */
  72701. //xzw add:
  72702. this.dracoLoader = new DRACOLoader;
  72703. this.ktx2Loader = new KTX2Loader;
  72704. this.meshoptDecoder = MeshoptDecoder;
  72705. this.ddsLoader = new DDSLoader; //这个没测过
  72706. //路径相对于index.html
  72707. this.dracoLoader.setDecoderPath( urlPrefix + 'three.js/loaders/draco/' /* '../libs/three.js/loaders/draco/' */ /* 'static/lib/three.js/loaders/draco/' */); //这两个路径可以自己改。在laser的环境也要放一份这个路径
  72708. this.ktx2Loader.setTranscoderPath(urlPrefix + 'three.js/loaders/ktx/' /* '../libs/three.js/loaders/ktx/' */ /* 'static/lib/three.js/loaders/ktx/' */ ).detectSupport( renderer );
  72709. //------------
  72710. this.pluginCallbacks = [];
  72711. this.register( function ( parser ) {
  72712. return new GLTFMaterialsClearcoatExtension( parser );
  72713. } );
  72714. this.register( function ( parser ) {
  72715. return new GLTFTextureBasisUExtension( parser );
  72716. } );
  72717. this.register( function ( parser ) {
  72718. return new GLTFTextureWebPExtension( parser );
  72719. } );
  72720. this.register( function ( parser ) {
  72721. return new GLTFMaterialsTransmissionExtension( parser );
  72722. } );
  72723. this.register( function ( parser ) {
  72724. return new GLTFLightsExtension( parser );
  72725. } );
  72726. this.register( function ( parser ) {
  72727. return new GLTFMeshoptCompression( parser );
  72728. } );
  72729. }
  72730. GLTFLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  72731. constructor: GLTFLoader,
  72732. load: function ( url, onLoad, onProgress, onError ) {
  72733. var scope = this;
  72734. var resourcePath;
  72735. if ( this.resourcePath !== '' ) {
  72736. resourcePath = this.resourcePath;
  72737. } else if ( this.path !== '' ) {
  72738. resourcePath = this.path;
  72739. } else {
  72740. resourcePath = LoaderUtils.extractUrlBase( url );
  72741. }
  72742. // Tells the LoadingManager to track an extra item, which resolves after
  72743. // the model is fully loaded. This means the count of items loaded will
  72744. // be incorrect, but ensures manager.onLoad() does not fire early.
  72745. this.manager.itemStart( url );
  72746. var _onError = function ( e ) {
  72747. if ( onError ) {
  72748. onError( e );
  72749. } else {
  72750. console.error( e );
  72751. }
  72752. scope.manager.itemError( url );
  72753. scope.manager.itemEnd( url );
  72754. };
  72755. var loader = new FileLoader( this.manager );
  72756. loader.setPath( this.path );
  72757. loader.setResponseType( 'arraybuffer' );
  72758. loader.setRequestHeader( this.requestHeader );
  72759. loader.setWithCredentials( this.withCredentials );
  72760. loader.load( url, function ( data, total ) {// xzw add total
  72761. console.log('数据加载成功', url.split('/').pop(), ' ,total: '+total);
  72762. let f = ()=>{
  72763. try {
  72764. scope.parse( data, resourcePath, function ( gltf ) {
  72765. onLoad( gltf, total );
  72766. scope.manager.itemEnd( url );
  72767. }, _onError );
  72768. } catch ( e ) {
  72769. _onError( e );
  72770. }
  72771. };
  72772. f();
  72773. //setTimeout(f,5000)/////////////////test
  72774. }, onProgress, _onError );
  72775. },
  72776. setDRACOLoader: function ( dracoLoader ) {
  72777. this.dracoLoader = dracoLoader;
  72778. return this;
  72779. },
  72780. setDDSLoader: function ( ddsLoader ) {
  72781. this.ddsLoader = ddsLoader;
  72782. return this;
  72783. },
  72784. setKTX2Loader: function ( ktx2Loader ) {
  72785. this.ktx2Loader = ktx2Loader;
  72786. return this;
  72787. },
  72788. setMeshoptDecoder: function ( meshoptDecoder ) {
  72789. this.meshoptDecoder = meshoptDecoder;
  72790. return this;
  72791. },
  72792. register: function ( callback ) {
  72793. if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
  72794. this.pluginCallbacks.push( callback );
  72795. }
  72796. return this;
  72797. },
  72798. unregister: function ( callback ) {
  72799. if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
  72800. this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
  72801. }
  72802. return this;
  72803. },
  72804. parse: function ( data, path, onLoad, onError ) {
  72805. var content;
  72806. var extensions = {};
  72807. var plugins = {};
  72808. if ( typeof data === 'string' ) {
  72809. content = data;
  72810. } else {
  72811. var magic = LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  72812. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  72813. try {
  72814. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  72815. } catch ( error ) {
  72816. if ( onError ) onError( error );
  72817. return;
  72818. }
  72819. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  72820. } else {
  72821. content = LoaderUtils.decodeText( new Uint8Array( data ) );
  72822. }
  72823. }
  72824. var json = JSON.parse( content );
  72825. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  72826. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
  72827. return;
  72828. }
  72829. var parser = new GLTFParser( json, {
  72830. path: path || this.resourcePath || '',
  72831. crossOrigin: this.crossOrigin,
  72832. manager: this.manager,
  72833. ktx2Loader: this.ktx2Loader,
  72834. meshoptDecoder: this.meshoptDecoder,
  72835. } );
  72836. parser.unlitMat = this.unlitMat;//add
  72837. parser.fileLoader.setRequestHeader( this.requestHeader );
  72838. for ( var i = 0; i < this.pluginCallbacks.length; i ++ ) {
  72839. var plugin = this.pluginCallbacks[ i ]( parser );
  72840. plugins[ plugin.name ] = plugin;
  72841. // Workaround to avoid determining as unknown extension
  72842. // in addUnknownExtensionsToUserData().
  72843. // Remove this workaround if we move all the existing
  72844. // extension handlers to plugin system
  72845. extensions[ plugin.name ] = true;
  72846. }
  72847. if ( json.extensionsUsed ) {
  72848. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  72849. var extensionName = json.extensionsUsed[ i ];
  72850. var extensionsRequired = json.extensionsRequired || [];
  72851. switch ( extensionName ) {
  72852. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  72853. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  72854. break;
  72855. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  72856. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  72857. break;
  72858. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  72859. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  72860. break;
  72861. case EXTENSIONS.MSFT_TEXTURE_DDS:
  72862. extensions[ extensionName ] = new GLTFTextureDDSExtension( this.ddsLoader );
  72863. break;
  72864. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  72865. extensions[ extensionName ] = new GLTFTextureTransformExtension();
  72866. break;
  72867. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  72868. extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
  72869. break;
  72870. default:
  72871. if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {
  72872. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  72873. }
  72874. }
  72875. }
  72876. }
  72877. parser.setExtensions( extensions );
  72878. parser.setPlugins( plugins );
  72879. parser.parse( onLoad, onError );
  72880. }
  72881. } );
  72882. /* GLTFREGISTRY */
  72883. function GLTFRegistry() {
  72884. var objects = {};
  72885. return {
  72886. get: function ( key ) {
  72887. return objects[ key ];
  72888. },
  72889. add: function ( key, object ) {
  72890. objects[ key ] = object;
  72891. },
  72892. remove: function ( key ) {
  72893. delete objects[ key ];
  72894. },
  72895. removeAll: function () {
  72896. objects = {};
  72897. }
  72898. };
  72899. }
  72900. /*********************************/
  72901. /********** EXTENSIONS ***********/
  72902. /*********************************/
  72903. var EXTENSIONS = {
  72904. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  72905. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  72906. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  72907. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  72908. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  72909. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  72910. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  72911. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  72912. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  72913. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  72914. EXT_TEXTURE_WEBP: 'EXT_texture_webp',
  72915. EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
  72916. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  72917. };
  72918. /**
  72919. * DDS Texture Extension
  72920. *
  72921. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  72922. *
  72923. */
  72924. function GLTFTextureDDSExtension( ddsLoader ) {
  72925. if ( ! ddsLoader ) {
  72926. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader' );
  72927. }
  72928. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  72929. this.ddsLoader = ddsLoader;
  72930. }
  72931. /**
  72932. * Punctual Lights Extension
  72933. *
  72934. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  72935. */
  72936. function GLTFLightsExtension( parser ) {
  72937. this.parser = parser;
  72938. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  72939. // Object3D instance caches
  72940. this.cache = { refs: {}, uses: {} };
  72941. }
  72942. GLTFLightsExtension.prototype._markDefs = function () {
  72943. var parser = this.parser;
  72944. var nodeDefs = this.parser.json.nodes || [];
  72945. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  72946. var nodeDef = nodeDefs[ nodeIndex ];
  72947. if ( nodeDef.extensions
  72948. && nodeDef.extensions[ this.name ]
  72949. && nodeDef.extensions[ this.name ].light !== undefined ) {
  72950. parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light );
  72951. }
  72952. }
  72953. };
  72954. GLTFLightsExtension.prototype._loadLight = function ( lightIndex ) {
  72955. var parser = this.parser;
  72956. var cacheKey = 'light:' + lightIndex;
  72957. var dependency = parser.cache.get( cacheKey );
  72958. if ( dependency ) return dependency;
  72959. var json = parser.json;
  72960. var extensions = ( json.extensions && json.extensions[ this.name ] ) || {};
  72961. var lightDefs = extensions.lights || [];
  72962. var lightDef = lightDefs[ lightIndex ];
  72963. var lightNode;
  72964. var color = new Color( 0xffffff );
  72965. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  72966. var range = lightDef.range !== undefined ? lightDef.range : 0;
  72967. switch ( lightDef.type ) {
  72968. case 'directional':
  72969. lightNode = new DirectionalLight( color );
  72970. lightNode.target.position.set( 0, 0, - 1 );
  72971. lightNode.add( lightNode.target );
  72972. break;
  72973. case 'point':
  72974. lightNode = new PointLight( color );
  72975. lightNode.distance = range;
  72976. break;
  72977. case 'spot':
  72978. lightNode = new SpotLight( color );
  72979. lightNode.distance = range;
  72980. // Handle spotlight properties.
  72981. lightDef.spot = lightDef.spot || {};
  72982. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  72983. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  72984. lightNode.angle = lightDef.spot.outerConeAngle;
  72985. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  72986. lightNode.target.position.set( 0, 0, - 1 );
  72987. lightNode.add( lightNode.target );
  72988. break;
  72989. default:
  72990. throw new Error( 'THREE.GLTFLoader: Unexpected light type: ' + lightDef.type );
  72991. }
  72992. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  72993. // here, because node-level parsing will only override position if explicitly specified.
  72994. lightNode.position.set( 0, 0, 0 );
  72995. lightNode.decay = 2;
  72996. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  72997. lightNode.name = parser.createUniqueName( lightDef.name || ( 'light_' + lightIndex ) );
  72998. dependency = Promise.resolve( lightNode );
  72999. parser.cache.add( cacheKey, dependency );
  73000. return dependency;
  73001. };
  73002. GLTFLightsExtension.prototype.createNodeAttachment = function ( nodeIndex ) {
  73003. var self = this;
  73004. var parser = this.parser;
  73005. var json = parser.json;
  73006. var nodeDef = json.nodes[ nodeIndex ];
  73007. var lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {};
  73008. var lightIndex = lightDef.light;
  73009. if ( lightIndex === undefined ) return null;
  73010. return this._loadLight( lightIndex ).then( function ( light ) {
  73011. return parser._getNodeRef( self.cache, lightIndex, light );
  73012. } );
  73013. };
  73014. /**
  73015. * Unlit Materials Extension
  73016. *
  73017. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  73018. */
  73019. function GLTFMaterialsUnlitExtension() {
  73020. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  73021. }
  73022. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  73023. return MeshBasicMaterial;
  73024. };
  73025. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  73026. var pending = [];
  73027. materialParams.color = new Color( 1.0, 1.0, 1.0 );
  73028. materialParams.opacity = 1.0;
  73029. var metallicRoughness = materialDef.pbrMetallicRoughness;
  73030. if ( metallicRoughness ) {
  73031. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  73032. var array = metallicRoughness.baseColorFactor;
  73033. materialParams.color.fromArray( array );
  73034. materialParams.opacity = array[ 3 ];
  73035. }
  73036. if ( metallicRoughness.baseColorTexture !== undefined ) {
  73037. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  73038. }
  73039. }
  73040. return Promise.all( pending );
  73041. };
  73042. /**
  73043. * Clearcoat Materials Extension
  73044. *
  73045. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  73046. */
  73047. function GLTFMaterialsClearcoatExtension( parser ) {
  73048. this.parser = parser;
  73049. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  73050. }
  73051. GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function ( materialIndex ) {
  73052. var parser = this.parser;
  73053. var materialDef = parser.json.materials[ materialIndex ];
  73054. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  73055. return MeshPhysicalMaterial;
  73056. };
  73057. GLTFMaterialsClearcoatExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  73058. var parser = this.parser;
  73059. var materialDef = parser.json.materials[ materialIndex ];
  73060. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  73061. return Promise.resolve();
  73062. }
  73063. var pending = [];
  73064. var extension = materialDef.extensions[ this.name ];
  73065. if ( extension.clearcoatFactor !== undefined ) {
  73066. materialParams.clearcoat = extension.clearcoatFactor;
  73067. }
  73068. if ( extension.clearcoatTexture !== undefined ) {
  73069. pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
  73070. }
  73071. if ( extension.clearcoatRoughnessFactor !== undefined ) {
  73072. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  73073. }
  73074. if ( extension.clearcoatRoughnessTexture !== undefined ) {
  73075. pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
  73076. }
  73077. if ( extension.clearcoatNormalTexture !== undefined ) {
  73078. pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
  73079. if ( extension.clearcoatNormalTexture.scale !== undefined ) {
  73080. var scale = extension.clearcoatNormalTexture.scale;
  73081. materialParams.clearcoatNormalScale = new Vector2$1( scale, scale );
  73082. }
  73083. }
  73084. return Promise.all( pending );
  73085. };
  73086. /**
  73087. * Transmission Materials Extension
  73088. *
  73089. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  73090. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  73091. */
  73092. function GLTFMaterialsTransmissionExtension( parser ) {
  73093. this.parser = parser;
  73094. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  73095. }
  73096. GLTFMaterialsTransmissionExtension.prototype.getMaterialType = function ( materialIndex ) {
  73097. var parser = this.parser;
  73098. var materialDef = parser.json.materials[ materialIndex ];
  73099. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  73100. return MeshPhysicalMaterial;
  73101. };
  73102. GLTFMaterialsTransmissionExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  73103. var parser = this.parser;
  73104. var materialDef = parser.json.materials[ materialIndex ];
  73105. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  73106. return Promise.resolve();
  73107. }
  73108. var pending = [];
  73109. var extension = materialDef.extensions[ this.name ];
  73110. if ( extension.transmissionFactor !== undefined ) {
  73111. materialParams.transmission = extension.transmissionFactor;
  73112. }
  73113. if ( extension.transmissionTexture !== undefined ) {
  73114. pending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );
  73115. }
  73116. return Promise.all( pending );
  73117. };
  73118. /**
  73119. * BasisU Texture Extension
  73120. *
  73121. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  73122. */
  73123. function GLTFTextureBasisUExtension( parser ) {
  73124. this.parser = parser;
  73125. this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  73126. }
  73127. GLTFTextureBasisUExtension.prototype.loadTexture = function ( textureIndex ) {
  73128. var parser = this.parser;
  73129. var json = parser.json;
  73130. var textureDef = json.textures[ textureIndex ];
  73131. if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {
  73132. return null;
  73133. }
  73134. var extension = textureDef.extensions[ this.name ];
  73135. var source = json.images[ extension.source ];
  73136. var loader = parser.options.ktx2Loader;
  73137. if ( ! loader ) {
  73138. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  73139. throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );
  73140. } else {
  73141. // Assumes that the extension is optional and that a fallback texture is present
  73142. return null;
  73143. }
  73144. }
  73145. return parser.loadTextureImage( textureIndex, source, loader );
  73146. };
  73147. /**
  73148. * WebP Texture Extension
  73149. *
  73150. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
  73151. */
  73152. function GLTFTextureWebPExtension( parser ) {
  73153. this.parser = parser;
  73154. this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
  73155. this.isSupported = null;
  73156. }
  73157. GLTFTextureWebPExtension.prototype.loadTexture = function ( textureIndex ) {
  73158. var name = this.name;
  73159. var parser = this.parser;
  73160. var json = parser.json;
  73161. var textureDef = json.textures[ textureIndex ];
  73162. if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
  73163. return null;
  73164. }
  73165. var extension = textureDef.extensions[ name ];
  73166. var source = json.images[ extension.source ];
  73167. var loader = source.uri ? parser.options.manager.getHandler( source.uri ) : parser.textureLoader;
  73168. return this.detectSupport().then( function ( isSupported ) {
  73169. if ( isSupported ) return parser.loadTextureImage( textureIndex, source, loader );
  73170. if ( json.extensionsRequired && json.extensionsRequired.indexOf( name ) >= 0 ) {
  73171. throw new Error( 'THREE.GLTFLoader: WebP required by asset but unsupported.' );
  73172. }
  73173. // Fall back to PNG or JPEG.
  73174. return parser.loadTexture( textureIndex );
  73175. } );
  73176. };
  73177. GLTFTextureWebPExtension.prototype.detectSupport = function () {
  73178. if ( ! this.isSupported ) {
  73179. this.isSupported = new Promise( function ( resolve ) {
  73180. var image = new Image();
  73181. // Lossy test image. Support for lossy images doesn't guarantee support for all
  73182. // WebP images, unfortunately.
  73183. image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
  73184. image.onload = image.onerror = function () {
  73185. resolve( image.height === 1 );
  73186. };
  73187. } );
  73188. }
  73189. return this.isSupported;
  73190. };
  73191. /**
  73192. * meshopt BufferView Compression Extension
  73193. *
  73194. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
  73195. */
  73196. function GLTFMeshoptCompression( parser ) {
  73197. this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
  73198. this.parser = parser;
  73199. }
  73200. GLTFMeshoptCompression.prototype.loadBufferView = function ( index ) {
  73201. var json = this.parser.json;
  73202. var bufferView = json.bufferViews[ index ];
  73203. if ( bufferView.extensions && bufferView.extensions[ this.name ] ) {
  73204. var extensionDef = bufferView.extensions[ this.name ];
  73205. var buffer = this.parser.getDependency( 'buffer', extensionDef.buffer );
  73206. var decoder = this.parser.options.meshoptDecoder;
  73207. if ( ! decoder || ! decoder.supported ) {
  73208. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  73209. throw new Error( 'THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files' );
  73210. } else {
  73211. // Assumes that the extension is optional and that fallback buffer data is present
  73212. return null;
  73213. }
  73214. }
  73215. return Promise.all( [ buffer, decoder.ready ] ).then( function ( res ) {
  73216. var byteOffset = extensionDef.byteOffset || 0;
  73217. var byteLength = extensionDef.byteLength || 0;
  73218. var count = extensionDef.count;
  73219. var stride = extensionDef.byteStride;
  73220. var result = new ArrayBuffer( count * stride );
  73221. var source = new Uint8Array( res[ 0 ], byteOffset, byteLength );
  73222. decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter );
  73223. return result;
  73224. } );
  73225. } else {
  73226. return null;
  73227. }
  73228. };
  73229. /* BINARY EXTENSION */
  73230. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  73231. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  73232. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  73233. function GLTFBinaryExtension( data ) {
  73234. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  73235. this.content = null;
  73236. this.body = null;
  73237. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  73238. this.header = {
  73239. magic: LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  73240. version: headerView.getUint32( 4, true ),
  73241. length: headerView.getUint32( 8, true )
  73242. };
  73243. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  73244. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  73245. } else if ( this.header.version < 2.0 ) {
  73246. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
  73247. }
  73248. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  73249. var chunkIndex = 0;
  73250. while ( chunkIndex < chunkView.byteLength ) {
  73251. var chunkLength = chunkView.getUint32( chunkIndex, true );
  73252. chunkIndex += 4;
  73253. var chunkType = chunkView.getUint32( chunkIndex, true );
  73254. chunkIndex += 4;
  73255. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  73256. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  73257. this.content = LoaderUtils.decodeText( contentArray );
  73258. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  73259. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  73260. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  73261. }
  73262. // Clients must ignore chunks with unknown types.
  73263. chunkIndex += chunkLength;
  73264. }
  73265. if ( this.content === null ) {
  73266. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  73267. }
  73268. }
  73269. /**
  73270. * DRACO Mesh Compression Extension
  73271. *
  73272. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  73273. */
  73274. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  73275. if ( ! dracoLoader ) {
  73276. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  73277. }
  73278. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  73279. this.json = json;
  73280. this.dracoLoader = dracoLoader;
  73281. this.dracoLoader.preload();
  73282. }
  73283. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  73284. var json = this.json;
  73285. var dracoLoader = this.dracoLoader;
  73286. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  73287. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  73288. var threeAttributeMap = {};
  73289. var attributeNormalizedMap = {};
  73290. var attributeTypeMap = {};
  73291. for ( var attributeName in gltfAttributeMap ) {
  73292. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  73293. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  73294. }
  73295. for ( attributeName in primitive.attributes ) {
  73296. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  73297. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  73298. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  73299. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  73300. attributeTypeMap[ threeAttributeName ] = componentType;
  73301. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  73302. }
  73303. }
  73304. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  73305. return new Promise( function ( resolve ) {
  73306. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  73307. for ( var attributeName in geometry.attributes ) {
  73308. var attribute = geometry.attributes[ attributeName ];
  73309. var normalized = attributeNormalizedMap[ attributeName ];
  73310. if ( normalized !== undefined ) attribute.normalized = normalized;
  73311. }
  73312. resolve( geometry );
  73313. }, threeAttributeMap, attributeTypeMap );
  73314. } );
  73315. } );
  73316. };
  73317. /**
  73318. * Texture Transform Extension
  73319. *
  73320. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  73321. */
  73322. function GLTFTextureTransformExtension() {
  73323. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  73324. }
  73325. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  73326. texture = texture.clone();
  73327. if ( transform.offset !== undefined ) {
  73328. texture.offset.fromArray( transform.offset );
  73329. }
  73330. if ( transform.rotation !== undefined ) {
  73331. texture.rotation = transform.rotation;
  73332. }
  73333. if ( transform.scale !== undefined ) {
  73334. texture.repeat.fromArray( transform.scale );
  73335. }
  73336. if ( transform.texCoord !== undefined ) {
  73337. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  73338. }
  73339. texture.needsUpdate = true;
  73340. return texture;
  73341. };
  73342. /**
  73343. * Specular-Glossiness Extension
  73344. *
  73345. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  73346. */
  73347. /**
  73348. * A sub class of StandardMaterial with some of the functionality
  73349. * changed via the `onBeforeCompile` callback
  73350. * @pailhead
  73351. */
  73352. function GLTFMeshStandardSGMaterial( params ) {
  73353. MeshStandardMaterial.call( this );
  73354. this.isGLTFSpecularGlossinessMaterial = true;
  73355. //various chunks that need replacing
  73356. var specularMapParsFragmentChunk = [
  73357. '#ifdef USE_SPECULARMAP',
  73358. ' uniform sampler2D specularMap;',
  73359. '#endif'
  73360. ].join( '\n' );
  73361. var glossinessMapParsFragmentChunk = [
  73362. '#ifdef USE_GLOSSINESSMAP',
  73363. ' uniform sampler2D glossinessMap;',
  73364. '#endif'
  73365. ].join( '\n' );
  73366. var specularMapFragmentChunk = [
  73367. 'vec3 specularFactor = specular;',
  73368. '#ifdef USE_SPECULARMAP',
  73369. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  73370. ' texelSpecular = sRGBToLinear( texelSpecular );',
  73371. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  73372. ' specularFactor *= texelSpecular.rgb;',
  73373. '#endif'
  73374. ].join( '\n' );
  73375. var glossinessMapFragmentChunk = [
  73376. 'float glossinessFactor = glossiness;',
  73377. '#ifdef USE_GLOSSINESSMAP',
  73378. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  73379. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  73380. ' glossinessFactor *= texelGlossiness.a;',
  73381. '#endif'
  73382. ].join( '\n' );
  73383. var lightPhysicalFragmentChunk = [
  73384. 'PhysicalMaterial material;',
  73385. 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );',
  73386. 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );',
  73387. 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );',
  73388. 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.',
  73389. 'material.specularRoughness += geometryRoughness;',
  73390. 'material.specularRoughness = min( material.specularRoughness, 1.0 );',
  73391. 'material.specularColor = specularFactor;',
  73392. ].join( '\n' );
  73393. var uniforms = {
  73394. specular: { value: new Color().setHex( 0xffffff ) },
  73395. glossiness: { value: 1 },
  73396. specularMap: { value: null },
  73397. glossinessMap: { value: null }
  73398. };
  73399. this._extraUniforms = uniforms;
  73400. this.onBeforeCompile = function ( shader ) {
  73401. for ( var uniformName in uniforms ) {
  73402. shader.uniforms[ uniformName ] = uniforms[ uniformName ];
  73403. }
  73404. shader.fragmentShader = shader.fragmentShader
  73405. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  73406. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  73407. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  73408. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  73409. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  73410. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  73411. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  73412. };
  73413. Object.defineProperties( this, {
  73414. specular: {
  73415. get: function () {
  73416. return uniforms.specular.value;
  73417. },
  73418. set: function ( v ) {
  73419. uniforms.specular.value = v;
  73420. }
  73421. },
  73422. specularMap: {
  73423. get: function () {
  73424. return uniforms.specularMap.value;
  73425. },
  73426. set: function ( v ) {
  73427. uniforms.specularMap.value = v;
  73428. if ( v ) {
  73429. this.defines.USE_SPECULARMAP = ''; // USE_UV is set by the renderer for specular maps
  73430. } else {
  73431. delete this.defines.USE_SPECULARMAP;
  73432. }
  73433. }
  73434. },
  73435. glossiness: {
  73436. get: function () {
  73437. return uniforms.glossiness.value;
  73438. },
  73439. set: function ( v ) {
  73440. uniforms.glossiness.value = v;
  73441. }
  73442. },
  73443. glossinessMap: {
  73444. get: function () {
  73445. return uniforms.glossinessMap.value;
  73446. },
  73447. set: function ( v ) {
  73448. uniforms.glossinessMap.value = v;
  73449. if ( v ) {
  73450. this.defines.USE_GLOSSINESSMAP = '';
  73451. this.defines.USE_UV = '';
  73452. } else {
  73453. delete this.defines.USE_GLOSSINESSMAP;
  73454. delete this.defines.USE_UV;
  73455. }
  73456. }
  73457. }
  73458. } );
  73459. delete this.metalness;
  73460. delete this.roughness;
  73461. delete this.metalnessMap;
  73462. delete this.roughnessMap;
  73463. this.setValues( params );
  73464. }
  73465. GLTFMeshStandardSGMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  73466. GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial;
  73467. GLTFMeshStandardSGMaterial.prototype.copy = function ( source ) {
  73468. MeshStandardMaterial.prototype.copy.call( this, source );
  73469. this.specularMap = source.specularMap;
  73470. this.specular.copy( source.specular );
  73471. this.glossinessMap = source.glossinessMap;
  73472. this.glossiness = source.glossiness;
  73473. delete this.metalness;
  73474. delete this.roughness;
  73475. delete this.metalnessMap;
  73476. delete this.roughnessMap;
  73477. return this;
  73478. };
  73479. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  73480. return {
  73481. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  73482. specularGlossinessParams: [
  73483. 'color',
  73484. 'map',
  73485. 'lightMap',
  73486. 'lightMapIntensity',
  73487. 'aoMap',
  73488. 'aoMapIntensity',
  73489. 'emissive',
  73490. 'emissiveIntensity',
  73491. 'emissiveMap',
  73492. 'bumpMap',
  73493. 'bumpScale',
  73494. 'normalMap',
  73495. 'normalMapType',
  73496. 'displacementMap',
  73497. 'displacementScale',
  73498. 'displacementBias',
  73499. 'specularMap',
  73500. 'specular',
  73501. 'glossinessMap',
  73502. 'glossiness',
  73503. 'alphaMap',
  73504. 'envMap',
  73505. 'envMapIntensity',
  73506. 'refractionRatio',
  73507. ],
  73508. getMaterialType: function () {
  73509. return GLTFMeshStandardSGMaterial;
  73510. },
  73511. extendParams: function ( materialParams, materialDef, parser ) {
  73512. var pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  73513. materialParams.color = new Color( 1.0, 1.0, 1.0 );
  73514. materialParams.opacity = 1.0;
  73515. var pending = [];
  73516. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  73517. var array = pbrSpecularGlossiness.diffuseFactor;
  73518. materialParams.color.fromArray( array );
  73519. materialParams.opacity = array[ 3 ];
  73520. }
  73521. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  73522. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  73523. }
  73524. materialParams.emissive = new Color( 0.0, 0.0, 0.0 );
  73525. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  73526. materialParams.specular = new Color( 1.0, 1.0, 1.0 );
  73527. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  73528. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  73529. }
  73530. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  73531. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  73532. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  73533. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  73534. }
  73535. return Promise.all( pending );
  73536. },
  73537. createMaterial: function ( materialParams ) {
  73538. var material = new GLTFMeshStandardSGMaterial( materialParams );
  73539. material.fog = true;
  73540. material.color = materialParams.color;
  73541. material.map = materialParams.map === undefined ? null : materialParams.map;
  73542. material.lightMap = null;
  73543. material.lightMapIntensity = 1.0;
  73544. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  73545. material.aoMapIntensity = 1.0;
  73546. material.emissive = materialParams.emissive;
  73547. material.emissiveIntensity = 1.0;
  73548. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  73549. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  73550. material.bumpScale = 1;
  73551. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  73552. material.normalMapType = TangentSpaceNormalMap;
  73553. if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale;
  73554. material.displacementMap = null;
  73555. material.displacementScale = 1;
  73556. material.displacementBias = 0;
  73557. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  73558. material.specular = materialParams.specular;
  73559. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  73560. material.glossiness = materialParams.glossiness;
  73561. material.alphaMap = null;
  73562. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  73563. material.envMapIntensity = 1.0;
  73564. material.refractionRatio = 0.98;
  73565. return material;
  73566. },
  73567. };
  73568. }
  73569. /**
  73570. * Mesh Quantization Extension
  73571. *
  73572. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  73573. */
  73574. function GLTFMeshQuantizationExtension() {
  73575. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  73576. }
  73577. /*********************************/
  73578. /********** INTERPOLATION ********/
  73579. /*********************************/
  73580. // Spline Interpolation
  73581. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  73582. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  73583. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  73584. }
  73585. GLTFCubicSplineInterpolant.prototype = Object.create( Interpolant.prototype );
  73586. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  73587. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  73588. // Copies a sample value to the result buffer. See description of glTF
  73589. // CUBICSPLINE values layout in interpolate_() function below.
  73590. var result = this.resultBuffer,
  73591. values = this.sampleValues,
  73592. valueSize = this.valueSize,
  73593. offset = index * valueSize * 3 + valueSize;
  73594. for ( var i = 0; i !== valueSize; i ++ ) {
  73595. result[ i ] = values[ offset + i ];
  73596. }
  73597. return result;
  73598. };
  73599. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  73600. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  73601. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  73602. var result = this.resultBuffer;
  73603. var values = this.sampleValues;
  73604. var stride = this.valueSize;
  73605. var stride2 = stride * 2;
  73606. var stride3 = stride * 3;
  73607. var td = t1 - t0;
  73608. var p = ( t - t0 ) / td;
  73609. var pp = p * p;
  73610. var ppp = pp * p;
  73611. var offset1 = i1 * stride3;
  73612. var offset0 = offset1 - stride3;
  73613. var s2 = - 2 * ppp + 3 * pp;
  73614. var s3 = ppp - pp;
  73615. var s0 = 1 - s2;
  73616. var s1 = s3 - pp + p;
  73617. // Layout of keyframe output values for CUBICSPLINE animations:
  73618. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  73619. for ( var i = 0; i !== stride; i ++ ) {
  73620. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  73621. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  73622. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  73623. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  73624. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  73625. }
  73626. return result;
  73627. };
  73628. /*********************************/
  73629. /********** INTERNALS ************/
  73630. /*********************************/
  73631. /* CONSTANTS */
  73632. var WEBGL_CONSTANTS = {
  73633. FLOAT: 5126,
  73634. //FLOAT_MAT2: 35674,
  73635. FLOAT_MAT3: 35675,
  73636. FLOAT_MAT4: 35676,
  73637. FLOAT_VEC2: 35664,
  73638. FLOAT_VEC3: 35665,
  73639. FLOAT_VEC4: 35666,
  73640. LINEAR: 9729,
  73641. REPEAT: 10497,
  73642. SAMPLER_2D: 35678,
  73643. POINTS: 0,
  73644. LINES: 1,
  73645. LINE_LOOP: 2,
  73646. LINE_STRIP: 3,
  73647. TRIANGLES: 4,
  73648. TRIANGLE_STRIP: 5,
  73649. TRIANGLE_FAN: 6,
  73650. UNSIGNED_BYTE: 5121,
  73651. UNSIGNED_SHORT: 5123
  73652. };
  73653. var WEBGL_COMPONENT_TYPES = {
  73654. 5120: Int8Array,
  73655. 5121: Uint8Array,
  73656. 5122: Int16Array,
  73657. 5123: Uint16Array,
  73658. 5125: Uint32Array,
  73659. 5126: Float32Array
  73660. };
  73661. var WEBGL_FILTERS = {
  73662. 9728: NearestFilter,
  73663. 9729: LinearFilter,
  73664. 9984: NearestMipmapNearestFilter,
  73665. 9985: LinearMipmapNearestFilter,
  73666. 9986: NearestMipmapLinearFilter,
  73667. 9987: LinearMipmapLinearFilter
  73668. };
  73669. var WEBGL_WRAPPINGS = {
  73670. 33071: ClampToEdgeWrapping,
  73671. 33648: MirroredRepeatWrapping,
  73672. 10497: RepeatWrapping
  73673. };
  73674. var WEBGL_TYPE_SIZES = {
  73675. 'SCALAR': 1,
  73676. 'VEC2': 2,
  73677. 'VEC3': 3,
  73678. 'VEC4': 4,
  73679. 'MAT2': 4,
  73680. 'MAT3': 9,
  73681. 'MAT4': 16
  73682. };
  73683. var ATTRIBUTES = {
  73684. POSITION: 'position',
  73685. NORMAL: 'normal',
  73686. TANGENT: 'tangent',
  73687. TEXCOORD_0: 'uv',
  73688. TEXCOORD_1: 'uv2',
  73689. COLOR_0: 'color',
  73690. WEIGHTS_0: 'skinWeight',
  73691. JOINTS_0: 'skinIndex',
  73692. };
  73693. var PATH_PROPERTIES = {
  73694. scale: 'scale',
  73695. translation: 'position',
  73696. rotation: 'quaternion',
  73697. weights: 'morphTargetInfluences'
  73698. };
  73699. var INTERPOLATION = {
  73700. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  73701. // keyframe track will be initialized with a default interpolation type, then modified.
  73702. LINEAR: InterpolateLinear,
  73703. STEP: InterpolateDiscrete
  73704. };
  73705. var ALPHA_MODES = {
  73706. OPAQUE: 'OPAQUE',
  73707. MASK: 'MASK',
  73708. BLEND: 'BLEND'
  73709. };
  73710. /* UTILITY FUNCTIONS */
  73711. function resolveURL( url, path ) {
  73712. // Invalid URL
  73713. if ( typeof url !== 'string' || url === '' ) return '';
  73714. // Host Relative URL
  73715. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  73716. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  73717. }
  73718. // Absolute URL http://,https://,//
  73719. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  73720. // Data URI
  73721. if ( /^data:.*,.*$/i.test( url ) ) return url;
  73722. // Blob URL
  73723. if ( /^blob:.*$/i.test( url ) ) return url;
  73724. // Relative URL
  73725. return path + url;
  73726. }
  73727. /**
  73728. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  73729. */
  73730. function createDefaultMaterial( cache ) {
  73731. if ( cache[ 'DefaultMaterial' ] === undefined ) {
  73732. cache[ 'DefaultMaterial' ] = new MeshStandardMaterial( {
  73733. color: 0xFFFFFF,
  73734. emissive: 0x000000,
  73735. metalness: 1,
  73736. roughness: 1,
  73737. transparent: false,
  73738. depthTest: true,
  73739. side: FrontSide
  73740. } );
  73741. }
  73742. return cache[ 'DefaultMaterial' ];
  73743. }
  73744. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  73745. // Add unknown glTF extensions to an object's userData.
  73746. for ( var name in objectDef.extensions ) {
  73747. if ( knownExtensions[ name ] === undefined ) {
  73748. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  73749. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  73750. }
  73751. }
  73752. }
  73753. /**
  73754. * @param {Object3D|Material|BufferGeometry} object
  73755. * @param {GLTF.definition} gltfDef
  73756. */
  73757. function assignExtrasToUserData( object, gltfDef ) {
  73758. if ( gltfDef.extras !== undefined ) {
  73759. if ( typeof gltfDef.extras === 'object' ) {
  73760. Object.assign( object.userData, gltfDef.extras );
  73761. } else {
  73762. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  73763. }
  73764. }
  73765. }
  73766. /**
  73767. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  73768. *
  73769. * @param {BufferGeometry} geometry
  73770. * @param {Array<GLTF.Target>} targets
  73771. * @param {GLTFParser} parser
  73772. * @return {Promise<BufferGeometry>}
  73773. */
  73774. function addMorphTargets( geometry, targets, parser ) {
  73775. var hasMorphPosition = false;
  73776. var hasMorphNormal = false;
  73777. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  73778. var target = targets[ i ];
  73779. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  73780. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  73781. if ( hasMorphPosition && hasMorphNormal ) break;
  73782. }
  73783. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  73784. var pendingPositionAccessors = [];
  73785. var pendingNormalAccessors = [];
  73786. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  73787. var target = targets[ i ];
  73788. if ( hasMorphPosition ) {
  73789. var pendingAccessor = target.POSITION !== undefined
  73790. ? parser.getDependency( 'accessor', target.POSITION )
  73791. : geometry.attributes.position;
  73792. pendingPositionAccessors.push( pendingAccessor );
  73793. }
  73794. if ( hasMorphNormal ) {
  73795. var pendingAccessor = target.NORMAL !== undefined
  73796. ? parser.getDependency( 'accessor', target.NORMAL )
  73797. : geometry.attributes.normal;
  73798. pendingNormalAccessors.push( pendingAccessor );
  73799. }
  73800. }
  73801. return Promise.all( [
  73802. Promise.all( pendingPositionAccessors ),
  73803. Promise.all( pendingNormalAccessors )
  73804. ] ).then( function ( accessors ) {
  73805. var morphPositions = accessors[ 0 ];
  73806. var morphNormals = accessors[ 1 ];
  73807. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  73808. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  73809. geometry.morphTargetsRelative = true;
  73810. return geometry;
  73811. } );
  73812. }
  73813. /**
  73814. * @param {Mesh} mesh
  73815. * @param {GLTF.Mesh} meshDef
  73816. */
  73817. function updateMorphTargets( mesh, meshDef ) {
  73818. mesh.updateMorphTargets();
  73819. if ( meshDef.weights !== undefined ) {
  73820. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  73821. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  73822. }
  73823. }
  73824. // .extras has user-defined data, so check that .extras.targetNames is an array.
  73825. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  73826. var targetNames = meshDef.extras.targetNames;
  73827. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  73828. mesh.morphTargetDictionary = {};
  73829. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  73830. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  73831. }
  73832. } else {
  73833. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  73834. }
  73835. }
  73836. }
  73837. function createPrimitiveKey( primitiveDef ) {
  73838. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  73839. var geometryKey;
  73840. if ( dracoExtension ) {
  73841. geometryKey = 'draco:' + dracoExtension.bufferView
  73842. + ':' + dracoExtension.indices
  73843. + ':' + createAttributesKey( dracoExtension.attributes );
  73844. } else {
  73845. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  73846. }
  73847. return geometryKey;
  73848. }
  73849. function createAttributesKey( attributes ) {
  73850. var attributesKey = '';
  73851. var keys = Object.keys( attributes ).sort();
  73852. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  73853. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  73854. }
  73855. return attributesKey;
  73856. }
  73857. /* GLTF PARSER */
  73858. function GLTFParser( json, options ) {
  73859. this.json = json || {};
  73860. this.extensions = {};
  73861. this.plugins = {};
  73862. this.options = options || {};
  73863. // loader object cache
  73864. this.cache = new GLTFRegistry();
  73865. // associations between Three.js objects and glTF elements
  73866. this.associations = new Map();
  73867. // BufferGeometry caching
  73868. this.primitiveCache = {};
  73869. // Object3D instance caches
  73870. this.meshCache = { refs: {}, uses: {} };
  73871. this.cameraCache = { refs: {}, uses: {} };
  73872. this.lightCache = { refs: {}, uses: {} };
  73873. // Track node names, to ensure no duplicates
  73874. this.nodeNamesUsed = {};
  73875. // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
  73876. // expensive work of uploading a texture to the GPU off the main thread.
  73877. /* if ( typeof createImageBitmap !== 'undefined' && /Firefox/.test( navigator.userAgent ) === false ) {
  73878. this.textureLoader = new ImageBitmapLoader( this.options.manager );
  73879. } else { */
  73880. //为了防止chrome出现报错 The source image could not be decoded. 导致reject,改用TextureLoader by xzw
  73881. this.textureLoader = new TextureLoader( this.options.manager );
  73882. //}
  73883. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  73884. this.fileLoader = new FileLoader( this.options.manager );
  73885. this.fileLoader.setResponseType( 'arraybuffer' );
  73886. if ( this.options.crossOrigin === 'use-credentials' ) {
  73887. this.fileLoader.setWithCredentials( true );
  73888. }
  73889. }
  73890. GLTFParser.prototype.setExtensions = function ( extensions ) {
  73891. this.extensions = extensions;
  73892. };
  73893. GLTFParser.prototype.setPlugins = function ( plugins ) {
  73894. this.plugins = plugins;
  73895. };
  73896. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  73897. var parser = this;
  73898. var json = this.json;
  73899. var extensions = this.extensions;
  73900. // Clear the loader cache
  73901. this.cache.removeAll();
  73902. // Mark the special nodes/meshes in json for efficient parse
  73903. this._invokeAll( function ( ext ) {
  73904. return ext._markDefs && ext._markDefs();
  73905. } );
  73906. Promise.all( [
  73907. this.getDependencies( 'scene' ),
  73908. this.getDependencies( 'animation' ),
  73909. this.getDependencies( 'camera' ),
  73910. ] ).then( function ( dependencies ) {
  73911. var result = {
  73912. scene: dependencies[ 0 ][ json.scene || 0 ],
  73913. scenes: dependencies[ 0 ],
  73914. animations: dependencies[ 1 ],
  73915. cameras: dependencies[ 2 ],
  73916. asset: json.asset,
  73917. parser: parser,
  73918. userData: {}
  73919. };
  73920. addUnknownExtensionsToUserData( extensions, result, json );
  73921. assignExtrasToUserData( result, json );
  73922. onLoad( result );
  73923. } ).catch( onError );
  73924. };
  73925. /**
  73926. * Marks the special nodes/meshes in json for efficient parse.
  73927. */
  73928. GLTFParser.prototype._markDefs = function () {
  73929. var nodeDefs = this.json.nodes || [];
  73930. var skinDefs = this.json.skins || [];
  73931. var meshDefs = this.json.meshes || [];
  73932. // Nothing in the node definition indicates whether it is a Bone or an
  73933. // Object3D. Use the skins' joint references to mark bones.
  73934. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  73935. var joints = skinDefs[ skinIndex ].joints;
  73936. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  73937. nodeDefs[ joints[ i ] ].isBone = true;
  73938. }
  73939. }
  73940. // Iterate over all nodes, marking references to shared resources,
  73941. // as well as skeleton joints.
  73942. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  73943. var nodeDef = nodeDefs[ nodeIndex ];
  73944. if ( nodeDef.mesh !== undefined ) {
  73945. this._addNodeRef( this.meshCache, nodeDef.mesh );
  73946. // Nothing in the mesh definition indicates whether it is
  73947. // a SkinnedMesh or Mesh. Use the node's mesh reference
  73948. // to mark SkinnedMesh if node has skin.
  73949. if ( nodeDef.skin !== undefined ) {
  73950. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  73951. }
  73952. }
  73953. if ( nodeDef.camera !== undefined ) {
  73954. this._addNodeRef( this.cameraCache, nodeDef.camera );
  73955. }
  73956. }
  73957. };
  73958. /**
  73959. * Counts references to shared node / Object3D resources. These resources
  73960. * can be reused, or "instantiated", at multiple nodes in the scene
  73961. * hierarchy. Mesh, Camera, and Light instances are instantiated and must
  73962. * be marked. Non-scenegraph resources (like Materials, Geometries, and
  73963. * Textures) can be reused directly and are not marked here.
  73964. *
  73965. * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  73966. */
  73967. GLTFParser.prototype._addNodeRef = function ( cache, index ) {
  73968. if ( index === undefined ) return;
  73969. if ( cache.refs[ index ] === undefined ) {
  73970. cache.refs[ index ] = cache.uses[ index ] = 0;
  73971. }
  73972. cache.refs[ index ] ++;
  73973. };
  73974. /** Returns a reference to a shared resource, cloning it if necessary. */
  73975. GLTFParser.prototype._getNodeRef = function ( cache, index, object ) {
  73976. if ( cache.refs[ index ] <= 1 ) return object;
  73977. var ref = object.clone();
  73978. ref.name += '_instance_' + ( cache.uses[ index ] ++ );
  73979. return ref;
  73980. };
  73981. GLTFParser.prototype._invokeOne = function ( func ) {
  73982. var extensions = Object.values( this.plugins );
  73983. extensions.push( this );
  73984. for ( var i = 0; i < extensions.length; i ++ ) {
  73985. var result = func( extensions[ i ] );
  73986. if ( result ) return result;
  73987. }
  73988. };
  73989. GLTFParser.prototype._invokeAll = function ( func ) {
  73990. var extensions = Object.values( this.plugins );
  73991. extensions.unshift( this );
  73992. var pending = [];
  73993. for ( var i = 0; i < extensions.length; i ++ ) {
  73994. var result = func( extensions[ i ] );
  73995. if ( result ) pending.push( result );
  73996. }
  73997. return pending;
  73998. };
  73999. /**
  74000. * Requests the specified dependency asynchronously, with caching.
  74001. * @param {string} type
  74002. * @param {number} index
  74003. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  74004. */
  74005. GLTFParser.prototype.getDependency = function ( type, index ) {
  74006. var cacheKey = type + ':' + index;
  74007. var dependency = this.cache.get( cacheKey );
  74008. if ( ! dependency ) {
  74009. switch ( type ) {
  74010. case 'scene':
  74011. dependency = this.loadScene( index );
  74012. break;
  74013. case 'node':
  74014. dependency = this.loadNode( index );
  74015. break;
  74016. case 'mesh':
  74017. dependency = this._invokeOne( function ( ext ) {
  74018. return ext.loadMesh && ext.loadMesh( index );
  74019. } );
  74020. break;
  74021. case 'accessor':
  74022. dependency = this.loadAccessor( index );
  74023. break;
  74024. case 'bufferView':
  74025. dependency = this._invokeOne( function ( ext ) {
  74026. return ext.loadBufferView && ext.loadBufferView( index );
  74027. } );
  74028. break;
  74029. case 'buffer':
  74030. dependency = this.loadBuffer( index );
  74031. break;
  74032. case 'material':
  74033. dependency = this._invokeOne( function ( ext ) {
  74034. return ext.loadMaterial && ext.loadMaterial( index );
  74035. } );
  74036. break;
  74037. case 'texture':
  74038. dependency = this._invokeOne( function ( ext ) {
  74039. return ext.loadTexture && ext.loadTexture( index );
  74040. } );
  74041. break;
  74042. case 'skin':
  74043. dependency = this.loadSkin( index );
  74044. break;
  74045. case 'animation':
  74046. dependency = this.loadAnimation( index );
  74047. break;
  74048. case 'camera':
  74049. dependency = this.loadCamera( index );
  74050. break;
  74051. default:
  74052. throw new Error( 'Unknown type: ' + type );
  74053. }
  74054. this.cache.add( cacheKey, dependency );
  74055. }
  74056. return dependency;
  74057. };
  74058. /**
  74059. * Requests all dependencies of the specified type asynchronously, with caching.
  74060. * @param {string} type
  74061. * @return {Promise<Array<Object>>}
  74062. */
  74063. GLTFParser.prototype.getDependencies = function ( type ) {
  74064. var dependencies = this.cache.get( type );
  74065. if ( ! dependencies ) {
  74066. var parser = this;
  74067. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  74068. dependencies = Promise.all( defs.map( function ( def, index ) {
  74069. return parser.getDependency( type, index );
  74070. } ) );
  74071. this.cache.add( type, dependencies );
  74072. }
  74073. return dependencies;
  74074. };
  74075. /**
  74076. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  74077. * @param {number} bufferIndex
  74078. * @return {Promise<ArrayBuffer>}
  74079. */
  74080. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  74081. var bufferDef = this.json.buffers[ bufferIndex ];
  74082. var loader = this.fileLoader;
  74083. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  74084. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  74085. }
  74086. // If present, GLB container is required to be the first buffer.
  74087. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  74088. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  74089. }
  74090. var options = this.options;
  74091. return new Promise( function ( resolve, reject ) {
  74092. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  74093. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  74094. } );
  74095. } );
  74096. };
  74097. /**
  74098. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  74099. * @param {number} bufferViewIndex
  74100. * @return {Promise<ArrayBuffer>}
  74101. */
  74102. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  74103. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  74104. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  74105. var byteLength = bufferViewDef.byteLength || 0;
  74106. var byteOffset = bufferViewDef.byteOffset || 0;
  74107. return buffer.slice( byteOffset, byteOffset + byteLength );
  74108. } );
  74109. };
  74110. /**
  74111. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  74112. * @param {number} accessorIndex
  74113. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  74114. */
  74115. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  74116. var parser = this;
  74117. var json = this.json;
  74118. var accessorDef = this.json.accessors[ accessorIndex ];
  74119. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  74120. // Ignore empty accessors, which may be used to declare runtime
  74121. // information about attributes coming from another source (e.g. Draco
  74122. // compression extension).
  74123. return Promise.resolve( null );
  74124. }
  74125. var pendingBufferViews = [];
  74126. if ( accessorDef.bufferView !== undefined ) {
  74127. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  74128. } else {
  74129. pendingBufferViews.push( null );
  74130. }
  74131. if ( accessorDef.sparse !== undefined ) {
  74132. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  74133. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  74134. }
  74135. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  74136. var bufferView = bufferViews[ 0 ];
  74137. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  74138. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  74139. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  74140. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  74141. var itemBytes = elementBytes * itemSize;
  74142. var byteOffset = accessorDef.byteOffset || 0;
  74143. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  74144. var normalized = accessorDef.normalized === true;
  74145. var array, bufferAttribute;
  74146. // The buffer is not interleaved if the stride is the item size in bytes.
  74147. if ( byteStride && byteStride !== itemBytes ) {
  74148. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  74149. // This makes sure that IBA.count reflects accessor.count properly
  74150. var ibSlice = Math.floor( byteOffset / byteStride );
  74151. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  74152. var ib = parser.cache.get( ibCacheKey );
  74153. if ( ! ib ) {
  74154. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
  74155. // Integer parameters to IB/IBA are in array elements, not bytes.
  74156. ib = new InterleavedBuffer( array, byteStride / elementBytes );
  74157. parser.cache.add( ibCacheKey, ib );
  74158. }
  74159. bufferAttribute = new InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
  74160. } else {
  74161. if ( bufferView === null ) {
  74162. array = new TypedArray( accessorDef.count * itemSize );
  74163. } else {
  74164. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  74165. }
  74166. bufferAttribute = new BufferAttribute( array, itemSize, normalized );
  74167. }
  74168. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  74169. if ( accessorDef.sparse !== undefined ) {
  74170. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  74171. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  74172. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  74173. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  74174. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  74175. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  74176. if ( bufferView !== null ) {
  74177. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  74178. bufferAttribute = new BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
  74179. }
  74180. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  74181. var index = sparseIndices[ i ];
  74182. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  74183. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  74184. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  74185. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  74186. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  74187. }
  74188. }
  74189. return bufferAttribute;
  74190. } );
  74191. };
  74192. /**
  74193. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  74194. * @param {number} textureIndex
  74195. * @return {Promise<THREE.Texture>}
  74196. */
  74197. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  74198. var parser = this;
  74199. var json = this.json;
  74200. var options = this.options;
  74201. var textureDef = json.textures[ textureIndex ];
  74202. var textureExtensions = textureDef.extensions || {};
  74203. var source;
  74204. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  74205. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  74206. } else {
  74207. source = json.images[ textureDef.source ];
  74208. }
  74209. var loader;
  74210. if ( source.uri ) {
  74211. loader = options.manager.getHandler( source.uri );
  74212. }
  74213. if ( ! loader ) {
  74214. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  74215. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  74216. : this.textureLoader;
  74217. }
  74218. return this.loadTextureImage( textureIndex, source, loader );
  74219. };
  74220. GLTFParser.prototype.loadTextureImage = function ( textureIndex, source, loader ) {
  74221. var parser = this;
  74222. var json = this.json;
  74223. var options = this.options;
  74224. var textureDef = json.textures[ textureIndex ];
  74225. var URL = self.URL || self.webkitURL;
  74226. var sourceURI = source.uri;
  74227. var isObjectURL = false;
  74228. var hasAlpha = true;
  74229. if ( source.mimeType === 'image/jpeg' ) hasAlpha = false;
  74230. if ( source.bufferView !== undefined ) {
  74231. // Load binary image data from bufferView, if provided.
  74232. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  74233. if ( source.mimeType === 'image/png' ) {
  74234. // Inspect the PNG 'IHDR' chunk to determine whether the image could have an
  74235. // alpha channel. This check is conservative — the image could have an alpha
  74236. // channel with all values == 1, and the indexed type (colorType == 3) only
  74237. // sometimes contains alpha.
  74238. //
  74239. // https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header
  74240. var colorType = new DataView( bufferView, 25, 1 ).getUint8( 0, false );
  74241. hasAlpha = colorType === 6 || colorType === 4 || colorType === 3;
  74242. }
  74243. isObjectURL = true;
  74244. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  74245. sourceURI = URL.createObjectURL( blob );
  74246. return sourceURI;
  74247. } );
  74248. }
  74249. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  74250. return new Promise( function ( resolve, reject ) {
  74251. /* var onLoad = resolve;
  74252. if ( loader.isImageBitmapLoader === true ) {
  74253. onLoad = function ( imageBitmap ) {
  74254. //console.log('resolveURL onLoad',textureIndex )
  74255. resolve( new CanvasTexture( imageBitmap ) );
  74256. };
  74257. }
  74258. */
  74259. //为了防止chrome出现报错 The source image could not be decoded. 导致reject,重新写贴图加载方式:
  74260. parser.textureLoader.load(sourceURI, (tex)=>{
  74261. tex.minFilter = THREE.LinearMipmapLinearFilter; //原本:NearestMipMapNearestFilter 闪烁
  74262. //tex.needsUpdate
  74263. resolve(tex);
  74264. });
  74265. return;
  74266. loader.load( resolveURL( sourceURI, options.path ), onLoad, undefined, (e,url)=>{
  74267. console.log('reject',textureIndex, arguments);
  74268. if ( loader.isImageBitmapLoader === true ) {
  74269. let img = new Image;
  74270. img.setAttribute('crossOrigin', 'Anonymous');
  74271. img.src = url;
  74272. resolve(new THREE.Texture(img));
  74273. /* img.onload = ()=>{
  74274. let canvas = document.createElement('canvas')
  74275. let context = canvas.getContext('2d')
  74276. context.canvas.width = img.width
  74277. context.canvas.height = img.height
  74278. context.drawImage(img, 0, 0, img.width, img.height)
  74279. resolve( new CanvasTexture( canvas ) );
  74280. console.log('自己绘制 onload', textureIndex)
  74281. } */
  74282. }else {
  74283. reject.apply(this,arguments);
  74284. }
  74285. } /* , reject */ );
  74286. } );
  74287. } ).then( function ( texture ) {
  74288. // Clean up resources and configure Texture.
  74289. //console.log('texture', textureIndex, texture.image)
  74290. if ( isObjectURL === true ) {
  74291. URL.revokeObjectURL( sourceURI );
  74292. }
  74293. texture.flipY = false;
  74294. if ( textureDef.name ) texture.name = textureDef.name;
  74295. // When there is definitely no alpha channel in the texture, set RGBFormat to save space.
  74296. if ( ! hasAlpha ) texture.format = RGBFormat;
  74297. var samplers = json.samplers || {};
  74298. var sampler = samplers[ textureDef.sampler ] || {};
  74299. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || LinearFilter;
  74300. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || LinearMipmapLinearFilter;
  74301. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || RepeatWrapping;
  74302. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || RepeatWrapping;
  74303. parser.associations.set( texture, {
  74304. type: 'textures',
  74305. index: textureIndex
  74306. } );
  74307. return texture;
  74308. } );
  74309. };
  74310. /**
  74311. * Asynchronously assigns a texture to the given material parameters.
  74312. * @param {Object} materialParams
  74313. * @param {string} mapName
  74314. * @param {Object} mapDef
  74315. * @return {Promise}
  74316. */
  74317. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  74318. var parser = this;
  74319. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  74320. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  74321. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  74322. if ( mapDef.texCoord !== undefined && mapDef.texCoord != 0 && ! ( mapName === 'aoMap' && mapDef.texCoord == 1 ) ) {
  74323. console.warn( 'THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.' );
  74324. }
  74325. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  74326. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  74327. if ( transform ) {
  74328. var gltfReference = parser.associations.get( texture );
  74329. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  74330. parser.associations.set( texture, gltfReference );
  74331. }
  74332. }
  74333. materialParams[ mapName ] = texture;
  74334. } );
  74335. };
  74336. /**
  74337. * Assigns final material to a Mesh, Line, or Points instance. The instance
  74338. * already has a material (generated from the glTF material options alone)
  74339. * but reuse of the same glTF material may require multiple threejs materials
  74340. * to accomodate different primitive types, defines, etc. New materials will
  74341. * be created if necessary, and reused from a cache.
  74342. * @param {Object3D} mesh Mesh, Line, or Points instance.
  74343. */
  74344. GLTFParser.prototype.assignFinalMaterial = function ( mesh ) {
  74345. var geometry = mesh.geometry;
  74346. var material = mesh.material;
  74347. var useVertexTangents = geometry.attributes.tangent !== undefined;
  74348. var useVertexColors = geometry.attributes.color !== undefined;
  74349. var useFlatShading = geometry.attributes.normal === undefined;
  74350. var useSkinning = mesh.isSkinnedMesh === true;
  74351. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  74352. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  74353. if ( mesh.isPoints ) {
  74354. var cacheKey = 'PointsMaterial:' + material.uuid;
  74355. var pointsMaterial = this.cache.get( cacheKey );
  74356. if ( ! pointsMaterial ) {
  74357. pointsMaterial = new PointsMaterial();
  74358. Material.prototype.copy.call( pointsMaterial, material );
  74359. pointsMaterial.color.copy( material.color );
  74360. pointsMaterial.map = material.map;
  74361. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  74362. this.cache.add( cacheKey, pointsMaterial );
  74363. }
  74364. material = pointsMaterial;
  74365. } else if ( mesh.isLine ) {
  74366. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  74367. var lineMaterial = this.cache.get( cacheKey );
  74368. if ( ! lineMaterial ) {
  74369. lineMaterial = new LineBasicMaterial();
  74370. Material.prototype.copy.call( lineMaterial, material );
  74371. lineMaterial.color.copy( material.color );
  74372. this.cache.add( cacheKey, lineMaterial );
  74373. }
  74374. material = lineMaterial;
  74375. }
  74376. // Clone the material if it will be modified
  74377. if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  74378. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  74379. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  74380. if ( useSkinning ) cacheKey += 'skinning:';
  74381. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  74382. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  74383. if ( useFlatShading ) cacheKey += 'flat-shading:';
  74384. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  74385. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  74386. var cachedMaterial = this.cache.get( cacheKey );
  74387. if ( ! cachedMaterial ) {
  74388. cachedMaterial = material.clone();
  74389. if ( useSkinning ) cachedMaterial.skinning = true;
  74390. if ( useVertexTangents ) cachedMaterial.vertexTangents = true;
  74391. if ( useVertexColors ) cachedMaterial.vertexColors = true;
  74392. if ( useFlatShading ) cachedMaterial.flatShading = true;
  74393. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  74394. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  74395. this.cache.add( cacheKey, cachedMaterial );
  74396. this.associations.set( cachedMaterial, this.associations.get( material ) );
  74397. }
  74398. material = cachedMaterial;
  74399. }
  74400. // workarounds for mesh and geometry
  74401. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  74402. geometry.setAttribute( 'uv2', geometry.attributes.uv );
  74403. }
  74404. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  74405. if ( material.normalScale && ! useVertexTangents ) {
  74406. material.normalScale.y = - material.normalScale.y;
  74407. }
  74408. if ( material.clearcoatNormalScale && ! useVertexTangents ) {
  74409. material.clearcoatNormalScale.y = - material.clearcoatNormalScale.y;
  74410. }
  74411. mesh.material = material;
  74412. };
  74413. GLTFParser.prototype.getMaterialType = function ( /* materialIndex */ ) {
  74414. return this.unlitMat ? MeshBasicMaterial : MeshStandardMaterial; //xzw add unlitMat
  74415. };
  74416. /**
  74417. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  74418. * @param {number} materialIndex
  74419. * @return {Promise<Material>}
  74420. */
  74421. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  74422. var parser = this;
  74423. var json = this.json;
  74424. var extensions = this.extensions;
  74425. var materialDef = json.materials[ materialIndex ];
  74426. var materialType;
  74427. var materialParams = {};
  74428. var materialExtensions = materialDef.extensions || {};
  74429. var pending = [];
  74430. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  74431. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  74432. materialType = sgExtension.getMaterialType();
  74433. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  74434. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  74435. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  74436. materialType = kmuExtension.getMaterialType();
  74437. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  74438. } else {
  74439. // Specification:
  74440. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  74441. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  74442. materialParams.color = new Color( 1.0, 1.0, 1.0 );
  74443. materialParams.opacity = 1.0;
  74444. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  74445. var array = metallicRoughness.baseColorFactor;
  74446. materialParams.color.fromArray( array );
  74447. materialParams.opacity = array[ 3 ];
  74448. }
  74449. if ( metallicRoughness.baseColorTexture !== undefined ) {
  74450. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  74451. }
  74452. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  74453. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  74454. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  74455. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  74456. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  74457. }
  74458. materialType = this._invokeOne( function ( ext ) {
  74459. return ext.getMaterialType && ext.getMaterialType( materialIndex );
  74460. } );
  74461. pending.push( Promise.all( this._invokeAll( function ( ext ) {
  74462. return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );
  74463. } ) ) );
  74464. }
  74465. if ( materialDef.doubleSided === true ) {
  74466. materialParams.side = DoubleSide;
  74467. }
  74468. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  74469. if ( alphaMode === ALPHA_MODES.BLEND ) {
  74470. materialParams.transparent = true;
  74471. // See: https://github.com/mrdoob/three.js/issues/17706
  74472. materialParams.depthWrite = false;
  74473. } else {
  74474. materialParams.transparent = false;
  74475. if ( alphaMode === ALPHA_MODES.MASK ) {
  74476. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  74477. }
  74478. }
  74479. if ( materialDef.normalTexture !== undefined && materialType !== MeshBasicMaterial ) {
  74480. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  74481. materialParams.normalScale = new Vector2$1( 1, 1 );
  74482. if ( materialDef.normalTexture.scale !== undefined ) {
  74483. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  74484. }
  74485. }
  74486. if ( materialDef.occlusionTexture !== undefined && materialType !== MeshBasicMaterial ) {
  74487. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  74488. if ( materialDef.occlusionTexture.strength !== undefined ) {
  74489. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  74490. }
  74491. }
  74492. if ( materialDef.emissiveFactor !== undefined && materialType !== MeshBasicMaterial ) {
  74493. materialParams.emissive = new Color().fromArray( materialDef.emissiveFactor );
  74494. }
  74495. if ( materialDef.emissiveTexture !== undefined && materialType !== MeshBasicMaterial ) {
  74496. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  74497. }
  74498. return Promise.all( pending ).then( function () {
  74499. var material;
  74500. if ( materialType === GLTFMeshStandardSGMaterial ) {
  74501. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  74502. } else {
  74503. material = new materialType( materialParams );
  74504. }
  74505. if ( materialDef.name ) material.name = materialDef.name;
  74506. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  74507. if ( material.map ) material.map.encoding = sRGBEncoding;
  74508. if ( material.emissiveMap ) material.emissiveMap.encoding = sRGBEncoding;
  74509. assignExtrasToUserData( material, materialDef );
  74510. parser.associations.set( material, { type: 'materials', index: materialIndex } );
  74511. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  74512. return material;
  74513. } );
  74514. };
  74515. /** When Object3D instances are targeted by animation, they need unique names. */
  74516. GLTFParser.prototype.createUniqueName = function ( originalName ) {
  74517. var sanitizedName = PropertyBinding.sanitizeNodeName( originalName || '' );
  74518. var name = sanitizedName;
  74519. for ( var i = 1; this.nodeNamesUsed[ name ]; ++ i ) {
  74520. name = sanitizedName + '_' + i;
  74521. }
  74522. this.nodeNamesUsed[ name ] = true;
  74523. return name;
  74524. };
  74525. /**
  74526. * @param {BufferGeometry} geometry
  74527. * @param {GLTF.Primitive} primitiveDef
  74528. * @param {GLTFParser} parser
  74529. */
  74530. function computeBounds( geometry, primitiveDef, parser ) {
  74531. var attributes = primitiveDef.attributes;
  74532. var box = new Box3();
  74533. if ( attributes.POSITION !== undefined ) {
  74534. var accessor = parser.json.accessors[ attributes.POSITION ];
  74535. var min = accessor.min;
  74536. var max = accessor.max;
  74537. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  74538. if ( min !== undefined && max !== undefined ) {
  74539. box.set(
  74540. new Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
  74541. new Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) );
  74542. } else {
  74543. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  74544. return;
  74545. }
  74546. } else {
  74547. return;
  74548. }
  74549. var targets = primitiveDef.targets;
  74550. if ( targets !== undefined ) {
  74551. var maxDisplacement = new Vector3();
  74552. var vector = new Vector3();
  74553. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  74554. var target = targets[ i ];
  74555. if ( target.POSITION !== undefined ) {
  74556. var accessor = parser.json.accessors[ target.POSITION ];
  74557. var min = accessor.min;
  74558. var max = accessor.max;
  74559. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  74560. if ( min !== undefined && max !== undefined ) {
  74561. // we need to get max of absolute components because target weight is [-1,1]
  74562. vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
  74563. vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
  74564. vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
  74565. // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  74566. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  74567. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  74568. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  74569. maxDisplacement.max( vector );
  74570. } else {
  74571. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  74572. }
  74573. }
  74574. }
  74575. // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  74576. box.expandByVector( maxDisplacement );
  74577. }
  74578. geometry.boundingBox = box;
  74579. var sphere = new Sphere();
  74580. box.getCenter( sphere.center );
  74581. sphere.radius = box.min.distanceTo( box.max ) / 2;
  74582. geometry.boundingSphere = sphere;
  74583. }
  74584. /**
  74585. * @param {BufferGeometry} geometry
  74586. * @param {GLTF.Primitive} primitiveDef
  74587. * @param {GLTFParser} parser
  74588. * @return {Promise<BufferGeometry>}
  74589. */
  74590. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  74591. var attributes = primitiveDef.attributes;
  74592. var pending = [];
  74593. function assignAttributeAccessor( accessorIndex, attributeName ) {
  74594. return parser.getDependency( 'accessor', accessorIndex )
  74595. .then( function ( accessor ) {
  74596. geometry.setAttribute( attributeName, accessor );
  74597. } );
  74598. }
  74599. for ( var gltfAttributeName in attributes ) {
  74600. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  74601. // Skip attributes already provided by e.g. Draco extension.
  74602. if ( threeAttributeName in geometry.attributes ) continue;
  74603. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  74604. }
  74605. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  74606. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  74607. geometry.setIndex( accessor );
  74608. } );
  74609. pending.push( accessor );
  74610. }
  74611. assignExtrasToUserData( geometry, primitiveDef );
  74612. computeBounds( geometry, primitiveDef, parser );
  74613. return Promise.all( pending ).then( function () {
  74614. return primitiveDef.targets !== undefined
  74615. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  74616. : geometry;
  74617. } );
  74618. }
  74619. /**
  74620. * @param {BufferGeometry} geometry
  74621. * @param {Number} drawMode
  74622. * @return {BufferGeometry}
  74623. */
  74624. function toTrianglesDrawMode( geometry, drawMode ) {
  74625. var index = geometry.getIndex();
  74626. // generate index if not present
  74627. if ( index === null ) {
  74628. var indices = [];
  74629. var position = geometry.getAttribute( 'position' );
  74630. if ( position !== undefined ) {
  74631. for ( var i = 0; i < position.count; i ++ ) {
  74632. indices.push( i );
  74633. }
  74634. geometry.setIndex( indices );
  74635. index = geometry.getIndex();
  74636. } else {
  74637. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  74638. return geometry;
  74639. }
  74640. }
  74641. //
  74642. var numberOfTriangles = index.count - 2;
  74643. var newIndices = [];
  74644. if ( drawMode === TriangleFanDrawMode ) {
  74645. // gl.TRIANGLE_FAN
  74646. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  74647. newIndices.push( index.getX( 0 ) );
  74648. newIndices.push( index.getX( i ) );
  74649. newIndices.push( index.getX( i + 1 ) );
  74650. }
  74651. } else {
  74652. // gl.TRIANGLE_STRIP
  74653. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  74654. if ( i % 2 === 0 ) {
  74655. newIndices.push( index.getX( i ) );
  74656. newIndices.push( index.getX( i + 1 ) );
  74657. newIndices.push( index.getX( i + 2 ) );
  74658. } else {
  74659. newIndices.push( index.getX( i + 2 ) );
  74660. newIndices.push( index.getX( i + 1 ) );
  74661. newIndices.push( index.getX( i ) );
  74662. }
  74663. }
  74664. }
  74665. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  74666. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  74667. }
  74668. // build final geometry
  74669. var newGeometry = geometry.clone();
  74670. newGeometry.setIndex( newIndices );
  74671. return newGeometry;
  74672. }
  74673. /**
  74674. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  74675. *
  74676. * Creates BufferGeometries from primitives.
  74677. *
  74678. * @param {Array<GLTF.Primitive>} primitives
  74679. * @return {Promise<Array<BufferGeometry>>}
  74680. */
  74681. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  74682. var parser = this;
  74683. var extensions = this.extensions;
  74684. var cache = this.primitiveCache;
  74685. function createDracoPrimitive( primitive ) {
  74686. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  74687. .decodePrimitive( primitive, parser )
  74688. .then( function ( geometry ) {
  74689. return addPrimitiveAttributes( geometry, primitive, parser );
  74690. } );
  74691. }
  74692. var pending = [];
  74693. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  74694. var primitive = primitives[ i ];
  74695. var cacheKey = createPrimitiveKey( primitive );
  74696. // See if we've already created this geometry
  74697. var cached = cache[ cacheKey ];
  74698. if ( cached ) {
  74699. // Use the cached geometry if it exists
  74700. pending.push( cached.promise );
  74701. } else {
  74702. var geometryPromise;
  74703. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  74704. // Use DRACO geometry if available
  74705. geometryPromise = createDracoPrimitive( primitive );
  74706. } else {
  74707. // Otherwise create a new geometry
  74708. geometryPromise = addPrimitiveAttributes( new BufferGeometry(), primitive, parser );
  74709. }
  74710. // Cache this geometry
  74711. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  74712. pending.push( geometryPromise );
  74713. }
  74714. }
  74715. return Promise.all( pending );
  74716. };
  74717. /**
  74718. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  74719. * @param {number} meshIndex
  74720. * @return {Promise<Group|Mesh|SkinnedMesh>}
  74721. */
  74722. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  74723. var parser = this;
  74724. var json = this.json;
  74725. var extensions = this.extensions;
  74726. var meshDef = json.meshes[ meshIndex ];
  74727. var primitives = meshDef.primitives;
  74728. var pending = [];
  74729. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  74730. var material = primitives[ i ].material === undefined
  74731. ? createDefaultMaterial( this.cache )
  74732. : this.getDependency( 'material', primitives[ i ].material );
  74733. pending.push( material );
  74734. }
  74735. pending.push( parser.loadGeometries( primitives ) );
  74736. return Promise.all( pending ).then( function ( results ) {
  74737. var materials = results.slice( 0, results.length - 1 );
  74738. var geometries = results[ results.length - 1 ];
  74739. var meshes = [];
  74740. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  74741. var geometry = geometries[ i ];
  74742. var primitive = primitives[ i ];
  74743. // 1. create Mesh
  74744. var mesh;
  74745. var material = materials[ i ];
  74746. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  74747. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  74748. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  74749. primitive.mode === undefined ) {
  74750. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  74751. mesh = meshDef.isSkinnedMesh === true
  74752. ? new SkinnedMesh( geometry, material )
  74753. : new Mesh( geometry, material );
  74754. if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) {
  74755. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  74756. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  74757. mesh.normalizeSkinWeights();
  74758. }
  74759. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  74760. mesh.geometry = toTrianglesDrawMode( mesh.geometry, TriangleStripDrawMode );
  74761. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  74762. mesh.geometry = toTrianglesDrawMode( mesh.geometry, TriangleFanDrawMode );
  74763. }
  74764. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  74765. mesh = new LineSegments( geometry, material );
  74766. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  74767. mesh = new Line( geometry, material );
  74768. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  74769. mesh = new LineLoop( geometry, material );
  74770. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  74771. mesh = new Points( geometry, material );
  74772. } else {
  74773. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  74774. }
  74775. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  74776. updateMorphTargets( mesh, meshDef );
  74777. }
  74778. mesh.name = parser.createUniqueName( meshDef.name || ( 'mesh_' + meshIndex ) );
  74779. assignExtrasToUserData( mesh, meshDef );
  74780. if ( primitive.extensions ) addUnknownExtensionsToUserData( extensions, mesh, primitive );
  74781. parser.assignFinalMaterial( mesh );
  74782. meshes.push( mesh );
  74783. }
  74784. if ( meshes.length === 1 ) {
  74785. return meshes[ 0 ];
  74786. }
  74787. var group = new Group();
  74788. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  74789. group.add( meshes[ i ] );
  74790. }
  74791. return group;
  74792. } );
  74793. };
  74794. /**
  74795. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  74796. * @param {number} cameraIndex
  74797. * @return {Promise<THREE.Camera>}
  74798. */
  74799. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  74800. var camera;
  74801. var cameraDef = this.json.cameras[ cameraIndex ];
  74802. var params = cameraDef[ cameraDef.type ];
  74803. if ( ! params ) {
  74804. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  74805. return;
  74806. }
  74807. if ( cameraDef.type === 'perspective' ) {
  74808. camera = new PerspectiveCamera( MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  74809. } else if ( cameraDef.type === 'orthographic' ) {
  74810. camera = new OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
  74811. }
  74812. if ( cameraDef.name ) camera.name = this.createUniqueName( cameraDef.name );
  74813. assignExtrasToUserData( camera, cameraDef );
  74814. return Promise.resolve( camera );
  74815. };
  74816. /**
  74817. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  74818. * @param {number} skinIndex
  74819. * @return {Promise<Object>}
  74820. */
  74821. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  74822. var skinDef = this.json.skins[ skinIndex ];
  74823. var skinEntry = { joints: skinDef.joints };
  74824. if ( skinDef.inverseBindMatrices === undefined ) {
  74825. return Promise.resolve( skinEntry );
  74826. }
  74827. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  74828. skinEntry.inverseBindMatrices = accessor;
  74829. return skinEntry;
  74830. } );
  74831. };
  74832. /**
  74833. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  74834. * @param {number} animationIndex
  74835. * @return {Promise<AnimationClip>}
  74836. */
  74837. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  74838. var json = this.json;
  74839. var animationDef = json.animations[ animationIndex ];
  74840. var pendingNodes = [];
  74841. var pendingInputAccessors = [];
  74842. var pendingOutputAccessors = [];
  74843. var pendingSamplers = [];
  74844. var pendingTargets = [];
  74845. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  74846. var channel = animationDef.channels[ i ];
  74847. var sampler = animationDef.samplers[ channel.sampler ];
  74848. var target = channel.target;
  74849. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  74850. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  74851. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  74852. pendingNodes.push( this.getDependency( 'node', name ) );
  74853. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  74854. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  74855. pendingSamplers.push( sampler );
  74856. pendingTargets.push( target );
  74857. }
  74858. return Promise.all( [
  74859. Promise.all( pendingNodes ),
  74860. Promise.all( pendingInputAccessors ),
  74861. Promise.all( pendingOutputAccessors ),
  74862. Promise.all( pendingSamplers ),
  74863. Promise.all( pendingTargets )
  74864. ] ).then( function ( dependencies ) {
  74865. var nodes = dependencies[ 0 ];
  74866. var inputAccessors = dependencies[ 1 ];
  74867. var outputAccessors = dependencies[ 2 ];
  74868. var samplers = dependencies[ 3 ];
  74869. var targets = dependencies[ 4 ];
  74870. var tracks = [];
  74871. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  74872. var node = nodes[ i ];
  74873. var inputAccessor = inputAccessors[ i ];
  74874. var outputAccessor = outputAccessors[ i ];
  74875. var sampler = samplers[ i ];
  74876. var target = targets[ i ];
  74877. if ( node === undefined ) continue;
  74878. node.updateMatrix();
  74879. node.matrixAutoUpdate = true;
  74880. var TypedKeyframeTrack;
  74881. switch ( PATH_PROPERTIES[ target.path ] ) {
  74882. case PATH_PROPERTIES.weights:
  74883. TypedKeyframeTrack = NumberKeyframeTrack;
  74884. break;
  74885. case PATH_PROPERTIES.rotation:
  74886. TypedKeyframeTrack = QuaternionKeyframeTrack;
  74887. break;
  74888. case PATH_PROPERTIES.position:
  74889. case PATH_PROPERTIES.scale:
  74890. default:
  74891. TypedKeyframeTrack = VectorKeyframeTrack;
  74892. break;
  74893. }
  74894. var targetName = node.name ? node.name : node.uuid;
  74895. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : InterpolateLinear;
  74896. var targetNames = [];
  74897. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  74898. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  74899. node.traverse( function ( object ) {
  74900. if ( object.isMesh === true && object.morphTargetInfluences ) {
  74901. targetNames.push( object.name ? object.name : object.uuid );
  74902. }
  74903. } );
  74904. } else {
  74905. targetNames.push( targetName );
  74906. }
  74907. var outputArray = outputAccessor.array;
  74908. if ( outputAccessor.normalized ) {
  74909. var scale;
  74910. if ( outputArray.constructor === Int8Array ) {
  74911. scale = 1 / 127;
  74912. } else if ( outputArray.constructor === Uint8Array ) {
  74913. scale = 1 / 255;
  74914. } else if ( outputArray.constructor == Int16Array ) {
  74915. scale = 1 / 32767;
  74916. } else if ( outputArray.constructor === Uint16Array ) {
  74917. scale = 1 / 65535;
  74918. } else {
  74919. throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' );
  74920. }
  74921. var scaled = new Float32Array( outputArray.length );
  74922. for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) {
  74923. scaled[ j ] = outputArray[ j ] * scale;
  74924. }
  74925. outputArray = scaled;
  74926. }
  74927. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  74928. var track = new TypedKeyframeTrack(
  74929. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  74930. inputAccessor.array,
  74931. outputArray,
  74932. interpolation
  74933. );
  74934. // Override interpolation with custom factory method.
  74935. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  74936. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  74937. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  74938. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  74939. // must be divided by three to get the interpolant's sampleSize argument.
  74940. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  74941. };
  74942. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  74943. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  74944. }
  74945. tracks.push( track );
  74946. }
  74947. }
  74948. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  74949. return new AnimationClip( name, undefined, tracks );
  74950. } );
  74951. };
  74952. /**
  74953. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  74954. * @param {number} nodeIndex
  74955. * @return {Promise<Object3D>}
  74956. */
  74957. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  74958. var json = this.json;
  74959. var extensions = this.extensions;
  74960. var parser = this;
  74961. var nodeDef = json.nodes[ nodeIndex ];
  74962. // reserve node's name before its dependencies, so the root has the intended name.
  74963. var nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : '';
  74964. return ( function () {
  74965. var pending = [];
  74966. if ( nodeDef.mesh !== undefined ) {
  74967. pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  74968. var node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );
  74969. // if weights are provided on the node, override weights on the mesh.
  74970. if ( nodeDef.weights !== undefined ) {
  74971. node.traverse( function ( o ) {
  74972. if ( ! o.isMesh ) return;
  74973. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  74974. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  74975. }
  74976. } );
  74977. }
  74978. return node;
  74979. } ) );
  74980. }
  74981. if ( nodeDef.camera !== undefined ) {
  74982. pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {
  74983. return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );
  74984. } ) );
  74985. }
  74986. parser._invokeAll( function ( ext ) {
  74987. return ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex );
  74988. } ).forEach( function ( promise ) {
  74989. pending.push( promise );
  74990. } );
  74991. return Promise.all( pending );
  74992. }() ).then( function ( objects ) {
  74993. var node;
  74994. // .isBone isn't in glTF spec. See ._markDefs
  74995. if ( nodeDef.isBone === true ) {
  74996. node = new Bone();
  74997. } else if ( objects.length > 1 ) {
  74998. node = new Group();
  74999. } else if ( objects.length === 1 ) {
  75000. node = objects[ 0 ];
  75001. } else {
  75002. node = new Object3D();
  75003. }
  75004. if ( node !== objects[ 0 ] ) {
  75005. for ( var i = 0, il = objects.length; i < il; i ++ ) {
  75006. node.add( objects[ i ] );
  75007. }
  75008. }
  75009. if ( nodeDef.name ) {
  75010. node.userData.name = nodeDef.name;
  75011. node.name = nodeName;
  75012. }
  75013. assignExtrasToUserData( node, nodeDef );
  75014. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  75015. if ( nodeDef.matrix !== undefined ) {
  75016. var matrix = new Matrix4();
  75017. matrix.fromArray( nodeDef.matrix );
  75018. node.applyMatrix4( matrix );
  75019. } else {
  75020. if ( nodeDef.translation !== undefined ) {
  75021. node.position.fromArray( nodeDef.translation );
  75022. }
  75023. if ( nodeDef.rotation !== undefined ) {
  75024. node.quaternion.fromArray( nodeDef.rotation );
  75025. }
  75026. if ( nodeDef.scale !== undefined ) {
  75027. node.scale.fromArray( nodeDef.scale );
  75028. }
  75029. }
  75030. parser.associations.set( node, { type: 'nodes', index: nodeIndex } );
  75031. return node;
  75032. } );
  75033. };
  75034. /**
  75035. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  75036. * @param {number} sceneIndex
  75037. * @return {Promise<Group>}
  75038. */
  75039. GLTFParser.prototype.loadScene = function () {
  75040. // scene node hierachy builder
  75041. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  75042. var nodeDef = json.nodes[ nodeId ];
  75043. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  75044. if ( nodeDef.skin === undefined ) return node;
  75045. // build skeleton here as well
  75046. var skinEntry;
  75047. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  75048. skinEntry = skin;
  75049. var pendingJoints = [];
  75050. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  75051. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  75052. }
  75053. return Promise.all( pendingJoints );
  75054. } ).then( function ( jointNodes ) {
  75055. node.traverse( function ( mesh ) {
  75056. if ( ! mesh.isMesh ) return;
  75057. var bones = [];
  75058. var boneInverses = [];
  75059. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  75060. var jointNode = jointNodes[ j ];
  75061. if ( jointNode ) {
  75062. bones.push( jointNode );
  75063. var mat = new Matrix4();
  75064. if ( skinEntry.inverseBindMatrices !== undefined ) {
  75065. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  75066. }
  75067. boneInverses.push( mat );
  75068. } else {
  75069. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  75070. }
  75071. }
  75072. mesh.bind( new Skeleton( bones, boneInverses ), mesh.matrixWorld );
  75073. } );
  75074. return node;
  75075. } );
  75076. } ).then( function ( node ) {
  75077. // build node hierachy
  75078. parentObject.add( node );
  75079. var pending = [];
  75080. if ( nodeDef.children ) {
  75081. var children = nodeDef.children;
  75082. for ( var i = 0, il = children.length; i < il; i ++ ) {
  75083. var child = children[ i ];
  75084. pending.push( buildNodeHierachy( child, node, json, parser ) );
  75085. }
  75086. }
  75087. return Promise.all( pending );
  75088. } );
  75089. }
  75090. return function loadScene( sceneIndex ) {
  75091. var json = this.json;
  75092. var extensions = this.extensions;
  75093. var sceneDef = this.json.scenes[ sceneIndex ];
  75094. var parser = this;
  75095. // Loader returns Group, not Scene.
  75096. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  75097. var scene = new Group();
  75098. if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name );
  75099. assignExtrasToUserData( scene, sceneDef );
  75100. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  75101. var nodeIds = sceneDef.nodes || [];
  75102. var pending = [];
  75103. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  75104. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  75105. }
  75106. return Promise.all( pending ).then( function () {
  75107. return scene;
  75108. } );
  75109. };
  75110. }();
  75111. return GLTFLoader;
  75112. } )();
  75113. /**
  75114. * @webxr-input-profiles/motion-controllers 1.0.0 https://github.com/immersive-web/webxr-input-profiles
  75115. */
  75116. const Constants = {
  75117. Handedness: Object.freeze({
  75118. NONE: 'none',
  75119. LEFT: 'left',
  75120. RIGHT: 'right'
  75121. }),
  75122. ComponentState: Object.freeze({
  75123. DEFAULT: 'default',
  75124. TOUCHED: 'touched',
  75125. PRESSED: 'pressed'
  75126. }),
  75127. ComponentProperty: Object.freeze({
  75128. BUTTON: 'button',
  75129. X_AXIS: 'xAxis',
  75130. Y_AXIS: 'yAxis',
  75131. STATE: 'state'
  75132. }),
  75133. ComponentType: Object.freeze({
  75134. TRIGGER: 'trigger',
  75135. SQUEEZE: 'squeeze',
  75136. TOUCHPAD: 'touchpad',
  75137. THUMBSTICK: 'thumbstick',
  75138. BUTTON: 'button'
  75139. }),
  75140. ButtonTouchThreshold: 0.05,
  75141. AxisTouchThreshold: 0.1,
  75142. VisualResponseProperty: Object.freeze({
  75143. TRANSFORM: 'transform',
  75144. VISIBILITY: 'visibility'
  75145. })
  75146. };
  75147. /**
  75148. * @description Static helper function to fetch a JSON file and turn it into a JS object
  75149. * @param {string} path - Path to JSON file to be fetched
  75150. */
  75151. async function fetchJsonFile(path) {
  75152. const response = await fetch(path);
  75153. if (!response.ok) {
  75154. throw new Error(response.statusText);
  75155. } else {
  75156. return response.json();
  75157. }
  75158. }
  75159. async function fetchProfilesList(basePath) {
  75160. if (!basePath) {
  75161. throw new Error('No basePath supplied');
  75162. }
  75163. const profileListFileName = 'profilesList.json';
  75164. const profilesList = await fetchJsonFile(`${basePath}/${profileListFileName}`);
  75165. return profilesList;
  75166. }
  75167. async function fetchProfile(xrInputSource, basePath, defaultProfile = null, getAssetPath = true) {
  75168. if (!xrInputSource) {
  75169. throw new Error('No xrInputSource supplied');
  75170. }
  75171. if (!basePath) {
  75172. throw new Error('No basePath supplied');
  75173. }
  75174. // Get the list of profiles
  75175. const supportedProfilesList = await fetchProfilesList(basePath);
  75176. // Find the relative path to the first requested profile that is recognized
  75177. let match;
  75178. xrInputSource.profiles.some((profileId) => {
  75179. const supportedProfile = supportedProfilesList[profileId];
  75180. if (supportedProfile) {
  75181. match = {
  75182. profileId,
  75183. profilePath: `${basePath}/${supportedProfile.path}`,
  75184. deprecated: !!supportedProfile.deprecated
  75185. };
  75186. }
  75187. return !!match;
  75188. });
  75189. if (!match) {
  75190. if (!defaultProfile) {
  75191. throw new Error('No matching profile name found');
  75192. }
  75193. const supportedProfile = supportedProfilesList[defaultProfile];
  75194. if (!supportedProfile) {
  75195. throw new Error(`No matching profile name found and default profile "${defaultProfile}" missing.`);
  75196. }
  75197. match = {
  75198. profileId: defaultProfile,
  75199. profilePath: `${basePath}/${supportedProfile.path}`,
  75200. deprecated: !!supportedProfile.deprecated
  75201. };
  75202. }
  75203. const profile = await fetchJsonFile(match.profilePath);
  75204. let assetPath;
  75205. if (getAssetPath) {
  75206. let layout;
  75207. if (xrInputSource.handedness === 'any') {
  75208. layout = profile.layouts[Object.keys(profile.layouts)[0]];
  75209. } else {
  75210. layout = profile.layouts[xrInputSource.handedness];
  75211. }
  75212. if (!layout) {
  75213. throw new Error(
  75214. `No matching handedness, ${xrInputSource.handedness}, in profile ${match.profileId}`
  75215. );
  75216. }
  75217. if (layout.assetPath) {
  75218. assetPath = match.profilePath.replace('profile.json', layout.assetPath);
  75219. }
  75220. }
  75221. return { profile, assetPath };
  75222. }
  75223. /** @constant {Object} */
  75224. const defaultComponentValues = {
  75225. xAxis: 0,
  75226. yAxis: 0,
  75227. button: 0,
  75228. state: Constants.ComponentState.DEFAULT
  75229. };
  75230. /**
  75231. * @description Converts an X, Y coordinate from the range -1 to 1 (as reported by the Gamepad
  75232. * API) to the range 0 to 1 (for interpolation). Also caps the X, Y values to be bounded within
  75233. * a circle. This ensures that thumbsticks are not animated outside the bounds of their physical
  75234. * range of motion and touchpads do not report touch locations off their physical bounds.
  75235. * @param {number} x The original x coordinate in the range -1 to 1
  75236. * @param {number} y The original y coordinate in the range -1 to 1
  75237. */
  75238. function normalizeAxes(x = 0, y = 0) {
  75239. let xAxis = x;
  75240. let yAxis = y;
  75241. // Determine if the point is outside the bounds of the circle
  75242. // and, if so, place it on the edge of the circle
  75243. const hypotenuse = Math.sqrt((x * x) + (y * y));
  75244. if (hypotenuse > 1) {
  75245. const theta = Math.atan2(y, x);
  75246. xAxis = Math.cos(theta);
  75247. yAxis = Math.sin(theta);
  75248. }
  75249. // Scale and move the circle so values are in the interpolation range. The circle's origin moves
  75250. // from (0, 0) to (0.5, 0.5). The circle's radius scales from 1 to be 0.5.
  75251. const result = {
  75252. normalizedXAxis: (xAxis * 0.5) + 0.5,
  75253. normalizedYAxis: (yAxis * 0.5) + 0.5
  75254. };
  75255. return result;
  75256. }
  75257. /**
  75258. * Contains the description of how the 3D model should visually respond to a specific user input.
  75259. * This is accomplished by initializing the object with the name of a node in the 3D model and
  75260. * property that need to be modified in response to user input, the name of the nodes representing
  75261. * the allowable range of motion, and the name of the input which triggers the change. In response
  75262. * to the named input changing, this object computes the appropriate weighting to use for
  75263. * interpolating between the range of motion nodes.
  75264. */
  75265. class VisualResponse {
  75266. constructor(visualResponseDescription) {
  75267. this.componentProperty = visualResponseDescription.componentProperty;
  75268. this.states = visualResponseDescription.states;
  75269. this.valueNodeName = visualResponseDescription.valueNodeName;
  75270. this.valueNodeProperty = visualResponseDescription.valueNodeProperty;
  75271. if (this.valueNodeProperty === Constants.VisualResponseProperty.TRANSFORM) {
  75272. this.minNodeName = visualResponseDescription.minNodeName;
  75273. this.maxNodeName = visualResponseDescription.maxNodeName;
  75274. }
  75275. // Initializes the response's current value based on default data
  75276. this.value = 0;
  75277. this.updateFromComponent(defaultComponentValues);
  75278. }
  75279. /**
  75280. * Computes the visual response's interpolation weight based on component state
  75281. * @param {Object} componentValues - The component from which to update
  75282. * @param {number} xAxis - The reported X axis value of the component
  75283. * @param {number} yAxis - The reported Y axis value of the component
  75284. * @param {number} button - The reported value of the component's button
  75285. * @param {string} state - The component's active state
  75286. */
  75287. updateFromComponent({
  75288. xAxis, yAxis, button, state
  75289. }) {
  75290. const { normalizedXAxis, normalizedYAxis } = normalizeAxes(xAxis, yAxis);
  75291. switch (this.componentProperty) {
  75292. case Constants.ComponentProperty.X_AXIS:
  75293. this.value = (this.states.includes(state)) ? normalizedXAxis : 0.5;
  75294. break;
  75295. case Constants.ComponentProperty.Y_AXIS:
  75296. this.value = (this.states.includes(state)) ? normalizedYAxis : 0.5;
  75297. break;
  75298. case Constants.ComponentProperty.BUTTON:
  75299. this.value = (this.states.includes(state)) ? button : 0;
  75300. break;
  75301. case Constants.ComponentProperty.STATE:
  75302. if (this.valueNodeProperty === Constants.VisualResponseProperty.VISIBILITY) {
  75303. this.value = (this.states.includes(state));
  75304. } else {
  75305. this.value = this.states.includes(state) ? 1.0 : 0.0;
  75306. }
  75307. break;
  75308. default:
  75309. throw new Error(`Unexpected visualResponse componentProperty ${this.componentProperty}`);
  75310. }
  75311. }
  75312. }
  75313. class Component {
  75314. /**
  75315. * @param {Object} componentId - Id of the component
  75316. * @param {Object} componentDescription - Description of the component to be created
  75317. */
  75318. constructor(componentId, componentDescription) {
  75319. if (!componentId
  75320. || !componentDescription
  75321. || !componentDescription.visualResponses
  75322. || !componentDescription.gamepadIndices
  75323. || Object.keys(componentDescription.gamepadIndices).length === 0) {
  75324. throw new Error('Invalid arguments supplied');
  75325. }
  75326. this.id = componentId;
  75327. this.type = componentDescription.type;
  75328. this.rootNodeName = componentDescription.rootNodeName;
  75329. this.touchPointNodeName = componentDescription.touchPointNodeName;
  75330. // Build all the visual responses for this component
  75331. this.visualResponses = {};
  75332. Object.keys(componentDescription.visualResponses).forEach((responseName) => {
  75333. const visualResponse = new VisualResponse(componentDescription.visualResponses[responseName]);
  75334. this.visualResponses[responseName] = visualResponse;
  75335. });
  75336. // Set default values
  75337. this.gamepadIndices = Object.assign({}, componentDescription.gamepadIndices);
  75338. this.values = {
  75339. state: Constants.ComponentState.DEFAULT,
  75340. button: (this.gamepadIndices.button !== undefined) ? 0 : undefined,
  75341. xAxis: (this.gamepadIndices.xAxis !== undefined) ? 0 : undefined,
  75342. yAxis: (this.gamepadIndices.yAxis !== undefined) ? 0 : undefined
  75343. };
  75344. }
  75345. get data() {
  75346. const data = { id: this.id, ...this.values };
  75347. return data;
  75348. }
  75349. /**
  75350. * @description Poll for updated data based on current gamepad state
  75351. * @param {Object} gamepad - The gamepad object from which the component data should be polled
  75352. */
  75353. updateFromGamepad(gamepad) {
  75354. // Set the state to default before processing other data sources
  75355. this.values.state = Constants.ComponentState.DEFAULT;
  75356. // Get and normalize button
  75357. if (this.gamepadIndices.button !== undefined
  75358. && gamepad.buttons.length > this.gamepadIndices.button) {
  75359. const gamepadButton = gamepad.buttons[this.gamepadIndices.button];
  75360. this.values.button = gamepadButton.value;
  75361. this.values.button = (this.values.button < 0) ? 0 : this.values.button;
  75362. this.values.button = (this.values.button > 1) ? 1 : this.values.button;
  75363. // Set the state based on the button
  75364. if (gamepadButton.pressed || this.values.button === 1) {
  75365. this.values.state = Constants.ComponentState.PRESSED;
  75366. } else if (gamepadButton.touched || this.values.button > Constants.ButtonTouchThreshold) {
  75367. this.values.state = Constants.ComponentState.TOUCHED;
  75368. }
  75369. }
  75370. // Get and normalize x axis value
  75371. if (this.gamepadIndices.xAxis !== undefined
  75372. && gamepad.axes.length > this.gamepadIndices.xAxis) {
  75373. this.values.xAxis = gamepad.axes[this.gamepadIndices.xAxis];
  75374. this.values.xAxis = (this.values.xAxis < -1) ? -1 : this.values.xAxis;
  75375. this.values.xAxis = (this.values.xAxis > 1) ? 1 : this.values.xAxis;
  75376. // If the state is still default, check if the xAxis makes it touched
  75377. if (this.values.state === Constants.ComponentState.DEFAULT
  75378. && Math.abs(this.values.xAxis) > Constants.AxisTouchThreshold) {
  75379. this.values.state = Constants.ComponentState.TOUCHED;
  75380. }
  75381. }
  75382. // Get and normalize Y axis value
  75383. if (this.gamepadIndices.yAxis !== undefined
  75384. && gamepad.axes.length > this.gamepadIndices.yAxis) {
  75385. this.values.yAxis = gamepad.axes[this.gamepadIndices.yAxis];
  75386. this.values.yAxis = (this.values.yAxis < -1) ? -1 : this.values.yAxis;
  75387. this.values.yAxis = (this.values.yAxis > 1) ? 1 : this.values.yAxis;
  75388. // If the state is still default, check if the yAxis makes it touched
  75389. if (this.values.state === Constants.ComponentState.DEFAULT
  75390. && Math.abs(this.values.yAxis) > Constants.AxisTouchThreshold) {
  75391. this.values.state = Constants.ComponentState.TOUCHED;
  75392. }
  75393. }
  75394. // Update the visual response weights based on the current component data
  75395. Object.values(this.visualResponses).forEach((visualResponse) => {
  75396. visualResponse.updateFromComponent(this.values);
  75397. });
  75398. }
  75399. }
  75400. /**
  75401. * @description Builds a motion controller with components and visual responses based on the
  75402. * supplied profile description. Data is polled from the xrInputSource's gamepad.
  75403. * @author Nell Waliczek / https://github.com/NellWaliczek
  75404. */
  75405. class MotionController {
  75406. /**
  75407. * @param {Object} xrInputSource - The XRInputSource to build the MotionController around
  75408. * @param {Object} profile - The best matched profile description for the supplied xrInputSource
  75409. * @param {Object} assetUrl
  75410. */
  75411. constructor(xrInputSource, profile, assetUrl) {
  75412. if (!xrInputSource) {
  75413. throw new Error('No xrInputSource supplied');
  75414. }
  75415. if (!profile) {
  75416. throw new Error('No profile supplied');
  75417. }
  75418. this.xrInputSource = xrInputSource;
  75419. this.assetUrl = assetUrl;
  75420. this.id = profile.profileId;
  75421. // Build child components as described in the profile description
  75422. this.layoutDescription = profile.layouts[xrInputSource.handedness];
  75423. this.components = {};
  75424. Object.keys(this.layoutDescription.components).forEach((componentId) => {
  75425. const componentDescription = this.layoutDescription.components[componentId];
  75426. this.components[componentId] = new Component(componentId, componentDescription);
  75427. });
  75428. // Initialize components based on current gamepad state
  75429. this.updateFromGamepad();
  75430. }
  75431. get gripSpace() {
  75432. return this.xrInputSource.gripSpace;
  75433. }
  75434. get targetRaySpace() {
  75435. return this.xrInputSource.targetRaySpace;
  75436. }
  75437. /**
  75438. * @description Returns a subset of component data for simplified debugging
  75439. */
  75440. get data() {
  75441. const data = [];
  75442. Object.values(this.components).forEach((component) => {
  75443. data.push(component.data);
  75444. });
  75445. return data;
  75446. }
  75447. /**
  75448. * @description Poll for updated data based on current gamepad state
  75449. */
  75450. updateFromGamepad() {
  75451. Object.values(this.components).forEach((component) => {
  75452. component.updateFromGamepad(this.xrInputSource.gamepad);
  75453. });
  75454. }
  75455. }
  75456. const DEFAULT_PROFILES_PATH = 'https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles';
  75457. const DEFAULT_PROFILE = 'generic-trigger';
  75458. function XRControllerModel( ) {
  75459. Object3D.call( this );
  75460. this.motionController = null;
  75461. this.envMap = null;
  75462. }
  75463. XRControllerModel.prototype = Object.assign( Object.create( Object3D.prototype ), {
  75464. constructor: XRControllerModel,
  75465. setEnvironmentMap: function ( envMap ) {
  75466. if ( this.envMap == envMap ) {
  75467. return this;
  75468. }
  75469. this.envMap = envMap;
  75470. this.traverse( ( child ) => {
  75471. if ( child.isMesh ) {
  75472. child.material.envMap = this.envMap;
  75473. child.material.needsUpdate = true;
  75474. }
  75475. } );
  75476. return this;
  75477. },
  75478. /**
  75479. * Polls data from the XRInputSource and updates the model's components to match
  75480. * the real world data
  75481. */
  75482. updateMatrixWorld: function ( force ) {
  75483. Object3D.prototype.updateMatrixWorld.call( this, force );
  75484. if ( ! this.motionController ) return;
  75485. // Cause the MotionController to poll the Gamepad for data
  75486. this.motionController.updateFromGamepad();
  75487. // Update the 3D model to reflect the button, thumbstick, and touchpad state
  75488. Object.values( this.motionController.components ).forEach( ( component ) => {
  75489. // Update node data based on the visual responses' current states
  75490. Object.values( component.visualResponses ).forEach( ( visualResponse ) => {
  75491. const { valueNode, minNode, maxNode, value, valueNodeProperty } = visualResponse;
  75492. // Skip if the visual response node is not found. No error is needed,
  75493. // because it will have been reported at load time.
  75494. if ( ! valueNode ) return;
  75495. // Calculate the new properties based on the weight supplied
  75496. if ( valueNodeProperty === Constants.VisualResponseProperty.VISIBILITY ) {
  75497. valueNode.visible = value;
  75498. } else if ( valueNodeProperty === Constants.VisualResponseProperty.TRANSFORM ) {
  75499. Quaternion.slerp(
  75500. minNode.quaternion,
  75501. maxNode.quaternion,
  75502. valueNode.quaternion,
  75503. value
  75504. );
  75505. valueNode.position.lerpVectors(
  75506. minNode.position,
  75507. maxNode.position,
  75508. value
  75509. );
  75510. }
  75511. } );
  75512. } );
  75513. }
  75514. } );
  75515. /**
  75516. * Walks the model's tree to find the nodes needed to animate the components and
  75517. * saves them to the motionContoller components for use in the frame loop. When
  75518. * touchpads are found, attaches a touch dot to them.
  75519. */
  75520. function findNodes( motionController, scene ) {
  75521. // Loop through the components and find the nodes needed for each components' visual responses
  75522. Object.values( motionController.components ).forEach( ( component ) => {
  75523. const { type, touchPointNodeName, visualResponses } = component;
  75524. if ( type === Constants.ComponentType.TOUCHPAD ) {
  75525. component.touchPointNode = scene.getObjectByName( touchPointNodeName );
  75526. if ( component.touchPointNode ) {
  75527. // Attach a touch dot to the touchpad.
  75528. const sphereGeometry = new SphereBufferGeometry( 0.001 );
  75529. const material = new MeshBasicMaterial( { color: 0x0000FF } );
  75530. const sphere = new Mesh( sphereGeometry, material );
  75531. component.touchPointNode.add( sphere );
  75532. } else {
  75533. console.warn( `Could not find touch dot, ${component.touchPointNodeName}, in touchpad component ${component.id}` );
  75534. }
  75535. }
  75536. // Loop through all the visual responses to be applied to this component
  75537. Object.values( visualResponses ).forEach( ( visualResponse ) => {
  75538. const { valueNodeName, minNodeName, maxNodeName, valueNodeProperty } = visualResponse;
  75539. // If animating a transform, find the two nodes to be interpolated between.
  75540. if ( valueNodeProperty === Constants.VisualResponseProperty.TRANSFORM ) {
  75541. visualResponse.minNode = scene.getObjectByName( minNodeName );
  75542. visualResponse.maxNode = scene.getObjectByName( maxNodeName );
  75543. // If the extents cannot be found, skip this animation
  75544. if ( ! visualResponse.minNode ) {
  75545. console.warn( `Could not find ${minNodeName} in the model` );
  75546. return;
  75547. }
  75548. if ( ! visualResponse.maxNode ) {
  75549. console.warn( `Could not find ${maxNodeName} in the model` );
  75550. return;
  75551. }
  75552. }
  75553. // If the target node cannot be found, skip this animation
  75554. visualResponse.valueNode = scene.getObjectByName( valueNodeName );
  75555. if ( ! visualResponse.valueNode ) {
  75556. console.warn( `Could not find ${valueNodeName} in the model` );
  75557. }
  75558. } );
  75559. } );
  75560. }
  75561. function addAssetSceneToControllerModel( controllerModel, scene ) {
  75562. // Find the nodes needed for animation and cache them on the motionController.
  75563. findNodes( controllerModel.motionController, scene );
  75564. // Apply any environment map that the mesh already has set.
  75565. if ( controllerModel.envMap ) {
  75566. scene.traverse( ( child ) => {
  75567. if ( child.isMesh ) {
  75568. child.material.envMap = controllerModel.envMap;
  75569. child.material.needsUpdate = true;
  75570. }
  75571. } );
  75572. }
  75573. // Add the glTF scene to the controllerModel.
  75574. controllerModel.add( scene );
  75575. }
  75576. var XRControllerModelFactory = ( function () {
  75577. function XRControllerModelFactory( gltfLoader = null ) {
  75578. this.gltfLoader = gltfLoader;
  75579. this.path = DEFAULT_PROFILES_PATH;
  75580. this._assetCache = {};
  75581. // If a GLTFLoader wasn't supplied to the constructor create a new one.
  75582. if ( ! this.gltfLoader ) {
  75583. this.gltfLoader = new GLTFLoader();
  75584. }
  75585. }
  75586. XRControllerModelFactory.prototype = {
  75587. constructor: XRControllerModelFactory,
  75588. createControllerModel: function ( controller ) {
  75589. const controllerModel = new XRControllerModel();
  75590. let scene = null;
  75591. controller.addEventListener( 'connected', ( event ) => {
  75592. const xrInputSource = event.data;
  75593. if ( xrInputSource.targetRayMode !== 'tracked-pointer' || ! xrInputSource.gamepad ) return;
  75594. fetchProfile( xrInputSource, this.path, DEFAULT_PROFILE ).then( ( { profile, assetPath } ) => {
  75595. controllerModel.motionController = new MotionController(
  75596. xrInputSource,
  75597. profile,
  75598. assetPath
  75599. );
  75600. const cachedAsset = this._assetCache[ controllerModel.motionController.assetUrl ];
  75601. if ( cachedAsset ) {
  75602. scene = cachedAsset.scene.clone();
  75603. addAssetSceneToControllerModel( controllerModel, scene );
  75604. } else {
  75605. if ( ! this.gltfLoader ) {
  75606. throw new Error( 'GLTFLoader not set.' );
  75607. }
  75608. this.gltfLoader.setPath( '' );
  75609. this.gltfLoader.load( controllerModel.motionController.assetUrl, ( asset ) => {
  75610. this._assetCache[ controllerModel.motionController.assetUrl ] = asset;
  75611. scene = asset.scene.clone();
  75612. addAssetSceneToControllerModel( controllerModel, scene );
  75613. },
  75614. null,
  75615. () => {
  75616. throw new Error( `Asset ${controllerModel.motionController.assetUrl} missing or malformed.` );
  75617. } );
  75618. }
  75619. } ).catch( ( err ) => {
  75620. console.warn( err );
  75621. } );
  75622. } );
  75623. controller.addEventListener( 'disconnected', () => {
  75624. controllerModel.motionController = null;
  75625. controllerModel.remove( scene );
  75626. scene = null;
  75627. } );
  75628. return controllerModel;
  75629. }
  75630. };
  75631. return XRControllerModelFactory;
  75632. } )();
  75633. let fakeCam = new PerspectiveCamera();
  75634. function toScene(vec, ref){
  75635. let node = ref.clone();
  75636. node.updateMatrix();
  75637. node.updateMatrixWorld();
  75638. let result = vec.clone().applyMatrix4(node.matrix);
  75639. result.z -= 0.8 * node.scale.x;
  75640. return result;
  75641. };
  75642. function computeMove(vrControls, controller){
  75643. if(!controller || !controller.inputSource || !controller.inputSource.gamepad){
  75644. return null;
  75645. }
  75646. let pad = controller.inputSource.gamepad;
  75647. let axes = pad.axes;
  75648. // [0,1] are for touchpad, [2,3] for thumbsticks?
  75649. let y = 0;
  75650. if(axes.length === 2){
  75651. y = axes[1];
  75652. }else if(axes.length === 4){
  75653. y = axes[3];
  75654. }
  75655. y = Math.sign(y) * (2 * y) ** 2;
  75656. let maxSize = 0;
  75657. for(let pc of viewer.scene.pointclouds){
  75658. let size = pc.boundingBox.min.distanceTo(pc.boundingBox.max);
  75659. maxSize = Math.max(maxSize, size);
  75660. }
  75661. let multiplicator = Math.pow(maxSize, 0.5) / 2;
  75662. let scale = vrControls.node.scale.x;
  75663. let moveSpeed = viewer.getMoveSpeed();
  75664. let amount = multiplicator * y * (moveSpeed ** 0.5) / scale;
  75665. let rotation = new Quaternion().setFromEuler(controller.rotation);
  75666. let dir = new Vector3(0, 0, -1);
  75667. dir.applyQuaternion(rotation);
  75668. let move = dir.clone().multiplyScalar(amount);
  75669. let p1 = vrControls.toScene(controller.position);
  75670. let p2 = vrControls.toScene(controller.position.clone().add(move));
  75671. move = p2.clone().sub(p1);
  75672. return move;
  75673. };
  75674. class FlyMode{
  75675. constructor(vrControls){
  75676. this.moveFactor = 1;
  75677. this.dbgLabel = null;
  75678. }
  75679. start(vrControls){
  75680. if(!this.dbgLabel){
  75681. /* this.dbgLabel = new Potree.TextSprite("abc");
  75682. this.dbgLabel.name = "debug label";
  75683. vrControls.viewer.sceneVR.add(this.dbgLabel);
  75684. this.dbgLabel.visible = false; */
  75685. }
  75686. }
  75687. end(){
  75688. }
  75689. update(vrControls, delta){
  75690. let primary = vrControls.cPrimary;
  75691. let secondary = vrControls.cSecondary;
  75692. let move1 = computeMove(vrControls, primary);
  75693. let move2 = computeMove(vrControls, secondary);
  75694. if(!move1){
  75695. move1 = new Vector3();
  75696. }
  75697. if(!move2){
  75698. move2 = new Vector3();
  75699. }
  75700. let move = move1.clone().add(move2);
  75701. move.multiplyScalar(-delta * this.moveFactor);
  75702. vrControls.node.position.add(move);
  75703. let scale = vrControls.node.scale.x;
  75704. let camVR = vrControls.viewer.renderer.xr.getCamera(fakeCam);
  75705. let vrPos = camVR.getWorldPosition(new Vector3());
  75706. let vrDir = camVR.getWorldDirection(new Vector3());
  75707. let vrTarget = vrPos.clone().add(vrDir.multiplyScalar(scale));
  75708. let scenePos = toScene(vrPos, vrControls.node);
  75709. let sceneDir = toScene(vrPos.clone().add(vrDir), vrControls.node).sub(scenePos);
  75710. sceneDir.normalize().multiplyScalar(scale);
  75711. let sceneTarget = scenePos.clone().add(sceneDir);
  75712. vrControls.viewer.scene.view.setView(scenePos, sceneTarget);
  75713. if(Potree.debug.message){
  75714. this.dbgLabel.visible = true;
  75715. this.dbgLabel.setText(Potree.debug.message);
  75716. this.dbgLabel.scale.set(0.1, 0.1, 0.1);
  75717. this.dbgLabel.position.copy(primary.position);
  75718. }
  75719. }
  75720. };
  75721. class TranslationMode{
  75722. constructor(){
  75723. this.controller = null;
  75724. this.startPos = null;
  75725. this.debugLine = null;
  75726. }
  75727. start(vrControls){
  75728. this.controller = vrControls.triggered.values().next().value;
  75729. this.startPos = vrControls.node.position.clone();
  75730. }
  75731. end(vrControls){
  75732. }
  75733. update(vrControls, delta){
  75734. let start = this.controller.start.position;
  75735. let end = this.controller.position;
  75736. start = vrControls.toScene(start);
  75737. end = vrControls.toScene(end);
  75738. let diff = end.clone().sub(start);
  75739. diff.set(-diff.x, -diff.y, -diff.z);
  75740. let pos = new Vector3().addVectors(this.startPos, diff);
  75741. vrControls.node.position.copy(pos);
  75742. }
  75743. };
  75744. class RotScaleMode{
  75745. constructor(){
  75746. this.line = null;
  75747. this.startState = null;
  75748. }
  75749. start(vrControls){
  75750. if(!this.line){
  75751. this.line = Potree.Utils.debugLine(
  75752. vrControls.viewer.sceneVR,
  75753. new Vector3(0, 0, 0),
  75754. new Vector3(0, 0, 0),
  75755. 0xffff00,
  75756. );
  75757. this.dbgLabel = new Potree.TextSprite("abc");
  75758. this.dbgLabel.scale.set(0.1, 0.1, 0.1);
  75759. vrControls.viewer.sceneVR.add(this.dbgLabel);
  75760. }
  75761. this.line.node.visible = true;
  75762. this.startState = vrControls.node.clone();
  75763. }
  75764. end(vrControls){
  75765. this.line.node.visible = false;
  75766. this.dbgLabel.visible = false;
  75767. }
  75768. update(vrControls, delta){
  75769. let start_c1 = vrControls.cPrimary.start.position.clone();
  75770. let start_c2 = vrControls.cSecondary.start.position.clone();
  75771. let start_center = start_c1.clone().add(start_c2).multiplyScalar(0.5);
  75772. let start_c1_c2 = start_c2.clone().sub(start_c1);
  75773. let end_c1 = vrControls.cPrimary.position.clone();
  75774. let end_c2 = vrControls.cSecondary.position.clone();
  75775. let end_center = end_c1.clone().add(end_c2).multiplyScalar(0.5);
  75776. let end_c1_c2 = end_c2.clone().sub(end_c1);
  75777. let d1 = start_c1_c2.length();
  75778. let d2 = end_c1_c2.length();
  75779. let angleStart = new Vector2$1(start_c1_c2.x, start_c1_c2.z).angle();
  75780. let angleEnd = new Vector2$1(end_c1_c2.x, end_c1_c2.z).angle();
  75781. let angleDiff = angleEnd - angleStart;
  75782. let scale = d2 / d1;
  75783. let node = this.startState.clone();
  75784. node.updateMatrix();
  75785. node.matrixAutoUpdate = false;
  75786. let mToOrigin = new Matrix4().makeTranslation(...toScene(start_center, this.startState).multiplyScalar(-1).toArray());
  75787. let mToStart = new Matrix4().makeTranslation(...toScene(start_center, this.startState).toArray());
  75788. let mRotate = new Matrix4().makeRotationZ(angleDiff);
  75789. let mScale = new Matrix4().makeScale(1 / scale, 1 / scale, 1 / scale);
  75790. node.applyMatrix4(mToOrigin);
  75791. node.applyMatrix4(mRotate);
  75792. node.applyMatrix4(mScale);
  75793. node.applyMatrix4(mToStart);
  75794. let oldScenePos = toScene(start_center, this.startState);
  75795. let newScenePos = toScene(end_center, node);
  75796. let toNew = oldScenePos.clone().sub(newScenePos);
  75797. let mToNew = new Matrix4().makeTranslation(...toNew.toArray());
  75798. node.applyMatrix4(mToNew);
  75799. node.matrix.decompose(node.position, node.quaternion, node.scale );
  75800. vrControls.node.position.copy(node.position);
  75801. vrControls.node.quaternion.copy(node.quaternion);
  75802. vrControls.node.scale.copy(node.scale);
  75803. vrControls.node.updateMatrix();
  75804. {
  75805. let scale = vrControls.node.scale.x;
  75806. let camVR = vrControls.viewer.renderer.xr.getCamera(fakeCam);
  75807. let vrPos = camVR.getWorldPosition(new Vector3());
  75808. let vrDir = camVR.getWorldDirection(new Vector3());
  75809. let vrTarget = vrPos.clone().add(vrDir.multiplyScalar(scale));
  75810. let scenePos = toScene(vrPos, this.startState);
  75811. let sceneDir = toScene(vrPos.clone().add(vrDir), this.startState).sub(scenePos);
  75812. sceneDir.normalize().multiplyScalar(scale);
  75813. let sceneTarget = scenePos.clone().add(sceneDir);
  75814. vrControls.viewer.scene.view.setView(scenePos, sceneTarget);
  75815. vrControls.viewer.setMoveSpeed(scale);
  75816. }
  75817. { // update "GUI"
  75818. this.line.set(end_c1, end_c2);
  75819. let scale = vrControls.node.scale.x;
  75820. this.dbgLabel.visible = true;
  75821. this.dbgLabel.position.copy(end_center);
  75822. this.dbgLabel.setText(`scale: 1 : ${scale.toFixed(2)}`);
  75823. this.dbgLabel.scale.set(0.05, 0.05, 0.05);
  75824. }
  75825. }
  75826. };
  75827. class VRControls extends EventDispatcher{
  75828. constructor(viewer){
  75829. super(viewer);
  75830. this.viewer = viewer;
  75831. viewer.addEventListener("vr_start", this.onStart.bind(this));
  75832. viewer.addEventListener("vr_end", this.onEnd.bind(this));
  75833. this.node = new Object3D();
  75834. this.node.up.set(0, 0, 1);
  75835. this.triggered = new Set();
  75836. let xr = viewer.renderer.xr;
  75837. { // lights
  75838. const light = new PointLight( 0xffffff, 5, 0, 1 );
  75839. light.position.set(0, 2, 0);
  75840. this.viewer.sceneVR.add(light);
  75841. }
  75842. this.menu = null;
  75843. const controllerModelFactory = new XRControllerModelFactory();
  75844. let sg = new SphereGeometry(1, 32, 32);
  75845. let sm = new MeshNormalMaterial();
  75846. { // setup primary controller
  75847. let controller = xr.getController(0);
  75848. let grip = xr.getControllerGrip(0);
  75849. grip.name = "grip(0)";
  75850. // ADD CONTROLLERMODEL
  75851. grip.add( controllerModelFactory.createControllerModel( grip ) );
  75852. this.viewer.sceneVR.add(grip);
  75853. // ADD SPHERE
  75854. let sphere = new Mesh(sg, sm);
  75855. sphere.scale.set(0.005, 0.005, 0.005);
  75856. controller.add(sphere);
  75857. controller.visible = true;
  75858. this.viewer.sceneVR.add(controller);
  75859. { // ADD LINE
  75860. let lineGeometry = new LineGeometry();
  75861. lineGeometry.setPositions([
  75862. 0, 0, -0.15,
  75863. 0, 0, 0.05,
  75864. ]);
  75865. let lineMaterial = new LineMaterial({
  75866. color: 0xff0000,
  75867. lineWidth: 2,
  75868. resolution: new Vector2$1(1000, 1000),
  75869. });
  75870. const line = new Line2(lineGeometry, lineMaterial);
  75871. controller.add(line);
  75872. }
  75873. controller.addEventListener( 'connected', function ( event ) {
  75874. const xrInputSource = event.data;
  75875. controller.inputSource = xrInputSource;
  75876. // initInfo(controller);
  75877. });
  75878. controller.addEventListener( 'selectstart', () => {this.onTriggerStart(controller);});
  75879. controller.addEventListener( 'selectend', () => {this.onTriggerEnd(controller);});
  75880. this.cPrimary = controller;
  75881. }
  75882. { // setup secondary controller
  75883. let controller = xr.getController(1);
  75884. let grip = xr.getControllerGrip(1);
  75885. // ADD CONTROLLER MODEL
  75886. let model = controllerModelFactory.createControllerModel( grip );
  75887. grip.add(model);
  75888. this.viewer.sceneVR.add( grip );
  75889. // ADD SPHERE
  75890. let sphere = new Mesh(sg, sm);
  75891. sphere.scale.set(0.005, 0.005, 0.005);
  75892. controller.add(sphere);
  75893. controller.visible = true;
  75894. this.viewer.sceneVR.add(controller);
  75895. { // ADD LINE
  75896. let lineGeometry = new LineGeometry();
  75897. lineGeometry.setPositions([
  75898. 0, 0, -0.15,
  75899. 0, 0, 0.05,
  75900. ]);
  75901. let lineMaterial = new LineMaterial({
  75902. color: 0xff0000,
  75903. lineWidth: 2,
  75904. resolution: new Vector2$1(1000, 1000),
  75905. });
  75906. const line = new Line2(lineGeometry, lineMaterial);
  75907. controller.add(line);
  75908. }
  75909. controller.addEventListener( 'connected', (event) => {
  75910. const xrInputSource = event.data;
  75911. controller.inputSource = xrInputSource;
  75912. this.initMenu(controller);
  75913. });
  75914. controller.addEventListener( 'selectstart', () => {this.onTriggerStart(controller);});
  75915. controller.addEventListener( 'selectend', () => {this.onTriggerEnd(controller);});
  75916. this.cSecondary = controller;
  75917. }
  75918. this.mode_fly = new FlyMode();
  75919. this.mode_translate = new TranslationMode();
  75920. this.mode_rotScale = new RotScaleMode();
  75921. this.setMode(this.mode_fly);
  75922. }
  75923. createSlider(label, min, max){
  75924. let sg = new SphereGeometry(1, 8, 8);
  75925. let cg = new CylinderGeometry(1, 1, 1, 8);
  75926. let matHandle = new MeshBasicMaterial({color: 0xff0000});
  75927. let matScale = new MeshBasicMaterial({color: 0xff4444});
  75928. let matValue = new MeshNormalMaterial();
  75929. let node = new Object3D("slider");
  75930. let nLabel = new Potree.TextSprite(`${label}: 0`);
  75931. let nMax = new Mesh(sg, matHandle);
  75932. let nMin = new Mesh(sg, matHandle);
  75933. let nValue = new Mesh(sg, matValue);
  75934. let nScale = new Mesh(cg, matScale);
  75935. nLabel.scale.set(0.2, 0.2, 0.2);
  75936. nLabel.position.set(0, 0.35, 0);
  75937. nMax.scale.set(0.02, 0.02, 0.02);
  75938. nMax.position.set(0, 0.25, 0);
  75939. nMin.scale.set(0.02, 0.02, 0.02);
  75940. nMin.position.set(0, -0.25, 0);
  75941. nValue.scale.set(0.02, 0.02, 0.02);
  75942. nValue.position.set(0, 0, 0);
  75943. nScale.scale.set(0.005, 0.5, 0.005);
  75944. node.add(nLabel);
  75945. node.add(nMax);
  75946. node.add(nMin);
  75947. node.add(nValue);
  75948. node.add(nScale);
  75949. return node;
  75950. }
  75951. createInfo(){
  75952. let texture = new TextureLoader().load(`${Potree.resourcePath}/images/vr_controller_help.jpg`);
  75953. let plane = new PlaneBufferGeometry(1, 1, 1, 1);
  75954. let infoMaterial = new MeshBasicMaterial({map: texture});
  75955. let infoNode = new Mesh(plane, infoMaterial);
  75956. return infoNode;
  75957. }
  75958. initMenu(controller){
  75959. if(this.menu){
  75960. return;
  75961. }
  75962. let node = new Object3D("vr menu");
  75963. // let nSlider = this.createSlider("speed", 0, 1);
  75964. // let nInfo = this.createInfo();
  75965. // // node.add(nSlider);
  75966. // node.add(nInfo);
  75967. // {
  75968. // node.rotation.set(-1.5, 0, 0)
  75969. // node.scale.set(0.3, 0.3, 0.3);
  75970. // node.position.set(-0.2, -0.002, -0.1)
  75971. // // nInfo.position.set(0.5, 0, 0);
  75972. // nInfo.scale.set(0.8, 0.6, 0);
  75973. // // controller.add(node);
  75974. // }
  75975. // node.position.set(-0.3, 1.2, 0.2);
  75976. // node.scale.set(0.3, 0.2, 0.3);
  75977. // node.lookAt(new THREE.Vector3(0, 1.5, 0.1));
  75978. // this.viewer.sceneVR.add(node);
  75979. this.menu = node;
  75980. // window.vrSlider = nSlider;
  75981. window.vrMenu = node;
  75982. }
  75983. toScene(vec){
  75984. let camVR = this.getCamera();
  75985. let mat = camVR.matrixWorld;
  75986. let result = vec.clone().applyMatrix4(mat);
  75987. return result;
  75988. }
  75989. toVR(vec){
  75990. let camVR = this.getCamera();
  75991. let mat = camVR.matrixWorld.clone();
  75992. mat.invert();
  75993. let result = vec.clone().applyMatrix4(mat);
  75994. return result;
  75995. }
  75996. setMode(mode){
  75997. if(this.mode === mode){
  75998. return;
  75999. }
  76000. if(this.mode){
  76001. this.mode.end(this);
  76002. }
  76003. for(let controller of [this.cPrimary, this.cSecondary]){
  76004. let start = {
  76005. position: controller.position.clone(),
  76006. rotation: controller.rotation.clone(),
  76007. };
  76008. controller.start = start;
  76009. }
  76010. this.mode = mode;
  76011. this.mode.start(this);
  76012. }
  76013. onTriggerStart(controller){
  76014. this.triggered.add(controller);
  76015. if(this.triggered.size === 0){
  76016. this.setMode(this.mode_fly);
  76017. }else if(this.triggered.size === 1){
  76018. this.setMode(this.mode_translate);
  76019. }else if(this.triggered.size === 2){
  76020. this.setMode(this.mode_rotScale);
  76021. }
  76022. }
  76023. onTriggerEnd(controller){
  76024. this.triggered.delete(controller);
  76025. if(this.triggered.size === 0){
  76026. this.setMode(this.mode_fly);
  76027. }else if(this.triggered.size === 1){
  76028. this.setMode(this.mode_translate);
  76029. }else if(this.triggered.size === 2){
  76030. this.setMode(this.mode_rotScale);
  76031. }
  76032. }
  76033. onStart(){
  76034. let position = this.viewer.scene.view.position.clone();
  76035. let direction = this.viewer.scene.view.direction;
  76036. direction.multiplyScalar(-1);
  76037. let target = position.clone().add(direction);
  76038. target.z = position.z;
  76039. let scale = this.viewer.getMoveSpeed();
  76040. this.node.position.copy(position);
  76041. this.node.lookAt(target);
  76042. this.node.scale.set(scale, scale, scale);
  76043. this.node.updateMatrix();
  76044. this.node.updateMatrixWorld();
  76045. }
  76046. onEnd(){
  76047. }
  76048. setScene(scene){
  76049. this.scene = scene;
  76050. }
  76051. getCamera(){
  76052. let reference = this.viewer.scene.getActiveCamera();
  76053. let camera = new PerspectiveCamera();
  76054. // let scale = this.node.scale.x;
  76055. let scale = this.viewer.getMoveSpeed();
  76056. //camera.near = 0.01 / scale;
  76057. camera.near = 0.1;
  76058. camera.far = 1000;
  76059. // camera.near = reference.near / scale;
  76060. // camera.far = reference.far / scale;
  76061. camera.up.set(0, 0, 1);
  76062. camera.lookAt(new Vector3(0, -1, 0));
  76063. camera.updateMatrix();
  76064. camera.updateMatrixWorld();
  76065. camera.position.copy(this.node.position);
  76066. camera.rotation.copy(this.node.rotation);
  76067. camera.scale.set(scale, scale, scale);
  76068. camera.updateMatrix();
  76069. camera.updateMatrixWorld();
  76070. camera.matrixAutoUpdate = false;
  76071. camera.parent = camera;
  76072. return camera;
  76073. }
  76074. update(delta){
  76075. // if(this.mode === this.mode_fly){
  76076. // let ray = new THREE.Ray(origin, direction);
  76077. // for(let object of this.selectables){
  76078. // if(object.intersectsRay(ray)){
  76079. // object.onHit(ray);
  76080. // }
  76081. // }
  76082. // }
  76083. this.mode.update(this, delta);
  76084. }
  76085. };
  76086. // Adapted from three.js VRButton
  76087. class VRButton {
  76088. constructor(){
  76089. this.onStartListeners = [];
  76090. this.onEndListeners = [];
  76091. this.element = null;
  76092. }
  76093. onStart(callback){
  76094. this.onStartListeners.push(callback);
  76095. }
  76096. onEnd(callback){
  76097. this.onEndListeners.push(callback);
  76098. }
  76099. static async createButton( renderer, options ) {
  76100. if ( options ) {
  76101. console.error( 'THREE.VRButton: The "options" parameter has been removed. Please set the reference space type via renderer.xr.setReferenceSpaceType() instead.' );
  76102. }
  76103. const button = new VRButton();
  76104. const element = document.createElement( 'button' );
  76105. button.element = element;
  76106. function setEnter(){
  76107. button.element.innerHTML = `
  76108. <div style="font-size: 0.5em;">ENTER</div>
  76109. <div style="font-weight: bold;">VR</div>
  76110. `;
  76111. }
  76112. function setExit(){
  76113. button.element.innerHTML = `
  76114. <div style="font-size: 0.5em;">EXIT</div>
  76115. <div style="font-weight: bold;">VR</div>
  76116. `;
  76117. }
  76118. function showEnterVR( /*device*/ ) {
  76119. let currentSession = null;
  76120. function onSessionStarted( session ) {
  76121. session.addEventListener( 'end', onSessionEnded );
  76122. for(let listener of button.onStartListeners){
  76123. listener();
  76124. }
  76125. renderer.xr.setSession( session );
  76126. setExit();
  76127. currentSession = session;
  76128. }
  76129. function onSessionEnded( /*event*/ ) {
  76130. currentSession.removeEventListener( 'end', onSessionEnded );
  76131. for(let listener of button.onEndListeners){
  76132. listener();
  76133. }
  76134. setEnter();
  76135. currentSession = null;
  76136. }
  76137. //
  76138. button.element.style.display = '';
  76139. button.element.style.cursor = 'pointer';
  76140. setEnter();
  76141. button.element.onmouseenter = function () {
  76142. button.element.style.opacity = '1.0';
  76143. };
  76144. button.element.onmouseleave = function () {
  76145. button.element.style.opacity = '0.7';
  76146. };
  76147. button.element.onclick = function () {
  76148. if ( currentSession === null ) {
  76149. // WebXR's requestReferenceSpace only works if the corresponding feature
  76150. // was requested at session creation time. For simplicity, just ask for
  76151. // the interesting ones as optional features, but be aware that the
  76152. // requestReferenceSpace call will fail if it turns out to be unavailable.
  76153. // ('local' is always available for immersive sessions and doesn't need to
  76154. // be requested separately.)
  76155. const sessionInit = { optionalFeatures: [ 'local-floor', 'bounded-floor', 'hand-tracking' ] };
  76156. navigator.xr.requestSession( 'immersive-vr', sessionInit ).then( onSessionStarted );
  76157. } else {
  76158. currentSession.end();
  76159. }
  76160. };
  76161. }
  76162. function stylizeElement( element ) {
  76163. element.style.position = 'absolute';
  76164. element.style.bottom = '20px';
  76165. element.style.padding = '12px 6px';
  76166. element.style.border = '1px solid #fff';
  76167. element.style.borderRadius = '4px';
  76168. element.style.background = 'rgba(0,0,0,0.1)';
  76169. element.style.color = '#fff';
  76170. element.style.font = 'normal 13px sans-serif';
  76171. element.style.textAlign = 'center';
  76172. element.style.opacity = '0.7';
  76173. element.style.outline = 'none';
  76174. element.style.zIndex = '999';
  76175. }
  76176. if ( 'xr' in navigator ) {
  76177. button.element.id = 'VRButton';
  76178. button.element.style.display = 'none';
  76179. stylizeElement( button.element );
  76180. let supported = await navigator.xr.isSessionSupported( 'immersive-vr' );
  76181. if(supported){
  76182. showEnterVR();
  76183. return button;
  76184. }else {
  76185. return null;
  76186. }
  76187. } else {
  76188. if ( window.isSecureContext === false ) {
  76189. console.log("WEBXR NEEDS HTTPS");
  76190. } else {
  76191. console.log("WEBXR not available");
  76192. }
  76193. return null;
  76194. }
  76195. }
  76196. }
  76197. //处理cursor优先级
  76198. var CursorDeal = {
  76199. priorityEvent : [//在前面的优先级高
  76200. {'zoomInCloud':'zoom-in'},
  76201. {'hoverPano':'pointer'},
  76202. {'connectPano':`url({Potree.resourcePath}/images/connect.png),auto`},
  76203. {'disconnectPano':`url({Potree.resourcePath}/images/connect-dis.png),auto`},
  76204. {'hoverLine':'pointer'},
  76205. {"movePointcloud":'move'},
  76206. {"polygon_isIntersectSelf":'not-allowed'},
  76207. {"polygon_AtWrongPlace":'not-allowed'},
  76208. {"markerMove":'grab'},
  76209. {'mapClipMove':'move'},
  76210. {'mapClipRotate':`url({Potree.resourcePath}/images/rotate-cursor.png),auto`},
  76211. {'rotatePointcloud':`url({Potree.resourcePath}/images/rotate-cursor.png),auto`},
  76212. {'siteModelFloorDrag':'row-resize'},
  76213. {'addSth':'cell'},//or crosshair
  76214. ],
  76215. list:[], //当前存在的cursor状态
  76216. currentCursorIndex:null,
  76217. init : function(viewer, viewers){
  76218. this.priorityEvent.forEach(e=>{//刚开始Potree.resourcePath没值,现在换
  76219. for(let i in e){
  76220. e[i] = Common.replaceAll(e[i],'{Potree.resourcePath}',Potree.resourcePath);
  76221. }
  76222. });
  76223. this.domElements = viewers.map(e=>e.renderArea);
  76224. viewer.addEventListener("CursorChange",(e)=>{
  76225. if(e.action == 'add'){
  76226. this.add(e.name);
  76227. }else {
  76228. this.remove(e.name);
  76229. }
  76230. });
  76231. },
  76232. add : function(name){
  76233. var priorityItem = this.priorityEvent.find(e=>e[name]);
  76234. if(!priorityItem){
  76235. console.error('CursorDeal 未定义优先级 name:'+ name);
  76236. return
  76237. }
  76238. if(!this.list.includes(name)){
  76239. this.judge({addItem: priorityItem, name});
  76240. this.list.push(name);
  76241. }
  76242. },
  76243. remove : function(name){
  76244. var index = this.list.indexOf(name);
  76245. if(index > -1){
  76246. this.list.splice(index, 1);
  76247. this.judge();
  76248. }
  76249. },
  76250. judge:function(o={}){
  76251. //console.log(o,this.list)
  76252. if(o.addItem){
  76253. var addIndex = this.priorityEvent.indexOf(o.addItem);
  76254. if(addIndex < this.currentCursorIndex || this.currentCursorIndex == void 0){
  76255. this.domElements.forEach(e=>e.style.cursor = o.addItem[o.name] );
  76256. this.currentCursorIndex = addIndex;
  76257. }
  76258. }else {
  76259. var levelMax = {index:Infinity, cursor:null };
  76260. this.list.forEach(name=>{
  76261. var priorityItem = this.priorityEvent.find(e=>e[name]);
  76262. var index = this.priorityEvent.indexOf(priorityItem);
  76263. if(index < levelMax.index){
  76264. levelMax.index = index;
  76265. levelMax.cursor = priorityItem[name];
  76266. }
  76267. });
  76268. this.currentCursorIndex = levelMax.index;
  76269. this.domElements.forEach(e=>e.style.cursor = levelMax.cursor || '');
  76270. }
  76271. }
  76272. };
  76273. let texLoader$6 = new TextureLoader();
  76274. let color$1 = new Color(config$1.clip.color);
  76275. let markerMats$1;
  76276. let markerSizeInfo$1 = {width2d:30};
  76277. class mapClipBox extends ctrlPolygon {
  76278. constructor (center, scale) {
  76279. center = center.clone().setZ(0);//所有Z都为0
  76280. let prop = {
  76281. points : getPoints(center, scale, 0),
  76282. closed : true,
  76283. isRect : true,
  76284. dimension : '2d'
  76285. };
  76286. super('mapClipBox', prop);
  76287. this.angle = 0;
  76288. this.createRotateBar();
  76289. this.edgeMarkers = [];
  76290. //addMarkers:
  76291. this.initData(prop);
  76292. {//areaPlane event 能拖动
  76293. this.areaPlane.addEventListener('mouseover',()=>{
  76294. viewer.dispatchEvent({
  76295. type : "CursorChange", action : "add", name:"mapClipMove"
  76296. });
  76297. });
  76298. this.areaPlane.addEventListener('mouseleave',()=>{
  76299. viewer.dispatchEvent({
  76300. type : "CursorChange", action : "remove", name:"mapClipMove"
  76301. });
  76302. });
  76303. let lastPos;
  76304. let drag = (e)=>{
  76305. let intersect = e.intersect.orthoIntersect;
  76306. if(lastPos){
  76307. let moveVec = new Vector3().subVectors(intersect, lastPos).setZ(0);
  76308. this.center.add(moveVec);
  76309. this.updatePoints();
  76310. this.dispatchEvent({type:'repos'});
  76311. }
  76312. lastPos = intersect.clone();
  76313. };
  76314. let drop = (e)=>{
  76315. lastPos = null;
  76316. };
  76317. this.areaPlane.addEventListener('drag', drag);
  76318. this.areaPlane.addEventListener('drop', drop);
  76319. }
  76320. /* this.addEventListener('dragChange',()=>{
  76321. this.updateTwoMidMarker(index+1)
  76322. }) */
  76323. viewer.setObjectLayers(this, 'mapObjects' );
  76324. }
  76325. getScale(){
  76326. return new Vector3(this.points[0].distanceTo(this.points[1]), this.points[1].distanceTo(this.points[2]) ,1)
  76327. }
  76328. addMarker(o={} ){
  76329. let marker = new Sprite$1({mat:this.getMarkerMaterial('default'), sizeInfo: markerSizeInfo$1, dontFixOrient: true, viewports:viewer.mapViewer.viewports, name:"mapClipBox_marker", } );
  76330. marker.renderOrder = 3;
  76331. //marker.markerSelectStates = {}
  76332. let edge = LineDraw.createLine([new Vector3,new Vector3],{color: color$1 });
  76333. let edgeMarker = new Sprite$1({mat:this.getMarkerMaterial('default'), sizeInfo: markerSizeInfo$1, dontFixOrient: true, viewports:viewer.mapViewer.viewports, name:"mapClipBox_edgePoint"} );
  76334. let mouseover = (e) => {
  76335. this.setMarkerSelected(e.object, true, 'single');
  76336. viewer.dispatchEvent({
  76337. type : "CursorChange", action : "add", name:"markerMove"
  76338. });
  76339. };
  76340. let mouseleave = (e) => {
  76341. this.setMarkerSelected(e.object, false, 'single');
  76342. viewer.dispatchEvent({
  76343. type : "CursorChange", action : "remove", name:"markerMove"
  76344. });
  76345. };
  76346. edgeMarker.addEventListener('mouseover', mouseover);
  76347. edgeMarker.addEventListener('mouseleave', mouseleave);
  76348. let dragInfo = {lastPos:null};
  76349. edgeMarker.addEventListener('drag', this.dragEdge.bind(this,dragInfo));
  76350. edgeMarker.addEventListener('drop', this.dropEdge.bind(this,dragInfo));
  76351. this.edgeMarkers.push(edgeMarker);
  76352. this.add(edgeMarker);
  76353. marker.dispatchEvent('addHoverEvent');
  76354. super.addMarker({point:o.point, marker:marker, edge});
  76355. }
  76356. dragEdge(dragInfo, e){//拖拽一个边(或一个边类型的marker),带动它的两个端点。 可以转化为拖拽marker往法线方向
  76357. var I, atMap;
  76358. atMap = e.dragViewport.name == 'mapViewport';
  76359. I = e.intersect.orthoIntersect;
  76360. if (I && dragInfo.lastPos) {
  76361. let i = this.edgeMarkers.indexOf(e.drag.object);
  76362. if (i !== -1) {
  76363. let lineNormal = math.getNormal2d({p1:this.points[i], p2:this.points[(i+1)%4]});
  76364. let moveVec = new Vector3().subVectors(I, dragInfo.lastPos).setZ(0);//移动的向量
  76365. let dragVec = moveVec.projectOnVector(lineNormal).setZ(0);//在法线上移动的向量
  76366. let newPos = new Vector3().addVectors(this.points[i], dragVec); //marker应到的位置
  76367. this.dragChange(newPos, i, atMap); //转化为这个marker的拖拽
  76368. }
  76369. }
  76370. dragInfo.lastPos = I.clone();
  76371. }
  76372. dropEdge(dragInfo, e){
  76373. dragInfo.lastPos = null;
  76374. this.setMarkerSelected(e.drag.object, false, 'single'); //拖拽时似乎没有触发mouseout
  76375. }
  76376. createAreaPlane(){
  76377. var planeMat = new MeshBasicMaterial({
  76378. color: color$1,//"#00eeff",
  76379. side:DoubleSide,
  76380. opacity:0.3,
  76381. transparent:true,
  76382. depthTest:false
  76383. });
  76384. return super.createAreaPlane(planeMat)
  76385. }
  76386. getMarkerMaterial(type) {
  76387. if(!markerMats$1){
  76388. markerMats$1 = {
  76389. default: new MeshBasicMaterial({
  76390. transparent: !0,
  76391. color: color$1,
  76392. opacity: 0.8,
  76393. map: texLoader$6.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  76394. }),
  76395. select: new MeshBasicMaterial({
  76396. transparent: !0,
  76397. color: color$1,
  76398. opacity: 1,
  76399. map: texLoader$6.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  76400. }),
  76401. };
  76402. mapClipBox.markerMats = markerMats$1;
  76403. }
  76404. return markerMats$1[type]
  76405. }
  76406. setMarkerSelected(marker, state, hoverObject){
  76407. //console.warn(marker.id , state, hoverObject)
  76408. if(state == 'hover'){
  76409. marker.material = this.getMarkerMaterial('select');
  76410. }else {
  76411. marker.material = this.getMarkerMaterial('default');
  76412. }
  76413. /* marker.markerSelectStates[hoverObject] = state
  76414. let absoluteState = false
  76415. for(var i in marker.markerSelectStates){
  76416. if(marker.markerSelectStates[i]){
  76417. absoluteState = true; break;
  76418. }
  76419. }
  76420. if(absoluteState){
  76421. marker.material = this.getMarkerMaterial('select')
  76422. }else{
  76423. marker.material = this.getMarkerMaterial('default')
  76424. }
  76425. marker.selected = absoluteState */
  76426. viewer.mapViewer.dispatchEvent('content_changed');
  76427. }
  76428. createRotateBar(){
  76429. //中心点在线的一端,整体初始在box上方
  76430. const lineLen = 1.5, circleWidth = 2, barOpacity = 0.7;
  76431. let object = new Object3D;
  76432. let bar = new Sprite$1({mat:new MeshBasicMaterial({
  76433. side:DoubleSide,
  76434. opacity: barOpacity,
  76435. transparent:true,
  76436. depthTest:false,
  76437. map: texLoader$6.load(Potree.resourcePath+'/textures/rotation_circle.png' ),
  76438. }) ,
  76439. root:object,
  76440. sizeInfo: markerSizeInfo$1,
  76441. dontFixOrient: true,
  76442. viewports:viewer.mapViewer.viewports,
  76443. name:"mapClipRotateBar"
  76444. });
  76445. bar.position.set(0,lineLen+circleWidth/2,0);
  76446. bar.scale.set(circleWidth,circleWidth,circleWidth);
  76447. bar.addEventListener('mouseover',()=>{
  76448. bar.material.opacity = 1;
  76449. viewer.dispatchEvent({
  76450. type : "CursorChange", action : "add", name:"mapClipRotate"
  76451. });
  76452. viewer.mapViewer.dispatchEvent('content_changed');
  76453. });
  76454. let leave = ()=>{
  76455. bar.material.opacity = barOpacity;
  76456. viewer.dispatchEvent({
  76457. type : "CursorChange", action : "remove", name:"mapClipRotate"
  76458. });
  76459. viewer.mapViewer.dispatchEvent('content_changed');
  76460. };
  76461. bar.addEventListener('mouseleave',leave);
  76462. this.addEventListener('dispose', leave);
  76463. let lastPos;
  76464. bar.addEventListener('drag',(e)=>{
  76465. var intersect = e.intersect.orthoIntersect;
  76466. if(lastPos){
  76467. let vec1 = new Vector3().subVectors(lastPos, this.center).setZ(0);
  76468. let vec2 = new Vector3().subVectors(intersect, this.center).setZ(0);
  76469. let angle = math.getAngle(vec1,vec2,'z');
  76470. this.angle += angle;
  76471. this.rotateBar.rotation.z = this.angle;
  76472. this.updatePoints();
  76473. this.dispatchEvent({type:'rotate', angle: this.angle});
  76474. }
  76475. lastPos = intersect.clone();
  76476. });
  76477. bar.addEventListener('drop',()=>{
  76478. lastPos = null;
  76479. viewer.dispatchEvent({
  76480. type : "CursorChange", action : "remove", name:"mapClipRotate"
  76481. });
  76482. });
  76483. let line = LineDraw.createLine([new Vector3, new Vector3(0,lineLen,0)],{color: color$1});
  76484. object.add(bar);
  76485. object.add(line);
  76486. this.add(object);
  76487. this.rotateBar = object;
  76488. this.rotateBar.bar = bar;
  76489. }
  76490. updatePoints(scale){
  76491. this.points = getPoints(this.center, scale || this.getScale(), this.angle);
  76492. this.getPoint2dInfo(this.points);
  76493. this.update({ifUpdateMarkers:true});
  76494. }
  76495. update(options={}){
  76496. super.update(options);
  76497. {//update rotateBar
  76498. let center = new Vector3().addVectors(this.points[0], this.points[1]).multiplyScalar(0.5);
  76499. this.rotateBar.position.copy(center);
  76500. this.rotateBar.bar.update();//更新sprite matrix
  76501. }
  76502. {
  76503. for(let i=0;i<4;i++){
  76504. let current = this.points[i];
  76505. let next = this.points[(i+1)%4];
  76506. let mid = new Vector3().addVectors(current, next).multiplyScalar(0.5);
  76507. this.updateMarker(this.edgeMarkers[i], mid);
  76508. }
  76509. }
  76510. }
  76511. dispose(){
  76512. super.dispose();
  76513. this.dispatchEvent('dispose');
  76514. }
  76515. }
  76516. function getPoints(center, scale, angle=0){
  76517. let points = [
  76518. new Vector3(-scale.x/2, +scale.y/2, 0),
  76519. new Vector3(+scale.x/2, +scale.y/2, 0),
  76520. new Vector3(+scale.x/2, -scale.y/2, 0),
  76521. new Vector3(-scale.x/2, -scale.y/2, 0),
  76522. ];
  76523. var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0,0,1), angle);//再旋转
  76524. points.forEach(e=>{
  76525. e.applyMatrix4(rotMatrix);
  76526. e.add(center);
  76527. });
  76528. return points
  76529. }
  76530. const defaultBoxWidth = 6; //navvis: 10
  76531. //navvis position: si {x: 0, y: 0, z: 0}
  76532. var Clip = {
  76533. bus : new EventDispatcher,
  76534. selectedDatasets : [],
  76535. changeCallback(force){
  76536. if(Potree.settings.isOfficial){
  76537. Common.intervalTool.isWaiting('clipSelectedDatasets', ()=>{ //延时update,防止卡顿
  76538. let pointclouds = this.getIntersectPointcloud();
  76539. if(force || Common.getDifferenceSet(pointclouds,this.selectedDatasets).length){
  76540. this.selectedDatasets = pointclouds;
  76541. //console.error('clipSelectedDatasets',selectedDatasets)
  76542. this.bus.dispatchEvent({type:'updateSelectedDatasets', selectedDatasets:pointclouds.map(e=>e.dataset_id) });
  76543. force = false;
  76544. return true
  76545. }
  76546. }, 300);
  76547. }
  76548. },
  76549. enter:function(){
  76550. this.previousView = {
  76551. position: viewer.images360.position,
  76552. target: viewer.scene.view.getPivot(),
  76553. displayMode : Potree.settings.displayMode,
  76554. //---
  76555. ifShowMarker : Potree.settings.ifShowMarker,
  76556. };
  76557. let pointcloud = this.getPointcloud();
  76558. let bound = pointcloud.bound; //只选取其中一个数据集的bound,而非整体,是因为担心两个数据集中间有空隙,于是刚好落在没有点云的地方。
  76559. let boundSize = bound.getSize(new Vector3());
  76560. let target = this.getTarget(bound.getCenter(new Vector3())); //navvis的位置xy是用相机位置 this.ViewService.mainView.getCamera().position 我觉得也可以用第一个漫游点的,或者最接近bound中心的漫游点
  76561. let scale = new Vector3(defaultBoxWidth,defaultBoxWidth, boundSize.z);//z和navvis一样
  76562. let eyeDir = viewer.scene.view.direction.clone().setZ(0/* -boundSize.z/3 */).multiplyScalar(-defaultBoxWidth); //为了使所在楼层不变,不修改z
  76563. //let eyeDir = scale.clone().setZ(boundSize.z/3).multiplyScalar(1.3)
  76564. let position = new Vector3().addVectors(target, eyeDir);
  76565. Potree.settings.displayMode = 'showPointCloud';
  76566. viewer.setView({
  76567. position ,
  76568. target,
  76569. duration:300,
  76570. callback:function(){
  76571. }
  76572. });
  76573. viewer.setControls(viewer.orbitControls);
  76574. viewer.setLimitFar(false);
  76575. {
  76576. this.box = new BoxVolume({
  76577. clip:true
  76578. });
  76579. this.box.name = "ClipBox";
  76580. this.box.position.copy(target);
  76581. this.box.scale.copy(scale);
  76582. //带动mapBox
  76583. this.box.addEventListener('position_changed',e=>{
  76584. this.mapBox.center.setX(this.box.position.x);
  76585. this.mapBox.center.setY(this.box.position.y);
  76586. this.mapBox.updatePoints();
  76587. this.changeCallback();
  76588. });
  76589. this.box.addEventListener('scale_changed',e=>{
  76590. var scale = this.box.scale;
  76591. this.mapBox.updatePoints(scale);
  76592. this.changeCallback();
  76593. });
  76594. this.box.addEventListener('orientation_changed',e=>{
  76595. this.mapBox.angle = this.box.rotation.z;
  76596. this.mapBox.rotateBar.rotation.z = this.mapBox.angle;
  76597. this.mapBox.updatePoints();
  76598. this.changeCallback();
  76599. });
  76600. viewer.scene.addVolume(this.box);
  76601. }
  76602. {//map
  76603. let boxRotateBack = ()=>{//不知道是不是这么写。 因为可能z的旋转不一定都在z
  76604. this.box.rotation.x = 0;
  76605. this.box.rotation.y = 0;
  76606. };
  76607. this.mapBox = new mapClipBox(target, scale);
  76608. viewer.mapViewer.scene.add(this.mapBox);
  76609. //带动box
  76610. this.mapBox.addEventListener('repos',e=>{
  76611. this.box.position.setX(this.mapBox.center.x);
  76612. this.box.position.setY(this.mapBox.center.y);
  76613. boxRotateBack();
  76614. this.changeCallback();
  76615. });
  76616. this.mapBox.addEventListener('dragChange',e=>{
  76617. var scale = this.mapBox.getScale();
  76618. this.box.scale.setX(scale.x);
  76619. this.box.scale.setY(scale.y);
  76620. this.box.position.setX(this.mapBox.center.x);
  76621. this.box.position.setY(this.mapBox.center.y);
  76622. boxRotateBack();
  76623. this.changeCallback();
  76624. });
  76625. this.mapBox.addEventListener('rotate',e=>{
  76626. this.box.rotation.z = this.mapBox.angle;
  76627. boxRotateBack();
  76628. this.changeCallback();
  76629. });
  76630. }
  76631. {
  76632. viewer.setClipTask(ClipTask["SHOW_INSIDE"]);
  76633. //viewer.setClipMethod(ClipMethod["INSIDE_ANY"])
  76634. }
  76635. Potree.settings.unableNavigate = true;
  76636. Potree.settings.ifShowMarker = false;
  76637. viewer.updateVisible(viewer.measuringTool.scene, 'clipModel', false);
  76638. //viewer.updateVisible(viewer.mapViewer.cursor, 'clipModel', false)//隐藏地图游标
  76639. viewer.inputHandler.toggleSelection(this.box);
  76640. viewer.inputHandler.fixSelection = true;
  76641. viewer.transformationTool.frame.material.color.set(Potree.config.clip.color);//navvis 15899953
  76642. viewer.setPointStandardMat(true);
  76643. {
  76644. this.events = {
  76645. flyToPos : (e)=>{
  76646. let dis = 2;
  76647. let target = e.position;
  76648. //position = new THREE.Vector3().subVectors(target, this.scene.view.direction)
  76649. //永远朝向框的中心
  76650. /* let dir = new THREE.Vector3().subVectors(this.box.position, e.position).normalize()
  76651. position = new THREE.Vector3().subVectors(target, dir) */
  76652. target = this.box.position;
  76653. position = e.position;
  76654. //为了方便缩放操作,直接使用box中心作为target
  76655. let duration = 1000;
  76656. viewer.scene.view.setView({position, duration, target});
  76657. }
  76658. };
  76659. this.bus.addEventListener('flyToPos',this.events.flyToPos);
  76660. }
  76661. this.editing = true;
  76662. setTimeout(()=>{this.changeCallback(true);},1);
  76663. },
  76664. leave:function(){
  76665. viewer.inputHandler.fixSelection = false;
  76666. viewer.scene.removeVolume(this.box);
  76667. this.mapBox.dispose();
  76668. viewer.setControls(viewer.fpControls);
  76669. Potree.settings.unableNavigate = false;
  76670. Potree.settings.ifShowMarker = this.previousView.ifShowMarker;
  76671. viewer.updateVisible(viewer.measuringTool.scene, 'clipModel', true);
  76672. //viewer.updateVisible(viewer.mapViewer.cursor, 'clipModel', true)
  76673. viewer.setView(this.previousView);
  76674. viewer.setLimitFar(true);
  76675. viewer.setPointStandardMat(false);
  76676. {
  76677. this.bus.removeEventListener('flyToPos',this.events.flyToPos);
  76678. this.events = null;
  76679. }
  76680. this.editing = false;
  76681. },
  76682. getPointcloud:function(){ //找一个离当前最近的点云,且最好有漫游点
  76683. let pointclouds = viewer.scene.pointclouds.filter(e=>e.panos.length>0);
  76684. if(pointclouds.length == 0)pointclouds = viewer.scene.pointclouds;
  76685. let result = Common.sortByScore(pointclouds,[],[e=>{
  76686. let center = e.bound.getCenter(new Vector3);
  76687. let size = e.bound.getSize(new Vector3).length() / 2;
  76688. let posToCenter = viewer.images360.position.distanceTo(center);
  76689. return size / posToCenter
  76690. }]);
  76691. return result[0].item
  76692. },
  76693. getTarget:function(boundCenter){//box位置。要找一个有点云的地方。方案1相机位置, 方案2接近相机的漫游点, 方案3接近中心的漫游点。选择方案2,因最大概率有点云
  76694. var target = new Vector3();
  76695. var cameraPos = viewer.images360.position;
  76696. var pano = Common.find(viewer.images360.panos , [], [Images360.sortFunctions.floorDisSquaredToPoint(cameraPos)]);
  76697. if(pano){
  76698. target.copy(pano.position);
  76699. target.setZ(boundCenter.z);
  76700. }else {
  76701. target.copy(boundCenter);
  76702. }
  76703. return target
  76704. },
  76705. /* switchMap:function(state){
  76706. }, */
  76707. download:function( ){
  76708. if(this.getIntersectPointcloud().length == 0){
  76709. return null
  76710. }
  76711. var visiPointclouds = viewer.scene.pointclouds.filter(e=> viewer.getObjVisiByReason(e, 'datasetSelection'));
  76712. let data = {
  76713. transformation_matrix: visiPointclouds.map((cloud)=>{
  76714. let data = {
  76715. id: cloud.dataset_id,
  76716. matrix : this.getTransformationMatrix(cloud).elements,
  76717. modelMatrix:(new Matrix4).copy(cloud.transformMatrix).transpose().elements
  76718. };
  76719. return data
  76720. }) ,
  76721. aabb: "b-0.5 -0.5 -0.5 0.5 0.5 0.5" //剪裁空间( 所有点在乘上这个矩阵后, 还能落在 1 * 1 * 1的box内的点就是所裁剪的
  76722. };
  76723. return data
  76724. //https://testlaser.4dkankan.com/indoor/t-ia44BhY/api/pointcloud/crop
  76725. },
  76726. downloadNoCrop(){//不剪裁 下载整个点云
  76727. var visiPointclouds = viewer.scene.pointclouds.filter(e=> viewer.getObjVisiByReason(e, 'datasetSelection'));
  76728. let data = {
  76729. transformation_matrix: visiPointclouds.map((cloud)=>{
  76730. let data = {
  76731. id: cloud.dataset_id,
  76732. matrix : new Matrix4().elements, //固定值
  76733. modelMatrix:(new Matrix4).copy(cloud.transformMatrix).transpose().elements
  76734. };
  76735. return data
  76736. }) ,
  76737. aabb: "b-12742000 -12742000 -12742000 12742000 12742000 12742000" //固定剪裁空间
  76738. };
  76739. console.log(data);
  76740. return data
  76741. },
  76742. getTransformationMatrix:function(pointcloud) {//剪裁矩阵
  76743. var invMatrix = new Matrix4().getInverse(this.box.matrixWorld);
  76744. return (new Matrix4).multiplyMatrices(invMatrix, pointcloud.transformMatrix).transpose()
  76745. },
  76746. getIntersectPointcloud(){
  76747. var boxBound = new Box3(
  76748. new Vector3(-0.5,-0.5,-0.5), new Vector3(0.5,0.5,0.5),
  76749. ).applyMatrix4(this.box.matrixWorld); //large boundingbox
  76750. /* var boxTightPoints = this.box.children[0].geometry.vertices.map(e=>e.clone().applyMatrix4(this.matrixWorld))
  76751. console.log(boxTightPoints)
  76752. */
  76753. let boxMatrixInverse = new Matrix4().copy(this.box.matrixWorld).invert();
  76754. let boxPoints = [
  76755. new Vector3(boxBound.min.x, boxBound.min.y,0),
  76756. new Vector3(boxBound.max.x, boxBound.min.y,0),
  76757. new Vector3(boxBound.max.x, boxBound.max.y,0),
  76758. new Vector3(boxBound.min.x, boxBound.max.y,0)
  76759. ];
  76760. var intersect = (pointcloud)=>{
  76761. if(!pointcloud.bound.intersectsBox(boxBound))return false
  76762. //判断box和点云的tight bound是否相交(因为box可以任意旋转,且实在找不到三维中的立方体相交的函数,所以直接用boxBound)
  76763. var points = pointcloud.getUnrotBoundPoint('all');
  76764. let rings = math.getPolygonsMixedRings([points.slice(0,4), boxPoints] , true);
  76765. //console.log(pointcloud.dataset_id, pointcloud.name, rings.length)
  76766. if(rings.length > 1 )return false
  76767. {//再用frustum和数据集的sphere相交试试,能排除一些错误
  76768. let a = Potree.Utils.isInsideBox(points, boxMatrixInverse);
  76769. if(!a){
  76770. console.log('没能经过isInsideBox测试');
  76771. }
  76772. return a
  76773. }
  76774. return true
  76775. };
  76776. return viewer.scene.pointclouds.filter(e=>intersect(e))
  76777. }
  76778. /*
  76779. 裁剪点云时,2D界面显示全部平面图,按楼层切换显示。
  76780. */
  76781. };
  76782. class SplitScreen extends EventDispatcher{
  76783. constructor (args = {}) {
  76784. super();
  76785. }
  76786. splitStart(cameraProps){
  76787. let viewports = [];
  76788. let subViewports = [viewer.mainViewport];
  76789. if(viewer.mapViewer){
  76790. subViewports.push(viewer.mapViewer.viewports[0]);
  76791. }
  76792. let length = cameraProps.length;
  76793. for(let i=0;i<length;i++){
  76794. let prop = cameraProps[i];
  76795. let viewport;
  76796. let v = subViewports.find(e=>e.name == (prop.name2||prop.name));
  76797. if(v){
  76798. viewport = v;
  76799. viewport.left = prop.left; viewport.bottom = prop.bottom; viewport.width = prop.width; viewport.height = prop.height;
  76800. }
  76801. if(!viewport){
  76802. let view = new View();
  76803. if(prop.limitBound)view.limitBound = prop.limitBound;
  76804. prop.direction && (view.direction = prop.direction);
  76805. viewport = new Viewport(view , this.getOrthoCamera(), prop );
  76806. if(prop.viewContainsPoints)viewport.viewContainsPoints = prop.viewContainsPoints;
  76807. //viewport.unableDepth = true //depthBasicMaterial等在此viewport中不开启depth
  76808. }
  76809. if(viewport.camera.type == 'OrthographicCamera' ){
  76810. viewport.targetPlane = new Plane();
  76811. viewport.shiftTarget = new Vector3; //project在targetPlane上的位置
  76812. }
  76813. viewport.fitMargin = prop.margin;
  76814. viewports.push(viewport);
  76815. }
  76816. viewer.viewports = viewports;
  76817. viewer.updateScreenSize({forceUpdateSize:true});
  76818. viewports.forEach(viewport=>{
  76819. if(viewport.name == 'MainView')return
  76820. this.viewportFitBound(viewport, viewer.bound.boundingBox , viewer.bound.center , 0, viewport.fitMargin);
  76821. });
  76822. return viewports
  76823. }
  76824. unSplit(){
  76825. this.unfocusViewport();
  76826. viewer.viewports = [viewer.mainViewport];
  76827. viewer.mainViewport.width = 1;
  76828. viewer.mainViewport.height = 1;
  76829. viewer.mainViewport.left = 0;
  76830. viewer.mainViewport.bottom = 0;
  76831. viewer.updateScreenSize({forceUpdateSize:true});
  76832. }
  76833. viewportFitBound(viewport, bound, center, duration=0, margin){
  76834. let view = viewport.view;
  76835. let info = {bound};
  76836. let {boundSize, boundCenter} = this.getViewBound(viewport);
  76837. viewport.targetPlane.setFromNormalAndCoplanarPoint( view.direction.clone(), boundCenter );
  76838. viewport.targetPlane.projectPoint(center, viewport.shiftTarget); //target转换到过模型中心的平面,以保证镜头一定在模型外 this.shiftTarget是得到的
  76839. info.endPosition = this.getPosOutOfModel(viewport, boundSize);
  76840. //if(viewport.name == 'mapViewport')info.endPosition.z = Math.max(Potree.config.map.cameraHeight, info.endPosition.z)
  76841. info.margin = margin || {x:30, y:30};
  76842. view.moveOrthoCamera(viewport, info , duration );
  76843. }
  76844. getViewBound(viewport){
  76845. let {boundSize, center} = viewer.bound;
  76846. if(viewport.viewContainsPoints){//视野范围内必须要包含的点,直接算入模型区域。这时候得到的boundCenter和模型中心不重合
  76847. let boundingBox = viewer.bound.boundingBox.clone();
  76848. viewport.viewContainsPoints.forEach(point=>{
  76849. boundingBox.expandByPoint(point);
  76850. });
  76851. boundSize = boundingBox.getSize(new Vector3);
  76852. center = boundingBox.getCenter(new Vector3);
  76853. }
  76854. return {boundSize, boundCenter:center }
  76855. }
  76856. getPosOutOfModel(viewport, boundSize){
  76857. //let {boundSize, center} = viewer.bound
  76858. boundSize = boundSize || this.getViewBound(viewport).boundSize;
  76859. let expand = 10;
  76860. let radius = boundSize.length(); // / 2
  76861. let position = viewport.shiftTarget.clone().sub(viewport.view.direction.clone().multiplyScalar(radius + expand));
  76862. return position
  76863. }
  76864. updateCameraOutOfModel(){//因为移动模型导致模型超出相机外,所以更新位置
  76865. viewer.viewports.forEach((viewport, i )=>{
  76866. if(viewport != viewer.mainViewport){
  76867. let {boundSize, boundCenter} = this.getViewBound(viewport);
  76868. viewport.targetPlane.setFromNormalAndCoplanarPoint( viewport.view.direction.clone(), boundCenter);
  76869. viewport.targetPlane.projectPoint(viewport.view.position, viewport.shiftTarget); //target转换到过模型中心的平面,以保证镜头一定在模型外 this.shiftTarget是得到的
  76870. let endPosition = this.getPosOutOfModel(viewport, boundSize);
  76871. //if(viewport.name == 'mapViewport')endPosition.z = Math.max(Potree.config.map.cameraHeight, endPosition.z)
  76872. viewport.view.position.copy(endPosition);
  76873. }
  76874. });
  76875. }
  76876. rotateSideCamera(viewport, angle){//侧视图绕模型中心水平旋转
  76877. //let {boundSize, center} = viewer.bound
  76878. let {boundSize, boundCenter } = this.getViewBound(viewport);
  76879. let center = this.focusCenter || boundCenter; //旋转中心,一般是所有模型的中心,除非想指定中心点
  76880. //找到平移向量
  76881. viewport.targetPlane.setFromNormalAndCoplanarPoint(viewport.view.direction , center );
  76882. viewport.targetPlane.projectPoint(viewport.view.position, viewport.shiftTarget ); //target转换到过模型中心的平面,以保证镜头一定在模型外
  76883. let vec = new Vector3().subVectors(center, viewport.shiftTarget);//相对于中心的偏移值,旋转后偏移值也旋转
  76884. //旋转
  76885. var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0,0,1), angle);
  76886. viewport.view.direction = viewport.view.direction.applyMatrix4(rotMatrix);
  76887. vec.applyMatrix4(rotMatrix);
  76888. viewport.shiftTarget.subVectors(center,vec); //新的
  76889. viewport.view.position = this.getPosOutOfModel(viewport, boundSize);
  76890. }
  76891. getOrthoCamera(){
  76892. return new OrthographicCamera(-100, 100, 100, 100, 0.01, 10000)
  76893. }
  76894. focusOnViewport(name){//全屏
  76895. viewer.viewports.forEach((viewport, i )=>{
  76896. if(viewport.name == name){
  76897. this.focusInfo = {
  76898. name,
  76899. left : viewport.left, bottom : viewport.bottom, height : viewport.height, width : viewport.width
  76900. };
  76901. viewport.left = 0; viewport.bottom = 0; viewport.height = 1; viewport.width = 1;
  76902. }else {
  76903. viewport.active = false;
  76904. }
  76905. });
  76906. viewer.updateScreenSize({forceUpdateSize:true});
  76907. }
  76908. unfocusViewport(){
  76909. if(!this.focusInfo)return
  76910. viewer.viewports.forEach((viewport, i )=>{
  76911. if(this.focusInfo.name == viewport.name){//全屏的恢复
  76912. viewport.left = this.focusInfo.left;
  76913. viewport.bottom = this.focusInfo.bottom;
  76914. viewport.height = this.focusInfo.height;
  76915. viewport.width = this.focusInfo.width;
  76916. }
  76917. viewport.active = true;
  76918. });
  76919. viewer.updateScreenSize({forceUpdateSize:true});
  76920. this.focusInfo = null;
  76921. }
  76922. }
  76923. const viewportProps = [
  76924. {
  76925. left:0.5,
  76926. bottom:0.5,
  76927. width: 0.5,height:0.5,
  76928. name : 'MainView',
  76929. //view: viewer.scene.view,
  76930. active: true,
  76931. },
  76932. {
  76933. left:0,
  76934. bottom:0.5,
  76935. width: 0.5,height:0.5,
  76936. name : 'top',
  76937. name2 : 'mapViewport',
  76938. axis:["x","y"],
  76939. direction : new Vector3(0,0,-1), //镜头朝向
  76940. //axisSign:[1,1],
  76941. active: true,
  76942. //相机位置在z轴正向
  76943. },
  76944. {
  76945. left:0.5,
  76946. bottom:0,
  76947. width: 0.5,height:0.5,
  76948. name : 'right',
  76949. axis:["y","z"],
  76950. direction : new Vector3(1,0,0),
  76951. //axisSign:[1,1],
  76952. active: true,
  76953. //相机位置在x轴负向 右下角屏
  76954. },
  76955. {
  76956. left:0,
  76957. bottom:0,
  76958. width: 0.5,height:0.5,
  76959. name : 'back',
  76960. axis:["x","z"],
  76961. direction : new Vector3(0,-1,0),
  76962. //axisSign:[-1,1], // 从镜头方向看 x向左 所以取负
  76963. active: true,
  76964. //相机位置在y轴正向 左下角屏
  76965. },
  76966. ];
  76967. var SplitScreen4Views = new SplitScreen();
  76968. SplitScreen4Views.split = function(o={}){
  76969. var defaultCamera = viewer.scene.getActiveCamera();
  76970. let {boundSize, center} = viewer.bound;
  76971. viewer.setLimitFar(false);
  76972. viewer.mapViewer.attachToMainViewer(true,'split4Screens','dontSet');
  76973. let viewports = this.splitStart(viewportProps);
  76974. //覆盖在map上、点云等其他物体之下的一层背景
  76975. let mapViewport = viewer.mapViewer.viewports[0];
  76976. mapViewport.noPointcloud = false;
  76977. //隐藏地图游标
  76978. //viewer.updateVisible(viewer.mapViewer.cursor, 'split4Screens', false)
  76979. /* viewer.images360.panos.forEach(pano=>{
  76980. viewer.updateVisible(pano.mapMarker, 'split4Screens', false) //希望这时候mapMarker已经建好了吧
  76981. }) */
  76982. //材质
  76983. this.statesBefore = {
  76984. pointDensity : Potree.settings.pointDensity,
  76985. displayMode : Potree.settings.displayMode,
  76986. position: viewer.images360.position,
  76987. target: viewer.scene.view.getPivot(),
  76988. //---
  76989. //ifShowMarker : Potree.settings.ifShowMarker,
  76990. };
  76991. viewer.setPointStandardMat(true,null,true); //切换到标准模式(主要为了mainViewport) 点云使用标准大小
  76992. var matBefore = {
  76993. opacity : new Map()
  76994. };
  76995. var newOpacityMap = new Map();
  76996. viewer.scene.pointclouds.forEach(e=>{
  76997. matBefore.opacity.set(e, e.temp.pointOpacity);
  76998. matBefore.colorType = e.material.activeAttributeName;
  76999. /* {
  77000. var map = new Map()
  77001. newOpacityMap.set(e, map )
  77002. var size = e.bound.getSize()
  77003. viewports.forEach(viewport=>{//根据bound设置opacity,越小的要靠越近,需要大的opacity。但似乎影响太大了
  77004. if(viewport.name == 'MainView')return;
  77005. var prop = viewportProps.find(v => viewport.name == v.name2||viewport.name == v.name)
  77006. let axis = prop.axis
  77007. var width = size[axis[0]]
  77008. var height = size[axis[1]]
  77009. var area = width * height
  77010. map.set(viewport, 5000/area);
  77011. })
  77012. } */
  77013. });
  77014. let beforeRender = function(){
  77015. viewer.scene.pointclouds.forEach(e=>{
  77016. if(this.name == "MainView"){
  77017. e.material.activeAttributeName = matBefore.colorType; // 'rgba'
  77018. e.material.useFilterByNormal = false;
  77019. e.changePointOpacity(matBefore.opacity.get(e)); //1 //恢复下 e.temp.pointOpacity 其实就是1
  77020. Potree.settings.pointDensity = 'fourViewportsMain';/* 'fourViewports' */ //本来想比另外三屏高一点质量,结果发现会闪烁,因为点云加载需要时间 (navvis仿版也是一样,以后看看能否优化)
  77021. }else {
  77022. e.material.activeAttributeName = "color";
  77023. e.material.useFilterByNormal = true;
  77024. Potree.settings.pointDensity = 'fourViewports'; //强制降低点云质量
  77025. e.changePointOpacity(0.6/* newOpacityMap.get(e).get(viewport), true */); //多数据集有的数据集很小,放大后显示特别淡
  77026. //console.log(e.name, viewport.name, e.temp.pointOpacity, e.material.opacity)
  77027. }
  77028. });
  77029. };
  77030. viewports.forEach(viewport=>{viewport.beforeRender = beforeRender;});
  77031. this.enableMap(false);
  77032. this.enableFloorplan(false);
  77033. viewer.mapViewer.setViewLimit('expand'); //多数据集距离远时可以任意远,所以不限制了。但是这样就会看到地图边界了怎么办?
  77034. //viewer.dispatchEvent({'type': 'beginSplitView' })
  77035. //viewer.updateScreenSize({forceUpdateSize:true})
  77036. //this.viewportFitBound(mapViewport, boundSize, center)
  77037. //Potree.settings.ifShowMarker = false
  77038. Potree.settings.displayMode = 'showPointCloud';
  77039. };
  77040. SplitScreen4Views.recover = function(){
  77041. this.unSplit();
  77042. /* const {width, height} = viewer.renderer.getSize(new THREE.Vector2());
  77043. viewer.renderer.setViewport(0,0,width,height)
  77044. viewer.renderer.setScissorTest( false ); */
  77045. viewer.setView({
  77046. position: this.statesBefore.position,
  77047. target: this.statesBefore.target,
  77048. duration:300,
  77049. callback:function(){
  77050. }
  77051. });
  77052. viewer.mainViewport.beforeRender = null;
  77053. viewer.setLimitFar(true);
  77054. let mapViewport = viewer.mapViewer.viewports[0];
  77055. viewer.mapViewer.attachToMainViewer(false);
  77056. //viewer.updateVisible(viewer.mapViewer.cursor, 'split4Screens', true)
  77057. /* viewer.images360.panos.forEach(pano=>{
  77058. viewer.updateVisible(pano.mapMarker, 'split4Screens', true)
  77059. }) */
  77060. mapViewport.noPointcloud = true;
  77061. {
  77062. this.enableMap(Potree.settings.mapEnable);
  77063. this.enableFloorplan(Potree.settings.floorplanEnable);
  77064. if(this.floorplanListener){
  77065. viewer.mapViewer.mapLayer.removeEventListener( 'floorplanLoaded', this.floorplanListener );
  77066. this.floorplanListener = null;
  77067. }
  77068. }
  77069. Potree.settings.pointDensity = this.statesBefore.pointDensity;
  77070. if(!Potree.settings.isOfficial){
  77071. Potree.settings.displayMode = this.statesBefore.displayMode;
  77072. }
  77073. viewer.scene.pointclouds.forEach(e=>{
  77074. //e.material.color.set(this.statesBefore.mat.color)
  77075. //e.material.activeAttributeName = this.statesBefore.mat.colorType
  77076. e.material.useFilterByNormal = false;
  77077. //e.material.opacity = this.statesBefore.mat.opacity
  77078. });
  77079. viewer.setPointStandardMat(false);
  77080. viewer.mapViewer.setViewLimit('standard');
  77081. //Potree.settings.ifShowMarker = this.statesBefore.ifShowMarker
  77082. //viewer.dispatchEvent({'type': 'finishSplitView' })
  77083. //viewer.updateScreenSize({forceUpdateSize:true})
  77084. };
  77085. SplitScreen4Views.updateMapViewerBG = function(){
  77086. let mapViewport = viewer.mapViewer.viewports[0];
  77087. if(this.floorplanEnabled || this.mapEnabled){
  77088. mapViewport.background = 'overlayColor';
  77089. mapViewport.backgroundColor = new Color(0,0,0);
  77090. mapViewport.backgroundOpacity = 0.5;
  77091. }else {
  77092. mapViewport.background = null;
  77093. mapViewport.backgroundColor = null;
  77094. mapViewport.backgroundOpacity = null;
  77095. }
  77096. };
  77097. SplitScreen4Views.setFloorplanDisplay = function(e, show=false){
  77098. //viewer.updateVisible(e.floorplan.objectGroup, 'splitScreen', !!show)
  77099. //e.floorplan.objectGroup.visible = !!show
  77100. //viewer.mapViewer.mapLayer.needUpdate = true
  77101. e.floorplan.setEnable(show);
  77102. };
  77103. SplitScreen4Views.enableMap = function(enable){
  77104. let map = viewer.mapViewer.mapLayer.maps.find(e=>e.name == 'map');
  77105. //viewer.updateVisible(map.objectGroup, 'splitScreen', !!enable)
  77106. //map.objectGroup.visible = !!enable
  77107. //if(enable)viewer.mapViewer.mapLayer.needUpdate = true //加载地图
  77108. map.setEnable(!!enable);
  77109. //viewer.mapViewer.mapGradientBG = viewer.background == 'gradient' && !enable
  77110. this.mapEnabled = enable;
  77111. this.updateMapViewerBG();
  77112. },
  77113. //直接覆盖原设置
  77114. SplitScreen4Views.enableFloorplan = function(enable){ //是否让自定义的平面图显示
  77115. let floorplans = viewer.mapViewer.mapLayer.maps.filter(e=>e.name.includes('floorplan'));
  77116. if(this.floorplanListener){
  77117. viewer.mapViewer.mapLayer.removeEventListener( 'floorplanLoaded', this.floorplanListener );
  77118. }
  77119. this.floorplanListener = (e)=>{
  77120. this.setFloorplanDisplay(e, enable);
  77121. };
  77122. viewer.mapViewer.mapLayer.addEventListener( 'floorplanLoaded', this.floorplanListener ); //万一之后才加载
  77123. if(!enable){
  77124. //隐藏平面图
  77125. floorplans.forEach(floorplan=>this.setFloorplanDisplay({floorplan},false));
  77126. }else {
  77127. floorplans.forEach(floorplan=>this.setFloorplanDisplay({floorplan},true));
  77128. }
  77129. if (enable && floorplans.length == 0) Potree.loadMapEntity('all',true);
  77130. this.floorplanEnabled = enable;
  77131. this.updateMapViewerBG();
  77132. },
  77133. /* viewportFitBound:function(viewport, boundSize, center){ //使一个viewport聚焦在某个范围
  77134. var prop = viewportProps.find(v => viewport.name == v.name2||viewport.name == v.name)
  77135. let axis = prop.axis
  77136. let expand = 10;
  77137. let position = center.clone()
  77138. var moveAtAxis = ['x','y','z'].find(e=>!(axis.includes(e)))
  77139. if(viewport.name == 'mapViewport'){
  77140. let ori = viewport.view.position[moveAtAxis]
  77141. position[moveAtAxis] = ori //不改变这个值,尤其是mapViewer中的z
  77142. }else{
  77143. position[moveAtAxis] += boundSize[moveAtAxis]/2+expand//移动到bounding边缘外
  77144. }
  77145. viewport.view.position.copy(position)
  77146. var width = Math.max(boundSize[axis[0]], boundSize[axis[1]] * viewport.camera.aspect)//视口宽度(米)
  77147. var margin = 50 //px
  77148. viewport.camera.zoom = (viewport.resolution.x - margin) / width
  77149. viewport.camera.updateProjectionMatrix()
  77150. },
  77151. */
  77152. SplitScreen4Views.focusOnPointCloud = function(pointcloud){//三个屏都聚焦在这个点云
  77153. var boundSize = pointcloud.bound.getSize(new Vector3);
  77154. var center = pointcloud.bound.getCenter(new Vector3);
  77155. let target = pointcloud.panosBound && pointcloud.panosBound.center; //看向pano集中的地方,也就是真正有点云的地方。(因为需要展示所有点云,所以没办法用这个做为center)
  77156. this.focusOnObject(pointcloud.bound, center,target);
  77157. viewer.flyToDataset({pointcloud, dontMoveMap:true, duration:0});
  77158. };
  77159. SplitScreen4Views.focusOnObject = function(bound, center, target, duration=0){
  77160. viewer.viewports.forEach(e=>{
  77161. if(e.name == 'MainView'){
  77162. /* let len = boundSize.length()
  77163. let distance = THREE.Math.clamp(e.view.position.distanceTo(center), len * 0.01, len*0.3 ) //距离限制
  77164. //viewer.focusOnObject({position:center}, 'point', duration, {distance, direction: e.view.direction,dontMoveMap:true} )//平移镜头
  77165. //为了方便定位,直接飞到中心位置:
  77166. e.view.setView({
  77167. position:center, duration, target
  77168. }) */
  77169. }else {
  77170. this.viewportFitBound(e, bound, center);
  77171. }
  77172. });
  77173. };
  77174. class History extends EventDispatcher{
  77175. constructor(o){
  77176. super();
  77177. this.list = [];
  77178. this.callback = o.callback;
  77179. }
  77180. undo(){
  77181. let last = this.list.pop();
  77182. last && this.callback && this.callback(last);
  77183. }
  77184. redo(){//暂时不写
  77185. }
  77186. writeIn(item){
  77187. this.list.push(item);
  77188. }
  77189. clear(){
  77190. this.list.length = 0;
  77191. }
  77192. }
  77193. var Alignment = {
  77194. SplitScreen: SplitScreen4Views,
  77195. handleState:null, //操作状态 'translate'|'rotate'
  77196. bus: new EventDispatcher(),
  77197. prepareRecord : true,
  77198. writeToHistory(content){
  77199. if(!this.prepareRecord)return;
  77200. this.prepareRecord = false;
  77201. this.history.writeIn(content);
  77202. },
  77203. /* undo(){//撤销一步
  77204. let last = this.history.pop();
  77205. last && last.forEach(item=>{
  77206. this.applyTemp(item)
  77207. })
  77208. }, */
  77209. applyTemp(item){
  77210. var pointcloud = viewer.scene.pointclouds.find(p=>p.dataset_id+p.name == item.sid);
  77211. pointcloud.orientationUser = item.orientationUser;
  77212. pointcloud.translateUser = item.translateUser;
  77213. this.setMatrix( pointcloud );
  77214. },
  77215. getTemp(pointclouds){//记录最近一次保存后的状态,便于恢复
  77216. pointclouds = pointclouds || viewer.scene.pointclouds;
  77217. return pointclouds.map(e=>{
  77218. return {
  77219. sid : e.dataset_id+e.name,
  77220. orientationUser : e.orientationUser,
  77221. translateUser : e.translateUser.clone(),
  77222. }
  77223. } )
  77224. },
  77225. init:function(){
  77226. let rotateInfo;
  77227. viewer.fpControls.addEventListener("transformPointcloud",(e)=>{
  77228. if(e.pointclouds[0].dataset_id == Potree.settings.originDatasetId){//禁止手动移动初始数据集
  77229. return this.bus.dispatchEvent('forbitMoveOriginDataset')
  77230. }
  77231. this.writeToHistory(this.getTemp(e.pointclouds) );
  77232. if(this.handleState == 'translate'){
  77233. e.pointclouds.forEach(cloud=>Alignment.translate(cloud, e.moveVec));
  77234. }else if(this.handleState == 'rotate'){
  77235. if(Potree.settings.editType == 'pano'){
  77236. let center = e.intersectStart; //旋转中心是mousedown的位置
  77237. if(e.intersect.equals(center))return
  77238. if(!rotateInfo){
  77239. rotateInfo = {
  77240. orientationUser : e.pointclouds[0].orientationUser,
  77241. //vecStart : e.moveVec, // 首次移动向量 只有八个方向,精度太小,所以延迟
  77242. pointclouds: e.pointclouds
  77243. };
  77244. this.bus.dispatchEvent({type:'rotateStart', startPoint:center});
  77245. return
  77246. }else if(!rotateInfo.vecStart){
  77247. let vec = new Vector3().subVectors(e.intersect, center).setZ(0);
  77248. if(vec.length() * e.camera.zoom > 30){ //在屏幕上距离初始点有一定距离后开始算
  77249. //console.log('moveVec',vec)
  77250. rotateInfo.vecStart = vec;
  77251. }
  77252. }else {
  77253. let vec = new Vector3().subVectors(e.intersect, center).setZ(0);
  77254. let angle = math.getAngle(rotateInfo.vecStart,vec,'z');
  77255. let diffAngle = rotateInfo.orientationUser + angle - rotateInfo.pointclouds[0].orientationUser;
  77256. rotateInfo.pointclouds.forEach(cloud=>{
  77257. /* let centerNoTranfrom = Potree.Utils.datasetPosTransform({ toDataset: true, pointcloud:cloud, position: center }) //中心点在数据集中的位置
  77258. Alignment.rotate(cloud, null, diffAngle)
  77259. let centerNow = Potree.Utils.datasetPosTransform({ fromDataset: true, pointcloud:cloud, position: centerNoTranfrom }) //中心点的现在位置
  77260. let shift = new THREE.Vector3().subVectors( center, centerNow); //偏移量
  77261. Alignment.translate(cloud,shift) //使center还保留在原位
  77262. //let centerNow1 = Potree.Utils.datasetPosTransform({ fromDataset: true, pointcloud:rotateInfo.pointcloud, position: centerNoTranfrom }) //中心点的现在位置
  77263. */
  77264. Alignment.rotateAround(center, cloud, null, diffAngle);
  77265. });
  77266. }
  77267. this.bus.dispatchEvent({type:'rotate', endPoint: e.intersect});
  77268. }else {
  77269. let center = e.pointclouds[0].translateUser; //移动到的位置就是中心
  77270. if(e.intersect.equals(center))return
  77271. if(!rotateInfo){
  77272. rotateInfo = {
  77273. orientationUser : e.pointclouds[0].orientationUser,
  77274. vecStart : new Vector3().subVectors(e.intersectStart, center).setZ(0),
  77275. //pointclouds: e.pointclouds
  77276. pointcloud: e.pointclouds[0]
  77277. };
  77278. }else {
  77279. let vec = new Vector3().subVectors(e.intersect, center).setZ(0);
  77280. let angle = math.getAngle(rotateInfo.vecStart,vec,'z');
  77281. let diffAngle = rotateInfo.orientationUser + angle - rotateInfo.pointcloud.orientationUser;
  77282. Alignment.rotate(rotateInfo.pointcloud, null, diffAngle);
  77283. }
  77284. }
  77285. }
  77286. });
  77287. viewer.fpControls.addEventListener("end",(e)=>{
  77288. rotateInfo = null;
  77289. this.prepareRecord = true;
  77290. });
  77291. viewer.inputHandler.addEventListener('keydown',e=>{
  77292. if(e.keyCode == 90 && e.event.ctrlKey){//Z
  77293. this.history.undo();
  77294. }
  77295. });
  77296. // cursor:
  77297. let updateCursor = (e)=>{
  77298. if(e.drag || !this.editing)return //仅在鼠标不按下时更新:
  77299. let handleState = Alignment.handleState;
  77300. if(e.hoverViewport.alignment && handleState && e.hoverViewport.alignment[handleState]){
  77301. if(handleState == 'translate'){
  77302. if( e.intersect && e.intersect.location ){
  77303. viewer.dispatchEvent({
  77304. type : "CursorChange", action : "add", name:"movePointcloud"
  77305. });
  77306. }else {
  77307. viewer.dispatchEvent({
  77308. type : "CursorChange", action : "remove", name:"movePointcloud"
  77309. });
  77310. }
  77311. }else if(handleState == 'rotate'){
  77312. if( e.intersect && e.intersect.location ){
  77313. viewer.dispatchEvent({
  77314. type : "CursorChange", action : "add", name:"rotatePointcloud"
  77315. });
  77316. }else {
  77317. viewer.dispatchEvent({
  77318. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  77319. });
  77320. }
  77321. }
  77322. }else {
  77323. //清空:
  77324. viewer.dispatchEvent({
  77325. type : "CursorChange", action : "remove", name:"movePointcloud"
  77326. });
  77327. viewer.dispatchEvent({
  77328. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  77329. });
  77330. }
  77331. };
  77332. viewer.addEventListener('global_mousemove',updateCursor);
  77333. viewer.addEventListener('global_drop',updateCursor);//拖拽结束
  77334. viewer.addEventListener('updateModelBound', (e)=>{
  77335. if(this.editing){
  77336. this.SplitScreen.updateCameraOutOfModel();
  77337. }
  77338. });
  77339. },
  77340. setMatrix : function(pointcloud){
  77341. var vec1 = pointcloud.position; //position为数据集内部的偏移,在navvis中对应的是dataset.pointCloudSceneNode的children[0].position
  77342. var vec2 = pointcloud.translateUser;
  77343. var angle = pointcloud.orientationUser;
  77344. var pos1Matrix = new Matrix4().setPosition(vec1);//先移动到点云本身应该在的初始位置(在4dkk里和其他应用中都是在这个位置的,也能和漫游点对应上)
  77345. var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0,0,1), angle);//再旋转
  77346. var pos2Matrix = new Matrix4().setPosition(vec2);//最后是平移
  77347. var matrix = new Matrix4().multiplyMatrices(pos2Matrix, rotMatrix);
  77348. pointcloud.transformMatrix = matrix.clone();//为该数据集的变化矩阵。 对应navvis的m2w_
  77349. pointcloud.transformInvMatrix.copy(matrix).invert();
  77350. pointcloud.rotateMatrix = rotMatrix;
  77351. pointcloud.rotateInvMatrix.copy(rotMatrix).invert();
  77352. pointcloud.panos.forEach(e=>e.transformByPointcloud());
  77353. matrix = new Matrix4().multiplyMatrices(matrix, pos1Matrix);
  77354. pointcloud.matrix = matrix;
  77355. //pointcloud.matrixWorldNeedsUpdate = true //更新matrixWorld (非计算,直接赋值)
  77356. pointcloud.updateMatrixWorld(true);
  77357. if(this.editing){
  77358. Alignment.changeCallBack && Alignment.changeCallBack();
  77359. }
  77360. if(pointcloud.spriteNodeRoot){
  77361. pointcloud.spriteNodeRoot.matrixWorld.copy(pointcloud.matrixWorld);//.multiplyMatrices(pointcloud.matrixWorld, pointcloud.matrixWorld);
  77362. }
  77363. viewer.updateModelBound();
  77364. //pointcloud.updateBound()
  77365. pointcloud.getPanosBound();
  77366. },
  77367. rotateAround(center, pointcloud, deg, angle){//绕center点转动
  77368. var angle = angle != void 0 ? angle : MathUtils.degToRad(deg);
  77369. let vec1 = new Vector3().subVectors(pointcloud.translateUser, center);
  77370. let rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0,0,1), angle);
  77371. let vec2 = vec1.clone().applyMatrix4(rotMatrix); //将到旋转中心的偏差也转动
  77372. let vec3 = new Vector3().subVectors(vec2,vec1); //这个就是多出来的一步translateUser
  77373. this.rotate(pointcloud, deg, angle);
  77374. this.translate(pointcloud, vec3);
  77375. //绕点转动就是比普通转动多一步移动到相对center的某个位置。 1 初始点云移动到自己的position; 2 移动一个vec1 3绕原点旋转 4再移动一个原本的translateUser。 绘制出来后发现移动量就是第二步vec旋转后的偏移
  77376. },
  77377. rotate:function(pointcloud, deg, angle){//绕各自中心转动(各自的position) 假设点云位移position后0,0,0就是它的中心了(根据navvis观察这样做是绕同一个点旋转的)
  77378. var angle = angle != void 0 ? angle : MathUtils.degToRad(deg); //正逆负顺
  77379. pointcloud.orientationUser += angle;
  77380. Alignment.setMatrix(pointcloud);
  77381. },
  77382. translate:function(pointcloud, vec){
  77383. pointcloud.translateUser.add(vec);
  77384. Alignment.setMatrix(pointcloud);
  77385. },
  77386. enter:function(){
  77387. //this.saveTemp()
  77388. this.originData = this.getTemp();
  77389. this.SplitScreen.split({alignment:true});
  77390. viewer.images360.panos.forEach(pano=>{
  77391. viewer.updateVisible(pano.mapMarker, 'split4Screens', false);
  77392. });
  77393. viewer.viewports.find(e=>e.name == 'mapViewport').alignment = {rotate:true,translate:true};
  77394. viewer.viewports.find(e=>e.name == 'right').alignment = {translate:true};
  77395. viewer.viewports.find(e=>e.name == 'back').alignment = {translate:true};
  77396. this.editing = true;
  77397. viewer.updateFpVisiDatasets();
  77398. },
  77399. leave:function(){
  77400. this.switchHandle(null);
  77401. /* this.originData.forEach(e=>{//恢复
  77402. var pointcloud = viewer.scene.pointclouds.find(p=>p.dataset_id == e.id)
  77403. this.translate(pointcloud, new THREE.Vector3().subVectors(e.translateUser , pointcloud.translateUser))
  77404. this.rotate(pointcloud, null, e.orientationUser - pointcloud.orientationUser)
  77405. }) */
  77406. this.originData.forEach(e=>{//恢复
  77407. this.applyTemp(e);
  77408. });
  77409. this.SplitScreen.recover();
  77410. viewer.images360.panos.forEach(pano=>{
  77411. viewer.updateVisible(pano.mapMarker, 'split4Screens', true);
  77412. });
  77413. this.editing = false;
  77414. this.history.clear();
  77415. viewer.updateFpVisiDatasets();
  77416. viewer.dispatchEvent({
  77417. type : "CursorChange", action : "remove", name:"movePointcloud"
  77418. });
  77419. viewer.dispatchEvent({
  77420. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  77421. });
  77422. }
  77423. ,
  77424. switchHandle:function(state){
  77425. this.handleState = state;
  77426. //清空:
  77427. viewer.dispatchEvent({
  77428. type : "CursorChange", action : "remove", name:"movePointcloud"
  77429. });
  77430. viewer.dispatchEvent({
  77431. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  77432. });
  77433. this.bus.dispatchEvent({type:'switchHandle' , state });
  77434. },
  77435. save: function(){//保存所有数据集的位置和旋转
  77436. let callback = ()=>{//保存成功后
  77437. this.originData = this.getTemp(); //this.saveTemp();
  77438. //需要修改 测量线的position。漫游点已经实时修改了
  77439. viewer.scene.measurements.forEach(e=>e.transformByPointcloud());
  77440. viewer.images360.updateCube(viewer.bound);
  77441. };
  77442. var data = viewer.scene.pointclouds.map(e=>{
  77443. let pos = viewer.transform.lonlatToLocal.inverse(e.translateUser.clone());
  77444. return {
  77445. id: e.dataset_id,
  77446. orientation : e.orientationUser,
  77447. location:[pos.x, pos.y, pos.z],
  77448. //transformMatrix: e.transformMatrix.elements,
  77449. }
  77450. });
  77451. //data = JSON.stringify(data)
  77452. //test: 退出后保留结果
  77453. if(!Potree.settings.isOfficial){
  77454. callback();
  77455. }
  77456. return {data, callback}
  77457. }
  77458. };
  77459. Alignment.history = new History({
  77460. callback: (data)=>{
  77461. data.forEach(item=>{
  77462. Alignment.applyTemp(item);
  77463. });
  77464. }
  77465. });
  77466. let texLoader$7 = new TextureLoader();
  77467. let markerMats$2;
  77468. let markerSizeInfo$2 = {width2d:35};
  77469. let color$2 = new Color('#FFF');
  77470. let faceMats;
  77471. let getFaceMat = (name)=>{
  77472. if(!faceMats){ //navvis材质可以搜gridTexture
  77473. let gridTex = texLoader$7.load( Potree.resourcePath+'/textures/gridmap.png' );
  77474. gridTex.wrapS = gridTex.wrapT = RepeatWrapping;
  77475. //gridTex.repeat.set(0.5,0.5)//放大一些
  77476. faceMats = {
  77477. dataset: new MeshStandardMaterial({
  77478. color:812922,
  77479. side:DoubleSide,
  77480. opacity:0.2,
  77481. transparent:true,
  77482. depthTest:false,
  77483. wireframe:true
  77484. }),
  77485. building: new MeshStandardMaterial({
  77486. color:812922, metalness: 0.2, roughness:0.8,
  77487. side:DoubleSide,
  77488. opacity:0.1,
  77489. transparent:true,
  77490. depthTest:true
  77491. }),
  77492. buildingSelect: new MeshStandardMaterial({
  77493. color:36582, metalness: 0, roughness:1,
  77494. side:DoubleSide,
  77495. opacity:0.1,
  77496. transparent:true,
  77497. depthTest:true
  77498. }),
  77499. floor: new MeshStandardMaterial({
  77500. color:11708469, metalness: 0.1, roughness:1,
  77501. side:DoubleSide,//BackSide,
  77502. opacity:0.05,
  77503. transparent:true,
  77504. depthTest:true,
  77505. }),
  77506. /* floorSelect: new THREE.MeshStandardMaterial({
  77507. color:16707151, metalness: 0, roughness:1,
  77508. side:THREE.DoubleSide,
  77509. opacity:1,
  77510. transparent:true,
  77511. depthTest:true,
  77512. polygonOffset : true,//是否开启多边形偏移
  77513. polygonOffsetFactor : -0.75,//多边形偏移因子
  77514. polygonOffsetUnits : -4.0,//多边形偏移单位
  77515. map: gridTex,
  77516. }), */
  77517. floorSelect: new DepthBasicMaterial({
  77518. map: gridTex,
  77519. color:16707151,
  77520. side:DoubleSide,//BackSide,
  77521. opacity:1,
  77522. transparent:true,
  77523. useDepth : true,
  77524. /* polygonOffset : true,//是否开启多边形偏移
  77525. polygonOffsetFactor : -0.75,//多边形偏移因子
  77526. polygonOffsetUnits : -4.0,//多边形偏移单位 */
  77527. clipDistance : 1, occlusionDistance:1, /* occlusionDistance:变为backColor距离, clipDistance:opacity到达0或者1-maxClipFactor时的距离 */
  77528. maxClipFactor:0.4, backColor:'#efe' //backColor:"#669988" ,
  77529. }),
  77530. room: new MeshStandardMaterial({
  77531. color:"#ff44ee", metalness: 0, roughness:1,
  77532. side:DoubleSide,//BackSide,
  77533. opacity:0.08,
  77534. transparent:true,
  77535. depthTest:false,
  77536. }),
  77537. /* roomSelect: new THREE.MeshStandardMaterial({
  77538. color:"#ff44ee", metalness: 0.3, roughness:1,
  77539. side:THREE.DoubleSide,//BackSide,
  77540. opacity:1,
  77541. transparent:true,
  77542. depthTest:true,
  77543. polygonOffset : true,//是否开启多边形偏移.(开启是因为和floor重叠了会闪烁)
  77544. polygonOffsetFactor : -0.75,//多边形偏移因子
  77545. polygonOffsetUnits : -4.0,//多边形偏移单位
  77546. map: gridTex,
  77547. }), */
  77548. roomSelect: new DepthBasicMaterial({
  77549. map: gridTex,
  77550. color:"#ff44ee",
  77551. side:DoubleSide,//BackSide,
  77552. opacity:1,
  77553. transparent:true,
  77554. useDepth : true,
  77555. /* polygonOffset : true,//是否开启多边形偏移
  77556. polygonOffsetFactor : -0.75,//多边形偏移因子
  77557. polygonOffsetUnits : -4.0,//多边形偏移单位 */
  77558. clipDistance : 1, occlusionDistance:0.5, /* occlusionDistance:变为backColor距离, clipDistance:opacity到达0或者1-maxClipFactor时的距离 */
  77559. maxClipFactor:0.6, backColor:'#ff88dd'//"#cc99c2" ,
  77560. })
  77561. };
  77562. }
  77563. return faceMats[name]
  77564. };
  77565. class BuildingBox extends ctrlPolygon{//建筑实体,包括building, floor, room
  77566. constructor(prop) {
  77567. prop.dimension = '3d';
  77568. //prop.name = Potree.config.siteModel.names[prop.buildType] +
  77569. super('siteModel_'+prop.buildType, prop);
  77570. this.midMarkers = [];
  77571. this.buildChildren = [];//子实体
  77572. this.holes = []; //在这创建的hole
  77573. this.parentHoles = [];//floor从building那得到的当层holes
  77574. this.mats = {}; //材质
  77575. this.panos = this.panos || [];
  77576. this.center; //中心点
  77577. if(this.buildType=='floor'){
  77578. this.points = prop.points = this.buildParent.points;//完全等于建筑的点
  77579. this.buildParent.holes.forEach(hole=>{//从building获取holes
  77580. let floorHole = new BuildingBox({
  77581. buildType : 'hole',
  77582. buildParent:this,
  77583. originHole : hole, //整栋大楼在当层的hole
  77584. ifDraw: this.ifDraw || Potree.settings.drawEntityData
  77585. });
  77586. this.parentHoles.push(floorHole);
  77587. this.add(floorHole);
  77588. floorHole.points = hole.points;//完全等于建筑的点
  77589. });
  77590. }
  77591. if(this.buildType == 'room' || this.buildType == 'hole'){
  77592. this.restrictArea = this.buildParent; //不能超出的区域
  77593. }
  77594. if(this.ifDraw){ //只存储空间模型信息,不绘制
  77595. if(this.buildType != 'hole'){
  77596. this.box = this.createBox();
  77597. this.add(this.box);
  77598. }
  77599. {
  77600. this.lineMesh = LineDraw.createLine([],{color: color$2});
  77601. this.lineMesh.name = 'buildingLines';
  77602. this.lineMesh.visible = false;
  77603. this.add(this.lineMesh);
  77604. viewer.setObjectLayers(this.lineMesh, 'bothMapAndScene' );
  77605. }
  77606. this.addEventListener('dragChange',(e)=>{ //修改中点
  77607. this.updateTwoMidMarker(e.index);
  77608. });
  77609. }
  77610. this.initData(prop);
  77611. }
  77612. initData(prop){
  77613. if(prop.ifDraw){
  77614. super.initData(prop);
  77615. }else {
  77616. if(prop.points){
  77617. this.points = prop.points;
  77618. }
  77619. }
  77620. }
  77621. intersectPointcloudVolume(pointcloud){//和pointcloud的重叠体积
  77622. var bound = this.getBound();
  77623. let bound2 = pointcloud.bound;
  77624. if(!bound.intersectsBox(bound2)) return 0;
  77625. let {zMin , zMax} = this.getRealZ();
  77626. let min = Math.min(zMin, bound2.min.z);
  77627. let max = Math.max(zMax, bound2.max.z);
  77628. let height1 = zMax - zMin;
  77629. let height2 = bound2.max.z-bound2.min.z;
  77630. let coverHeight = height1 + height2 - (max-min);//重叠高度 <=0是没重叠
  77631. let boxPoints = pointcloud.getUnrotBoundPoint(); //获取tightBound的四个点。 如果是有旋转角度的点云,这个和pointcloud.bound的四个点是不一致的,覆盖面积小于pointcloud.bound
  77632. let areaWhole = 0;
  77633. let area1 = this.getArea();
  77634. let area2 = Math.abs(math.getArea(boxPoints));
  77635. {//计算points与点云总面积 (但是把hole也加入了面积)(并集,重叠部分只算一次)
  77636. let rings = math.getPolygonsMixedRings([this.points, boxPoints] );
  77637. rings.forEach(e=>{
  77638. areaWhole+=e.area;
  77639. });
  77640. }
  77641. let coverHoleArea = 0; //holes与数据集重叠的部分
  77642. let holes = this.holes.concat(this.parentHoles);
  77643. let holesArea = 0; //所有holes面积相加
  77644. let areaHoleWithPointcloud = 0; //hole和点云的面积并集
  77645. if(holes.length>0){//还要再扣除holes与数据集重叠的部分。其中holes为mix轮廓
  77646. let outHoles = [];//没有重合的holes的外轮廓
  77647. /* if(holes.length>=2){//合并holes。如果能在绘制时直接合并holes就好啦,这步就转移到那去,但是要删除hole好麻烦
  77648. let holes_ = holes.map(e=>e.points)
  77649. outHoles = math.getPolygonsMixedRings(holes_, true )
  77650. outHoles.forEach(e=>{
  77651. holesArea+=e.area
  77652. })
  77653. outHoles = outHoles.map(e=>e.points)
  77654. }else{
  77655. outHoles = holes.map(e=>e.points)
  77656. outHoles.forEach(e=> holesArea += Math.abs(math.getArea(e)))
  77657. } */
  77658. holesArea = this.getHolesArea();
  77659. //holes与数据集重叠的部分
  77660. {
  77661. let polygons = outHoles.concat([boxPoints]);
  77662. let rings = math.getPolygonsMixedRings(polygons);
  77663. rings.forEach(e=>{
  77664. areaHoleWithPointcloud+=e.area;
  77665. });
  77666. coverHoleArea = holesArea + area2 - areaHoleWithPointcloud;//hole和点云的交集
  77667. }
  77668. }
  77669. let coverArea = area1 + area2 - areaWhole - coverHoleArea; //重叠面积
  77670. return coverArea * coverHeight
  77671. }
  77672. addHole(points=[]){
  77673. let prop = {
  77674. buildType : 'hole',
  77675. zMin : this.zMin,
  77676. zMax : this.zMax,
  77677. points,
  77678. buildParent:this,
  77679. ifDraw: this.ifDraw || Potree.settings.drawEntityData
  77680. };
  77681. //hole的zMin zMax跟随buildParent
  77682. var hole = new BuildingBox(prop);
  77683. this.holes.push(hole);
  77684. if(this.buildType == 'building'){//为每一层添加对应的hole
  77685. this.buildChildren.forEach(floor=>{
  77686. let floorHole = new BuildingBox({
  77687. buildType : 'hole',
  77688. zMin : this.zMin,
  77689. zMax : this.zMax,
  77690. buildParent:floor,
  77691. originHole : hole, //整栋大楼在当层的hole
  77692. ifDraw: this.ifDraw || Potree.settings.drawEntityData
  77693. });
  77694. floor.parentHoles.push(floorHole);
  77695. floor.add(floorHole);
  77696. floorHole.points = hole.points;//完全等于建筑的点
  77697. });
  77698. }
  77699. this.add(hole);//直接加在这,不加meshGroup了
  77700. this.update(); //update box mesh
  77701. return hole
  77702. //hole不创建box,只有它的buildParent需要更新box。 但有线条和marker. hole不在buildChildren里,但有buildParent
  77703. }
  77704. removeHole(hole){// 这个hole不会是parentHoles里的。
  77705. hole.dispose();
  77706. if(this.buildType == 'building'){ //若是整栋大楼的hole,在每层去除它的对应hole
  77707. this.buildChildren.forEach(floor=>{
  77708. let holeAtFloor = floor.parentHoles.find(e=>e.originHole == this );
  77709. let index = floor.parentHoles.indexOf(holeAtFloor);
  77710. index > -1 && floor.parentHoles.splice(index, 1);
  77711. holeAtFloor.dispose();
  77712. });
  77713. }
  77714. let index = this.holes.indexOf(hole);
  77715. if(index>-1){
  77716. this.holes.splice(index, 1);
  77717. }
  77718. this.remove(hole);
  77719. this.update();
  77720. }
  77721. createBox(){
  77722. var geometry = new Geometry();
  77723. this.mats.boxDefault = getFaceMat(this.buildType);
  77724. this.mats.boxSelected = getFaceMat(this.buildType+'Select');
  77725. var mesh = new Mesh(geometry, this.mats.boxDefault);
  77726. mesh.name = 'buildingBox';
  77727. if(this.buildType == 'floor'){
  77728. viewer.setObjectLayers(mesh, 'siteModelMapUnvisi' ); //楼层默认在地图不显示,为了不会叠加透明度
  77729. }else {
  77730. viewer.setObjectLayers(mesh, 'bothMapAndScene' );
  77731. }
  77732. //mesh.frustumCulled = false;
  77733. return mesh
  77734. }
  77735. addMarker(o={} ){
  77736. if(this.buildType=='floor')return; //楼层不需要marker
  77737. let marker = new Sprite$1({mat:this.getMarkerMaterial('default'), renderOrder : 3, sizeInfo: markerSizeInfo$2, dontFixOrient: true, name:"building_marker"} );
  77738. viewer.setObjectLayers(marker, 'siteModeOnlyMapVisi' );
  77739. o.marker = marker;
  77740. super.addMarker(o);
  77741. if(!this.selected)viewer.updateVisible(marker,'select',false);
  77742. let addClickEvent = (e)=>{
  77743. let click = (e) => {
  77744. this.dispatchEvent({type:'clickMarker', marker } ); //由entity发送给sitemodel统一处理
  77745. };
  77746. marker.addEventListener('click', click);
  77747. marker.addEventListener('clickSelect', (e)=>{
  77748. this.setMarkerSelected(marker, e.state ? 'select' : 'unselect' );
  77749. });
  77750. marker.removeEventListener('addHoverEvent',addClickEvent);
  77751. };
  77752. marker.addEventListener('addHoverEvent',addClickEvent);//当非isNew时才添加事件
  77753. if(!this.isNew){
  77754. marker.dispatchEvent('addHoverEvent');
  77755. }
  77756. return marker
  77757. }
  77758. removeMarker(index){
  77759. super.removeMarker(index);
  77760. if(!this.isNew){
  77761. //重新添加midMarkers
  77762. this.midMarkers.forEach(e=>this.remove(e));
  77763. this.midMarkers = [];
  77764. this.addMidMarkers();
  77765. }
  77766. this.update();
  77767. if(this.points.length == 2 && this.box){//清除原先length>=3时候的
  77768. this.box.geometry = new Geometry();
  77769. }
  77770. }
  77771. addMidMarker(index, point){
  77772. if(this.buildType=='floor')return; //楼层不需要marker
  77773. let marker = new Sprite$1({mat:this.getMarkerMaterial('midPrepare'), sizeInfo: markerSizeInfo$2, dontFixOrient: true, name:"building_midMarker"} );
  77774. this.midMarkers = [...this.midMarkers.slice(0,index), marker, ...this.midMarkers.slice(index,this.midMarkers.length)];
  77775. marker.renderOrder = 3;
  77776. viewer.setObjectLayers(marker, 'siteModeOnlyMapVisi' );
  77777. { // Event Listeners
  77778. let mouseover = (e) => {
  77779. this.setMarkerSelected(e.object, 'hover', 'single');
  77780. viewer.dispatchEvent({
  77781. type : "CursorChange", action : "add", name:"markerMove"
  77782. });
  77783. };
  77784. let mouseleave = (e) => {
  77785. this.setMarkerSelected(e.object, 'unhover', 'single');
  77786. viewer.dispatchEvent({
  77787. type : "CursorChange", action : "remove", name:"markerMove"
  77788. });
  77789. };
  77790. let drag = (e) => {
  77791. let index = this.midMarkers.indexOf(marker);
  77792. let newMarker = this.addMarker({index:(index+1), point:marker.position.clone() });
  77793. this.addMidMarker(index+1, new Vector3 );
  77794. this.updateTwoMidMarker(index+1);
  77795. this.setMarkerSelected(marker, 'unhover');
  77796. viewer.inputHandler.startDragging(newMarker , {/* dragViewport:viewer.mapViewer.viewports[0], */ } ); //notPressMouse代表不是通过按下鼠标来拖拽. dragViewport指定了只能在地图上拖拽
  77797. };
  77798. marker.addEventListener('drag', drag );
  77799. //marker.addEventListener('drop', drop);
  77800. marker.addEventListener('mouseover', mouseover);
  77801. marker.addEventListener('mouseleave', mouseleave);
  77802. }
  77803. this.add(marker);
  77804. this.updateMarker(marker, point);
  77805. if(!this.selected)viewer.updateVisible(marker,'select',false);
  77806. return marker
  77807. }
  77808. addMidMarkers(){//第一次画好所有marker后,一次性为线段增加中点marker
  77809. let length = this.points.length;
  77810. this.points.forEach((point,index)=>{
  77811. let nextPoint = this.points[(index+1)%length];
  77812. let midPoint = new Vector3().addVectors(point, nextPoint).multiplyScalar(0.5);
  77813. this.addMidMarker(index, midPoint );
  77814. });
  77815. }
  77816. updateTwoMidMarker(index){//更新第index个marker两边的midMarker
  77817. if(!this.midMarkers.length)return
  77818. let length = this.points.length;
  77819. let last = this.points[(index-1+length)%length]; //它之前的marker位置
  77820. let next = this.points[(index+1)%length];//它之后的marker位置
  77821. let current = this.points[index];//当前位置
  77822. let lastMid = new Vector3().addVectors(last, current).multiplyScalar(0.5);//上一个中点
  77823. let nextMid = new Vector3().addVectors(next, current).multiplyScalar(0.5);//下一个中点
  77824. let lastMidMarker = this.midMarkers[(index-1+length)%length];
  77825. let nextMidMarker = this.midMarkers[index];
  77826. this.updateMarker(lastMidMarker, lastMid);
  77827. this.updateMarker(nextMidMarker, nextMid);
  77828. }
  77829. dispose(){//销毁geo、remove from parent
  77830. super.dispose();
  77831. this.box && this.box.geometry.dispose();
  77832. this.lineMesh && this.lineMesh.geometry.dispose();
  77833. this.holes.forEach(e=>e.dispose());
  77834. this.parentHoles.forEach(e=>e.dispose());
  77835. //this.buildChildren.forEach(e=>e.dispose())
  77836. this.dispatchEvent('dispose');
  77837. }
  77838. updateBox(){
  77839. if(!this.box)return
  77840. this.box.geometry.dispose();
  77841. var shrink = this.buildType == 'room' ? 0.11 : this.buildType == 'floor' ? 0.082 : 0.2 ;//防止mesh重叠冲突(给一个不寻常的数字) 但离远了还是会有点闪烁
  77842. if(this.points.length >= 3){
  77843. let holes = this.holes.concat(this.parentHoles);
  77844. let holesPoints = holes.filter(e=>e.points.length>2).map(e=>e.points);
  77845. this.box.geometry = MeshDraw.getExtrudeGeo(this.points, holesPoints, {
  77846. depth:this.zMax-this.zMin-shrink,
  77847. UVGenerator: new MetricUVGenerator()
  77848. });
  77849. if(this.buildType == 'building' ){
  77850. this.box.position.z = this.zMin - shrink / 2;
  77851. }else {
  77852. this.box.position.z = this.zMin + shrink / 2;
  77853. }
  77854. }
  77855. }
  77856. update(options={}){
  77857. super.update(this.buildType != 'floor' && options.ifUpdateMarkers);
  77858. let length = this.points.length;
  77859. {//确保一下一样
  77860. if(this.originHole){
  77861. this.points = this.originHole.points; //完全等于building的hole
  77862. }
  77863. if(this.buildType == 'hole'){
  77864. this.zMin = this.buildParent.zMin;
  77865. this.zMax = this.buildParent.zMax;
  77866. }
  77867. }
  77868. if(!options.dontUpdateBox){
  77869. let boxOwner;
  77870. if(this.buildType == 'hole'){
  77871. if(this.buildParent.buildType == 'building'){ //若是整栋大楼的hole,在每层都要更新下它的对应hole
  77872. this.buildParent.buildChildren.forEach(floor=>{
  77873. let holeAtFloor = floor.parentHoles.find(e=>e.originHole == this );
  77874. holeAtFloor && holeAtFloor.update(); //刚开始创建时还没创建对应的 holeAtFloor会为null
  77875. });
  77876. }
  77877. boxOwner = this.buildParent;
  77878. }else {
  77879. boxOwner = this;
  77880. }
  77881. boxOwner.updateBox();
  77882. }
  77883. {//update lines
  77884. let positions = [];
  77885. this.points.forEach((point, index)=>{
  77886. //竖线:
  77887. positions.push(point.clone().setZ(this.zMin), point.clone().setZ(this.zMax));
  77888. //横线
  77889. let nextPoint = this.points[(index+1)%length];
  77890. if(!nextPoint)return;//when length==1
  77891. positions.push(point.clone().setZ(this.zMax), nextPoint.clone().setZ(this.zMax));//上横线
  77892. positions.push(point.clone().setZ(this.zMin), nextPoint.clone().setZ(this.zMin));//下横线
  77893. });
  77894. LineDraw.moveLine(this.lineMesh,positions);
  77895. }
  77896. if(!options.dontUpdateChildren){
  77897. if(this.buildType == 'building' ){
  77898. this.buildChildren.forEach(floor=>{
  77899. floor.points = this.points;
  77900. floor.update();
  77901. });
  77902. }
  77903. {
  77904. let holes = this.holes.concat(this.parentHoles);
  77905. holes.forEach(hole=> {
  77906. hole.update({dontUpdateBox:true});//父级更新了box,hole就不需要更新box了
  77907. });
  77908. }
  77909. }
  77910. }
  77911. getHolesArea(){
  77912. let holes = this.holes.concat(this.parentHoles);
  77913. let outHoles, holesArea = 0;
  77914. if(holes.length>=2){//合并holes。如果能在绘制时直接合并holes就好啦,这步就转移到那去,但是要删除hole好麻烦
  77915. let holes_ = holes.map(e=>e.points);
  77916. outHoles = math.getPolygonsMixedRings(holes_, true );
  77917. outHoles.forEach(e=>{
  77918. holesArea+=e.area;
  77919. });
  77920. outHoles = outHoles.map(e=>e.points);
  77921. }else {
  77922. outHoles = holes.map(e=>e.points);
  77923. outHoles.forEach(e=> holesArea += Math.abs(math.getArea(e)));
  77924. }
  77925. return holesArea
  77926. }
  77927. getArea(ifRidOfHoles){//面积
  77928. //不排除hole
  77929. return Math.abs(math.getArea(this.points)) - (ifRidOfHoles ? this.getHolesArea() : 0)
  77930. }
  77931. getVolume(ifRidOfHoles){//体积
  77932. let {zMin , zMax} = this.getRealZ();
  77933. let height = zMax - zMin;
  77934. if(isNaN(height))height = 0;
  77935. return this.getArea(ifRidOfHoles) * height
  77936. }
  77937. getRealZ(){//求真实高度时用到的
  77938. let zMin , zMax;
  77939. if (this.buildType == 'building') {
  77940. //building的zMax和zMin一样的所以要算
  77941. let top = this.buildChildren[this.buildChildren.length - 1];
  77942. let btm = this.buildChildren[0];
  77943. zMin = btm ? btm.zMin : 0; //建好的建筑不加楼的话是0
  77944. zMax = top ? top.zMax : 0;
  77945. }else if(this.buildType == 'hole'){
  77946. return this.buildParent.getRealZ()
  77947. }else {
  77948. zMin = this.zMin, zMax = this.zMax;
  77949. }
  77950. return {zMin,zMax}
  77951. }
  77952. /* getDrawZ(){ //画线和box时用到的z
  77953. let zMin , zMax
  77954. if(this.buildType == 'hole'){
  77955. if(this.buildParent.buildType == 'building' && atFloor){
  77956. zMin = atFloor.zMin, zMax = atFloor.zMax
  77957. }else{
  77958. zMin = this.buildParent.zMin, zMax = this.buildParent.zMax
  77959. }
  77960. }else{
  77961. zMin = this.zMin, zMax = this.zMax
  77962. }
  77963. return {zMin, zMax}
  77964. } */
  77965. getBound(){
  77966. let bound = new Box3;
  77967. let {zMin , zMax} = this.getRealZ();
  77968. let points = this.buildType == 'floor' ? this.buildParent.points : this.points;
  77969. points.forEach(p=>{
  77970. bound.expandByPoint(p.clone().setZ(zMin));
  77971. bound.expandByPoint(p.clone().setZ(zMax));
  77972. });
  77973. return bound
  77974. }
  77975. getMarkerMaterial(type) {
  77976. if(!markerMats$2){
  77977. markerMats$2 = {
  77978. default: new MeshBasicMaterial({
  77979. transparent: !0,
  77980. color: color$2,
  77981. opacity: 0.8,
  77982. map: texLoader$7.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  77983. depthTest:false,
  77984. }),
  77985. midPrepare: new MeshBasicMaterial({ //线中心的半透明点
  77986. transparent: !0,
  77987. color: color$2,
  77988. opacity: 0.4,
  77989. map: texLoader$7.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  77990. depthTest:false,
  77991. }),
  77992. hover: new MeshBasicMaterial({
  77993. transparent: !0,
  77994. color: color$2,
  77995. opacity: 1,
  77996. map: texLoader$7.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  77997. depthTest:false,
  77998. }),
  77999. select: new MeshBasicMaterial({
  78000. transparent: !0,
  78001. color:new Color('#00C8AF'),
  78002. opacity: 1,
  78003. map: texLoader$7.load(Potree.resourcePath+'/textures/whiteCircle.png' ),
  78004. depthTest:false,
  78005. }),
  78006. };
  78007. }
  78008. return markerMats$2[type]
  78009. }
  78010. setMarkerSelected(marker, state, hoverObject){
  78011. //console.warn(marker.id , state, hoverObject)
  78012. if(state == 'select'){
  78013. marker.selected = true;
  78014. marker.material = this.getMarkerMaterial('select');
  78015. }else if(state == 'unselect'){
  78016. marker.selected = false;
  78017. marker.material = this.getMarkerMaterial('default');
  78018. }else {
  78019. if(marker.selected)return //选中时不允许修改为除了'unselect'以外的状态
  78020. if(state == 'hover'){
  78021. marker.material = this.getMarkerMaterial('hover');
  78022. }else if(state == 'unhover'){
  78023. if(marker.name.includes('mid')){
  78024. marker.material = this.getMarkerMaterial('midPrepare');
  78025. }else {
  78026. marker.material = this.getMarkerMaterial('default');
  78027. }
  78028. }
  78029. }
  78030. }
  78031. select(){
  78032. //最多再显示一层子级的线,如building不会显示room中的hole的线
  78033. //box是一直显示的,但会切换材质
  78034. /*
  78035. 选中 box 线
  78036. building 自己(底盘)选中 自己, floor不带hole
  78037. floor 自己选中 自己, room不带hole
  78038. room 自己选中 自己
  78039. */ //注:自己的就代表定包括hole,如果有parentHoles的也(building上的hole的对应)
  78040. //console.log('select '+this.name, this.selected)
  78041. if(this.selected)return
  78042. if(this.box){
  78043. this.box.material = this.mats.boxSelected;
  78044. }
  78045. if(this.buildType == 'building'|| this.buildType == 'floor'){
  78046. this.buildChildren.forEach(e=>{
  78047. e.lineMesh.visible = true;
  78048. });
  78049. if(this.buildType == 'floor'){
  78050. viewer.setObjectLayers(this.box, 'bothMapAndScene' );
  78051. viewer.setObjectLayers(this.buildParent.box, 'siteModelMapUnvisi' ); //当选中floor或room时,building在地图不可见
  78052. }
  78053. }else if(this.buildType == 'room'){
  78054. viewer.setObjectLayers(this.buildParent.box, 'bothMapAndScene' );
  78055. viewer.setObjectLayers(this.buildParent.buildParent.box, 'siteModelMapUnvisi' );
  78056. }
  78057. this.lineMesh.visible = true;
  78058. this.markers && this.markers.forEach(e=>viewer.updateVisible(e,'select',true) );
  78059. this.midMarkers && this.midMarkers.forEach(e=>e.visible = true);
  78060. let holes = this.holes.concat(this.parentHoles);
  78061. holes.forEach(e=>e.select());
  78062. this.selected = true;
  78063. this.dispatchEvent({type:'select'});
  78064. }
  78065. unselect(){
  78066. if(!this.selected)return
  78067. //console.log('unselect '+this.name )
  78068. if(this.box){
  78069. this.box.material = this.mats.boxDefault;
  78070. }
  78071. if(this.buildType == 'building' || this.buildType == 'floor'){
  78072. this.buildChildren.forEach(e=>{ //(这里要保证选中前要先取消选中,否则如选中房间后取消了楼层,房间线就隐藏了)
  78073. e.lineMesh.visible = false;
  78074. });
  78075. if(this.buildType == 'floor'){
  78076. viewer.setObjectLayers(this.box, 'siteModelMapUnvisi' );
  78077. viewer.setObjectLayers(this.buildParent.box, 'bothMapAndScene' );
  78078. }
  78079. }else if(this.buildType == 'room'){
  78080. viewer.setObjectLayers(this.buildParent.box, 'siteModelMapUnvisi' );
  78081. viewer.setObjectLayers(this.buildParent.buildParent.box, 'bothMapAndScene' );
  78082. }
  78083. this.lineMesh.visible = false;
  78084. this.markers && this.markers.forEach(e=>viewer.updateVisible(e,'select',false) );
  78085. this.midMarkers && this.midMarkers.forEach(e=>e.visible = false);
  78086. let holes = this.holes.concat(this.parentHoles);
  78087. holes.forEach(e=>e.unselect());
  78088. this.selected = false;
  78089. this.dispatchEvent({type:'unselect'});
  78090. }
  78091. ifContainsPoint(position){//看它所定义的空间是否包含某个坐标(要排除hole)
  78092. let {zMin , zMax} = this.getRealZ();
  78093. if(position.z < zMin || position.z > zMax ) return
  78094. let holes = this.holes.concat(this.parentHoles);
  78095. let holesPoints = holes.filter(e=>e!=this && e.points.length>2).map(e=>e.points);
  78096. let inShape = math.isPointInArea(this.points, holesPoints, position);
  78097. return !!inShape
  78098. }
  78099. }
  78100. class MetricUVGenerator{
  78101. constructor(){
  78102. this.a = new Vector3,
  78103. this.b = new Vector3,
  78104. this.c = new Vector3,
  78105. this.d = new Vector3;
  78106. }
  78107. generateTopUV(t, e, n, r, o) {
  78108. 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])]
  78109. }
  78110. generateSideWallUV(t, e, n, r, o, a) {
  78111. var s = e;
  78112. this.a.set(s[3 * n], s[3 * n + 1], s[3 * n + 2]),
  78113. this.b.set(s[3 * r], s[3 * r + 1], s[3 * r + 2]),
  78114. this.c.set(s[3 * o], s[3 * o + 1], s[3 * o + 2]),
  78115. this.d.set(s[3 * a], s[3 * a + 1], s[3 * a + 2]);
  78116. var c = this.a.x !== this.b.x
  78117. , l = c ? this.b : this.d
  78118. , u = this.a.distanceTo(l)
  78119. , d = l.distanceTo(this.c);
  78120. 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)]
  78121. }
  78122. }
  78123. const minFloorHeight = 0.5;
  78124. const ifDrawDatasetBound = true; //显示一下数据集的tightBound线框
  78125. const minMarkers = 3;
  78126. const Limit = {zMin:-config$1.map.cameraHeight, zMax:config$1.map.cameraHeight,}; //不能超过camera的高度,为了对称所以也限制了最低
  78127. var SiteModel = {
  78128. bus: new EventDispatcher(),
  78129. entities:[], //所有实体
  78130. buildings:[], //所有建筑父集
  78131. meshGroup: new Object3D,
  78132. inEntity : null,
  78133. lastPos: new Vector3(Infinity,Infinity,Infinity),
  78134. init: function(){
  78135. viewer.scene.scene.add(this.meshGroup);
  78136. this.meshGroup.name = 'siteModel';
  78137. this.SplitScreen = SplitScreen4Views;
  78138. if(Potree.settings.editType == 'pano'){
  78139. return
  78140. }
  78141. this.createHeightPull();
  78142. if(Potree.settings.isTest && ifDrawDatasetBound){
  78143. viewer.addEventListener('allLoaded',()=>{
  78144. viewer.scene.pointclouds.forEach(pointcloud=>{
  78145. let boxPoints = pointcloud.getUnrotBoundPoint();
  78146. let boundingBox = new BuildingBox({
  78147. name: '数据集tightBound_'+pointcloud.dataset_id,
  78148. points: boxPoints,
  78149. buildType : 'dataset',
  78150. zMax: pointcloud.bound.max.z,
  78151. zMin: pointcloud.bound.min.z,
  78152. ifDraw:true
  78153. });
  78154. this.meshGroup.add(boundingBox);
  78155. //boundingBox.markers.forEach(e=>e.visible = false)
  78156. });
  78157. });
  78158. }
  78159. if(Potree.settings.isOfficial){
  78160. viewer.addEventListener('camera_changed', e => {
  78161. if(e.changeInfo.positionChanged){
  78162. this.updateEntityAt();
  78163. }
  78164. });
  78165. }
  78166. {
  78167. let pressDelete = (e)=>{
  78168. if(e.keyCode == KeyCodes.BACKSPACE || e.keyCode == KeyCodes.DELETE){
  78169. if(this.selectedMarker){
  78170. let entity = this.selectedMarker.parent;
  78171. let index = entity.markers.indexOf(this.selectedMarker);
  78172. entity.removeMarker(index);
  78173. if(entity.points.length<2){//删到只剩一个点时重新画(如果是hole的点,直接删除hole吧?)
  78174. this.startInsertion('resume',entity);
  78175. }
  78176. }
  78177. }
  78178. };
  78179. viewer.inputHandler.addEventListener('keydown', pressDelete);
  78180. }
  78181. },
  78182. updateEntityAt(force){
  78183. //if(!this.entities.length || this.editing) return //编辑时也要根据位置显示不同楼层的漫游点与cad
  78184. let fun = ()=>{ //延时update,防止卡顿
  78185. let currPos = viewer.mainViewport.view.position;
  78186. //if(force || !currPos.equals(this.lastPos) ){
  78187. //console.log('currPos ', currPos.toArray())
  78188. this.lastPos.copy(currPos);
  78189. let entity;
  78190. let searchPos = Potree.settings.displayMode == 'showPanos' ? viewer.images360.currentPano : currPos;
  78191. entity = this.pointInWhichEntity(searchPos, 'room');
  78192. if(force || this.inEntity != entity ){
  78193. let oldEntity = this.inEntity;
  78194. this.inEntity = entity;
  78195. //console.log('buildingChange', entity)
  78196. this.bus.dispatchEvent({type:'buildingChange',entity});
  78197. //this.updatePanosVisible(oldEntity, this.inEntity)
  78198. let lastFloor = this.currentFloor; //oldEntity ? oldEntity.buildType == 'floor' ? oldEntity : oldEntity.buildType == 'room' ? oldEntity.buildParent : null : null; //基本只会是floor或room
  78199. let currentFloor = entity ? entity.buildType == 'floor' ? entity : entity.buildType == 'room' ? entity.buildParent : null : null; //基本只会是floor或room
  78200. if(force || currentFloor != lastFloor){
  78201. //console.log('改变了floor',lastFloor,currentFloor)
  78202. this.currentFloor = currentFloor;
  78203. this.bus.dispatchEvent({type:'FloorChange',currentFloor});
  78204. }
  78205. }
  78206. force = false;
  78207. return true
  78208. //}
  78209. };
  78210. if(force)fun();
  78211. else Common.intervalTool.isWaiting('sitemodelCameraInterval', fun , 500);
  78212. },
  78213. enter:function(){
  78214. Potree.Log('sitemodel enter');
  78215. this.clear(); //确保全部清空
  78216. this.editing = true;
  78217. //this.updatePanosVisible(null, null, true)//show all
  78218. viewer.updateFpVisiDatasets();
  78219. let mapViewport = viewer.mapViewer.viewports[0];
  78220. this.SplitScreen.split({siteModel:true/* , viewports:[{name:'Top',viewport : mapViewport }] */});
  78221. viewer.viewports.forEach(e=>{
  78222. if(e.name != 'mapViewport'){
  78223. e.layersAdd('siteModelMapUnvisi');
  78224. }
  78225. if(e.name == 'right' || e.name == 'back'){
  78226. e.layersAdd('siteModeSideVisi');
  78227. }
  78228. });
  78229. viewer.images360.panos.forEach(pano=>{
  78230. viewer.setObjectLayers(pano.marker, 'siteModelMapUnvisi' );
  78231. });
  78232. mapViewport.layersAdd('siteModeOnlyMapVisi'); //只有mapViewport能看到marker
  78233. },
  78234. leave:function(){
  78235. Potree.Log('sitemodel leave');
  78236. let mapViewport = viewer.mapViewer.viewports[0];
  78237. this.SplitScreen.recover();
  78238. viewer.viewports.forEach(e=>{
  78239. if(e.name != 'mapViewport'){
  78240. e.layersRemove('siteModelMapUnvisi');
  78241. }
  78242. if(e.name == 'right' || e.name == 'back'){
  78243. e.layersRemove('siteModeSideVisi');
  78244. }
  78245. });
  78246. viewer.images360.panos.forEach(pano=>{
  78247. viewer.setObjectLayers(pano.marker, 'sceneObjects' );
  78248. });
  78249. mapViewport.layersRemove('siteModeOnlyMapVisi');
  78250. this.clear();
  78251. this.editing = false;
  78252. this.updateEntityAt(true);
  78253. viewer.updateFpVisiDatasets();
  78254. } ,
  78255. addFloor:function(parent, dirType, sid, name){//dirType:'top'|'bottom'在上方建还是下方。如果建筑中没有楼层,默认在基底建一个
  78256. let buildType = 'floor';
  78257. let zMin, zMax;
  78258. if(parent.buildChildren.length == 0){
  78259. zMin = parent.zMin;
  78260. zMax = zMin + Potree.config.siteModel.floorHeightDefault;
  78261. }else {
  78262. if(dirType == 'bottom'){
  78263. //var btm = Common.find(parent.buildChildren,null,[e=>e.zMin])
  78264. var btm = parent.buildChildren[0];
  78265. zMax = btm.zMin;
  78266. zMin = zMax - Potree.config.siteModel.floorHeightDefault;
  78267. }else {
  78268. //var top = Common.find(parent.buildChildren,null,[e=>e.zMax])
  78269. var top = parent.buildChildren[parent.buildChildren.length - 1];
  78270. zMin = top.zMax;
  78271. zMax = zMin + Potree.config.siteModel.floorHeightDefault;
  78272. }
  78273. }
  78274. let prop = {
  78275. buildType,
  78276. //name : Potree.config.siteModel.names[buildType],
  78277. zMin,
  78278. zMax,
  78279. buildParent:parent,
  78280. sid, name,
  78281. ifDraw:true
  78282. };
  78283. var floor = new BuildingBox(prop);
  78284. /* parent.buildChildren.push(floor)
  78285. this.meshGroup.add(floor);
  78286. this.entities.push(floor) */
  78287. floor.update();
  78288. this.addEntity(floor,parent);
  78289. //this.selectEntity(floor)
  78290. if(this.selected == parent){//重新选择下,为了显示新楼层线框
  78291. parent.unselect();
  78292. parent.select();
  78293. }
  78294. return floor
  78295. },
  78296. startInsertion:function(buildType, parent, sid, name, callback, cancelFun){
  78297. let zMin, zMax, entity, resume;
  78298. let mapViewport = viewer.mapViewer.viewports[0];
  78299. if(buildType == 'resume'){//继续画(使用最后一个点或者新加的点)
  78300. resume = true;
  78301. entity = parent;
  78302. buildType = parent.buildType;
  78303. //删除原先所有的点,因为它们已经添加了事件,会很麻烦:
  78304. entity.reDraw(0);
  78305. entity.isNew = true; //当作新的来画
  78306. }
  78307. if(!resume){
  78308. if(buildType == 'hole' || buildType == 'room'){
  78309. zMin = parent.zMin;
  78310. zMax = parent.zMax;
  78311. }else if(buildType == 'building'){
  78312. parent = null;
  78313. zMin = viewer.bound.boundingBox.min.z;
  78314. zMax = viewer.bound.boundingBox.min.z;
  78315. }
  78316. if(buildType == 'hole'){
  78317. entity = parent.addHole();
  78318. entity.isNew = true;
  78319. this.selectEntity(parent);
  78320. entity.select();
  78321. console.log('挖洞 ',entity.uuid);
  78322. }else {
  78323. let prop = {
  78324. buildType,
  78325. //name : Potree.config.siteModel.names[buildType],//'building',
  78326. zMin,
  78327. zMax,
  78328. buildParent:parent,
  78329. sid, name,
  78330. ifDraw:true
  78331. };
  78332. entity = new BuildingBox(prop);
  78333. entity.isNew = true;
  78334. this.selectEntity(entity);
  78335. }
  78336. this.addEntity(entity, parent);
  78337. }
  78338. let timer;
  78339. let endDragFun = (e) => {
  78340. if (e.button == MOUSE.LEFT ) {
  78341. var marker = entity.addMarker({point:entity.points[entity.points.length - 1].clone()});
  78342. //entity.editStateChange(true) //重新激活reticule状态
  78343. entity.continueDrag(marker, e);
  78344. } else if (e.button === MOUSE.RIGHT ) {
  78345. if(e.pressDistance < Potree.config.clickMaxDragDis )end(e);//非拖拽的话
  78346. else entity.continueDrag(null, e/* .drag.object */);
  78347. }
  78348. };
  78349. let finish = ()=>{//结束绘画
  78350. viewer.removeEventListener('cancel_insertions', Exit);
  78351. entity.removeEventListener('unselect', Exit);
  78352. clearTimeout(timer);
  78353. entity.editStateChange(false);
  78354. //pressExit && viewer.inputHandler.removeEventListener('keydown', pressExit);
  78355. callback && callback(entity);
  78356. };
  78357. let end = (e={}) => {//尝试结束
  78358. /* 退出的三种形式:
  78359. 1 普通:如果大于三个marker,结束且保留;否则重新画。()
  78360. 2 删除:直接结束且删除。(remove)
  78361. 3 结束:如果大于三个marker,结束且保留;否则结束且删除。 (finish)
  78362. 4 保留:无论几个marker,都保留着,结束。(remain)
  78363. */
  78364. if(e.remove){
  78365. finish();
  78366. return this.removeEntity(entity)
  78367. }
  78368. if(!e.remain && !e.finish && !e.remove && entity.markers.length<=minMarkers){//右键 当个数不够时取消
  78369. //重新开始画
  78370. entity.reDraw(1);
  78371. viewer.updateVisible(entity.markers[0],'unMove',false);
  78372. var f = ()=>{
  78373. viewer.updateVisible(entity.markers[0],'unMove',true);
  78374. entity.removeEventListener('dragChange',f);
  78375. };
  78376. entity.addEventListener('dragChange',f);
  78377. //console.log('waitcontinue')
  78378. entity.continueDrag(entity.markers[0], e);
  78379. return
  78380. }
  78381. finish();
  78382. if (e.remain || !e.remove && entity.markers.length > 3) {//保留
  78383. entity.removeMarker(entity.points.length - 1);
  78384. entity.markers.forEach(marker=>{marker.dispatchEvent('addHoverEvent'); });
  78385. if(buildType == 'room'){
  78386. this.fitPullBox();
  78387. }
  78388. entity.isNew = false;
  78389. entity.addMidMarkers();
  78390. }else {
  78391. this.removeEntity(entity); //直接删除没画好的,比较简单。这样就不用担心旧的continueDrag仍旧触发了
  78392. }
  78393. return entity
  78394. };
  78395. let Exit = (e)=>{ //强制结束
  78396. entity.removeEventListener('unselect', Exit);
  78397. if(viewer.inputHandler.drag){//还未触发drop的话
  78398. viewer.inputHandler.drag.object.dispatchEvent({
  78399. type: 'drop',
  78400. drag: viewer.inputHandler.drag,
  78401. viewer: viewer,
  78402. pressDistance:0,
  78403. button : MOUSE.RIGHT
  78404. });
  78405. viewer.inputHandler.drag = null;
  78406. }else {
  78407. end({remain:true});
  78408. }
  78409. viewer.inputHandler.drag = null;
  78410. };
  78411. viewer.dispatchEvent( 'cancel_insertions' );//取消之前的
  78412. viewer.addEventListener('cancel_insertions', Exit);
  78413. entity.addEventListener('unselect', Exit);
  78414. var marker = entity.addMarker({point:new Vector3(0, 0, 0)});
  78415. viewer.updateVisible(marker,'unMove',false);//这时候的位置是假的(0,0,0)所以先不可见
  78416. var f = ()=>{
  78417. viewer.updateVisible(marker,'unMove',true);
  78418. entity.removeEventListener('dragChange',f);
  78419. };
  78420. entity.addEventListener('dragChange',f);
  78421. marker.isDragging = true;
  78422. viewer.inputHandler.startDragging(marker , {dragViewport:mapViewport, endDragFun, notPressMouse:true} ); //notPressMouse代表不是通过按下鼠标来拖拽. dragViewport指定了只能在地图上拖拽
  78423. return entity;
  78424. },
  78425. getPreDealData(points, zMin, zMax, initial, buildType, parent){
  78426. /* if( buildType == 'building' ){
  78427. zMax = zMin //强制变得一样,作为基底。如果有必要,保存时再算真实的zMax。目前zMin没有保存所以数据是错的,会直接根据floor计算
  78428. } */
  78429. var bound = viewer.bound.boundingBox;
  78430. if(buildType == 'building' && initial){//初始数据错的,要自己建(只有一个building和floor) 原posIsLonlat
  78431. console.log('空间模型未编辑过, 初始化了一个');
  78432. points = [
  78433. new Vector3(bound.min.x, bound.min.y,0),
  78434. new Vector3(bound.max.x, bound.min.y,0),
  78435. new Vector3(bound.max.x, bound.max.y,0),
  78436. new Vector3(bound.min.x, bound.max.y,0),
  78437. ];
  78438. zMin = bound.min.z;
  78439. zMax = bound.max.z;
  78440. /* points = points.map(e=>{
  78441. return viewer.transform.lonlatToLocal.forward(e)
  78442. }) */
  78443. }else {//相对于初始数据集的模型内坐标
  78444. points = points.map(e=> this.transform(e, 'fromDataset'));
  78445. if(buildType == 'floor' && initial){
  78446. zMin = bound.min.z;
  78447. zMax = bound.max.z;
  78448. }
  78449. }
  78450. return {points, zMax, zMin }
  78451. },
  78452. resetFromData:function(entity, points=[], holes=[], zMin, zMax ){
  78453. var {points, zMax, zMin} = this.getPreDealData(points, zMin, zMax , this.autoBuild , entity.buildType, entity.buildParent );
  78454. if(entity.buildType != 'floor' )entity.points = points;
  78455. if(entity.buildType == 'room'){
  78456. entity.zMin = zMin;
  78457. entity.zMax = zMax;
  78458. }else if(entity.buildType == 'floor'){//改楼高
  78459. let height = zMax - zMin;
  78460. let zMax2 = entity.zMin + height;
  78461. SiteModel.changeZ(entity, 'zMax', zMax2);
  78462. }
  78463. {
  78464. //删除旧的holes重新添加
  78465. let holesOld = entity.holes;
  78466. holesOld.forEach(e=>{
  78467. entity.removeHole(e);
  78468. });
  78469. holes.forEach(points =>{
  78470. let ps = points.map(e=> this.transform(e, 'fromDataset'));
  78471. let hole = entity.addHole(ps);
  78472. hole.addMidMarkers();
  78473. });
  78474. }
  78475. entity.update();
  78476. return entity
  78477. }
  78478. ,
  78479. createFromData:function( buildType, parent ,sid, name, points=[], holes=[], zMin, zMax, initial,panos_,flagPano){
  78480. if(buildType != 'building' && buildType != 'floor' && buildType != 'room' ) return
  78481. var {points, zMax, zMin} = this.getPreDealData(points, zMin, zMax , initial, buildType, parent );
  78482. let panos = [];
  78483. {
  78484. if(panos_){
  78485. panos_.forEach(sid=>{
  78486. let pano = viewer.images360.getPano(sid,'sid');
  78487. if(pano)panos.push(pano);
  78488. });
  78489. }
  78490. flagPano = flagPano != void 0 ? viewer.images360.getPano(flagPano,'sid') : null ; //最中心的pano 或者 最靠近该实体的pano(当panos为空时)
  78491. if(!this.editing && buildType == 'floor' && !flagPano){//没有的话可能是自动添加的floor,直接用parent的吧
  78492. panos = parent.panos;
  78493. flagPano = parent.flagPano;
  78494. }
  78495. }
  78496. let prop = {
  78497. buildType,
  78498. points,
  78499. name,
  78500. sid,
  78501. zMin,
  78502. zMax,
  78503. buildParent:parent,
  78504. ifDraw:this.editing || Potree.settings.drawEntityData,
  78505. panos, flagPano,
  78506. autoBuild : initial
  78507. };
  78508. let entity = new BuildingBox(prop);
  78509. SiteModel.addEntity(entity, parent );
  78510. if(this.editing){
  78511. if(buildType == 'building'|| buildType == 'room'){
  78512. entity.addMidMarkers();
  78513. }
  78514. }
  78515. holes.forEach(points =>{
  78516. let ps = points.map(e=> this.transform(e, 'fromDataset'));
  78517. let hole = entity.addHole(ps);
  78518. this.editing && hole.addMidMarkers();
  78519. });
  78520. /* if(buildType == 'floor'){
  78521. this.updateBuildingZ(parent)
  78522. } */
  78523. return entity
  78524. },
  78525. transform:function(pos, type){
  78526. if(Potree.settings.editType == 'pano'){ // 模型不经转换
  78527. return new Vector3().copy(pos).setZ(0);
  78528. }
  78529. if(type == 'toDataset'){
  78530. let point = Potree.Utils.datasetPosTransform({ toDataset: true, position: pos.clone(), datasetId: Potree.settings.originDatasetId });
  78531. return new Vector2$1().copy(point)
  78532. }else {
  78533. let position = new Vector3().copy(pos).setZ(0);
  78534. return Potree.Utils.datasetPosTransform({ fromDataset: true, position, datasetId: Potree.settings.originDatasetId })
  78535. }
  78536. },
  78537. addEntity:function(entity, parent){
  78538. this.meshGroup.add(entity);
  78539. this.entities.push(entity);
  78540. if(entity.buildType == 'building'){
  78541. this.buildings.push(entity);
  78542. }else {
  78543. parent.buildChildren.push(entity);
  78544. }
  78545. if(entity.buildType == 'room'){
  78546. entity.addEventListener('marker_dropped',()=>{
  78547. this.fitPullBox();
  78548. });
  78549. }else if(entity.buildType == 'floor'){
  78550. this.updateBuildingZ(parent);
  78551. parent.dispatchEvent({type:'addFloor'});
  78552. }
  78553. {//仅能存在一个marker被选中。选中的点可以被删除
  78554. entity.addEventListener('clickMarker', (e)=>{
  78555. if(this.selectedMarker == e.marker){
  78556. this.selectedMarker.dispatchEvent({type:'clickSelect',state:false});
  78557. this.selectedMarker = null;
  78558. }else {
  78559. if(this.selectedMarker){
  78560. this.selectedMarker.dispatchEvent({type:'clickSelect',state:false});
  78561. }
  78562. this.selectedMarker = e.marker;
  78563. this.selectedMarker.dispatchEvent({type:'clickSelect',state:true});
  78564. }
  78565. });
  78566. entity.addEventListener('removeMarker', (e)=>{
  78567. if(this.selectedMarker == e.marker){
  78568. this.selectedMarker = null;
  78569. }
  78570. });
  78571. let unselect = (e)=>{//取消选中实体或删除后
  78572. if(this.selectedMarker && entity.markers.includes(this.selectedMarker)){
  78573. this.selectedMarker.dispatchEvent({type:'clickSelect',state:false});
  78574. this.selectedMarker = null;
  78575. }
  78576. };
  78577. entity.addEventListener('dispose', unselect);
  78578. entity.addEventListener('unselect', unselect);
  78579. }
  78580. //console.log('添加实体:', entity.buildType, entity.sid, entity.uuid)
  78581. },
  78582. removeEntity : function(entity){
  78583. if(!this.entities.includes(entity))return
  78584. console.log('删除实体:', entity.buildType, entity.sid);
  78585. if(this.selected == entity){
  78586. this.height_pull_box.visible = false;
  78587. this.selectEntity(null);
  78588. }
  78589. if(entity.buildType == 'building'){
  78590. var index = this.buildings.indexOf(entity);
  78591. if(index>-1){
  78592. this.buildings.splice(index,1);
  78593. }
  78594. }else {
  78595. var index = entity.buildParent.buildChildren.indexOf(entity);
  78596. if(index>-1){
  78597. entity.buildParent.buildChildren.splice(index,1);
  78598. }
  78599. }
  78600. var index = this.entities.indexOf(entity);
  78601. if(index>-1){
  78602. this.entities.splice(index,1);
  78603. }
  78604. entity.dispose();
  78605. let buildChildren = entity.buildChildren.slice();
  78606. buildChildren.forEach(e=>this.removeEntity(e));
  78607. },
  78608. updateBuildingZ:function(building){
  78609. building.buildChildren = building.buildChildren.sort((e,a)=>e.zMin-a.zMin);//从低到高排序
  78610. building.zMin = building.zMax = building.buildChildren[0].zMin; //基底高度
  78611. //building.zMax = building.buildChildren[building.buildChildren.length-1].zMax
  78612. if(this.editing) building.update({dontUpdateChildren:true});
  78613. building.dispatchEvent('updateBuildingZ');
  78614. },
  78615. selectEntity : function(entity, state=true){
  78616. if(state === false){
  78617. entity.unselect();
  78618. if(this.selected == entity)this.selected = null;
  78619. return
  78620. }
  78621. if(this.selected == entity || entity && entity.buildType == 'hole')return
  78622. //this.buildings.forEach(e=>e.unselect())
  78623. this.selected && this.selected.unselect();
  78624. this.height_pull_box.visible = false;
  78625. if(entity){
  78626. entity.select();
  78627. }
  78628. this.selected = entity;
  78629. if(entity && (entity.buildType == 'floor' || entity.buildType == 'room' )){
  78630. this.height_pull_box.visible = true;
  78631. this.fitPullBox();
  78632. }
  78633. if(entity && !entity.isNew && (entity.buildType == 'building' || entity.buildType == 'room' ) && entity.points.length<2){
  78634. this.startInsertion('resume',entity); //继续画
  78635. }
  78636. },
  78637. fitPullBox: function(){ //自适应拖拽楼层的pullMesh
  78638. if(!this.selected || this.selected.buildType!= 'floor' && this.selected.buildType!= 'room')return
  78639. let bound = new Box3();
  78640. bound.expandByObject(this.selected.box);
  78641. let center = bound.getCenter(new Vector3() );
  78642. let size = bound.getSize(new Vector3() );
  78643. this.height_pull_box.scale.copy(size);
  78644. this.height_pull_box.position.copy(center);
  78645. },
  78646. changeZ:function(entity, dirType, value){ // floor or room 修改zMin or zMax
  78647. let max, min; //limit
  78648. if(entity.buildType == 'floor'){//楼层
  78649. let index = entity.buildParent.buildChildren.indexOf(entity);
  78650. if(dirType == 'zMax'){
  78651. let upper = entity.buildParent.buildChildren[index+1];
  78652. entity.zMax = Math.min(Limit.zMax, value);
  78653. min = entity.zMin + minFloorHeight;
  78654. if(entity.zMax < min){
  78655. entity.zMax = min;
  78656. }else {
  78657. if(upper){
  78658. max = upper.zMax - minFloorHeight;
  78659. if(entity.zMax > max){
  78660. entity.zMax = max;
  78661. }
  78662. }
  78663. }
  78664. if(upper){
  78665. upper.zMin = entity.zMax;
  78666. upper.update();
  78667. upper.dispatchEvent({type:'changeHeight'});
  78668. }
  78669. }else {
  78670. let lower = entity.buildParent.buildChildren[index-1];
  78671. entity.zMin = Math.max(Limit.zMin, value);
  78672. max = entity.zMax - minFloorHeight;
  78673. if(entity.zMin > max){
  78674. entity.zMin = max;
  78675. }else {
  78676. if(lower){
  78677. min = lower.zMin + minFloorHeight;
  78678. if(entity.zMin < min){
  78679. entity.zMin = min;
  78680. }
  78681. }
  78682. }
  78683. if(lower){
  78684. lower.zMax = entity.zMin;
  78685. lower.update();
  78686. lower.dispatchEvent({type:'changeHeight'});
  78687. }
  78688. if(index == 0)this.updateBuildingZ(entity.buildParent);
  78689. }
  78690. }else if(entity.buildType == 'room'){//房间
  78691. //按照navvis的是不一定限制在当前楼层,只要高度不超过当前楼层即可。
  78692. let maxHeight = entity.buildParent.zMax - entity.buildParent.zMin;
  78693. if(dirType == 'zMax'){
  78694. min = entity.zMin + minFloorHeight;
  78695. max = entity.zMin + maxHeight;
  78696. entity.zMax = MathUtils.clamp(value, min, max);
  78697. }else {
  78698. min = entity.zMax - maxHeight;
  78699. max = entity.zMax - minFloorHeight;
  78700. entity.zMin = MathUtils.clamp(value, min, max);
  78701. }
  78702. }
  78703. entity.update();
  78704. entity.dispatchEvent({type:'changeHeight'});
  78705. //this.selected.emit('update')
  78706. this.fitPullBox();
  78707. },
  78708. createHeightPull:function(){ //拖拽楼层的bounding box
  78709. let boxGeo = new BoxBufferGeometry( 1, 1, 1/4 );
  78710. let boxMat = new MeshBasicMaterial({
  78711. color:"#F00",
  78712. opacity:0,
  78713. transparent:true,
  78714. depthTest:false,
  78715. side:2
  78716. });
  78717. let height_pull_box_up = new Mesh(boxGeo,boxMat);
  78718. let height_pull_box_down = new Mesh(boxGeo,boxMat);
  78719. height_pull_box_up.name = 'height_pull_box_up';
  78720. height_pull_box_down.name = 'height_pull_box_down';
  78721. this.height_pull_box = new Object3D();
  78722. this.height_pull_box.name = 'height_pull_box';
  78723. this.height_pull_box.add(height_pull_box_up);
  78724. this.height_pull_box.add(height_pull_box_down);
  78725. this.height_pull_box.visible = false;
  78726. this.meshGroup.add(this.height_pull_box);
  78727. height_pull_box_up.position.set(0,0,1/2/* 3/8 */);
  78728. height_pull_box_down.position.set(0,0,-1/2/* -3/8 */);
  78729. viewer.setObjectLayers(this.height_pull_box, 'siteModeSideVisi' );
  78730. let mouseover = (e)=>{
  78731. viewer.dispatchEvent({
  78732. type : "CursorChange", action : "add", name:"siteModelFloorDrag"
  78733. });
  78734. };
  78735. let mouseleave = (e)=>{
  78736. viewer.dispatchEvent({
  78737. type : "CursorChange", action : "remove", name:"siteModelFloorDrag"
  78738. });
  78739. };
  78740. let firstZ, firstIntersect;
  78741. let drag = (e)=>{
  78742. var intersect = e.intersect.orthoIntersect; //不要点云的intersect,只要orthocamera算出的平面intersect
  78743. if(firstIntersect != void 0){
  78744. let moveZ = intersect.z - firstIntersect;
  78745. if(this.selected.buildType == 'floor'){//楼层
  78746. //限制高度不能超过上下
  78747. if(e.target == height_pull_box_up){
  78748. if(firstZ == void 0)firstZ = this.selected.zMax;
  78749. this.changeZ(this.selected, 'zMax', firstZ + moveZ);
  78750. }else {
  78751. if(firstZ == void 0)firstZ = this.selected.zMin;
  78752. this.changeZ(this.selected, 'zMin', firstZ + moveZ);
  78753. }
  78754. }else if(this.selected.buildType == 'room'){//房屋
  78755. if(e.target == height_pull_box_up){
  78756. if(firstZ == void 0)firstZ = this.selected.zMax;
  78757. this.changeZ(this.selected, 'zMax', firstZ + moveZ);
  78758. }else {
  78759. if(firstZ == void 0)firstZ = this.selected.zMin;
  78760. this.changeZ(this.selected, 'zMin', firstZ + moveZ);
  78761. }
  78762. }
  78763. }else {
  78764. firstIntersect = intersect.z;
  78765. }
  78766. };
  78767. let drop = (e)=>{
  78768. firstZ = firstIntersect = null;
  78769. };
  78770. height_pull_box_up.addEventListener('mousemove',mouseover);
  78771. height_pull_box_down.addEventListener('mousemove',mouseover);
  78772. height_pull_box_up.addEventListener('mouseleave',mouseleave);
  78773. height_pull_box_down.addEventListener('mouseleave',mouseleave);
  78774. height_pull_box_up.addEventListener('drag',drag);
  78775. height_pull_box_down.addEventListener('drag',drag);
  78776. height_pull_box_up.addEventListener('drop',drop);
  78777. height_pull_box_down.addEventListener('drop',drop);
  78778. },
  78779. pointInWhichEntity(location, buildType, ifIgnoreHole){//buildType是要找的建筑类型
  78780. //location 可以是pano或者坐标
  78781. //由于房间可能在building外,所以房间要另外单独识别。
  78782. let lastResult; //最接近的上一层结果,如果没有result返回这个
  78783. let result;
  78784. let level = {
  78785. building: 0, floor: 1, room: 2
  78786. };
  78787. let traverse = (parent, buildType)=>{//返回第一个符合标准的实体
  78788. let contains;
  78789. if(location instanceof Vector3){
  78790. contains = parent.ifContainsPoint(location);
  78791. }else {//is pano
  78792. contains = parent.panos.includes(location);
  78793. }
  78794. if(contains){
  78795. if(!lastResult || level[lastResult.buildType] < level[parent.buildType] )lastResult = parent;
  78796. if(parent.buildType == buildType){
  78797. return parent
  78798. }else {
  78799. for(let i=0,len=parent.buildChildren.length; i<len; i++){
  78800. let result1 = traverse(parent.buildChildren[i]);
  78801. if(result1) return result1
  78802. }
  78803. }
  78804. }
  78805. };
  78806. //因为建筑可能重叠,所以需要先找到最接近其中心的建筑物
  78807. result = Common.sortByScore(this.buildings, [(building)=>{
  78808. return traverse(building, 'building') //在building中
  78809. }], [(building)=>{ //写法类似pointInWhichPointcloud
  78810. let boundingBox = building.getBound();
  78811. let center = boundingBox.getCenter(new Vector3());
  78812. let position = location instanceof Vector3 ? location : location.position;
  78813. let dis = position.distanceTo(center);
  78814. let size = boundingBox.getSize(new Vector3());
  78815. let length = size.length() / 2;
  78816. return length / dis
  78817. }]);
  78818. let building = result && result[0] && result[0].score > 1 && result[0].item;
  78819. if(buildType == 'building' || !building)return building
  78820. result = traverse(building, buildType);
  78821. /* if(!result && buildType == 'room'){//如果要找的是room, 且按刚才的顺序找不到的话,就单独从所有rooms中找一遍。因为room可能不在floor和building内。
  78822. let rooms = this.entities.filter(e=>e.buildType == 'room');
  78823. result = rooms.find(e=>e.ifContainsPoint(position))
  78824. }*/
  78825. //虽然房间可以画到上级之外,但是为了方便起见,假定房间绝对在楼层之内。找不到的话要调整空间模型了。
  78826. return result || lastResult
  78827. }
  78828. ,
  78829. findPanos: function(){
  78830. {
  78831. this.entities.forEach(entity=>{
  78832. //清空:
  78833. entity.panos = [];
  78834. entity.flagPano = null;
  78835. viewer.images360.panos.forEach(pano=>{
  78836. if(entity.ifContainsPoint(pano.position)){
  78837. entity.panos.push(pano);
  78838. }
  78839. });
  78840. });
  78841. }
  78842. /* viewer.images360.panos.forEach(pano=>{ //一个漫游点只对应一个实体的话
  78843. let result = this.pointInWhichEntity(pano.position, 'room');
  78844. {//get panos for every entities
  78845. let entity = result
  78846. while(entity){
  78847. entity.panos.push(pano);
  78848. entity = entity.buildParent
  78849. }
  78850. }
  78851. }) */
  78852. {//search center pano
  78853. this.entities.forEach(entity=>{
  78854. let panos = entity.panos;
  78855. if(panos.length == 0)return
  78856. let bound = entity.getBound();
  78857. let center = bound.getCenter(new Vector3);
  78858. let request = [];
  78859. let rank = [
  78860. Images360.scoreFunctions.distanceSquared({position: center})
  78861. ];
  78862. //let panos = entity.panos && entity.panos.length ? entity.panos : viewer.images360.panos //entity没有panos的话,就扩大到所有panos
  78863. let r = Common.sortByScore(panos, request, rank);
  78864. if(r && r.length){
  78865. entity.flagPano = r[0].item;
  78866. }else {
  78867. console.error('no flagPano??');
  78868. }
  78869. });
  78870. }
  78871. }
  78872. ,
  78873. findEntityForDataset:function(){//为每一个数据集寻找它所属的最小实体
  78874. /* var entities = this.entities.filter(e=>e.buildType == 'room' || e.buildType == 'floor' && e.buildChildren.length == 0)
  78875. viewer.scene.pointclouds.forEach(pointcloud=>{
  78876. let cloudVolume = pointcloud.getVolume()
  78877. let scores = []
  78878. entities.forEach(entity=>{
  78879. let volume = entity.intersectPointcloudVolume(pointcloud)
  78880. //注:默认已经findPanos过
  78881. let panos = entity.panos.filter(e=>pointcloud.panos.includes(e));
  78882. let panoCount = panos.length
  78883. let score = volume / cloudVolume + panoCount / pointcloud.panos.length
  78884. scores.push({entity, volume, panoCount, score})
  78885. })
  78886. scores.sort((a,b)=>{ return b.score-a.score })
  78887. if(scores.length == 0 || scores[0].volume/cloudVolume < 0.0001 && scores[0].volume < 3 ){//如果约等于0
  78888. pointcloud.belongToEntity = null
  78889. }else{
  78890. pointcloud.belongToEntity = scores[0].entity;
  78891. }
  78892. }) */
  78893. let getScores = (pointcloud, entities, cloudVolume)=>{
  78894. let scores = [];
  78895. entities.forEach(entity=>{
  78896. let volume = entity.intersectPointcloudVolume(pointcloud);
  78897. //注:默认已经findPanos过
  78898. let panos = entity.panos.filter(e=>pointcloud.panos.includes(e));
  78899. let panoCount = panos.length;
  78900. let score = volume / cloudVolume;
  78901. if(pointcloud.panos.length > 0){
  78902. score += panoCount / pointcloud.panos.length;
  78903. }else {
  78904. //score += 1
  78905. }
  78906. scores.push({entity, volume, panoCount, score});
  78907. });
  78908. scores.sort((a,b)=>{ return b.score-a.score });
  78909. return scores
  78910. };
  78911. viewer.scene.pointclouds.forEach(pointcloud=>{ //先判断父级,如果父集不通过就不判断子级。
  78912. let cloudVolume = pointcloud.getVolume();
  78913. let entities = this.buildings;
  78914. while(1){
  78915. let scores = getScores(pointcloud, entities, cloudVolume);
  78916. if(scores.length == 0 || scores[0].volume/cloudVolume < 0.0001 && scores[0].volume < 3 ){//如果约等于0
  78917. if(scores[0] && scores[0].entity.buildType == 'room'){
  78918. pointcloud.belongToEntity = scores[0].entity; //当该数据集在楼层中,但不在楼层中的任意一个房间时,任意挂载在其中一个房间上。
  78919. break
  78920. }
  78921. pointcloud.belongToEntity = null;
  78922. break;
  78923. }else {
  78924. entities = scores[0].entity.buildChildren;
  78925. if(entities.length == 0){
  78926. pointcloud.belongToEntity = scores[0].entity;
  78927. break;
  78928. }
  78929. }
  78930. }
  78931. });
  78932. /*
  78933. 旧版:
  78934. 只需要考虑 floor 和 room, 因为building的只有一个基底没高度
  78935. floor 和 room 在空间中没有完全的从属关系,因为room可以超出floor之外。所以直接混在一起来查找,但要排除有房间的楼层。
  78936. (现在改为层层递进查找,否则数据集包含entity多的,会直接挂载到体积最大的房间里,即使看起来主体点云并不在该房间)
  78937. 有的数据集虽然很高,但只有近地面的部分才是主体,这部分一般含有全部漫游点。为了防止上层的实体因体积较大而分数高,就把包含漫游点的个数也加入考虑。
  78938. 重叠体积大、且包含漫游点最多的最小实体将会拥有该点云。
  78939. 期望: 最好不挂载到最小子级,因为现在有房间都到房间里了。
  78940. */
  78941. }
  78942. ,
  78943. clear:function(){//清空
  78944. /* entities:[], //所有实体
  78945. buildings:[], //所有建筑父集
  78946. meshGroup: new THREE.Object3D, */
  78947. this.selectEntity(null);
  78948. let length = this.entities.length;
  78949. for(let i=0;i<length;i++){
  78950. this.entities[i].dispose();
  78951. }
  78952. this.entities = [];
  78953. this.buildings = [];
  78954. this.inEntity = null;
  78955. }
  78956. ,
  78957. gotoEntity(id, isNearBy, duration=1000) {
  78958. var entity = this.entities.find(e => e.sid == id);
  78959. let aimPano;
  78960. if (!entity) {
  78961. return console.error('没找到entity ')
  78962. }
  78963. if(Potree.settings.displayMode == 'showPanos'){
  78964. if (isNearBy && entity.panos.length) {
  78965. if(entity.panos.includes(viewer.images360.currentPano)) return 'posNoChange' //已在当前实体中
  78966. let position = viewer.scene.getActiveCamera().position;
  78967. let request = [];
  78968. let rank = [Images360.scoreFunctions.distanceSquared({ position })];
  78969. let r = Common.sortByScore(entity.panos, request, rank);
  78970. aimPano = r[0].item;
  78971. } else {
  78972. if (!entity.flagPano) {
  78973. return console.log('没有flagPano')
  78974. }
  78975. aimPano = entity.flagPano;
  78976. }
  78977. if(aimPano == viewer.images360.currentPano) return 'posNoChange'
  78978. viewer.images360.flyToPano(aimPano);
  78979. }else {
  78980. if(isNearBy && entity.ifContainsPoint(viewer.images360.position) ){
  78981. return 'posNoChange' //已在当前实体中
  78982. }
  78983. let boundingBox = entity.getBound();
  78984. let position = boundingBox.getCenter(new Vector3()); //中心点不一定在entity中,比如半环形建筑(所以要不要改成到漫游点呢)
  78985. if(viewer.modules.Clip && viewer.modules.Clip.editing){
  78986. viewer.modules.Clip.bus.dispatchEvent({type:'flyToPos', position});
  78987. }else {
  78988. if(math.closeTo(position, viewer.images360.position)) return 'posNoChange'
  78989. let size = boundingBox.getSize(new Vector3());
  78990. viewer.scene.view.setView({position, duration});
  78991. viewer.mapViewer.moveTo(position, size, duration);
  78992. }
  78993. }
  78994. return true
  78995. },
  78996. focusEntity(id){
  78997. var entity = this.entities.find(e => e.sid == id);
  78998. let boundingBox = entity.getBound();
  78999. //let boundSize = boundingBox.getSize(new THREE.Vector3())
  79000. let center = boundingBox.getCenter(new Vector3());
  79001. this.SplitScreen.focusOnObject(boundingBox, center);
  79002. this.gotoEntity(id, false, 0);
  79003. },
  79004. removeIlligalArchi(){//删除marker数量小于3个的建筑,当保存时
  79005. let needDelete = [];
  79006. this.entities.forEach(e=>{
  79007. if(e.points.length<3){
  79008. needDelete.push(e);
  79009. }
  79010. });
  79011. needDelete.forEach(e=>this.removeEntity(e));
  79012. },
  79013. };
  79014. // Author: Fyrestar https://mevedia.com (https://github.com/Fyrestar/THREE.InfiniteGridHelper)
  79015. class InfiniteGridHelper extends Mesh{
  79016. constructor(size1, size2, color, distance, opacity1=0.2, opacity2=1){
  79017. color = color || new Color('white');
  79018. size1 = size1 || 10;
  79019. size2 = size2 || 100;
  79020. distance = distance || 8000; //可视距离?越远越模糊
  79021. const geometry = new PlaneBufferGeometry(2, 2, 1, 1);
  79022. const material = new ShaderMaterial({
  79023. side: DoubleSide,
  79024. uniforms: {
  79025. uSize1: {
  79026. value: size1
  79027. },
  79028. uSize2: {
  79029. value: size2
  79030. },
  79031. opacity1:{//线条1的
  79032. value: opacity1
  79033. },
  79034. opacity2:{//线条2的
  79035. value: opacity2
  79036. },
  79037. uColor: {
  79038. value: color
  79039. },
  79040. uDistance: {
  79041. value: distance
  79042. }
  79043. },
  79044. transparent: true,
  79045. vertexShader: `
  79046. varying vec3 worldPosition;
  79047. uniform float uDistance;
  79048. void main() {
  79049. vec3 pos = position.xyz * uDistance;
  79050. pos.xy += cameraPosition.xy;
  79051. worldPosition = pos;
  79052. gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
  79053. }
  79054. `,
  79055. fragmentShader: `
  79056. varying vec3 worldPosition;
  79057. uniform float uSize1;
  79058. uniform float uSize2;
  79059. uniform float opacity1;
  79060. uniform float opacity2;
  79061. uniform vec3 uColor;
  79062. uniform float uDistance;
  79063. float getGrid(float size) {
  79064. vec2 r = worldPosition.xy / size;
  79065. vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);
  79066. float line = min(grid.x, grid.y);
  79067. return 1.0 - min(line, 1.0);
  79068. }
  79069. //为何侧面看不到线,因为mesh的正侧面都看不到?
  79070. void main() {
  79071. float d = 1.0 - min(distance(cameraPosition.xy, worldPosition.xy) / uDistance, 1.0);
  79072. float g1 = getGrid(uSize1);
  79073. float g2 = getGrid(uSize2);
  79074. gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, 3.0));
  79075. //gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2);
  79076. gl_FragColor.a = mix(opacity1 * gl_FragColor.a, opacity2 * gl_FragColor.a, g2);
  79077. if ( gl_FragColor.a <= 0.0 ) discard;
  79078. }
  79079. `,
  79080. extensions: {
  79081. derivatives: true
  79082. }
  79083. });
  79084. super(geometry, material);
  79085. this.frustumCulled = false;
  79086. }
  79087. };
  79088. /*
  79089. THREE.InfiniteGridHelper.prototype = {
  79090. ...THREE.Mesh.prototype,
  79091. ...THREE.Object3D.prototype,
  79092. ...THREE.EventDispatcher.prototype
  79093. };
  79094. */
  79095. //import {Utils} from "../../utils.js";
  79096. var TransformControls = function ( camera, domElement, options ) {
  79097. if ( domElement === undefined ) {
  79098. console.warn( 'THREE.TransformControls: The second parameter "domElement" is now mandatory.' );
  79099. domElement = document;
  79100. }
  79101. Object3D.call( this );
  79102. this.visible = false;
  79103. this.domElement = domElement;
  79104. var _gizmo = new TransformControlsGizmo(options);
  79105. this.add( _gizmo );
  79106. var _plane = new TransformControlsPlane(options);
  79107. this.add( _plane );
  79108. /* this.linesAssistance = new TransformControlsLines(options); //水平 垂直 辅助
  79109. this.add( this.linesAssistance ); */
  79110. var scope = this;
  79111. //this.player = options.player;//xzw add
  79112. this.options = options;//xzw add
  79113. // Define properties with getters/setter
  79114. // Setting the defined property will automatically trigger change event
  79115. // Defined properties are passed down to gizmo and plane
  79116. defineProperty( "camera", camera );
  79117. defineProperty( "object", undefined );
  79118. defineProperty( "enabled", true );
  79119. defineProperty( "axis", null );
  79120. defineProperty( "mode", "translate" );
  79121. defineProperty( "translationSnap", null );
  79122. defineProperty( "rotationSnap", null );
  79123. defineProperty( "scaleSnap", null );
  79124. defineProperty( "space", "world" );
  79125. defineProperty( "size", 1 );
  79126. defineProperty( "dragging", false );
  79127. defineProperty( "showX", true );
  79128. defineProperty( "showY", true );
  79129. defineProperty( "showZ", true );
  79130. var changeEvent = { type: "change" };
  79131. var mouseDownEvent = { type: "mouseDown" };
  79132. var mouseUpEvent = { type: "mouseUp", mode: scope.mode };
  79133. var objectChangeEvent = { type: "objectChange" };
  79134. // Reusable utility variables
  79135. var ray = new Raycaster();
  79136. var _tempVector = new Vector3();
  79137. var _tempVector2 = new Vector3();
  79138. var _tempQuaternion = new Quaternion();
  79139. var _unit = {
  79140. X: new Vector3( 1, 0, 0 ),
  79141. Y: new Vector3( 0, 1, 0 ),
  79142. Z: new Vector3( 0, 0, 1 )
  79143. };
  79144. var pointStart = new Vector3();
  79145. var pointEnd = new Vector3();
  79146. var offset = new Vector3();
  79147. var rotationAxis = new Vector3();
  79148. var startNorm = new Vector3();
  79149. var endNorm = new Vector3();
  79150. var rotationAngle = 0;
  79151. var cameraPosition = new Vector3();
  79152. var cameraQuaternion = new Quaternion();
  79153. var cameraScale = new Vector3();
  79154. var parentPosition = new Vector3();
  79155. var parentQuaternion = new Quaternion();
  79156. var parentQuaternionInv = new Quaternion();
  79157. var parentScale = new Vector3();
  79158. var worldPositionStart = new Vector3();
  79159. var worldQuaternionStart = new Quaternion();
  79160. var worldScaleStart = new Vector3();
  79161. var worldPosition = new Vector3();
  79162. var worldQuaternion = new Quaternion();
  79163. var worldQuaternionInv = new Quaternion();
  79164. var worldScale = new Vector3();
  79165. var eye = new Vector3();
  79166. var positionStart = new Vector3();
  79167. var quaternionStart = new Quaternion();
  79168. var scaleStart = new Vector3();
  79169. // TODO: remove properties unused in plane and gizmo
  79170. defineProperty( "worldPosition", worldPosition );
  79171. defineProperty( "worldPositionStart", worldPositionStart );
  79172. defineProperty( "worldQuaternion", worldQuaternion );
  79173. defineProperty( "worldQuaternionStart", worldQuaternionStart );
  79174. defineProperty( "cameraPosition", cameraPosition );
  79175. defineProperty( "cameraQuaternion", cameraQuaternion );
  79176. defineProperty( "pointStart", pointStart );
  79177. defineProperty( "pointEnd", pointEnd );
  79178. defineProperty( "rotationAxis", rotationAxis );
  79179. defineProperty( "rotationAngle", rotationAngle );
  79180. defineProperty( "eye", eye );
  79181. {
  79182. domElement.addEventListener( "mousedown", onPointerDown, false );
  79183. domElement.addEventListener( "touchstart", onPointerDown, false );
  79184. domElement.addEventListener( "mousemove", onPointerHover, false );
  79185. domElement.addEventListener( "touchmove", onPointerHover, false );
  79186. domElement.addEventListener( "touchmove", onPointerMove, false );
  79187. document.addEventListener( "mouseup", onPointerUp, false );
  79188. domElement.addEventListener( "touchend", onPointerUp, false );
  79189. domElement.addEventListener( "touchcancel", onPointerUp, false );
  79190. domElement.addEventListener( "touchleave", onPointerUp, false );
  79191. viewer.addEventListener('global_drag',(e)=>{
  79192. if(this.dragging){
  79193. this.pointerMove();
  79194. return {stopContinue:true}
  79195. }
  79196. },10);
  79197. }
  79198. this.dispose = function () {
  79199. domElement.removeEventListener( "mousedown", onPointerDown );
  79200. domElement.removeEventListener( "touchstart", onPointerDown );
  79201. domElement.removeEventListener( "mousemove", onPointerHover );
  79202. domElement.removeEventListener( "mousemove", onPointerMove );
  79203. domElement.removeEventListener( "touchmove", onPointerHover );
  79204. domElement.removeEventListener( "touchmove", onPointerMove );
  79205. document.removeEventListener( "mouseup", onPointerUp );
  79206. domElement.removeEventListener( "touchend", onPointerUp );
  79207. domElement.removeEventListener( "touchcancel", onPointerUp );
  79208. domElement.removeEventListener( "touchleave", onPointerUp );
  79209. this.traverse( function ( child ) {
  79210. if ( child.geometry ) child.geometry.dispose();
  79211. if ( child.material ) child.material.dispose();
  79212. } );
  79213. };
  79214. // Set current object
  79215. this.attach = function ( object ) {
  79216. this.object = object;
  79217. this.visible = true;
  79218. //Config.keyCon = false;//add
  79219. //this.linesAssistance.setVisible(true)
  79220. return this;
  79221. };
  79222. // Detatch from object
  79223. this.detach = function () {
  79224. this.object = undefined;
  79225. this.visible = false;
  79226. this.axis = null;
  79227. //Config.keyCon = true;//add
  79228. //this.linesAssistance.setVisible(false)
  79229. return this;
  79230. };
  79231. // Defined getter, setter and store for a property
  79232. function defineProperty( propName, defaultValue ) {
  79233. var propValue = defaultValue;
  79234. Object.defineProperty( scope, propName, {
  79235. get: function () {
  79236. return propValue !== undefined ? propValue : defaultValue;
  79237. },
  79238. set: function ( value ) {
  79239. if ( propValue !== value ) {
  79240. propValue = value;
  79241. _plane[ propName ] = value;
  79242. _gizmo[ propName ] = value;
  79243. scope.dispatchEvent( { type: propName + "-changed", value: value } );
  79244. scope.dispatchEvent( changeEvent );
  79245. }
  79246. }
  79247. } );
  79248. scope[ propName ] = defaultValue;
  79249. _plane[ propName ] = defaultValue;
  79250. _gizmo[ propName ] = defaultValue;
  79251. }
  79252. // updateMatrixWorld updates key transformation variables
  79253. this.updateMatrixWorld = function () {
  79254. if ( this.object !== undefined ) {
  79255. this.object.updateMatrixWorld();
  79256. this.object.parent.matrixWorld.decompose( parentPosition, parentQuaternion, parentScale );
  79257. this.object.matrixWorld.decompose( worldPosition, worldQuaternion, worldScale );
  79258. //add 使坐标轴在boundingBox中心
  79259. this.object.boundingBox && this.object.boundingBox.getCenter(worldPosition).applyMatrix4(this.object.matrixWorld);
  79260. parentQuaternionInv.copy( parentQuaternion ).invert();
  79261. worldQuaternionInv.copy( worldQuaternion ).invert();
  79262. }
  79263. this.camera.updateMatrixWorld();
  79264. this.camera.matrixWorld.decompose( cameraPosition, cameraQuaternion, cameraScale );
  79265. eye.copy( cameraPosition ).sub( worldPosition ).normalize();
  79266. Object3D.prototype.updateMatrixWorld.call( this );
  79267. };
  79268. this.pointerHover = function () {
  79269. let pointer = viewer.inputHandler.pointer;
  79270. if ( this.object === undefined)return
  79271. //if(this.dragging === true /* || ( pointer.button !== undefined && pointer.button !== 0 ) */) return;
  79272. if(!this.dragging){
  79273. //ray.setFromCamera( pointer, this.camera ); //这句会在floorplan模式get不到intersect
  79274. let {origin, direction} = viewer.inputHandler.getMouseDirection();
  79275. ray.set(origin, direction);
  79276. var intersect = ray.intersectObjects( _gizmo.picker[ this.mode ].children, true )[ 0 ] || false;
  79277. if ( intersect ) {
  79278. this.axis = intersect.object.name;
  79279. } else {
  79280. this.axis = null;
  79281. }
  79282. }else {
  79283. //this.pointerMove()
  79284. }
  79285. };
  79286. this.pointerDown = function ( /* pointer */ ) {
  79287. let pointer = viewer.inputHandler.pointer;
  79288. if ( this.object === undefined || this.dragging === true /* || ( pointer.button !== undefined && pointer.button !== 0 ) */ ) return;
  79289. if ( /* ( pointer.button === 0 || pointer.button === undefined ) && */ this.axis !== null ) {
  79290. //ray.setFromCamera( pointer, this.camera ); //这句会在floorplan模式get不到intersect
  79291. let {origin, direction} = viewer.inputHandler.getMouseDirection();
  79292. ray.set(origin, direction);
  79293. var planeIntersect = ray.intersectObjects( [ _plane ], true )[ 0 ] || false;
  79294. if ( planeIntersect ) {
  79295. var space = this.space;
  79296. if ( this.mode === 'scale' ) {
  79297. space = 'local';
  79298. } else if ( this.axis === 'E' || this.axis === 'XYZE' || this.axis === 'XYZ' ) {
  79299. space = 'world';
  79300. }
  79301. if ( space === 'local' && this.mode === 'rotate' ) {
  79302. var snap = this.rotationSnap;
  79303. if ( this.axis === 'X' && snap ) this.object.rotation.x = Math.round( this.object.rotation.x / snap ) * snap;
  79304. if ( this.axis === 'Y' && snap ) this.object.rotation.y = Math.round( this.object.rotation.y / snap ) * snap;
  79305. if ( this.axis === 'Z' && snap ) this.object.rotation.z = Math.round( this.object.rotation.z / snap ) * snap;
  79306. }
  79307. this.object.updateMatrixWorld();
  79308. this.object.parent.updateMatrixWorld();
  79309. positionStart.copy( this.object.position );
  79310. quaternionStart.copy( this.object.quaternion );
  79311. scaleStart.copy( this.object.scale );
  79312. this.object.matrixWorld.decompose( worldPositionStart, worldQuaternionStart, worldScaleStart );
  79313. //add: 使坐标轴在boundingBox中心
  79314. this.object.boundingBox && this.object.boundingBox.getCenter(worldPositionStart).applyMatrix4(this.object.matrixWorld);
  79315. pointStart.copy( planeIntersect.point ).sub( worldPositionStart );
  79316. /* if(this.player.cameraControls.activeControl){
  79317. //this.player.cameraControls.activeControl.locked = true; //add
  79318. this.player.cameraControls.activeControl.enabled = false; //add
  79319. } */
  79320. }
  79321. this.dragging = true;
  79322. mouseDownEvent.mode = this.mode;
  79323. this.dispatchEvent( mouseDownEvent );
  79324. }
  79325. };
  79326. this.pointerMove = function ( /* pointer */ ) {
  79327. let pointer = viewer.inputHandler.pointer;
  79328. var axis = this.axis;
  79329. var mode = this.mode;
  79330. var object = this.object;
  79331. var space = this.space;
  79332. if ( mode === 'scale' ) {
  79333. space = 'local';
  79334. } else if ( axis === 'E' || axis === 'XYZE' || axis === 'XYZ' ) {
  79335. space = 'world';
  79336. }
  79337. if ( object === undefined || axis === null || this.dragging === false || ( pointer.button !== undefined && pointer.button !== 0 ) ) return;
  79338. //ray.setFromCamera( pointer, this.camera ); //这句会在floorplan模式get不到intersect
  79339. let {origin, direction} = viewer.inputHandler.getMouseDirection();
  79340. ray.set(origin, direction);
  79341. var planeIntersect = ray.intersectObjects( [ _plane ], true )[ 0 ] || false;
  79342. if ( planeIntersect === false ) return;
  79343. pointEnd.copy( planeIntersect.point ).sub( worldPositionStart );
  79344. if ( mode === 'translate' ) {
  79345. // Apply translate
  79346. offset.copy( pointEnd ).sub( pointStart );
  79347. if ( space === 'local' && axis !== 'XYZ' ) {
  79348. offset.applyQuaternion( worldQuaternionInv );
  79349. }
  79350. if ( axis.indexOf( 'X' ) === - 1 ) offset.x = 0;
  79351. if ( axis.indexOf( 'Y' ) === - 1 ) offset.y = 0;
  79352. if ( axis.indexOf( 'Z' ) === - 1 ) offset.z = 0;
  79353. if ( space === 'local' && axis !== 'XYZ' ) {
  79354. //xzw 加,否则会反向---------------
  79355. object.scale.x < 0 && (offset.x *= -1);
  79356. object.scale.y < 0 && (offset.y *= -1);
  79357. object.scale.z < 0 && (offset.z *= -1);
  79358. //---------------------------------
  79359. offset.applyQuaternion( quaternionStart ).divide( parentScale );
  79360. } else {
  79361. offset.applyQuaternion( parentQuaternionInv ).divide( parentScale );
  79362. }
  79363. object.position.copy( offset ).add( positionStart );
  79364. // Apply translation snap
  79365. if ( this.translationSnap ) {
  79366. if ( space === 'local' ) {
  79367. object.position.applyQuaternion( _tempQuaternion.copy( quaternionStart ).invert() );
  79368. if ( axis.search( 'X' ) !== - 1 ) {
  79369. object.position.x = Math.round( object.position.x / this.translationSnap ) * this.translationSnap;
  79370. }
  79371. if ( axis.search( 'Y' ) !== - 1 ) {
  79372. object.position.y = Math.round( object.position.y / this.translationSnap ) * this.translationSnap;
  79373. }
  79374. if ( axis.search( 'Z' ) !== - 1 ) {
  79375. object.position.z = Math.round( object.position.z / this.translationSnap ) * this.translationSnap;
  79376. }
  79377. object.position.applyQuaternion( quaternionStart );
  79378. }
  79379. if ( space === 'world' ) {
  79380. if ( object.parent ) {
  79381. object.position.add( _tempVector.setFromMatrixPosition( object.parent.matrixWorld ) );
  79382. }
  79383. if ( axis.search( 'X' ) !== - 1 ) {
  79384. object.position.x = Math.round( object.position.x / this.translationSnap ) * this.translationSnap;
  79385. }
  79386. if ( axis.search( 'Y' ) !== - 1 ) {
  79387. object.position.y = Math.round( object.position.y / this.translationSnap ) * this.translationSnap;
  79388. }
  79389. if ( axis.search( 'Z' ) !== - 1 ) {
  79390. object.position.z = Math.round( object.position.z / this.translationSnap ) * this.translationSnap;
  79391. }
  79392. if ( object.parent ) {
  79393. object.position.sub( _tempVector.setFromMatrixPosition( object.parent.matrixWorld ) );
  79394. }
  79395. }
  79396. }
  79397. //add:
  79398. object.dispatchEvent({
  79399. type: "position_changed"
  79400. });
  79401. } else if ( mode === 'scale' ) {
  79402. if ( axis.search( 'XYZ' ) !== - 1 ) {
  79403. var d = pointEnd.length() / pointStart.length();
  79404. if ( pointEnd.dot( pointStart ) < 0 ) d *= - 1;
  79405. if(options.NoScaleZ){//xzw add
  79406. _tempVector2.set( d, d, 1 );
  79407. }else {
  79408. _tempVector2.set( d, d, d );
  79409. }
  79410. }else if ( axis.search( 'XY' ) !== - 1 ) { //add 等比例for plane
  79411. var d = pointEnd.length() / pointStart.length();
  79412. if ( pointEnd.dot( pointStart ) < 0 ) d *= - 1;
  79413. _tempVector2.set( d, d, 1 );
  79414. }else {
  79415. _tempVector.copy( pointStart );
  79416. _tempVector2.copy( pointEnd );
  79417. _tempVector.applyQuaternion( worldQuaternionInv );
  79418. _tempVector2.applyQuaternion( worldQuaternionInv );
  79419. _tempVector2.divide( _tempVector );
  79420. if ( axis.search( 'X' ) === - 1 ) {
  79421. _tempVector2.x = 1;
  79422. }
  79423. if ( axis.search( 'Y' ) === - 1 ) {
  79424. _tempVector2.y = 1;
  79425. }
  79426. if ( axis.search( 'Z' ) === - 1 ) {
  79427. _tempVector2.z = 1;
  79428. }
  79429. }
  79430. // Apply scale
  79431. object.scale.copy( scaleStart ).multiply( _tempVector2 );
  79432. if ( this.scaleSnap ) {
  79433. if ( axis.search( 'X' ) !== - 1 ) {
  79434. object.scale.x = Math.round( object.scale.x / this.scaleSnap ) * this.scaleSnap || this.scaleSnap;
  79435. }
  79436. if ( axis.search( 'Y' ) !== - 1 ) {
  79437. object.scale.y = Math.round( object.scale.y / this.scaleSnap ) * this.scaleSnap || this.scaleSnap;
  79438. }
  79439. if ( axis.search( 'Z' ) !== - 1 ) {
  79440. object.scale.z = Math.round( object.scale.z / this.scaleSnap ) * this.scaleSnap || this.scaleSnap;
  79441. }
  79442. }
  79443. //add:
  79444. object.dispatchEvent({
  79445. type: "scale_changed"
  79446. });
  79447. } else if ( mode === 'rotate' ) {
  79448. offset.copy( pointEnd ).sub( pointStart );
  79449. var ROTATION_SPEED = 2 / worldPosition.distanceTo( _tempVector.setFromMatrixPosition( this.camera.matrixWorld ) );
  79450. if ( axis === 'E' ) {
  79451. rotationAxis.copy( eye );
  79452. rotationAngle = pointEnd.angleTo( pointStart );
  79453. startNorm.copy( pointStart ).normalize();
  79454. endNorm.copy( pointEnd ).normalize();
  79455. rotationAngle *= ( endNorm.cross( startNorm ).dot( eye ) < 0 ? 1 : - 1 );
  79456. } else if ( axis === 'XYZE' ) {
  79457. rotationAxis.copy( offset ).cross( eye ).normalize();
  79458. rotationAngle = offset.dot( _tempVector.copy( rotationAxis ).cross( this.eye ) ) * ROTATION_SPEED;
  79459. } else if ( axis === 'X' || axis === 'Y' || axis === 'Z' ) {
  79460. rotationAxis.copy( _unit[ axis ] );
  79461. _tempVector.copy( _unit[ axis ] );
  79462. if ( space === 'local' ) {
  79463. _tempVector.applyQuaternion( worldQuaternion );
  79464. }
  79465. rotationAngle = offset.dot( _tempVector.cross( eye ).normalize() ) * ROTATION_SPEED;
  79466. }
  79467. // Apply rotation snap
  79468. if ( this.rotationSnap ) rotationAngle = Math.round( rotationAngle / this.rotationSnap ) * this.rotationSnap;
  79469. this.rotationAngle = rotationAngle;
  79470. // Apply rotate
  79471. if ( space === 'local' && axis !== 'E' && axis !== 'XYZE' ) {
  79472. object.scale[axis.toLowerCase()] < 0 && (rotationAngle *= -1); //xzw 加,否则会反向
  79473. object.quaternion.copy( quaternionStart );
  79474. object.quaternion.multiply( _tempQuaternion.setFromAxisAngle( rotationAxis, rotationAngle ) ).normalize();
  79475. } else {
  79476. rotationAxis.applyQuaternion( parentQuaternionInv );
  79477. object.quaternion.copy( _tempQuaternion.setFromAxisAngle( rotationAxis, rotationAngle ) );
  79478. object.quaternion.multiply( quaternionStart ).normalize();
  79479. }
  79480. //add:
  79481. object.dispatchEvent({
  79482. type: "rotation_changed"
  79483. });
  79484. }
  79485. this.dispatchEvent( changeEvent );
  79486. this.dispatchEvent( objectChangeEvent );
  79487. };
  79488. this.pointerUp = function ( pointer ) {
  79489. //if ( pointer.button !== undefined && pointer.button !== 0 ) return;
  79490. if ( this.dragging && ( this.axis !== null ) ) {
  79491. mouseUpEvent.mode = this.mode;
  79492. this.dispatchEvent( mouseUpEvent );
  79493. /* if(this.player.cameraControls.activeControl){
  79494. //this.player.cameraControls.activeControl.locked = false; //add
  79495. this.player.cameraControls.activeControl.pointerDragOn = false //add
  79496. this.player.cameraControls.activeControl.enabled = true
  79497. } */
  79498. }
  79499. this.dragging = false;
  79500. //if ( pointer.button === undefined ) this.axis = null;
  79501. /* if(this.player.cameraControls.activeControl){
  79502. //this.player.cameraControls.activeControl.locked = false; //add
  79503. this.player.cameraControls.activeControl.pointerDragOn = false //add
  79504. this.player.cameraControls.activeControl.enabled = true
  79505. } */
  79506. };
  79507. // normalize mouse / touch pointer and remap {x,y} to view space.
  79508. function getPointer( event ) {
  79509. if(!event){
  79510. console.log('hhahhhahah');
  79511. return;
  79512. }
  79513. if ( document.pointerLockElement ) {
  79514. return {
  79515. x: 0,
  79516. y: 0,
  79517. button: event.button
  79518. };
  79519. } else {
  79520. var pointer = event.changedTouches ? event.changedTouches[ 0 ] : event;
  79521. var rect = domElement.getBoundingClientRect();
  79522. return {
  79523. x: ( pointer.clientX - rect.left ) / rect.width * 2 - 1,
  79524. y: - ( pointer.clientY - rect.top ) / rect.height * 2 + 1,
  79525. button: event.button
  79526. };
  79527. }
  79528. }
  79529. // mouse / touch event handlers
  79530. function onPointerHover( event ) {
  79531. if ( ! scope.enabled ) return;
  79532. //scope.pointerHover( getPointer( event ) );
  79533. scope.pointerHover( );
  79534. }
  79535. function onPointerDown( event ) {
  79536. if ( ! scope.enabled ) return;
  79537. //document.addEventListener( "mousemove", onPointerMove, false );
  79538. /* scope.pointerHover( getPointer( event ) );
  79539. scope.pointerDown( getPointer( event ) ); */
  79540. scope.pointerHover( );
  79541. scope.pointerDown();
  79542. }
  79543. this.onPointerDown = onPointerDown;
  79544. function onPointerMove( event ) {
  79545. if ( ! scope.enabled || !this.dragging) return; //xzw change
  79546. //scope.pointerMove( getPointer( event ) );
  79547. scope.pointerMove( );
  79548. }
  79549. this.onPointerMove = onPointerMove;
  79550. function onPointerUp( event ) {
  79551. if ( ! scope.enabled ) return;
  79552. //document.removeEventListener( "mousemove", onPointerMove, false );
  79553. //scope.pointerUp( getPointer( event ) );
  79554. scope.pointerUp( );
  79555. }
  79556. this.onPointerUp = onPointerUp;
  79557. // TODO: deprecate
  79558. this.getMode = function () {
  79559. return scope.mode;
  79560. };
  79561. this.setMode = function ( mode ) {
  79562. scope.mode = mode;
  79563. };
  79564. this.setTranslationSnap = function ( translationSnap ) {
  79565. scope.translationSnap = translationSnap;
  79566. };
  79567. this.setRotationSnap = function ( rotationSnap ) {
  79568. scope.rotationSnap = rotationSnap;
  79569. };
  79570. this.setScaleSnap = function ( scaleSnap ) {
  79571. scope.scaleSnap = scaleSnap;
  79572. };
  79573. this.setSize = function ( size ) {
  79574. scope.size = size;
  79575. };
  79576. this.setSpace = function ( space ) {
  79577. scope.space = space;
  79578. };
  79579. this.update = function () {
  79580. console.warn( 'THREE.TransformControls: update function has no more functionality and therefore has been deprecated.' );
  79581. };
  79582. };
  79583. var TransformControlsGizmo = function (options) {
  79584. 'use strict';
  79585. Object3D.call( this );
  79586. this.type = 'TransformControlsGizmo';
  79587. // shared materials
  79588. var gizmoMaterial = new MeshBasicMaterial( {
  79589. depthTest: false,
  79590. depthWrite: false,
  79591. transparent: true,
  79592. side: DoubleSide,
  79593. fog: false
  79594. } );
  79595. var gizmoLineMaterial = new LineBasicMaterial( {
  79596. depthTest: false,
  79597. depthWrite: false,
  79598. transparent: true,
  79599. fog: false
  79600. } );
  79601. // Make unique material for each axis/color
  79602. var matInvisible = gizmoMaterial.clone();
  79603. matInvisible.opacity = 0.15;
  79604. var matHelper = gizmoMaterial.clone();
  79605. matHelper.opacity = 0.33;
  79606. var matRed = gizmoMaterial.clone();
  79607. matRed.color.set( 0xff0000 );
  79608. var matGreen = gizmoMaterial.clone();
  79609. matGreen.color.set( 0x00ff00 );
  79610. var matBlue = gizmoMaterial.clone();
  79611. matBlue.color.set( 0x0000ff );
  79612. var matWhiteTransparent = gizmoMaterial.clone();
  79613. matWhiteTransparent.opacity = 0.35;
  79614. matWhiteTransparent.color.set( 0x00d0fd );//xzw add
  79615. var matYellowTransparent = matWhiteTransparent.clone();
  79616. matYellowTransparent.color.set( 0xffff00 );
  79617. var matCyanTransparent = matWhiteTransparent.clone();
  79618. matCyanTransparent.color.set( 0x00ffff );
  79619. var matMagentaTransparent = matWhiteTransparent.clone();
  79620. matMagentaTransparent.color.set( 0xff00ff );
  79621. var matYellow = gizmoMaterial.clone();
  79622. matYellow.color.set( 0xffff00 );
  79623. var matLineRed = gizmoLineMaterial.clone();
  79624. matLineRed.color.set( 0xff0000 );
  79625. var matLineGreen = gizmoLineMaterial.clone();
  79626. matLineGreen.color.set( 0x00ff00 );
  79627. var matLineBlue = gizmoLineMaterial.clone();
  79628. matLineBlue.color.set( 0x0000ff );
  79629. var matLineCyan = gizmoLineMaterial.clone();
  79630. matLineCyan.color.set( 0x00ffff );
  79631. var matLineMagenta = gizmoLineMaterial.clone();
  79632. matLineMagenta.color.set( 0xff00ff );
  79633. var matLineYellow = gizmoLineMaterial.clone();
  79634. matLineYellow.color.set( 0xffff00 );
  79635. var matLineGray = gizmoLineMaterial.clone();
  79636. matLineGray.color.set( 0x787878 );
  79637. var matLineYellowTransparent = matLineYellow.clone();
  79638. matLineYellowTransparent.opacity = 0.25;
  79639. // reusable geometry
  79640. var arrowGeometry = new CylinderBufferGeometry( 0, 0.05, 0.2, 12, 1, false );
  79641. var scaleHandleGeometry = new BoxBufferGeometry( 0.125, 0.125, 0.125 );
  79642. var lineGeometry = new BufferGeometry( );
  79643. //lineGeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( [ 0, 0, 0, 1, 0, 0 ], 3 ) );
  79644. lineGeometry.setAttribute("position", new BufferAttribute(new Float32Array([ 0, 0, 0, 1, 0, 0]), 3 ));
  79645. var CircleGeometry = function ( radius, arc ) {
  79646. var geometry = new BufferGeometry( );
  79647. var vertices = [];
  79648. for ( var i = 0; i <= 64 * arc; ++ i ) {
  79649. vertices.push( 0, Math.cos( i / 32 * Math.PI ) * radius, Math.sin( i / 32 * Math.PI ) * radius );
  79650. }
  79651. //geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  79652. geometry.setAttribute("position", new BufferAttribute(new Float32Array(vertices), 3 ));
  79653. return geometry;
  79654. };
  79655. // Special geometry for transform helper. If scaled with position vector it spans from [0,0,0] to position
  79656. var TranslateHelperGeometry = function () {
  79657. var geometry = new BufferGeometry();
  79658. //geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( [ 0, 0, 0, 1, 1, 1 ], 3 ) );
  79659. geometry.setAttribute("position", new BufferAttribute(new Float32Array([ 0, 0, 0, 1, 1, 1 ]), 3 ));
  79660. return geometry;
  79661. };
  79662. // Gizmo definitions - custom hierarchy definitions for setupGizmo() function
  79663. var gizmoTranslate = {
  79664. X: [
  79665. [ new Mesh( arrowGeometry, matRed ), [ 1, 0, 0 ], [ 0, 0, - Math.PI / 2 ], null, 'fwd' ],
  79666. //[ new THREE.Mesh( arrowGeometry, matRed ), [ 1, 0, 0 ], [ 0, 0, Math.PI / 2 ], null, 'bwd' ],
  79667. [ new Line( lineGeometry, matLineRed ) ]
  79668. ],
  79669. Y: [
  79670. [ new Mesh( arrowGeometry, matGreen ), [ 0, 1, 0 ], null, null, 'fwd' ],
  79671. //[ new THREE.Mesh( arrowGeometry, matGreen ), [ 0, 1, 0 ], [ Math.PI, 0, 0 ], null, 'bwd' ],
  79672. [ new Line( lineGeometry, matLineGreen ), null, [ 0, 0, Math.PI / 2 ]]
  79673. ],
  79674. Z: [
  79675. [ new Mesh( arrowGeometry, matBlue ), [ 0, 0, 1 ], [ Math.PI / 2, 0, 0 ], null, 'fwd' ],
  79676. //[ new THREE.Mesh( arrowGeometry, matBlue ), [ 0, 0, 1 ], [ - Math.PI / 2, 0, 0 ], null, 'bwd' ],
  79677. [ new Line( lineGeometry, matLineBlue ), null, [ 0, - Math.PI / 2, 0 ]]
  79678. ],
  79679. /* XYZ: [
  79680. [ new THREE.Mesh( new THREE.OctahedronBufferGeometry( 0.1, 0 ), matWhiteTransparent.clone() ), [ 0, 0, 0 ], [ 0, 0, 0 ]]
  79681. ], */
  79682. XY: [
  79683. [ new Mesh( new PlaneBufferGeometry( 0.295, 0.295 ), matYellowTransparent.clone() ), [ 0.15, 0.15, 0 ]],
  79684. [ new Line( lineGeometry, matLineYellow ), [ 0.18, 0.3, 0 ], null, [ 0.125, 1, 1 ]],
  79685. [ new Line( lineGeometry, matLineYellow ), [ 0.3, 0.18, 0 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]]
  79686. ],
  79687. YZ: [
  79688. [ new Mesh( new PlaneBufferGeometry( 0.295, 0.295 ), matCyanTransparent.clone() ), [ 0, 0.15, 0.15 ], [ 0, Math.PI / 2, 0 ]],
  79689. [ new Line( lineGeometry, matLineCyan ), [ 0, 0.18, 0.3 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]],
  79690. [ new Line( lineGeometry, matLineCyan ), [ 0, 0.3, 0.18 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
  79691. ],
  79692. XZ: [
  79693. [ new Mesh( new PlaneBufferGeometry( 0.295, 0.295 ), matMagentaTransparent.clone() ), [ 0.15, 0, 0.15 ], [ - Math.PI / 2, 0, 0 ]],
  79694. [ new Line( lineGeometry, matLineMagenta ), [ 0.18, 0, 0.3 ], null, [ 0.125, 1, 1 ]],
  79695. [ new Line( lineGeometry, matLineMagenta ), [ 0.3, 0, 0.18 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
  79696. ]
  79697. };
  79698. var pickerTranslate = {
  79699. X: [
  79700. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 1, 4, 1, false ), matInvisible ), [ 0.6, 0, 0 ], [ 0, 0, - Math.PI / 2 ]]
  79701. ],
  79702. Y: [
  79703. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 1, 4, 1, false ), matInvisible ), [ 0, 0.6, 0 ]]
  79704. ],
  79705. Z: [
  79706. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 1, 4, 1, false ), matInvisible ), [ 0, 0, 0.6 ], [ Math.PI / 2, 0, 0 ]]
  79707. ],
  79708. /* XYZ: [
  79709. [ new THREE.Mesh( new THREE.OctahedronBufferGeometry( 0.2, 0 ), matInvisible ) ]
  79710. ], */
  79711. XY: [
  79712. [ new Mesh( new PlaneBufferGeometry( 0.4, 0.4 ), matInvisible ), [ 0.2, 0.2, 0 ]]
  79713. ],
  79714. YZ: [
  79715. [ new Mesh( new PlaneBufferGeometry( 0.4, 0.4 ), matInvisible ), [ 0, 0.2, 0.2 ], [ 0, Math.PI / 2, 0 ]]
  79716. ],
  79717. XZ: [
  79718. [ new Mesh( new PlaneBufferGeometry( 0.4, 0.4 ), matInvisible ), [ 0.2, 0, 0.2 ], [ - Math.PI / 2, 0, 0 ]]
  79719. ]
  79720. };
  79721. var helperTranslate = {
  79722. START: [
  79723. [ new Mesh( new OctahedronBufferGeometry( 0.01, 2 ), matHelper ), null, null, null, 'helper' ]
  79724. ],
  79725. END: [
  79726. [ new Mesh( new OctahedronBufferGeometry( 0.01, 2 ), matHelper ), null, null, null, 'helper' ]
  79727. ],
  79728. DELTA: [
  79729. [ new Line( TranslateHelperGeometry(), matHelper ), null, null, null, 'helper' ]
  79730. ],
  79731. X: [
  79732. [ new Line( lineGeometry, matHelper.clone() ), [ - 1e3, 0, 0 ], null, [ 1e6, 1, 1 ], 'helper' ]
  79733. ],
  79734. Y: [
  79735. [ new Line( lineGeometry, matHelper.clone() ), [ 0, - 1e3, 0 ], [ 0, 0, Math.PI / 2 ], [ 1e6, 1, 1 ], 'helper' ]
  79736. ],
  79737. Z: [
  79738. [ new Line( lineGeometry, matHelper.clone() ), [ 0, 0, - 1e3 ], [ 0, - Math.PI / 2, 0 ], [ 1e6, 1, 1 ], 'helper' ]
  79739. ]
  79740. };
  79741. var gizmoRotate = {
  79742. X: [
  79743. [ new Line( CircleGeometry( 1, 0.5 ), matLineRed ) ],
  79744. [ new Mesh( new OctahedronBufferGeometry( 0.04, 0 ), matRed ), [ 0, 0, 0.99 ], null, [ 1, 3, 1 ]],
  79745. ],
  79746. Y: [
  79747. [ new Line( CircleGeometry( 1, 0.5 ), matLineGreen ), null, [ 0, 0, - Math.PI / 2 ]],
  79748. [ new Mesh( new OctahedronBufferGeometry( 0.04, 0 ), matGreen ), [ 0, 0, 0.99 ], null, [ 3, 1, 1 ]],
  79749. ],
  79750. Z: [
  79751. [ new Line( CircleGeometry( 1, 0.5 ), matLineBlue ), null, [ 0, Math.PI / 2, 0 ]],
  79752. [ new Mesh( new OctahedronBufferGeometry( 0.04, 0 ), matBlue ), [ 0.99, 0, 0 ], null, [ 1, 3, 1 ]],
  79753. ],
  79754. E: [
  79755. [ new Line( CircleGeometry( 1.25, 1 ), matLineYellowTransparent ), null, [ 0, Math.PI / 2, 0 ]],
  79756. [ 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 ]],
  79757. [ 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 ]],
  79758. [ 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 ]],
  79759. [ new Mesh( new CylinderBufferGeometry( 0.03, 0, 0.15, 4, 1, false ), matLineYellowTransparent ), [ 0, 1.17, 0 ], [ 0, 0, 0 ], [ 1, 1, 0.001 ]],
  79760. ],
  79761. XYZE: [
  79762. [ new Line( CircleGeometry( 1, 1 ), matLineGray ), null, [ 0, Math.PI / 2, 0 ]]
  79763. ]
  79764. };
  79765. var helperRotate = {
  79766. AXIS: [
  79767. [ new Line( lineGeometry, matHelper.clone() ), [ - 1e3, 0, 0 ], null, [ 1e6, 1, 1 ], 'helper' ]
  79768. ]
  79769. };
  79770. var pickerRotate = {
  79771. X: [
  79772. [ new Mesh( new TorusBufferGeometry( 1, 0.1, 4, 24 ), matInvisible ), [ 0, 0, 0 ], [ 0, - Math.PI / 2, - Math.PI / 2 ]],
  79773. ],
  79774. Y: [
  79775. [ new Mesh( new TorusBufferGeometry( 1, 0.1, 4, 24 ), matInvisible ), [ 0, 0, 0 ], [ Math.PI / 2, 0, 0 ]],
  79776. ],
  79777. Z: [
  79778. [ new Mesh( new TorusBufferGeometry( 1, 0.1, 4, 24 ), matInvisible ), [ 0, 0, 0 ], [ 0, 0, - Math.PI / 2 ]],
  79779. ],
  79780. E: [
  79781. [ new Mesh( new TorusBufferGeometry( 1.25, 0.1, 2, 24 ), matInvisible ) ]
  79782. ],
  79783. XYZE: [
  79784. [ new Mesh( new SphereBufferGeometry( 0.7, 10, 8 ), matInvisible ) ]
  79785. ]
  79786. };
  79787. var gizmoScale = {
  79788. X: [
  79789. [ new Mesh( scaleHandleGeometry, matRed ), [ 0.8, 0, 0 ], [ 0, 0, - Math.PI / 2 ]],
  79790. [ new Line( lineGeometry, matLineRed ), null, null, [ 0.8, 1, 1 ]]
  79791. ],
  79792. Y: [
  79793. [ new Mesh( scaleHandleGeometry, matGreen ), [ 0, 0.8, 0 ]],
  79794. [ new Line( lineGeometry, matLineGreen ), null, [ 0, 0, Math.PI / 2 ], [ 0.8, 1, 1 ]]
  79795. ],
  79796. Z: [
  79797. [ new Mesh( scaleHandleGeometry, matBlue ), [ 0, 0, 0.8 ], [ Math.PI / 2, 0, 0 ]],
  79798. [ new Line( lineGeometry, matLineBlue ), null, [ 0, - Math.PI / 2, 0 ], [ 0.8, 1, 1 ]]
  79799. ],
  79800. XY: [
  79801. [ new Mesh( scaleHandleGeometry, matYellowTransparent ), [ 0.85, 0.85, 0 ], null, [ 2, 2, 0.2 ]],
  79802. [ new Line( lineGeometry, matLineYellow ), [ 0.855, 0.98, 0 ], null, [ 0.125, 1, 1 ]],
  79803. [ new Line( lineGeometry, matLineYellow ), [ 0.98, 0.855, 0 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]]
  79804. ],
  79805. /* YZ: [
  79806. [ new THREE.Mesh( scaleHandleGeometry, matCyanTransparent ), [ 0, 0.85, 0.85 ], null, [ 0.2, 2, 2 ]],
  79807. [ new THREE.Line( lineGeometry, matLineCyan ), [ 0, 0.855, 0.98 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]],
  79808. [ new THREE.Line( lineGeometry, matLineCyan ), [ 0, 0.98, 0.855 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
  79809. ],
  79810. XZ: [
  79811. [ new THREE.Mesh( scaleHandleGeometry, matMagentaTransparent ), [ 0.85, 0, 0.85 ], null, [ 2, 0.2, 2 ]],
  79812. [ new THREE.Line( lineGeometry, matLineMagenta ), [ 0.855, 0, 0.98 ], null, [ 0.125, 1, 1 ]],
  79813. [ new THREE.Line( lineGeometry, matLineMagenta ), [ 0.98, 0, 0.855 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
  79814. ],
  79815. XYZX: [
  79816. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransparent.clone() ), [ 1.1, 0, 0 ]],
  79817. ],*/
  79818. XYZY: [
  79819. [ new Mesh( new BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransparent.clone() ), [ 0, 1.1, 0 ]],
  79820. ]/* ,
  79821. XYZZ: [
  79822. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransparent.clone() ), [ 0, 0, 1.1 ]],
  79823. ] */
  79824. };
  79825. var pickerScale = {
  79826. X: [
  79827. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 0.8, 4, 1, false ), matInvisible ), [ 0.5, 0, 0 ], [ 0, 0, - Math.PI / 2 ]]
  79828. ],
  79829. Y: [
  79830. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 0.8, 4, 1, false ), matInvisible ), [ 0, 0.5, 0 ]]
  79831. ],
  79832. Z: [
  79833. [ new Mesh( new CylinderBufferGeometry( 0.2, 0, 0.8, 4, 1, false ), matInvisible ), [ 0, 0, 0.5 ], [ Math.PI / 2, 0, 0 ]]
  79834. ],
  79835. XY: [
  79836. [ new Mesh( scaleHandleGeometry, matInvisible ), [ 0.85, 0.85, 0 ], null, [ 3, 3, 0.2 ]],
  79837. ],
  79838. /*YZ: [
  79839. [ new THREE.Mesh( scaleHandleGeometry, matInvisible ), [ 0, 0.85, 0.85 ], null, [ 0.2, 3, 3 ]],
  79840. ],
  79841. XZ: [
  79842. [ new THREE.Mesh( scaleHandleGeometry, matInvisible ), [ 0.85, 0, 0.85 ], null, [ 3, 0.2, 3 ]],
  79843. ],
  79844. XYZX: [
  79845. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.2, 0.2, 0.2 ), matInvisible ), [ 1.1, 0, 0 ]],
  79846. ],*/
  79847. XYZY: [
  79848. [ new Mesh( new BoxBufferGeometry( 0.2, 0.2, 0.2 ), matInvisible ), [ 0, 1.1, 0 ]],
  79849. ]/* ,
  79850. XYZZ: [
  79851. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.2, 0.2, 0.2 ), matInvisible ), [ 0, 0, 1.1 ]],
  79852. ] */
  79853. };
  79854. var helperScale = {
  79855. X: [
  79856. [ new Line( lineGeometry, matHelper.clone() ), [ - 1e3, 0, 0 ], null, [ 1e6, 1, 1 ], 'helper' ]
  79857. ],
  79858. Y: [
  79859. [ new Line( lineGeometry, matHelper.clone() ), [ 0, - 1e3, 0 ], [ 0, 0, Math.PI / 2 ], [ 1e6, 1, 1 ], 'helper' ]
  79860. ],
  79861. Z: [
  79862. [ new Line( lineGeometry, matHelper.clone() ), [ 0, 0, - 1e3 ], [ 0, - Math.PI / 2, 0 ], [ 1e6, 1, 1 ], 'helper' ]
  79863. ]
  79864. };
  79865. // Creates an THREE.Object3D with gizmos described in custom hierarchy definition.
  79866. var setupGizmo = function ( gizmoMap ) {
  79867. var gizmo = new Object3D();
  79868. for ( var name in gizmoMap ) {
  79869. for ( var i = gizmoMap[ name ].length; i --; ) {
  79870. var object = gizmoMap[ name ][ i ][ 0 ].clone();
  79871. var position = gizmoMap[ name ][ i ][ 1 ];
  79872. var rotation = gizmoMap[ name ][ i ][ 2 ];
  79873. var scale = gizmoMap[ name ][ i ][ 3 ];
  79874. var tag = gizmoMap[ name ][ i ][ 4 ];
  79875. // name and tag properties are essential for picking and updating logic.
  79876. object.name = name;
  79877. object.tag = tag;
  79878. if ( position ) {
  79879. object.position.set( position[ 0 ], position[ 1 ], position[ 2 ] );
  79880. }
  79881. if ( rotation ) {
  79882. object.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ] );
  79883. }
  79884. if ( scale ) {
  79885. object.scale.set( scale[ 0 ], scale[ 1 ], scale[ 2 ] );
  79886. }
  79887. object.updateMatrix();
  79888. var tempGeometry = object.geometry.clone();
  79889. tempGeometry.applyMatrix4( object.matrix );
  79890. object.geometry = tempGeometry;
  79891. object.renderOrder = Infinity;
  79892. object.position.set( 0, 0, 0 );
  79893. object.rotation.set( 0, 0, 0 );
  79894. object.scale.set( 1, 1, 1 );
  79895. gizmo.add( object );
  79896. }
  79897. }
  79898. return gizmo;
  79899. };
  79900. // Reusable utility variables
  79901. var tempVector = new Vector3( 0, 0, 0 );
  79902. var tempEuler = new Euler();
  79903. var alignVector = new Vector3( 0, 1, 0 );
  79904. var zeroVector = new Vector3( 0, 0, 0 );
  79905. var lookAtMatrix = new Matrix4();
  79906. var tempQuaternion = new Quaternion();
  79907. var tempQuaternion2 = new Quaternion();
  79908. var identityQuaternion = new Quaternion();
  79909. var unitX = new Vector3( 1, 0, 0 );
  79910. var unitY = new Vector3( 0, 1, 0 );
  79911. var unitZ = new Vector3( 0, 0, 1 );
  79912. // Gizmo creation
  79913. this.gizmo = {};
  79914. this.picker = {};
  79915. this.helper = {};
  79916. this.add( this.gizmo[ "translate" ] = setupGizmo( gizmoTranslate ) );
  79917. this.add( this.gizmo[ "rotate" ] = setupGizmo( gizmoRotate ) );
  79918. this.add( this.gizmo[ "scale" ] = setupGizmo( gizmoScale ) );
  79919. this.add( this.picker[ "translate" ] = setupGizmo( pickerTranslate ) );
  79920. this.add( this.picker[ "rotate" ] = setupGizmo( pickerRotate ) );
  79921. this.add( this.picker[ "scale" ] = setupGizmo( pickerScale ) );
  79922. this.add( this.helper[ "translate" ] = setupGizmo( helperTranslate ) );
  79923. this.add( this.helper[ "rotate" ] = setupGizmo( helperRotate ) );
  79924. this.add( this.helper[ "scale" ] = setupGizmo( helperScale ) );
  79925. // Pickers should be hidden always
  79926. this.picker[ "translate" ].visible = false;
  79927. this.picker[ "rotate" ].visible = false;
  79928. this.picker[ "scale" ].visible = false;
  79929. // updateMatrixWorld will update transformations and appearance of individual handles
  79930. this.updateMatrixWorld = function () {
  79931. var space = this.space;
  79932. if ( this.mode === 'scale' ) space = 'local'; // scale always oriented to local rotation
  79933. var quaternion = space === "local" ? this.worldQuaternion : identityQuaternion;
  79934. // Show only gizmos for current transform mode
  79935. this.gizmo[ "translate" ].visible = this.mode === "translate";
  79936. this.gizmo[ "rotate" ].visible = this.mode === "rotate";
  79937. this.gizmo[ "scale" ].visible = this.mode === "scale";
  79938. this.helper[ "translate" ].visible = this.mode === "translate";
  79939. this.helper[ "rotate" ].visible = this.mode === "rotate";
  79940. this.helper[ "scale" ].visible = this.mode === "scale";
  79941. var handles = [];
  79942. handles = handles.concat( this.picker[ this.mode ].children );
  79943. handles = handles.concat( this.gizmo[ this.mode ].children );
  79944. handles = handles.concat( this.helper[ this.mode ].children );
  79945. for ( var i = 0; i < handles.length; i ++ ) {
  79946. var handle = handles[ i ];
  79947. let visible = true;
  79948. // hide aligned to camera
  79949. handle.rotation.set( 0, 0, 0 );
  79950. handle.position.copy( this.worldPosition );
  79951. var eyeDistance = this.worldPosition.distanceTo( this.cameraPosition );
  79952. //俯视图的透视和距离无关,因此在两种相机切换切换时大小过渡比较困难
  79953. /* if(player.mode == "transitioning" && (player.modeTran.split('-')[0] == "floorplan" || player.modeTran.split('-')[1] == "floorplan")){
  79954. eyeDistance = Math.min(eyeDistance, 6.5)//从一开始很小的距离过渡到俯视图50的高度,会变得很大。
  79955. }else if(player.mode == "floorplan"){
  79956. var flcamera = player.cameraControls.cameras.floorplan;
  79957. eyeDistance = (flcamera.right - flcamera.left ) / flcamera.aspect ;
  79958. }
  79959. */
  79960. handle.scale.set( 1, 1, 1 ).multiplyScalar( eyeDistance * this.size / 7 );
  79961. // TODO: simplify helpers and consider decoupling from gizmo
  79962. if ( handle.tag === 'helper' ) {
  79963. visible = false;
  79964. if ( handle.name === 'AXIS' ) {
  79965. handle.position.copy( this.worldPositionStart );
  79966. visible = !!this.axis;
  79967. if ( this.axis === 'X' ) {
  79968. tempQuaternion.setFromEuler( tempEuler.set( 0, 0, 0 ) );
  79969. handle.quaternion.copy( quaternion ).multiply( tempQuaternion );
  79970. if ( Math.abs( alignVector.copy( unitX ).applyQuaternion( quaternion ).dot( this.eye ) ) > 0.9 ) {
  79971. visible = false;
  79972. }
  79973. }
  79974. if ( this.axis === 'Y' ) {
  79975. tempQuaternion.setFromEuler( tempEuler.set( 0, 0, Math.PI / 2 ) );
  79976. handle.quaternion.copy( quaternion ).multiply( tempQuaternion );
  79977. if ( Math.abs( alignVector.copy( unitY ).applyQuaternion( quaternion ).dot( this.eye ) ) > 0.9 ) {
  79978. visible = false;
  79979. }
  79980. }
  79981. if ( this.axis === 'Z' ) {
  79982. tempQuaternion.setFromEuler( tempEuler.set( 0, Math.PI / 2, 0 ) );
  79983. handle.quaternion.copy( quaternion ).multiply( tempQuaternion );
  79984. if ( Math.abs( alignVector.copy( unitZ ).applyQuaternion( quaternion ).dot( this.eye ) ) > 0.9 ) {
  79985. visible = false;
  79986. }
  79987. }
  79988. if ( this.axis === 'XYZE' ) {
  79989. tempQuaternion.setFromEuler( tempEuler.set( 0, Math.PI / 2, 0 ) );
  79990. alignVector.copy( this.rotationAxis );
  79991. handle.quaternion.setFromRotationMatrix( lookAtMatrix.lookAt( zeroVector, alignVector, unitY ) );
  79992. handle.quaternion.multiply( tempQuaternion );
  79993. visible = this.dragging;
  79994. }
  79995. if ( this.axis === 'E' ) {
  79996. visible = false;
  79997. }
  79998. } else if ( handle.name === 'START' ) {
  79999. handle.position.copy( this.worldPositionStart );
  80000. visible = this.dragging;
  80001. } else if ( handle.name === 'END' ) {
  80002. handle.position.copy( this.worldPosition );
  80003. visible = this.dragging;
  80004. } else if ( handle.name === 'DELTA' ) {
  80005. handle.position.copy( this.worldPositionStart );
  80006. handle.quaternion.copy( this.worldQuaternionStart );
  80007. tempVector.set( 1e-10, 1e-10, 1e-10 ).add( this.worldPositionStart ).sub( this.worldPosition ).multiplyScalar( - 1 );
  80008. tempVector.applyQuaternion( this.worldQuaternionStart.clone().invert() );
  80009. handle.scale.copy( tempVector );
  80010. visible = this.dragging;
  80011. } else {
  80012. handle.quaternion.copy( quaternion );
  80013. if ( this.dragging ) {
  80014. handle.position.copy( this.worldPositionStart );
  80015. } else {
  80016. handle.position.copy( this.worldPosition );
  80017. }
  80018. if ( this.axis ) {
  80019. visible = this.axis.search( handle.name ) !== - 1;
  80020. }
  80021. }
  80022. // If updating helper, skip rest of the loop
  80023. viewer.updateVisible(handle, 'hidden', !!visible);
  80024. continue;
  80025. }
  80026. // Align handles to current local or world rotation
  80027. handle.quaternion.copy( quaternion );
  80028. if ( this.mode === 'translate' || this.mode === 'scale' ) {
  80029. // Hide translate and scale axis facing the camera
  80030. var AXIS_HIDE_TRESHOLD = 0.99;
  80031. var PLANE_HIDE_TRESHOLD = 0.2;
  80032. var AXIS_FLIP_TRESHOLD = 0.0;
  80033. if(options.dontHideWhenFaceCamera){//xzw add
  80034. //正对镜头时不隐藏箭头
  80035. }else {
  80036. if ( handle.name === 'X' || handle.name === 'XYZX' ) {
  80037. if ( Math.abs( alignVector.copy( unitX ).applyQuaternion( quaternion ).dot( this.eye ) ) > AXIS_HIDE_TRESHOLD ) {
  80038. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80039. visible = false;
  80040. }
  80041. }
  80042. if ( handle.name === 'Y' || handle.name === 'XYZY' ) {
  80043. if ( Math.abs( alignVector.copy( unitY ).applyQuaternion( quaternion ).dot( this.eye ) ) > AXIS_HIDE_TRESHOLD ) {
  80044. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80045. visible = false;
  80046. }
  80047. }
  80048. if ( handle.name === 'Z' || handle.name === 'XYZZ' ) {
  80049. if ( Math.abs( alignVector.copy( unitZ ).applyQuaternion( quaternion ).dot( this.eye ) ) > AXIS_HIDE_TRESHOLD ) {
  80050. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80051. visible = false;
  80052. }
  80053. }
  80054. if ( handle.name === 'XY' ) {
  80055. if ( Math.abs( alignVector.copy( unitZ ).applyQuaternion( quaternion ).dot( this.eye ) ) < PLANE_HIDE_TRESHOLD ) {
  80056. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80057. visible = false;
  80058. }
  80059. }
  80060. if ( handle.name === 'YZ' ) {
  80061. if ( Math.abs( alignVector.copy( unitX ).applyQuaternion( quaternion ).dot( this.eye ) ) < PLANE_HIDE_TRESHOLD ) {
  80062. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80063. visible = false;
  80064. }
  80065. }
  80066. if ( handle.name === 'XZ' ) {
  80067. if ( Math.abs( alignVector.copy( unitY ).applyQuaternion( quaternion ).dot( this.eye ) ) < PLANE_HIDE_TRESHOLD ) {
  80068. handle.scale.set( 1e-10, 1e-10, 1e-10 );
  80069. visible = false;
  80070. }
  80071. }
  80072. }
  80073. // Flip translate and scale axis ocluded behind another axis
  80074. //xzw 改 去掉反向箭头
  80075. if ( handle.name.search( 'X' ) !== - 1 ) {
  80076. if ( alignVector.copy( unitX ).applyQuaternion( quaternion ).dot( this.eye ) < AXIS_FLIP_TRESHOLD ) {
  80077. /* if ( handle.tag === 'fwd' ) {
  80078. handle.visible = false;
  80079. } else {
  80080. handle.scale.x *= - 1;
  80081. }
  80082. } else if ( handle.tag === 'bwd' ) {
  80083. handle.visible = false;*/
  80084. handle.scale.x *= - 1;
  80085. }
  80086. }
  80087. if ( handle.name.search( 'Y' ) !== - 1 ) {
  80088. if ( alignVector.copy( unitY ).applyQuaternion( quaternion ).dot( this.eye ) < AXIS_FLIP_TRESHOLD ) {
  80089. /* if ( handle.tag === 'fwd' ) {
  80090. handle.visible = false;
  80091. } else {
  80092. handle.scale.y *= - 1;
  80093. }
  80094. } else if ( handle.tag === 'bwd' ) {
  80095. handle.visible = false;
  80096. */
  80097. handle.scale.y *= - 1;
  80098. }
  80099. }
  80100. if ( handle.name.search( 'Z' ) !== - 1 ) {
  80101. if ( alignVector.copy( unitZ ).applyQuaternion( quaternion ).dot( this.eye ) < AXIS_FLIP_TRESHOLD ) {
  80102. /* if ( handle.tag === 'fwd' ) {
  80103. handle.visible = false;
  80104. } else {
  80105. handle.scale.z *= - 1;
  80106. }
  80107. } else if ( handle.tag === 'bwd' ) {
  80108. handle.visible = false; */
  80109. handle.scale.z *= - 1;
  80110. }
  80111. }
  80112. } else if ( this.mode === 'rotate' ) {
  80113. // Align handles to current local or world rotation
  80114. tempQuaternion2.copy( quaternion );
  80115. alignVector.copy( this.eye ).applyQuaternion( tempQuaternion.copy( quaternion ).invert() );
  80116. if ( handle.name.search( "E" ) !== - 1 ) {
  80117. handle.quaternion.setFromRotationMatrix( lookAtMatrix.lookAt( this.eye, zeroVector, unitY ) );
  80118. }
  80119. if ( handle.name === 'X' ) {
  80120. tempQuaternion.setFromAxisAngle( unitX, Math.atan2( - alignVector.y, alignVector.z ) );
  80121. tempQuaternion.multiplyQuaternions( tempQuaternion2, tempQuaternion );
  80122. handle.quaternion.copy( tempQuaternion );
  80123. }
  80124. if ( handle.name === 'Y' ) {
  80125. tempQuaternion.setFromAxisAngle( unitY, Math.atan2( alignVector.x, alignVector.z ) );
  80126. tempQuaternion.multiplyQuaternions( tempQuaternion2, tempQuaternion );
  80127. handle.quaternion.copy( tempQuaternion );
  80128. }
  80129. if ( handle.name === 'Z' ) {
  80130. tempQuaternion.setFromAxisAngle( unitZ, Math.atan2( alignVector.y, alignVector.x ) );
  80131. tempQuaternion.multiplyQuaternions( tempQuaternion2, tempQuaternion );
  80132. handle.quaternion.copy( tempQuaternion );
  80133. }
  80134. }
  80135. // Hide disabled axes
  80136. visible = visible && ( handle.name.indexOf( "X" ) === - 1 || this.showX );
  80137. visible = visible && ( handle.name.indexOf( "Y" ) === - 1 || this.showY );
  80138. visible = visible && ( handle.name.indexOf( "Z" ) === - 1 || this.showZ );
  80139. visible = visible && ( handle.name.indexOf( "E" ) === - 1 || ( this.showX && this.showY && this.showZ ) );
  80140. viewer.updateVisible(handle, 'hidden', !!visible);
  80141. // highlight selected axis
  80142. handle.material._opacity = handle.material._opacity || handle.material.opacity;
  80143. handle.material._color = handle.material._color || handle.material.color.clone();
  80144. handle.material.color.copy( handle.material._color );
  80145. handle.material.opacity = handle.material._opacity;
  80146. if ( ! this.enabled ) {
  80147. handle.material.opacity *= 0.5;
  80148. handle.material.color.lerp( new Color( 1, 1, 1 ), 0.5 );
  80149. } else if ( this.axis ) {
  80150. if ( handle.name === this.axis ) {
  80151. handle.material.opacity = 1.0;
  80152. handle.material.color.lerp( new Color( 1, 1, 1 ), 0.5 );
  80153. } else if ( this.axis.split( '' ).some( function ( a ) {
  80154. return handle.name === a;
  80155. } ) ) {
  80156. handle.material.opacity = 1.0;
  80157. handle.material.color.lerp( new Color( 1, 1, 1 ), 0.5 );
  80158. } else {
  80159. handle.material.opacity *= 0.25;
  80160. handle.material.color.lerp( new Color( 1, 1, 1 ), 0.5 );
  80161. }
  80162. }
  80163. }
  80164. Object3D.prototype.updateMatrixWorld.call( this );
  80165. };
  80166. };
  80167. /* var TransformControlsLines = function (options) {
  80168. THREE.Object3D.call( this)
  80169. let label1 = new Label2D({ innerHTML:`<div>与相机水平距离</div>` , domElement:$("#otherLabels")[0] ,autoUpdate:true })
  80170. let label2 = new Label2D({ innerHTML:`<div>与相机高度差</div>` , domElement:$("#otherLabels")[0] ,autoUpdate:true })
  80171. let css = {'opacity': 0.7, 'color': '#07fceb', transform:'translate(-50%, -50%)'}
  80172. label1.elem.css(css);
  80173. label2.elem.css(css)
  80174. //for(let i=0;i<2;i++){
  80175. // let line = LineDraw.createLine([new THREE.THREE.Vector3, new THREE.THREE.Vector3],{color:'#07fceb', opacity:0.7 })
  80176. // this.add(line)
  80177. //}
  80178. this.updateTransform = function(object){
  80179. object = object || this.parent.object;
  80180. let A = player.position.clone(); //当前相机位置
  80181. let B = object.position //物体位置
  80182. let C = B.clone().setY(A.y); //物体在相机的高度的位置
  80183. let D = A.clone().setY(B.y); //相机在物体的高度的位置
  80184. //LineDraw.moveLine(this.children[0], [B, C]) // 垂直线
  80185. //LineDraw.moveLine(this.children[1], [D, B]) // 水平线
  80186. let dis1 = toPrecision(D.distanceTo(B),1)
  80187. let dis2 = C.y - B.y
  80188. label1.elem.text('与相机水平距离: '+dis1+'米')
  80189. label2.elem.text('在相机之'+ (dis2>0?'下' : '上') +' :'+ toPrecision(dis2 , 1) +'米')
  80190. label1.setPos(new THREE.THREE.Vector3().addVectors(D,B).multiplyScalar(0.5))
  80191. label2.setPos(new THREE.THREE.Vector3().addVectors(B,C).multiplyScalar(0.5))
  80192. }
  80193. this.setVisible = (v,reason)=>{
  80194. label1.setVisible(v, reason || 'unvisi')
  80195. label2.setVisible(v, reason || 'unvisi')
  80196. this.visible = label1.visible
  80197. if(this.visible){
  80198. this.updateTransform()
  80199. }
  80200. }
  80201. this.setVisible(false)
  80202. player.on("mode.changing",(currentMode, mode, pano, duration)=>{
  80203. if(mode != 'panorama'){
  80204. this.setVisible(false, 'isPanorama')
  80205. }else{
  80206. this.setVisible(true, 'isPanorama')
  80207. }
  80208. })
  80209. player.on("flying.started",( )=>{
  80210. this.setVisible(false, 'flying')
  80211. })
  80212. player.on("flying.ended",( )=>{
  80213. this.setVisible(true, 'flying')
  80214. })
  80215. }
  80216. */
  80217. var TransformControlsPlane = function (options) {
  80218. 'use strict';
  80219. Mesh.call( this,
  80220. new PlaneBufferGeometry( 100000, 100000, 2, 2 ),
  80221. new MeshBasicMaterial( { color: "#ff0000", visible: false, wireframe: false, side: DoubleSide, transparent: true, opacity: 0.2 } )
  80222. );
  80223. this.type = 'TransformControlsPlane';
  80224. var unitX = new Vector3( 1, 0, 0 );
  80225. var unitY = new Vector3( 0, 1, 0 );
  80226. var unitZ = new Vector3( 0, 0, 1 );
  80227. var tempVector = new Vector3();
  80228. var dirVector = new Vector3();
  80229. var alignVector = new Vector3();
  80230. var tempMatrix = new Matrix4();
  80231. var identityQuaternion = new Quaternion();
  80232. this.updateMatrixWorld = function () {
  80233. var space = this.space;
  80234. this.position.copy( this.worldPosition );
  80235. if ( this.mode === 'scale' ) space = 'local'; // scale always oriented to local rotation
  80236. unitX.set( 1, 0, 0 ).applyQuaternion( space === "local" ? this.worldQuaternion : identityQuaternion );
  80237. unitY.set( 0, 1, 0 ).applyQuaternion( space === "local" ? this.worldQuaternion : identityQuaternion );
  80238. unitZ.set( 0, 0, 1 ).applyQuaternion( space === "local" ? this.worldQuaternion : identityQuaternion );
  80239. // Align the plane for current transform mode, axis and space.
  80240. alignVector.copy( unitY );
  80241. switch ( this.mode ) {
  80242. case 'translate':
  80243. case 'scale':
  80244. switch ( this.axis ) {
  80245. case 'X':
  80246. alignVector.copy( this.eye ).cross( unitX );
  80247. dirVector.copy( unitX ).cross( alignVector );
  80248. break;
  80249. case 'Y':
  80250. alignVector.copy( this.eye ).cross( unitY );
  80251. dirVector.copy( unitY ).cross( alignVector );
  80252. break;
  80253. case 'Z':
  80254. alignVector.copy( this.eye ).cross( unitZ );
  80255. dirVector.copy( unitZ ).cross( alignVector );
  80256. break;
  80257. case 'XY':
  80258. dirVector.copy( unitZ );
  80259. break;
  80260. case 'YZ':
  80261. dirVector.copy( unitX );
  80262. break;
  80263. case 'XZ':
  80264. alignVector.copy( unitZ );
  80265. dirVector.copy( unitY );
  80266. break;
  80267. case 'XYZ':
  80268. case 'E':
  80269. default: //xzw add for scale xyzz
  80270. dirVector.set( 0, 0, 0 );
  80271. break;
  80272. }
  80273. break;
  80274. case 'rotate':
  80275. default:
  80276. // special case for rotate
  80277. dirVector.set( 0, 0, 0 );
  80278. }
  80279. if ( dirVector.length() === 0 ) {
  80280. // If in rotate mode, make the plane parallel to camera
  80281. this.quaternion.copy( this.cameraQuaternion );
  80282. } else {
  80283. tempMatrix.lookAt( tempVector.set( 0, 0, 0 ), dirVector, alignVector );
  80284. this.quaternion.setFromRotationMatrix( tempMatrix );
  80285. }
  80286. Object3D.prototype.updateMatrixWorld.call( this );
  80287. };
  80288. };
  80289. TransformControls.prototype = Object.assign( Object.create( Object3D.prototype ), {
  80290. constructor: TransformControls,
  80291. isTransformControls: true
  80292. } );
  80293. TransformControlsGizmo.prototype = Object.assign( Object.create( Object3D.prototype ), {
  80294. constructor: TransformControlsGizmo,
  80295. isTransformControlsGizmo: true
  80296. } );
  80297. TransformControlsPlane.prototype = Object.assign( Object.create( Mesh.prototype ), {
  80298. constructor: TransformControlsPlane,
  80299. isTransformControlsPlane: true
  80300. } );
  80301. /*
  80302. 备注:
  80303. //这里虽然 使坐标轴在boundingBox中心
  80304. boundingBox && this.object.boundingBox.getCenter(worldPosition).applyMatrix4(this.object.matrixWorld);
  80305. 但是旋转中心并不是这个坐标轴显示的位置,需要再执行 MergeEditor.maintainBoundXY()才能维持在这个中心
  80306. */
  80307. const texLoader$8 = new TextureLoader();
  80308. texLoader$8.crossOrigin = "anonymous";
  80309. const viewportProps$1 = [{
  80310. left:0,
  80311. bottom:0,
  80312. width: 0.5,height:1,
  80313. name : 'top',
  80314. axis:["x","y"],
  80315. direction : new Vector3(0,0,-1), //镜头朝向
  80316. active: true,
  80317. //相机位置在z轴正向
  80318. limitBound: new Box3(new Vector3(-Infinity,-Infinity, 1),new Vector3(Infinity,Infinity,5000)), //在地面以上
  80319. margin:{x:50, y:150} ,
  80320. },
  80321. {
  80322. left:0.5,
  80323. bottom:0,
  80324. width: 0.5,height:1,
  80325. name : 'right',
  80326. axis:["y","z"],
  80327. direction : new Vector3(1,0,0),
  80328. active: true,
  80329. //相机位置在x轴负向 右下角屏
  80330. viewContainsPoints:[new Vector3(0,0,0)],
  80331. margin:{x:300, y:250} ,
  80332. } ];
  80333. let MergeEditor = {
  80334. bus:new EventDispatcher(),
  80335. SplitScreen : new SplitScreen(),
  80336. init(){
  80337. {
  80338. let ground = this.ground = new InfiniteGridHelper(1, 10000, new Color('#fff'), 10000, 0.2, 0.3);
  80339. viewer.scene.scene.add(ground);
  80340. //再加两条线否则在正侧边看不到
  80341. let line1 = LineDraw.createLine([new Vector3(-10000, 0, 0),new Vector3(10000, 0, 0) ], {color:'#666', dontAlwaysSeen:true});
  80342. let line2 = LineDraw.createLine([new Vector3(0, -10000, 0),new Vector3(0, 10000, 0) ], {mat:line1.material});
  80343. ground.renderOrder = Potree.config.renderOrders.model + 1;//line1.renderOrder + 1 //要比模型低,否则模型透明时效果不对
  80344. ground.add(line1);
  80345. ground.add(line2);
  80346. ground.material.polygonOffset = true; //多边形偏移(视觉上没有移动模型位置),防止闪烁
  80347. ground.material.polygonOffsetFactor = 100; //多边形偏移因子
  80348. ground.material.polygonOffsetUnits = 10; //多边形偏移单位
  80349. ground.material.depthWrite = false;
  80350. //ground.material.depthTest = false
  80351. line1.material.polygonOffset = true;
  80352. line1.material.polygonOffsetFactor = 130;
  80353. line1.material.polygonOffsetUnits = 10;
  80354. line1.material.depthWrite = false;
  80355. //见笔记:透明物体的材质设置
  80356. }
  80357. {
  80358. this.transformControls = new TransformControls(viewer.mainViewport.camera, viewer.renderArea,{
  80359. dontHideWhenFaceCamera: true,
  80360. /* scaleAxis: ["x", "y"],
  80361. //隐藏了z轴。虽然参数没用上
  80362. NoScaleZ: true //整体缩放时只缩放xy轴。 */
  80363. });
  80364. //this.transformControls.space = 'local'//为了在当前方向上平移
  80365. this.transformControls.setSize(1.5);
  80366. viewer.scene.scene.add(this.transformControls);
  80367. }
  80368. viewer.setControls(viewer.orbitControls);
  80369. //viewer.mainViewport.view.fixZWhenPan = true
  80370. viewer.orbitControls.constantlyForward = true;
  80371. viewer.addEventListener('global_single_click',(e)=>{
  80372. if( viewer.scene.cameraAnimations.some(c=>c.onUpdate) //正在播放
  80373. || e.drag && e.drag.notPressMouse //在加测量线
  80374. || viewer.mainViewport.view.isFlying() //有其他校准
  80375. || this.split //分屏中
  80376. || e.clickElement //触发别的点击事件,如测量时click marker /* && e.clickElement != e.intersect.object */
  80377. ){
  80378. return
  80379. }
  80380. if(e.intersect){
  80381. let object = e.intersect.object || e.intersect.pointcloud;
  80382. let objects = this.getAllObjects();
  80383. if(objects.includes(object)){
  80384. this.selectModel(object);
  80385. }else {
  80386. //if(!viewer.inputHandler.selection[0]){//正在平移和旋转,不允许取消
  80387. this.selectModel(null);
  80388. //}
  80389. }
  80390. }else {
  80391. //if(!viewer.inputHandler.selection[0]){
  80392. this.selectModel(null);
  80393. //}
  80394. }
  80395. });
  80396. viewer.inputHandler.addEventListener('keydown', (e)=>{
  80397. if((e.event.key).toLowerCase() == "h" ){
  80398. this.fadeOutlineAuto = !this.fadeOutlineAuto;
  80399. this.showModelOutline(this.selected,!!this.selected);
  80400. }
  80401. });
  80402. viewer.ssaaRenderPass.enabled = false;
  80403. viewer.outlinePass.enabled = true;
  80404. //Potree.settings.intersectWhenHover = false
  80405. //viewer.updateVisible(viewer.reticule, 'force', false)
  80406. viewer.mainViewport.camera.near = 0.05; // too small will result in z-fighting
  80407. viewer.addEventListener('updateModelBound', (e)=>{
  80408. if(this.split){
  80409. this.SplitScreen.updateCameraOutOfModel(/* this.selected && [this.selected] */);
  80410. }
  80411. });
  80412. {//校准页面拖拽
  80413. let dragInfo;
  80414. let drag = (e)=>{
  80415. if(this.split && this.selected && this.transformState && (e.dragViewport.name == 'top' || this.transformState == 'translate') ){
  80416. if(e.type == 'global_mousedown' ){ //开始
  80417. //if((e.intersect.object || e.intersect.pointcloud) == this.selected){
  80418. if(e.intersect.pointclouds.includes(this.selected) || e.intersect.allElements.some(e=>e.object == this.selected)){
  80419. dragInfo = {};
  80420. }
  80421. }
  80422. if(e.type == 'global_drag' && dragInfo ){
  80423. if(this.transformState == 'translate'){
  80424. let moveVec = Potree.Utils.getOrthoCameraMoveVec(e.drag.pointerDelta, e.dragViewport.camera );//最近一次移动向量
  80425. this.selected.position.add(moveVec);
  80426. this.selected.dispatchEvent("position_changed");
  80427. }else if(this.transformState == 'rotate'){
  80428. let vec = new Vector3().subVectors(e.intersect.orthoIntersect || e.intersect.location, this.selected.boundCenter).setZ(0);
  80429. if(dragInfo.lastVec == void 0){//global_mousedown
  80430. dragInfo.lastVec = vec;
  80431. return
  80432. }
  80433. let angle = math.getAngle(dragInfo.lastVec, vec, 'z');
  80434. dragInfo.lastVec = vec;
  80435. //this.selected.rotation.z += angle //局部
  80436. /* object.quaternion.copy( .setFromAxisAngle( new THREE.Vector3(0,0,1), angle ) );
  80437. object.quaternion.multiply( quaternionStart ).normalize(); */
  80438. let diffQua = new Quaternion().setFromAxisAngle( new Vector3(0,0,1), angle );
  80439. this.selected.quaternion.premultiply(diffQua); //世界
  80440. this.selected.dispatchEvent("rotation_changed");
  80441. }
  80442. return {stopContinue:true}
  80443. }
  80444. }
  80445. };
  80446. viewer.addEventListener('global_mousedown', drag);
  80447. viewer.addEventListener('global_drag', drag, 10);
  80448. viewer.addEventListener('global_mousemove', (e)=>{
  80449. if(this.split && this.transformState && !e.drag && (e.hoverViewport.name == 'top' || this.transformState == 'translate')){
  80450. let mouseover = e.intersect.pointclouds.includes(this.selected) || e.intersect.allElements.some(e=>e.object == this.selected);
  80451. //let mouseover = (e.intersect.object || e.intersect.pointcloud) == this.selected
  80452. if(mouseover){
  80453. if(this.transformState == 'translate'){
  80454. viewer.dispatchEvent({
  80455. type : "CursorChange", action : "add", name:"movePointcloud"
  80456. });
  80457. }else {
  80458. viewer.dispatchEvent({
  80459. type : "CursorChange", action : "add", name:"rotatePointcloud"
  80460. });
  80461. }
  80462. }else {
  80463. this.clearTranCursor();
  80464. }
  80465. }
  80466. });
  80467. viewer.addEventListener('global_drop', (e)=>{
  80468. dragInfo = null;
  80469. this.clearTranCursor();
  80470. });
  80471. }
  80472. },
  80473. clearTranCursor(){
  80474. viewer.dispatchEvent({
  80475. type : "CursorChange", action : "remove", name:"movePointcloud"
  80476. });
  80477. viewer.dispatchEvent({
  80478. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  80479. });
  80480. },
  80481. enterSplit(){
  80482. this.split = true;
  80483. if(this.selected) this.SplitScreen.focusCenter = this.selected.boundCenter; //旋转中心。注意 boundCenter不能直接赋值,否则改变后focusCenter也要改
  80484. else this.SplitScreen.focusCenter = null;
  80485. this.SplitScreen.splitStart(viewportProps$1);
  80486. this.beforeSplit = {
  80487. pointDensity: Potree.settings.pointDensity,
  80488. };
  80489. Potree.settings.pointDensity = 'fourViewports'; //强制降低点云质量
  80490. /* viewer.scene.pointclouds.forEach(e=>{
  80491. e.material.activeAttributeName = "color"
  80492. e.material.useFilterByNormal = true
  80493. }) */
  80494. //取消outline,改点云颜色为和outline一样的颜色
  80495. /* if(this.selected && this.selected.isPointcloud){
  80496. this.showModelOutline(this.selected, false)
  80497. this.selected.material.activeAttributeName = "color"
  80498. this.selected.material.color = viewer.outlinePass.visibleEdgeColor
  80499. } */
  80500. viewer.setControls(viewer.fpControls);
  80501. viewer.viewports.find(e=>e.name == 'right').rotateSide = true;
  80502. viewer.viewports.find(e=>e.name == 'top').alignment = true;
  80503. },
  80504. leaveSplit(){
  80505. this.split = false;
  80506. this.SplitScreen.unSplit();
  80507. viewer.setControls(viewer.orbitControls);
  80508. Potree.settings.pointDensity = this.beforeSplit.pointDensity;
  80509. /* if(this.selected && this.selected.isPointcloud){
  80510. this.showModelOutline(this.selected, true)
  80511. this.selected.material.activeAttributeName = "rgba"
  80512. } */
  80513. },
  80514. rotateSideCamera(angle){
  80515. this.SplitScreen.rotateSideCamera(viewer.viewports.find(e=>e.name == 'right'), angle);
  80516. },
  80517. setTransformState(state){//校准时
  80518. this.transformState = state;
  80519. this.clearTranCursor();
  80520. },
  80521. //---------------------------
  80522. /* writeToHistory(content){
  80523. if(!this.prepareRecord)return;
  80524. this.prepareRecord = false
  80525. this.history.push(content)
  80526. }, */
  80527. //---------------------------
  80528. getAllObjects(){
  80529. return viewer.objs.children.concat(viewer.scene.pointclouds)
  80530. },
  80531. getModel(id){
  80532. let models = this.getAllObjects();
  80533. return models.find(e=>e.dataset_id == id)
  80534. },
  80535. removeModel(model){
  80536. if(this.selected == model) this.selectModel(null);
  80537. let dispose = (e)=>{
  80538. e.geometry && e.geometry.dispose();
  80539. e.material && e.material.dispose();
  80540. };
  80541. if(model.isPointcloud){
  80542. dispose(model);
  80543. viewer.scene.removePointCloud(model);
  80544. }else {
  80545. model.traverse(e=>{
  80546. dispose(e);
  80547. });
  80548. viewer.objs.remove(model);
  80549. }
  80550. },
  80551. selectModel(model, state=true, fitBound, by2d){
  80552. if(!model) {
  80553. model = this.selected;
  80554. state = false;
  80555. }
  80556. if(state){
  80557. if(this.selected){
  80558. if(this.selected == model) return
  80559. else this.selectModel(this.selected, false, fitBound, by2d);
  80560. }
  80561. this.selected = model;
  80562. MergeEditor.focusOn(model, 500, !!fitBound); //通过在场景里点击模型的话,不focus
  80563. this.showModelOutline(model);
  80564. if(model.isPointcloud){
  80565. viewer.outlinePass.edgeStrength = 4;
  80566. }else {
  80567. viewer.outlinePass.edgeStrength = 100;
  80568. }
  80569. //console.log('selectModel', model)
  80570. }else {
  80571. this.showModelOutline(model, false);
  80572. this.selected = null;
  80573. this.transformControls.detach(); //viewer.transformObject(null);
  80574. //console.log('selectModel', null)
  80575. }
  80576. if(!by2d && model){
  80577. model.dispatchEvent({type:'changeSelect', selected : state});
  80578. }
  80579. },
  80580. showModelOutline(model, state){
  80581. if(this.fadeOutlineAuto){
  80582. if(state === false){
  80583. viewer.outlinePass.selectedObjects = [];
  80584. clearTimeout(this.timer);
  80585. return
  80586. }
  80587. viewer.outlinePass.selectedObjects = [model];
  80588. if(this.timer){
  80589. clearTimeout(this.timer);
  80590. }
  80591. this.timer = setTimeout(()=>{
  80592. viewer.outlinePass.selectedObjects = [];
  80593. }, 1000);
  80594. }else {
  80595. if(state === false){
  80596. viewer.outlinePass.selectedObjects = [];
  80597. }else {
  80598. viewer.outlinePass.selectedObjects = [model];
  80599. }
  80600. }
  80601. },
  80602. /* focusOn(object, duration = 400){
  80603. let boundingBox = object.boundingBox.clone().applyMatrix4(object.matrixWorld)
  80604. let center = boundingBox.getCenter(new THREE.Vector3)
  80605. let size = boundingBox.getSize(new THREE.Vector3)
  80606. let maxSize = size.length() //对角线长度
  80607. if(object.isPointcloud){
  80608. maxSize /= 2
  80609. }
  80610. let hfov = cameraLight.getHFOVForCamera(viewer.mainViewport.camera,true)
  80611. let minRadius = maxSize / Math.tan(hfov/2)
  80612. //viewer.mainViewport.view.lookAt(center)
  80613. viewer.mainViewport.view.setView({
  80614. position: center.clone().sub(viewer.mainViewport.view.direction.clone().multiplyScalar(minRadius)),
  80615. target: center,
  80616. duration
  80617. }) //setView can cancel bump
  80618. }, */
  80619. focusOn(objects, duration = 400, fitBound=true, dontLookUp){
  80620. if(!(objects instanceof Array)){
  80621. objects = [objects];
  80622. }
  80623. let boundingBox = new Box3;
  80624. objects.forEach(object=>{
  80625. boundingBox.union(object.boundingBox.clone().applyMatrix4(object.matrixWorld));
  80626. });
  80627. if(fitBound){
  80628. viewer.focusOnObject({boundingBox}, 'boundingBox', duration, {dontLookUp, dontChangeCamDir:true});
  80629. }else {
  80630. /*
  80631. let position = viewer.inputHandler.intersect ? viewer.inputHandler.intersect.location : boundingBox.getCenter(new THREE.Vector3)
  80632. position && viewer.focusOnObject({position}, 'point', duration, {dontChangePos: true})
  80633. */
  80634. let position = viewer.inputHandler.intersect ? viewer.inputHandler.intersect.location : boundingBox.getCenter(new Vector3);
  80635. if(!position)return
  80636. /* let targetOld = viewer.mainViewport.view.getPivot()
  80637. let projected1 = targetOld.clone().project(viewer.mainViewport.camera);
  80638. let projected2 = position.clone().project(viewer.mainViewport.camera); //使用其z
  80639. let targetNew = projected1.clone().setZ(projected2.z).unproject(viewer.mainViewport.camera);
  80640. viewer.mainViewport.view.lookAt(targetNew) */
  80641. viewer.mainViewport.view.radius = viewer.mainViewport.camera.position.distanceTo(position);
  80642. //为了不改画面,不调节方向了,只能调调radius,一定程度将target靠近model
  80643. }
  80644. },
  80645. setModelBtmHeight(model, z ){
  80646. //无论模型怎么缩放、旋转,都使最低点为z
  80647. if(z == void 0) z = model.btmHeight; //维持离地高度
  80648. else model.btmHeight = z;
  80649. model.updateMatrixWorld();
  80650. let boundingBox2 = model.boundingBox.clone().applyMatrix4(model.matrixWorld);
  80651. let size = boundingBox2.getSize(new Vector3);
  80652. let center = boundingBox2.getCenter(new Vector3);
  80653. let hopeZ = z + size.z / 2;
  80654. //model.position.z = z + size.z / 2 - center.z
  80655. model.position.z += (hopeZ - center.z);
  80656. },
  80657. computeBtmHeight(model){ //位移之后重新计算btmHeight
  80658. model.updateMatrixWorld();
  80659. let boundingBox2 = model.boundingBox.clone().applyMatrix4(model.matrixWorld);
  80660. let size = boundingBox2.getSize(new Vector3);
  80661. let center = boundingBox2.getCenter(new Vector3);
  80662. model.btmHeight = center.z - size.z / 2;
  80663. },
  80664. maintainBoundXY(model){ //在旋转和缩放后,立即执行这个函数,使boundCenter保持原位
  80665. model.updateMatrixWorld();
  80666. let center1 = model.boundCenter.clone();//还未更新的
  80667. this.getBoundCenter(model);//更新
  80668. let center2 = model.boundCenter.clone();
  80669. let diff = new Vector2$1().subVectors(center1,center2);
  80670. model.position.x += diff.x;
  80671. model.position.y += diff.y;
  80672. /* model.updateMatrixWorld()
  80673. this.getBoundCenter(model)//再次更新,它需要和center1相同 */
  80674. model.boundCenter.copy(center1);
  80675. },
  80676. moveBoundCenterTo(model,pos){ //使boundCenter在所要的位置
  80677. let diff = new Vector3().subVectors(pos, model.boundCenter);
  80678. model.position.add(diff);
  80679. },
  80680. getBoundCenter(model){
  80681. if(!model.boundCenter) model.boundCenter = new Vector3;
  80682. model.boundingBox.getCenter(model.boundCenter).applyMatrix4(model.matrixWorld);
  80683. },
  80684. modelTransformCallback(model){
  80685. model.updateMatrixWorld();
  80686. if(model.matrixWorld.equals(model.lastMatrixWorld))return
  80687. viewer.scene.measurements.forEach(measure=>{
  80688. let changed;
  80689. measure.points_datasets.forEach((dataset_id,i)=>{
  80690. if(dataset_id == model.dataset_id){
  80691. changed = true;
  80692. measure.points[i] = Potree.Utils.datasetPosTransform({fromDataset:true,datasetId:dataset_id, position:measure.dataset_points[i].clone()});
  80693. measure.updateMarker(measure.markers[i], measure.points[i]);
  80694. }
  80695. });
  80696. if(changed){//仿transformByPointcloud
  80697. measure.getPoint2dInfo(measure.points);
  80698. measure.update();
  80699. measure.setSelected(false);//隐藏edgelabel
  80700. }
  80701. });
  80702. model.lastMatrixWorld = model.matrixWorld.clone();
  80703. }
  80704. };
  80705. /*
  80706. note:
  80707. 要注意getHoveredElements只在getIntersect时才使interactables包含加载的model, 也就是model上不能有使之成为interactables的事件,否则在鼠标hover到模型上开始转动的一瞬间很卡。
  80708. */
  80709. const texLoader$9 = new TextureLoader();
  80710. const circleGeo = new CircleGeometry(1.45,100);
  80711. const sphereGeo = new SphereBufferGeometry(0.018,10,10);
  80712. const magDistance_ = 1;//相机离目标位置的距离的分界线,当离得远时要缩小fov以使看到的视野固定(望远镜效果)
  80713. /* const radius_ = 0.2; //当相机离目标位置的距离>magDistance_时,希望看到的视野的半径
  80714. const maxFov = THREE.Math.radToDeg(Math.atan(radius_ / magDistance_ )) * 2//提前计算出当相机离目标位置的距离<magDistance_时的fov,均使用=magDistance_时的fov。只要保证该fov大于主相机的fov就会有放大效果
  80715. */
  80716. let w$2 = 200/1.43;
  80717. let maxPX = 1366*1024; //ipad pro. 大于这个分辨率的就直接用devicePixelRatio, 如macbook也是
  80718. 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); //触屏或高分辨率的可能要放大些。但在手机上不能太大
  80719. console.log('width2dPX', width2dPX);
  80720. class Magnifier extends Object3D {//放大镜or望远镜
  80721. constructor (viewer) {
  80722. super();
  80723. this.width = this.height = width2dPX/* * window.devicePixelRatio */;
  80724. this.camera = new PerspectiveCamera(50, 1, 0.01, 10000); //fov aspect near far
  80725. this.camera.up = new Vector3(0,0,1);
  80726. this.viewport = new Viewport( null, this.camera, {
  80727. left:0, bottom:0, width:1, height: 1, name:'magnifier' , cameraLayers:['magnifierContent'],
  80728. pixelRatio:1
  80729. });
  80730. this.viewport.setResolution(this.width, this.height,0,0);
  80731. {
  80732. let density;
  80733. let sizeType;
  80734. let colorType;
  80735. let opacityBefore = new Map();
  80736. this.viewport.beforeRender = ()=>{
  80737. viewer.scene.pointclouds.forEach(e=>{//因为更改pointDensity时会自动变opacity,所以这项最先获取
  80738. opacityBefore.set(e,e.temp.pointOpacity);
  80739. });
  80740. //使放大镜里的pointDensity是'magnifier' 最高质量。
  80741. density = Potree.settings.pointDensity;
  80742. Potree.settings.pointDensity = 'magnifier';
  80743. viewer.scene.pointclouds.forEach(e=>{//因为全景模式的pointSizeType是fixed所以要还原下
  80744. sizeType = e.material.pointSizeType;
  80745. e.material.pointSizeType = Potree.config.material.pointSizeType;
  80746. //材质
  80747. colorType = e.material.activeAttributeName;
  80748. e.material.activeAttributeName = 'rgba';
  80749. e.changePointOpacity(1);
  80750. });
  80751. };
  80752. this.viewport.afterRender = ()=>{
  80753. Potree.settings.pointDensity = density;
  80754. viewer.scene.pointclouds.forEach(e=>{
  80755. e.material.pointSizeType = sizeType;
  80756. e.material.activeAttributeName = colorType;
  80757. e.changePointOpacity(opacityBefore.get(e));
  80758. });
  80759. };
  80760. }
  80761. this.renderTarget = new WebGLRenderTarget(this.width,this.height, {
  80762. minFilter: LinearFilter, magFilter: LinearFilter,
  80763. format: RGBAFormat ,
  80764. /* type: THREE.FloatType,
  80765. minFilter: THREE.NearestFilter,
  80766. magFilter: THREE.NearestFilter,
  80767. */
  80768. } );
  80769. this.rtEDL = new WebGLRenderTarget(this.width, this.height, { //好像没用到? 因为这里不绘制测量线
  80770. minFilter: NearestFilter,
  80771. magFilter: NearestFilter,
  80772. format: RGBAFormat,
  80773. type: FloatType,
  80774. depthTexture: new DepthTexture(undefined, undefined, UnsignedIntType)
  80775. });
  80776. this.mesh = new Mesh(circleGeo, new MeshBasicMaterial({
  80777. side: DoubleSide ,
  80778. map: this.renderTarget.texture ,
  80779. transparent:true,
  80780. depthTest: !1,
  80781. //depthWrite: !1,
  80782. }));
  80783. this.overlayMesh = new Mesh(circleGeo, new MeshBasicMaterial({
  80784. side: DoubleSide ,
  80785. map:texLoader$9.load(Potree.resourcePath+'/textures/crosshair.png') ,
  80786. transparent:true,
  80787. depthTest: !1,
  80788. //depthWrite: !1,
  80789. }));
  80790. this.targetPoint = new Object3D;
  80791. this.targetPoint.add(new Mesh(sphereGeo, new MeshBasicMaterial({
  80792. color:"#ff0000",
  80793. transparent:true,
  80794. opacity:0.5,
  80795. })));
  80796. this.targetPoint.add(new Mesh(sphereGeo, new MeshBasicMaterial({
  80797. color:"#ff0000",
  80798. transparent:true,
  80799. opacity:0.2,
  80800. depthTest:false //被遮挡层
  80801. })));
  80802. this.targetPoint.name = 'magnifierPointTarget';
  80803. viewer.scene.scene.add(this.targetPoint);
  80804. viewer.setObjectLayers(this.targetPoint, 'magnifierContent' );
  80805. this.add(this.mesh);
  80806. this.add(this.overlayMesh);
  80807. this.position.set(-1000,-1000,-100000);//令它看不见
  80808. this.mesh.renderOrder = 10;
  80809. this.overlayMesh.renderOrder = 11;
  80810. this.aimPos;
  80811. viewer.setObjectLayers(this, 'magnifier' );
  80812. //viewer.inputHandler.addInputListener(this)
  80813. viewer.addEventListener('camera_changed',(e)=>{ // 平移、滚轮时更新
  80814. if(e.viewport == viewer.mainViewport) this.update(); //不过intersectPoint没更新
  80815. });
  80816. this.mesh.layers.set(Potree.config.renderLayers.magnifier);
  80817. this.overlayMesh.layers.set(Potree.config.renderLayers.magnifier);
  80818. //this.layers.set(Potree.config.renderLayers.magnifier);//这句在外层写没用
  80819. this.dontRender = false;
  80820. viewer.addEventListener('global_drag', (e)=>{//拖拽时不渲染。主要是右键平移时渲染延迟了,会闪烁。
  80821. this.dontRender = true;
  80822. });
  80823. viewer.addEventListener('global_drop', (e)=>{
  80824. this.dontRender = false;
  80825. });
  80826. viewer.addEventListener('global_mouseup', (e)=>{//测量时拖拽场景再mouseup
  80827. this.dontRender = false;
  80828. });
  80829. var updateVisi = (e)=>{
  80830. if(e.hoverViewport == viewer.mainViewport){
  80831. viewer.updateVisible(this,"atViewport", true);
  80832. this.update(e.intersect && e.intersect.location);
  80833. }else {
  80834. viewer.updateVisible(this,"atViewport", false); //小地图不显示
  80835. }
  80836. };
  80837. viewer.addEventListener('global_mousemove', updateVisi);
  80838. viewer.addEventListener('global_touchstart', updateVisi);
  80839. /* viewer.addEventListener("beginSplitView",()=>{
  80840. this.updateVisible("splitView", false)
  80841. })
  80842. viewer.addEventListener("finishSplitView",()=>{
  80843. this.updateVisible("splitView", true)
  80844. }) */
  80845. this.addEventListener("setEnable",(e)=>{
  80846. viewer.updateVisible(this, "enable", e.value); //界面开关
  80847. /* if(Potree.settings.displayMode == 'showPanos') && e.value){
  80848. Potree.settings.pointDensity = 'magnifier'
  80849. }else if() */
  80850. });
  80851. if(Potree.settings.isOfficial){
  80852. viewer.updateVisible(this, "enable", false);
  80853. }else {
  80854. viewer.updateVisible(this, "measure", false);
  80855. viewer.addEventListener("measureMovePoint",()=>{//测量开始
  80856. viewer.updateVisible(this, "measure", true);
  80857. });
  80858. viewer.addEventListener("endMeasureMove",()=>{
  80859. viewer.updateVisible(this, "measure", false);
  80860. });
  80861. }
  80862. viewer.scene.view.addEventListener('flyingDone',()=>{
  80863. if(!this.visible)return
  80864. let pickWindowSize = 100;
  80865. let intersect = viewer.inputHandler.getIntersect(viewer.mainViewport, viewer.mainViewport.camera, true, pickWindowSize );
  80866. this.update(intersect && intersect.location);
  80867. });
  80868. }
  80869. //注意:在鼠标没有移动的时候,无法获取到最新的intersect, 放大镜内的内容可能是错误的。全景模式下更奇怪,原因未知
  80870. update(aimPos){//相机靠近 navvis的做法
  80871. var dontRender = this.dontRender || !(aimPos instanceof Vector3) || Potree.settings.displayMode == 'showPanos' && viewer.images360.flying;
  80872. aimPos = aimPos instanceof Vector3 ? aimPos : this.aimPos;
  80873. if(!aimPos || !this.visible)return
  80874. var playerCamera = viewer.scene.getActiveCamera();
  80875. var playerPos = playerCamera.position;//viewer.scene.view.getPivot()
  80876. var dis = playerPos.distanceTo(aimPos);
  80877. var dirToCamera = new Vector3().subVectors(playerPos, aimPos ).normalize();
  80878. //相机位置
  80879. var finalDisToAim = dis>magDistance_ ? magDistance_ : dis / 2;
  80880. this.camera.position.copy(aimPos).add(dirToCamera.multiplyScalar(finalDisToAim));
  80881. this.camera.lookAt(aimPos);
  80882. this.camera.fov = playerCamera.fov / 2;
  80883. this.camera.updateProjectionMatrix();
  80884. //自身位置
  80885. //let pos2d = viewer.inputHandler.pointer.clone(); //跟随鼠标
  80886. let pos2d = Potree.Utils.getPos2d(aimPos, playerCamera, viewer.renderArea, viewer.mainViewport).vector; //更新目标点的实时二维位置
  80887. let margin = 0.4, maxY = 0.4;
  80888. let screenPos = pos2d.clone().setY(pos2d.y + (pos2d.y>maxY ? -margin : margin ));
  80889. let newPos = new Vector3(screenPos.x,screenPos.y,0.8).unproject(playerCamera); //z:-1朝外
  80890. let dir = newPos.clone().sub(playerPos).normalize().multiplyScalar(10);//这个数值要大于playerCamera.near
  80891. let s = dis>magDistance_ ? 1 : dis / magDistance_ ;
  80892. this.position.copy(playerPos.clone().add(dir));
  80893. this.quaternion.copy(playerCamera.quaternion);
  80894. this.targetPoint.position.copy(aimPos);
  80895. this.targetPoint.scale.set(s,s,s);
  80896. this.aimPos = aimPos;
  80897. var scale = math.getScaleForConstantSize({//
  80898. width2d : width2dPX,
  80899. camera:viewer.scene.getActiveCamera(), position: this.getWorldPosition(new Vector3()),
  80900. resolution: viewer.mainViewport.resolution2
  80901. });
  80902. this.scale.set(scale, scale, scale);
  80903. if(!dontRender){
  80904. this.waitRender = true;
  80905. }
  80906. }
  80907. /* update(aimPos){ //仅改fov的版本
  80908. aimPos = aimPos instanceof THREE.Vector3 ? aimPos : this.aimPos
  80909. if(!aimPos || !this.visible)return
  80910. //相机位置
  80911. var playerCamera = viewer.scene.getActiveCamera()
  80912. var playerPos = playerCamera.position;//viewer.scene.view.getPivot()
  80913. var dis = playerPos.distanceTo(aimPos);
  80914. if(dis<magDistance_){
  80915. this.camera.fov = maxFov
  80916. }else{
  80917. this.camera.fov = THREE.Math.radToDeg(Math.atan(radius_ / dis )) * 2 //radius_是能看到的范围半径。当dis大于magDistance_时就放大,否则维持fov为maxFov
  80918. }
  80919. this.camera.updateProjectionMatrix()
  80920. this.camera.position.copy(playerPos)
  80921. this.camera.lookAt(aimPos)
  80922. this.quaternion.copy(playerCamera.quaternion);
  80923. let pointer = viewer.inputHandler.pointer.clone();
  80924. let margin = 0.4, maxY = 0.4
  80925. let screenPos = pointer.clone().setY(pointer.y + (pointer.y>maxY ? -margin : margin ))
  80926. let newPos = new THREE.Vector3(screenPos.x,screenPos.y,0.8).unproject(playerCamera); //z:-1朝外
  80927. let dir = newPos.clone().sub(playerPos).normalize().multiplyScalar(10);//这个数值要大于playerCamera.near
  80928. this.position.copy(playerPos.clone().add(dir))
  80929. this.aimPos = aimPos
  80930. this.targetPoint.position.copy(aimPos);
  80931. var scale = math.getScaleForConstantSize({//
  80932. width2d : width2dPX,
  80933. camera:viewer.scene.getActiveCamera(), position: this.getWorldPosition(new THREE.Vector3()),
  80934. resolution: viewer.mainViewport.resolution2
  80935. })
  80936. this.scale.set(scale, scale, scale);
  80937. if(!this.dontRender){
  80938. this.waitRender = true
  80939. }
  80940. }//位置需要计算,不仅仅是点云,所以需要深度图
  80941. */
  80942. render(){
  80943. if(!this.waitRender)return
  80944. //this.visible = false;//防止放大镜里有自己
  80945. viewer.render({
  80946. target : this.renderTarget,
  80947. viewports : [this.viewport],
  80948. camera : this.camera,
  80949. magnifier : true,
  80950. rtEDL: this.rtEDL
  80951. /* width :this.renderTarget.width,
  80952. height: this.renderTarget.height, */
  80953. });
  80954. //this.visible = true;
  80955. this.waitRender = false;
  80956. }
  80957. }
  80958. let texLoader$a = new TextureLoader();
  80959. let defaultOpacity = 0.7;
  80960. //鼠标指示小圆片
  80961. class Reticule extends Mesh{
  80962. constructor(viewer){
  80963. var defaultTex = texLoader$a.load(Potree.resourcePath+'/textures/whiteCircle.png'/* reticule-256x256.png' */);
  80964. super(new PlaneBufferGeometry(0.11,0.11,1,1),new MeshBasicMaterial({
  80965. side: DoubleSide ,
  80966. map: defaultTex,
  80967. transparent:true,
  80968. depthTest: !1,
  80969. opacity: defaultOpacity,
  80970. //depthWrite: !1,
  80971. }));
  80972. this.name = 'reticule';
  80973. this.defaultTex = defaultTex;
  80974. this.crosshairTex = texLoader$a.load(Potree.resourcePath+'/textures/reticule_cross_hair.png');
  80975. this.forbitTex = texLoader$a.load(Potree.resourcePath+'/textures/pic-forbid.png');
  80976. //this.layers.set(0/* RenderLayers.RETICULE */);
  80977. this.renderOrder = 100;
  80978. this.layers.set(Potree.config.renderLayers.marker);
  80979. this.direction = new Vector3;
  80980. this.mouseLastMoveTime = Date.now();
  80981. this.hoverViewport;
  80982. this.matrixMap = new Map;
  80983. this.matrixAutoUpdate = false;
  80984. this.hide(0);
  80985. //viewer.inputHandler.addInputListener(this);
  80986. Potree.settings.intersectWhenHover && viewer.addEventListener('global_mousemove',this.move.bind(this));
  80987. //viewer.addEventListener('global_click',this.move.bind(this))
  80988. viewer.addEventListener('global_mousedown',this.move.bind(this));//主要针对触屏
  80989. this.state = {};
  80990. viewer.addEventListener('measureMovePoint',()=>{
  80991. this.state.cross = true;
  80992. this.judgeTex();
  80993. });
  80994. viewer.addEventListener('endMeasureMove',()=>{
  80995. this.state.cross = false;
  80996. this.judgeTex();
  80997. });
  80998. viewer.addEventListener('reticule_forbit',(e)=>{
  80999. if(this.state.forbit != e.v){
  81000. console.log('change forbit ',e.v);
  81001. }
  81002. this.state.forbit = e.v;
  81003. this.judgeTex();
  81004. });
  81005. viewer.setObjectLayers(this, 'sceneObjects' );
  81006. }
  81007. judgeTex(){
  81008. if(this.state.forbit){
  81009. this.material.map = this.forbitTex;
  81010. }else if(this.state.cross){
  81011. this.material.map = this.crosshairTex;
  81012. }else {
  81013. this.material.map = this.defaultTex;
  81014. }
  81015. viewer.mapViewer && viewer.mapViewer.dispatchEvent({type:'content_changed'});
  81016. }
  81017. move(e){
  81018. if(e.type == "global_mousemove" && (e.isTouch || e.buttons != Buttons.NONE) && this.state != 'crosshair'){
  81019. return//按下时不更新,除非拖拽测量
  81020. }
  81021. this.mouseLastMoveTime = Date.now();
  81022. this.updatePosition(e.intersect, e.hoverViewport);
  81023. }
  81024. hide(duration = 500){
  81025. if(this.hidden)return
  81026. this.hidden = !0;
  81027. transitions.start(lerp.property(this.material , "opacity", 0), duration);
  81028. this.dispatchEvent({type:'update', visible:false});
  81029. setTimeout(()=>{
  81030. this.dispatchEvent({type:'update', visible:false});
  81031. },duration);
  81032. }
  81033. show(duration = 300){
  81034. if(!viewer.getObjVisiByReason(this, 'force'))return
  81035. //console.log("show Reticule")
  81036. this.hidden = !1;
  81037. if(this.material.opacity <= 0){
  81038. transitions.start(lerp.property(this.material, "opacity", defaultOpacity), duration);
  81039. this.dispatchEvent({type:'update', visible:true});
  81040. setTimeout(()=>{
  81041. this.dispatchEvent({type:'update', visible:false});
  81042. },duration);
  81043. }
  81044. }
  81045. //鼠标静止一段时间它就会消失
  81046. updateVisible(){
  81047. Date.now() - this.mouseLastMoveTime > 1500 && !this.hidden && this.hide();
  81048. }
  81049. updateScale(viewport){
  81050. let s, camera = viewport.camera;
  81051. if(camera.type == "OrthographicCamera"){
  81052. var sizeInfo = this.state.cross ? {width2d:500} : {minSize : 100, maxSize : 400, nearBound : 100 , farBound : 700};
  81053. s = math.getScaleForConstantSize($.extend( sizeInfo ,
  81054. {position:this.position, camera, resolution:viewport.resolution/* 2 */} ));
  81055. }else {
  81056. let n = camera.position.distanceTo(this.position);
  81057. s = 1 + .1 * n;
  81058. n < 1 && (s -= 1 - n);
  81059. }
  81060. this.scale.set(s, s, s);
  81061. }
  81062. updateAtViewports(viewport){//当多个viewports时更新。更新大小等
  81063. if(viewport.name == 'magnifier' )return
  81064. if(this.hoverViewport && this.hoverViewport.name == 'mapViewport' && viewport != this.hoverViewport){
  81065. //若是在地图上更新,在其他viewport要隐藏。因为在地图上无法得知高度。
  81066. viewer.updateVisible(this, 'hoverMap', false);
  81067. return;
  81068. }
  81069. viewer.updateVisible(this, 'hoverMap', true);
  81070. var matrix = this.matrixMap.get(viewport);
  81071. if(!matrix){
  81072. this.updateScale(viewport);
  81073. this.updateMatrix();
  81074. //this.updateMatrixWorld()
  81075. this.matrixMap.set(viewport, this.matrix.clone());
  81076. }else {
  81077. this.matrix.copy(matrix);
  81078. //this.updateMatrixWorld()
  81079. }
  81080. }
  81081. updatePosition(intersect, viewport ){ //在地图(当地图融合到viewer时)和场景里都显示且完全相同(大小可能不同)
  81082. if (viewer.getObjVisiByReason(this, 'force')) {//没有被强制隐藏,如进入某个页面后强制不显示
  81083. if (!intersect /* || !intersect.point.normal */){
  81084. return //this.hide();
  81085. }
  81086. var atMap = !intersect.location;
  81087. let location = intersect.location || intersect.orthoIntersect.clone();
  81088. let normal;
  81089. //地图上要瞬间变化 , 因为要使needRender为true很麻烦
  81090. this.show(atMap ? 0 : 300);
  81091. if(atMap){
  81092. normal = new Vector3(0,0,1);//地图无normal
  81093. location.setZ(0);//低于相机高度即可
  81094. this.direction = normal.clone();
  81095. }else {
  81096. /* if(intersect.point){
  81097. if(intersect.pointcloud){
  81098. normal = new THREE.Vector3().fromArray(intersect.point.normal ).applyMatrix4( intersect.pointcloud.rotateMatrix );
  81099. }else{//mesh
  81100. normal = new THREE.Vector3().copy(intersect.point.normal).applyQuaternion(intersect.object.quaternion)
  81101. }
  81102. }else{
  81103. normal = intersect.normal //when showPanos
  81104. } */
  81105. normal = intersect.normal;
  81106. if(normal){
  81107. let ratio = /* Potree.settings.useDepthTex ? 1 : */ 0.2;
  81108. this.direction = this.direction.multiplyScalar(1-ratio);
  81109. this.direction.add(normal.clone().multiplyScalar(ratio));
  81110. }
  81111. //this.direction = normal.clone() //改为瞬间变化,否则刚hover上某个点时看起来不太对
  81112. }
  81113. this.position.copy(location);/* .add(normal.clone().multiplyScalar(.01)); */
  81114. this.updateMatrix(); //lookAt之前要保证得到matrix
  81115. this.lookAt(this.position.clone().add(this.direction));
  81116. this.hoverViewport = viewport; //记录下最近一次hover过的viewport
  81117. this.updateScale(viewport);
  81118. {//存储matrix,节省计算
  81119. this.updateMatrix();
  81120. //this.updateMatrixWorld()
  81121. this.matrixMap.clear();//重新计算
  81122. this.matrixMap.set(viewport, this.matrix.clone());
  81123. //别处会updateMatrixWorld
  81124. }
  81125. this.dispatchEvent({type:'update'});
  81126. //为什么navvis在校准数据集时每个viewport里reticule的朝向都刚好垂直于屏幕,似乎限定在了一定范围内,还是在pick时就只pick范围内的点?
  81127. }
  81128. }
  81129. //navvis在地图等地方看reticule是有厚度的
  81130. /* updateMatrixWorld(force){
  81131. console.log('updateMatrixWorld', force)
  81132. super.updateMatrixWorld(force)
  81133. } */
  81134. }
  81135. const FEET_TO_INCHES_FACTOR = 12;
  81136. const EIGHTHS_SYMBOLS = ["", "⅛", "¼", "⅜", "½", "⅝", "¾", "⅞"];//eighths 八分之……
  81137. class UnitOfMeasurement{//转化单位工具
  81138. constructor(t, e, n, i){
  81139. this.name = t,
  81140. this.symbol = e,
  81141. this.base = n,
  81142. this.factor = i;
  81143. }
  81144. toBase(t) {//换算到base
  81145. return t * this.factor
  81146. }
  81147. fromBase(t) {//换算到当前
  81148. return t / this.factor
  81149. }
  81150. }
  81151. /* var o = function t(e) {
  81152. this.gettext = e,
  81153. t.METRIC = this.gettext("metric", void 0, "measurement system"),
  81154. t.IMPERIAL = this.gettext("imperial", void 0, "measurement system")
  81155. };
  81156. e.UoMSystem = o;
  81157. let UoMSystem = {
  81158. } */
  81159. /* var MeasurementDomain = {
  81160. DISTANCE : "DISTANCE",
  81161. t.AREA = "AREA",
  81162. t.VOLUME = "VOLUME",
  81163. t.DATA = "DATA",
  81164. t
  81165. }
  81166. */
  81167. var UnitsOfMeasurement = {
  81168. MILLIMETER : ["Millimeter", "mm"],
  81169. CENTIMETER : ["Centimeter", "cm"],
  81170. METER : ["Meter", "m"],
  81171. KILOMETER : ["Kilometer", "km"],
  81172. INCH : ["Inch", "in"],
  81173. FOOT : ["Foot", "ft"],
  81174. MILE : ["Mile", "mi"],
  81175. SQUAREMETER : ["SquareMeter", "m²"],
  81176. SQUAREFOOT : ["SquareFoot", "ft²"],
  81177. CUBICMETER : ["CubicMeter", "m³"],
  81178. CUBICFOOT : ["CubicFoot", "ft³"],
  81179. BYTE : ["Byte", "B"],
  81180. KILOBYTE : ["Kilobyte", "kB"],
  81181. MEGABYTE : ["Megabyte", "MB"],
  81182. GIGABYTE : ["Gigabyte", "GB"],
  81183. TERABYTE : ["Terabyte", "TB"],
  81184. PETABYTE : ["Petabyte", "PB"],
  81185. init : function() {
  81186. var e, n, i, a, s, c, l, u, d, p, h,
  81187. f = new UnitOfMeasurement(UnitsOfMeasurement.METER[0],UnitsOfMeasurement.METER[1],void 0,1),
  81188. g = new UnitOfMeasurement(UnitsOfMeasurement.SQUAREMETER[0],UnitsOfMeasurement.SQUAREMETER[1],void 0,1),
  81189. m = new UnitOfMeasurement(UnitsOfMeasurement.CUBICMETER[0],UnitsOfMeasurement.CUBICMETER[1],void 0,1),
  81190. v = new UnitOfMeasurement(UnitsOfMeasurement.BYTE[0],UnitsOfMeasurement.BYTE[1],void 0,1);
  81191. UnitsOfMeasurement.DISTANCE = (
  81192. (e = {})['metric'] = ((n = {})[UnitsOfMeasurement.MILLIMETER[0]] = new UnitOfMeasurement(UnitsOfMeasurement.MILLIMETER[0],UnitsOfMeasurement.MILLIMETER[1],f,.001),
  81193. n[UnitsOfMeasurement.CENTIMETER[0]] = new UnitOfMeasurement(UnitsOfMeasurement.CENTIMETER[0],UnitsOfMeasurement.CENTIMETER[1],f,.01),
  81194. n[UnitsOfMeasurement.METER[0]] = f,
  81195. n[UnitsOfMeasurement.KILOMETER[0]] = new UnitOfMeasurement(UnitsOfMeasurement.KILOMETER[0],UnitsOfMeasurement.KILOMETER[1],f,1e3),
  81196. n),
  81197. e['imperial'] = ((i = {})[UnitsOfMeasurement.INCH[0]] = new UnitOfMeasurement(UnitsOfMeasurement.INCH[0],UnitsOfMeasurement.INCH[1],f,.0254),
  81198. i[UnitsOfMeasurement.FOOT[0]] = new UnitOfMeasurement(UnitsOfMeasurement.FOOT[0],UnitsOfMeasurement.FOOT[1],f,.3048),
  81199. i[UnitsOfMeasurement.MILE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.MILE[0],UnitsOfMeasurement.MILE[1],f,1609.344),
  81200. i),
  81201. e);
  81202. UnitsOfMeasurement.AREA = ((a = {})['metric'] = ((s = {})[UnitsOfMeasurement.SQUAREMETER[0]] = g,
  81203. s),
  81204. a['imperial'] = ((c = {})[UnitsOfMeasurement.SQUAREFOOT[0]] = new UnitOfMeasurement(UnitsOfMeasurement.SQUAREFOOT[0],UnitsOfMeasurement.SQUAREFOOT[1],g,.092903),
  81205. c),
  81206. a);
  81207. UnitsOfMeasurement.VOLUME = ((l = {})['metric'] = ((u = {})[UnitsOfMeasurement.CUBICMETER[0]] = m,
  81208. u),
  81209. l['imperial'] = ((d = {})[UnitsOfMeasurement.CUBICFOOT[0]] = new UnitOfMeasurement(UnitsOfMeasurement.CUBICFOOT[0],UnitsOfMeasurement.CUBICFOOT[1],m,.0283168),
  81210. d),
  81211. l);
  81212. //数据大小
  81213. var y = ((p = {})[UnitsOfMeasurement.BYTE[0]] = v,
  81214. p[UnitsOfMeasurement.KILOBYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.KILOBYTE[0],UnitsOfMeasurement.KILOBYTE[1],v,1e3),
  81215. p[UnitsOfMeasurement.MEGABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.MEGABYTE[0],UnitsOfMeasurement.MEGABYTE[1],v,1e6),
  81216. p[UnitsOfMeasurement.GIGABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.GIGABYTE[0],UnitsOfMeasurement.GIGABYTE[1],v,1e9),
  81217. p[UnitsOfMeasurement.TERABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.TERABYTE[0],UnitsOfMeasurement.TERABYTE[1],v,1e12),
  81218. p[UnitsOfMeasurement.PETABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.PETABYTE[0],UnitsOfMeasurement.PETABYTE[1],v,1e15),
  81219. p);
  81220. UnitsOfMeasurement.DATA = ((h = {})['metric'] = y,
  81221. h['imperial'] = y,
  81222. h);
  81223. }
  81224. ,
  81225. getUnitsOfMeasurementByDomain : function(e) {
  81226. return this[e.toUpperCase()]
  81227. /* switch (e.toUpperCase()) {
  81228. case a.DISTANCE:
  81229. return t.DISTANCE;
  81230. case a.AREA:
  81231. return t.AREA;
  81232. case a.VOLUME:
  81233. return t.VOLUME;
  81234. case a.DATA:
  81235. return t.DATA;
  81236. default:
  81237. console.error(e + " measurement domain is not supported.")
  81238. } */
  81239. }
  81240. ,
  81241. getUnitsOfMeasurementByDomainAndSystem : function(domain, system) {
  81242. var r = this.getUnitsOfMeasurementByDomain(domain);
  81243. if (r.hasOwnProperty(system.toLowerCase()))
  81244. return r[system.toLowerCase()];
  81245. console.error(n + " measurement system is not supported.");
  81246. }
  81247. ,
  81248. getDefaultUnitByDomainAndSystem : function(e, n) {
  81249. switch (e.toUpperCase()) {
  81250. case 'DISTANCE':
  81251. switch (n.toLowerCase()) {
  81252. case 'metric':
  81253. return this.DISTANCE['metric'][this.METER[0]];
  81254. case 'imperial':
  81255. return this.DISTANCE['imperial'][this.FOOT[0]];
  81256. default:
  81257. console.error(n + " measurement system is not supported.");
  81258. }
  81259. case 'AREA':
  81260. switch (n.toLowerCase()) {
  81261. case 'metric':
  81262. return this.AREA['metric'][this.SQUAREMETER[0]];
  81263. case 'imperial':
  81264. return this.AREA['imperial'][this.SQUAREFOOT[0]];
  81265. default:
  81266. console.error(n + " measurement system is not supported.");
  81267. }
  81268. case 'VOLUME':
  81269. switch (n.toLowerCase()) {
  81270. case 'metric':
  81271. return this.VOLUME['metric'][this.CUBICMETER[0]];
  81272. case 'imperial':
  81273. return this.VOLUME['imperial'][this.CUBICFOOT[0]];
  81274. default:
  81275. console.error(n + " measurement system is not supported.");
  81276. }
  81277. case 'DATA':
  81278. switch (n.toLowerCase()) {
  81279. case 'metric':
  81280. return this.DATA['metric'][this.BYTE[0]];
  81281. case 'imperial':
  81282. return this.DATA['imperial'][this.BYTE[0]];
  81283. default:
  81284. console.error(n + " measurement system is not supported.");
  81285. }
  81286. default:
  81287. console.error(e + " measurement domain is not supported.");
  81288. }
  81289. }
  81290. };
  81291. class UnitService{
  81292. constructor(/* e, n, i */){
  81293. //this.LanguageService = e,
  81294. //this.localStorageService = n,
  81295. //this.gettext = i,
  81296. //this.unitChanged = new r.Signal,
  81297. this.LOCAL_STORAGE_KEY = "iv_unit_key";//?
  81298. UnitsOfMeasurement.init();
  81299. this.unitSystems = ['metric', 'imperial'];//[o.UoMSystem.METRIC, o.UoMSystem.IMPERIAL],
  81300. this.defaultSystem = 'metric';//'imperial'
  81301. //var a = this.LanguageService.getBrowserLocaleString().toLowerCase();
  81302. //this.defaultSystem = t.isLocaleImperial(a) ? o.UoMSystem.IMPERIAL : o.UoMSystem.METRIC,
  81303. //this.initUnit()
  81304. }
  81305. /* initUnit() {
  81306. var t = this.localStorageService.get(this.LOCAL_STORAGE_KEY);
  81307. if (t)
  81308. for (var e = 0, n = this.unitSystems; e < n.length; e++) {
  81309. var i = n[e];
  81310. if (i === t)
  81311. return void this.setUnit(i, !0)
  81312. }
  81313. this.setUnit(this.defaultSystem, !1)
  81314. }
  81315. setUnit(t, e) {
  81316. this.currentSystem !== t && (this.currentSystem = t,
  81317. this.unitChanged.emit()),
  81318. e && this.localStorageService.set(this.LOCAL_STORAGE_KEY, t)
  81319. } */
  81320. /*isLocaleImperial(e) {
  81321. return t.IMPERIAL_LOCALES.indexOf(e.toLowerCase()) >= 0
  81322. }
  81323. ,
  81324. t.IMPERIAL_LOCALES = ["en_us"],
  81325. t.ɵfac(e) {
  81326. return new (e || t)(c.ɵɵinject(l.LanguageService),
  81327. c.ɵɵinject("localStorageService"),c.ɵɵinject("gettext"))
  81328. }
  81329. ,
  81330. t.ɵprov = c.ɵɵdefineInjectable({
  81331. token: t,
  81332. factory: t.ɵfac,
  81333. providedIn: "root"
  81334. }), */
  81335. }
  81336. class UoMService{
  81337. constructor(/* UnitService */){
  81338. this.UnitService = new UnitService();/* UnitService */
  81339. }
  81340. scopedConvert (t, n, precision = 2, r, minFactor) {
  81341. return this.convert(t, n, precision, r, minFactor)
  81342. }
  81343. convert(number, domain, precision = 2, system, minFactor, ifEighths = !1) {
  81344. if (!number) return "";
  81345. var s = this.getMostRelevantMeasurement(domain, system || this.UnitService.currentSystem, number, minFactor);
  81346. return this.getFormattedMeasurementString(s[0], s[1], precision, ifEighths)
  81347. }
  81348. convertBack(number, domain, precision = 2, fromSystem, minFactor ) { //从英制转到'metric'
  81349. if (!number) return "";
  81350. var d = UnitsOfMeasurement.getDefaultUnitByDomainAndSystem(domain,'metric');
  81351. var s = this.getMostRelevantMeasurement2(domain, fromSystem, number, minFactor);
  81352. return this.getFormattedMeasurementString(s[0], d, precision )
  81353. /* 栗子:
  81354. viewer.unitConvert.convertBack(1, 'area', 5, 'imperial')
  81355. '0.09290 m²'
  81356. viewer.unitConvert.convertBack(1, 'Distance', 2, 'imperial')
  81357. '0.03 m'
  81358. */
  81359. }
  81360. getFormattedMeasurementString(number, unit, precision, ifEighths) {
  81361. var result;
  81362. if(ifEighths && unit.name === UnitsOfMeasurement.FOOT[0]){
  81363. result = this.formatImperialDistance(number * FEET_TO_INCHES_FACTOR);
  81364. }else if(ifEighths && unit.name === UnitsOfMeasurement.INCH[0]){
  81365. result = this.formatImperialDistance(number);
  81366. }else {
  81367. result = number.toLocaleString(void 0, {
  81368. minimumFractionDigits: precision,
  81369. maximumFractionDigits: precision
  81370. }) + " " + unit.symbol;
  81371. }
  81372. return result
  81373. }
  81374. formatImperialDistance(e) {
  81375. var n = Math.round(8 * e)
  81376. , i = Math.floor(n / 8)
  81377. , r = Math.floor(i / FEET_TO_INCHES_FACTOR)
  81378. , o = i - r * FEET_TO_INCHES_FACTOR
  81379. , a = EIGHTHS_SYMBOLS[n % 8]
  81380. , s = 0 === o && "" !== a ? "" : o;
  81381. "" !== s && "" !== a && (a = " " + a);
  81382. return 0 !== r ? r + "' " + s + a + '"' : "" + s + a + '"'
  81383. }
  81384. getMostRelevantMeasurement(domain, system, number, minFactor=0) {
  81385. /* var a = r.values(UnitsOfMeasurement.getUnitsOfMeasurementByDomainAndSystem(domain, system))
  81386. , s = r.filter(a, function(t) {
  81387. return t.factor >= i
  81388. })
  81389. , c = r.reduce(s, function(t, e) {
  81390. return e.fromBase(number) < t.fromBase(number) && e.fromBase(number) >= 1 ? e : t
  81391. }); */
  81392. let a = [];
  81393. let u = UnitsOfMeasurement.getUnitsOfMeasurementByDomainAndSystem(domain, system);
  81394. for(let i in u){a.push(u[i]);}
  81395. let s = a.filter(m=>m.factor >= minFactor);
  81396. let c = s.reduce(function(prev, currentValue) {//reduce最终值是最后一次return的值 ( 没看懂这句话作用)
  81397. return currentValue.fromBase(number) < prev.fromBase(number) && currentValue.fromBase(number) >= 1 ? currentValue : prev
  81398. });
  81399. return c ? [c.fromBase(number), c] : void 0
  81400. }
  81401. getMostRelevantMeasurement2(domain, system, number, minFactor=0) {//add
  81402. let a = [];
  81403. let u = UnitsOfMeasurement.getUnitsOfMeasurementByDomainAndSystem(domain, system);
  81404. for(let i in u){a.push(u[i]);}
  81405. let s = a.filter(m=>m.factor >= minFactor);
  81406. let c = s.reduce(function(prev, currentValue) {//reduce最终值是最后一次return的值 ( 没看懂这句话作用)
  81407. return currentValue.toBase(number) < prev.toBase(number) && currentValue.toBase(number) >= 1 ? currentValue : prev
  81408. });
  81409. return c ? [c.toBase(number), c] : void 0
  81410. }
  81411. /* ɵfac(e){
  81412. return new (e || t)(c.ɵɵinject(l.UnitService))
  81413. }
  81414. ɵprov = c.ɵɵdefineInjectable({
  81415. token: t,
  81416. factory: t.ɵfac,
  81417. providedIn: "root"
  81418. }) */
  81419. }
  81420. const texLoader$b = new TextureLoader();
  81421. const arrowSpacing = 1; //间隔
  81422. const arrowSize = arrowSpacing * 0.5;
  81423. const planeGeo$4 = new PlaneBufferGeometry(1,1);
  81424. const sphereSizeInfo = {
  81425. nearBound : 2, scale:arrowSize, restricMeshScale : true,
  81426. };
  81427. //const arrowsShowingCount = 25; //场景里最多展示多少个箭头
  81428. const arrowShowMinDis = 10;
  81429. class RouteGuider extends EventDispatcher{
  81430. constructor () {
  81431. super();
  81432. this.route = [];
  81433. this.curve = [];
  81434. this.scenePoints = [];
  81435. this.sceneMeshGroup = new Object3D;
  81436. this.mapMeshGroup = new Object3D;
  81437. this.generateDeferred;
  81438. viewer.addEventListener('loadPointCloudDone',this.init.bind(this));
  81439. this.lastResult;//保存上一个的结果,以便于反向
  81440. this.datasetIds = [];//起始和终点的datasetId
  81441. }
  81442. init(){
  81443. if(this.inited) return;
  81444. let zoom;
  81445. viewer.mapViewer.addEventListener('camera_changed', e => {
  81446. if(!this.routeStart || !this.routeEnd) return
  81447. var camera = e.viewport.camera;
  81448. Common.intervalTool.isWaiting('routeCameraInterval', ()=>{ //延时update,防止卡顿
  81449. if(camera.zoom != zoom){
  81450. //console.log('updateMapArrows')
  81451. this.updateMapArrows(true);
  81452. zoom = camera.zoom;
  81453. return true
  81454. }
  81455. }, browser.isMobile()?500:200);
  81456. });
  81457. //let lastPos = new THREE.Vector3
  81458. viewer.addEventListener('camera_changed', e => {
  81459. if(!this.routeStart || !this.routeEnd || !e.changeInfo.positionChanged) return
  81460. Common.intervalTool.isWaiting('routeCameraInterval', ()=>{ //延时update,防止卡顿
  81461. //let currPos = viewer.scene.getActiveCamera().position
  81462. //if(!currPos.equals(lastPos)){
  81463. // lastPos.copy(currPos)
  81464. this.updateArrowDisplay();
  81465. return true
  81466. //}
  81467. }, 1000);
  81468. });
  81469. var polesMats = {
  81470. shadowMat: new MeshBasicMaterial({
  81471. transparent:true, depthTest:false,
  81472. map: texLoader$b.load(Potree.resourcePath+'/textures/pano_instruction_bottomMarker.png' )
  81473. }),
  81474. sphereMat : new MeshBasicMaterial({
  81475. transparent:true, depthTest:false,
  81476. map: texLoader$b.load(Potree.resourcePath+'/textures/whiteCircle.png' )
  81477. }),
  81478. hatMats:{
  81479. start: new MeshBasicMaterial({
  81480. transparent:true, depthTest:false,
  81481. map: texLoader$b.load(Potree.resourcePath+'/textures/pano_instruction_start_route.png' )
  81482. }),
  81483. end: new MeshBasicMaterial({
  81484. transparent:true, depthTest:false,
  81485. map: texLoader$b.load(Potree.resourcePath+'/textures/pano_instruction_target_reached.png' )
  81486. })
  81487. }
  81488. };
  81489. polesMats.shadowMat.map.anisotropy = 4;
  81490. this.poleStart = this.createPole(polesMats, 'start');
  81491. this.poleEnd = this.createPole(polesMats, 'end');
  81492. this.sceneMeshGroup.add(this.poleStart);
  81493. this.sceneMeshGroup.add(this.poleEnd);
  81494. let map = texLoader$b.load(Potree.resourcePath+'/textures/routePoint_panorama.png' );
  81495. map.anisotropy = 4; // 各向异性过滤 .防止倾斜模糊
  81496. this.arrow = new Mesh(planeGeo$4, new MeshBasicMaterial({
  81497. transparent:true,
  81498. depthTest:false,
  81499. map
  81500. }));
  81501. this.arrow.scale.set(arrowSize,arrowSize,arrowSize);
  81502. viewer.setObjectLayers(this.arrow, 'sceneObjects' );
  81503. /* this.testArrow = this.arrow.clone();
  81504. this.testArrow.material = this.arrow.material.clone()
  81505. this.testArrow.material.color = 'red' */
  81506. this.arrows = new Object3D;
  81507. this.sceneMeshGroup.add(this.arrows);
  81508. viewer.setObjectLayers(this.sceneMeshGroup, 'sceneObjects' );
  81509. //this.sceneMeshGroup.traverse(e=>e.renderOrder = 90)
  81510. viewer.scene.scene.add(this.sceneMeshGroup);
  81511. this.sceneMeshGroup.visible = /* this.poleStart.visibile = this.poleEnd.visibile = */ false;
  81512. //-------------map---------------------
  81513. /* this.mapMarkStart = new THREE.Mesh( planeGeo, new THREE.MeshBasicMaterial({
  81514. transparent:true, depthTest:false,
  81515. map: texLoader.load(Potree.resourcePath+'/textures/map_instruction_start_route.png' )
  81516. }))
  81517. this.mapMarkEnd = new THREE.Mesh( planeGeo, new THREE.MeshBasicMaterial({
  81518. transparent:true, depthTest:false,
  81519. map: texLoader.load(Potree.resourcePath+'/textures/map_instruction_target_reached.png' )
  81520. }))
  81521. this.mapMarkStart.renderOrder = this.mapMarkEnd.renderOrder = 2//在箭头之上 */
  81522. let map2 = texLoader$b.load(Potree.resourcePath+'/textures/routePoint_map_fsna.png' );
  81523. this.mapArrowMats = {
  81524. default: new MeshBasicMaterial({
  81525. transparent:true, depthTest:false,
  81526. map:map2,
  81527. }),
  81528. fade: new MeshBasicMaterial({
  81529. transparent:true, depthTest:false,
  81530. map:map2,
  81531. opacity:0.4
  81532. }),
  81533. };
  81534. this.mapArrow = new Mesh( planeGeo$4, this.mapArrowMats.default);
  81535. this.mapArrow.scale.set(arrowSize,arrowSize,arrowSize);
  81536. this.mapArrows = new Object3D;
  81537. this.mapArrows.name = 'mapArrows';
  81538. this.mapMeshGroup.add(this.mapArrows);
  81539. this.mapMeshGroup.name = 'mapRouteLayer';
  81540. this.mapMeshGroup.visible = false;
  81541. viewer.mapViewer.dispatchEvent({type:'add', object:this.mapMeshGroup, name:'route'});
  81542. this.mapArrow.layers.mask = this.mapArrows.layers.mask; // 修改成和map中的layer一样的
  81543. viewer.modules.SiteModel.bus.addEventListener('FloorChange',()=>{
  81544. if(this.routeStart && this.routeEnd){
  81545. this.updateOpacityAtMap();
  81546. }
  81547. });
  81548. this.inited = true;
  81549. }
  81550. updateOpacityAtMap(){//只有当前楼层的透明度为1
  81551. var currentFloor = viewer.modules.SiteModel.currentFloor;
  81552. //console.log('updateOpacityAtMap', currentFloor && currentFloor.name)
  81553. const lift = 0.3; // 因为发送请求时用的是floorPosition的高度,而它可能会到画好的floor之下,所以有误差
  81554. this.mapArrows.children.forEach((arrow,index)=>{
  81555. let pos = this.mapPoints[index].clone();
  81556. pos.z += lift;
  81557. let inSide = currentFloor && currentFloor.ifContainsPoint(pos);
  81558. arrow.material = inSide ? this.mapArrowMats.default : this.mapArrowMats.fade;
  81559. //console.log('arrow',index, arrow.material.opacity)
  81560. });
  81561. viewer.mapViewer.dispatchEvent('content_changed');
  81562. }//但是如果楼层刚好只框柱相机位置而没框住地面位置就不好了……
  81563. createPole(polesMats, name){
  81564. const height = 1.5, sphereCount = 6, shadowSize = sphereSizeInfo.scale, sphereSize = 0.04;
  81565. var group = new Object3D;
  81566. group.name = 'pole_'+name;
  81567. var shadow = new Mesh(planeGeo$4,polesMats.shadowMat);
  81568. shadow.scale.set(shadowSize,shadowSize,shadowSize);
  81569. var sliceDis = height / (sphereCount+1);
  81570. group.add(shadow);
  81571. for(let i=0;i<sphereCount;i++){
  81572. var sphere = new Sprite$1({mat: polesMats.sphereMat});
  81573. sphere.position.set(0,0,sliceDis*(i+1));
  81574. sphere.scale.set(sphereSize,sphereSize,sphereSize);
  81575. sphere.visible = false;
  81576. group.add(sphere);
  81577. }
  81578. var hatSphere = new Sprite$1({mat: polesMats.hatMats[name], sizeInfo:sphereSizeInfo});
  81579. sphere.visible = false;
  81580. hatSphere.position.set(0,0,height);
  81581. hatSphere.scale.copy(shadow.scale);
  81582. group.add(hatSphere);
  81583. return group
  81584. }
  81585. addTestArrow(){
  81586. }
  81587. addArrow(position){
  81588. var arrow = this.arrow.clone();
  81589. arrow.position.copy(position);
  81590. this.arrows.add(arrow);
  81591. }
  81592. addMapArrow(position){
  81593. var mapArrow = this.mapArrow.clone();
  81594. mapArrow.position.copy(position).setZ(0);
  81595. this.mapArrows.add(mapArrow);
  81596. }
  81597. setArrowDir(arrows,index){
  81598. let arrow = arrows[index];
  81599. var nextOne = arrows[index+1];
  81600. var nextPos = nextOne ? nextOne.position : this.endPolePos; //routeEnd
  81601. var direction = new Vector3().subVectors(arrow.position, nextPos).setZ(0);
  81602. //direction.normalize();
  81603. //console.log(direction.toArray())
  81604. var angle = Math.atan2(direction.y, direction.x ) + Math.PI/2; //Math.PI/2是因为贴图本身箭头方向不朝x
  81605. arrow.rotation.z = angle;
  81606. //console.log(angle)
  81607. }
  81608. setRouteStart(pos, dealZ , datasetId ){
  81609. if(this.routeStart && pos && this.routeStart.equals(pos)) return //可能重复设置
  81610. this.routeStart = pos && new Vector3().copy(pos);
  81611. if(dealZ && this.routeStart){
  81612. this.routeStart.setZ(this.getZAtMap());
  81613. this.bus && this.bus.emit('reposStartMarker', this.routeStart);
  81614. }
  81615. console.log('setRouteStart',this.routeStart&&this.routeStart.toArray());
  81616. this.datasetIds[0] = datasetId;
  81617. //this.setStartPole(pos)
  81618. this.generateRoute();
  81619. }
  81620. setStartPole(pos){
  81621. this.startPolePos = pos;
  81622. this.bus && this.bus.emit('reposStartMarker', pos);
  81623. }
  81624. setRouteEnd(pos, dealZ , datasetId ){
  81625. if(this.routeEnd && pos && this.routeEnd.equals(pos)) return
  81626. this.routeEnd = pos && new Vector3().copy(pos);
  81627. if(dealZ && this.routeEnd){
  81628. this.routeEnd.setZ(this.getZAtMap());
  81629. this.bus && this.bus.emit('reposEndMarker', this.routeEnd);
  81630. }
  81631. console.log('setRouteEnd',this.routeEnd&&this.routeEnd.toArray());
  81632. this.datasetIds[1] = datasetId;
  81633. //this.setEndPole(pos)
  81634. this.generateRoute();
  81635. }
  81636. getZAtMap(){
  81637. //找到position.z与当前高度最接近的漫游点
  81638. let result = Common.sortByScore(viewer.images360.panos,[],[e=> -(Math.abs(e.position.z - viewer.images360.position.z)) ]);
  81639. let pano = result && result[0] && result[0].item;
  81640. return pano ? pano.floorPosition.z : viewer.bound.boundingBox.min.z + 1
  81641. //若在平面图上画实在得不到当前楼层的,大概率是楼层画得不好,那就只能去获取当前楼层的了
  81642. //navvis的高度取的是主视图所在楼层的中心高度(可能再高些)
  81643. }
  81644. setEndPole(pos){
  81645. this.endPolePos = pos;
  81646. this.bus && this.bus.emit('reposEndMarker', pos);
  81647. }
  81648. getSourceProjectionIndex(route) {//真正的起始
  81649. var e = route.findIndex(function(t) {
  81650. return t.instruction && t.instruction.type === 'source_projection_to_navgraph'
  81651. });
  81652. return e < 0 ? 0 : e
  81653. }
  81654. getDestinationProjectionIndex(route) {//真正的终点
  81655. var e = route.findIndex(function(t) {
  81656. return t.instruction && t.instruction.type === "destination_projection_to_navgraph"
  81657. });
  81658. return e < 0 ? route.length - 1 : e
  81659. }
  81660. generateRoute(){
  81661. if(!this.routeStart || !this.routeEnd){
  81662. return
  81663. }
  81664. //array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
  81665. let create = ()=>{
  81666. this.routeLength = this.route.reduce((total, currentValue, currentIndex, arr)=>{
  81667. if(currentIndex == 0)return 0
  81668. return total + currentValue.distanceTo(arr[currentIndex-1]);
  81669. },0);
  81670. let count = Math.max(2,Math.round(this.routeLength / arrowSpacing));//点数
  81671. const curve = new CatmullRomCurve3( this.route );
  81672. curve.curveType = 'chordal';//'centripetal' 'catmullrom'这个可能会超出路径外
  81673. this.curve = curve;
  81674. const scenePoints = curve.getSpacedPoints( count );//更平均
  81675. //const scenePoints = curve.getPoints( count );
  81676. scenePoints.splice(0,1);//去掉首尾
  81677. scenePoints.pop();
  81678. this.scenePoints = scenePoints;
  81679. this.updateMapArrows();
  81680. this.displayRoute();
  81681. {//map focus on this area
  81682. const minBound = new Vector2$1(1,1);//针对垂直线,在地图上只有一个点
  81683. let bound = new Box2;
  81684. this.route.forEach(e=>{
  81685. bound.expandByPoint(e);
  81686. });
  81687. let size = bound.getSize(new Vector2$1);
  81688. let markerSize = new Vector2$1(115,40); //起始和终点的标识呈长方形
  81689. let areaSize = viewer.mapViewer.viewports[0].resolution2;
  81690. let areaArea = areaSize.x * areaSize.y;
  81691. if(areaArea> 800 * 400){//是放大的
  81692. markerSize.multiplyScalar(areaArea / (800 * 400) /* / (size.x * size.y) */);
  81693. }
  81694. let margin = size.clone().divide(viewer.mapViewer.viewports[0].resolution2).multiply(markerSize); ///边距 重点是起始和终点的标识占据较大
  81695. size.add(margin);
  81696. let center = bound.getCenter(new Vector2$1);
  81697. size.x = Math.max(size.x, minBound.x );
  81698. size.y = Math.max(size.y, minBound.y );
  81699. let duration = 1000;
  81700. viewer.mapViewer.moveTo(center, size, duration);
  81701. }
  81702. this.bus.emit('gotResult', {dis:this.routeLength});
  81703. /* this.generateDeferred && this.generateDeferred.resolve({dis:this.routeLength})
  81704. this.generateDeferred = null */
  81705. };
  81706. if(Potree.fileServer){
  81707. let dealData = (data)=>{
  81708. if(!data.data){
  81709. console.log('没有数据');
  81710. let result;
  81711. if(data && data.code == 4002){
  81712. result = data;//正被修改数据集
  81713. }else if(this.routeStart.distanceTo(this.routeEnd) < 1){
  81714. result = { code: 500, msg: '距离太短,无法规划路线' };
  81715. }else {
  81716. result = { code: 500, msg: '超出数据集范围,无法规划路线' };
  81717. }
  81718. this.clearRoute();
  81719. this.setStartPole(this.routeStart);
  81720. this.setEndPole(this.routeEnd);
  81721. this.displayRoute(); //还是要显示一下起始
  81722. this.bus && this.bus.emit('gotResult', result );
  81723. return //this.generateDeferred && this.generateDeferred.resolve()
  81724. }
  81725. data = data.data;
  81726. this.clearRoute();
  81727. let length = data.length;
  81728. if(length < 2){//可能距离太短
  81729. console.log('路径点数为'+length+',直接取起点和终点连线');
  81730. this.route = [this.routeStart, this.routeEnd];
  81731. }else {
  81732. let startIndex = this.getSourceProjectionIndex(data);
  81733. let endIndex = this.getDestinationProjectionIndex(data);
  81734. let effectiveItems = data.slice(startIndex, endIndex + 1 );//只要点云范围内的点
  81735. effectiveItems.forEach((item,i)=>{
  81736. let pos = viewer.transform.lonlatToLocal.forward(item.location.slice(0));
  81737. pos = new Vector3().fromArray(pos);//.setZ(item.z)
  81738. this.route.push(pos);
  81739. });
  81740. console.log(this.route);
  81741. }
  81742. this.setStartPole(this.route[0]);
  81743. this.setEndPole(this.route[this.route.length-1]);
  81744. create();
  81745. /*
  81746. distance: 0.17581000000000116
  81747. distance_to_previous: 0.17581000000000116
  81748. id: 567
  81749. instruction: {type: 'source_projection_to_navgraph'}
  81750. latitude: 22.366605927999238
  81751. location: (3) [113.5957510575092, 22.366605927999238, -1.12419]
  81752. longitude: 113.5957510575092
  81753. z: -1.12419
  81754. */
  81755. };
  81756. if(this.lastResult && (this.lastResult.data || this.lastResult.data.code != 4002)){//正被修改数据集的话要重新计算
  81757. let data = Common.CloneObject(this.lastResult.data) , use; //直接用上次的结果
  81758. if(this.lastResult.routeStart.equals(this.routeStart) && this.lastResult.routeEnd.equals(this.routeEnd)){//和上次请求相同
  81759. use = true;
  81760. }else if(this.lastResult.routeStart.equals(this.routeEnd) && this.lastResult.routeEnd.equals(this.routeStart)){//..反向
  81761. use = true;
  81762. if(data.data){
  81763. data.data = this.lastResult.data.data.slice(0).reverse();
  81764. }
  81765. }
  81766. if(use){
  81767. console.log('直接用上次的结果');
  81768. return setTimeout(()=>{dealData(data);}, 1)//延迟是为了等待获得 RouteGuider.generateDeferred
  81769. }
  81770. }
  81771. let start = this.routeStart.clone();
  81772. let end = this.routeEnd.clone();
  81773. let startLonlat = viewer.transform.lonlatToLocal.inverse(start);
  81774. let endLonlat = viewer.transform.lonlatToLocal.inverse(end);
  81775. var query = {
  81776. source_longitude: startLonlat.x,
  81777. source_latitude: startLonlat.y,
  81778. source_z: start.z,
  81779. destination_longitude: endLonlat.x,
  81780. destination_latitude: endLonlat.y,
  81781. destination_z: end.z
  81782. };
  81783. //let url = `/laser/route/${Potree.settings.number}/getRoute/${this.datasetIds[0]}/${this.datasetIds[1]}?`
  81784. let url = `/laser/route/${Potree.settings.number}/getRoute/${Potree.settings.originDatasetId}?`;
  81785. for(let i in query){
  81786. url+= (i + '='+ query[i] +'&');
  81787. }
  81788. Potree.fileServer.get(url).then((data)=>{
  81789. console.log(data.data);
  81790. if(!this.routeStart || !this.routeEnd)return
  81791. this.lastResult = {//保存数据
  81792. routeStart : this.routeStart.clone(),
  81793. routeEnd: this.routeEnd.clone(),
  81794. data,
  81795. };
  81796. dealData(data);
  81797. });
  81798. }else {
  81799. //创个直线
  81800. /* const sliceDis = 1
  81801. let dis = this.routeStart.distanceTo(this.routeEnd);
  81802. let count = Math.max(2,Math.round(dis / sliceDis))//点数
  81803. let realSlideDis = dis / (count-1);
  81804. let dir = new THREE.Vector3().subVectors(this.routeEnd, this.routeStart).normalize().multiplyScalar(realSlideDis);
  81805. this.route = [this.routeStart];
  81806. for(let i=0;i<count-1;i++){
  81807. let lastOne = this.route[i];
  81808. this.route.push(new THREE.Vector3().addVectors(lastOne,dir))
  81809. }
  81810. this.route.splice(0,1) //route不用包含收尾 */
  81811. this.clearRoute();
  81812. this.route = [this.routeStart, this.routeEnd];
  81813. create();
  81814. }
  81815. }
  81816. updateMapArrows(ifReset){
  81817. if(this.route.length == 0)return
  81818. var zoom = viewer.mapViewer.camera.zoom;
  81819. let count = Math.max(2,Math.round(this.routeLength * zoom / arrowSpacing / 25));//点数
  81820. if(count == this.mapPoints.length+1)return//没变
  81821. const mapPoints = this.curve.getSpacedPoints( count );
  81822. mapPoints.splice(0,1);//去掉首尾
  81823. mapPoints.pop();
  81824. this.mapPoints = mapPoints;
  81825. var scale = 25/zoom;
  81826. this.mapArrow.scale.set(scale*0.6,scale*0.6,scale*0.6);
  81827. /* this.mapMarkStart.scale.set(scale,scale,scale)
  81828. this.mapMarkEnd.scale.set(scale,scale,scale) */
  81829. if(ifReset){//因为缩放而重新排布箭头
  81830. this.clearRoute({resetMap:true});
  81831. this.displayRoute({resetMap:true});
  81832. }
  81833. this.updateOpacityAtMap();
  81834. }
  81835. updateArrowDisplay(){//根据当前位置更新显示一定范围内的箭头'
  81836. if(this.scenePoints.length == 0)return
  81837. /* var a = Common.sortByScore(this.scenePoints , null, [(point)=>{ //是否还要再requires里限制最远距离?
  81838. var playerPos = viewer.scene.getActiveCamera().position.clone().setZ(0)
  81839. var pos = point.clone().setZ(0)
  81840. return -pos.distanceTo(playerPos);
  81841. }]);
  81842. //获得展示的起始点
  81843. let start = a[0].item
  81844. let startIndex = this.scenePoints.indexOf(start)
  81845. this.arrows.children.forEach((e,i)=>{
  81846. if(i<startIndex || i>startIndex+arrowsShowingCount)e.visible = false
  81847. else e.visible = true
  81848. }) */
  81849. let cameraPos = viewer.scene.getActiveCamera().position;
  81850. this.arrows.children.forEach((e,i)=>{
  81851. if(e.position.distanceTo(cameraPos) < arrowShowMinDis) e.visible = true;
  81852. else e.visible = false;
  81853. });
  81854. }
  81855. displayRoute(o={}){
  81856. if(!o.resetMap){
  81857. this.poleStart.position.copy(this.startPolePos || this.routeStart);
  81858. this.poleEnd.position.copy(this.endPolePos || this.routeEnd);
  81859. /* this.mapMarkStart.position.copy(this.routeStart).setZ(0)
  81860. this.mapMarkEnd.position.copy(this.routeEnd).setZ(0) */
  81861. this.scenePoints.forEach(e=>this.addArrow(e));
  81862. this.arrows.children.forEach((e,i)=>this.setArrowDir(this.arrows.children,i));
  81863. }
  81864. this.sceneMeshGroup.traverse(e=>e.visible = true);
  81865. this.mapMeshGroup.visible = true;
  81866. this.mapPoints.forEach(e=>this.addMapArrow(e));
  81867. this.mapArrows.children.forEach((e,i)=>this.setArrowDir(this.mapArrows.children,i));
  81868. viewer.mapViewer.dispatchEvent({'type':'content_changed'});
  81869. this.updateArrowDisplay();
  81870. }
  81871. clearRoute(o={}){
  81872. if(!o.resetMap){
  81873. this.routeLength = 0;
  81874. this.route = [];
  81875. this.scenePoints = [];
  81876. this.mapPoints = [];
  81877. let arrows = this.arrows.children.slice(0);
  81878. arrows.forEach(e=>{
  81879. this.arrows.remove(e);
  81880. });
  81881. }
  81882. let mapArrows = this.mapArrows.children.slice(0);
  81883. mapArrows.forEach(e=>{
  81884. this.mapArrows.remove(e);
  81885. });
  81886. this.sceneMeshGroup.traverse(e=>e.visible = false); //包括sprite也要设置,防止update
  81887. this.mapMeshGroup.visible = false;
  81888. viewer.mapViewer.dispatchEvent({'type':'content_changed'});
  81889. }
  81890. clear(){//退出
  81891. console.log('导航clear');
  81892. this.routeStart = null;
  81893. this.routeEnd = null;
  81894. this.clearRoute();
  81895. }
  81896. }
  81897. //大概每十米要花一秒
  81898. /*
  81899. 存在的问题:
  81900. 路径不准确。起始点和终点偏移。
  81901. */
  81902. const vertexShader = `
  81903. attribute float randam;
  81904. attribute float sprite;
  81905. attribute float centerHeight; //add
  81906. //uniform float fireHeight; //add
  81907. uniform float time;
  81908. uniform float size;
  81909. uniform float heightOfNearPlane;
  81910. //varying float heightRatio;
  81911. varying float vSprite;
  81912. varying float vOpacity;
  81913. float PI = 3.14;
  81914. float quadraticIn( float t )
  81915. {
  81916. float tt = t * t;
  81917. return tt * tt;
  81918. //变化曲线 越来越快
  81919. }
  81920. void main() {
  81921. float progress = fract( time + ( 2.0 * randam - 1.0 ) );
  81922. float progressNeg = 1.0 - progress;
  81923. float ease = quadraticIn( progress );
  81924. float influence = sin( PI * ease );
  81925. //vec3 newPosition = position * vec3( 1.0, 1.0 , ease);
  81926. vec3 newPosition = position;
  81927. newPosition.z = (newPosition.z - centerHeight) * ease + centerHeight;
  81928. gl_Position = projectionMatrix * modelViewMatrix * vec4( newPosition, 1.0 );
  81929. gl_PointSize = ( heightOfNearPlane * size ) / gl_Position.w;
  81930. vOpacity = min( influence * 4.0, 1.0 ) * progressNeg;
  81931. vSprite = sprite;
  81932. //heightRatio = (newPosition.z - centerHeight) / fireHeight ;
  81933. }
  81934. `;
  81935. const fragmentShader = `
  81936. uniform vec3 color;
  81937. uniform sampler2D u_sampler;
  81938. varying float vSprite;
  81939. varying float vOpacity;
  81940. //varying float heightRatio;
  81941. void main()
  81942. {
  81943. vec2 texCoord = vec2(gl_PointCoord.x * 0.25 + vSprite, gl_PointCoord.y);
  81944. gl_FragColor = vec4( texture2D( u_sampler, texCoord ).xyz * color * vOpacity, 1.0 );
  81945. }
  81946. `;
  81947. // import { vertexShader, fragmentShader } from './shaders'
  81948. let ONE_SPRITE_ROW_LENGTH = 0.25; //对应着色器的0.25
  81949. let texture;
  81950. const getTexture = ()=>{
  81951. if(!texture){
  81952. texture = new TextureLoader().load( Potree.resourcePath+'/textures/fire.png');
  81953. }
  81954. return texture
  81955. };
  81956. const boxGeo = new BoxBufferGeometry(1,1,1,1);
  81957. const boxMat = new MeshBasicMaterial({wireframe:true, color:"#ffffff"});
  81958. class FireParticle extends Points{
  81959. constructor (prop) {
  81960. super();
  81961. for ( var key in prop ){
  81962. this[key] = prop[key];
  81963. }
  81964. this.strength = this.strength || 1;
  81965. this.radius = prop.radius || 1;
  81966. this.height = prop.height || 5;
  81967. this.computeParams();
  81968. this.geometry = this.createGeometry( this.radius, this.height, this.particleCount );
  81969. if(this.color == void 0) this.color = 0xff3200;
  81970. this.createMaterial( ); //小蓝火:0x00338f
  81971. //---?:
  81972. this.velocity = new Vector3();
  81973. this.acceleration = new Vector3();
  81974. this.angle = 0;
  81975. this.angleVelocity = 0;
  81976. this.angleAcceleration = 0;
  81977. this.size = 16;
  81978. this.opacity = 1;
  81979. this.age = 0;
  81980. this.alive = 0;
  81981. this.sizeTween = null;
  81982. this.colorTween = null;
  81983. this.opacityTween = null;
  81984. this.setSize({viewport:viewer.mainViewport});
  81985. this.setFov(viewer.fov);
  81986. let setSize = (e)=>{
  81987. if(e.viewport.name != "MainView")return
  81988. this.setSize(e);
  81989. };
  81990. let setFov = (e)=>{
  81991. this.setFov(e.fov);
  81992. };
  81993. viewer.addEventListener('resize',setSize);
  81994. viewer.addEventListener('fov_changed',setFov);
  81995. this.addEventListener('dispose',()=>{
  81996. viewer.removeEventListener('resize',setSize);
  81997. viewer.removeEventListener('fov_changed',setFov);
  81998. });
  81999. }
  82000. computeParams(){
  82001. let length = (this.curve ? this.curve.wholeLength : 0) + this.radius * 2; //加上首尾的半径
  82002. const minSize = 0.3, maxSize = 3, minRadiusBound = 0.3, maxRadiusBound = 10;
  82003. this.size = minSize + (maxSize - minSize) * MathUtils.smoothstep(this.radius, minRadiusBound, maxRadiusBound);
  82004. //console.log('fire material particle size:', size )
  82005. this.particleCount = Math.ceil( length * Math.sqrt(this.strength * this.height ) * this.radius / (this.size * this.size) * 25 );
  82006. //console.log('fire particleCount',this.particleCount)
  82007. }
  82008. getPointsForBound(){
  82009. return this.boundPoints; //可以用于expand实时bound的点, 不含particle的size等边距
  82010. }
  82011. getBound(points){ // points为生成点(圆心)
  82012. this.boundPoints = [];
  82013. let boundingBox = new Box3();
  82014. let margin = this.size * 0.13 + 0.3;
  82015. points.forEach(bottom=>{
  82016. let top = bottom.clone();
  82017. top.z += this.height;
  82018. boundingBox.expandByPoint(bottom);
  82019. boundingBox.expandByPoint(top);
  82020. this.boundPoints.push(bottom,top);
  82021. });
  82022. let xyExpand = this.radius+margin;
  82023. boundingBox.expandByVector(new Vector3(xyExpand,xyExpand,margin));
  82024. this.boundingBox = boundingBox;
  82025. /* if(!this.debugBox){
  82026. this.debugBox = new THREE.Mesh(boxGeo, boxMat)
  82027. this.add(this.debugBox)
  82028. }
  82029. this.debugBox.scale.copy(boundingBox.getSize(new THREE.Vector3))
  82030. this.debugBox.position.copy(boundingBox.getCenter(new THREE.Vector3)) */
  82031. }
  82032. createGeometry( radius, height, particleCount){
  82033. let geometry = new BufferGeometry();
  82034. let count , points;
  82035. if(this.positions.length>1){
  82036. const spaceDis = 0.2;//间隔距离
  82037. count = Math.ceil(this.curve.wholeLength / spaceDis) + 1;
  82038. //console.log('count', count)
  82039. points = this.curve.getSpacedPoints( count ); //得到的数量会比count多一个
  82040. count = points.length;
  82041. //得到的点不太均匀,两端容易点少。
  82042. this.getBound(points);
  82043. }else {
  82044. this.getBound(this.positions);
  82045. }
  82046. var position = new Float32Array(particleCount * 3);
  82047. var randam = new Float32Array(particleCount);
  82048. var sprite = new Float32Array(particleCount);
  82049. var centerHeight = new Float32Array(particleCount);
  82050. for (var i = 0; i < particleCount; i++) {
  82051. var center = new Vector3().copy(this.positions.length>1 ? points[Math.floor(i/particleCount * count)] : this.positions[0]);
  82052. centerHeight[i] = center.z;
  82053. if (i === 0) {
  82054. // to avoid going out of Frustum
  82055. position[i * 3 + 0] = center.x;
  82056. position[i * 3 + 1] = center.y;
  82057. position[i * 3 + 2] = center.z;
  82058. }else {
  82059. var r = Math.sqrt(Math.random()) * radius;
  82060. var angle = Math.random() * 2 * Math.PI;
  82061. position[i * 3 + 0] = center.x + Math.cos(angle) * r;
  82062. position[i * 3 + 1] = center.y + Math.sin(angle) * r;
  82063. position[i * 3 + 2] = center.z + (radius - r) / radius * height/2 + height/2; //不太明白这句为什么能达到height高度
  82064. sprite[i] = 0.25 * (Math.random() * 4 | 0);
  82065. randam[i] = Math.random();
  82066. //center在底部
  82067. }
  82068. }
  82069. geometry.setAttribute('centerHeight', new BufferAttribute(centerHeight, 1));
  82070. geometry.setAttribute('position', new BufferAttribute(position, 3));
  82071. geometry.setAttribute('randam', new BufferAttribute(randam, 1));
  82072. geometry.setAttribute('sprite', new BufferAttribute(sprite, 1));
  82073. return geometry;
  82074. }
  82075. updateGeometry(){
  82076. this.computeParams();
  82077. this.geometry.dispose();
  82078. this.geometry = this.createGeometry( this.radius, this.height, this.particleCount );
  82079. this.material.uniforms.size.value = this.size;
  82080. }
  82081. createMaterial(){
  82082. const material = new ShaderMaterial( {
  82083. uniforms:{
  82084. color: { type: "c", value: new Color(this.color) },
  82085. size: { type: "f", value: this.size},
  82086. u_sampler: { type: "t", value: getTexture() },
  82087. time: { type: "f", value: 0.0 },
  82088. heightOfNearPlane: { type: "f", value:0}, //相对far ,以确保画面缩放时点的大小也会缩放
  82089. height :{ type: "f", value:this.height} ,
  82090. },
  82091. vertexShader,
  82092. fragmentShader,
  82093. blending: AdditiveBlending, //加法融合模式 glBlendFunc(GL_ONE, GL_ONE)
  82094. depthTest: true,
  82095. depthWrite: false,
  82096. transparent: true
  82097. } );
  82098. this.material = material;
  82099. this.setPerspective(this.fov, this.screenHeight);
  82100. }
  82101. setSize(e){
  82102. let viewport = e.viewport;
  82103. this.screenHeight = viewport.resolution.y;
  82104. this.setPerspective(this.fov, this.screenHeight);
  82105. }
  82106. setFov(fov){
  82107. this.fov = fov;
  82108. this.setPerspective(this.fov, this.screenHeight);
  82109. }
  82110. setPerspective(fov, height){
  82111. //this.uniforms.heightOfNearPlane.value = Math.abs(height / (2 * Math.tan(THREE.Math.degToRad(fov * 0.5))));
  82112. let far = Math.abs(height / (2 * Math.tan(MathUtils.degToRad(fov * 0.5))));
  82113. this.material.uniforms.heightOfNearPlane.value = far;
  82114. }
  82115. update(delta){
  82116. if(!viewer.getObjVisiByReason(this,'force')){//被手动隐藏了
  82117. return
  82118. }
  82119. if(!Potree.Utils.isInsideFrustum(this.boundingBox, viewer.scene.getActiveCamera())){
  82120. viewer.updateVisible(this,'isInsideFrustum', false ); //不在视野范围
  82121. //console.log('unvi')
  82122. return
  82123. }else {
  82124. viewer.updateVisible(this,'isInsideFrustum', true );
  82125. }
  82126. delta *= 1;//更改速度
  82127. this.material.uniforms.time.value = (this.material.uniforms.time.value + delta) % 1;
  82128. }
  82129. dispose(){
  82130. this.geometry.dispose();
  82131. this.material.dispose();
  82132. this.dispatchEvent('dispose');
  82133. }
  82134. }
  82135. class Tween {
  82136. constructor(times, values) {
  82137. this.times = times || [];
  82138. this.values = values || [];
  82139. }
  82140. lerp(t) {
  82141. if(this.times.length == 0) return
  82142. let i = 0, n = this.times.length;
  82143. while(i < n && t > this.times[i]) i++;
  82144. if(i == 0) return this.values[0]
  82145. if(i == n) return this.values[n-1]
  82146. const ratio = (t - this.times[i-1]) / (this.times[i] - this.times[i-1]);
  82147. if(this.values[0] instanceof Vector3) {
  82148. return this.values[i-1].clone().lerp(this.values[i], ratio)
  82149. } else {
  82150. return this.values[i-1] + ratio * (this.values[i] - this.values[i-1])
  82151. }
  82152. }
  82153. clone () {
  82154. return Common.CloneClassObject(this)
  82155. }
  82156. }
  82157. class Particle$1{
  82158. constructor(prop={}){
  82159. this.position = new Vector3();
  82160. this.velocity = new Vector3(); // units per second
  82161. this.angle = 0;
  82162. this.angleVelocity = 0; // degrees per second
  82163. this.angleAcceleration = 0; // degrees per second, per second
  82164. this.size = 16.0;
  82165. this.color = new Color();
  82166. this.opacity = 1.0;
  82167. this.age = 0;
  82168. this.alive = 0; // use float instead of boolean for shader purposes
  82169. this.lastChangeVage = 0; //add
  82170. this.sizeTween = prop.sizeTween || new Tween( [0, 1], [32, 128] );
  82171. this.opacityTween = prop.opacityTween || new Tween( [0.8, 2], [0.5, 0] );
  82172. this.colorTween = prop.colorTween || new Tween( [0.4, 1], [ new Vector3(0,0,0.2), new Vector3(0, 0, 0.5) ] );
  82173. }
  82174. update(dt)
  82175. {
  82176. this.position.add(this.velocity.clone().multiplyScalar(dt));
  82177. this.velocity.multiplyScalar( 1+this.acceleration*dt );
  82178. // convert from degrees to radians: 0.01745329251 = Math.PI/180
  82179. this.angle += this.angleVelocity * 0.01745329251 * dt;
  82180. this.angleVelocity += this.angleAcceleration * 0.01745329251 * dt;
  82181. this.age += dt;
  82182. // if the tween for a given attribute is nonempty,
  82183. // then use it to update the attribute's value
  82184. if ( this.sizeTween.times.length > 0 )
  82185. this.size = this.sizeTween.lerp( this.age/this.deathAge );
  82186. if ( this.colorTween.times.length > 0 )
  82187. {
  82188. var colorHSL = this.colorTween.lerp( this.age/this.deathAge );
  82189. this.color = new Color().setHSL( colorHSL.x, colorHSL.y, colorHSL.z );
  82190. }
  82191. if ( this.opacityTween.times.length > 0 )
  82192. {
  82193. this.opacity = this.opacityTween.lerp( this.age/this.deathAge);
  82194. }
  82195. }
  82196. }
  82197. const vertexShader$1 = `
  82198. attribute vec3 customColor;
  82199. attribute float customOpacity;
  82200. attribute float customSize;
  82201. attribute float customAngle;
  82202. attribute float customVisible;
  82203. uniform float heightOfNearPlane;
  82204. varying vec4 vColor;
  82205. varying float vAngle;
  82206. void main()
  82207. {
  82208. if ( customVisible > 0.5 )
  82209. vColor = vec4( customColor, customOpacity );
  82210. else
  82211. vColor = vec4(0.0, 0.0, 0.0, 0.0);
  82212. vAngle = customAngle;
  82213. vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
  82214. //gl_PointSize = customSize * ( 300.0 / length( mvPosition.xyz ) );
  82215. gl_Position = projectionMatrix * mvPosition;
  82216. gl_PointSize = ( heightOfNearPlane * customSize ) / gl_Position.w;
  82217. }
  82218. `;
  82219. const fragmentShader$1 = `
  82220. uniform sampler2D u_sampler;
  82221. varying vec4 vColor;
  82222. varying float vAngle;
  82223. void main()
  82224. {
  82225. gl_FragColor = vColor;
  82226. float c = cos(vAngle);
  82227. float s = sin(vAngle);
  82228. 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);
  82229. vec4 rotatedTexture = texture2D( u_sampler, rotatedUV );
  82230. gl_FragColor = gl_FragColor * rotatedTexture;
  82231. }
  82232. `;
  82233. const Type = Object.freeze({ "CUBE":1, "SPHERE":2 });
  82234. let particleTexture;
  82235. const getTexture$1 = ()=>{
  82236. if(!particleTexture){
  82237. particleTexture = new TextureLoader().load( Potree.resourcePath+'/textures/smokeparticle.png');
  82238. }
  82239. return particleTexture
  82240. };
  82241. const boxGeo$1 = new BoxBufferGeometry(1,1,1,1);
  82242. const boxMat$1 = new MeshBasicMaterial({wireframe:true, color:"#ffffff"});
  82243. const defaults =
  82244. {
  82245. positions: [],
  82246. positionStyle : "sphere",
  82247. positionBase : new Vector3( 0, 0, 0 ),
  82248. positionSpread : new Vector3( 1, 1, 0), //cube
  82249. radius : 1, // sphere
  82250. velocityStyle : 'cube',
  82251. velocityBase : new Vector3( 0, 0, 0.5), // cube 基础速度
  82252. velocitySpread : new Vector3( 1, 1, 0.3),
  82253. accelerationBase : 0.3, //基础加速度
  82254. accelerationSpread : 0.6,
  82255. //没使用
  82256. speedBase : 0.1, //sphere
  82257. speedSpread : 0.5,
  82258. angleBase : 0,
  82259. angleSpread : 360,
  82260. angleVelocityBase : 1,
  82261. angleVelocitySpread : 30,
  82262. angleAccelerationBase : 1,
  82263. angleAccelerationSpread : 5,
  82264. sizeBase : 0,
  82265. sizeSpread : 0,
  82266. sizeTween : [[0, 0.3, 1], [0.3, 1.4, 6 ]],
  82267. colorBase : new Vector3(0.0, 1.0, 0.5),
  82268. colorSpread : new Vector3(0.0, 0.0, 0.0),
  82269. colorTween : new Tween( [0.2, 1], [ new Vector3(0,0,0.4), new Vector3(0, 0, 0.1) ] ),
  82270. opacityBase : 0.1,//1.0,
  82271. opacitySpread : 0.2,
  82272. opacityTween :[ [0, 0.1, 0.9, 1], [0.1, 0.4 , 0.03, 0 ] ],
  82273. //particlesPerSecond : 20,
  82274. strength : 1,
  82275. particleDeathAge : 3, //从底下升起后能持续的时间
  82276. //emitterDeathAge : 60 // time (seconds) at which to stop creating particles.
  82277. height : 3,
  82278. };
  82279. const debugSphere = new Mesh(new SphereBufferGeometry(0.03, 5,5), new MeshBasicMaterial({color:'white',depthTest:false}));
  82280. class SmokeParticle extends Points{
  82281. constructor(prop={}) {
  82282. super();
  82283. this.blendStyle = NormalBlending; // false;
  82284. this.emitterAge = 0.0;
  82285. //this.emitterAlive = true;
  82286. prop = $.extend({}, defaults, prop);
  82287. for ( var key in prop ){
  82288. let value = prop[key];
  82289. if(value instanceof Array && value[0] instanceof Array ) this[ key ] = new Tween(...value);
  82290. else if(value instanceof Vector3 || value instanceof Color){
  82291. this[ key ] = value.clone();
  82292. }else {
  82293. this[ key ] = value;
  82294. }
  82295. }
  82296. this.defaultSizeTween = this.sizeTween.clone();
  82297. this.defaultOpacityTween = this.opacityTween.clone();
  82298. this.geometry = new BufferGeometry();
  82299. this.computeParams();
  82300. this.createMaterial();
  82301. this.createGeometry();
  82302. this.dynamic = true;
  82303. this.sortParticles = true;
  82304. this.frustumCulled = false;//似乎是禁止相机裁剪,否则会在某些角度消失。但是会不会更耗性能呢?
  82305. prop.position && this.position.copy(prop.position);
  82306. //---------------------------------------
  82307. this.setSize({viewport:viewer.mainViewport});
  82308. this.setFov(viewer.fov);
  82309. let setSize = (e)=>{
  82310. if(e.viewport.name != "MainView")return
  82311. this.setSize(e);
  82312. };
  82313. let setFov = (e)=>{
  82314. this.setFov(e.fov);
  82315. };
  82316. /* let reStart = (e)=>{
  82317. if(e.v){//重新一个个放出粒子,否则会一股脑儿全部出来,因为同时大于粒子周期了一起重新生成出现。
  82318. setTimeout(()=>{//会先update一次delta为pageUnvisile的时间才触发
  82319. //console.log('归零')
  82320. //this.reStart()
  82321. },1)
  82322. }
  82323. } */
  82324. viewer.addEventListener('resize',setSize);
  82325. viewer.addEventListener('fov_changed',setFov);
  82326. //viewer.addEventListener('pageVisible', reStart)
  82327. this.addEventListener('dispose',()=>{
  82328. viewer.removeEventListener('resize',setSize);
  82329. viewer.removeEventListener('fov_changed',setFov);
  82330. //viewer.removeEventListener('pageVisible', reStart)
  82331. });
  82332. }
  82333. computeParams(){
  82334. let length = (this.curve ? this.curve.wholeLength : 0) + this.radius * 2; //加上首尾的半径
  82335. //注意:烟最低高度一米, 0<strength<1
  82336. if(this.positionStyle == 'cube'){
  82337. this.positionSpread.set(this.radius,this.radius,0);
  82338. }
  82339. this.velocityBase.set(0,0, (this.height - 0.5 * this.accelerationBase * this.particleDeathAge * this.particleDeathAge) / this.particleDeathAge );
  82340. //let height = this.velocityBase.z * this.particleDeathAge + 0.5 * this.accelerationBase * this.particleDeathAge * this.particleDeathAge;//s = V0 * t + 0.5 * a * t*t ;
  82341. this.velocityBase.z = Math.max(0,this.velocityBase.z);
  82342. this.particleCount = Math.ceil( length * Math.sqrt(this.strength * this.height * this.radius ) );
  82343. this.particleCount = Math.max(5,this.particleCount);
  82344. {
  82345. const minSize = 1, maxSize = 2, minBound = 0.01, maxBound = 1;
  82346. let size = minSize + (maxSize - minSize) * MathUtils.smoothstep( this.strength, minBound, maxBound);
  82347. this.sizeTween.values = this.defaultSizeTween.values.map(e=> e*size);
  82348. }
  82349. {
  82350. const minSize = 1 , maxSize = 1.5, minBound = 0.01, maxBound = 1;
  82351. let opac = minSize + (maxSize - minSize) * MathUtils.smoothstep( this.strength, minBound, maxBound);
  82352. this.opacityTween.values = this.defaultOpacityTween.values.map(e=> e*opac );
  82353. }
  82354. //console.log('smoke particleCount',this.particleCount)
  82355. }
  82356. reStart(){
  82357. this.emitterAge = 0;
  82358. this.createGeometry();
  82359. }
  82360. updateGeometry(){
  82361. this.computeParams();
  82362. this.reStart();
  82363. }
  82364. createParticle(center)
  82365. {
  82366. var particle = new Particle$1({
  82367. sizeTween : this.sizeTween,
  82368. opacityTween : this.opacityTween,
  82369. colorTween : this.colorTween,
  82370. });
  82371. particle.deathAge = this.particleDeathAge;
  82372. particle.center = center;
  82373. if (this.positionStyle == 'cube')
  82374. particle.position = this.randomVector3( this.positionBase, this.positionSpread );
  82375. if (this.positionStyle == 'sphere')
  82376. {
  82377. /* var z = 2 * Math.random() - 1
  82378. var t = Math.PI * 2 * Math.random();
  82379. var r = Math.sqrt( 1 - z*z ) ;
  82380. var vec3 = new THREE.Vector3( r * Math.cos(t), r * Math.sin(t), z );
  82381. particle.position = new THREE.Vector3().addVectors( this.positionBase, vec3.multiplyScalar( this.radius ) );
  82382. */
  82383. //怎么改半径
  82384. let y = 2 * Math.random() - 1;
  82385. let t = Math.PI * 2 * Math.random();
  82386. let r = Math.sqrt( 1 - y*y ) ; //因为 r*r = 1-y*y = x*x + z*z = r*r(cos^2 + sin^2 );
  82387. let lowDownRatio = 0.2; //压低近平面
  82388. let vec3 = new Vector3( r * Math.cos(t), y, Math.abs(r * Math.sin(t) ) * lowDownRatio);
  82389. particle.position = new Vector3().addVectors( this.positionBase, vec3.multiplyScalar( this.radius ) );
  82390. }
  82391. particle.position.add(center);//add
  82392. if ( this.velocityStyle == 'cube' )
  82393. {
  82394. particle.velocity = this.randomVector3( this.velocityBase, this.velocitySpread );
  82395. }
  82396. if ( this.velocityStyle == 'sphere' )
  82397. {
  82398. //var direction = particle.position.clone()
  82399. var direction = new Vector3(0,0,1); //烟应该都是向上的
  82400. var speed = this.randomValue( this.speedBase, this.speedSpread );
  82401. particle.velocity = direction.normalize().multiplyScalar( speed );
  82402. }
  82403. particle.acceleration = this.randomValue( this.accelerationBase, this.accelerationSpread );
  82404. particle.angle = this.randomValue( this.angleBase, this.angleSpread );
  82405. particle.angleVelocity = this.randomValue( this.angleVelocityBase, this.angleVelocitySpread );
  82406. particle.angleAcceleration = this.randomValue( this.angleAccelerationBase, this.angleAccelerationSpread );
  82407. particle.size = this.randomValue( this.sizeBase, this.sizeSpread );
  82408. var color = this.randomVector3( this.colorBase, this.colorSpread );
  82409. particle.color = new Color().setHSL( color.x, color.y, color.z );
  82410. particle.opacity = this.randomValue( this.opacityBase, this.opacitySpread );
  82411. particle.age = 0;
  82412. particle.alive = 0; // particles initialize as inactive
  82413. return particle;
  82414. }
  82415. getPointsForBound(){
  82416. return this.boundPoints; //可以用于expand实时bound的点, 不含particle的size等边距
  82417. }
  82418. getBound(points){ // points为生成点(圆心)
  82419. this.boundPoints = [];
  82420. let boundingBox = new Box3();
  82421. let maxSize = this.sizeTween.values.slice().sort((a,b)=>b-a)[0];
  82422. let margin0 = maxSize * 0.11;
  82423. let margin1 = margin0 + 0.5 ;//保守估计还会飘出这么多距离吧: size + 飘动
  82424. points.forEach(bottom=>{
  82425. let top = bottom.clone();
  82426. top.z += this.height;
  82427. boundingBox.expandByPoint(bottom);
  82428. boundingBox.expandByPoint(top);
  82429. this.boundPoints.push(bottom,top);
  82430. });
  82431. let xyExpand = this.radius+margin1;
  82432. boundingBox.expandByVector(new Vector3(xyExpand,xyExpand,0));
  82433. boundingBox.min.z -= margin0;
  82434. boundingBox.max.z += margin1;
  82435. this.boundingBox = boundingBox;
  82436. /* if(!this.debugBox){
  82437. this.debugBox = new THREE.Mesh(boxGeo, boxMat)
  82438. this.add(this.debugBox)
  82439. }
  82440. this.debugBox.scale.copy(boundingBox.getSize(new THREE.Vector3))
  82441. this.debugBox.position.copy(boundingBox.getCenter(new THREE.Vector3)) */
  82442. }
  82443. createGeometry(){
  82444. this.particleArray = [];
  82445. const positions = [];
  82446. const colors = [];
  82447. const alives = [];
  82448. const opacitys = [];
  82449. const sizes = [];
  82450. const angles = [];
  82451. let count, points;
  82452. if(this.positions.length>1){
  82453. const spaceDis = 0.6;//间隔距离
  82454. count = Math.ceil(this.curve.wholeLength / spaceDis) + 1;
  82455. points = this.curve.getSpacedPoints( count );
  82456. count = points.length;
  82457. /* points.forEach(e=> {
  82458. var sphere = debugSphere.clone();
  82459. sphere.position.copy(e)
  82460. viewer.scene.scene.add(sphere)
  82461. }) */
  82462. let haventGetPoints = points.slice();
  82463. var getRanPoints = function(i){
  82464. var a = Math.random();
  82465. let choseIndex = Math.floor(haventGetPoints.length * a);
  82466. var point = haventGetPoints[choseIndex];
  82467. if(haventGetPoints.length == 1){
  82468. haventGetPoints = points.slice();
  82469. }else {
  82470. haventGetPoints.splice(choseIndex, 1);
  82471. }
  82472. return point
  82473. };
  82474. this.getBound(points);
  82475. }else {
  82476. this.getBound(this.positions);
  82477. }
  82478. for (var i = 0; i < this.particleCount; i++)
  82479. {
  82480. var center = new Vector3().copy(this.positions.length>1 ? getRanPoints(i) : this.positions[0]);
  82481. //var center = new THREE.Vector3().copy(this.positions.length>1 ? points[Math.floor(i/this.particleCount * count)] : this.positions[0])
  82482. // remove duplicate code somehow, here and in update function below.
  82483. this.particleArray[i] = this.createParticle(center);
  82484. positions[3*i] = this.particleArray[i].position.x;
  82485. positions[3*i+1] = this.particleArray[i].position.y;
  82486. positions[3*i+2] = this.particleArray[i].position.z;
  82487. colors[3*i] = this.particleArray[i].color.r;
  82488. colors[3*i+1] = this.particleArray[i].color.g;
  82489. colors[3*i+2] = this.particleArray[i].color.b;
  82490. alives[i] = this.particleArray[i].alive;
  82491. opacitys[i] = this.particleArray[i].opacity;
  82492. sizes[i] = this.particleArray[i].size;
  82493. angles[i] = this.particleArray[i].angle;
  82494. }
  82495. this.geometry.setAttribute( 'position', new BufferAttribute( new Float32Array(positions), 3 ));
  82496. this.geometry.setAttribute( 'customColor', new BufferAttribute( new Float32Array(colors), 3 ) );
  82497. this.geometry.setAttribute( 'customVisible', new BufferAttribute( new Float32Array(alives), 1 ) );
  82498. this.geometry.setAttribute( 'customOpacity', new BufferAttribute( new Float32Array(opacitys), 1 ) );
  82499. this.geometry.setAttribute( 'customSize', new BufferAttribute( new Float32Array(sizes), 1 ) );
  82500. this.geometry.setAttribute( 'customAngle', new BufferAttribute( new Float32Array(angles), 1 ) );
  82501. }
  82502. createMaterial(){
  82503. this.material = new ShaderMaterial(
  82504. {
  82505. uniforms:
  82506. {
  82507. u_sampler: { type: "t", value: getTexture$1() },
  82508. heightOfNearPlane: { type: "f", value:0} //相对far ,以确保画面缩放时点的大小也会缩放
  82509. },
  82510. vertexShader: vertexShader$1,vertexShader: vertexShader$1,
  82511. fragmentShader: fragmentShader$1,
  82512. transparent: true,
  82513. alphaTest: 0.5, // if having transparency issues, try including: alphaTest: 0.5,
  82514. blending: this.blendStyle,
  82515. depthTest: this.blendStyle != NormalBlending
  82516. });
  82517. this.setPerspective(this.fov, this.screenHeight);
  82518. }
  82519. update(dt){
  82520. if(!viewer.getObjVisiByReason(this,'force')){//被手动隐藏了
  82521. return
  82522. }
  82523. if(!Potree.Utils.isInsideFrustum(this.boundingBox, viewer.scene.getActiveCamera())){
  82524. viewer.updateVisible(this,'isInsideFrustum', false ); //不在视野范围
  82525. //console.log('unvi')
  82526. return
  82527. }else {
  82528. viewer.updateVisible(this,'isInsideFrustum', true );
  82529. }
  82530. if(dt > 1){
  82531. console.log('update dt>1', dt);
  82532. }
  82533. //dt *= 0.5;
  82534. const recycleIndices = [];
  82535. const recycleAges = [];
  82536. const positions = [];
  82537. const colors = [];
  82538. const alives = [];
  82539. const opacitys = [];
  82540. const sizes = [];
  82541. const angles = [];
  82542. for (var i = 0; i < this.particleCount; i++)
  82543. {
  82544. if ( this.particleArray[i].alive )
  82545. {
  82546. if ( this.velocityStyle == 'cube' )
  82547. { //一定几率改变下方向
  82548. let ratio = Math.random();
  82549. if(this.particleArray[i].age - this.particleArray[i].lastChangeVage > this.particleDeathAge*ratio ){
  82550. this.particleArray[i].velocity = this.randomVector3( this.velocityBase, this.velocitySpread );
  82551. this.particleArray[i].lastChangeVage = this.particleArray[i].age;
  82552. }
  82553. }else {
  82554. /* if(this.particleArray[i].age - this.particleArray[i].lastChangeVage > this.particleDeathAge*0.3 ){
  82555. if( Math.random()>0.1){//一定几率改变下方向
  82556. var speed = this.randomValue( this.speedBase, this.speedSpread );
  82557. this.particleArray[i].velocity = this.randomVector3( new THREE.Vector3, new THREE.Vector3(1,1,1) );
  82558. this.particleArray[i].velocity.normalize().multiplyScalar( speed );
  82559. }
  82560. this.particleArray[i].lastChangeVage = this.particleArray[i].age
  82561. } */
  82562. }
  82563. this.particleArray[i].update(dt);
  82564. // check if particle should expire
  82565. // could also use: death by size<0 or alpha<0.
  82566. if ( this.particleArray[i].age > this.particleDeathAge )
  82567. {
  82568. this.particleArray[i].alive = 0.0;
  82569. recycleIndices.push(i);
  82570. recycleAges.push((this.particleArray[i].age - this.particleDeathAge)%(this.particleDeathAge ));
  82571. }
  82572. // update particle properties in shader
  82573. positions[3*i] = this.particleArray[i].position.x;
  82574. positions[3*i+1] = this.particleArray[i].position.y;
  82575. positions[3*i+2] = this.particleArray[i].position.z;
  82576. colors[3*i] = this.particleArray[i].color.r;
  82577. colors[3*i+1] = this.particleArray[i].color.g;
  82578. colors[3*i+2] = this.particleArray[i].color.b;
  82579. alives[i] = this.particleArray[i].alive;
  82580. opacitys[i] = this.particleArray[i].opacity;
  82581. sizes[i] = this.particleArray[i].size;
  82582. angles[i] = this.particleArray[i].angle;
  82583. }
  82584. }
  82585. // check if particle emitter is still running
  82586. //if ( !this.emitterAlive ) return;
  82587. this.geometry.setAttribute( 'position', new BufferAttribute( new Float32Array(positions), 3 ) );
  82588. this.geometry.setAttribute( 'customColor', new BufferAttribute( new Float32Array(colors), 3 ) );
  82589. this.geometry.setAttribute( 'customVisible', new BufferAttribute( new Float32Array(alives), 1 ) );
  82590. this.geometry.setAttribute( 'customOpacity', new BufferAttribute( new Float32Array(opacitys), 1 ) );
  82591. this.geometry.setAttribute( 'customSize', new BufferAttribute( new Float32Array(sizes), 1 ) );
  82592. this.geometry.setAttribute( 'customAngle', new BufferAttribute( new Float32Array(angles), 1 ) );
  82593. this.geometry.attributes.customColor.needsUpdate = true;
  82594. this.geometry.attributes.customVisible.needsUpdate = true;
  82595. this.geometry.attributes.customOpacity.needsUpdate = true;
  82596. this.geometry.attributes.customSize.needsUpdate = true;
  82597. this.geometry.attributes.customAngle.needsUpdate = true;
  82598. // if no particles have died yet, then there are still particles to activate
  82599. if ( this.emitterAge < this.particleDeathAge ) //开始时一个个放出来
  82600. {
  82601. let particlesPerSecond = this.particleCount / this.particleDeathAge;
  82602. // determine indices of particles to activate
  82603. var startIndex = Math.round( particlesPerSecond * (this.emitterAge + 0) );
  82604. var endIndex = Math.round( particlesPerSecond * (this.emitterAge + dt) );
  82605. if ( endIndex > this.particleCount )
  82606. endIndex = this.particleCount;
  82607. for (var i = startIndex; i < endIndex; i++)
  82608. this.particleArray[i].alive = 1.0;
  82609. }
  82610. // if any particles have died while the emitter is still running, we imediately recycle them
  82611. for (var j = 0; j < recycleIndices.length; j++)
  82612. {
  82613. var i = recycleIndices[j];
  82614. this.particleArray[i] = this.createParticle(this.particleArray[i].center);
  82615. this.particleArray[i].alive = 1.0; // activate right away
  82616. this.particleArray[i].age = recycleAges[j];
  82617. positions[3*i] = this.particleArray[i].position.x;
  82618. positions[3*i+1] = this.particleArray[i].position.y;
  82619. positions[3*i+2] = this.particleArray[i].position.z;
  82620. }
  82621. this.geometry.setAttribute( 'position', new BufferAttribute( new Float32Array(positions), 3 ) );
  82622. this.geometry.attributes.position.needsUpdate = true;
  82623. // stop emitter?
  82624. this.emitterAge += dt;
  82625. //if ( this.emitterAge > this.emitterDeathAge ) this.emitterAlive = false;
  82626. }
  82627. randomValue(base, spread)
  82628. {
  82629. //return base + spread * (Math.random() - 0.5);
  82630. let p = Math.random();
  82631. return base * p + spread * (1-p)
  82632. }
  82633. randomVector3(base, spread)
  82634. {
  82635. var rand3 = new Vector3( Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5 );
  82636. return new Vector3().addVectors( base, new Vector3().multiplyVectors( spread, rand3 ) );
  82637. }
  82638. setSize(e){
  82639. let viewport = e.viewport;
  82640. this.screenHeight = viewport.resolution.y;
  82641. this.setPerspective(this.fov, this.screenHeight);
  82642. }
  82643. setFov(fov){
  82644. this.fov = fov;
  82645. this.setPerspective(this.fov, this.screenHeight);
  82646. }
  82647. setPerspective(fov, height){
  82648. //this.uniforms.heightOfNearPlane.value = Math.abs(height / (2 * Math.tan(THREE.Math.degToRad(fov * 0.5))));
  82649. let far = Math.abs(height / (2 * Math.tan(MathUtils.degToRad(fov * 0.5))));
  82650. this.material.uniforms.heightOfNearPlane.value = far;
  82651. }
  82652. dispose(){
  82653. this.geometry.dispose();
  82654. this.material.dispose();
  82655. this.dispatchEvent('dispose');
  82656. }
  82657. }
  82658. /*
  82659. 改进:如果有必要
  82660. 根据curve中分成的点,分成多个簇,每个簇掌管该部分的可见性和particle的数量。
  82661. 在camera_changed时根据远近修改每个簇的particle的数量,当然不会大于初始创建的个数。多出的随机隐藏。
  82662. */
  82663. const vertexShader$2 = `
  82664. attribute vec3 color;
  82665. attribute float size;
  82666. attribute float angle;
  82667. attribute float opacity;
  82668. attribute float visible;
  82669. varying vec4 vColor;
  82670. varying float vAngle;
  82671. uniform float heightOfNearPlane;
  82672. void main() {
  82673. if(visible > 0.5) {
  82674. vColor = vec4(color, opacity);
  82675. } else {
  82676. vColor = vec4(0.0, 0.0, 0.0, 0.0);
  82677. }
  82678. vAngle = angle;
  82679. vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
  82680. gl_Position = projectionMatrix * mvPosition;
  82681. gl_PointSize = ( heightOfNearPlane * size ) / gl_Position.w;
  82682. }
  82683. `;
  82684. const fragmentShader$2 = `
  82685. uniform sampler2D u_sampler;
  82686. varying vec4 vColor;
  82687. varying float vAngle;
  82688. void main() {
  82689. gl_FragColor = vColor;
  82690. float u = cos(vAngle);
  82691. float v = sin(vAngle);
  82692. vec2 uv = vec2(
  82693. u * (gl_PointCoord.x - 0.5) + v * (gl_PointCoord.y - 0.5) + 0.5,
  82694. u * (gl_PointCoord.y - 0.5) - v * (gl_PointCoord.x - 0.5) + 0.5
  82695. );
  82696. vec4 texture = texture2D(u_sampler, uv);
  82697. gl_FragColor = gl_FragColor * texture;
  82698. }
  82699. `;
  82700. // import { vertexShader, fragmentShader } from './shader'
  82701. const DEG2RAD = Math.PI / 180;
  82702. class Particle$2 {
  82703. constructor() {
  82704. this.position = new Vector3();
  82705. this.velocity = new Vector3();
  82706. this.angle = 0;
  82707. this.angleVelocity = 0;
  82708. this.angleAcceleration = 0;
  82709. this.size = 16;
  82710. this.color = new Color();
  82711. this.opacity = 1;
  82712. this.rebornCount = 0;//重生次数
  82713. this.age = 0;
  82714. this.alive = 0; //注意,一开始时是未出生的
  82715. this.deadAge = 0;//已死亡时间
  82716. this.sizeTween = null;
  82717. this.colorTween = null;
  82718. this.opacityTween = null;
  82719. }
  82720. update(dt) {
  82721. //s = s0 + (v0 + at) * t 或 lastS + delta(vt)
  82722. this.position.add(this.velocity.clone().multiplyScalar(dt));
  82723. this.velocity.multiplyScalar( 1+this.acceleration*dt );
  82724. this.angle += this.angleVelocity * DEG2RAD * dt;
  82725. this.angleVelocity += this.angleAcceleration * DEG2RAD * dt;
  82726. this.age += dt;
  82727. if(this.sizeTween.times.length > 0) {
  82728. this.size = this.sizeTween.lerp(this.age/this.deathAge);
  82729. }
  82730. if(this.colorTween.times.length > 0) {
  82731. const colorHSL = this.colorTween.lerp(this.age/this.deathAge);
  82732. this.color = new Color().setHSL(colorHSL.x, colorHSL.y, colorHSL.z);
  82733. }
  82734. if(this.opacityTween.times.length > 0) {
  82735. this.opacity = this.opacityTween.lerp(this.age/this.deathAge);
  82736. }
  82737. }
  82738. }
  82739. class Util {
  82740. constructor() {}
  82741. randomValue(min, max) {
  82742. //return min + max * (Math.random() - 0.5)
  82743. let p = Math.random();
  82744. return min * p + max * (1-p)
  82745. }
  82746. randomVector3(min, max) {
  82747. const rand3 = new Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5);
  82748. return new Vector3().addVectors(min, new Vector3().multiplyVectors(max, rand3))
  82749. }
  82750. }
  82751. const util$1 = new Util();
  82752. const Shape$1 = {
  82753. CUBE: 1,
  82754. SPHERE: 2
  82755. };
  82756. let particleTexture$1;
  82757. const getTexture$2 = ()=>{
  82758. if (!particleTexture$1) {
  82759. particleTexture$1 = new TextureLoader().load(Potree.resourcePath + '/textures/explode.png');
  82760. }
  82761. return particleTexture$1
  82762. };
  82763. const sphereGeo$1 = new SphereBufferGeometry(1, 10,4);
  82764. const sphereMat = new MeshBasicMaterial({wireframe:true, color:"#ffffff"});
  82765. const defaults$1 = {
  82766. position: new Vector3(0,0,1),
  82767. positionShape: Shape$1.SPHERE,
  82768. positionRange: new Vector3(1,1,1),
  82769. //cube
  82770. radius: 1.3,
  82771. //sphere
  82772. velocityShape: Shape$1.SPHERE,
  82773. velocity: new Vector3(0,0,2),
  82774. //cube
  82775. velocityRange: new Vector3(0,0,3),
  82776. //sphere
  82777. speed: 0.4,
  82778. speedRange: 1,
  82779. size: 0.4,
  82780. sizeRange: 2,
  82781. //sizeTween: new Tween( [0, 0.05, 0.3, 0.45], [0, 1, 3, 0.1] ),
  82782. sizeTween: [[0, 0.04, 0.2, 1],[0.1, 1, 6, 8]] ,
  82783. color: new Vector3(1.0,1.0,1.0),
  82784. colorRange: new Vector3(0,0,0),
  82785. colorTween: new Tween(),
  82786. opacity: 1.0,
  82787. opacityRange: 0.0,
  82788. opacityTween: new Tween([0, 0.06, 0.3, 0.8, 1],[0, 1, 0.3, 0.05, 0]),
  82789. blendMode: AdditiveBlending,
  82790. acceleration: 0.5,
  82791. accelerationRange: 0,
  82792. angle: 0,
  82793. angleRange: 0,
  82794. angleVelocity: 0,
  82795. angleVelocityRange: 0,
  82796. angleAcceleration: 0,
  82797. angleAccelerationRange: 0,
  82798. strength:1,
  82799. //particlesPerSecond: 8,
  82800. particleDeathAge: 0.7 ,
  82801. recycleTimes : 3 , //每个粒子在一次爆炸后循环次数,循环完毕进入particleSpaceTime,等待下一次爆炸.
  82802. //爆炸时长: particleDeathAge * (recycleTimes+1)
  82803. particleSpaceTime: 3, //间隔
  82804. };
  82805. class ExplodeParticle extends Points {
  82806. constructor(params) {
  82807. super();
  82808. this.age = 0;
  82809. this.alive = true;
  82810. //this.deathAge = 60
  82811. this.loop = true;
  82812. this.blendMode = NormalBlending;
  82813. this.setParameters(params);
  82814. this.createParticles();
  82815. this.frustumCulled = false;//似乎是禁止相机裁剪,否则会在某些角度消失。但是会不会更耗性能呢?
  82816. //------------------------------------
  82817. this.setSize({viewport:viewer.mainViewport});
  82818. this.setFov(viewer.fov);
  82819. let setSize = (e)=>{
  82820. if(e.viewport.name != "MainView")return
  82821. this.setSize(e);
  82822. };
  82823. let setFov = (e)=>{
  82824. this.setFov(e.fov);
  82825. };
  82826. /* let reStart = (e)=>{
  82827. if(e.v){//重新一个个放出粒子,否则会一股脑儿全部出来,因为同时大于粒子周期了一起重新生成出现。
  82828. setTimeout(()=>{//会先update一次delta为pageUnvisile的时间才触发
  82829. //console.log('归零')
  82830. //this.reStart()
  82831. },1)
  82832. }
  82833. } */
  82834. viewer.addEventListener('resize',setSize);
  82835. viewer.addEventListener('fov_changed',setFov);
  82836. //viewer.addEventListener('pageVisible', reStart)
  82837. this.addEventListener('dispose',()=>{
  82838. viewer.removeEventListener('resize',setSize);
  82839. viewer.removeEventListener('fov_changed',setFov);
  82840. //viewer.removeEventListener('pageVisible', reStart)
  82841. });
  82842. }
  82843. computeParams(){
  82844. if(this.curve){
  82845. this.position.copy(this.curve.points[0]);
  82846. }
  82847. const minSize = 0.8, maxSize = 10, minRadiusBound = 0.2, maxRadiusBound = 20;
  82848. let size = minSize + (maxSize - minSize) * MathUtils.smoothstep(this.radius*this.strength , minRadiusBound, maxRadiusBound);
  82849. this.sizeTween.values = this.defaultSizeTween.values.map(e=> e*size);
  82850. this.particleCount = Math.ceil( this.strength * this.radius * 5 /* * this.radius * this.radius */ );
  82851. this.speed = defaults$1.speed * this.radius;
  82852. this.speedRange = defaults$1.speedRange * this.radius;
  82853. console.log(this.particleCount);
  82854. {
  82855. this.boundPoints = [];
  82856. this.boundPoints.push(this.position.clone());
  82857. let maxSize = this.sizeTween.values.slice().sort((a,b)=>b-a)[0];
  82858. let margin = maxSize * 0.35 + 0.5;
  82859. let scale = this.radius+margin;
  82860. let sphere = new Sphere(this.position, scale);//加上防止剪裁
  82861. this.boundingSphere = sphere; //虽然还是会有一些后续移动的会超出
  82862. this.boundingBox = new Box3().setFromCenterAndSize(this.position, new Vector3(scale*2,scale*2,scale*2));
  82863. /* if(!this.debugSphere){
  82864. this.debugSphere = new THREE.Mesh(sphereGeo, sphereMat)
  82865. this.add(this.debugSphere)
  82866. }
  82867. this.debugSphere.scale.set(scale,scale,scale) */
  82868. }
  82869. }
  82870. getPointsForBound(){
  82871. return this.boundPoints; //可以用于expand实时bound的点, 不含particle的size等边距
  82872. }
  82873. reStart(){
  82874. this.age = 0;
  82875. this.createParticles();
  82876. }
  82877. setParameters(params) {
  82878. params = $.extend({}, defaults$1, params);
  82879. for (var key in params) {
  82880. let value = params[key];
  82881. if (key == 'position')
  82882. this.position.copy(value);
  82883. else if (value instanceof Array && value[0]instanceof Array){
  82884. this[key] = new Tween(...value);
  82885. }else if(value instanceof Vector3 || value instanceof Color){
  82886. this[ key ] = value.clone();
  82887. }else {
  82888. this[key] = value;
  82889. }
  82890. }
  82891. this.defaultSizeTween = this.sizeTween.clone();
  82892. //Object.assign(this, params)
  82893. this.particles = [];
  82894. this.age = 0.0;
  82895. this.alive = true;
  82896. this.geometry = new BufferGeometry();
  82897. this.computeParams();
  82898. this.material = new ShaderMaterial({
  82899. uniforms: {
  82900. u_sampler: {
  82901. value: this.texture || getTexture$2()
  82902. },
  82903. heightOfNearPlane: {
  82904. type: "f",
  82905. value: 0
  82906. }//相对far ,以确保画面缩放时点的大小也会缩放
  82907. },
  82908. vertexShader: vertexShader$2,
  82909. fragmentShader: fragmentShader$2,
  82910. transparent: true,
  82911. alphaTest: 0.5,
  82912. depthTest: this.blendMode == NormalBlending,
  82913. blending: this.blendMode
  82914. });
  82915. }
  82916. createParticles() {
  82917. this.particles = [];
  82918. const count = this.particleCount;
  82919. const positionArray = new Float32Array(count * 3);
  82920. const colorArray = new Float32Array(count * 3);
  82921. const sizeArray = new Float32Array(count);
  82922. const angleArray = new Float32Array(count);
  82923. const opacityArray = new Float32Array(count);
  82924. const visibleArray = new Float32Array(count);
  82925. for (let i = 0; i < count; i++) {
  82926. const particle = this.createParticle();
  82927. /* positionArray[i * 3] = particle.position.x
  82928. positionArray[i * 3 + 1] = particle.position.y
  82929. positionArray[i * 3 + 2] = particle.position.z
  82930. colorArray[i * 3] = particle.color.r
  82931. colorArray[i * 3 + 1] = particle.color.g
  82932. colorArray[i * 3 + 2] = particle.color.b
  82933. sizeArray[i] = particle.size
  82934. angleArray[i] = particle.angel
  82935. opacityArray[i] = particle.opacity
  82936. visibleArray[i] = particle.alive */
  82937. this.particles[i] = particle;
  82938. }
  82939. this.geometry.setAttribute('position', new BufferAttribute(positionArray,3));
  82940. this.geometry.setAttribute('color', new BufferAttribute(colorArray,3));
  82941. this.geometry.setAttribute('angle', new BufferAttribute(angleArray,1));
  82942. this.geometry.setAttribute('size', new BufferAttribute(sizeArray,1));
  82943. this.geometry.setAttribute('visible', new BufferAttribute(visibleArray,1));
  82944. this.geometry.setAttribute('opacity', new BufferAttribute(opacityArray,1));
  82945. }
  82946. createParticle() {
  82947. const particle = new Particle$2();
  82948. particle.sizeTween = this.sizeTween;
  82949. particle.colorTween = this.colorTween;
  82950. particle.opacityTween = this.opacityTween;
  82951. particle.deathAge = this.particleDeathAge;
  82952. if (this.positionShape == Shape$1.CUBE) {
  82953. particle.position = util$1.randomVector3(new Vector3, this.positionRange);
  82954. }
  82955. if (this.positionShape == Shape$1.SPHERE) {
  82956. /* const z = 2 * Math.random() - 1
  82957. const t = Math.PI * 2 * Math.random()
  82958. const r = Math.sqrt(1 - z*z)
  82959. const vec3 = new THREE.Vector3(r * Math.cos(t), r * Math.sin(t), z)
  82960. particle.position = vec3.multiplyScalar(this.radius) */
  82961. const y = 2 * Math.random() - 1;
  82962. const t = Math.PI * 2 * Math.random();
  82963. const r = Math.sqrt(1 - y * y);
  82964. const vec3 = new Vector3(r * Math.cos(t),y,r * Math.sin(t));
  82965. particle.position = vec3.multiplyScalar(this.radius);
  82966. }
  82967. if (this.velocityShape == Shape$1.CUBE) {
  82968. particle.velocity = util$1.randomVector3(this.velocity, this.velocityRange);
  82969. }
  82970. if (this.velocityShape == Shape$1.SPHERE) {
  82971. const direction = new Vector3().addVectors(particle.position, new Vector3(0,0,this.radius*2));//向上升?
  82972. const speed = util$1.randomValue(this.speed, this.speedRange);
  82973. particle.velocity = direction.normalize().multiplyScalar(speed);
  82974. }
  82975. particle.acceleration = util$1.randomValue(this.acceleration, this.accelerationRange);
  82976. particle.angle = util$1.randomValue(this.angle, this.angleRange);
  82977. particle.angleVelocity = util$1.randomValue(this.angleVelocity, this.angleVelocityRange);
  82978. particle.angleAcceleration = util$1.randomValue(this.angleAcceleration, this.angleAccelerationRange);
  82979. particle.size = util$1.randomValue(this.size, this.sizeRange);
  82980. const color = util$1.randomVector3(this.color, this.colorRange);
  82981. particle.color = new Color().setHSL(color.x, color.y, color.z);
  82982. particle.opacity = util$1.randomValue(this.opacity, this.opacityRange);
  82983. return particle
  82984. }
  82985. update(dt) {
  82986. if(!viewer.getObjVisiByReason(this,'force')){//被手动隐藏了
  82987. return
  82988. }
  82989. if(this.delayStartTime>0){ // 爆炸延迟
  82990. return this.delayStartTime -= dt
  82991. }
  82992. if(!Potree.Utils.isInsideFrustum(this.boundingSphere, viewer.scene.getActiveCamera())){
  82993. viewer.updateVisible(this,'isInsideFrustum', false ); //不在视野范围
  82994. return
  82995. }else {
  82996. viewer.updateVisible(this,'isInsideFrustum', true );
  82997. }
  82998. //const timeRatio = 0.5
  82999. if(dt > 1){
  83000. console.log('update dt>1', dt);
  83001. }
  83002. //dt *= timeRatio
  83003. let particleDeathAge = this.particleDeathAge;/* * timeRatio */
  83004. let particleSpaceTime = this.particleSpaceTime; /* * timeRatio */
  83005. const recycleIndices = [];
  83006. const recycleAges = [];
  83007. const recycleRebornCount = [];
  83008. const positionArray = this.geometry.attributes.position.array;
  83009. const opacityArray = this.geometry.attributes.opacity.array;
  83010. const visibleArray = this.geometry.attributes.visible.array;
  83011. const colorArray = this.geometry.attributes.color.array;
  83012. const angleArray = this.geometry.attributes.angle.array;
  83013. const sizeArray = this.geometry.attributes.size.array;
  83014. for (let i = 0; i < this.particleCount; i++) {
  83015. const particle = this.particles[i];
  83016. if (particle.alive) {
  83017. particle.update(dt);
  83018. if (particle.age > particleDeathAge) {
  83019. particle.alive = 0.0;
  83020. if(particle.rebornCount >= this.recycleTimes){
  83021. particle.deadAge = particle.age - particleDeathAge; //已死亡时间
  83022. }else {//直接循环
  83023. recycleIndices.push(i);
  83024. recycleAges.push(/* ( */particle.age - particleDeathAge/* )%(this.particleDeathAge ) */);
  83025. recycleRebornCount.push(particle.rebornCount+1);
  83026. }
  83027. }
  83028. positionArray[i * 3] = particle.position.x;
  83029. positionArray[i * 3 + 1] = particle.position.y;
  83030. positionArray[i * 3 + 2] = particle.position.z;
  83031. colorArray[i * 3] = particle.color.r;
  83032. colorArray[i * 3 + 1] = particle.color.g;
  83033. colorArray[i * 3 + 2] = particle.color.b;
  83034. visibleArray[i] = particle.alive;
  83035. opacityArray[i] = particle.opacity;
  83036. angleArray[i] = particle.angle;
  83037. sizeArray[i] = particle.size;
  83038. }else {
  83039. if(particle.rebornCount >= this.recycleTimes){
  83040. if(particle.age > particleDeathAge) {//其他已经死亡的粒子的时间继续增加
  83041. particle.deadAge += dt;
  83042. }
  83043. }
  83044. }
  83045. if (particle.rebornCount >= this.recycleTimes && particle.age > particleDeathAge) {//已经死亡
  83046. if(particle.deadAge >= particleSpaceTime){//死亡时间超过设定的间隔时间后重启
  83047. recycleIndices.push(i);
  83048. let wholeTime = particleDeathAge * (this.recycleTimes+1) + particleSpaceTime;
  83049. recycleAges.push((particle.deadAge - particleSpaceTime)% wholeTime ); //剩余时间就是重生后的age
  83050. recycleRebornCount.push(0);
  83051. }
  83052. }
  83053. }
  83054. this.geometry.attributes.size.needsUpdate = true;
  83055. this.geometry.attributes.color.needsUpdate = true;
  83056. this.geometry.attributes.angle.needsUpdate = true;
  83057. this.geometry.attributes.visible.needsUpdate = true;
  83058. this.geometry.attributes.opacity.needsUpdate = true;
  83059. this.geometry.attributes.position.needsUpdate = true;
  83060. if (!this.alive)
  83061. return
  83062. if (this.age < particleDeathAge) {
  83063. let startIndex = Math.round(this.particleCount * (this.age + 0)/ particleDeathAge);
  83064. let endIndex = Math.round(this.particleCount * (this.age + dt)/ particleDeathAge);
  83065. if (endIndex > this.particleCount) {
  83066. endIndex = this.particleCount;
  83067. }
  83068. for (let i = startIndex; i < endIndex; i++) {
  83069. this.particles[i].alive = 1.0;
  83070. }
  83071. }
  83072. for (let j = 0; j < recycleIndices.length; j++) {
  83073. let i = recycleIndices[j];
  83074. this.particles[i] = this.createParticle();
  83075. this.particles[i].alive = 1.0; //出生
  83076. this.particles[i].age = recycleAges[j];
  83077. this.particles[i].rebornCount= recycleRebornCount[j];
  83078. /* if(this.particles[i].age < particleDeathAge){
  83079. positionArray[i * 3] = this.particles[i].position.x
  83080. positionArray[i * 3 + 1] = this.particles[i].position.y
  83081. positionArray[i * 3 + 2] = this.particles[i].position.z
  83082. visibleArray[i] = particle.alive?
  83083. } */
  83084. }
  83085. this.geometry.attributes.position.needsUpdate = true;
  83086. this.age += dt;
  83087. if (this.age > this.deathAge && !this.loop) {
  83088. this.alive = false;
  83089. }
  83090. }
  83091. setSize(e) {
  83092. let viewport = e.viewport;
  83093. this.screenHeight = viewport.resolution.y;
  83094. this.setPerspective(this.fov, this.screenHeight);
  83095. }
  83096. setFov(fov) {
  83097. this.fov = fov;
  83098. this.setPerspective(this.fov, this.screenHeight);
  83099. }
  83100. setPerspective(fov, height) {
  83101. //this.uniforms.heightOfNearPlane.value = Math.abs(height / (2 * Math.tan(THREE.Math.degToRad(fov * 0.5))));
  83102. let far = Math.abs(height / (2 * Math.tan(MathUtils.degToRad(fov * 0.5))));
  83103. this.material.uniforms.heightOfNearPlane.value = far;
  83104. }
  83105. updateGeometry(){
  83106. this.computeParams();
  83107. this.reStart();
  83108. }
  83109. dispose(){
  83110. this.geometry.dispose();
  83111. this.material.dispose();
  83112. this.dispatchEvent('dispose');
  83113. }
  83114. }
  83115. const colors$1 = {
  83116. 'fire+smoke':0xffffff,
  83117. 'smoke': 0xffffff,
  83118. 'explode':0xffffff,
  83119. };
  83120. let depthMatPrefix = {
  83121. clipDistance : 100, occlusionDistance:60, /* 变为backColor距离 */
  83122. maxClipFactor:0.5, backColor:"#777" ,
  83123. useDepth:true, transparent: !0,
  83124. };
  83125. let lineMats$2;
  83126. let getLineMat$1 = function(type){
  83127. if(!lineMats$2){
  83128. lineMats$2 = {
  83129. 'fire+smoke':LineDraw.createFatLineMat($.extend(depthMatPrefix,{
  83130. color: colors$1['fire+smoke'],
  83131. lineWidth: 2
  83132. })),
  83133. 'smoke' :LineDraw.createFatLineMat($.extend(depthMatPrefix,{
  83134. color: colors$1['smoke'],
  83135. lineWidth: 2
  83136. })),
  83137. 'explode' :LineDraw.createFatLineMat($.extend(depthMatPrefix,{
  83138. color: colors$1['explode'],
  83139. lineWidth: 2
  83140. })),
  83141. };
  83142. }
  83143. return lineMats$2[type]
  83144. };
  83145. let handleMats;
  83146. let getHandleMat = function(type){
  83147. if(!handleMats){
  83148. let texLoader = new TextureLoader();
  83149. handleMats = {
  83150. "fire+smoke" : new DepthBasicMaterial($.extend(depthMatPrefix,{
  83151. map: texLoader.load(Potree.resourcePath+'/textures/icon-fire.png' ),
  83152. color: colors$1['fire+smoke'],
  83153. })),
  83154. "smoke" : new DepthBasicMaterial($.extend(depthMatPrefix,{
  83155. map: texLoader.load(Potree.resourcePath+'/textures/icon-smoke.png' ),
  83156. color: colors$1['smoke'],
  83157. })),
  83158. "explode" : new DepthBasicMaterial($.extend(depthMatPrefix,{
  83159. map: texLoader.load(Potree.resourcePath+'/textures/icon-explode.png' ),
  83160. color: colors$1['explode'],
  83161. })),
  83162. };
  83163. }
  83164. return handleMats[type]
  83165. };
  83166. let ParticleEditor = {
  83167. bus: new EventDispatcher$1,
  83168. particleGroup : new Object3D ,
  83169. curveGroup:new Object3D ,
  83170. init:function(){
  83171. this.particleGroup.name = 'particles';
  83172. viewer.scene.scene.add( this.particleGroup );
  83173. this.curveGroup.name = 'particles-curves';
  83174. viewer.scene.scene.add( this.curveGroup );
  83175. },
  83176. addParticle : function(prop={}){
  83177. let particle;
  83178. if(prop.type == 'fire'){
  83179. particle = new FireParticle(prop);
  83180. }else if(prop.type == 'smoke'){
  83181. particle = new SmokeParticle(prop);
  83182. }else if(prop.type == 'explode'){
  83183. particle = new ExplodeParticle(prop);
  83184. }
  83185. this.particleGroup.add(particle);
  83186. return particle
  83187. }
  83188. ,
  83189. removeParticle(particle){
  83190. //particle.dispatchEvent('delete')
  83191. particle.dispose();
  83192. this.particleGroup.remove(particle);
  83193. particle.curve.dispose();
  83194. }
  83195. ,
  83196. update(delta){
  83197. this.particleGroup.children.forEach(e=>e.update(delta));
  83198. }
  83199. ,
  83200. startInsertion(type = 'fire', prop={}){ //viewer.modules.ParticleEditor.startInsertion()
  83201. let deferred = $.Deferred();
  83202. let particles = [];
  83203. let finish = (ifDone)=>{
  83204. if(ifDone){
  83205. deferred.resolve(particles);
  83206. }
  83207. viewer.dispatchEvent({
  83208. type : "CursorChange", action : "remove", name:"addSth"
  83209. });
  83210. viewer.removeEventListener('global_click', click);
  83211. this.bus.removeEventListener('cancel_insertions',cancel);
  83212. };
  83213. let curve = new CurveCtrl([], getLineMat$1(type), colors$1[type], type+'_curve', {handleMat:getHandleMat(type)} );
  83214. this.curveGroup.add(curve);
  83215. prop.curve = curve;
  83216. prop.type = type;
  83217. //console.log('创建curve',type,curve.uuid)
  83218. let cancel = ()=>{
  83219. console.log('cancel_insertions', curve.uuid );
  83220. curve.dispose();
  83221. finish(false);
  83222. };
  83223. this.bus.dispatchEvent('cancel_insertions');//删除旧的
  83224. this.bus.addEventListener('cancel_insertions',cancel);
  83225. var click = (e)=>{
  83226. if(e.button === MOUSE.RIGHT){
  83227. if(curve.points.length>=1){ //if(type.includes('fire') || type.includes('smoke') ){
  83228. particles = this.createFromData(prop);
  83229. finish(true);
  83230. }
  83231. return
  83232. }
  83233. var I = e.intersect && (e.intersect.orthoIntersect || e.intersect.location);
  83234. if(!I)return
  83235. curve.addPoint(I, null, true);
  83236. if(type == 'explode'){
  83237. particles = this.createFromData(prop);
  83238. finish(true);
  83239. }
  83240. return {stopContinue:true}//防止继续执行别的侦听,如flytopano
  83241. };
  83242. viewer.addEventListener('global_click', click, 10);//add importance:10
  83243. viewer.dispatchEvent({
  83244. type : "CursorChange", action : "add", name:"addSth"
  83245. });
  83246. return deferred.promise()
  83247. },
  83248. createFromData(prop){
  83249. const type = prop.type;
  83250. var particles = [];
  83251. let curve = prop.curve;
  83252. if(!curve){
  83253. curve = new CurveCtrl(prop.points, getLineMat$1(type), colors$1[type], type+'_curve', {handleMat:getHandleMat(type)} );
  83254. this.curveGroup.add(curve);
  83255. }
  83256. if(type.includes('fire') || type.includes('smoke') ){
  83257. if(type.includes('fire')){
  83258. var fire = this.addParticle({
  83259. type : 'fire',
  83260. positions : curve.points,
  83261. curve,
  83262. radius : prop.radius,
  83263. height: prop.height,
  83264. strength : prop.strength,
  83265. });
  83266. particles.push(fire);
  83267. }
  83268. if(type.includes('smoke')){
  83269. var smoke = this.addParticle({
  83270. type : 'smoke',
  83271. positions : curve.points,
  83272. curve,
  83273. positionStyle : 'sphere' ,
  83274. strength : prop.smokeStrength,
  83275. radius: prop.smokeRadius,
  83276. height: prop.smokeHeight,
  83277. });
  83278. particles.push(smoke);
  83279. }
  83280. }else if(type == 'explode'){
  83281. var explode = this.addParticle({
  83282. type : 'explode',
  83283. position : curve.points[0],
  83284. strength: prop.strength,
  83285. radius : prop.radius,
  83286. particleSpaceTime: prop.particleSpaceTime,
  83287. curve,
  83288. delayStartTime:prop.delayStartTime,
  83289. });
  83290. particles.push(explode);
  83291. }
  83292. var geoNeedsUpdate;
  83293. curve.addEventListener('dragCurvePoint',()=>{
  83294. geoNeedsUpdate = true;
  83295. Common.intervalTool.isWaiting('particlePointChange', ()=>{ //延时update,防止卡顿
  83296. if(geoNeedsUpdate){
  83297. particles.forEach(e=>e.updateGeometry());
  83298. geoNeedsUpdate = false;
  83299. curve.dispatchEvent('sendUpdatePoints');
  83300. return true
  83301. }
  83302. }, 400);
  83303. });
  83304. return particles
  83305. }
  83306. };
  83307. let CamAniEditor = {
  83308. createAnimation(data){
  83309. let animation = new CameraAnimation(viewer);
  83310. if(data) {
  83311. animation.name = data.name;
  83312. animation.duration = data.duration;
  83313. animation.useDurSlice = data.useDurSlice;
  83314. for(const cpdata of data.points){
  83315. /* const position = Potree.Utils.datasetPosTransform({ fromDataset: true, position: cpdata.position, datasetId: Potree.settings.originDatasetId })
  83316. const target = Potree.Utils.datasetPosTransform({ fromDataset: true, position: cpdata.target, datasetId: Potree.settings.originDatasetId })
  83317. */
  83318. const position = new Vector3().copy(cpdata.position);
  83319. const target = new Vector3().copy(cpdata.target);
  83320. const duration = cpdata.time;
  83321. const cp = animation.createControlPoint(null, {position, target, duration});
  83322. }
  83323. }
  83324. animation.changeCallback();
  83325. viewer.scene.addCameraAnimation(animation);
  83326. return animation
  83327. },
  83328. removeAnimation(animation){
  83329. animation.dispatchEvent('dispose');
  83330. viewer.scene.removeCameraAnimation(animation);
  83331. }
  83332. };
  83333. let images360, Alignment$1, SiteModel$1;
  83334. const texLoader$c = new TextureLoader();
  83335. texLoader$c.crossOrigin = "anonymous";
  83336. const lineMats$3 = {};
  83337. const circleMats = {};
  83338. const renderOrders$1 = {
  83339. circleSelected:3,
  83340. circle:2,
  83341. line:1,
  83342. };
  83343. const pointColor = {
  83344. /* selected:"#c80",
  83345. default:'#1ac' */
  83346. selected:"#c60",
  83347. default:'#17c'
  83348. };
  83349. const opacitys = {
  83350. default:1.3,
  83351. selected: 2.0
  83352. };
  83353. const cameraProps = [
  83354. {
  83355. name : 'top',
  83356. axis:["x","y"],
  83357. direction : new Vector3(0,0,-1), //镜头朝向
  83358. openCount:0,
  83359. },
  83360. {
  83361. name : 'right',
  83362. axis:["y","z"],
  83363. direction : new Vector3(1,0,0),
  83364. openCount:0,
  83365. }
  83366. ];
  83367. class PanoEditor extends EventDispatcher{
  83368. constructor(){
  83369. super();
  83370. this.panoGroup = [], //分组
  83371. this.viewports = {},
  83372. this.panoLink = {},
  83373. this.panoMeshs = new Object3D,
  83374. this.lineMeshes = new Object3D;
  83375. this.views = {};
  83376. this.cameras = {};
  83377. this.orthoCamera = new OrthographicCamera(-100, 100, 100, 100, 0.01, 10000);
  83378. this.selectedPano;
  83379. this.selectedGroup;
  83380. this.operation;
  83381. this.visiblePanos = [];
  83382. }
  83383. init(){
  83384. {//init lineMats
  83385. lineMats$3.default = LineDraw.createFatLineMat({
  83386. color: '#eeeeee',
  83387. lineWidth: 2,
  83388. depthTest:false
  83389. });
  83390. lineMats$3.hovered = LineDraw.createFatLineMat({
  83391. color: '#00c8af',
  83392. lineWidth: 2,
  83393. depthTest:false
  83394. });
  83395. lineMats$3.selected = LineDraw.createFatLineMat({
  83396. color: '#00c8af',
  83397. lineWidth: 3,
  83398. depthTest:false
  83399. });
  83400. }
  83401. this.initViews();
  83402. viewer.addEventListener('allLoaded',()=>{
  83403. images360 = viewer.images360;
  83404. Alignment$1 = viewer.modules.Alignment;
  83405. SiteModel$1 = viewer.modules.SiteModel;
  83406. this.panoMeshs.name = 'panoMeshs';
  83407. viewer.scene.scene.add(this.panoMeshs);
  83408. this.lineMeshes.name = 'lineMeshes';
  83409. viewer.scene.scene.add(this.lineMeshes);
  83410. this.initPanoLink();
  83411. this.addPanoMesh();
  83412. viewer.scene.pointclouds.forEach(e=>{
  83413. e.material.color = pointColor.default;
  83414. });
  83415. this.switchView('top');
  83416. SiteModel$1.bus.addEventListener('initDataDone',()=>{
  83417. let floor = SiteModel$1.entities.find(e=>e.buildType == 'floor' && e.panos.length); //选择有漫游点的一层
  83418. if(!floor){
  83419. floor = 'all'; //SiteModel.entities.find(e=>e.buildType == 'floor')
  83420. console.log('没有一层有漫游点?!');
  83421. }
  83422. this.gotoFloor(floor);
  83423. });
  83424. Alignment$1.bus.addEventListener('switchHandle', this.updateCursor.bind(this));
  83425. viewer.addEventListener('global_click',(e)=>{
  83426. if(e.button === MOUSE.RIGHT){//取消旋转和平移
  83427. console.log('right click',e);
  83428. this.setLinkOperateState('addLink',false);
  83429. this.setLinkOperateState('removeLink',false);
  83430. }else if(this.clickToZoomInEnabled){
  83431. this.zoomIn(e.intersect.orthoIntersect, e.pointer);
  83432. this.setZoomInState(false);
  83433. }
  83434. });
  83435. {//旋转时的辅助线
  83436. this.rotGuideLine = LineDraw.createLine([], {color:'#aaffee'});
  83437. this.rotGuideLine.visible = false;
  83438. this.rotGuideLine.name = 'rotGuideLine';
  83439. this.rotGuideLine.renderOrder = renderOrders$1.line;
  83440. viewer.scene.scene.add(this.rotGuideLine);
  83441. let startPoint;
  83442. Alignment$1.bus.addEventListener('rotateStart', (e)=>{
  83443. startPoint = e.startPoint;
  83444. });
  83445. Alignment$1.bus.addEventListener('rotate', (e)=>{
  83446. LineDraw.updateLine(this.rotGuideLine, [startPoint, e.endPoint] );
  83447. this.rotGuideLine.visible = true;
  83448. });
  83449. viewer.fpControls.addEventListener("end",(e)=>{
  83450. startPoint = null;
  83451. this.rotGuideLine.visible = false;
  83452. });
  83453. }
  83454. {//连接时的辅助线
  83455. this.linkGuideLine = LineDraw.createLine([], {color:'#aaa', deshed:true, dashSize:0.1,gapSize:0.1,});
  83456. this.linkGuideLine.visible = false;
  83457. this.linkGuideLine.name = 'linkGuideLine';
  83458. viewer.scene.scene.add(this.linkGuideLine);
  83459. this.linkGuideLine.renderOrder = renderOrders$1.line;
  83460. let update = (e)=>{
  83461. if(this.operation != 'addLink' || this.activeViewName != 'top' || !this.selectedPano){
  83462. return this.linkGuideLine.visible = false
  83463. }
  83464. LineDraw.updateLine(this.linkGuideLine, [this.selectedPano.position, e.intersect.orthoIntersect.clone().setZ(this.selectedPano.position.z)] );
  83465. this.linkGuideLine.visible = true;
  83466. };
  83467. viewer.addEventListener('global_mousemove', (e)=>{
  83468. update(e);
  83469. });
  83470. this.addEventListener('updateLinkGuideLine', update);
  83471. //为何打开调试时移动很卡
  83472. }
  83473. });
  83474. }
  83475. //////////////////////////////////
  83476. initViews(){
  83477. this.splitScreenTool = new SplitScreen;
  83478. this.targetPlane = viewer.mainViewport.targetPlane = new Plane();
  83479. this.shiftTarget = viewer.mainViewport.shiftTarget = new Vector3; //project在targetPlane上的位置
  83480. for(let i=0;i<2;i++){
  83481. let prop = cameraProps[i];
  83482. let view = new View();
  83483. this.views[prop.name] = view;
  83484. this.cameras[prop.name] = this.orthoCamera;
  83485. view.direction = prop.direction;
  83486. }
  83487. this.views.mainView = viewer.mainViewport.view;
  83488. this.cameras.mainView = viewer.mainViewport.camera;
  83489. }
  83490. switchView(name){//替换view和camera到mainViewport
  83491. let view = this.views[name];
  83492. let camera = this.cameras[name];
  83493. let prop = cameraProps.find(e=>e.name == name);
  83494. let {boundSize, center} = viewer.bound;
  83495. this.lastViewName = this.activeViewName;
  83496. this.activeViewName = name;
  83497. let lastView = this.views[this.lastViewName];
  83498. let lastCamera = this.cameras[this.lastViewName];
  83499. viewer.mainViewport.view = view;
  83500. viewer.mainViewport.camera = camera;
  83501. if(lastCamera)lastView.zoom = lastCamera.zoom;
  83502. this.targetPlane.setFromNormalAndCoplanarPoint( view.direction.clone(), center );
  83503. this.targetPlane.projectPoint(view.position, this.shiftTarget ); //target转换到过模型中心的平面,以保证镜头一定在模型外
  83504. view.position.copy(this.splitScreenTool.getPosOutOfModel(viewer.mainViewport));
  83505. if(view.zoom)camera.zoom = view.zoom;//恢复上次的zoom
  83506. viewer.updateScreenSize({forceUpdateSize:true});//更新camera aspect left等
  83507. this.updateCursor();
  83508. if(name == 'mainView'){
  83509. viewer.mainViewport.alignment = null;
  83510. viewer.scene.pointclouds.forEach(e=>{
  83511. e.material.activeAttributeName = 'rgba';
  83512. e.material.useFilterByNormal = false;
  83513. e.changePointOpacity(1,true);
  83514. });
  83515. viewer.updateVisible(viewer.reticule, 'force', true);
  83516. if(lastView){
  83517. view.copy(lastView);
  83518. //view.position.
  83519. let direction = view.direction;
  83520. let panos = images360.panos.filter(e=>e.circle.visible);
  83521. let nearestPano = Common.sortByScore(panos , [], [(pano)=>{
  83522. let vec = new Vector3().subVectors(pano.position, view.position);
  83523. return -vec.dot(direction);
  83524. }], true);
  83525. console.log('最近',nearestPano );
  83526. if(nearestPano && nearestPano[0] ){ //尽量不变画面范围,使pano点保持原位,转换到mainView
  83527. let halfHeight = lastCamera.top/lastCamera.zoom;
  83528. let dis = halfHeight / Math.tan( MathUtils.degToRad(camera.fov/2));
  83529. view.position.add(direction.clone().multiplyScalar(-nearestPano[0].score - dis));
  83530. //console.log('getCloser', -nearestPano[0].score - dis)
  83531. this.lastDisToPano = dis; //记录一下
  83532. }
  83533. }
  83534. viewer.fpControls.lockKey = false;
  83535. }else {
  83536. if(prop.openCount == 0){//只需执行一次
  83537. this.viewportFitBound(name, boundSize, center);
  83538. }
  83539. prop.openCount ++;
  83540. viewer.scene.pointclouds.forEach(e=>{
  83541. e.material.activeAttributeName = 'color';
  83542. e.material.useFilterByNormal = true; //defines : use_filter_by_normal attenuated_opacity
  83543. if(this.selectedPano && this.selectedClouds.includes(e) /* this.selectedPano.pointcloud == e */){
  83544. e.changePointOpacity(opacitys.selected,true);
  83545. }else {
  83546. e.changePointOpacity(opacitys.default,true);
  83547. }
  83548. });
  83549. viewer.updateVisible(viewer.reticule, 'force', false);
  83550. if(name == 'top') viewer.mainViewport.alignment = {rotate:true,translate:true};
  83551. if(name == 'right'){
  83552. viewer.mainViewport.alignment = {translate:true, rotateSide:true};
  83553. viewer.mainViewport.rotateSide = true;
  83554. }else {
  83555. viewer.mainViewport.rotateSide = false;
  83556. }
  83557. viewer.fpControls.lockKey = true;
  83558. }
  83559. this.setZoomInState(false); //取消放大模式
  83560. }
  83561. //new THREE.Plane().setFromNormalAndCoplanarPoint( normal, this.points[0] )
  83562. viewportFitBound(/* name, boundSize_, target */){ //使一个viewport聚焦在某个范围
  83563. /* let viewport = viewer.mainViewport
  83564. let {boundSize, center} = viewer.bound
  83565. var prop = cameraProps.find(v => name == v.name )
  83566. let expand = 10;
  83567. targetPlane.setFromNormalAndCoplanarPoint( prop.direction.clone(), center )
  83568. let shiftTarget = targetPlane.projectPoint(target, new THREE.Vector3() ) //target转换到过模型中心的平面,以保证镜头一定在模型外
  83569. this.setCameraPose(shiftTarget, prop.direction)
  83570. if(name == 'top'){
  83571. let axis = prop.axis
  83572. var width = Math.max(boundSize_[axis[0]], boundSize_[axis[1]] * viewport.camera.aspect)//视口宽度(米)
  83573. }else{//因为侧面可能旋转
  83574. let vec1 = new THREE.Vector3(boundSize_.x, 0,0);
  83575. let vec2 = new THREE.Vector3(0,boundSize_.y,0);
  83576. let v1 = vec1.projectOnPlane( prop.direction.clone() )
  83577. let v2 = vec2.projectOnPlane( prop.direction.clone() )
  83578. var width = Math.max(v1.length()+v2.length(), boundSize_.z * viewport.camera.aspect)//视口宽度(米)
  83579. }
  83580. var margin = 50 //px
  83581. viewport.camera.zoom = (viewport.resolution.x - margin) / width
  83582. viewport.camera.updateProjectionMatrix() */
  83583. if(viewer.mainViewport.resolution.x == 0 || viewer.mainViewport.resolution.y == 0){
  83584. return setTimeout(()=>{
  83585. this.viewportFitBound(/* name, boundSize_, target */);
  83586. },10)
  83587. }
  83588. this.gotoFloor(this.currentFloor, true, 0, null, true);
  83589. }
  83590. rotateSideCamera(angle){//侧视图绕模型中心水平旋转
  83591. this.splitScreenTool.rotateSideCamera(viewer.mainViewport, angle);
  83592. }
  83593. /* rotateSideCamera(angle){//侧视图绕模型中心水平旋转
  83594. var prop = cameraProps.find(v => v.name == 'right' )
  83595. let {boundSize, center} = viewer.bound
  83596. //找到平移向量
  83597. targetPlane.setFromNormalAndCoplanarPoint(viewer.mainViewport.view.direction , center )
  83598. targetPlane.projectPoint(viewer.mainViewport.view.position, this.shiftTarget ) //target转换到过模型中心的平面,以保证镜头一定在模型外
  83599. let vec = new THREE.Vector3().subVectors(center, this.shiftTarget)//相对于中心的偏移值,旋转后偏移值也旋转
  83600. //旋转
  83601. var rotMatrix = new THREE.Matrix4().makeRotationAxis(new THREE.Vector3(0,0,1), angle)
  83602. //prop.direction.applyMatrix4(rotMatrix)
  83603. viewer.mainViewport.view.direction = viewer.mainViewport.view.direction.applyMatrix4(rotMatrix)
  83604. vec.applyMatrix4(rotMatrix)
  83605. this.shiftTarget.subVectors(center,vec) //新的
  83606. viewer.mainViewport.view.position = this.splitScreenTool.getPosOutOfModel(viewer.mainViewport) // this.getPosOutOfModel()
  83607. } */
  83608. /* getPosOutOfModel(){//已知shiftTarget和currentDir后
  83609. let {boundSize, center} = viewer.bound
  83610. let expand = 10;
  83611. let view = viewer.mainViewport.view
  83612. let radius = boundSize.length() / 2
  83613. let position = this.shiftTarget.clone().sub(view.direction.clone().multiplyScalar(radius + expand))
  83614. return position
  83615. } */
  83616. zoomIn(intersect, pointer){
  83617. let camera = viewer.mainViewport.camera;
  83618. let endZoom = 700;
  83619. //this.moveFit(intersect, {endZoom:viewer.mainViewport.camera.zoom < aimZoom ? aimZoom : null} , 300)
  83620. let startZoom = camera.zoom;
  83621. if(startZoom >= endZoom){return}
  83622. viewer.mainViewport.view.zoomOrthoCamera(camera, endZoom, pointer, 300);
  83623. }
  83624. /* getRadius(){
  83625. let {boundSize, center} = viewer.bound
  83626. let expand = 10;
  83627. let radius = boundSize.length() / 2
  83628. return radius + expand
  83629. } */
  83630. moveFit(pos, info, duration){
  83631. var margin = {x:200, y:230};
  83632. this.splitScreenTool.viewportFitBound(viewer.mainViewport, info.bound, pos, duration, margin );
  83633. /* targetPlane.projectPoint(pos, this.shiftTarget) //target转换到过模型中心的平面,以保证镜头一定在模型外 this.shiftTarget是得到的
  83634. info.endPosition = this.getPosOutOfModel()
  83635. info
  83636. let view = viewer.mainViewport.view
  83637. view.moveOrthoCamera(viewer.mainViewport, info , duration ) */
  83638. }
  83639. setZoomInState(state, informinformBy2d){//是否点击后可放大
  83640. if(state && this.activeViewName == 'mainView')return console.log('3D不可放大')
  83641. this.clickToZoomInEnabled = !!state;
  83642. if(state){
  83643. viewer.dispatchEvent({type : "CursorChange", action : "add", name:"zoomInCloud"} );
  83644. }else {
  83645. viewer.dispatchEvent({type : "CursorChange", action : "remove", name:"zoomInCloud" });
  83646. }
  83647. if(!state && !informinformBy2d){
  83648. this.dispatchEvent({type:'operationCancel', operation: 'zoomIn'});
  83649. }
  83650. }
  83651. gotoFloor(floor, force, duration = 600, informBy2d, fitBound){// 选择不同楼层, 切换点位显示。 'all'为全部显示
  83652. floor = floor || 'all';
  83653. if(this.currentFloor == floor && !force)return
  83654. //let pointclouds = viewer.findPointcloudsAtFloor(floor)
  83655. let panos = floor == 'all' ? viewer.images360.panos : floor.panos;
  83656. viewer.images360.panos.forEach(pano=>{
  83657. let v = panos.includes(pano);
  83658. this.switchPanoVisible(pano,v);
  83659. });
  83660. this.updateLinesVisible();
  83661. //切换楼层时清空选择状态
  83662. if(this.selectedPano && floor != 'all' && !floor.panos.includes(this.selectedPano)){
  83663. this.selectedPano.circle.dispatchEvent('click');
  83664. }
  83665. if(this.selectedLine){
  83666. this.selectedLine.dispatchEvent('click');
  83667. }
  83668. let bound, center;
  83669. if(floor == 'all'){
  83670. bound = viewer.images360.bound.bounding;
  83671. center = viewer.images360.bound.center;
  83672. }else {
  83673. bound = this.getPanosBound(floor);
  83674. center = bound.getCenter(new Vector3());
  83675. if(floor.panos.length == 0)console.log(floor.name, 'floor无漫游点' );
  83676. }
  83677. if(this.activeViewName != 'mainView' ){
  83678. fitBound && this.moveFit(center, {bound}, duration);
  83679. }else if(this.activeViewName == 'mainView'){
  83680. if(floor != 'all'){ //切换一下位置,因为原处点云会消失
  83681. viewer.scene.view.setView({position:center, duration });
  83682. }
  83683. }
  83684. this.currentFloor = floor;
  83685. if(!informBy2d){
  83686. this.dispatchEvent({type:'changeFloor', floor});
  83687. }
  83688. }
  83689. getPanosBound(floor){
  83690. if(!floor.panosBound){
  83691. if(floor.panos.length == 0){
  83692. floor.panosBound = viewer.images360.bound.bounding.clone();
  83693. }else {
  83694. /* floor.panosBound = new THREE.Box3
  83695. floor.panos.forEach(pano=>{
  83696. floor.panosBound.expandByPoint(pano.position)
  83697. })
  83698. let center = floor.panosBound.getCenter(new THREE.Vector3)
  83699. let minBound = (new THREE.Box3()).setFromCenterAndSize(center, new THREE.Vector3(5,5,5))
  83700. floor.panosBound.union(minBound) */
  83701. let minSize = new Vector3(5,5,5);
  83702. let bound = math.getBoundByPoints(floor.panos.map(e=>e.position), minSize);
  83703. floor.panosBound = bound.bounding;
  83704. }
  83705. }
  83706. return floor.panosBound
  83707. }
  83708. switchPanoVisible(pano, v, informBy2d){
  83709. pano.circle.visible = v;
  83710. viewer.updateVisible(pano, 'panoEditor', v);
  83711. viewer.updateVisible(pano.pointcloud, 'panoEditor', v);
  83712. if(v){
  83713. this.visiblePanos.includes(pano) || this.visiblePanos.push(pano);
  83714. }else {
  83715. let index = this.visiblePanos.indexOf(pano);
  83716. index>-1 && this.visiblePanos.splice(index,1);
  83717. }
  83718. if(informBy2d){
  83719. this.updateLinesVisible();
  83720. }
  83721. informBy2d || this.dispatchEvent({type:"switchPanoVisible", pano, v});
  83722. }
  83723. updateLinesVisible(){
  83724. this.lineMeshes.children.forEach(line=>{
  83725. let names = line.name.split('-');
  83726. var pano0 = images360.getPano(names[0]);
  83727. var pano1 = images360.getPano(names[1]);
  83728. line.visible = this.visiblePanos.includes(pano0) || this.visiblePanos.includes(pano1);
  83729. });
  83730. }
  83731. updateCursor(){
  83732. let cursor;
  83733. if(this.activeViewName == 'mainView' || !this.selectedPano){
  83734. cursor = null;
  83735. }else {
  83736. cursor = Alignment$1.handleState;
  83737. }
  83738. if(cursor == 'rotate'){
  83739. viewer.dispatchEvent({
  83740. type : "CursorChange", action : "add", name:"rotatePointcloud"
  83741. });
  83742. viewer.dispatchEvent({
  83743. type : "CursorChange", action : "remove", name:"movePointcloud"
  83744. });
  83745. }else if(cursor == 'translate'){
  83746. viewer.dispatchEvent({
  83747. type : "CursorChange", action : "add", name:"movePointcloud"
  83748. });
  83749. viewer.dispatchEvent({
  83750. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  83751. });
  83752. }else {
  83753. viewer.dispatchEvent({
  83754. type : "CursorChange", action : "remove", name:"movePointcloud"
  83755. });
  83756. viewer.dispatchEvent({
  83757. type : "CursorChange", action : "remove", name:"rotatePointcloud"
  83758. });
  83759. }
  83760. //this.cursorState = cursor
  83761. }
  83762. setLinkOperateState(name, state, informinformBy2d){
  83763. if(state && name == this.operation || !state && name != this.operation)return
  83764. let old = this.operation;
  83765. this.operation = state ? name : null;
  83766. if(this.operation == 'removeLink'){
  83767. if(this.selectedLine){
  83768. this.selectedLine.dispatchEvent('click');//删除
  83769. }
  83770. if(this.selectedPano){
  83771. this.selectedPano.circle.dispatchEvent('click');//删除
  83772. }
  83773. }
  83774. if(this.operation != 'addLink'){
  83775. this.linkGuideLine.visible = false;
  83776. }
  83777. if(!state && !informinformBy2d){
  83778. this.dispatchEvent({type: "operationCancel", operation: old});
  83779. }
  83780. if(this.operation == 'addLink'){
  83781. viewer.dispatchEvent({type : "CursorChange", action : "add", name:"connectPano"} );
  83782. }else {
  83783. viewer.dispatchEvent({type : "CursorChange", action : "remove", name:"connectPano"} );
  83784. }
  83785. if(this.operation == 'removeLink'){
  83786. viewer.dispatchEvent({type : "CursorChange", action : "add", name:"disconnectPano"} );
  83787. }else {
  83788. viewer.dispatchEvent({type : "CursorChange", action : "remove", name:"disconnectPano"} );
  83789. }
  83790. }
  83791. /////////////////////////////////
  83792. initPanoLink(){
  83793. images360.panos.forEach((pano)=>{
  83794. this.panoLink[pano.id] = {};
  83795. });
  83796. images360.panos.forEach((pano)=>{
  83797. pano.visibles.forEach(index=>{//visibles中存的是下标!
  83798. this.linkChange(pano, images360.getPano(index,'index'), 'add');
  83799. });
  83800. });
  83801. console.log('panoLink',this.panoLink);
  83802. }
  83803. groupChange(pano0, pano1, type){//修改group (type == 'remove'时,pano1可以为空)
  83804. if(type == 'add'){
  83805. Common.pushToGroupAuto([pano0, pano1], this.panoGroup );
  83806. }else {
  83807. let atGroup = this.panoGroup.find(e=>e.includes(pano0) && (e.includes(pano1) || !pano1));//所在组
  83808. if(!atGroup){
  83809. if(pano1){
  83810. console.log('这两个pano原本就不在一个组', pano0.id, pano1.id);
  83811. }else {
  83812. console.log('pano0不在任何组', pano0);
  83813. }
  83814. return
  83815. }
  83816. //断开连接时,因为组内没有其他成员的连接信息,所以需要清除整组,并将剩余的一个个重新连接
  83817. this.panoGroup.splice(this.panoGroup.indexOf(atGroup),1); //删除
  83818. atGroup.forEach(pano=>{//然后再重新生成这两个和组的关系,各自分组
  83819. if(pano == pano0 || pano == pano1)return
  83820. for(let id in this.panoLink[pano.id]){
  83821. if(this.panoLink[pano.id][id]){
  83822. let pano_ = images360.getPano(id);
  83823. Common.pushToGroupAuto([pano, pano_], this.panoGroup );
  83824. }
  83825. }
  83826. });
  83827. }
  83828. }
  83829. linkChange(pano0, pano1, type){//修改link (type == 'remove'时,pano1可以为空)
  83830. let temp = [];
  83831. if(type == 'add'){
  83832. if(!pano1)return console.error('不支持add时pano1为空')
  83833. this.panoLink[pano0.id][pano1.id] = this.panoLink[pano0.id][pano1.id] || {};
  83834. this.panoLink[pano1.id][pano0.id] = this.panoLink[pano1.id][pano0.id] || {};
  83835. }else {
  83836. if(!pano1){
  83837. for(let id in this.panoLink[pano0.id]){
  83838. if(this.panoLink[pano0.id][id]){
  83839. this.panoLink[id][pano0.id] = false;
  83840. temp.push(id);
  83841. }
  83842. }
  83843. this.panoLink[pano0.id] = {}; //全部断连
  83844. }else {
  83845. this.panoLink[pano0.id][pano1.id] = false;
  83846. this.panoLink[pano1.id][pano0.id] = false;
  83847. }
  83848. }
  83849. if(!pano1){ //全部断连
  83850. temp.forEach(id=>{
  83851. this.lineChange(pano0, images360.getPano(id) , type);
  83852. });
  83853. }else {
  83854. this.lineChange(pano0, pano1, type);
  83855. }
  83856. this.groupChange(pano0, pano1, type);
  83857. //this.updateSelectGroup()
  83858. this.selectPano(this.selectedPano, false,true); //更新选中点云显示
  83859. }
  83860. lineChange(pano0, pano1, type){//修改line
  83861. if(type == 'add'){
  83862. if(this.panoLink[pano0.id][pano1.id].line) return
  83863. let line = LineDraw.createFatLine([pano0.position, pano1.position], {material:lineMats$3.default});
  83864. line.name = `${pano0.id}-${pano1.id}`;
  83865. line.renderOrder = line.pickOrder = renderOrders$1.line;
  83866. this.lineMeshes.add(line);
  83867. this.panoLink[pano0.id][pano1.id].line = this.panoLink[pano1.id][pano0.id].line = line;
  83868. line.addEventListener('mouseover', ()=>{
  83869. if(this.clickToZoomInEnabled)return
  83870. if(this.activeViewName == 'mainView')return
  83871. if(this.selectedLine != line)line.material = lineMats$3.hovered;
  83872. viewer.dispatchEvent({
  83873. type : "CursorChange", action : "add", name:"hoverLine"
  83874. });
  83875. });
  83876. line.addEventListener('mouseleave', ()=>{
  83877. if(this.clickToZoomInEnabled)return
  83878. //if(this.activeViewName == 'mainView')return
  83879. if(this.selectedLine != line)line.material = lineMats$3.default;
  83880. viewer.dispatchEvent({
  83881. type : "CursorChange", action : "remove", name:"hoverLine"
  83882. });
  83883. });
  83884. line.addEventListener('click', (e)=>{
  83885. if(this.clickToZoomInEnabled)return
  83886. if(this.activeViewName == 'mainView')return
  83887. if(this.operation == 'removeLink'){
  83888. if(this.selectedLine == line) this.selectLine(null);
  83889. return this.linkChange(pano0, pano1, 'remove')
  83890. }
  83891. this.selectLine(line);
  83892. });
  83893. }else {
  83894. let line = this.lineMeshes.children.find(e=>e.name == `${pano0.id}-${pano1.id}` || e.name == `${pano1.id}-${pano0.id}` );
  83895. if(line){
  83896. this.lineMeshes.remove(line);
  83897. line.geometry.dispose();
  83898. }
  83899. }
  83900. }
  83901. selectLine(line){
  83902. if(this.selectedLine == line)return
  83903. if(this.selectedLine){
  83904. this.selectedLine.material = lineMats$3.default;
  83905. }
  83906. if(line){
  83907. line.material = lineMats$3.selected;
  83908. }
  83909. this.selectedLine = line;
  83910. }
  83911. addPanoMesh(){
  83912. let map = texLoader$c.load(Potree.resourcePath+'/textures/correct_n.png' );
  83913. circleMats.default = new MeshBasicMaterial({
  83914. map,
  83915. color: 0xffffff,
  83916. transparent: true,
  83917. depthTest: false,
  83918. depthWrite: false,
  83919. });
  83920. circleMats.hovered = new MeshBasicMaterial({
  83921. map,
  83922. color: 0xffff00,
  83923. transparent: true,
  83924. depthTest: false,
  83925. depthWrite: false,
  83926. });
  83927. circleMats.selected = new MeshBasicMaterial({
  83928. map: texLoader$c.load(Potree.resourcePath+'/textures/correct_s.png' ) ,
  83929. color: 0xffffff,
  83930. transparent: true,
  83931. depthTest: false,
  83932. depthWrite: false,
  83933. });
  83934. let setPos = (circle)=>{
  83935. circle.position.copy(circle.pano.position);
  83936. for(let id in this.panoLink[circle.pano.id]){
  83937. let linkInfo = this.panoLink[circle.pano.id][id];
  83938. if(linkInfo){
  83939. LineDraw.updateLine(linkInfo.line, [circle.pano.position, images360.getPano(id).position] );
  83940. }
  83941. }
  83942. circle.update(); //update sprite Matrix
  83943. };
  83944. images360.panos.forEach(pano=>{
  83945. var circle = new Sprite$1({mat: circleMats.default, sizeInfo:{
  83946. minSize : 50 , maxSize : 120, nearBound : 2, farBound : 10,
  83947. },
  83948. renderOrder : renderOrders$1.circle,
  83949. pickOrder: renderOrders$1.circle
  83950. }); //new THREE.Sprite(circleMats.default)
  83951. circle.name = 'panoCircle';
  83952. circle.sid = pano.id;
  83953. circle.pano = pano;
  83954. pano.circle = circle;
  83955. this.panoMeshs.add(circle);
  83956. setPos(circle);
  83957. pano.addEventListener('rePos', setPos.bind(this,circle));
  83958. let drag = ()=>{
  83959. if(this.activeViewName == 'mainView')return
  83960. this.selectPano(circle.pano); //为了方便拖拽点云,拖动circle就直接选中
  83961. viewer.inputHandler.drag.object = null; //取消拖拽状态,否则不触发点云拖动
  83962. };
  83963. circle.addEventListener('drag', drag);
  83964. /* circle.addEventListener('drop', ()=>{
  83965. }) */
  83966. circle.addEventListener('mouseover', ()=>{
  83967. this.hoverPano(pano,true);
  83968. });
  83969. circle.addEventListener('mouseleave', ()=>{
  83970. this.hoverPano(pano,false);
  83971. });
  83972. circle.addEventListener('click', ()=>{
  83973. //if(this.activeViewName == 'mainView')return
  83974. if(this.clickToZoomInEnabled)return
  83975. if(this.operation == 'removeLink'){
  83976. this.linkChange(pano, null, 'remove'); //删除所有连接
  83977. }
  83978. if(this.selectedPano == circle.pano) return this.selectPano(null)
  83979. if(this.operation == 'addLink' && this.selectedPano){
  83980. this.linkChange(this.selectedPano, circle.pano, 'add');
  83981. //this.setLinkOperateState('addLink',false)
  83982. return
  83983. }
  83984. //if(this.operation == 'removeLink' && this.selectedPano){ //和选择中心点冲突
  83985. // this.linkChange(this.selectedPano, circle.pano, 'remove')
  83986. // //this.setLinkOperateState('removeLink',false)
  83987. // return
  83988. // }
  83989. this.selectPano(circle.pano);
  83990. });
  83991. });
  83992. }
  83993. hoverPano(pano, state){
  83994. if(this.clickToZoomInEnabled)return
  83995. if(pano && state){ //在hover一个pano之前,一定会先取消已经hover的pano, 最多存在一个hovered的pano
  83996. if(this.hoveredPano == pano)return
  83997. if(this.hoveredPano){
  83998. this.hoverPano(this.hoveredPano,false);
  83999. }
  84000. this.hoveredPano = pano;
  84001. pano.hovered = true;
  84002. if(/* this.activeViewName == 'mainView' || */Alignment$1.handleState && this.selectedPano && this.selectedPano == pano)return
  84003. if(this.operation != 'addLink' || !this.selectedPano || this.selectedPano == pano){ // this.selectedPano == pano?
  84004. viewer.dispatchEvent({
  84005. type : "CursorChange", action : "add", name:"hoverPano"
  84006. });
  84007. }
  84008. if(this.selectedPano != pano) pano.circle.material = circleMats.hovered;
  84009. }else if(pano && !state){//unhover
  84010. if(this.hoveredPano != pano)return
  84011. pano.hovered = false;
  84012. viewer.dispatchEvent({
  84013. type : "CursorChange", action : "remove", name:"hoverPano"
  84014. });
  84015. if(this.selectedPano != pano) pano.circle.material = circleMats.default;
  84016. this.hoveredPano = null;
  84017. }else {//unhover any
  84018. if(this.hoveredPano){
  84019. this.hoverPano(this.hoveredPano, false);
  84020. }
  84021. }
  84022. }
  84023. selectPano(pano, informinformBy2d, force){
  84024. if(this.selectedPano == pano && !force)return
  84025. let lastSeletedPano = this.selectedPano;
  84026. if(this.selectedPano){
  84027. this.selectedPano.circle.material = circleMats.default;
  84028. this.selectedPano.circle.renderOrder = renderOrders$1.circle;
  84029. if(this.activeViewName != 'mainView'){
  84030. this.selectedClouds.forEach(e=>{
  84031. e.changePointOpacity(opacitys.default,true);
  84032. e.material.color = pointColor.default;
  84033. });
  84034. //this.selectedPano.pointcloud.changePointOpacity(opacitys.default,true)
  84035. //this.selectedPano.pointcloud.material.color = Potree.config.material.pointColor
  84036. }
  84037. }
  84038. this.selectedPano = pano || null;
  84039. this.updateSelectGroup();
  84040. if(pano){
  84041. this.selectedPano.circle.material = circleMats.selected;
  84042. this.selectedPano.circle.renderOrder = this.selectedPano.circle.pickOrder = renderOrders$1.circleSelected; //侧视图能显示在最前
  84043. //this.selectedPano.pointcloud.material.color = '#ff0000'
  84044. //this.selectedPano.pointcloud.changePointOpacity(opacitys.selected,true)
  84045. if(this.activeViewName != 'mainView'){
  84046. this.selectedClouds.forEach(e=>{
  84047. e.changePointOpacity(opacitys.selected,true);
  84048. e.material.color = pointColor.selected;
  84049. });
  84050. }
  84051. {//自动切换楼层
  84052. let atFloor = SiteModel$1.entities.find(e=>e.buildType == 'floor' && e.panos.includes(pano));
  84053. if(!atFloor){
  84054. atFloor = 'all';
  84055. }else {
  84056. }
  84057. this.gotoFloor(atFloor, false, 600 );
  84058. }
  84059. }
  84060. this.updateCursor();
  84061. if(informinformBy2d){
  84062. if(this.selectedPano){
  84063. if(this.activeViewName == 'mainView'){ //平移,focus选中的pano
  84064. let distance = this.lastDisToPano || 5;
  84065. if(lastSeletedPano){
  84066. distance = viewer.mainViewport.camera.position.distanceTo(lastSeletedPano.position);
  84067. }
  84068. viewer.focusOnObject({ position:this.selectedPano.position}, 'point', null, {distance });
  84069. }else {
  84070. this.moveFit(this.selectedPano.position, {}, 500);
  84071. }
  84072. }
  84073. }else {
  84074. this.dispatchEvent({type:'panoSelect', pano });
  84075. }
  84076. }
  84077. updateSelectGroup(){//更新选中的组
  84078. this.selectedGroup = this.panoGroup.find(e=>e.includes(this.selectedPano));
  84079. this.selectedClouds = this.selectedPano ? (this.selectedGroup || [this.selectedPano]).map(e=>e.pointcloud) : [];
  84080. }
  84081. checkIfCanSave(){//如果未全部相连,不能保存
  84082. for(let datasetId in Potree.settings.datasetsPanos ) {
  84083. if(!this.checkIfAllLinked({datasetId})){
  84084. console.log('没有全部连通,不能保存。其中一个:', datasetId);
  84085. return
  84086. }
  84087. }
  84088. return true
  84089. }
  84090. checkIfAllLinked(o){//某个(or组所在的)数据集是否全部连通
  84091. let datasetId, group;
  84092. if(o.group){
  84093. group = o.group;
  84094. let pano = o.group[0];
  84095. if(!pano)return //会有没有漫游点的点云来编辑吗
  84096. datasetId = pano.pointcloud.dataset_id;
  84097. }else if(o.datasetId){
  84098. datasetId = o.datasetId;
  84099. group = this.panoGroup.find(panos=>panos[0].pointcloud.dataset_id == datasetId );
  84100. if(!group)return //要找的数据集的pano全部都孤立了
  84101. }
  84102. let panos = Potree.settings.datasetsPanos[datasetId].panos;
  84103. return panos.length == group.length
  84104. }
  84105. exportSavingData(){//输出漫游点新的坐标和朝向、以及连接信息
  84106. let sweepLocations = {};
  84107. for(let datasetId in Potree.settings.datasetsPanos ) {
  84108. let {panos} = Potree.settings.datasetsPanos[datasetId];
  84109. let data = panos.map(pano=>{
  84110. let visibles = [];
  84111. for(let id in this.panoLink[pano.id]){
  84112. if(this.panoLink[pano.id][id]){
  84113. visibles.push(viewer.images360.getPano(id).index);
  84114. }
  84115. }
  84116. return Object.assign({}, pano.panosData, {
  84117. uuid: pano.uuid,
  84118. pose:{
  84119. translation: dealData(pano.position.clone().negate()),
  84120. rotation: dealData(new Quaternion().setFromRotationMatrix(pano.panoMatrix) ),
  84121. },
  84122. visibles,
  84123. //subgroup: 0,group: 1, "id_view":..
  84124. })
  84125. });
  84126. sweepLocations[datasetId] = {sweepLocations:data};
  84127. }
  84128. /* this.lineMeshes.children.forEach(e=>{//从line中搜集连接信息,而不从linkInfo,这样visibles不会重复一次
  84129. let names = e.name.split('-') //是不是该转成数字
  84130. var pano0 = names[0]
  84131. var pano1 = names[1]
  84132. sweepLocations.find(s=>s.uuid == pano0).visibles.push(pano1)
  84133. }) */
  84134. function dealData(value){
  84135. let v = math.toPrecision(value, 6);
  84136. if(v instanceof Quaternion){
  84137. return {x:v.x, y:v.y, z:v.z, w:v.w}
  84138. }else if(v instanceof Vector3){
  84139. return {x:v.x, y:v.y, z:v.z}
  84140. }
  84141. }
  84142. console.log(sweepLocations);
  84143. return sweepLocations
  84144. }
  84145. }
  84146. /*
  84147. 不同数据集之间不能连线
  84148. 不同楼层可能也不能
  84149. 如果楼层在不同建筑物怎么办? 楼层切换按钮只能在一个建筑内切换。
  84150. 全部相连时不能移动和旋转
  84151. 如果未全部相连,不能保存
  84152. */
  84153. var PanoEditor$1 = new PanoEditor();
  84154. var OBJLoader = ( function () {
  84155. // o object_name | g group_name
  84156. var object_pattern = /^[og]\s*(.+)?/;
  84157. // mtllib file_reference
  84158. var material_library_pattern = /^mtllib /;
  84159. // usemtl material_name
  84160. var material_use_pattern = /^usemtl /;
  84161. // usemap map_name
  84162. var map_use_pattern = /^usemap /;
  84163. var vA = new Vector3();
  84164. var vB = new Vector3();
  84165. var vC = new Vector3();
  84166. var ab = new Vector3();
  84167. var cb = new Vector3();
  84168. function ParserState() {
  84169. var state = {
  84170. objects: [],
  84171. object: {},
  84172. vertices: [],
  84173. normals: [],
  84174. colors: [],
  84175. uvs: [],
  84176. materials: {},
  84177. materialLibraries: [],
  84178. startObject: function ( name, fromDeclaration ) {
  84179. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  84180. // file. We need to use it for the first parsed g/o to keep things in sync.
  84181. if ( this.object && this.object.fromDeclaration === false ) {
  84182. this.object.name = name;
  84183. this.object.fromDeclaration = ( fromDeclaration !== false );
  84184. return;
  84185. }
  84186. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  84187. if ( this.object && typeof this.object._finalize === 'function' ) {
  84188. this.object._finalize( true );
  84189. }
  84190. this.object = {
  84191. name: name || '',
  84192. fromDeclaration: ( fromDeclaration !== false ),
  84193. geometry: {
  84194. vertices: [],
  84195. normals: [],
  84196. colors: [],
  84197. uvs: [],
  84198. hasUVIndices: false
  84199. },
  84200. materials: [],
  84201. smooth: true,
  84202. startMaterial: function ( name, libraries ) {
  84203. var previous = this._finalize( false );
  84204. // New usemtl declaration overwrites an inherited material, except if faces were declared
  84205. // after the material, then it must be preserved for proper MultiMaterial continuation.
  84206. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  84207. this.materials.splice( previous.index, 1 );
  84208. }
  84209. var material = {
  84210. index: this.materials.length,
  84211. name: name || '',
  84212. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  84213. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  84214. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  84215. groupEnd: - 1,
  84216. groupCount: - 1,
  84217. inherited: false,
  84218. clone: function ( index ) {
  84219. var cloned = {
  84220. index: ( typeof index === 'number' ? index : this.index ),
  84221. name: this.name,
  84222. mtllib: this.mtllib,
  84223. smooth: this.smooth,
  84224. groupStart: 0,
  84225. groupEnd: - 1,
  84226. groupCount: - 1,
  84227. inherited: false
  84228. };
  84229. cloned.clone = this.clone.bind( cloned );
  84230. return cloned;
  84231. }
  84232. };
  84233. this.materials.push( material );
  84234. return material;
  84235. },
  84236. currentMaterial: function () {
  84237. if ( this.materials.length > 0 ) {
  84238. return this.materials[ this.materials.length - 1 ];
  84239. }
  84240. return undefined;
  84241. },
  84242. _finalize: function ( end ) {
  84243. var lastMultiMaterial = this.currentMaterial();
  84244. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  84245. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  84246. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  84247. lastMultiMaterial.inherited = false;
  84248. }
  84249. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  84250. if ( end && this.materials.length > 1 ) {
  84251. for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) {
  84252. if ( this.materials[ mi ].groupCount <= 0 ) {
  84253. this.materials.splice( mi, 1 );
  84254. }
  84255. }
  84256. }
  84257. // Guarantee at least one empty material, this makes the creation later more straight forward.
  84258. if ( end && this.materials.length === 0 ) {
  84259. this.materials.push( {
  84260. name: '',
  84261. smooth: this.smooth
  84262. } );
  84263. }
  84264. return lastMultiMaterial;
  84265. }
  84266. };
  84267. // Inherit previous objects material.
  84268. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  84269. // If a usemtl declaration is encountered while this new object is being parsed, it will
  84270. // overwrite the inherited material. Exception being that there was already face declarations
  84271. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  84272. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  84273. var declared = previousMaterial.clone( 0 );
  84274. declared.inherited = true;
  84275. this.object.materials.push( declared );
  84276. }
  84277. this.objects.push( this.object );
  84278. },
  84279. finalize: function () {
  84280. if ( this.object && typeof this.object._finalize === 'function' ) {
  84281. this.object._finalize( true );
  84282. }
  84283. },
  84284. parseVertexIndex: function ( value, len ) {
  84285. var index = parseInt( value, 10 );
  84286. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  84287. },
  84288. parseNormalIndex: function ( value, len ) {
  84289. var index = parseInt( value, 10 );
  84290. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  84291. },
  84292. parseUVIndex: function ( value, len ) {
  84293. var index = parseInt( value, 10 );
  84294. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  84295. },
  84296. addVertex: function ( a, b, c ) {
  84297. var src = this.vertices;
  84298. var dst = this.object.geometry.vertices;
  84299. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  84300. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  84301. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  84302. },
  84303. addVertexPoint: function ( a ) {
  84304. var src = this.vertices;
  84305. var dst = this.object.geometry.vertices;
  84306. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  84307. },
  84308. addVertexLine: function ( a ) {
  84309. var src = this.vertices;
  84310. var dst = this.object.geometry.vertices;
  84311. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  84312. },
  84313. addNormal: function ( a, b, c ) {
  84314. var src = this.normals;
  84315. var dst = this.object.geometry.normals;
  84316. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  84317. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  84318. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  84319. },
  84320. addFaceNormal: function ( a, b, c ) {
  84321. var src = this.vertices;
  84322. var dst = this.object.geometry.normals;
  84323. vA.fromArray( src, a );
  84324. vB.fromArray( src, b );
  84325. vC.fromArray( src, c );
  84326. cb.subVectors( vC, vB );
  84327. ab.subVectors( vA, vB );
  84328. cb.cross( ab );
  84329. cb.normalize();
  84330. dst.push( cb.x, cb.y, cb.z );
  84331. dst.push( cb.x, cb.y, cb.z );
  84332. dst.push( cb.x, cb.y, cb.z );
  84333. },
  84334. addColor: function ( a, b, c ) {
  84335. var src = this.colors;
  84336. var dst = this.object.geometry.colors;
  84337. if ( src[ a ] !== undefined ) dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  84338. if ( src[ b ] !== undefined ) dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  84339. if ( src[ c ] !== undefined ) dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  84340. },
  84341. addUV: function ( a, b, c ) {
  84342. var src = this.uvs;
  84343. var dst = this.object.geometry.uvs;
  84344. dst.push( src[ a + 0 ], src[ a + 1 ] );
  84345. dst.push( src[ b + 0 ], src[ b + 1 ] );
  84346. dst.push( src[ c + 0 ], src[ c + 1 ] );
  84347. },
  84348. addDefaultUV: function () {
  84349. var dst = this.object.geometry.uvs;
  84350. dst.push( 0, 0 );
  84351. dst.push( 0, 0 );
  84352. dst.push( 0, 0 );
  84353. },
  84354. addUVLine: function ( a ) {
  84355. var src = this.uvs;
  84356. var dst = this.object.geometry.uvs;
  84357. dst.push( src[ a + 0 ], src[ a + 1 ] );
  84358. },
  84359. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  84360. var vLen = this.vertices.length;
  84361. var ia = this.parseVertexIndex( a, vLen );
  84362. var ib = this.parseVertexIndex( b, vLen );
  84363. var ic = this.parseVertexIndex( c, vLen );
  84364. this.addVertex( ia, ib, ic );
  84365. this.addColor( ia, ib, ic );
  84366. // normals
  84367. if ( na !== undefined && na !== '' ) {
  84368. var nLen = this.normals.length;
  84369. ia = this.parseNormalIndex( na, nLen );
  84370. ib = this.parseNormalIndex( nb, nLen );
  84371. ic = this.parseNormalIndex( nc, nLen );
  84372. this.addNormal( ia, ib, ic );
  84373. } else {
  84374. this.addFaceNormal( ia, ib, ic );
  84375. }
  84376. // uvs
  84377. if ( ua !== undefined && ua !== '' ) {
  84378. var uvLen = this.uvs.length;
  84379. ia = this.parseUVIndex( ua, uvLen );
  84380. ib = this.parseUVIndex( ub, uvLen );
  84381. ic = this.parseUVIndex( uc, uvLen );
  84382. this.addUV( ia, ib, ic );
  84383. this.object.geometry.hasUVIndices = true;
  84384. } else {
  84385. // add placeholder values (for inconsistent face definitions)
  84386. this.addDefaultUV();
  84387. }
  84388. },
  84389. addPointGeometry: function ( vertices ) {
  84390. this.object.geometry.type = 'Points';
  84391. var vLen = this.vertices.length;
  84392. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  84393. var index = this.parseVertexIndex( vertices[ vi ], vLen );
  84394. this.addVertexPoint( index );
  84395. this.addColor( index );
  84396. }
  84397. },
  84398. addLineGeometry: function ( vertices, uvs ) {
  84399. this.object.geometry.type = 'Line';
  84400. var vLen = this.vertices.length;
  84401. var uvLen = this.uvs.length;
  84402. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  84403. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  84404. }
  84405. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  84406. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  84407. }
  84408. }
  84409. };
  84410. state.startObject( '', false );
  84411. return state;
  84412. }
  84413. //
  84414. function OBJLoader( manager ) {
  84415. Loader.call( this, manager );
  84416. this.materials = null;
  84417. }
  84418. OBJLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  84419. constructor: OBJLoader,
  84420. load: function ( url, onLoad, onProgress, onError ) {
  84421. var scope = this;
  84422. var loader = new FileLoader( this.manager );
  84423. loader.setPath( this.path );
  84424. loader.setRequestHeader( this.requestHeader );
  84425. loader.setWithCredentials( this.withCredentials );
  84426. loader.load( url, function ( text , total ) {// xzw add total
  84427. try {
  84428. onLoad( scope.parse( text ) , total );
  84429. } catch ( e ) {
  84430. if ( onError ) {
  84431. onError( e );
  84432. } else {
  84433. console.error( e );
  84434. }
  84435. scope.manager.itemError( url );
  84436. }
  84437. }, onProgress, onError );
  84438. },
  84439. setMaterials: function ( materials ) {
  84440. this.materials = materials;
  84441. return this;
  84442. },
  84443. parse: function ( text ) {
  84444. var state = new ParserState();
  84445. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  84446. // This is faster than String.split with regex that splits on both
  84447. text = text.replace( /\r\n/g, '\n' );
  84448. }
  84449. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  84450. // join lines separated by a line continuation character (\)
  84451. text = text.replace( /\\\n/g, '' );
  84452. }
  84453. var lines = text.split( '\n' );
  84454. var line = '', lineFirstChar = '';
  84455. var lineLength = 0;
  84456. var result = [];
  84457. // Faster to just trim left side of the line. Use if available.
  84458. var trimLeft = ( typeof ''.trimLeft === 'function' );
  84459. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  84460. line = lines[ i ];
  84461. line = trimLeft ? line.trimLeft() : line.trim();
  84462. lineLength = line.length;
  84463. if ( lineLength === 0 ) continue;
  84464. lineFirstChar = line.charAt( 0 );
  84465. // @todo invoke passed in handler if any
  84466. if ( lineFirstChar === '#' ) continue;
  84467. if ( lineFirstChar === 'v' ) {
  84468. var data = line.split( /\s+/ );
  84469. switch ( data[ 0 ] ) {
  84470. case 'v':
  84471. state.vertices.push(
  84472. parseFloat( data[ 1 ] ),
  84473. parseFloat( data[ 2 ] ),
  84474. parseFloat( data[ 3 ] )
  84475. );
  84476. if ( data.length >= 7 ) {
  84477. state.colors.push(
  84478. parseFloat( data[ 4 ] ),
  84479. parseFloat( data[ 5 ] ),
  84480. parseFloat( data[ 6 ] )
  84481. );
  84482. } else {
  84483. // if no colors are defined, add placeholders so color and vertex indices match
  84484. state.colors.push( undefined, undefined, undefined );
  84485. }
  84486. break;
  84487. case 'vn':
  84488. state.normals.push(
  84489. parseFloat( data[ 1 ] ),
  84490. parseFloat( data[ 2 ] ),
  84491. parseFloat( data[ 3 ] )
  84492. );
  84493. break;
  84494. case 'vt':
  84495. state.uvs.push(
  84496. parseFloat( data[ 1 ] ),
  84497. parseFloat( data[ 2 ] )
  84498. );
  84499. break;
  84500. }
  84501. } else if ( lineFirstChar === 'f' ) {
  84502. var lineData = line.substr( 1 ).trim();
  84503. var vertexData = lineData.split( /\s+/ );
  84504. var faceVertices = [];
  84505. // Parse the face vertex data into an easy to work with format
  84506. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  84507. var vertex = vertexData[ j ];
  84508. if ( vertex.length > 0 ) {
  84509. var vertexParts = vertex.split( '/' );
  84510. faceVertices.push( vertexParts );
  84511. }
  84512. }
  84513. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  84514. var v1 = faceVertices[ 0 ];
  84515. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  84516. var v2 = faceVertices[ j ];
  84517. var v3 = faceVertices[ j + 1 ];
  84518. state.addFace(
  84519. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  84520. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  84521. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  84522. );
  84523. }
  84524. } else if ( lineFirstChar === 'l' ) {
  84525. var lineParts = line.substring( 1 ).trim().split( ' ' );
  84526. var lineVertices = [], lineUVs = [];
  84527. if ( line.indexOf( '/' ) === - 1 ) {
  84528. lineVertices = lineParts;
  84529. } else {
  84530. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  84531. var parts = lineParts[ li ].split( '/' );
  84532. if ( parts[ 0 ] !== '' ) lineVertices.push( parts[ 0 ] );
  84533. if ( parts[ 1 ] !== '' ) lineUVs.push( parts[ 1 ] );
  84534. }
  84535. }
  84536. state.addLineGeometry( lineVertices, lineUVs );
  84537. } else if ( lineFirstChar === 'p' ) {
  84538. var lineData = line.substr( 1 ).trim();
  84539. var pointData = lineData.split( ' ' );
  84540. state.addPointGeometry( pointData );
  84541. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  84542. // o object_name
  84543. // or
  84544. // g group_name
  84545. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  84546. // var name = result[ 0 ].substr( 1 ).trim();
  84547. var name = ( ' ' + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  84548. state.startObject( name );
  84549. } else if ( material_use_pattern.test( line ) ) {
  84550. // material
  84551. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  84552. } else if ( material_library_pattern.test( line ) ) {
  84553. // mtl file
  84554. state.materialLibraries.push( line.substring( 7 ).trim() );
  84555. } else if ( map_use_pattern.test( line ) ) {
  84556. // the line is parsed but ignored since the loader assumes textures are defined MTL files
  84557. // (according to https://www.okino.com/conv/imp_wave.htm, 'usemap' is the old-style Wavefront texture reference method)
  84558. console.warn( 'THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.' );
  84559. } else if ( lineFirstChar === 's' ) {
  84560. result = line.split( ' ' );
  84561. // smooth shading
  84562. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  84563. // but does not define a usemtl for each face set.
  84564. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  84565. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  84566. // where explicit usemtl defines geometry groups.
  84567. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  84568. /*
  84569. * http://paulbourke.net/dataformats/obj/
  84570. * or
  84571. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  84572. *
  84573. * From chapter "Grouping" Syntax explanation "s group_number":
  84574. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  84575. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  84576. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  84577. * than 0."
  84578. */
  84579. if ( result.length > 1 ) {
  84580. var value = result[ 1 ].trim().toLowerCase();
  84581. state.object.smooth = ( value !== '0' && value !== 'off' );
  84582. } else {
  84583. // ZBrush can produce "s" lines #11707
  84584. state.object.smooth = true;
  84585. }
  84586. var material = state.object.currentMaterial();
  84587. if ( material ) material.smooth = state.object.smooth;
  84588. } else {
  84589. // Handle null terminated files without exception
  84590. if ( line === '\0' ) continue;
  84591. console.warn( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  84592. }
  84593. }
  84594. state.finalize();
  84595. var container = new Group();
  84596. container.materialLibraries = [].concat( state.materialLibraries );
  84597. var hasPrimitives = ! ( state.objects.length === 1 && state.objects[ 0 ].geometry.vertices.length === 0 );
  84598. if ( hasPrimitives === true ) {
  84599. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  84600. var object = state.objects[ i ];
  84601. var geometry = object.geometry;
  84602. var materials = object.materials;
  84603. var isLine = ( geometry.type === 'Line' );
  84604. var isPoints = ( geometry.type === 'Points' );
  84605. var hasVertexColors = false;
  84606. // Skip o/g line declarations that did not follow with any faces
  84607. if ( geometry.vertices.length === 0 ) continue;
  84608. var buffergeometry = new BufferGeometry();
  84609. buffergeometry.setAttribute( 'position', new Float32BufferAttribute( geometry.vertices, 3 ) );
  84610. if ( geometry.normals.length > 0 ) {
  84611. buffergeometry.setAttribute( 'normal', new Float32BufferAttribute( geometry.normals, 3 ) );
  84612. }
  84613. if ( geometry.colors.length > 0 ) {
  84614. hasVertexColors = true;
  84615. buffergeometry.setAttribute( 'color', new Float32BufferAttribute( geometry.colors, 3 ) );
  84616. }
  84617. if ( geometry.hasUVIndices === true ) {
  84618. buffergeometry.setAttribute( 'uv', new Float32BufferAttribute( geometry.uvs, 2 ) );
  84619. }
  84620. // Create materials
  84621. var createdMaterials = [];
  84622. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  84623. var sourceMaterial = materials[ mi ];
  84624. var materialHash = sourceMaterial.name + '_' + sourceMaterial.smooth + '_' + hasVertexColors;
  84625. var material = state.materials[ materialHash ];
  84626. if ( this.materials !== null ) {
  84627. material = this.materials.create( sourceMaterial.name );
  84628. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  84629. if ( isLine && material && ! ( material instanceof LineBasicMaterial ) ) {
  84630. var materialLine = new LineBasicMaterial();
  84631. Material.prototype.copy.call( materialLine, material );
  84632. materialLine.color.copy( material.color );
  84633. material = materialLine;
  84634. } else if ( isPoints && material && ! ( material instanceof PointsMaterial ) ) {
  84635. var materialPoints = new PointsMaterial( { size: 10, sizeAttenuation: false } );
  84636. Material.prototype.copy.call( materialPoints, material );
  84637. materialPoints.color.copy( material.color );
  84638. materialPoints.map = material.map;
  84639. material = materialPoints;
  84640. }
  84641. }
  84642. if ( material === undefined ) {
  84643. if ( isLine ) {
  84644. material = new LineBasicMaterial();
  84645. } else if ( isPoints ) {
  84646. material = new PointsMaterial( { size: 1, sizeAttenuation: false } );
  84647. } else {
  84648. material = new MeshPhongMaterial();
  84649. }
  84650. material.name = sourceMaterial.name;
  84651. material.flatShading = sourceMaterial.smooth ? false : true;
  84652. material.vertexColors = hasVertexColors;
  84653. state.materials[ materialHash ] = material;
  84654. }
  84655. createdMaterials.push( material );
  84656. }
  84657. // Create mesh
  84658. var mesh;
  84659. if ( createdMaterials.length > 1 ) {
  84660. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  84661. var sourceMaterial = materials[ mi ];
  84662. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  84663. }
  84664. if ( isLine ) {
  84665. mesh = new LineSegments( buffergeometry, createdMaterials );
  84666. } else if ( isPoints ) {
  84667. mesh = new Points( buffergeometry, createdMaterials );
  84668. } else {
  84669. mesh = new Mesh( buffergeometry, createdMaterials );
  84670. }
  84671. } else {
  84672. if ( isLine ) {
  84673. mesh = new LineSegments( buffergeometry, createdMaterials[ 0 ] );
  84674. } else if ( isPoints ) {
  84675. mesh = new Points( buffergeometry, createdMaterials[ 0 ] );
  84676. } else {
  84677. mesh = new Mesh( buffergeometry, createdMaterials[ 0 ] );
  84678. }
  84679. }
  84680. mesh.name = object.name;
  84681. container.add( mesh );
  84682. }
  84683. } else {
  84684. // if there is only the default parser state object with no geometry data, interpret data as point cloud
  84685. if ( state.vertices.length > 0 ) {
  84686. var material = new PointsMaterial( { size: 1, sizeAttenuation: false } );
  84687. var buffergeometry = new BufferGeometry();
  84688. buffergeometry.setAttribute( 'position', new Float32BufferAttribute( state.vertices, 3 ) );
  84689. if ( state.colors.length > 0 && state.colors[ 0 ] !== undefined ) {
  84690. buffergeometry.setAttribute( 'color', new Float32BufferAttribute( state.colors, 3 ) );
  84691. material.vertexColors = true;
  84692. }
  84693. var points = new Points( buffergeometry, material );
  84694. container.add( points );
  84695. }
  84696. }
  84697. return container;
  84698. }
  84699. } );
  84700. return OBJLoader;
  84701. } )();
  84702. /**
  84703. * Loads a Wavefront .mtl file specifying materials
  84704. */
  84705. var MTLLoader = function ( manager ) {
  84706. Loader.call( this, manager );
  84707. };
  84708. MTLLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
  84709. constructor: MTLLoader,
  84710. /**
  84711. * Loads and parses a MTL asset from a URL.
  84712. *
  84713. * @param {String} url - URL to the MTL file.
  84714. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  84715. * @param {Function} [onProgress] - Callback for download progress.
  84716. * @param {Function} [onError] - Callback for download errors.
  84717. *
  84718. * @see setPath setResourcePath
  84719. *
  84720. * @note In order for relative texture references to resolve correctly
  84721. * you must call setResourcePath() explicitly prior to load.
  84722. */
  84723. load: function ( url, onLoad, onProgress, onError ) {
  84724. var scope = this;
  84725. var path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  84726. var loader = new FileLoader( this.manager );
  84727. loader.setPath( this.path );
  84728. loader.setRequestHeader( this.requestHeader );
  84729. loader.setWithCredentials( this.withCredentials );
  84730. loader.load( url, function ( text ) {
  84731. try {
  84732. onLoad( scope.parse( text, path ) );
  84733. } catch ( e ) {
  84734. if ( onError ) {
  84735. onError( e );
  84736. } else {
  84737. console.error( e );
  84738. }
  84739. scope.manager.itemError( url );
  84740. }
  84741. }, onProgress, onError );
  84742. },
  84743. setMaterialOptions: function ( value ) {
  84744. this.materialOptions = value;
  84745. return this;
  84746. },
  84747. /**
  84748. * Parses a MTL file.
  84749. *
  84750. * @param {String} text - Content of MTL file
  84751. * @return {MTLLoader.MaterialCreator}
  84752. *
  84753. * @see setPath setResourcePath
  84754. *
  84755. * @note In order for relative texture references to resolve correctly
  84756. * you must call setResourcePath() explicitly prior to parse.
  84757. */
  84758. parse: function ( text, path ) {
  84759. var lines = text.split( '\n' );
  84760. var info = {};
  84761. var delimiter_pattern = /\s+/;
  84762. var materialsInfo = {};
  84763. for ( var i = 0; i < lines.length; i ++ ) {
  84764. var line = lines[ i ];
  84765. line = line.trim();
  84766. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  84767. // Blank line or comment ignore
  84768. continue;
  84769. }
  84770. var pos = line.indexOf( ' ' );
  84771. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  84772. key = key.toLowerCase();
  84773. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  84774. value = value.trim();
  84775. if ( key === 'newmtl' ) {
  84776. // New material
  84777. info = { name: value };
  84778. materialsInfo[ value ] = info;
  84779. } else {
  84780. if ( key === 'ka' || key === 'kd' || key === 'ks' || key === 'ke' ) {
  84781. var ss = value.split( delimiter_pattern, 3 );
  84782. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  84783. } else {
  84784. info[ key ] = value;
  84785. }
  84786. }
  84787. }
  84788. var materialCreator = new MTLLoader.MaterialCreator( this.resourcePath || path, this.materialOptions );
  84789. materialCreator.setCrossOrigin( this.crossOrigin );
  84790. materialCreator.setManager( this.manager );
  84791. materialCreator.setMaterials( materialsInfo );
  84792. return materialCreator;
  84793. }
  84794. } );
  84795. /**
  84796. * Create a new MTLLoader.MaterialCreator
  84797. * @param baseUrl - Url relative to which textures are loaded
  84798. * @param options - Set of options on how to construct the materials
  84799. * side: Which side to apply the material
  84800. * FrontSide (default), THREE.BackSide, THREE.DoubleSide
  84801. * wrap: What type of wrapping to apply for textures
  84802. * RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  84803. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  84804. * Default: false, assumed to be already normalized
  84805. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  84806. * Default: false
  84807. * @constructor
  84808. */
  84809. MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  84810. this.baseUrl = baseUrl || '';
  84811. this.options = options;
  84812. this.materialsInfo = {};
  84813. this.materials = {};
  84814. this.materialsArray = [];
  84815. this.nameLookup = {};
  84816. this.side = ( this.options && this.options.side ) ? this.options.side : FrontSide;
  84817. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : RepeatWrapping;
  84818. };
  84819. MTLLoader.MaterialCreator.prototype = {
  84820. constructor: MTLLoader.MaterialCreator,
  84821. crossOrigin: 'anonymous',
  84822. setCrossOrigin: function ( value ) {
  84823. this.crossOrigin = value;
  84824. return this;
  84825. },
  84826. setManager: function ( value ) {
  84827. this.manager = value;
  84828. },
  84829. setMaterials: function ( materialsInfo ) {
  84830. this.materialsInfo = this.convert( materialsInfo );
  84831. this.materials = {};
  84832. this.materialsArray = [];
  84833. this.nameLookup = {};
  84834. },
  84835. convert: function ( materialsInfo ) {
  84836. if ( ! this.options ) return materialsInfo;
  84837. var converted = {};
  84838. for ( var mn in materialsInfo ) {
  84839. // Convert materials info into normalized form based on options
  84840. var mat = materialsInfo[ mn ];
  84841. var covmat = {};
  84842. converted[ mn ] = covmat;
  84843. for ( var prop in mat ) {
  84844. var save = true;
  84845. var value = mat[ prop ];
  84846. var lprop = prop.toLowerCase();
  84847. switch ( lprop ) {
  84848. case 'kd':
  84849. case 'ka':
  84850. case 'ks':
  84851. // Diffuse color (color under white light) using RGB values
  84852. if ( this.options && this.options.normalizeRGB ) {
  84853. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  84854. }
  84855. if ( this.options && this.options.ignoreZeroRGBs ) {
  84856. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  84857. // ignore
  84858. save = false;
  84859. }
  84860. }
  84861. break;
  84862. default:
  84863. break;
  84864. }
  84865. if ( save ) {
  84866. covmat[ lprop ] = value;
  84867. }
  84868. }
  84869. }
  84870. return converted;
  84871. },
  84872. preload: function () {
  84873. for ( var mn in this.materialsInfo ) {
  84874. this.create( mn );
  84875. }
  84876. },
  84877. getIndex: function ( materialName ) {
  84878. return this.nameLookup[ materialName ];
  84879. },
  84880. getAsArray: function () {
  84881. var index = 0;
  84882. for ( var mn in this.materialsInfo ) {
  84883. this.materialsArray[ index ] = this.create( mn );
  84884. this.nameLookup[ mn ] = index;
  84885. index ++;
  84886. }
  84887. return this.materialsArray;
  84888. },
  84889. create: function ( materialName ) {
  84890. if ( this.materials[ materialName ] === undefined ) {
  84891. this.createMaterial_( materialName );
  84892. }
  84893. return this.materials[ materialName ];
  84894. },
  84895. createMaterial_: function ( materialName ) {
  84896. // Create material
  84897. var scope = this;
  84898. var mat = this.materialsInfo[ materialName ];
  84899. var params = {
  84900. name: materialName,
  84901. side: this.side
  84902. };
  84903. function resolveURL( baseUrl, url ) {
  84904. if ( typeof url !== 'string' || url === '' )
  84905. return '';
  84906. // Absolute URL
  84907. if ( /^https?:\/\//i.test( url ) ) return url;
  84908. return baseUrl + url;
  84909. }
  84910. function setMapForType( mapType, value ) {
  84911. if ( params[ mapType ] ) return; // Keep the first encountered texture
  84912. var texParams = scope.getTextureParams( value, params );
  84913. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  84914. map.repeat.copy( texParams.scale );
  84915. map.offset.copy( texParams.offset );
  84916. map.wrapS = scope.wrap;
  84917. map.wrapT = scope.wrap;
  84918. params[ mapType ] = map;
  84919. }
  84920. for ( var prop in mat ) {
  84921. var value = mat[ prop ];
  84922. var n;
  84923. if ( value === '' ) continue;
  84924. switch ( prop.toLowerCase() ) {
  84925. // Ns is material specular exponent
  84926. case 'kd':
  84927. // Diffuse color (color under white light) using RGB values
  84928. params.color = new Color().fromArray( value );
  84929. break;
  84930. case 'ks':
  84931. // Specular color (color when light is reflected from shiny surface) using RGB values
  84932. //params.specular = new Color().fromArray( value );
  84933. //console.log('specular',value)
  84934. break;
  84935. case 'ke':
  84936. // Emissive using RGB values
  84937. params.emissive = new Color().fromArray( value );
  84938. break;
  84939. case 'map_kd':
  84940. // Diffuse texture map
  84941. setMapForType( 'map', value );
  84942. break;
  84943. case 'map_ks':
  84944. // Specular map
  84945. setMapForType( 'specularMap', value );
  84946. break;
  84947. case 'map_ke':
  84948. // Emissive map
  84949. setMapForType( 'emissiveMap', value );
  84950. break;
  84951. case 'norm':
  84952. setMapForType( 'normalMap', value );
  84953. break;
  84954. case 'map_bump':
  84955. case 'bump':
  84956. // Bump texture map
  84957. setMapForType( 'bumpMap', value );
  84958. break;
  84959. case 'map_d':
  84960. // Alpha map
  84961. setMapForType( 'alphaMap', value );
  84962. params.transparent = true;
  84963. break;
  84964. case 'ns':
  84965. // The specular exponent (defines the focus of the specular highlight)
  84966. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  84967. //params.shininess = parseFloat( value );
  84968. //console.log('shininess',value)
  84969. break;
  84970. case 'd':
  84971. n = parseFloat( value );
  84972. if ( n < 1 ) {
  84973. params.opacity = n;
  84974. params.transparent = true;
  84975. }
  84976. break;
  84977. case 'tr':
  84978. n = parseFloat( value );
  84979. if ( this.options && this.options.invertTrProperty ) n = 1 - n;
  84980. if ( n > 0 ) {
  84981. params.opacity = 1 - n;
  84982. params.transparent = true;
  84983. }
  84984. break;
  84985. default:
  84986. break;
  84987. }
  84988. }
  84989. this.materials[ materialName ] = new MeshStandardMaterial( params );//MeshPhongMaterial( params );
  84990. return this.materials[ materialName ];
  84991. },
  84992. getTextureParams: function ( value, matParams ) {
  84993. var texParams = {
  84994. scale: new Vector2$1( 1, 1 ),
  84995. offset: new Vector2$1( 0, 0 )
  84996. };
  84997. var items = value.split( /\s+/ );
  84998. var pos;
  84999. pos = items.indexOf( '-bm' );
  85000. if ( pos >= 0 ) {
  85001. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  85002. items.splice( pos, 2 );
  85003. }
  85004. pos = items.indexOf( '-s' );
  85005. if ( pos >= 0 ) {
  85006. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  85007. items.splice( pos, 4 ); // we expect 3 parameters here!
  85008. }
  85009. pos = items.indexOf( '-o' );
  85010. if ( pos >= 0 ) {
  85011. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  85012. items.splice( pos, 4 ); // we expect 3 parameters here!
  85013. }
  85014. texParams.url = items.join( ' ' ).trim();
  85015. return texParams;
  85016. },
  85017. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  85018. var texture;
  85019. var manager = ( this.manager !== undefined ) ? this.manager : DefaultLoadingManager;
  85020. var loader = manager.getHandler( url );
  85021. if ( loader === null ) {
  85022. loader = new TextureLoader( manager );
  85023. }
  85024. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  85025. texture = loader.load( url, onLoad, onProgress, onError );
  85026. if ( mapping !== undefined ) texture.mapping = mapping;
  85027. return texture;
  85028. }
  85029. };
  85030. /**
  85031. * @author alteredq / http://alteredqualia.com/
  85032. */
  85033. let Pass = function () {
  85034. // if set to true, the pass is processed by the composer
  85035. this.enabled = true;
  85036. // if set to true, the pass indicates to swap read and write buffer after rendering
  85037. this.needsSwap = true;
  85038. // if set to true, the pass clears its buffer before rendering
  85039. this.clear = false;
  85040. // if set to true, the result of the pass is rendered to screen
  85041. this.renderToScreen = false;
  85042. };
  85043. Object.assign( Pass.prototype, {
  85044. setSize: function ( width, height ) {},
  85045. render: function ( renderer, writeBuffer, readBuffer, delta, maskActive ) {
  85046. console.error( 'THREE.Pass: .render() must be implemented in derived pass.' );
  85047. }
  85048. } );
  85049. let ShaderPass = function ( shader, textureID ) {
  85050. Pass.call( this );
  85051. this.textureID = ( textureID !== undefined ) ? textureID : "tDiffuse";
  85052. if ( shader instanceof ShaderMaterial ) {
  85053. this.uniforms = shader.uniforms;
  85054. this.material = shader;
  85055. } else if ( shader ) {
  85056. this.uniforms = UniformsUtils.clone( shader.uniforms );
  85057. this.material = new ShaderMaterial( {
  85058. defines: Object.assign( {}, shader.defines ),
  85059. uniforms: this.uniforms,
  85060. vertexShader: shader.vertexShader,
  85061. fragmentShader: shader.fragmentShader,
  85062. transparent:true,//add
  85063. } );
  85064. }
  85065. this.camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  85066. this.scene = new Scene();
  85067. this.quad = new Mesh( new PlaneBufferGeometry( 2, 2 ), null );
  85068. this.quad.frustumCulled = false; // Avoid getting clipped
  85069. this.scene.add( this.quad );
  85070. };
  85071. ShaderPass.prototype = Object.assign( Object.create( Pass.prototype ), {
  85072. constructor: ShaderPass,
  85073. render: function(scene,camera, renderer, writeBuffer, readBuffer, delta, maskActive ) {
  85074. let oldTarget = renderer.getRenderTarget();
  85075. /* if(this.readTarget){ //add
  85076. readBuffer = oldTarget
  85077. } */
  85078. if ( this.uniforms[ this.textureID ] ) {
  85079. this.uniforms[ this.textureID ].value = readBuffer.texture;
  85080. }
  85081. this.quad.material = this.material;
  85082. if ( this.renderToScreen ) {
  85083. renderer.render( this.scene, this.camera );
  85084. } else {
  85085. renderer.setRenderTarget(writeBuffer);
  85086. if(this.clear) renderer.clear();
  85087. renderer.render( this.scene, this.camera );
  85088. renderer.setRenderTarget(oldTarget);
  85089. }
  85090. }
  85091. } );
  85092. /**
  85093. * @author alteredq / http://alteredqualia.com/
  85094. *
  85095. * Full-screen textured quad shader
  85096. */
  85097. let CopyShader = {
  85098. uniforms: {
  85099. "tDiffuse": { value: null },
  85100. "opacity": { value: 1.0 }
  85101. },
  85102. vertexShader: [
  85103. "varying vec2 vUv;",
  85104. "void main() {",
  85105. "vUv = uv;",
  85106. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  85107. "}"
  85108. ].join( "\n" ),
  85109. fragmentShader: [
  85110. "uniform float opacity;",
  85111. "uniform sampler2D tDiffuse;",
  85112. "varying vec2 vUv;",
  85113. "void main() {",
  85114. "vec4 texel = texture2D( tDiffuse, vUv );", //如果开启premultipliedAlpha用这个,否则用注释的
  85115. "gl_FragColor = opacity * texel;",
  85116. //"gl_FragColor = texture2D( tDiffuse, vUv );",
  85117. //"gl_FragColor.a *= opacity;",
  85118. "}"
  85119. ].join( "\n" )
  85120. };
  85121. /**
  85122. *
  85123. * Supersample Anti-Aliasing Render Pass
  85124. *
  85125. * @author bhouston / http://clara.io/
  85126. *
  85127. * This manual approach to SSAA re-renders the scene ones for each sample with camera jitter and accumulates the results.
  85128. *
  85129. * References: https://en.wikipedia.org/wiki/Supersampling
  85130. *
  85131. */
  85132. //较为原始的一种抗锯齿 (超级采样抗锯齿)
  85133. let SSAARenderPass = function ( clearColor, clearAlpha ) {
  85134. Pass.call( this );
  85135. //this.scene //= scene;
  85136. //this.camera = camera;
  85137. this.sampleLevel = 4; // specified as n, where the number of samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16.
  85138. this.unbiased = true;
  85139. // as we need to clear the buffer in this pass, clearColor must be set to something, defaults to black.
  85140. this.clearColor = ( clearColor !== undefined ) ? clearColor : 0x000000;
  85141. this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 0;
  85142. this.renderUniforms = {
  85143. bgTex : {value:null},
  85144. outlineTex : {value:null},
  85145. opacity : {value:1},
  85146. };
  85147. this.renderMat = new ShaderMaterial({
  85148. uniforms: this.renderUniforms,
  85149. vertexShader: CopyShader.vertexShader,
  85150. /* fragmentShader: CopyShader.fragmentShader, */
  85151. fragmentShader: `
  85152. uniform sampler2D bgTex;
  85153. uniform sampler2D outlineTex;
  85154. uniform float opacity;
  85155. varying vec2 vUv;
  85156. void main() {
  85157. vec4 color1 = texture2D( bgTex, vUv );
  85158. vec4 color2 = texture2D( outlineTex, vUv );
  85159. gl_FragColor = opacity * mix(color1, color2, color2.a) ;
  85160. }
  85161. `,
  85162. premultipliedAlpha: true,
  85163. blending: AdditiveBlending,
  85164. depthTest: false,
  85165. depthWrite: false,
  85166. transparent: true
  85167. });
  85168. this.renderMat2 = new ShaderMaterial({
  85169. uniforms: UniformsUtils.clone(CopyShader.uniforms) ,
  85170. vertexShader: CopyShader.vertexShader,
  85171. fragmentShader:`uniform float opacity;
  85172. uniform sampler2D tDiffuse;
  85173. varying vec2 vUv;
  85174. void main() {
  85175. vec4 texel = texture2D( tDiffuse, vUv );
  85176. if(texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0){
  85177. discard;
  85178. }else{
  85179. gl_FragColor = opacity * texel;
  85180. }
  85181. }
  85182. ` ,
  85183. depthTest: false,
  85184. depthWrite: false,
  85185. transparent: true
  85186. });
  85187. ////////////////////
  85188. /* this.renderMat.blendSrc = THREE.OneFactor //即将写入缓冲区的颜色。
  85189. this.renderMat.blendDst = THREE.OneFactor //缓冲区已经存在的颜色
  85190. this.renderMat.blendEquation = THREE.AddEquation;
  85191. this.renderMat.blendEquationAlpha = THREE.AddEquation;
  85192. this.renderMat.blendDstAlpha = THREE.SrcAlphaFactor
  85193. this.renderMat.blendSrcAlpha = THREE.SrcAlphaFactor */
  85194. this.camera2 = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  85195. this.scene2 = new Scene();
  85196. this.quad2 = new Mesh( new PlaneBufferGeometry( 2, 2 ), this.renderMat/* this.copyMaterial */ );
  85197. this.quad2.frustumCulled = false; // Avoid getting clipped
  85198. this.scene2.add( this.quad2 );
  85199. this.copyPass = new ShaderPass( CopyShader );
  85200. this.copyPass.renderToScreen = true;
  85201. };
  85202. SSAARenderPass.prototype = Object.assign( Object.create( Pass.prototype ), {
  85203. constructor: SSAARenderPass,
  85204. dispose: function () {
  85205. if ( this.sampleRenderTarget ) {
  85206. this.sampleRenderTarget.dispose();
  85207. this.sampleRenderTarget = null;
  85208. }
  85209. },
  85210. setSize: function ( width, height ) {
  85211. if ( this.sampleRenderTarget ) this.sampleRenderTarget.setSize( width, height );
  85212. this.childPass && this.childPass.setSize(width, height);
  85213. },
  85214. addPass: function (pass){
  85215. this.childPass = pass;
  85216. },
  85217. render: function (scene, camera, viewports, renderer, writeBuffer, readBuffer, maskActive, renderFun ) {
  85218. if(this.useCopy ){
  85219. scene = this.copyPass.scene; camera = this.copyPass.camera;
  85220. }
  85221. if ( ! this.sampleRenderTarget ) {
  85222. this.sampleRenderTarget = new WebGLRenderTarget( readBuffer.width, readBuffer.height, { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat } );
  85223. this.sampleRenderTarget.texture.name = "SSAARenderPass.sample";
  85224. }
  85225. var jitterOffsets = SSAARenderPass.JitterVectors[ Math.max( 0, Math.min( this.sampleLevel, 5 ) ) ];
  85226. var autoClear = renderer.autoClear;
  85227. renderer.autoClear = false;
  85228. var oldClearColor = renderer.getClearColor(new Color).getHex();
  85229. var oldClearAlpha = renderer.getClearAlpha();
  85230. renderer.setClearColor( this.clearColor, this.clearAlpha );
  85231. var baseSampleWeight = 1.0 / jitterOffsets.length;
  85232. var roundingRange = 1 / 32;
  85233. //this.copyUniforms[ "tDiffuse" ].value = this.sampleRenderTarget.texture;
  85234. let oldTarget = renderer.getRenderTarget();
  85235. if(oldTarget){
  85236. if(oldTarget.scissorTest){
  85237. var width = oldTarget.scissor.w, height = oldTarget.scissor.z;
  85238. }else {
  85239. var width = oldTarget.width, height = oldTarget.height;
  85240. }
  85241. }else {
  85242. var width = readBuffer.width, height = readBuffer.height;
  85243. }
  85244. // render the scene multiple times, each slightly jitter offset from the last and accumulate the results.
  85245. let opa = 0;
  85246. for ( var i = 0; i < jitterOffsets.length; i ++ ) {
  85247. var jitterOffset = jitterOffsets[ i ];
  85248. if ( camera.setViewOffset ) {
  85249. camera.setViewOffset( width, height,
  85250. jitterOffset[ 0 ] * 0.0625 , jitterOffset[ 1 ] * 0.0625 , // 0.0625 = 1 / 16
  85251. width, height );
  85252. }
  85253. var sampleWeight = baseSampleWeight;
  85254. if ( this.unbiased ) {//更柔和
  85255. var uniformCenteredDistribution = ( - 0.5 + ( i + 0.5 ) / jitterOffsets.length );
  85256. sampleWeight += roundingRange * uniformCenteredDistribution;
  85257. }
  85258. renderer.setRenderTarget(this.sampleRenderTarget);
  85259. renderer.clear();
  85260. if(this.useCopy){
  85261. this.copyPass.render(scene,camera, renderer, writeBuffer, readBuffer );
  85262. }else {
  85263. if(renderFun){
  85264. renderFun({target : this.sampleRenderTarget});
  85265. }else {
  85266. renderer.render( scene, camera );
  85267. }
  85268. }
  85269. renderer.setRenderTarget(oldTarget);
  85270. //---------------------
  85271. //获取outline tex
  85272. let hasOutline = this.childPass && this.childPass.render(scene, camera, renderer, writeBuffer, readBuffer, null, renderFun );
  85273. //合成到该材质
  85274. this.renderUniforms[ "bgTex" ].value = this.sampleRenderTarget.texture;
  85275. this.renderUniforms[ "outlineTex" ].value = hasOutline ? readBuffer.texture : null;
  85276. this.renderUniforms[ "opacity" ].value = sampleWeight;
  85277. /* console.log('sampleWeight', sampleWeight)
  85278. opa += sampleWeight */
  85279. if(!this.renderToScreen){
  85280. renderer.setRenderTarget(writeBuffer);
  85281. }
  85282. if(i === 0 ){
  85283. renderer.setClearColor( 0x000000, 0 ); //叠加前颜色必须0
  85284. renderer.clear();
  85285. }
  85286. renderer.render( this.scene2, this.camera2); // , this.renderToScreen ? null : writeBuffer, ( i === 0 )
  85287. if(!this.renderToScreen){
  85288. renderer.setRenderTarget(oldTarget);
  85289. }
  85290. //if(i==2)break;
  85291. }
  85292. //console.log('sum:',opa)
  85293. if ( camera.clearViewOffset )camera.clearViewOffset();
  85294. //renderer.setRenderTarget(readBuffer)
  85295. //renderer.setClearColor( 0x000000, 0 );
  85296. //renderer.clear()
  85297. /* this.quad2.material = this.renderMat2
  85298. this.renderMat2.uniforms.tDiffuse.value = writeBuffer.texture;
  85299. renderer.render( this.scene2, this.camera2);
  85300. this.quad2.material = this.renderMat */
  85301. //renderer.setRenderTarget(oldTarget)
  85302. renderer.autoClear = autoClear;
  85303. renderer.setClearColor( oldClearColor, oldClearAlpha );
  85304. /* 试了好几次,测量线的透明度还是还原不了。 clearAlpha十分影响结果。
  85305. 因为绘制测量线需要背景透明。 或许可以先全部绘制完后,再 copyshader中 抗锯齿?
  85306. 另外会有黑边。
  85307. */
  85308. }
  85309. } );
  85310. // These jitter vectors are specified in integers because it is easier.
  85311. // I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5)
  85312. // before being used, thus these integers need to be scaled by 1/16.
  85313. //
  85314. // Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
  85315. SSAARenderPass.JitterVectors = [
  85316. [
  85317. [ 0, 0 ]
  85318. ],
  85319. [
  85320. [ 4, 4 ], [ - 4, - 4 ]
  85321. ],
  85322. [
  85323. [ - 2, - 6 ], [ 6, - 2 ], [ - 6, 2 ], [ 2, 6 ]
  85324. ],
  85325. [
  85326. [ 1, - 3 ], [ - 1, 3 ], [ 5, 1 ], [ - 3, - 5 ],
  85327. [ - 5, 5 ], [ - 7, - 1 ], [ 3, 7 ], [ 7, - 7 ]
  85328. ],
  85329. [
  85330. [ 1, 1 ], [ - 1, - 3 ], [ - 3, 2 ], [ 4, - 1 ],
  85331. [ - 5, - 2 ], [ 2, 5 ], [ 5, 3 ], [ 3, - 5 ],
  85332. [ - 2, 6 ], [ 0, - 7 ], [ - 4, - 6 ], [ - 6, 4 ],
  85333. [ - 8, 0 ], [ 7, - 4 ], [ 6, 7 ], [ - 7, - 8 ]
  85334. ],
  85335. [
  85336. [ - 4, - 7 ], [ - 7, - 5 ], [ - 3, - 5 ], [ - 5, - 4 ],
  85337. [ - 1, - 4 ], [ - 2, - 2 ], [ - 6, - 1 ], [ - 4, 0 ],
  85338. [ - 7, 1 ], [ - 1, 2 ], [ - 6, 3 ], [ - 3, 3 ],
  85339. [ - 7, 6 ], [ - 3, 6 ], [ - 5, 7 ], [ - 1, 7 ],
  85340. [ 5, - 7 ], [ 1, - 6 ], [ 6, - 5 ], [ 4, - 4 ],
  85341. [ 2, - 3 ], [ 7, - 2 ], [ 1, - 1 ], [ 4, - 1 ],
  85342. [ 2, 1 ], [ 6, 2 ], [ 0, 4 ], [ 4, 4 ],
  85343. [ 2, 5 ], [ 7, 5 ], [ 5, 6 ], [ 3, 7 ]
  85344. ]
  85345. ];
  85346. class MaskPass extends Pass {
  85347. constructor( scene, camera ) {
  85348. super();
  85349. this.scene = scene;
  85350. this.camera = camera;
  85351. this.clear = true;
  85352. this.needsSwap = false;
  85353. this.inverse = false;
  85354. }
  85355. render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
  85356. const context = renderer.getContext();
  85357. const state = renderer.state;
  85358. // don't update color or depth
  85359. state.buffers.color.setMask( false );
  85360. state.buffers.depth.setMask( false );
  85361. // lock buffers
  85362. state.buffers.color.setLocked( true );
  85363. state.buffers.depth.setLocked( true );
  85364. // set up stencil
  85365. let writeValue, clearValue;
  85366. if ( this.inverse ) {
  85367. writeValue = 0;
  85368. clearValue = 1;
  85369. } else {
  85370. writeValue = 1;
  85371. clearValue = 0;
  85372. }
  85373. state.buffers.stencil.setTest( true );
  85374. state.buffers.stencil.setOp( context.REPLACE, context.REPLACE, context.REPLACE );
  85375. state.buffers.stencil.setFunc( context.ALWAYS, writeValue, 0xffffffff );
  85376. state.buffers.stencil.setClear( clearValue );
  85377. state.buffers.stencil.setLocked( true );
  85378. // draw into the stencil buffer
  85379. renderer.setRenderTarget( readBuffer );
  85380. if ( this.clear ) renderer.clear();
  85381. renderer.render( this.scene, this.camera );
  85382. renderer.setRenderTarget( writeBuffer );
  85383. if ( this.clear ) renderer.clear();
  85384. renderer.render( this.scene, this.camera );
  85385. // unlock color and depth buffer for subsequent rendering
  85386. state.buffers.color.setLocked( false );
  85387. state.buffers.depth.setLocked( false );
  85388. // only render where stencil is set to 1
  85389. state.buffers.stencil.setLocked( false );
  85390. state.buffers.stencil.setFunc( context.EQUAL, 1, 0xffffffff ); // draw if == 1
  85391. state.buffers.stencil.setOp( context.KEEP, context.KEEP, context.KEEP );
  85392. state.buffers.stencil.setLocked( true );
  85393. }
  85394. }
  85395. class ClearMaskPass extends Pass {
  85396. constructor() {
  85397. super();
  85398. this.needsSwap = false;
  85399. }
  85400. render( renderer /*, writeBuffer, readBuffer, deltaTime, maskActive */ ) {
  85401. renderer.state.buffers.stencil.setLocked( false );
  85402. renderer.state.buffers.stencil.setTest( false );
  85403. }
  85404. }
  85405. /**
  85406. * @author alteredq / http://alteredqualia.com/
  85407. */
  85408. var EffectComposer = function ( renderer, renderTarget ) {
  85409. this.renderer = renderer;
  85410. if ( renderTarget === undefined ) {
  85411. var parameters = {
  85412. minFilter: LinearFilter,
  85413. magFilter: LinearFilter,
  85414. format: RGBAFormat,
  85415. stencilBuffer: false,
  85416. };
  85417. var size = renderer.getDrawingBufferSize(new Vector2$1);
  85418. renderTarget = new WebGLRenderTarget( size.width, size.height , parameters );
  85419. renderTarget.texture.name = 'EffectComposer.rt1';
  85420. }
  85421. this.renderTarget1 = renderTarget;
  85422. this.renderTarget2 = renderTarget.clone();
  85423. this.renderTarget2.texture.name = 'EffectComposer.rt2';
  85424. this.writeBuffer = this.renderTarget1;
  85425. this.readBuffer = this.renderTarget2;
  85426. this.passes = [];
  85427. // dependencies
  85428. /* if ( THREE.CopyShader === undefined ) {
  85429. console.error( 'THREE.EffectComposer relies on THREE.CopyShader' );
  85430. }
  85431. if ( THREE.ShaderPass === undefined ) {
  85432. console.error( 'THREE.EffectComposer relies on THREE.ShaderPass' );
  85433. } */
  85434. this.copyPass = new ShaderPass( CopyShader );
  85435. };
  85436. Object.assign( EffectComposer.prototype, {
  85437. swapBuffers: function () {
  85438. var tmp = this.readBuffer;
  85439. this.readBuffer = this.writeBuffer;
  85440. this.writeBuffer = tmp;
  85441. },
  85442. addPass: function ( pass ) {
  85443. this.passes.push( pass );
  85444. var size = this.renderer.getDrawingBufferSize(new Vector2$1);
  85445. pass.setSize( size.width, size.height );
  85446. },
  85447. removePass: function(pass){ //add
  85448. let index = this.passes.indexOf(pass);
  85449. index > -1 && this.passes.splice(index,1);
  85450. },
  85451. insertPass: function ( pass, index ) {
  85452. this.passes.splice( index, 0, pass );
  85453. },
  85454. render: function ( scene, camera, viewports, renderFun ) {
  85455. var maskActive = false;
  85456. let passes = this.passes.filter(e=>e.enabled);
  85457. var pass, i, il = passes.length;
  85458. if(this.readTarget){ //add 使用当前renderTarget中的像素
  85459. this.copyPass.render(scene, this.renderer, this.readBuffer, this.renderer.getRenderTarget() );
  85460. }
  85461. for ( i = 0; i < il; i ++ ) {
  85462. pass = passes[ i ];
  85463. //if(i == il-1)pass.renderToScreen = true//
  85464. pass.render( scene, camera, viewports, this.renderer, this.writeBuffer, this.readBuffer, maskActive, renderFun );
  85465. if ( pass.needsSwap ) {
  85466. if ( maskActive ) {
  85467. var context = this.renderer.context;
  85468. context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff );
  85469. this.copyPass.render( this.renderer, this.writeBuffer, this.readBuffer );// delta
  85470. context.stencilFunc( context.EQUAL, 1, 0xffffffff );
  85471. }
  85472. this.swapBuffers();
  85473. }
  85474. if ( MaskPass !== undefined ) {
  85475. if ( pass instanceof MaskPass ) {
  85476. maskActive = true;
  85477. } else if ( pass instanceof ClearMaskPass ) {
  85478. maskActive = false;
  85479. }
  85480. }
  85481. }
  85482. //add
  85483. if(!pass.renderToScreen){ //最后一个如果没有绘制到屏幕or target上
  85484. this.copyPass.renderToScreen = true;
  85485. this.copyPass.render(null,null, this.renderer, this.writeBuffer, this.readBuffer);
  85486. }
  85487. },
  85488. reset: function ( renderTarget ) {
  85489. if ( renderTarget === undefined ) {
  85490. var size = this.renderer.getDrawingBufferSize(new Vector2$1);
  85491. renderTarget = this.renderTarget1.clone();
  85492. renderTarget.setSize( size.width, size.height );
  85493. }
  85494. this.renderTarget1.dispose();
  85495. this.renderTarget2.dispose();
  85496. this.renderTarget1 = renderTarget;
  85497. this.renderTarget2 = renderTarget.clone();
  85498. this.writeBuffer = this.renderTarget1;
  85499. this.readBuffer = this.renderTarget2;
  85500. },
  85501. setSize: function ( width, height, scaleRatio ) {
  85502. scaleRatio = scaleRatio || 1;
  85503. this.renderTarget1.setSize( width * scaleRatio , height * scaleRatio );
  85504. this.renderTarget2.setSize( width * scaleRatio, height * scaleRatio );
  85505. for ( var i = 0; i < this.passes.length; i ++ ) {
  85506. this.passes[ i ].setSize( width * scaleRatio, height * scaleRatio );
  85507. }
  85508. }
  85509. } );
  85510. /**
  85511. * @author alteredq / http://alteredqualia.com/
  85512. */
  85513. class RenderPass extends Pass {
  85514. constructor( overrideMaterial, clearColor, clearAlpha ) {
  85515. super();
  85516. /* this.scene = scene;
  85517. this.camera = camera; */
  85518. this.overrideMaterial = overrideMaterial;
  85519. this.clearColor = clearColor;
  85520. this.clearAlpha = ( clearAlpha !== undefined ) ? clearAlpha : 0;
  85521. this.clear = true;
  85522. this.clearDepth = false;
  85523. this.needsSwap = false;
  85524. this._oldClearColor = new Color();
  85525. }
  85526. render(scene, camera, renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
  85527. const oldAutoClear = renderer.autoClear;
  85528. renderer.autoClear = false;
  85529. let oldClearAlpha, oldOverrideMaterial;
  85530. if ( this.overrideMaterial !== undefined ) {
  85531. oldOverrideMaterial = this.scene.overrideMaterial;
  85532. scene.overrideMaterial = this.overrideMaterial;
  85533. }
  85534. if ( this.clearColor ) {
  85535. renderer.getClearColor( this._oldClearColor );
  85536. oldClearAlpha = renderer.getClearAlpha();
  85537. renderer.setClearColor( this.clearColor, this.clearAlpha );
  85538. }
  85539. if ( this.clearDepth ) {
  85540. renderer.clearDepth();
  85541. }
  85542. let oldTarget = renderer.getRenderTarget();
  85543. if(!this.renderToScreen)renderer.setRenderTarget( readBuffer );
  85544. // TODO: Avoid using autoClear properties, see https://github.com/mrdoob/three.js/pull/15571#issuecomment-465669600
  85545. if ( this.clear ) renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  85546. renderer.render( scene, camera );
  85547. if(!this.renderToScreen)renderer.setRenderTarget( oldTarget );
  85548. if ( this.clearColor ) {
  85549. renderer.setClearColor( this._oldClearColor, oldClearAlpha );
  85550. }
  85551. if ( this.overrideMaterial !== undefined ) {
  85552. scene.overrideMaterial = oldOverrideMaterial;
  85553. }
  85554. renderer.autoClear = oldAutoClear;
  85555. }
  85556. }
  85557. /**
  85558. * NVIDIA FXAA by Timothy Lottes
  85559. * https://developer.download.nvidia.com/assets/gamedev/files/sdk/11/FXAA_WhitePaper.pdf
  85560. * - WebGL port by @supereggbert
  85561. * http://www.glge.org/demos/fxaa/
  85562. * Further improved by Daniel Sturk
  85563. */
  85564. const FXAAShader = {
  85565. uniforms: {
  85566. 'tDiffuse': { value: null },
  85567. 'resolution': { value: new Vector2$1( 1 / 1024, 1 / 512 ) }
  85568. },
  85569. vertexShader: /* glsl */`
  85570. varying vec2 vUv;
  85571. void main() {
  85572. vUv = uv;
  85573. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  85574. }`,
  85575. fragmentShader: `
  85576. precision highp float;
  85577. uniform sampler2D tDiffuse;
  85578. uniform vec2 resolution;
  85579. varying vec2 vUv;
  85580. // FXAA 3.11 implementation by NVIDIA, ported to WebGL by Agost Biro (biro@archilogic.com)
  85581. //----------------------------------------------------------------------------------
  85582. // File: es3-kepler\FXAA\assets\shaders/FXAA_DefaultES.frag
  85583. // SDK Version: v3.00
  85584. // Email: gameworks@nvidia.com
  85585. // Site: http://developer.nvidia.com/
  85586. //
  85587. // Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
  85588. //
  85589. // Redistribution and use in source and binary forms, with or without
  85590. // modification, are permitted provided that the following conditions
  85591. // are met:
  85592. // * Redistributions of source code must retain the above copyright
  85593. // notice, this list of conditions and the following disclaimer.
  85594. // * Redistributions in binary form must reproduce the above copyright
  85595. // notice, this list of conditions and the following disclaimer in the
  85596. // documentation and/or other materials provided with the distribution.
  85597. // * Neither the name of NVIDIA CORPORATION nor the names of its
  85598. // contributors may be used to endorse or promote products derived
  85599. // from this software without specific prior written permission.
  85600. //
  85601. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
  85602. // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  85603. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  85604. // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  85605. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  85606. // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  85607. // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  85608. // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  85609. // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  85610. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  85611. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  85612. //
  85613. //----------------------------------------------------------------------------------
  85614. #ifndef FXAA_DISCARD
  85615. //
  85616. // Only valid for PC OpenGL currently.
  85617. // Probably will not work when FXAA_GREEN_AS_LUMA = 1.
  85618. //
  85619. // 1 = Use discard on pixels which don't need AA.
  85620. // For APIs which enable concurrent TEX+ROP from same surface.
  85621. // 0 = Return unchanged color on pixels which don't need AA.
  85622. //
  85623. #define FXAA_DISCARD 0
  85624. #endif
  85625. /*--------------------------------------------------------------------------*/
  85626. #define FxaaTexTop(t, p) texture2D(t, p, -100.0)
  85627. #define FxaaTexOff(t, p, o, r) texture2D(t, p + (o * r), -100.0)
  85628. /*--------------------------------------------------------------------------*/
  85629. #define NUM_SAMPLES 5
  85630. // assumes colors have premultipliedAlpha, so that the calculated color contrast is scaled by alpha
  85631. float contrast( vec4 a, vec4 b ) {
  85632. vec4 diff = abs( a - b );
  85633. return max( max( max( diff.r, diff.g ), diff.b ), diff.a );
  85634. }
  85635. /*============================================================================
  85636. FXAA3 QUALITY - PC
  85637. ============================================================================*/
  85638. /*--------------------------------------------------------------------------*/
  85639. vec4 FxaaPixelShader(
  85640. vec2 posM,
  85641. sampler2D tex,
  85642. vec2 fxaaQualityRcpFrame,
  85643. float fxaaQualityEdgeThreshold,
  85644. float fxaaQualityinvEdgeThreshold
  85645. ) {
  85646. vec4 rgbaM = FxaaTexTop(tex, posM);
  85647. vec4 rgbaS = FxaaTexOff(tex, posM, vec2( 0.0, 1.0), fxaaQualityRcpFrame.xy);
  85648. vec4 rgbaE = FxaaTexOff(tex, posM, vec2( 1.0, 0.0), fxaaQualityRcpFrame.xy);
  85649. vec4 rgbaN = FxaaTexOff(tex, posM, vec2( 0.0,-1.0), fxaaQualityRcpFrame.xy);
  85650. vec4 rgbaW = FxaaTexOff(tex, posM, vec2(-1.0, 0.0), fxaaQualityRcpFrame.xy);
  85651. // . S .
  85652. // W M E
  85653. // . N .
  85654. bool earlyExit = max( max( max(
  85655. contrast( rgbaM, rgbaN ),
  85656. contrast( rgbaM, rgbaS ) ),
  85657. contrast( rgbaM, rgbaE ) ),
  85658. contrast( rgbaM, rgbaW ) )
  85659. < fxaaQualityEdgeThreshold;
  85660. // . 0 .
  85661. // 0 0 0
  85662. // . 0 .
  85663. #if (FXAA_DISCARD == 1)
  85664. if(earlyExit) FxaaDiscard;
  85665. #else
  85666. if(earlyExit) return rgbaM;
  85667. #endif
  85668. float contrastN = contrast( rgbaM, rgbaN );
  85669. float contrastS = contrast( rgbaM, rgbaS );
  85670. float contrastE = contrast( rgbaM, rgbaE );
  85671. float contrastW = contrast( rgbaM, rgbaW );
  85672. float relativeVContrast = ( contrastN + contrastS ) - ( contrastE + contrastW );
  85673. relativeVContrast *= fxaaQualityinvEdgeThreshold;
  85674. bool horzSpan = relativeVContrast > 0.;
  85675. // . 1 .
  85676. // 0 0 0
  85677. // . 1 .
  85678. // 45 deg edge detection and corners of objects, aka V/H contrast is too similar
  85679. if( abs( relativeVContrast ) < .3 ) {
  85680. // locate the edge
  85681. vec2 dirToEdge;
  85682. dirToEdge.x = contrastE > contrastW ? 1. : -1.;
  85683. dirToEdge.y = contrastS > contrastN ? 1. : -1.;
  85684. // . 2 . . 1 .
  85685. // 1 0 2 ~= 0 0 1
  85686. // . 1 . . 0 .
  85687. // tap 2 pixels and see which ones are "outside" the edge, to
  85688. // determine if the edge is vertical or horizontal
  85689. vec4 rgbaAlongH = FxaaTexOff(tex, posM, vec2( dirToEdge.x, -dirToEdge.y ), fxaaQualityRcpFrame.xy);
  85690. float matchAlongH = contrast( rgbaM, rgbaAlongH );
  85691. // . 1 .
  85692. // 0 0 1
  85693. // . 0 H
  85694. vec4 rgbaAlongV = FxaaTexOff(tex, posM, vec2( -dirToEdge.x, dirToEdge.y ), fxaaQualityRcpFrame.xy);
  85695. float matchAlongV = contrast( rgbaM, rgbaAlongV );
  85696. // V 1 .
  85697. // 0 0 1
  85698. // . 0 .
  85699. relativeVContrast = matchAlongV - matchAlongH;
  85700. relativeVContrast *= fxaaQualityinvEdgeThreshold;
  85701. if( abs( relativeVContrast ) < .3 ) { // 45 deg edge
  85702. // 1 1 .
  85703. // 0 0 1
  85704. // . 0 1
  85705. // do a simple blur
  85706. return mix(
  85707. rgbaM,
  85708. (rgbaN + rgbaS + rgbaE + rgbaW) * .25,
  85709. .4
  85710. );
  85711. }
  85712. horzSpan = relativeVContrast > 0.;
  85713. }
  85714. if(!horzSpan) rgbaN = rgbaW;
  85715. if(!horzSpan) rgbaS = rgbaE;
  85716. // . 0 . 1
  85717. // 1 0 1 -> 0
  85718. // . 0 . 1
  85719. bool pairN = contrast( rgbaM, rgbaN ) > contrast( rgbaM, rgbaS );
  85720. if(!pairN) rgbaN = rgbaS;
  85721. vec2 offNP;
  85722. offNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x;
  85723. offNP.y = ( horzSpan) ? 0.0 : fxaaQualityRcpFrame.y;
  85724. bool doneN = false;
  85725. bool doneP = false;
  85726. float nDist = 0.;
  85727. float pDist = 0.;
  85728. vec2 posN = posM;
  85729. vec2 posP = posM;
  85730. int iterationsUsed = 0;
  85731. int iterationsUsedN = 0;
  85732. int iterationsUsedP = 0;
  85733. for( int i = 0; i < NUM_SAMPLES; i++ ) {
  85734. iterationsUsed = i;
  85735. float increment = float(i + 1);
  85736. if(!doneN) {
  85737. nDist += increment;
  85738. posN = posM + offNP * nDist;
  85739. vec4 rgbaEndN = FxaaTexTop(tex, posN.xy);
  85740. doneN = contrast( rgbaEndN, rgbaM ) > contrast( rgbaEndN, rgbaN );
  85741. iterationsUsedN = i;
  85742. }
  85743. if(!doneP) {
  85744. pDist += increment;
  85745. posP = posM - offNP * pDist;
  85746. vec4 rgbaEndP = FxaaTexTop(tex, posP.xy);
  85747. doneP = contrast( rgbaEndP, rgbaM ) > contrast( rgbaEndP, rgbaN );
  85748. iterationsUsedP = i;
  85749. }
  85750. if(doneN || doneP) break;
  85751. }
  85752. if ( !doneP && !doneN ) return rgbaM; // failed to find end of edge
  85753. float dist = min(
  85754. doneN ? float( iterationsUsedN ) / float( NUM_SAMPLES - 1 ) : 1.,
  85755. doneP ? float( iterationsUsedP ) / float( NUM_SAMPLES - 1 ) : 1.
  85756. );
  85757. // hacky way of reduces blurriness of mostly diagonal edges
  85758. // but reduces AA quality
  85759. dist = pow(dist, .5);
  85760. dist = 1. - dist;
  85761. return mix(
  85762. rgbaM,
  85763. rgbaN,
  85764. dist * .5
  85765. );
  85766. }
  85767. void main() {
  85768. const float edgeDetectionQuality = .05 ; //越高,越保留细节;越低,越平滑 但模糊
  85769. const float invEdgeDetectionQuality = 1. / edgeDetectionQuality;
  85770. gl_FragColor = FxaaPixelShader(
  85771. vUv,
  85772. tDiffuse,
  85773. resolution,
  85774. edgeDetectionQuality, // [0,1] contrast needed, otherwise early discard
  85775. invEdgeDetectionQuality
  85776. );
  85777. }
  85778. `
  85779. };
  85780. /**
  85781. * @author spidersharma / http://eduperiment.com/
  85782. */
  85783. let OutlinePass = function ( selectedObjects ) {
  85784. /* scene = scene;
  85785. camera = camera; */
  85786. this.selectedObjects = selectedObjects !== undefined ? selectedObjects : [];
  85787. this.visibleEdgeColor = new Color( 1, 1, 1 );
  85788. this.hiddenEdgeColor = new Color( 0.1, 0.04, 0.02 );
  85789. this.edgeGlow = 0.0;
  85790. this.usePatternTexture = false;
  85791. //this.edgeThickness = 1.0;
  85792. this.edgeStrength = 50;
  85793. this.downSampleRatio = 1;//2; // 抗锯齿 值越低renderTarget size越大,抗锯齿越强,线条可越细(或许可以把模糊化去掉?)
  85794. this.pulsePeriod = 0;
  85795. Pass.call( this );
  85796. this.resolution = new Vector2$1( 256, 256 );
  85797. var pars = { minFilter: LinearFilter, magFilter: LinearFilter, format: RGBAFormat };
  85798. var resx = Math.round( this.resolution.x / this.downSampleRatio );
  85799. var resy = Math.round( this.resolution.y / this.downSampleRatio );
  85800. //this.maskBufferMaterial = new THREE.MeshBasicMaterial( { color: 0xffffff } );
  85801. //this.maskBufferMaterial.side = THREE.DoubleSide;
  85802. this.renderTargetMaskBuffer = new WebGLRenderTarget( this.resolution.x, this.resolution.y, pars );
  85803. this.renderTargetMaskBuffer.texture.name = "OutlinePass.mask";
  85804. this.renderTargetMaskBuffer.texture.generateMipmaps = false;
  85805. this.depthMaterial = new MeshDepthMaterial();
  85806. this.depthMaterial.side = DoubleSide;
  85807. this.depthMaterial.depthPacking = RGBADepthPacking;
  85808. this.depthMaterial.blending = NoBlending;
  85809. this.prepareMaskMaterial = this.getPrepareMaskMaterial();
  85810. this.prepareMaskMaterial.side = DoubleSide;
  85811. //this.replaceDepthToViewZ( viewer.mainViewport.camera /* camera */ );
  85812. this.renderTargetDepthBuffer = new WebGLRenderTarget( this.resolution.x, this.resolution.y, pars );
  85813. this.renderTargetDepthBuffer.texture.name = "OutlinePass.depth";
  85814. this.renderTargetDepthBuffer.texture.generateMipmaps = false;
  85815. /* this.renderTargetMaskDownSampleBuffer = new THREE.WebGLRenderTarget( resx, resy, pars );
  85816. this.renderTargetMaskDownSampleBuffer.texture.name = "OutlinePass.depthDownSample";
  85817. this.renderTargetMaskDownSampleBuffer.texture.generateMipmaps = false;
  85818. this.renderTargetBlurBuffer1 = new THREE.WebGLRenderTarget( resx, resy, pars );
  85819. this.renderTargetBlurBuffer1.texture.name = "OutlinePass.blur1";
  85820. this.renderTargetBlurBuffer1.texture.generateMipmaps = false;
  85821. this.renderTargetBlurBuffer2 = new THREE.WebGLRenderTarget( Math.round( resx / 2 ), Math.round( resy / 2 ), pars );
  85822. this.renderTargetBlurBuffer2.texture.name = "OutlinePass.blur2";
  85823. this.renderTargetBlurBuffer2.texture.generateMipmaps = false; */
  85824. this.edgeDetectionMaterial = this.getEdgeDetectionMaterial(this.edgeStrength);
  85825. this.renderTargetEdgeBuffer1 = new WebGLRenderTarget( resx, resy, pars );
  85826. this.renderTargetEdgeBuffer1.texture.name = "OutlinePass.edge1";
  85827. this.renderTargetEdgeBuffer1.texture.generateMipmaps = false;
  85828. /* this.renderTargetEdgeBuffer2 = new THREE.WebGLRenderTarget( Math.round( resx / 2 ), Math.round( resy / 2 ), pars );
  85829. this.renderTargetEdgeBuffer2.texture.name = "OutlinePass.edge2";
  85830. this.renderTargetEdgeBuffer2.texture.generateMipmaps = false;
  85831. var MAX_EDGE_THICKNESS = 4;
  85832. var MAX_EDGE_GLOW = 4;
  85833. this.separableBlurMaterial1 = this.getSeperableBlurMaterial( MAX_EDGE_THICKNESS );
  85834. this.separableBlurMaterial1.uniforms[ "texSize" ].value = new THREE.Vector2( resx, resy );
  85835. this.separableBlurMaterial1.uniforms[ "kernelRadius" ].value = 1;
  85836. this.separableBlurMaterial2 = this.getSeperableBlurMaterial( MAX_EDGE_GLOW );
  85837. this.separableBlurMaterial2.uniforms[ "texSize" ].value = new THREE.Vector2( Math.round( resx / 2 ), Math.round( resy / 2 ) );
  85838. this.separableBlurMaterial2.uniforms[ "kernelRadius" ].value = MAX_EDGE_GLOW;
  85839. */
  85840. // Overlay material
  85841. this.overlayMaterial = this.getOverlayMaterial();
  85842. // copy material
  85843. this.copyUniforms = UniformsUtils.clone( CopyShader.uniforms );
  85844. this.copyUniforms[ "opacity" ].value = 1.0;
  85845. this.materialCopy = new ShaderMaterial( {
  85846. uniforms: this.copyUniforms,
  85847. vertexShader: CopyShader.vertexShader,
  85848. fragmentShader: CopyShader.fragmentShader,
  85849. blending: NoBlending,
  85850. depthTest: false,
  85851. depthWrite: false,
  85852. transparent: true
  85853. } );
  85854. this.enabled = true;
  85855. this.needsSwap = false;
  85856. this.oldClearColor = new Color();
  85857. this.oldClearAlpha = 1;
  85858. this.camera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  85859. this.scene = new Scene();
  85860. this.quad = new Mesh( new PlaneBufferGeometry( 2, 2 ), null );
  85861. this.quad.frustumCulled = false; // Avoid getting clipped
  85862. this.scene.add( this.quad );
  85863. /* this.tempPulseColor1 = new THREE.Color();
  85864. this.tempPulseColor2 = new THREE.Color(); */
  85865. this.textureMatrix = new Matrix4();
  85866. };
  85867. OutlinePass.prototype = Object.assign( Object.create( Pass.prototype ), {
  85868. constructor: OutlinePass,
  85869. dispose: function () {
  85870. this.renderTargetMaskBuffer.dispose();
  85871. this.renderTargetEdgeBuffer1.dispose();
  85872. this.renderTargetDepthBuffer.dispose();
  85873. },
  85874. replaceDepthToViewZ( camera ) {
  85875. var type = camera.isPerspectiveCamera ? 'perspective' : 'orthographic';
  85876. if(type == this.lastCameraType )return
  85877. this.lastCameraType = type;
  85878. this.prepareMaskMaterial.fragmentShader = this.prepareMaskMaterial.fragmentShader.replace( /DEPTH_TO_VIEW_Z/g, type + 'DepthToViewZ' );
  85879. this.prepareMaskMaterial.needsUpdate = true;
  85880. },
  85881. setSize: function ( width, height ) {
  85882. this.renderTargetEdgeBuffer1.setSize( width, height );
  85883. this.renderTargetMaskBuffer.setSize( width, height );
  85884. this.resolution.set(width,height);
  85885. },
  85886. changeVisibilityOfSelectedObjects: function ( bVisible ) {
  85887. function gatherSelectedMeshesCallBack( object ) {
  85888. /* if ( object.isMesh ) { */
  85889. if ( object.isPointcloud || object.isMesh || object.isLine || object.isSprite ) {
  85890. /* if ( bVisible ) {
  85891. object.visible = object.userData.oldVisible;
  85892. delete object.userData.oldVisible;
  85893. } else {
  85894. object.userData.oldVisible = object.visible;
  85895. object.visible = bVisible;
  85896. } */
  85897. viewer.updateVisible(object, 'overlinePass', bVisible);
  85898. }
  85899. }
  85900. for ( var i = 0; i < this.selectedObjects.length; i ++ ) {
  85901. var selectedObject = this.selectedObjects[ i ];
  85902. selectedObject.traverse( gatherSelectedMeshesCallBack );
  85903. }
  85904. },
  85905. changeVisibilityOfNonSelectedObjects: function ( bVisible , scenes) {
  85906. var selectedMeshes = [];
  85907. function gatherSelectedMeshesCallBack( object ) {
  85908. //if ( object.isMesh ) selectedMeshes.push( object );
  85909. if ( object.isPointcloud || object.isMesh || object.isLine || object.isSprite ) {
  85910. selectedMeshes.push( object );
  85911. }
  85912. }
  85913. for ( var i = 0; i < this.selectedObjects.length; i ++ ) {
  85914. var selectedObject = this.selectedObjects[ i ];
  85915. selectedObject.traverse( gatherSelectedMeshesCallBack );
  85916. }
  85917. function VisibilityChangeCallBack( object ) {
  85918. if ( object.isPointcloud || object.isMesh || object.isLine || object.isSprite ) {
  85919. var bFound = false;
  85920. for ( var i = 0; i < selectedMeshes.length; i ++ ) {
  85921. var selectedObjectId = selectedMeshes[ i ].id;
  85922. if ( selectedObjectId === object.id ) {
  85923. bFound = true;
  85924. break;
  85925. }
  85926. }
  85927. if ( ! bFound ) {
  85928. var visibility = object.visible;
  85929. viewer.updateVisible(object, 'overlinePass', bVisible); //add
  85930. //但保不齐在设置为false后,渲染时又true了,所以在其他地方update时设置visible 得用updateVisible
  85931. if(!bVisible){
  85932. object.visible = false;
  85933. }else {
  85934. object.visible = !!object.bVisible;
  85935. }
  85936. object.bVisible = visibility;
  85937. //这两种updateVisible 和 visible 设置都不能去掉, 第一块是为了防止有的visible不是通过updateVisible设置的; 第二块是为了防止渲染时updateVisible又修改了visible为true, 另外渲染时
  85938. return {stopContinue:true} //for pointcloud
  85939. }
  85940. }
  85941. }
  85942. scenes.forEach(scene=>scene.traverse( VisibilityChangeCallBack ));
  85943. },
  85944. updateTextureMatrix: function (camera) {
  85945. this.textureMatrix.set( 0.5, 0.0, 0.0, 0.5,
  85946. 0.0, 0.5, 0.0, 0.5,
  85947. 0.0, 0.0, 0.5, 0.5,
  85948. 0.0, 0.0, 0.0, 1.0 );
  85949. this.textureMatrix.multiply( camera.projectionMatrix );
  85950. this.textureMatrix.multiply( camera.matrixWorldInverse );
  85951. },
  85952. render: function (scenes, camera, viewports, renderer, writeBuffer, readBuffer, maskActive, renderFun ) {
  85953. if(!(scenes instanceof Array))scenes = [scenes];
  85954. if ( this.selectedObjects.length > 0 ) {
  85955. let render2 = (target, dontRenderRtEDL=true)=>{
  85956. if(renderFun){
  85957. renderFun({target , dontRenderRtEDL});
  85958. }else {
  85959. renderer.setRenderTarget(target);
  85960. renderer.clear();
  85961. scenes.forEach(scene=>renderer.render( scene, camera));
  85962. }
  85963. };
  85964. viewports.forEach(e=> e.beforeRender = ()=>{
  85965. this.replaceDepthToViewZ( e.camera );
  85966. });
  85967. this.oldClearColor.copy( renderer.getClearColor(new Color) );
  85968. this.oldClearAlpha = renderer.getClearAlpha();
  85969. let oldAutoClear = renderer.autoClear;
  85970. let oldTarget = renderer.getRenderTarget();
  85971. renderer.autoClear = false;
  85972. if ( maskActive ) renderer.context.disable( renderer.context.STENCIL_TEST );
  85973. renderer.setClearColor( 0xffffff, 1 );
  85974. // Make selected objects invisible
  85975. this.changeVisibilityOfSelectedObjects( false );
  85976. scenes.forEach(scene=>{
  85977. scene.currentBackground = scene.background;
  85978. scene.background = null;
  85979. // 1. Draw Non Selected objects in the depth buffer
  85980. scene.overrideMaterial = this.depthMaterial;
  85981. });
  85982. render2(this.renderTargetDepthBuffer);
  85983. //renderer.setRenderTarget(this.renderTargetDepthBuffer)
  85984. //renderer.clear()
  85985. //renderer.render( scene, camera/* , this.renderTargetDepthBuffer, true */);
  85986. // Make selected objects visible
  85987. this.changeVisibilityOfSelectedObjects( true );
  85988. viewports.forEach(e=> e.beforeRender = ()=>{
  85989. // Update Texture Matrix for Depth compare
  85990. this.updateTextureMatrix(e.camera);
  85991. this.prepareMaskMaterial.uniforms[ "cameraNearFar" ].value = new Vector2$1( e.camera.near, e.camera.far );
  85992. });
  85993. // Make non selected objects invisible, and draw only the selected objects, by comparing the depth buffer of non selected objects
  85994. this.changeVisibilityOfNonSelectedObjects( false , scenes);
  85995. scenes.forEach(scene=>{
  85996. scene.overrideMaterial = this.prepareMaskMaterial;
  85997. });
  85998. this.prepareMaskMaterial.uniforms[ "depthTexture" ].value = this.renderTargetDepthBuffer.texture;
  85999. this.prepareMaskMaterial.uniforms[ "textureMatrix" ].value = this.textureMatrix;
  86000. //renderer.setRenderTarget(this.renderTargetMaskBuffer)
  86001. //renderer.clear()
  86002. //renderer.render( scene, camera/* , this.renderTargetMaskBuffer, true */ );
  86003. render2(this.renderTargetMaskBuffer);
  86004. viewports.forEach((e)=>{e.beforeRender = null;});
  86005. this.changeVisibilityOfNonSelectedObjects( true , scenes);
  86006. scenes.forEach(scene=>{
  86007. scene.overrideMaterial = null;
  86008. scene.background = scene.currentBackground;
  86009. });
  86010. // 3. Apply Edge Detection Pass
  86011. this.quad.material = this.edgeDetectionMaterial;
  86012. this.edgeDetectionMaterial.uniforms[ "maskTexture" ].value = this.renderTargetMaskBuffer.texture;//this.renderTargetMaskDownSampleBuffer.texture;
  86013. this.edgeDetectionMaterial.uniforms[ "texSize" ].value = new Vector2$1(this.resolution.x, this.resolution.y );//new THREE.Vector2( this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height );
  86014. //this.edgeDetectionMaterial.uniforms[ "texSize" ].value = new THREE.Vector2(this.renderTargetMaskBuffer.width, this.renderTargetMaskBuffer.height)//new THREE.Vector2( this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height );
  86015. this.edgeDetectionMaterial.uniforms[ "thickness" ].value = this.edgeStrength;
  86016. this.edgeDetectionMaterial.uniforms[ "visibleEdgeColor" ].value = this.visibleEdgeColor;//this.tempPulseColor1;
  86017. this.edgeDetectionMaterial.uniforms[ "hiddenEdgeColor" ].value = this.hiddenEdgeColor; //this.tempPulseColor2;
  86018. let buffer = readBuffer;
  86019. if ( this.renderToScreen ) {
  86020. this.quad.material.transparent = true;
  86021. buffer = null;
  86022. renderer.setClearColor( this.oldClearColor, this.oldClearAlpha );
  86023. render2(null,false);
  86024. //绘制到全屏
  86025. let renderSize = renderer.getSize(new Vector2$1()); //是client大小
  86026. renderer.setViewport(0, 0, renderSize.x, renderSize.y); //规定视口,影响图形变换(画布的使用范围)
  86027. renderer.setScissorTest( false );
  86028. }else {
  86029. renderer.setClearColor( 0x000000, 0 );
  86030. renderer.clear();
  86031. }
  86032. renderer.setRenderTarget(buffer/* this.renderTargetEdgeBuffer1 */);
  86033. renderer.render( this.scene, this.camera/* , this.renderTargetEdgeBuffer1, true */);
  86034. //这次删掉
  86035. /* // Blend it additively over the input texture
  86036. this.quad.material = this.overlayMaterial;
  86037. //this.overlayMaterial.uniforms[ "maskTexture" ].value = this.renderTargetMaskBuffer.texture;
  86038. this.overlayMaterial.uniforms[ "edgeTexture1" ].value = this.renderTargetEdgeBuffer1.texture;
  86039. //this.overlayMaterial.uniforms[ "edgeTexture2" ].value = this.renderTargetEdgeBuffer2.texture;
  86040. //this.overlayMaterial.uniforms[ "patternTexture" ].value = this.patternTexture;
  86041. this.overlayMaterial.uniforms[ "edgeStrength" ].value = this.edgeStrength;
  86042. //this.overlayMaterial.uniforms[ "edgeGlow" ].value = this.edgeGlow;
  86043. //this.overlayMaterial.uniforms[ "usePatternTexture" ].value = this.usePatternTexture;
  86044. if ( maskActive ) renderer.context.enable( renderer.context.STENCIL_TEST );
  86045. //renderer.render( this.scene, camera, readBuffer, false );
  86046. //改:清空readBuffer, 仅绘制出outline的部分
  86047. renderer.setClearColor( 0x000000, 0 );
  86048. renderer.setRenderTarget(readBuffer)
  86049. renderer.clear()
  86050. renderer.render( this.scene, this.camera );
  86051. */
  86052. renderer.setRenderTarget(oldTarget);
  86053. renderer.setClearColor( this.oldClearColor, this.oldClearAlpha );
  86054. renderer.autoClear = oldAutoClear;
  86055. return true
  86056. }
  86057. /* if ( this.renderToScreen ) {
  86058. this.quad.material = this.materialCopy;
  86059. this.copyUniforms[ "tDiffuse" ].value = readBuffer.texture;
  86060. renderer.render( this.scene , this.camera );
  86061. } */
  86062. },
  86063. getPrepareMaskMaterial: function () {
  86064. return new ShaderMaterial( {
  86065. uniforms: {
  86066. "depthTexture": { value: null },
  86067. "cameraNearFar": { value: new Vector2$1( 0.5, 0.5 ) },
  86068. "textureMatrix": { value: new Matrix4() }
  86069. },
  86070. vertexShader: [
  86071. 'varying vec4 projTexCoord;',
  86072. 'varying vec4 vPosition;',
  86073. 'uniform mat4 textureMatrix;',
  86074. 'void main() {',
  86075. ' vPosition = modelViewMatrix * vec4( position, 1.0 );',
  86076. ' vec4 worldPosition = modelMatrix * vec4( position, 1.0 );',
  86077. ' projTexCoord = textureMatrix * worldPosition;',
  86078. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  86079. '}'
  86080. ].join( '\n' ),
  86081. fragmentShader: [
  86082. '#include <packing>',
  86083. 'varying vec4 vPosition;',
  86084. 'varying vec4 projTexCoord;',
  86085. 'uniform sampler2D depthTexture;',
  86086. 'uniform vec2 cameraNearFar;',
  86087. 'void main() {',
  86088. ' float depth = unpackRGBAToDepth(texture2DProj( depthTexture, projTexCoord ));',
  86089. ' float viewZ = - DEPTH_TO_VIEW_Z( depth, cameraNearFar.x, cameraNearFar.y );',
  86090. ' float depthTest = (-vPosition.z > viewZ) ? 1.0 : 0.0;',
  86091. ' gl_FragColor = vec4(0.0, depthTest, 1.0, 1.0);',
  86092. '}'
  86093. ].join( '\n' )
  86094. } );
  86095. },
  86096. getEdgeDetectionMaterial: function (thickness) {
  86097. return new ShaderMaterial( {
  86098. uniforms: {
  86099. "thickness": { value: thickness },
  86100. "maskTexture": { value: null },
  86101. "texSize": { value: new Vector2$1( 10, 10 ) },
  86102. "visibleEdgeColor": { value: new Vector3( 1.0, 1.0, 1.0 ) },
  86103. "hiddenEdgeColor": { value: new Vector3( 1.0, 1.0, 1.0 ) },
  86104. },
  86105. vertexShader:
  86106. "varying vec2 vUv;\n\
  86107. void main() {\n\
  86108. vUv = uv;\n\
  86109. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
  86110. }",
  86111. /* fragmentShader:
  86112. "varying vec2 vUv;\
  86113. uniform sampler2D maskTexture;\
  86114. uniform vec2 texSize;\
  86115. uniform vec3 visibleEdgeColor;\
  86116. uniform vec3 hiddenEdgeColor;\
  86117. \
  86118. void main() {\n\
  86119. vec2 invSize = 1.0 / texSize;\
  86120. vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize);\
  86121. vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy);\
  86122. vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy);\
  86123. vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw);\
  86124. vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw);\
  86125. float diff1 = (c1.r - c2.r)*0.5;\
  86126. float diff2 = (c3.r - c4.r)*0.5;\
  86127. float d = length( vec2(diff1, diff2) );\
  86128. float a1 = min(c1.g, c2.g);\
  86129. float a2 = min(c3.g, c4.g);\
  86130. float visibilityFactor = min(a1, a2);\
  86131. vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor;\
  86132. gl_FragColor = vec4(edgeColor, 1.0) * vec4(d);\
  86133. }" */
  86134. fragmentShader:
  86135. "varying vec2 vUv;\
  86136. uniform sampler2D maskTexture;\
  86137. uniform float thickness;\
  86138. uniform vec2 texSize;\
  86139. uniform vec3 visibleEdgeColor;\
  86140. uniform vec3 hiddenEdgeColor;\
  86141. \
  86142. void main() {\n\
  86143. vec2 invSize = 1.0 / texSize;\
  86144. vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize);\
  86145. vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy);\
  86146. vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy);\
  86147. vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw);\
  86148. vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw);\
  86149. float diff1 = (c1.r - c2.r)*0.5;\
  86150. float diff2 = (c3.r - c4.r)*0.5;\
  86151. float d = length( vec2(diff1, diff2) ) * thickness;\
  86152. float a1 = min(c1.g, c2.g);\
  86153. float a2 = min(c3.g, c4.g);\
  86154. float visibilityFactor = min(a1, a2);\
  86155. vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor;\
  86156. gl_FragColor = vec4(edgeColor, 1.0) * vec4(d);\
  86157. }"
  86158. } );
  86159. },
  86160. getSeperableBlurMaterial: function ( maxRadius ) {
  86161. return new ShaderMaterial( {
  86162. defines: {
  86163. "MAX_RADIUS": maxRadius,
  86164. },
  86165. uniforms: {
  86166. "colorTexture": { value: null },
  86167. "texSize": { value: new Vector2$1( 0.5, 0.5 ) },
  86168. "direction": { value: new Vector2$1( 0.5, 0.5 ) },
  86169. "kernelRadius": { value: 1.0 }
  86170. },
  86171. vertexShader:
  86172. "varying vec2 vUv;\n\
  86173. void main() {\n\
  86174. vUv = uv;\n\
  86175. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
  86176. }",
  86177. fragmentShader:
  86178. "#include <common>\
  86179. varying vec2 vUv;\
  86180. uniform sampler2D colorTexture;\
  86181. uniform vec2 texSize;\
  86182. uniform vec2 direction;\
  86183. uniform float kernelRadius;\
  86184. \
  86185. float gaussianPdf(in float x, in float sigma) {\
  86186. return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma;\
  86187. }\
  86188. void main() {\
  86189. vec2 invSize = 1.0 / texSize;\
  86190. float weightSum = gaussianPdf(0.0, kernelRadius);\
  86191. vec3 diffuseSum = texture2D( colorTexture, vUv).rgb * weightSum;\
  86192. vec2 delta = direction * invSize * kernelRadius/float(MAX_RADIUS);\
  86193. vec2 uvOffset = delta;\
  86194. for( int i = 1; i <= MAX_RADIUS; i ++ ) {\
  86195. float w = gaussianPdf(uvOffset.x, kernelRadius);\
  86196. vec3 sample1 = texture2D( colorTexture, vUv + uvOffset).rgb;\
  86197. vec3 sample2 = texture2D( colorTexture, vUv - uvOffset).rgb;\
  86198. diffuseSum += ((sample1 + sample2) * w);\
  86199. weightSum += (2.0 * w);\
  86200. uvOffset += delta;\
  86201. }\
  86202. gl_FragColor = vec4(diffuseSum/weightSum, 1.0);\
  86203. }"
  86204. } );
  86205. },
  86206. getOverlayMaterial: function () {
  86207. return new ShaderMaterial( {
  86208. uniforms: {
  86209. "maskTexture": { value: null },
  86210. "edgeTexture1": { value: null },
  86211. "edgeTexture2": { value: null },
  86212. "patternTexture": { value: null },
  86213. "edgeStrength": { value: 1.0 },
  86214. "edgeGlow": { value: 1.0 },
  86215. "usePatternTexture": { value: 0.0 }
  86216. },
  86217. vertexShader:
  86218. "varying vec2 vUv;\n\
  86219. void main() {\n\
  86220. vUv = uv;\n\
  86221. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
  86222. }",
  86223. /* fragmentShader:
  86224. "varying vec2 vUv;\
  86225. uniform sampler2D maskTexture;\
  86226. uniform sampler2D edgeTexture1;\
  86227. uniform sampler2D edgeTexture2;\
  86228. uniform sampler2D patternTexture;\
  86229. uniform float edgeStrength;\
  86230. uniform float edgeGlow;\
  86231. uniform bool usePatternTexture;\
  86232. \
  86233. void main() {\
  86234. vec4 edgeValue1 = texture2D(edgeTexture1, vUv);\
  86235. vec4 edgeValue2 = texture2D(edgeTexture2, vUv);\
  86236. vec4 maskColor = texture2D(maskTexture, vUv);\
  86237. vec4 patternColor = texture2D(patternTexture, 6.0 * vUv);\
  86238. float visibilityFactor = 1.0 - maskColor.g > 0.0 ? 1.0 : 0.5;\
  86239. vec4 edgeValue = edgeValue1 + edgeValue2 * edgeGlow;\
  86240. vec4 finalColor = edgeStrength * maskColor.r * edgeValue;\ // 删除 * maskColor.r 也就是去掉遮罩,使模型部分也有outline
  86241. if(usePatternTexture)\
  86242. finalColor += + visibilityFactor * (1.0 - maskColor.r) * (1.0 - patternColor.r);\
  86243. gl_FragColor = finalColor;\
  86244. }", */
  86245. fragmentShader:
  86246. `varying vec2 vUv;
  86247. uniform sampler2D edgeTexture1;
  86248. uniform float edgeStrength;
  86249. void main() {
  86250. gl_FragColor = edgeStrength * texture2D(edgeTexture1, vUv);
  86251. }`,
  86252. blending: AdditiveBlending,
  86253. depthTest: false,
  86254. depthWrite: false,
  86255. transparent: true
  86256. } );
  86257. }
  86258. } );
  86259. OutlinePass.BlurDirectionX = new Vector2$1( 1.0, 0.0 );
  86260. OutlinePass.BlurDirectionY = new Vector2$1( 0.0, 1.0 );
  86261. class BasicMaterial extends ShaderMaterial{
  86262. constructor(o={}){
  86263. super( Object.assign({},{
  86264. uniforms:{
  86265. tDiffuse: { type: 't', value: o.map },
  86266. alpha : {type:'f', value : 1 }
  86267. },
  86268. vertexShader: Shaders['basicTextured.vs'],
  86269. fragmentShader: Shaders['basicTextured.fs']
  86270. },o));
  86271. }
  86272. set opacity(o){
  86273. this.uniforms && (this.uniforms.alpha.value = o);
  86274. }
  86275. get opacity(){
  86276. return this.uniforms.alpha.value
  86277. }
  86278. set map(o){
  86279. this.uniforms.tDiffuse.value = o;
  86280. }
  86281. get map(){
  86282. return this.uniforms.tDiffuse.value
  86283. }
  86284. }
  86285. const manager = new LoadingManager();
  86286. let loaders = {};
  86287. let mapArea;
  86288. let blockedByIntersectHistory = new Map();
  86289. class Viewer extends ViewerBase{
  86290. constructor(domElement, mapArea_, args = {}){
  86291. super(domElement, $.extend(args,{name:'mainViewer'}));
  86292. window.viewer = this;
  86293. if(Potree.settings.editType == "pano" || Potree.settings.editType == "merge"){
  86294. this.modules = {
  86295. Alignment,
  86296. SiteModel
  86297. };
  86298. Potree.settings.useDepthTex = false;
  86299. if(Potree.settings.editType == "pano" ){
  86300. this.modules.PanoEditor = PanoEditor$1;
  86301. }else if(Potree.settings.editType == "merge"){
  86302. this.modules.MergeEditor = MergeEditor;
  86303. this.modules.CamAniEditor = CamAniEditor;
  86304. }
  86305. }else {
  86306. this.modules = {
  86307. Clip,
  86308. Alignment,
  86309. SiteModel,
  86310. RouteGuider : new RouteGuider,
  86311. ParticleEditor,
  86312. CamAniEditor,
  86313. };
  86314. }
  86315. console.log('create viewer');
  86316. this.navigateMode = 'free'; // 'panorama'; 'free'自由模式是只显示点云或者未进入到漫游点,
  86317. this.isEdit = true;
  86318. this.waitQueue = [];
  86319. this.unitConvert = new UoMService();
  86320. mapArea = mapArea_;
  86321. this.visible = true;
  86322. this.fpVisiDatasets = [];
  86323. this.atDatasets = [];
  86324. this.objs = new Object3D;
  86325. //this.lastPos = new THREE.Vector3(Infinity,Infinity,Infinity)
  86326. //-------------
  86327. var supportExtFragDepth = !!Features.EXT_DEPTH.isSupported() ;//iphoneX居然不支持
  86328. //这意味着边缘增强和测量线遮挡失效
  86329. if(!supportExtFragDepth)console.error('ExtFragDepth unsupported! 边缘增强和测量线遮挡失效');
  86330. this.guiLoaded = false;
  86331. this.guiLoadTasks = [];
  86332. this.onVrListeners = [];
  86333. this.messages = [];
  86334. this.elMessages = $(`
  86335. <div id="message_listing"
  86336. style="position: absolute; z-index: 1000; left: 10px; bottom: 10px">
  86337. </div>`);
  86338. $(domElement).append(this.elMessages);
  86339. this.paused;
  86340. document.addEventListener('visibilitychange',(e)=>{
  86341. //console.log('visibilitychange', !document.hidden )
  86342. this.dispatchEvent({type:'pageVisible', v:!document.hidden} );
  86343. });
  86344. try{
  86345. if(!Potree.settings.isOfficial)
  86346. { // generate missing dom hierarchy
  86347. if ($(domElement).find('#potree_map').length === 0) {
  86348. let potreeMap = $(`
  86349. <div id="potree_map" class="mapBox" style="position: absolute; left: 50px; top: 50px; width: 400px; height: 400px; display: none">
  86350. <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;">
  86351. </div>
  86352. <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>
  86353. </div>
  86354. `);
  86355. $(domElement).append(potreeMap);
  86356. }
  86357. if ($(domElement).find('#potree_description').length === 0) {
  86358. let potreeDescription = $(`<div id="potree_description" class="potree_info_text"></div>`);
  86359. $(domElement).append(potreeDescription);
  86360. }
  86361. if ($(domElement).find('#potree_annotations').length === 0) {
  86362. let potreeAnnotationContainer = $(`
  86363. <div id="potree_annotation_container"
  86364. style="position: absolute; z-index: 100000; width: 100%; height: 100%; pointer-events: none;"></div>`);
  86365. $(domElement).append(potreeAnnotationContainer);
  86366. }
  86367. if ($(domElement).find('#potree_quick_buttons').length === 0) {
  86368. let potreeMap = $(`
  86369. <div id="potree_quick_buttons" class="quick_buttons_container" style="">
  86370. </div>
  86371. `);
  86372. $(domElement).append(potreeMap);
  86373. }
  86374. //add
  86375. {
  86376. if(!mapArea && Potree.settings.editType != 'merge'){
  86377. $(domElement).append($("<div id='potree_labels'></div>"));
  86378. mapArea = $("<div id='mapGaode'></div>");
  86379. $(domElement).append(mapArea);
  86380. mapArea = mapArea[0];
  86381. }
  86382. }
  86383. /* let domRoot = this.renderer.domElement.parentElement;
  86384. let elAttach = $("<input type='button' value='test'></input>");
  86385. elAttach.css({
  86386. position : "absolute",
  86387. right : '10%',
  86388. bottom: '20px',
  86389. zIndex: "10000",
  86390. fontSize:'1em', color:"black",
  86391. background:'rgba(255,255,255,0.8)',
  86392. })
  86393. let state = false
  86394. elAttach.on("click", () => {
  86395. window.buttonFunction && window.buttonFunction()
  86396. });
  86397. domRoot.appendChild(elAttach[0]); */
  86398. }
  86399. this.pointCloudLoadedCallback = args.onPointCloudLoaded || function () {};
  86400. // if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
  86401. // defaultSettings.navigation = "Orbit";
  86402. // }
  86403. this.server = null;
  86404. this.fov = 60;
  86405. this.isFlipYZ = false;
  86406. this.useDEMCollisions = false;
  86407. this.generateDEM = false;
  86408. this.minNodeSize = 30;
  86409. this.edlStrength = 1.0;
  86410. this.edlRadius = 1.4;
  86411. this.edlOpacity = 1.0;
  86412. this.useEDL = false;
  86413. this.description = "";
  86414. this.classifications = ClassificationScheme.DEFAULT;
  86415. this.moveSpeed = 10;
  86416. this.lengthUnit = LengthUnits.METER;
  86417. this.lengthUnitDisplay = LengthUnits.METER;
  86418. this.showBoundingBox = false;
  86419. this.showAnnotations = true;
  86420. this.freeze = false;
  86421. this.clipTask = ClipTask.HIGHLIGHT;
  86422. this.clipMethod = ClipMethod.INSIDE_ANY;
  86423. this.elevationGradientRepeat = ElevationGradientRepeat.CLAMP;
  86424. this.filterReturnNumberRange = [0, 7];
  86425. this.filterNumberOfReturnsRange = [0, 7];
  86426. this.filterGPSTimeRange = [-Infinity, Infinity];
  86427. this.filterPointSourceIDRange = [0, 65535];
  86428. this.potreeRenderer = null;
  86429. this.edlRenderer = null;
  86430. this.pRenderer = null;
  86431. this.scene = null;
  86432. this.sceneVR = null;
  86433. this.overlay = null;
  86434. this.overlayCamera = null;
  86435. this.inputHandler = null;
  86436. this.controls = null;
  86437. this.clippingTool = null;
  86438. this.transformationTool = null;
  86439. this.navigationCube = null;
  86440. this.compass = null;
  86441. this.skybox = null;
  86442. this.clock = new Clock();
  86443. this.background = null;
  86444. if(args.noDragAndDrop){
  86445. }else {
  86446. this.initDragAndDrop();
  86447. }
  86448. if(typeof Stats !== "undefined"){
  86449. this.stats = new Stats();
  86450. this.stats.showPanel( 0 ); // 0: fps, 1: ms, 2: mb, 3+: custom
  86451. document.body.appendChild( this.stats.dom );
  86452. }
  86453. {
  86454. let canvas = this.renderer.domElement;
  86455. canvas.addEventListener("webglcontextlost", (e) => {
  86456. console.log(e);
  86457. this.postMessage("WebGL context lost. \u2639");
  86458. let gl = this.renderer.getContext();
  86459. let error = gl.getError();
  86460. console.log(error);
  86461. this.dispatchEvent({type:'webglError', msg:'webglcontextlost'});
  86462. }, false);
  86463. }
  86464. {
  86465. this.overlay = new Scene();
  86466. this.overlayCamera = new OrthographicCamera(
  86467. 0, 1,
  86468. 1, 0,
  86469. -1000, 1000
  86470. );
  86471. }
  86472. this.pRenderer = new Renderer(this.renderer);
  86473. {
  86474. let near = 2.5;
  86475. let far = 10.0;
  86476. let fov = 90;
  86477. this.shadowTestCam = new PerspectiveCamera(90, 1, near, far);
  86478. this.shadowTestCam.position.set(3.50, -2.80, 8.561);
  86479. this.shadowTestCam.lookAt(new Vector3(0, 0, 4.87));
  86480. }
  86481. let scene = new Scene$1(this.renderer);
  86482. { // create VR scene
  86483. this.sceneVR = new Scene();
  86484. // let texture = new THREE.TextureLoader().load(`${Potree.resourcePath}/images/vr_controller_help.jpg`);
  86485. // let plane = new THREE.PlaneBufferGeometry(1, 1, 1, 1);
  86486. // let infoMaterial = new THREE.MeshBasicMaterial({map: texture});
  86487. // let infoNode = new THREE.Mesh(plane, infoMaterial);
  86488. // infoNode.position.set(-0.5, 1, 0);
  86489. // infoNode.scale.set(0.4, 0.3, 1);
  86490. // infoNode.lookAt(0, 1, 0)
  86491. // this.sceneVR.add(infoNode);
  86492. // window.infoNode = infoNode;
  86493. }
  86494. this.setScene(scene);
  86495. //add: for 截图时抗锯齿
  86496. {
  86497. this.composer = new EffectComposer( this.renderer );
  86498. this.ssaaRenderPass = new SSAARenderPass(0x000000, 0);
  86499. this.composer.addPass( this.ssaaRenderPass );
  86500. //this.ssaaRenderPass.useCopy = true
  86501. //this.ssaaRenderPass.renderToScreen = true;
  86502. //this.ssaaRenderPass.needsSwap = false
  86503. //见 https://threejs.org/examples/?q=AA#webgl_postprocessing_fxaa 效果和SSAA差不多,都对透明不太友好。
  86504. /* const renderPass = new RenderPass();
  86505. renderPass.clearColor = new THREE.Color( 0, 0, 0 );
  86506. renderPass.clearAlpha = 0;
  86507. this.composer.addPass( renderPass );
  86508. this.fxaaPass = new ShaderPass( FXAAShader );
  86509. this.composer.addPass( this.fxaaPass );
  86510. this.fxaaPass.setSize = function(width, height){
  86511. this.material.uniforms[ 'resolution' ].value.x = 1 / ( width );
  86512. this.material.uniforms[ 'resolution' ].value.y = 1 / ( height );
  86513. }
  86514. this.fxaaPass.renderToScreen = true; */
  86515. /* this.fxaaPass = new ShaderPass( FXAAShader );
  86516. //this.fxaaPass.readTarget = true //add
  86517. this.composer.addPass( this.fxaaPass );
  86518. this.composer.readTarget = true
  86519. this.fxaaPass.setSize = function(width, height){
  86520. this.material.uniforms[ 'resolution' ].value.x = 1 / ( width );
  86521. this.material.uniforms[ 'resolution' ].value.y = 1 / ( height );
  86522. }
  86523. this.fxaaPass.renderToScreen = true; */
  86524. //for 融合页面
  86525. /* let outlinePass = this.outlinePass = new OutlinePass( );
  86526. //composer.addPass( outlinePass );
  86527. outlinePass.edgeStrength = 10
  86528. outlinePass.edgeGlow = 0
  86529. outlinePass.visibleEdgeColor = new THREE.Color("#09a1b3")
  86530. outlinePass.hiddenEdgeColor = new THREE.Color("#09a1b3")
  86531. this.ssaaRenderPass.addPass(outlinePass)
  86532. */
  86533. let outlinePass = this.outlinePass = new OutlinePass( );
  86534. outlinePass.renderToScreen = true; //这样更流畅,不用ssaa了,缺点是outline有锯齿
  86535. outlinePass.enabled = false;
  86536. this.composer.addPass( outlinePass );
  86537. outlinePass.edgeStrength = 10;
  86538. outlinePass.edgeGlow = 0;
  86539. outlinePass.visibleEdgeColor = new Color("#09a1b3");
  86540. outlinePass.hiddenEdgeColor = new Color("#09a1b3");
  86541. }
  86542. {
  86543. this.mainViewport = new Viewport( this.scene.view, this.scene.cameraP, {
  86544. left:0, bottom:0, width:1, height: 1, name:'MainView'
  86545. });
  86546. this.viewports = [this.mainViewport];
  86547. this.compass = new Compass(this);
  86548. this.magnifier = new Magnifier(this);
  86549. this.reticule = new Reticule(this);
  86550. this.scene.scene.add(this.magnifier);
  86551. this.scene.scene.add(this.reticule);
  86552. if(Potree.settings.editType != "pano" && Potree.settings.editType != 'merge'){
  86553. this.mapViewer = new MapViewer(mapArea/* $('#mapGaode')[0] */);
  86554. }
  86555. this.inputHandler = new InputHandler(this, this.scene.scene);
  86556. //this.inputHandler.setScene(this.scene);
  86557. //this.inputHandler.addInputListener(this);//add
  86558. this.clippingTool = new ClippingTool(this);
  86559. this.transformationTool = new TransformationTool(this);
  86560. this.navigationCube = new NavigationCube(this);
  86561. this.navigationCube.visible = false;
  86562. this.createControls();
  86563. this.clippingTool.setScene(this.scene);
  86564. let onPointcloudAdded = (e) => {
  86565. if (this.scene.pointclouds.length === 1) {
  86566. let speed = e.pointcloud.boundingBox.getSize(new Vector3()).length();
  86567. speed = speed / 2000;
  86568. this.setMoveSpeed(speed);
  86569. }
  86570. };
  86571. let onVolumeRemoved = (e) => {
  86572. this.inputHandler.deselect(e.volume);
  86573. };
  86574. this.addEventListener('scene_changed', (e) => {
  86575. this.inputHandler.setScene(e.scene);
  86576. this.clippingTool.setScene(this.scene);
  86577. if(!e.scene.hasEventListener("pointcloud_added", onPointcloudAdded)){
  86578. e.scene.addEventListener("pointcloud_added", onPointcloudAdded);
  86579. }
  86580. if(!e.scene.hasEventListener("volume_removed", onPointcloudAdded)){
  86581. e.scene.addEventListener("volume_removed", onVolumeRemoved);
  86582. }
  86583. });
  86584. this.scene.addEventListener("volume_removed", onVolumeRemoved);
  86585. this.scene.addEventListener('pointcloud_added', onPointcloudAdded);
  86586. }
  86587. { // set defaults
  86588. this.setFOV(60);
  86589. this.setEDLEnabled(false);
  86590. this.setEDLRadius(1.4);
  86591. this.setEDLStrength(0.4);
  86592. this.setEDLOpacity(1.0);
  86593. this.setClipTask(ClipTask.HIGHLIGHT);
  86594. this.setClipMethod(ClipMethod.INSIDE_ANY);
  86595. this.setPointBudget(1*1000*1000);
  86596. this.setShowBoundingBox(false);
  86597. this.setFreeze(false);
  86598. this.setControls(this.fpControls/* orbitControls */);
  86599. this.setBackground( new Color(Potree.config.background),1 /* 'gradient' */ );
  86600. this.scaleFactor = 1;
  86601. this.loadSettingsFromURL();
  86602. }
  86603. // start rendering!
  86604. //if(args.useDefaultRenderLoop === undefined || args.useDefaultRenderLoop === true){
  86605. //requestAnimationFrame(this.loop.bind(this));
  86606. //}
  86607. this.renderer.setAnimationLoop(this.loop.bind(this));
  86608. this.loadGUI = this.loadGUI.bind(this);
  86609. this.annotationTool = new AnnotationTool(this);
  86610. this.measuringTool = new MeasuringTool(this);
  86611. this.profileTool = new ProfileTool(this);
  86612. this.volumeTool = new VolumeTool(this);
  86613. this.tagTool = new TagTool(this);
  86614. //-----------
  86615. CursorDeal.init(this, this.mapViewer ? [this, this.mapViewer] : [this]);//ADD
  86616. if(Potree.settings.editType == "pano"){
  86617. this.modules.PanoEditor.init();
  86618. }else if(Potree.settings.editType == "merge"){
  86619. this.modules.MergeEditor.init();
  86620. }else {
  86621. this.modules.SiteModel.init();
  86622. this.modules.ParticleEditor.init();
  86623. }
  86624. this.modules.Alignment.init();
  86625. this.images360 = new Images360(this);
  86626. this.scene.scene.add(this.objs);
  86627. loaders = {
  86628. objLoader : new OBJLoader( manager ),
  86629. mtlLoader : new MTLLoader( manager ),
  86630. glbLoader : new GLTFLoader(undefined, this.renderer, Potree.settings.libsUrl )
  86631. };
  86632. //add test
  86633. /* const environment = new RoomEnvironment();
  86634. const pmremGenerator = new THREE.PMREMGenerator( this.renderer );
  86635. this.scene.scene.environment = pmremGenerator.fromScene( environment ).texture;
  86636. */
  86637. //-----------
  86638. }catch(e){
  86639. this.onCrash(e);
  86640. }
  86641. //-----------------------add----------------------------------------------------
  86642. /* {
  86643. let ratio
  86644. this.addEventListener('resize',(e)=>{
  86645. if(ratio != e.deviceRatio){ //因为devicePixelRatio会影响到点云大小,所以改变时计算下点云大小
  86646. viewer.scene.pointclouds.forEach(p => {
  86647. p.changePointSize()
  86648. })
  86649. }
  86650. ratio = e.deviceRatio
  86651. })
  86652. } */
  86653. {
  86654. let pointDensity = '';
  86655. Object.defineProperty(Potree.settings , "pointDensity",{
  86656. get: function() {
  86657. return pointDensity
  86658. },
  86659. set: (density)=>{
  86660. if(density && density != pointDensity){
  86661. let pointBudget;
  86662. var config = Potree.config.pointDensity[density];
  86663. if(this.magnifier.visible){//放大镜打开时不要切换pointBudget,否则点云会闪烁。这时使用最高密度。
  86664. pointBudget = Potree.config.pointDensity['magnifier'].pointBudget;
  86665. }else {
  86666. pointBudget = config.pointBudget;
  86667. }
  86668. viewer.setPointBudget(pointBudget );
  86669. //Potree.maxPointLevel = config.maxLevel
  86670. pointDensity = density;
  86671. this.setPointLevels();
  86672. }
  86673. }
  86674. });
  86675. let UserPointDensity = '';
  86676. Object.defineProperty(Potree.settings , "UserPointDensity",{
  86677. get: function() {
  86678. return UserPointDensity
  86679. },
  86680. set: (density)=>{
  86681. if(UserPointDensity != density){
  86682. if(Potree.settings.displayMode == 'showPointCloud' && this.viewports.length != 4){//漫游模式和四屏时都有自己的pointDensity
  86683. Potree.settings.pointDensity = density;
  86684. }
  86685. UserPointDensity = density;
  86686. }
  86687. }
  86688. });
  86689. }
  86690. {
  86691. let cameraFar = Potree.settings.cameraFar;
  86692. Object.defineProperty(Potree.settings , "cameraFar",{
  86693. get: function() {
  86694. return cameraFar
  86695. },
  86696. set: (far)=>{
  86697. if(far != cameraFar){
  86698. if(Potree.settings.displayMode != 'showPanos'){
  86699. this.mainViewport.camera.far = far;
  86700. this.mainViewport.camera.updateProjectionMatrix();
  86701. }
  86702. cameraFar = far;
  86703. }
  86704. }
  86705. });
  86706. }
  86707. this.addEventListener('allLoaded', ()=>{
  86708. setTimeout(this.testPointcloudsMaxLevel.bind(this), 2000); //延迟一丢丢,等画面出现
  86709. });
  86710. if(Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge'){
  86711. this.addEventListener('switchFloorplanSelect',(e)=>{//进入平面图设置后 切换选中的数据集
  86712. this.selectedFloorplan = e.pointcloud; //绝对显示
  86713. this.updateFpVisiDatasets();
  86714. let pointclouds;
  86715. if(e.pointcloud){
  86716. pointclouds = [e.pointcloud];
  86717. }else if(this.fpVisiDatasets.length){
  86718. pointclouds = this.fpVisiDatasets;
  86719. }
  86720. pointclouds && this.mapViewer.fitToDatasets(pointclouds);
  86721. });
  86722. this.modules.SiteModel.bus.addEventListener('FloorChange',()=>{
  86723. this.updateFpVisiDatasets();
  86724. });
  86725. this.mapViewer.mapLayer.addEventListener('floorplanLoaded',()=>{
  86726. this.updateCadVisibles(this.fpVisiDatasets, true); //加载完成后重新更新下
  86727. });
  86728. /* this.modules.Clip.bus.addEventListener('updateSelectedDatasets',()=>{
  86729. this.updateFpVisiDatasets()
  86730. }) */
  86731. }
  86732. {
  86733. //更新所在数据集
  86734. this.addEventListener('camera_changed', e => {
  86735. if(e.changeInfo.positionChanged){
  86736. blockedByIntersectHistory.clear(); //清空
  86737. this.updateDatasetAt();
  86738. }
  86739. });
  86740. }
  86741. }
  86742. ifPointBlockedByIntersect(pos3d, object){//点是否被遮挡
  86743. let ifShelter;
  86744. let shelter = blockedByIntersectHistory.get(object || pos3d);
  86745. if(shelter){
  86746. ifShelter = shelter.ifShelter;
  86747. }else {
  86748. ifShelter = viewer.inputHandler.ifBlockedByIntersect(pos3d, 0.3, true);//由于热点都是使用点云得到的位置,所以判断遮挡时也用点云
  86749. blockedByIntersectHistory.set(object || pos3d, {ifShelter});
  86750. }
  86751. return ifShelter
  86752. }
  86753. updateDatasetAt(force){//更新所在数据集
  86754. let fun = ()=>{
  86755. let currPos = viewer.mainViewport.view.position;
  86756. //if(force || !currPos.equals(this.lastPos)){
  86757. //this.lastPos.copy(currPos)
  86758. var at = this.scene.pointclouds.filter(e=>e.ifContainsPoint(currPos));
  86759. if(Common.getDifferenceSet(at, this.atDatasets).length){
  86760. //console.log('atDatasets', at)
  86761. this.atDatasets = at;
  86762. if(Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge')this.updateFpVisiDatasets();
  86763. this.dispatchEvent({type:'pointcloudAtChange',pointclouds:at});
  86764. }
  86765. force = false;
  86766. return true
  86767. //}
  86768. };
  86769. if(force)fun();
  86770. else Common.intervalTool.isWaiting('atWhichDataset', fun , 500);
  86771. }
  86772. updatePanosVisibles(currentFloor){//显示当前楼层的所有panos
  86773. viewer.images360.panos.forEach(pano=>{
  86774. let visible = currentFloor && currentFloor.panos.includes(pano);
  86775. viewer.updateVisible(pano, 'buildingChange', visible, 2);
  86776. });
  86777. }
  86778. updateFpVisiDatasets(){
  86779. let Clip = this.modules.Clip;
  86780. let SiteModel = this.modules.SiteModel;
  86781. let Alignment = this.modules.Alignment;
  86782. var currentFloor = SiteModel.currentFloor;
  86783. /* if(Clip.editing){//下载页面已经改为和普通时一样,根据位置判断
  86784. this.updateCadVisibles(Clip.selectedDatasets)
  86785. }else */if(this.selectedFloorplan){//平面图设置中
  86786. let pointclouds = [this.selectedFloorplan];
  86787. this.updateCadVisibles(pointclouds);
  86788. }else if(SiteModel.editing || Alignment.editing){//只显示勾选的,也就是显示的点云的
  86789. let pointclouds = this.scene.pointclouds.filter(p => this.getObjVisiByReason(p,'datasetSelection') );
  86790. this.updateCadVisibles(pointclouds);
  86791. this.updatePanosVisibles(currentFloor/* , pointclouds */);
  86792. }else {
  86793. let pointclouds = currentFloor ? this.findPointcloudsAtFloor(currentFloor) : [];
  86794. if(pointclouds.length == 0){//如果当前不在任何楼层或楼层中无数据集,就用当前所在数据集
  86795. pointclouds = this.atDatasets;
  86796. }
  86797. this.updateCadVisibles(pointclouds);
  86798. this.updatePanosVisibles(currentFloor/* , pointclouds */);
  86799. }
  86800. }
  86801. findPointcloudsAtFloor(entity){//找当前楼层需要显示哪些数据集。
  86802. //数据集的belongToEntity 在这个entity内(否则会出现点击数据集飞过去平面图却不显示)。or 如果数据集有漫游点的话,需要包含>20%的漫游点。 (防止重叠体积很大但其实一个漫游点都不包含)
  86803. //重叠体积>50% 或 包含>50%的漫游点
  86804. const ratio1 = 0.2, ratio2 = 0.5, ratio3 = 0.95;
  86805. var lowScores = [];
  86806. var pointclouds = viewer.scene.pointclouds.filter(e=>{
  86807. let score = 0;
  86808. if(e.belongToEntity && (e.belongToEntity == entity || e.belongToEntity.buildParent == entity)){//条件1 若该数据集挂载到该楼层 或 该数据集挂载到的房间属于该楼层(这样能显示该层所有房间)
  86809. return true
  86810. }
  86811. if(e.panos.length){//条件2
  86812. var insidePanos = e.panos.filter(a=>entity.ifContainsPoint(a.position));
  86813. let panoCountRatio = insidePanos.length / e.panos.length;
  86814. if(panoCountRatio > ratio2)return true
  86815. if(panoCountRatio < ratio1){
  86816. score += panoCountRatio;//return false
  86817. }
  86818. }
  86819. //条件3
  86820. let volume = entity.intersectPointcloudVolume(e);
  86821. let volumeRatio = volume / entity.getVolume(true); //注:hole加入计算
  86822. if(volumeRatio > ratio3){ //ratio3要高一些,因为点云bounding可能很大,包含很多无点云的空间。即使整个数据集包含entity都不一定看起来在数据集中。(千万要防止两层楼都显示了)
  86823. return true
  86824. }else {
  86825. score += volumeRatio;
  86826. }
  86827. lowScores.push({score, pointcloud:e});
  86828. });
  86829. if(pointclouds.length == 0){//从低分项挑一个出来。
  86830. lowScores.sort((a,b)=>{return a.score - b.score});
  86831. if(lowScores[0].score > 0.4){
  86832. pointclouds = [lowScores[0].pointcloud];
  86833. }
  86834. }
  86835. return pointclouds
  86836. }
  86837. updateCadVisibles(visiClouds, force){
  86838. let oldVisi = this.fpVisiDatasets;
  86839. var visiClouds = this.fpVisiDatasets = visiClouds;
  86840. if(!force){
  86841. var difference = Common.getDifferenceSet(oldVisi , visiClouds);
  86842. if(difference.length == 0)return
  86843. }
  86844. //console.log('visiClouds',visiClouds.map(e=>e.name))
  86845. viewer.scene.pointclouds.forEach(pointcloud=>{
  86846. var floorplan = viewer.mapViewer.mapLayer.getFloorplan(pointcloud.dataset_id);
  86847. var visi = visiClouds.includes(pointcloud);
  86848. if(floorplan){
  86849. viewer.updateVisible(floorplan.objectGroup, 'buildingChange', visi);
  86850. }/* else if(!visi){
  86851. let changeVisi = (e)=>{
  86852. viewer.updateVisible(e.floorplan.objectGroup, 'buildingChange', this.fpVisiDatasets.includes(pointcloud))
  86853. viewer.mapViewer.mapLayer.removeEventListener('floorplanLoaded', changeVisi)
  86854. console.log('updateCadVisibles加载后更改显示',e)
  86855. }
  86856. viewer.mapViewer.mapLayer.addEventListener('floorplanLoaded', changeVisi)
  86857. } */
  86858. //已经添加了全局的 floorplanLoaded后会updateCadVisibles,这段就删了
  86859. });
  86860. viewer.mapViewer.mapLayer.needUpdate = true; //可能需要更新加载的level程度
  86861. viewer.mapViewer.needRender = true; //若上句不触发加载也要立即重新绘制
  86862. }
  86863. //促使点云加载出最高级别
  86864. testPointcloudsMaxLevel(){ //所有点云都无需testMaxNodeLevel 就停止
  86865. let camera_changed, count = 0;
  86866. let test = ()=>{
  86867. camera_changed = true;
  86868. Common.intervalTool.isWaiting('testPointcloudsMaxLevel', ()=>{
  86869. if(!camera_changed && count>20 )return //只有当camera_changed后才继续循环, 除了最开始几次需要连续加载下
  86870. camera_changed = false;
  86871. count ++;
  86872. //console.log('testPointcloudsMaxLevel中')
  86873. var success = true;
  86874. viewer.scene.pointclouds.forEach(e=>{
  86875. var wait = e.testMaxNodeLevel();
  86876. if(wait){
  86877. success = false;
  86878. }
  86879. });
  86880. if(!success)return true //没有全部加载完,继续循环
  86881. else {
  86882. this.removeEventListener('camera_changed',test);
  86883. console.log('testPointcloudsMaxLevel结束');
  86884. }
  86885. }, count<10 ? 150 : 500);
  86886. };
  86887. this.addEventListener('camera_changed',test);
  86888. test();
  86889. /* 检验:
  86890. viewer.scene.pointclouds.sort((a,b)=>a.nodeMaxLevelPredict.min - b.nodeMaxLevelPredict.min).forEach(e=>console.log(e.nodeMaxLevel, e.nodeMaxLevelPredict.min))
  86891. */
  86892. }
  86893. setPointLevels(){
  86894. this.scene.pointclouds.forEach(e=>{
  86895. e.setPointLevel();
  86896. });
  86897. }
  86898. onCrash(error){
  86899. $(this.renderArea).empty();
  86900. if ($(this.renderArea).find('#potree_failpage').length === 0) {
  86901. let elFailPage = $(`
  86902. <div id="#potree_failpage" class="potree_failpage">
  86903. <h1>Potree Encountered An Error </h1>
  86904. <p>
  86905. This may happen if your browser or graphics card is not supported.
  86906. <br>
  86907. We recommend to use
  86908. <a href="https://www.google.com/chrome/browser" target="_blank" style="color:initial">Chrome</a>
  86909. or
  86910. <a href="https://www.mozilla.org/" target="_blank">Firefox</a>.
  86911. </p>
  86912. <p>
  86913. Please also visit <a href="http://webglreport.com/" target="_blank">webglreport.com</a> and
  86914. check whether your system supports WebGL.
  86915. </p>
  86916. <p>
  86917. If you are already using one of the recommended browsers and WebGL is enabled,
  86918. consider filing an issue report at <a href="https://github.com/potree/potree/issues" target="_blank">github</a>,<br>
  86919. including your operating system, graphics card, browser and browser version, as well as the
  86920. error message below.<br>
  86921. Please do not report errors on unsupported browsers.
  86922. </p>
  86923. <pre id="potree_error_console" style="width: 100%; height: 100%"></pre>
  86924. </div>`);
  86925. let elErrorMessage = elFailPage.find('#potree_error_console');
  86926. elErrorMessage.html(error.stack);
  86927. $(this.renderArea).append(elFailPage);
  86928. }
  86929. throw error;
  86930. }
  86931. // ------------------------------------------------------------------------------------
  86932. // Viewer API
  86933. // ------------------------------------------------------------------------------------
  86934. setScene (scene) {
  86935. if (scene === this.scene) {
  86936. return;
  86937. }
  86938. let oldScene = this.scene;
  86939. this.scene = scene;
  86940. this.dispatchEvent({
  86941. type: 'scene_changed',
  86942. oldScene: oldScene,
  86943. scene: scene
  86944. });
  86945. { // Annotations
  86946. $('.annotation').detach();
  86947. // for(let annotation of this.scene.annotations){
  86948. // this.renderArea.appendChild(annotation.domElement[0]);
  86949. // }
  86950. this.scene.annotations.traverse(annotation => {
  86951. this.renderArea.appendChild(annotation.domElement[0]);
  86952. });
  86953. if (!this.onAnnotationAdded) {
  86954. this.onAnnotationAdded = e => {
  86955. // console.log("annotation added: " + e.annotation.title);
  86956. e.annotation.traverse(node => {
  86957. $("#potree_annotation_container").append(node.domElement);
  86958. //this.renderArea.appendChild(node.domElement[0]);
  86959. node.scene = this.scene;
  86960. });
  86961. };
  86962. }
  86963. if (oldScene) {
  86964. oldScene.annotations.removeEventListener('annotation_added', this.onAnnotationAdded);
  86965. }
  86966. this.scene.annotations.addEventListener('annotation_added', this.onAnnotationAdded);
  86967. }
  86968. };
  86969. setControls(controls/* , setSpeed */){
  86970. if (controls !== this.controls) {
  86971. if (this.controls) {
  86972. this.controls.setEnable(false);
  86973. //this.inputHandler.removeInputListener(this.controls);
  86974. this.controls.moveSpeed = this.moveSpeed; //记录 (因为orbit的radius很大,转为firstPerson时要缩小)
  86975. }
  86976. this.controls = controls;
  86977. controls.moveSpeed && this.setMoveSpeed(controls.moveSpeed); //add
  86978. this.controls.setEnable(true);
  86979. //this.inputHandler.addInputListener(this.controls);
  86980. }
  86981. }
  86982. getControls () {
  86983. if(this.renderer.xr.isPresenting){
  86984. return this.vrControls;
  86985. }else {
  86986. return this.controls;
  86987. }
  86988. }
  86989. getMinNodeSize () {
  86990. return this.minNodeSize;
  86991. };
  86992. setMinNodeSize (value) {
  86993. if (this.minNodeSize !== value) {
  86994. this.minNodeSize = value;
  86995. this.dispatchEvent({'type': 'minnodesize_changed', 'viewer': this});
  86996. }
  86997. };
  86998. getBackground () {
  86999. return this.background;
  87000. }
  87001. setBackground(bg){
  87002. if (this.background === bg) {
  87003. return;
  87004. }
  87005. if(bg === "skybox"){
  87006. this.skybox = Utils.loadSkybox(new URL(Potree.resourcePath + '/textures/skybox2/').href);
  87007. }
  87008. this.background = bg;
  87009. this.backgroundOpacity = 1;//add
  87010. this.dispatchEvent({'type': 'background_changed', 'viewer': this});
  87011. }
  87012. setDescription (value) {
  87013. this.description = value;
  87014. $('#potree_description').html(value);
  87015. //$('#potree_description').text(value);
  87016. }
  87017. getDescription(){
  87018. return this.description;
  87019. }
  87020. setShowBoundingBox (value) {
  87021. if (this.showBoundingBox !== value) {
  87022. this.showBoundingBox = value;
  87023. this.dispatchEvent({'type': 'show_boundingbox_changed', 'viewer': this});
  87024. }
  87025. };
  87026. getShowBoundingBox () {
  87027. return this.showBoundingBox;
  87028. };
  87029. setMoveSpeed (value) {
  87030. if (this.getMoveSpeed() !== value) {
  87031. this.mainViewport.setMoveSpeed(value);
  87032. this.dispatchEvent({'type': 'move_speed_changed', 'viewer': this, 'speed': value});
  87033. }
  87034. };
  87035. getMoveSpeed () {
  87036. return this.mainViewport.moveSpeed;
  87037. };
  87038. setWeightClassification (w) {
  87039. for (let i = 0; i < this.scene.pointclouds.length; i++) {
  87040. this.scene.pointclouds[i].material.weightClassification = w;
  87041. this.dispatchEvent({'type': 'attribute_weights_changed' + i, 'viewer': this});
  87042. }
  87043. };
  87044. setFreeze (value) {
  87045. value = Boolean(value);
  87046. if (this.freeze !== value) {
  87047. this.freeze = value;
  87048. this.dispatchEvent({'type': 'freeze_changed', 'viewer': this});
  87049. }
  87050. };
  87051. getFreeze () {
  87052. return this.freeze;
  87053. };
  87054. getClipTask(){
  87055. return this.clipTask;
  87056. }
  87057. getClipMethod(){
  87058. return this.clipMethod;
  87059. }
  87060. setClipTask(value){
  87061. if(this.clipTask !== value){
  87062. this.clipTask = value;
  87063. this.dispatchEvent({
  87064. type: "cliptask_changed",
  87065. viewer: this});
  87066. }
  87067. }
  87068. setClipMethod(value){
  87069. if(this.clipMethod !== value){
  87070. this.clipMethod = value;
  87071. this.dispatchEvent({
  87072. type: "clipmethod_changed",
  87073. viewer: this});
  87074. }
  87075. }
  87076. setElevationGradientRepeat(value){
  87077. if(this.elevationGradientRepeat !== value){
  87078. this.elevationGradientRepeat = value;
  87079. this.dispatchEvent({
  87080. type: "elevation_gradient_repeat_changed",
  87081. viewer: this});
  87082. }
  87083. }
  87084. setPointBudget (value) {
  87085. if (Potree.pointBudget !== value) {
  87086. Potree.pointBudget = parseInt(value);
  87087. this.dispatchEvent({'type': 'point_budget_changed', 'viewer': this});
  87088. }
  87089. };
  87090. getPointBudget () {
  87091. return Potree.pointBudget;
  87092. };
  87093. setShowAnnotations (value) {
  87094. if (this.showAnnotations !== value) {
  87095. this.showAnnotations = value;
  87096. this.dispatchEvent({'type': 'show_annotations_changed', 'viewer': this});
  87097. }
  87098. }
  87099. getShowAnnotations () {
  87100. return this.showAnnotations;
  87101. }
  87102. setDEMCollisionsEnabled(value){
  87103. if(this.useDEMCollisions !== value){
  87104. this.useDEMCollisions = value;
  87105. this.dispatchEvent({'type': 'use_demcollisions_changed', 'viewer': this});
  87106. };
  87107. };
  87108. getDEMCollisionsEnabled () {
  87109. return this.useDEMCollisions;
  87110. };
  87111. setEDLEnabled (value) {
  87112. value = Boolean(value) && Features.SHADER_EDL.isSupported();
  87113. if (this.useEDL !== value) {
  87114. this.useEDL = value;
  87115. this.dispatchEvent({'type': 'use_edl_changed', 'viewer': this});
  87116. }
  87117. };
  87118. getEDLEnabled () {
  87119. return this.useEDL;
  87120. };
  87121. setEDLRadius (value) {
  87122. if (this.edlRadius !== value) {
  87123. this.edlRadius = value;
  87124. this.dispatchEvent({'type': 'edl_radius_changed', 'viewer': this});
  87125. }
  87126. };
  87127. getEDLRadius () {
  87128. return this.edlRadius;
  87129. };
  87130. setEDLStrength (value) {
  87131. if (this.edlStrength !== value) {
  87132. this.edlStrength = value;
  87133. this.dispatchEvent({'type': 'edl_strength_changed', 'viewer': this});
  87134. }
  87135. };
  87136. getEDLStrength () {
  87137. return this.edlStrength;
  87138. };
  87139. setEDLOpacity (value) {
  87140. if (this.edlOpacity !== value) {
  87141. this.edlOpacity = value;
  87142. this.dispatchEvent({'type': 'edl_opacity_changed', 'viewer': this});
  87143. }
  87144. };
  87145. getEDLOpacity () {
  87146. return this.edlOpacity;
  87147. };
  87148. setFOV (value) {
  87149. if (this.fov !== value) {
  87150. let oldFov = this.fov;
  87151. this.fov = value;
  87152. this.scene.cameraP.fov = this.fov;
  87153. this.scene.cameraP.updateProjectionMatrix();
  87154. this.dispatchEvent({'type': 'fov_changed', 'viewer': this, oldFov, fov:this.fov});
  87155. }
  87156. };
  87157. getFOV () {
  87158. return this.fov;
  87159. };
  87160. disableAnnotations () {
  87161. this.scene.annotations.traverse(annotation => {
  87162. annotation.domElement.css('pointer-events', 'none');
  87163. // return annotation.visible;
  87164. });
  87165. };
  87166. enableAnnotations () {
  87167. this.scene.annotations.traverse(annotation => {
  87168. annotation.domElement.css('pointer-events', 'auto');
  87169. // return annotation.visible;
  87170. });
  87171. }
  87172. setClassifications(classifications){
  87173. this.classifications = classifications;
  87174. this.dispatchEvent({'type': 'classifications_changed', 'viewer': this});
  87175. }
  87176. setClassificationVisibility (key, value) {
  87177. if (!this.classifications[key]) {
  87178. this.classifications[key] = {visible: value, name: 'no name'};
  87179. this.dispatchEvent({'type': 'classification_visibility_changed', 'viewer': this});
  87180. } else if (this.classifications[key].visible !== value) {
  87181. this.classifications[key].visible = value;
  87182. this.dispatchEvent({'type': 'classification_visibility_changed', 'viewer': this});
  87183. }
  87184. }
  87185. toggleAllClassificationsVisibility(){
  87186. let numVisible = 0;
  87187. let numItems = 0;
  87188. for(const key of Object.keys(this.classifications)){
  87189. if(this.classifications[key].visible){
  87190. numVisible++;
  87191. }
  87192. numItems++;
  87193. }
  87194. let visible = true;
  87195. if(numVisible === numItems){
  87196. visible = false;
  87197. }
  87198. let somethingChanged = false;
  87199. for(const key of Object.keys(this.classifications)){
  87200. if(this.classifications[key].visible !== visible){
  87201. this.classifications[key].visible = visible;
  87202. somethingChanged = true;
  87203. }
  87204. }
  87205. if(somethingChanged){
  87206. this.dispatchEvent({'type': 'classification_visibility_changed', 'viewer': this});
  87207. }
  87208. }
  87209. setFilterReturnNumberRange(from, to){
  87210. this.filterReturnNumberRange = [from, to];
  87211. this.dispatchEvent({'type': 'filter_return_number_range_changed', 'viewer': this});
  87212. }
  87213. setFilterNumberOfReturnsRange(from, to){
  87214. this.filterNumberOfReturnsRange = [from, to];
  87215. this.dispatchEvent({'type': 'filter_number_of_returns_range_changed', 'viewer': this});
  87216. }
  87217. setFilterGPSTimeRange(from, to){
  87218. this.filterGPSTimeRange = [from, to];
  87219. this.dispatchEvent({'type': 'filter_gps_time_range_changed', 'viewer': this});
  87220. }
  87221. setFilterPointSourceIDRange(from, to){
  87222. this.filterPointSourceIDRange = [from, to];
  87223. this.dispatchEvent({'type': 'filter_point_source_id_range_changed', 'viewer': this});
  87224. }
  87225. setLengthUnit (value) {
  87226. switch (value) {
  87227. case 'm':
  87228. this.lengthUnit = LengthUnits.METER;
  87229. this.lengthUnitDisplay = LengthUnits.METER;
  87230. break;
  87231. case 'ft':
  87232. this.lengthUnit = LengthUnits.FEET;
  87233. this.lengthUnitDisplay = LengthUnits.FEET;
  87234. break;
  87235. case 'in':
  87236. this.lengthUnit = LengthUnits.INCH;
  87237. this.lengthUnitDisplay = LengthUnits.INCH;
  87238. break;
  87239. }
  87240. this.dispatchEvent({ 'type': 'length_unit_changed', 'viewer': this, value: value});
  87241. };
  87242. setLengthUnitAndDisplayUnit(lengthUnitValue, lengthUnitDisplayValue) {
  87243. switch (lengthUnitValue) {
  87244. case 'm':
  87245. this.lengthUnit = LengthUnits.METER;
  87246. break;
  87247. case 'ft':
  87248. this.lengthUnit = LengthUnits.FEET;
  87249. break;
  87250. case 'in':
  87251. this.lengthUnit = LengthUnits.INCH;
  87252. break;
  87253. }
  87254. switch (lengthUnitDisplayValue) {
  87255. case 'm':
  87256. this.lengthUnitDisplay = LengthUnits.METER;
  87257. break;
  87258. case 'ft':
  87259. this.lengthUnitDisplay = LengthUnits.FEET;
  87260. break;
  87261. case 'in':
  87262. this.lengthUnitDisplay = LengthUnits.INCH;
  87263. break;
  87264. }
  87265. this.dispatchEvent({ 'type': 'length_unit_changed', 'viewer': this, value: lengthUnitValue });
  87266. };
  87267. zoomTo(node, factor, animationDuration = 0){
  87268. let view = this.scene.view;
  87269. let camera = this.scene.cameraP.clone();
  87270. camera.rotation.copy(this.scene.cameraP.rotation);
  87271. camera.rotation.order = "ZXY";
  87272. camera.rotation.x = Math.PI / 2 + view.pitch;
  87273. camera.rotation.z = view.yaw;
  87274. camera.updateMatrix();
  87275. camera.updateMatrixWorld();
  87276. camera.zoomTo(node, factor);
  87277. let bs;
  87278. if (node.boundingSphere) {
  87279. bs = node.boundingSphere;
  87280. } else if (node.geometry && node.geometry.boundingSphere) {
  87281. bs = node.geometry.boundingSphere;
  87282. } else {
  87283. bs = node.boundingBox.getBoundingSphere(new Sphere());
  87284. }
  87285. bs = bs.clone().applyMatrix4(node.matrixWorld);
  87286. let startPosition = view.position.clone();
  87287. let endPosition = camera.position.clone();
  87288. let startTarget = view.getPivot();
  87289. let endTarget = bs.center;
  87290. let startRadius = view.radius;
  87291. let endRadius = endPosition.distanceTo(endTarget);
  87292. let easing = TWEEN.Easing.Quartic.Out;
  87293. { // animate camera position
  87294. let pos = startPosition.clone();
  87295. let tween = new TWEEN.Tween(pos).to(endPosition, animationDuration);
  87296. tween.easing(easing);
  87297. tween.onUpdate(() => {
  87298. view.position.copy(pos);
  87299. });
  87300. tween.start();
  87301. }
  87302. { // animate camera target
  87303. let target = startTarget.clone();
  87304. let tween = new TWEEN.Tween(target).to(endTarget, animationDuration);
  87305. tween.easing(easing);
  87306. tween.onUpdate(() => {
  87307. view.lookAt(target);
  87308. });
  87309. tween.onComplete(() => {
  87310. view.lookAt(target);
  87311. this.dispatchEvent({type: 'focusing_finished', target: this});
  87312. });
  87313. this.dispatchEvent({type: 'focusing_started', target: this});
  87314. tween.start();
  87315. }
  87316. };
  87317. moveToGpsTimeVicinity(time){
  87318. const result = Potree.Utils.findClosestGpsTime(time, viewer);
  87319. const box = result.node.pointcloud.deepestNodeAt(result.position).getBoundingBox();
  87320. const diameter = box.min.distanceTo(box.max);
  87321. const camera = this.scene.getActiveCamera();
  87322. const offset = camera.getWorldDirection(new Vector3()).multiplyScalar(diameter);
  87323. const newCamPos = result.position.clone().sub(offset);
  87324. this.scene.view.position.copy(newCamPos);
  87325. this.scene.view.lookAt(result.position);
  87326. }
  87327. showAbout () {
  87328. $(function () {
  87329. $('#about-panel').dialog();
  87330. });
  87331. };
  87332. getGpsTimeExtent(){
  87333. const range = [Infinity, -Infinity];
  87334. for(const pointcloud of this.scene.pointclouds){
  87335. const attributes = pointcloud.pcoGeometry.pointAttributes.attributes;
  87336. const aGpsTime = attributes.find(a => a.name === "gps-time");
  87337. if(aGpsTime){
  87338. range[0] = Math.min(range[0], aGpsTime.range[0]);
  87339. range[1] = Math.max(range[1], aGpsTime.range[1]);
  87340. }
  87341. }
  87342. return range;
  87343. }
  87344. fitToScreen (factor = 1, animationDuration = 0) {
  87345. let box = this.getBoundingBox(this.scene.pointclouds);
  87346. let node = new Object3D();
  87347. node.boundingBox = box;
  87348. this.zoomTo(node, factor, animationDuration);
  87349. this.controls.stop();
  87350. };
  87351. toggleNavigationCube() {
  87352. this.navigationCube.visible = !this.navigationCube.visible;
  87353. }
  87354. /* setView(pos, view) {
  87355. if(!pos) return;
  87356. switch(pos) {
  87357. case "F":
  87358. this.setFrontView(view);
  87359. break;
  87360. case "B":
  87361. this.setBackView(view);
  87362. break;
  87363. case "L":
  87364. this.setLeftView(view);
  87365. break;
  87366. case "R":
  87367. this.setRightView(view);
  87368. break;
  87369. case "U":
  87370. this.setTopView(view);
  87371. break;
  87372. case "D":
  87373. this.setBottomView(view);
  87374. break;
  87375. }
  87376. } */
  87377. setTopView(view){
  87378. view = view || this.scene.view;
  87379. view.setCubeView("top");
  87380. this.fitToScreen();
  87381. };
  87382. setBottomView(){
  87383. this.scene.view.yaw = -Math.PI;
  87384. this.scene.view.pitch = Math.PI / 2;
  87385. this.fitToScreen();
  87386. };
  87387. setFrontView(view){
  87388. view = view || this.scene.view;
  87389. view.yaw = 0;
  87390. view.pitch = 0;
  87391. this.fitToScreen();
  87392. };
  87393. setBackView(view){
  87394. view = view || this.scene.view;
  87395. view.yaw = Math.PI;
  87396. view.pitch = 0;
  87397. this.fitToScreen();
  87398. };
  87399. setLeftView(){
  87400. this.scene.view.yaw = -Math.PI / 2;
  87401. this.scene.view.pitch = 0;
  87402. this.fitToScreen();
  87403. };
  87404. setRightView () {
  87405. this.scene.view.yaw = Math.PI / 2;
  87406. this.scene.view.pitch = 0;
  87407. this.fitToScreen();
  87408. };
  87409. flipYZ () {
  87410. this.isFlipYZ = !this.isFlipYZ;
  87411. // TODO flipyz
  87412. console.log('TODO');
  87413. }
  87414. setCameraMode(mode){
  87415. this.scene.cameraMode = mode;
  87416. for(let pointcloud of this.scene.pointclouds) {
  87417. pointcloud.material.useOrthographicCamera = mode == CameraMode.ORTHOGRAPHIC;
  87418. }
  87419. }
  87420. getProjection(){
  87421. const pointcloud = this.scene.pointclouds[0];
  87422. if(pointcloud){
  87423. return pointcloud.projection;
  87424. }else {
  87425. return null;
  87426. }
  87427. }
  87428. async loadProject(url,done){
  87429. const response = await fetch(url);
  87430. if(response.ok){
  87431. const text = await response.text();
  87432. const json = lib.parse(text);
  87433. // const json = JSON.parse(text);
  87434. if(json.type === "Potree"){
  87435. Potree.loadProject(viewer, json, done);
  87436. }
  87437. }else {
  87438. console.warn("未能加载:"+url );
  87439. }
  87440. }
  87441. saveProject(){
  87442. return Potree.saveProject(this);
  87443. }
  87444. loadSettingsFromURL(){
  87445. if(Utils.getParameterByName("pointSize")){
  87446. this.setPointSize(parseFloat(Utils.getParameterByName("pointSize")));
  87447. }
  87448. if(Utils.getParameterByName("FOV")){
  87449. this.setFOV(parseFloat(Utils.getParameterByName("FOV")));
  87450. }
  87451. if(Utils.getParameterByName("opacity")){
  87452. this.setOpacity(parseFloat(Utils.getParameterByName("opacity")));
  87453. }
  87454. if(Utils.getParameterByName("edlEnabled")){
  87455. let enabled = Utils.getParameterByName("edlEnabled") === "true";
  87456. this.setEDLEnabled(enabled);
  87457. }
  87458. if (Utils.getParameterByName('edlRadius')) {
  87459. this.setEDLRadius(parseFloat(Utils.getParameterByName('edlRadius')));
  87460. }
  87461. if (Utils.getParameterByName('edlStrength')) {
  87462. this.setEDLStrength(parseFloat(Utils.getParameterByName('edlStrength')));
  87463. }
  87464. if (Utils.getParameterByName('pointBudget')) {
  87465. this.setPointBudget(parseFloat(Utils.getParameterByName('pointBudget')));
  87466. }
  87467. if (Utils.getParameterByName('showBoundingBox')) {
  87468. let enabled = Utils.getParameterByName('showBoundingBox') === 'true';
  87469. if (enabled) {
  87470. this.setShowBoundingBox(true);
  87471. } else {
  87472. this.setShowBoundingBox(false);
  87473. }
  87474. }
  87475. if (Utils.getParameterByName('material')) {
  87476. let material = Utils.getParameterByName('material');
  87477. this.setMaterial(material);
  87478. }
  87479. if (Utils.getParameterByName('pointSizing')) {
  87480. let sizing = Utils.getParameterByName('pointSizing');
  87481. this.setPointSizing(sizing);
  87482. }
  87483. if (Utils.getParameterByName('quality')) {
  87484. let quality = Utils.getParameterByName('quality');
  87485. this.setQuality(quality);
  87486. }
  87487. if (Utils.getParameterByName('position')) {
  87488. let value = Utils.getParameterByName('position');
  87489. value = value.replace('[', '').replace(']', '');
  87490. let tokens = value.split(';');
  87491. let x = parseFloat(tokens[0]);
  87492. let y = parseFloat(tokens[1]);
  87493. let z = parseFloat(tokens[2]);
  87494. this.scene.view.position.set(x, y, z);
  87495. }
  87496. if (Utils.getParameterByName('target')) {
  87497. let value = Utils.getParameterByName('target');
  87498. value = value.replace('[', '').replace(']', '');
  87499. let tokens = value.split(';');
  87500. let x = parseFloat(tokens[0]);
  87501. let y = parseFloat(tokens[1]);
  87502. let z = parseFloat(tokens[2]);
  87503. this.scene.view.lookAt(new Vector3(x, y, z));
  87504. }
  87505. if (Utils.getParameterByName('background')) {
  87506. let value = Utils.getParameterByName('background');
  87507. this.setBackground(value);
  87508. }
  87509. // if(Utils.getParameterByName("elevationRange")){
  87510. // let value = Utils.getParameterByName("elevationRange");
  87511. // value = value.replace("[", "").replace("]", "");
  87512. // let tokens = value.split(";");
  87513. // let x = parseFloat(tokens[0]);
  87514. // let y = parseFloat(tokens[1]);
  87515. //
  87516. // this.setElevationRange(x, y);
  87517. // //this.scene.view.target.set(x, y, z);
  87518. // }
  87519. };
  87520. // ------------------------------------------------------------------------------------
  87521. // Viewer Internals
  87522. // ------------------------------------------------------------------------------------
  87523. createControls () {
  87524. { // create FIRST PERSON CONTROLS
  87525. this.fpControls = new FirstPersonControls(this, this.mainViewport);
  87526. this.fpControls.enabled = false;
  87527. this.fpControls.addEventListener('start', this.disableAnnotations.bind(this));
  87528. this.fpControls.addEventListener('end', this.enableAnnotations.bind(this));
  87529. /* this.addEventListener("loadPointCloudDone", ()=>{
  87530. let boundPlane = new THREE.Box3()
  87531. boundPlane.expandByPoint(this.bound.boundingBox.min.clone())//最低高度为bound的最低
  87532. boundPlane.expandByPoint(this.bound.boundingBox.max.clone().setZ(this.bound.center.z))//最高高度为bound的中心高度
  87533. FirstPersonControls.boundPlane = boundPlane
  87534. FirstPersonControls.standardSpeed = THREE.Math.clamp( Math.sqrt(this.bound.boundSize.length() )/ 100 , 0.02,0.5); //在这个boundPlane中的速度
  87535. }) */
  87536. }
  87537. // { // create GEO CONTROLS
  87538. // this.geoControls = new GeoControls(this.scene.camera, this.renderer.domElement);
  87539. // this.geoControls.enabled = false;
  87540. // this.geoControls.addEventListener("start", this.disableAnnotations.bind(this));
  87541. // this.geoControls.addEventListener("end", this.enableAnnotations.bind(this));
  87542. // this.geoControls.addEventListener("move_speed_changed", (event) => {
  87543. // this.setMoveSpeed(this.geoControls.moveSpeed);
  87544. // });
  87545. // }
  87546. { // create ORBIT CONTROLS
  87547. this.orbitControls = new OrbitControls(this);
  87548. this.orbitControls.enabled = false;
  87549. this.orbitControls.addEventListener('start', this.disableAnnotations.bind(this));
  87550. this.orbitControls.addEventListener('end', this.enableAnnotations.bind(this));
  87551. }
  87552. { // create EARTH CONTROLS
  87553. this.earthControls = new EarthControls(this);
  87554. this.earthControls.enabled = false;
  87555. this.earthControls.addEventListener('start', this.disableAnnotations.bind(this));
  87556. this.earthControls.addEventListener('end', this.enableAnnotations.bind(this));
  87557. }
  87558. { // create DEVICE ORIENTATION CONTROLS
  87559. this.deviceControls = new DeviceOrientationControls(this);
  87560. this.deviceControls.enabled = false;
  87561. this.deviceControls.addEventListener('start', this.disableAnnotations.bind(this));
  87562. this.deviceControls.addEventListener('end', this.enableAnnotations.bind(this));
  87563. }
  87564. /* { // create VR CONTROLS
  87565. this.vrControls = new VRControls(this);
  87566. this.vrControls.enabled = false;
  87567. this.vrControls.addEventListener('start', this.disableAnnotations.bind(this));
  87568. this.vrControls.addEventListener('end', this.enableAnnotations.bind(this));
  87569. } */
  87570. };
  87571. toggleSidebar () {
  87572. let renderArea = $('#potree_render_area');
  87573. let isVisible = renderArea.css('left') !== '0px';
  87574. if (isVisible) {
  87575. renderArea.css('left', '0px');
  87576. } else {
  87577. renderArea.css('left', '300px');
  87578. }
  87579. };
  87580. toggleMap () {
  87581. // let map = $('#potree_map');
  87582. // map.toggle(100);
  87583. if (this.mapView) {
  87584. this.mapView.toggle();
  87585. }
  87586. };
  87587. onGUILoaded(callback){
  87588. if(this.guiLoaded){
  87589. callback();
  87590. }else {
  87591. this.guiLoadTasks.push(callback);
  87592. }
  87593. }
  87594. promiseGuiLoaded(){
  87595. return new Promise( resolve => {
  87596. if(this.guiLoaded){
  87597. resolve();
  87598. }else {
  87599. this.guiLoadTasks.push(resolve);
  87600. }
  87601. });
  87602. }
  87603. loadGUI(callback){
  87604. if(callback){
  87605. this.onGUILoaded(callback);
  87606. }
  87607. let viewer = this;
  87608. let sidebarContainer = $('#potree_sidebar_container');
  87609. sidebarContainer.load(new URL(Potree.scriptPath + '/' + (Potree.settings.sidebar || 'sidebar.html')).href, () => {
  87610. sidebarContainer.css('width', '300px');
  87611. sidebarContainer.css('height', '100%');
  87612. let imgMenuToggle = document.createElement('img');
  87613. imgMenuToggle.src = new URL(Potree.resourcePath + '/icons/menu_button.svg').href;
  87614. imgMenuToggle.onclick = this.toggleSidebar;
  87615. imgMenuToggle.classList.add('potree_menu_toggle');
  87616. let imgMapToggle = document.createElement('img');
  87617. imgMapToggle.src = new URL(Potree.resourcePath + '/icons/map_icon.png').href;
  87618. imgMapToggle.style.display = 'none';
  87619. imgMapToggle.onclick = e => { this.toggleMap(); };
  87620. imgMapToggle.id = 'potree_map_toggle';
  87621. let elButtons = $("#potree_quick_buttons").get(0);
  87622. elButtons.append(imgMenuToggle);
  87623. elButtons.append(imgMapToggle);
  87624. /*
  87625. VRButton.createButton(this.renderer).then(vrButton => {
  87626. if(vrButton == null){
  87627. console.log("VR not supported or active.");
  87628. return;
  87629. }
  87630. this.renderer.xr.enabled = true;
  87631. let element = vrButton.element;
  87632. element.style.position = "";
  87633. element.style.bottom = "";
  87634. element.style.left = "";
  87635. element.style.margin = "4px";
  87636. element.style.fontSize = "100%";
  87637. element.style.width = "2.5em";
  87638. element.style.height = "2.5em";
  87639. element.style.padding = "0";
  87640. element.style.textShadow = "black 2px 2px 2px";
  87641. element.style.display = "block";
  87642. elButtons.append(element);
  87643. vrButton.onStart(() => {
  87644. this.dispatchEvent({type: "vr_start"});
  87645. });
  87646. vrButton.onEnd(() => {
  87647. this.dispatchEvent({type: "vr_end"});
  87648. });
  87649. });
  87650. this.mapView = new MapView(this);
  87651. this.mapView.init(); */
  87652. i18n.init({
  87653. lng: 'en',
  87654. resGetPath: Potree.resourcePath + '/lang/__lng__/__ns__.json',
  87655. preload: ['en', 'fr', 'de', 'jp', 'se', 'es', 'zh'],
  87656. getAsync: true,
  87657. debug: false
  87658. }, function (t) {
  87659. // Start translation once everything is loaded
  87660. $('body').i18n();
  87661. });
  87662. $(() => {
  87663. //initSidebar(this);
  87664. let sidebar = new Sidebar(this);
  87665. sidebar.init();
  87666. this.sidebar = sidebar;
  87667. //if (callback) {
  87668. // $(callback);
  87669. //}
  87670. let elProfile = $('<div>').load(new URL(Potree.scriptPath + '/profile.html').href, () => {
  87671. $(document.body).append(elProfile.children());
  87672. this.profileWindow = new ProfileWindow(this);
  87673. this.profileWindowController = new ProfileWindowController(this);
  87674. $('#profile_window').draggable({
  87675. handle: $('#profile_titlebar'),
  87676. containment: $(document.body)
  87677. });
  87678. $('#profile_window').resizable({
  87679. containment: $(document.body),
  87680. handles: 'n, e, s, w'
  87681. });
  87682. $(() => {
  87683. this.guiLoaded = true;
  87684. for(let task of this.guiLoadTasks){
  87685. task();
  87686. }
  87687. });
  87688. });
  87689. });
  87690. });
  87691. return this.promiseGuiLoaded();
  87692. }
  87693. setLanguage (lang) {
  87694. i18n.setLng(lang);
  87695. $('body').i18n();
  87696. }
  87697. setServer (server) {
  87698. this.server = server;
  87699. }
  87700. initDragAndDrop(){
  87701. function allowDrag(e) {
  87702. e.dataTransfer.dropEffect = 'copy';
  87703. e.preventDefault();
  87704. }
  87705. let dropHandler = async (event) => {
  87706. console.log(event);
  87707. event.preventDefault();
  87708. for(const item of event.dataTransfer.items){
  87709. console.log(item);
  87710. if(item.kind !== "file"){
  87711. continue;
  87712. }
  87713. const file = item.getAsFile();
  87714. const isJson = file.name.toLowerCase().endsWith(".json");
  87715. const isGeoPackage = file.name.toLowerCase().endsWith(".gpkg");
  87716. if(isJson){
  87717. try{
  87718. const text = await file.text();
  87719. const json = JSON.parse(text);
  87720. if(json.type === "Potree"){
  87721. Potree.loadProject(viewer, json);
  87722. }
  87723. }catch(e){
  87724. console.error("failed to parse the dropped file as JSON");
  87725. console.error(e);
  87726. }
  87727. }else if(isGeoPackage){
  87728. const hasPointcloud = viewer.scene.pointclouds.length > 0;
  87729. if(!hasPointcloud){
  87730. let msg = "At least one point cloud is needed that specifies the ";
  87731. msg += "coordinate reference system before loading vector data.";
  87732. console.error(msg);
  87733. }else {
  87734. proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
  87735. proj4.defs("pointcloud", this.getProjection());
  87736. let transform = proj4("WGS84", "pointcloud");
  87737. const buffer = await file.arrayBuffer();
  87738. const params = {
  87739. transform: transform,
  87740. source: file.name,
  87741. };
  87742. const geo = await Potree.GeoPackageLoader.loadBuffer(buffer, params);
  87743. viewer.scene.addGeopackage(geo);
  87744. }
  87745. }
  87746. }
  87747. };
  87748. $("body")[0].addEventListener("dragenter", allowDrag);
  87749. $("body")[0].addEventListener("dragover", allowDrag);
  87750. $("body")[0].addEventListener("drop", dropHandler);
  87751. }
  87752. updateAnnotations () {
  87753. if(!this.visibleAnnotations){
  87754. this.visibleAnnotations = new Set();
  87755. }
  87756. this.scene.annotations.updateBounds();
  87757. this.scene.cameraP.updateMatrixWorld();
  87758. this.scene.cameraO.updateMatrixWorld();
  87759. let distances = [];
  87760. let renderAreaSize = this.renderer.getSize(new Vector2$1());
  87761. let viewer = this;
  87762. let visibleNow = [];
  87763. this.scene.annotations.traverse(annotation => {
  87764. if (annotation === this.scene.annotations) {
  87765. return true;
  87766. }
  87767. if (!annotation.visible) {
  87768. return false;
  87769. }
  87770. annotation.scene = this.scene;
  87771. let element = annotation.domElement;
  87772. let position = annotation.position.clone();
  87773. position.add(annotation.offset);
  87774. if (!position) {
  87775. position = annotation.boundingBox.getCenter(new Vector3());
  87776. }
  87777. let distance = viewer.scene.cameraP.position.distanceTo(position);
  87778. let radius = annotation.boundingBox.getBoundingSphere(new Sphere()).radius;
  87779. let screenPos = new Vector3();
  87780. let screenSize = 0;
  87781. {
  87782. // SCREEN POS
  87783. screenPos.copy(position).project(this.scene.getActiveCamera());
  87784. screenPos.x = renderAreaSize.x * (screenPos.x + 1) / 2;
  87785. screenPos.y = renderAreaSize.y * (1 - (screenPos.y + 1) / 2);
  87786. // SCREEN SIZE
  87787. if(viewer.scene.cameraMode == CameraMode.PERSPECTIVE) {
  87788. let fov = Math.PI * viewer.scene.cameraP.fov / 180;
  87789. let slope = Math.tan(fov / 2.0);
  87790. let projFactor = 0.5 * renderAreaSize.y / (slope * distance);
  87791. screenSize = radius * projFactor;
  87792. } else {
  87793. screenSize = Utils.projectedRadiusOrtho(radius, viewer.scene.cameraO.projectionMatrix, renderAreaSize.x, renderAreaSize.y);
  87794. }
  87795. }
  87796. element.css("left", screenPos.x + "px");
  87797. element.css("top", screenPos.y + "px");
  87798. //element.css("display", "block");
  87799. let zIndex = 10000000 - distance * (10000000 / this.scene.cameraP.far);
  87800. if(annotation.descriptionVisible){
  87801. zIndex += 10000000;
  87802. }
  87803. element.css("z-index", parseInt(zIndex));
  87804. if(annotation.children.length > 0){
  87805. let expand = screenSize > annotation.collapseThreshold || annotation.boundingBox.containsPoint(this.scene.getActiveCamera().position);
  87806. annotation.expand = expand;
  87807. if (!expand) {
  87808. //annotation.display = (screenPos.z >= -1 && screenPos.z <= 1);
  87809. let inFrustum = (screenPos.z >= -1 && screenPos.z <= 1);
  87810. if(inFrustum){
  87811. visibleNow.push(annotation);
  87812. }
  87813. }
  87814. return expand;
  87815. } else {
  87816. //annotation.display = (screenPos.z >= -1 && screenPos.z <= 1);
  87817. let inFrustum = (screenPos.z >= -1 && screenPos.z <= 1);
  87818. if(inFrustum){
  87819. visibleNow.push(annotation);
  87820. }
  87821. }
  87822. });
  87823. let notVisibleAnymore = new Set(this.visibleAnnotations);
  87824. for(let annotation of visibleNow){
  87825. annotation.display = true;
  87826. notVisibleAnymore.delete(annotation);
  87827. }
  87828. this.visibleAnnotations = visibleNow;
  87829. for(let annotation of notVisibleAnymore){
  87830. annotation.display = false;
  87831. }
  87832. }
  87833. updateMaterialDefaults(pointcloud){
  87834. // PROBLEM STATEMENT:
  87835. // * [min, max] of intensity, source id, etc. are computed as point clouds are loaded
  87836. // * the point cloud material won't know the range it should use until some data is loaded
  87837. // * users can modify the range at runtime, but sensible default ranges should be
  87838. // applied even if no GUI is present
  87839. // * display ranges shouldn't suddenly change even if the actual range changes over time.
  87840. // e.g. the root node has intensity range [1, 478]. One of the descendants increases range to
  87841. // [0, 2047]. We should not automatically change to the new range because that would result
  87842. // in sudden and drastic changes of brightness. We should adjust the min/max of the sidebar slider.
  87843. const material = pointcloud.material;
  87844. const attIntensity = pointcloud.getAttribute("intensity");
  87845. if(attIntensity != null && material.intensityRange[0] === Infinity){
  87846. material.intensityRange = [...attIntensity.range];
  87847. }
  87848. // const attIntensity = pointcloud.getAttribute("intensity");
  87849. // if(attIntensity && material.intensityRange[0] === Infinity){
  87850. // material.intensityRange = [...attIntensity.range];
  87851. // }
  87852. // let attributes = pointcloud.getAttributes();
  87853. // for(let attribute of attributes.attributes){
  87854. // if(attribute.range){
  87855. // let range = [...attribute.range];
  87856. // material.computedRange.set(attribute.name, range);
  87857. // //material.setRange(attribute.name, range);
  87858. // }
  87859. // }
  87860. }
  87861. update(delta, timestamp){
  87862. if(Potree.measureTimings) performance.mark("update-start");
  87863. this.dispatchEvent({
  87864. type: 'update_start',
  87865. delta: delta,
  87866. timestamp: timestamp});
  87867. this.updateScreenSize(); //判断是否改变canvas大小
  87868. const scene = this.scene;
  87869. const camera = scene.getActiveCamera();
  87870. const visiblePointClouds = this.scene.pointclouds.filter(pc => pc.visible);
  87871. Potree.pointLoadLimit = Potree.pointBudget * 2;
  87872. const lTarget = camera.position.clone().add(camera.getWorldDirection(new Vector3()).multiplyScalar(1000));
  87873. this.scene.directionalLight.position.copy(camera.position);
  87874. this.scene.directionalLight.lookAt(lTarget);
  87875. for (let pointcloud of visiblePointClouds) {
  87876. pointcloud.showBoundingBox = this.showBoundingBox;
  87877. pointcloud.generateDEM = this.generateDEM;
  87878. pointcloud.minimumNodePixelSize = this.minNodeSize;
  87879. let material = pointcloud.material;
  87880. material.uniforms.uFilterReturnNumberRange.value = this.filterReturnNumberRange;
  87881. material.uniforms.uFilterNumberOfReturnsRange.value = this.filterNumberOfReturnsRange;
  87882. material.uniforms.uFilterGPSTimeClipRange.value = this.filterGPSTimeRange;
  87883. material.uniforms.uFilterPointSourceIDClipRange.value = this.filterPointSourceIDRange;
  87884. material.classification = this.classifications;
  87885. material.recomputeClassification();
  87886. this.updateMaterialDefaults(pointcloud);
  87887. }
  87888. {
  87889. if(this.showBoundingBox){
  87890. let bbRoot = this.scene.scene.getObjectByName("potree_bounding_box_root");
  87891. if(!bbRoot){
  87892. let node = new Object3D();
  87893. node.name = "potree_bounding_box_root";
  87894. this.scene.scene.add(node);
  87895. bbRoot = node;
  87896. }
  87897. let visibleBoxes = [];
  87898. for(let pointcloud of this.scene.pointclouds){
  87899. for(let node of pointcloud.visibleNodes.filter(vn => vn.boundingBoxNode !== undefined)){
  87900. let box = node.boundingBoxNode;
  87901. visibleBoxes.push(box);
  87902. }
  87903. }
  87904. bbRoot.children = visibleBoxes;
  87905. }
  87906. }
  87907. if (!this.freeze) {
  87908. /*let cameraGroup = []
  87909. let size = this.renderer.getSize(new THREE.Vector2())
  87910. if(this.viewports){
  87911. this.viewports.forEach(viewport=>{
  87912. if(!viewport.active)return
  87913. cameraGroup.push({camera:viewport.camera, areaSize:new THREE.Vector2(Math.floor(size.x * viewport.width), Math.floor(size.y * viewport.height))})
  87914. })
  87915. }else{
  87916. cameraGroup.push({camera, areaSize:size})
  87917. }
  87918. let result = Potree.updatePointClouds(scene.pointclouds, cameraGroup );
  87919. */
  87920. // DEBUG - ONLY DISPLAY NODES THAT INTERSECT MOUSE
  87921. //if(false){
  87922. // let renderer = viewer.renderer;
  87923. // let mouse = viewer.inputHandler.mouse;
  87924. // let nmouse = {
  87925. // x: (mouse.x / renderer.domElement.clientWidth) * 2 - 1,
  87926. // y: -(mouse.y / renderer.domElement.clientHeight) * 2 + 1
  87927. // };
  87928. // let pickParams = {};
  87929. // //if(params.pickClipped){
  87930. // // pickParams.pickClipped = params.pickClipped;
  87931. // //}
  87932. // pickParams.x = mouse.x;
  87933. // pickParams.y = renderer.domElement.clientHeight - mouse.y;
  87934. // let raycaster = new THREE.Raycaster();
  87935. // raycaster.setFromCamera(nmouse, camera);
  87936. // let ray = raycaster.ray;
  87937. // for(let pointcloud of scene.pointclouds){
  87938. // let nodes = pointcloud.nodesOnRay(pointcloud.visibleNodes, ray);
  87939. // pointcloud.visibleNodes = nodes;
  87940. // }
  87941. //}
  87942. // const tStart = performance.now();
  87943. // const worldPos = new THREE.Vector3();
  87944. // const camPos = viewer.scene.getActiveCamera().getWorldPosition(new THREE.Vector3());
  87945. // let lowestDistance = Infinity;
  87946. // let numNodes = 0;
  87947. // viewer.scene.scene.traverse(node => {
  87948. // node.getWorldPosition(worldPos);
  87949. // const distance = worldPos.distanceTo(camPos);
  87950. // lowestDistance = Math.min(lowestDistance, distance);
  87951. // numNodes++;
  87952. // if(Number.isNaN(distance)){
  87953. // console.error(":(");
  87954. // }
  87955. // });
  87956. // const duration = (performance.now() - tStart).toFixed(2);
  87957. // Potree.debug.computeNearDuration = duration;
  87958. // Potree.debug.numNodes = numNodes;
  87959. //console.log(lowestDistance.toString(2), duration);
  87960. //搬走
  87961. /* const tStart = performance.now();
  87962. const campos = camera.position;
  87963. let closestImage = Infinity;
  87964. for(const images of this.scene.orientedImages){
  87965. for(const image of images.images){
  87966. const distance = image.mesh.position.distanceTo(campos);
  87967. closestImage = Math.min(closestImage, distance);
  87968. }
  87969. }
  87970. const tEnd = performance.now();
  87971. if(result.lowestSpacing !== Infinity){
  87972. let near = result.lowestSpacing * 10.0;
  87973. let far = -this.getBoundingBox().applyMatrix4(camera.matrixWorldInverse).min.z;
  87974. far = Math.max(far * 1.5, 10000);
  87975. near = Math.min(100.0, Math.max(0.01, near));
  87976. near = Math.min(near, closestImage);
  87977. far = Math.max(far, near + 10000);
  87978. if(near === Infinity){
  87979. near = 0.1;
  87980. }
  87981. camera.near = near;
  87982. camera.far = far;
  87983. }else{
  87984. // don't change near and far in this case
  87985. }
  87986. if(this.scene.cameraMode == CameraMode.ORTHOGRAPHIC) {
  87987. camera.near = -camera.far;
  87988. }*/
  87989. }
  87990. this.scene.cameraP.fov = this.fov;
  87991. let controls = this.getControls();
  87992. if (controls === this.deviceControls) {
  87993. this.controls.setScene(scene);
  87994. this.controls.update(delta);
  87995. this.scene.cameraP.position.copy(scene.view.position);
  87996. this.scene.cameraO.position.copy(scene.view.position);
  87997. } else if (controls !== null) {
  87998. controls.setScene(scene);
  87999. controls.update(delta);
  88000. //更新camera
  88001. this.viewports.forEach(viewport=>{
  88002. if(!viewport.active)return
  88003. viewport.view.applyToCamera(viewport.camera);
  88004. });
  88005. }
  88006. /* this.viewports.forEach(e=>{//判断camera画面是否改变
  88007. if(e.cameraChanged()){
  88008. this.dispatchEvent({
  88009. type: "camera_changed",
  88010. camera: e.camera,
  88011. viewport : e
  88012. })
  88013. }
  88014. }) */
  88015. this.cameraChanged();//判断camera画面是否改变
  88016. /* {//判断camera画面是否改变
  88017. if(this._previousCamera === undefined){
  88018. this._previousCamera = this.scene.getActiveCamera().clone();
  88019. this._previousCamera.rotation.copy(this.scene.getActiveCamera().rotation);
  88020. }
  88021. if(!this._previousCamera.matrixWorld.equals(camera.matrixWorld) ||
  88022. !this._previousCamera.projectionMatrix.equals(camera.projectionMatrix)
  88023. ){
  88024. this.dispatchEvent({
  88025. type: "camera_changed",
  88026. previous: this._previousCamera,
  88027. camera: camera
  88028. });
  88029. }
  88030. this._previousCamera = this.scene.getActiveCamera().clone();
  88031. this._previousCamera.rotation.copy(this.scene.getActiveCamera().rotation);
  88032. } */
  88033. { // update clip boxes
  88034. let boxes = [];
  88035. // volumes with clipping enabled
  88036. //boxes.push(...this.scene.volumes.filter(v => (v.clip)));
  88037. boxes.push(...this.scene.volumes.filter(v => (v.clip && v instanceof BoxVolume)));
  88038. // profile segments
  88039. for(let profile of this.scene.profiles){
  88040. boxes.push(...profile.boxes);
  88041. }
  88042. // Needed for .getInverse(), pre-empt a determinant of 0, see #815 / #816
  88043. let degenerate = (box) => box.matrixWorld.determinant() !== 0;
  88044. let clipBoxes = boxes.filter(degenerate).map( box => {
  88045. box.updateMatrixWorld();
  88046. let boxInverse = box.matrixWorld.clone().invert();
  88047. let boxPosition = box.getWorldPosition(new Vector3());
  88048. return {box: box, inverse: boxInverse, position: boxPosition};
  88049. });
  88050. let clipPolygons = this.scene.polygonClipVolumes.filter(vol => vol.initialized);
  88051. // set clip volumes in material
  88052. for(let pointcloud of visiblePointClouds){
  88053. pointcloud.material.setClipBoxes(clipBoxes);
  88054. pointcloud.material.setClipPolygons(clipPolygons, this.clippingTool.maxPolygonVertices);
  88055. pointcloud.material.clipTask = this.clipTask;
  88056. pointcloud.material.clipMethod = this.clipMethod;
  88057. }
  88058. }
  88059. {
  88060. for(let pointcloud of visiblePointClouds){
  88061. pointcloud.material.elevationGradientRepeat = this.elevationGradientRepeat;
  88062. }
  88063. }
  88064. { // update navigation cube
  88065. this.navigationCube.update(camera.rotation);
  88066. }
  88067. this.updateAnnotations();
  88068. if(this.mapView){
  88069. this.mapView.update(delta);
  88070. if(this.mapView.sceneProjection){
  88071. $( "#potree_map_toggle" ).css("display", "block");
  88072. }
  88073. }
  88074. TWEEN.update(timestamp);
  88075. transitions.update(delta);
  88076. this.transformationTool.update();
  88077. if(Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge'){
  88078. this.modules.ParticleEditor.update(delta);
  88079. this.mapViewer.update(delta);
  88080. }
  88081. this.dispatchEvent({
  88082. type: 'update',
  88083. delta: delta,
  88084. timestamp: timestamp});
  88085. if(Potree.measureTimings) {
  88086. performance.mark("update-end");
  88087. performance.measure("update", "update-start", "update-end");
  88088. }
  88089. //add ------
  88090. this.reticule.updateVisible();
  88091. }
  88092. updateViewPointcloud(camera, areaSize, isViewport){
  88093. let result = Potree.updatePointClouds(this.scene.pointclouds, camera, areaSize );
  88094. //if(isViewport)return
  88095. const tStart = performance.now();
  88096. const campos = camera.position;
  88097. let closestImage = Infinity;
  88098. for(const images of this.scene.orientedImages){
  88099. for(const image of images.images){
  88100. const distance = image.mesh.position.distanceTo(campos);
  88101. closestImage = Math.min(closestImage, distance);
  88102. }
  88103. }
  88104. const tEnd = performance.now();
  88105. //改:不根据点云修改视野near far
  88106. var near = camera.near, far = camera.far;
  88107. if(!camera.limitFar && result.lowestSpacing !== Infinity){
  88108. //let near = result.lowestSpacing * 10.0;
  88109. let far = -this.getBoundingBox().applyMatrix4(camera.matrixWorldInverse).min.z;
  88110. far = Math.max(far * 1.5, 10000);
  88111. //near = Math.min(100.0, Math.max(0.01, near));
  88112. //near = Math.min(near, closestImage);
  88113. far = Math.max(far, near + 10000);
  88114. /* if(near === Infinity){
  88115. near = 0.1;
  88116. } */
  88117. //camera.near = near; //为了其他物体的显示,不修改near
  88118. camera.far = far;
  88119. }
  88120. /* if(this.scene.cameraMode == CameraMode.ORTHOGRAPHIC) {//???
  88121. camera.near = -camera.far;
  88122. } */
  88123. if(/* near != camera.near || */far != camera.far){
  88124. camera.updateProjectionMatrix();
  88125. }
  88126. //注:pointcloud.visibleNodes会随着near far自动更新
  88127. }
  88128. getPRenderer(){
  88129. if(this.useHQ){
  88130. if (!this.hqRenderer) {
  88131. this.hqRenderer = new HQSplatRenderer(this);
  88132. }
  88133. this.hqRenderer.useEDL = this.useEDL;
  88134. return this.hqRenderer;
  88135. }else {
  88136. /* if (this.useEDL && Features.SHADER_EDL.isSupported()) {
  88137. if (!this.edlRenderer) {
  88138. this.edlRenderer = new EDLRenderer(this);
  88139. }
  88140. return this.edlRenderer;
  88141. } else {
  88142. if (!this.potreeRenderer) {
  88143. this.potreeRenderer = new PotreeRenderer(this);
  88144. }
  88145. return this.potreeRenderer;
  88146. } */
  88147. if (!this.edlRenderer) {
  88148. this.edlRenderer = new EDLRenderer(this);
  88149. }
  88150. return this.edlRenderer;
  88151. }
  88152. }
  88153. renderVR(){
  88154. let renderer = this.renderer;
  88155. renderer.setClearColor(0x550000, 0);
  88156. renderer.clear();
  88157. let xr = renderer.xr;
  88158. let dbg = new PerspectiveCamera();
  88159. let xrCameras = xr.getCamera(dbg);
  88160. if(xrCameras.cameras.length !== 2){
  88161. return;
  88162. }
  88163. let makeCam = this.vrControls.getCamera.bind(this.vrControls);
  88164. { // clear framebuffer
  88165. if(viewer.background === "skybox"){
  88166. renderer.setClearColor(0xff0000, 1);
  88167. }else if(viewer.background === "gradient"){
  88168. renderer.setClearColor(0x112233, 1);
  88169. }else if(viewer.background === "black"){
  88170. renderer.setClearColor(0x000000, 1);
  88171. }else if(viewer.background === "white"){
  88172. renderer.setClearColor(0xFFFFFF, 1);
  88173. }else {
  88174. renderer.setClearColor(0x000000, 0);
  88175. }
  88176. renderer.clear();
  88177. }
  88178. // render background
  88179. if(this.background === "skybox"){
  88180. let {skybox} = this;
  88181. let cam = makeCam();
  88182. skybox.camera.rotation.copy(cam.rotation);
  88183. skybox.camera.fov = cam.fov;
  88184. skybox.camera.aspect = cam.aspect;
  88185. // let dbg = new THREE.Object3D();
  88186. let dbg = skybox.parent;
  88187. // dbg.up.set(0, 0, 1);
  88188. dbg.rotation.x = Math.PI / 2;
  88189. // skybox.camera.parent = dbg;
  88190. // dbg.children.push(skybox.camera);
  88191. dbg.updateMatrix();
  88192. dbg.updateMatrixWorld();
  88193. skybox.camera.updateMatrix();
  88194. skybox.camera.updateMatrixWorld();
  88195. skybox.camera.updateProjectionMatrix();
  88196. renderer.render(skybox.scene, skybox.camera);
  88197. // renderer.render(skybox.scene, cam);
  88198. }else if(this.background === "gradient"){
  88199. // renderer.render(this.scene.sceneBG, this.scene.cameraBG);
  88200. }
  88201. this.renderer.xr.getSession().updateRenderState({
  88202. depthNear: 0.1,
  88203. depthFar: 10000
  88204. });
  88205. let cam = null;
  88206. let view = null;
  88207. { // render world scene
  88208. cam = makeCam();
  88209. cam.position.z -= 0.8 * cam.scale.x;
  88210. cam.parent = null;
  88211. // cam.near = 0.05;
  88212. cam.near = viewer.scene.getActiveCamera().near;
  88213. cam.far = viewer.scene.getActiveCamera().far;
  88214. cam.updateMatrix();
  88215. cam.updateMatrixWorld();
  88216. this.scene.scene.updateMatrix();
  88217. this.scene.scene.updateMatrixWorld();
  88218. this.scene.scene.matrixAutoUpdate = false;
  88219. let camWorld = cam.matrixWorld.clone();
  88220. view = camWorld.clone().invert();
  88221. this.scene.scene.matrix.copy(view);
  88222. this.scene.scene.matrixWorld.copy(view);
  88223. cam.matrix.identity();
  88224. cam.matrixWorld.identity();
  88225. cam.matrixWorldInverse.identity();
  88226. renderer.render(this.scene.scene, cam);
  88227. this.scene.scene.matrixWorld.identity();
  88228. }
  88229. for(let pointcloud of this.scene.pointclouds){
  88230. let viewport = xrCameras.cameras[0].viewport;
  88231. pointcloud.material.useEDL = false;
  88232. pointcloud.screenHeight = viewport.height;
  88233. pointcloud.screenWidth = viewport.width;
  88234. // automatically switch to paraboloids because they cause far less flickering in VR,
  88235. // when point sizes are larger than around 2 pixels
  88236. // if(Features.SHADER_INTERPOLATION.isSupported()){
  88237. // pointcloud.material.shape = Potree.PointShape.PARABOLOID;
  88238. // }
  88239. }
  88240. // render point clouds
  88241. for(let xrCamera of xrCameras.cameras){
  88242. let v = xrCamera.viewport;
  88243. renderer.setViewport(v.x, v.y, v.width, v.height);
  88244. // xrCamera.fov = 90;
  88245. { // estimate VR fov
  88246. let proj = xrCamera.projectionMatrix;
  88247. let inv = proj.clone().invert();
  88248. let p1 = new Vector4(0, 1, -1, 1).applyMatrix4(inv);
  88249. let rad = p1.y;
  88250. let fov = 180 * (rad / Math.PI);
  88251. xrCamera.fov = fov;
  88252. }
  88253. for(let pointcloud of this.scene.pointclouds){
  88254. const {material} = pointcloud;
  88255. material.useEDL = false;
  88256. }
  88257. let vrWorld = view.clone().invert();
  88258. vrWorld.multiply(xrCamera.matrixWorld);
  88259. let vrView = vrWorld.clone().invert();
  88260. this.pRenderer.render(this.scene.scenePointCloud, xrCamera, null, {
  88261. viewOverride: vrView,
  88262. });
  88263. }
  88264. { // render VR scene
  88265. let cam = makeCam();
  88266. cam.parent = null;
  88267. renderer.render(this.sceneVR, cam);
  88268. }
  88269. renderer.resetState();
  88270. }
  88271. clear(params={}){
  88272. let background = params.background || this.background;
  88273. let backgroundOpacity = params.backgroundOpacity == void 0 ? this.backgroundOpacity : params.backgroundOpacity;//如果想完全透明,只需要backgroundOpacity为0
  88274. let renderer = this.renderer;
  88275. //let gl = renderer.getContext()
  88276. if(background instanceof Color){ //add
  88277. renderer.setClearColor(background, backgroundOpacity);
  88278. }else if(background === "skybox"){
  88279. renderer.setClearColor(0x000000, 0);
  88280. } else if (background === 'gradient') {
  88281. renderer.setClearColor(0x000000, 0);
  88282. } else if (background === 'black') {
  88283. renderer.setClearColor(0x000000, 1);
  88284. } else if (background === 'white') {
  88285. renderer.setClearColor(0xFFFFFF, 1);
  88286. } else {
  88287. renderer.setClearColor(background, backgroundOpacity);
  88288. }
  88289. params.target || renderer.clear();
  88290. }
  88291. renderDefault(params_={}){
  88292. if(!this.visible || this.paused )return
  88293. /* if(this.outlinePass.selectedObjects.length){
  88294. this.clear()
  88295. this.composer.render(this.scene.scene, this.mainViewport.camera );
  88296. return;
  88297. } */
  88298. let pRenderer = this.getPRenderer();
  88299. let viewports = params_.viewports || this.viewports;
  88300. let renderSize;
  88301. if(params_.target){
  88302. renderSize = new Vector2$1(params_.target.width, params_.target.height); //是画布大小
  88303. //可能需要viewer.setSize
  88304. }else {
  88305. renderSize = this.renderer.getSize(new Vector2$1()); //是client大小
  88306. }
  88307. let needSResize = viewports.filter(e=>e.active).length > 1 || params_.resize;
  88308. viewports.forEach(view=>{
  88309. let params = $.extend({},params_);
  88310. params.viewport = view;
  88311. //if(!params.target){
  88312. params.camera = params.camera || view.camera;
  88313. params.extraEnableLayers = view.extraEnableLayers;
  88314. params.cameraLayers = view.cameraLayers;
  88315. //}
  88316. if(!view.active)return
  88317. var left,bottom,width,height;
  88318. {
  88319. left = Math.ceil(renderSize.x * view.left);
  88320. bottom = Math.ceil(renderSize.y * view.bottom);
  88321. if(params_.target){//有target时最好viewport是专门建出来的
  88322. width = Math.ceil(renderSize.x * view.width); //target的大小可能和viewport不同,比如截图,这时会更改viewport大小
  88323. height = Math.ceil(renderSize.y * view.height);
  88324. }else {
  88325. width = view.resolution.x; // 用的是client的width和height
  88326. height = view.resolution.y;
  88327. }
  88328. if(width == 0 || height == 0)return
  88329. let scissorTest = view.width<1 || view.height<1;
  88330. if(params_.target){
  88331. params_.target.viewport.set(left, bottom, width, height);
  88332. scissorTest && params_.target.scissor.set(left, bottom, width, height);
  88333. params_.target.scissorTest = scissorTest;
  88334. }else {
  88335. this.renderer.setViewport(left, bottom, width, height); //规定视口,影响图形变换(画布的使用范围)
  88336. scissorTest && this.renderer.setScissor( left, bottom, width, height );//规定渲染范围
  88337. this.renderer.setScissorTest( scissorTest );//开启WebGL剪裁测试功能,如果不开启,.setScissor方法设置的范围不起作用 | width==1且height==1时开启会只有鼠标的地方刷新,很奇怪
  88338. }
  88339. }
  88340. if(needSResize){
  88341. this.emitResizeMsg( { viewport:view} );
  88342. }
  88343. //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
  88344. viewer.dispatchEvent({type: "render.begin", viewer: viewer, viewport:view, params });
  88345. if(view.render){
  88346. view.render($.extend({}, params, {
  88347. renderer:this.renderer, clear:this.clear.bind(this), resize:null,
  88348. renderOverlay: this.renderOverlay.bind(this), force:!view.noPointcloud //如果要渲染点云,必须也一直渲染地图,否则地图会被覆盖(点云目前未能获取是否改变,也可能有其他动态物体,所以还是一直渲染的好)
  88349. }));
  88350. }
  88351. if(!view.noPointcloud ){
  88352. //if(!params.target){
  88353. //params.width = width; params.height = height;
  88354. //}
  88355. if(view.render){
  88356. params.noBG = true;
  88357. }
  88358. view.beforeRender && view.beforeRender();
  88359. this.updateViewPointcloud(params.camera, view.resolution2, true);
  88360. params.background = view.background;
  88361. params.backgroundColor = view.backgroundColor;
  88362. params.backgroundOpacity = view.backgroundOpacity;
  88363. view.render || this.clear(params);
  88364. pRenderer.clearTargets(params);
  88365. pRenderer.render(params);
  88366. }
  88367. view.render || this.renderOverlay(params);
  88368. view.afterRender && view.afterRender();
  88369. this.dispatchEvent({type: "render.end", viewer: this, viewport:view });
  88370. });
  88371. /* if(params_.screenshot){ //抗锯齿
  88372. params_.target.viewport.set(0, 0, params_.target.width, params_.target.height);
  88373. //scissorTest && params_.target.scissor.set(left, bottom, width, height);
  88374. params_.target.scissorTest = false
  88375. this.renderer.setRenderTarget(params_.target)
  88376. this.composer.render();
  88377. this.renderer.setRenderTarget(params_.target) //本想再画一层标签,但是viewport总是出错
  88378. } */
  88379. this.renderer.setRenderTarget(null);
  88380. }
  88381. renderOverlay(params){
  88382. let camera = params.camera ? params.camera : this.scene.getActiveCamera();
  88383. this.reticule.updateAtViewports(params.viewport);
  88384. //为什么要在点云之后渲染,否则透明失效 、 会被点云覆盖
  88385. let cameraLayers;
  88386. if(params.cameraLayers) cameraLayers = params.cameraLayers;
  88387. else {
  88388. if(params.isMap)cameraLayers = ['bothMapAndScene'];
  88389. else cameraLayers = ['sceneObjects', 'model', 'bothMapAndScene' ];
  88390. }
  88391. if(cameraLayers.length){
  88392. this.setCameraLayers(camera, cameraLayers, params.extraEnableLayers); //透明贴图层 skybox 、reticule marker 不能遮住测量线
  88393. /* if(this.outlinePass.selectedObjects.some(e=>e.isModel).length){
  88394. this.composer.render(this.scene.scene, camera);
  88395. }else{ */
  88396. this.renderer.render(this.scene.scene, camera);
  88397. //}
  88398. }
  88399. this.dispatchEvent({type: "render.pass.scene", viewer: viewer});
  88400. //清除深度 !!!!
  88401. this.renderer.clearDepth();
  88402. //this.transformationTool.update();
  88403. if(!params.magnifier){
  88404. //测量线
  88405. this.dispatchEvent({type: "render.pass.perspective_overlay", camera, screenshot:params.screenshot});
  88406. if(!params.screenshot && !params.isMap){
  88407. this.setCameraLayers(camera, ['magnifier']); //magnifier 遮住测量线
  88408. this.renderer.render(this.scene.scene, camera);
  88409. }
  88410. }
  88411. if(!params.isMap) {
  88412. this.setCameraLayers(camera, ['volume','transformationTool']);
  88413. this.renderer.render(this.clippingTool.sceneVolume, camera);
  88414. this.renderer.render(this.transformationTool.scene, camera);
  88415. }
  88416. }
  88417. /* renderDefault(){//测试 ios15.4.1
  88418. //let pRenderer = this.getPRenderer();
  88419. //this.clear()
  88420. this.renderer.autoClear = false
  88421. this.renderer.setRenderTarget(null)
  88422. let camera = this.scene.getActiveCamera();
  88423. this.setCameraLayers(camera, [ 'sceneObjects', 'marker' , 'reticule' ,'skybox' ])
  88424. this.renderer.render(this.scene.scene, camera);
  88425. // pRenderer.clearTargets( );
  88426. //pRenderer.render( );
  88427. } */
  88428. setLimitFar(state){//切换是否limitFar
  88429. viewer.mainViewport.camera.limitFar = !!state;
  88430. if(state){
  88431. viewer.mainViewport.camera.near = 0.02;
  88432. viewer.mainViewport.camera.far = Potree.settings.displayMode == 'showPanos' ? viewer.farWhenShowPano : Potree.settings.cameraFar;
  88433. viewer.mainViewport.camera.updateProjectionMatrix();
  88434. }
  88435. }
  88436. setCameraLayers(camera, enableLayers, extraEnableLayers=[]){//add
  88437. camera.layers.disableAll();
  88438. enableLayers.concat(extraEnableLayers).forEach(e=>{
  88439. let layer = Potree.config.renderLayers[e];
  88440. if(layer == void 0){
  88441. console.error('setCameraLayer没找到layer!');
  88442. return
  88443. }
  88444. camera.layers.enable(layer);
  88445. });
  88446. }
  88447. setObjectLayers(object, layerName){//add
  88448. let layer = Potree.config.renderLayers[layerName];
  88449. if(layer == void 0){
  88450. console.error('setCameraLayer没找到layer!');
  88451. return
  88452. }
  88453. object.traverse(e=>{
  88454. e.layers.set(layer);
  88455. });
  88456. }
  88457. /* updateVisible(object, reason, ifShow, force){//当所有加入的条件都不为false时才显示. reason='force'一般是强制、临时的
  88458. if(!object.unvisibleReasons) object.unvisibleReasons = []; //如果length>0代表不可见
  88459. if(!object.forceVisibleReasons) object.forceVisibleReasons = []; //只要有一项代表一定可见,优先级比unvisibleReasons高
  88460. if(ifShow){
  88461. if(force){
  88462. object.forceVisibleReasons.includes(reason) || object.forceVisibleReasons.push(reason)
  88463. object.visible = true;
  88464. object.dispatchEvent({
  88465. type: 'isVisible',
  88466. visible:true,
  88467. reason
  88468. })
  88469. }
  88470. var index = object.unvisibleReasons.indexOf(reason)
  88471. if(index > -1){
  88472. object.unvisibleReasons.splice(index, 1);
  88473. if(object.unvisibleReasons.length == 0){
  88474. object.visible = true;
  88475. //mapChange()
  88476. object.dispatchEvent({
  88477. type: 'isVisible',
  88478. visible:true,
  88479. reason
  88480. })
  88481. }
  88482. }
  88483. }else{
  88484. var index = object.forceVisibleReasons.indexOf(reason)
  88485. if(index > -1){//如果是forceVisibleReasons里的,就只是单纯取消之前设置的一定可见
  88486. object.forceVisibleReasons.splice(index, 1);
  88487. }else{
  88488. if(!object.unvisibleReasons.includes(reason)) object.unvisibleReasons.push(reason)
  88489. }
  88490. if(object.forceVisibleReasons.length) return
  88491. var visiBefore = object.visible
  88492. if(object.unvisibleReasons.length && visiBefore){
  88493. object.visible = false
  88494. //mapChange()
  88495. object.dispatchEvent({
  88496. type: 'isVisible',
  88497. visible:false,
  88498. reason,
  88499. })
  88500. }else if(object.unvisibleReasons.length ==0 && !visiBefore){
  88501. object.visible = true;
  88502. //mapChange()
  88503. object.dispatchEvent({
  88504. type: 'isVisible',
  88505. visible:true,
  88506. reason
  88507. })
  88508. }
  88509. }
  88510. } */
  88511. updateVisible(object, reason, ifShow, level=0, type){//当所有加入的条件都不为false时才显示. reason='force'一般是强制、临时的
  88512. if(!object.unvisibleReasons) object.unvisibleReasons = []; //如果length>0代表不可见
  88513. if(!object.visibleReasons) object.visibleReasons = []; //在同级时,优先可见
  88514. var update = function(){
  88515. //先按从高到低的level排列
  88516. object.unvisibleReasons = object.unvisibleReasons.sort((a,b)=>b.level-a.level);
  88517. object.visibleReasons = object.visibleReasons.sort((a,b)=>b.level-a.level);
  88518. var maxVisiLevel = object.visibleReasons[0] ? object.visibleReasons[0].level : -1;
  88519. var maxunVisiLevel = object.unvisibleReasons[0] ? object.unvisibleReasons[0].level : -1;
  88520. var shouldVisi = maxVisiLevel >= maxunVisiLevel;
  88521. var visiBefore = object.visible;
  88522. if(visiBefore != shouldVisi){
  88523. object.visible = shouldVisi;
  88524. object.dispatchEvent({
  88525. type: 'isVisible',
  88526. visible: shouldVisi,
  88527. reason,
  88528. });
  88529. }
  88530. };
  88531. if(ifShow){
  88532. var index = object.unvisibleReasons.findIndex(e=>e.reason == reason);
  88533. if(index > -1){
  88534. type = 'cancel';
  88535. object.unvisibleReasons.splice(index, 1);
  88536. }
  88537. if(type == 'add' ){
  88538. if(!object.visibleReasons.some(e=>e.reason == reason)){
  88539. object.visibleReasons.push({reason,level});
  88540. }
  88541. }
  88542. }else {
  88543. var index = object.visibleReasons.findIndex(e=>e.reason == reason);
  88544. if(index > -1){
  88545. type = 'cancel';
  88546. object.visibleReasons.splice(index, 1);
  88547. }
  88548. if(type != 'cancel' ){
  88549. if(!object.unvisibleReasons.some(e=>e.reason == reason)){
  88550. object.unvisibleReasons.push({reason,level});
  88551. }
  88552. }
  88553. }
  88554. update();
  88555. }
  88556. getObjVisiByReason(object,reason){//获取在某条件下是否可见. 注: 用户在数据集选择可不可见为"datasetSelection"
  88557. if(object.visible)return true
  88558. else {
  88559. return !object.unvisibleReasons || !object.unvisibleReasons.some(e=>e.reason == reason)
  88560. }
  88561. }
  88562. /* 大规模WebGL应用引发浏览器崩溃的几种情况及解决办法
  88563. https://blog.csdn.net/weixin_30378311/article/details/94846947 */
  88564. render(params={}){//add params
  88565. if(Potree.measureTimings) performance.mark("render-start");
  88566. if(this.outlinePass.selectedObjects.length && !params.screenshot){
  88567. this.composer.render(this.inputHandler.interactiveScenes.concat(this.scene.scene).concat(viewer.scene.scenePointCloud), null, this.viewports, this.renderDefault.bind(this));
  88568. }else {
  88569. this.renderDefault(params);
  88570. }
  88571. if(Potree.measureTimings){
  88572. performance.mark("render-end");
  88573. performance.measure("render", "render-start", "render-end");
  88574. }
  88575. }
  88576. startScreenshot(info={}, width=800, height=400, compressRatio){//add
  88577. let deferred = info.deferred || $.Deferred();
  88578. let viewerMaster = info.map ? this.mapViewer : this; //截图主体
  88579. let useMap = info.type == 'measure' || info.map;
  88580. if(this.images360.flying){//如果在飞,飞完再截图
  88581. info.deferred = deferred;
  88582. let f = ()=>{
  88583. this.startScreenshot(info, width, height, compressRatio);
  88584. this.images360.removeEventListener('cameraMoveDone', f);
  88585. };
  88586. this.images360.addEventListener('cameraMoveDone', f); //once
  88587. return deferred.promise()
  88588. }
  88589. var sid = Date.now();
  88590. //抗锯齿待加 1 post处理 2截图大张再抗锯齿缩小
  88591. console.log('startScreenshot: '+sid);
  88592. let updateCamera = ()=>{
  88593. this.viewports.forEach(e=>{
  88594. e.view.applyToCamera(e.camera); //因为fly时只更新了view所以要强制更新下camera
  88595. this.dispatchEvent({ //update map and sprite
  88596. type: "camera_changed",
  88597. camera: e.camera,
  88598. viewport : e,
  88599. changeInfo:{positionChanged:true,changed:true}
  88600. });
  88601. });
  88602. };
  88603. let screenshot = ()=>{
  88604. useMap && (viewer.mapViewer.needRender = true);
  88605. let { dataUrl } = viewerMaster.makeScreenshot( new Vector2$1(width,height), null, compressRatio );
  88606. if(!Potree.settings.isOfficial){
  88607. Common.downloadFile(dataUrl, 'screenshot.jpg');
  88608. }
  88609. var finish = ()=>{
  88610. oldStates.viewports.forEach(old=>{//恢复相机
  88611. var viewport = viewports.find(v=>v.name == old.name);
  88612. viewport.left = old.left;
  88613. viewport.width = old.width;
  88614. viewport.view.copy(old.view);
  88615. viewport.view.applyToCamera(viewport.camera);
  88616. });
  88617. viewer.updateScreenSize({forceUpdateSize:true});//更新像素
  88618. /* oldStates.viewports.forEach(old=>{//恢复相机
  88619. var viewport = [mapViewport, mainViewport].find(v=>v.name == old.name);
  88620. this.dispatchEvent({ //update map
  88621. type: "camera_changed",
  88622. camera: viewport.camera,
  88623. viewport : viewport
  88624. })
  88625. }) */
  88626. updateCamera();
  88627. deferred.resolve(dataUrl);
  88628. console.log('screenshot done: '+sid);
  88629. };
  88630. {//恢复:
  88631. if(info.type == 'measure'){
  88632. this.scene.measurements.forEach(e=>this.updateVisible(e, 'screenshot',true));
  88633. info.measurement.setSelected(false, 'screenshot');
  88634. }
  88635. this.images360.panos.forEach(pano=>{
  88636. viewer.updateVisible(pano, 'screenshot', true);
  88637. });
  88638. viewer.updateVisible(this.reticule, 'screenshot', true);
  88639. if(useMap){
  88640. viewer.updateVisible(this.mapViewer.cursor, 'screenshot', true);
  88641. if(oldStates.attachedToViewer != this.mapViewer.attachedToViewer){
  88642. if(info.type == 'measure'){
  88643. this.mapViewer.attachToMainViewer(false );
  88644. }
  88645. }
  88646. mapViewport.camera.zoom = oldStates.mapZoom;
  88647. mapViewport.camera.updateProjectionMatrix();
  88648. }
  88649. if(Potree.settings.displayMode == 'showPanos') {
  88650. viewer.images360.flyToPano({pano:oldStates.pano, duration:0, callback:()=>{
  88651. finish();
  88652. }});
  88653. }else {
  88654. finish();
  88655. }
  88656. }
  88657. };// screenshot end
  88658. let mapViewport;
  88659. let mainViewport = this.mainViewport;
  88660. let viewports = [mainViewport];
  88661. let oldStates = {
  88662. viewports : [mainViewport.clone()],
  88663. pano: Potree.settings.displayMode == 'showPanos' ? viewer.images360.currentPano : null,
  88664. };
  88665. if(useMap){
  88666. mapViewport = this.mapViewer.viewports[0];
  88667. viewports.push(mapViewport);
  88668. oldStates.viewports.push(mapViewport.clone());
  88669. oldStates.attachedToViewer = this.mapViewer.attachedToViewer;
  88670. oldStates.mapZoom = mapViewport.camera.zoom;
  88671. viewer.updateVisible(this.mapViewer.cursor, 'screenshot', false);//令mapCursor不可见
  88672. }
  88673. if(info.hideMarkers){
  88674. this.images360.panos.forEach(pano=>{//令漫游点不可见
  88675. viewer.updateVisible(pano, 'screenshot', false);
  88676. });
  88677. }
  88678. viewer.updateVisible(this.reticule, 'screenshot', false);//令reticule不可见
  88679. if(info.type == 'measure'){//要截图双屏
  88680. this.scene.measurements.forEach(e=>this.updateVisible(e,'screenshot',e == info.measurement) );
  88681. info.measurement.setSelected(true, 'screenshot');
  88682. //因为分屏后位置才最终确定,才能确定是否显示出floorplan所以先分屏
  88683. if(Potree.settings.floorplanEnable){
  88684. this.mapViewer.attachToMainViewer(true, 'measure', 0.5 );
  88685. }
  88686. viewer.updateScreenSize({forceUpdateSize:true, width, height}); //更新viewports相机透视 使focusOnObject在此窗口大小下
  88687. let begin = ()=>{
  88688. useMap = this.mapViewer.attachedToViewer;
  88689. updateCamera();
  88690. let waitTime = Potree.settings.displayMode == 'showPointCloud' ? 500 : 0; //等点云加载 网速差的话还是加载稀疏 是否要用最高质量点云
  88691. if(useMap){
  88692. let waitMap = ()=>{
  88693. //console.log('waitMap: '+sid)
  88694. this.mapViewer.waitLoadDone(screenshot.bind(this));//等待地图所有加载完
  88695. };
  88696. setTimeout(waitMap.bind(this), waitTime);
  88697. }else {
  88698. setTimeout(screenshot.bind(this), waitTime);
  88699. }
  88700. };
  88701. let {promise}= this.focusOnObject(info.measurement, 'measure', 0, {basePanoSize:1024} );//注意:不同角度截图 得到三维的会不一样,因为focusOnObject是根据方向的
  88702. promise.done(()=>{
  88703. //console.log('promise.done')
  88704. //根据当前位置更新floorplan显示
  88705. //console.log('view Pos ', this.mainViewport.view.position.toArray())
  88706. this.updateDatasetAt(true);
  88707. this.modules.SiteModel.updateEntityAt(true);
  88708. //this.updateFpVisiDatasets()
  88709. //console.log('currentFloor', this.modules.SiteModel.currentFloor, 'currentDataset', this.atDatasets )
  88710. let floorplanShowed = this.mapViewer.mapLayer.maps.some(e => e.name.includes('floorplan') && e.objectGroup.visible);
  88711. if(!floorplanShowed && this.mapViewer.attachedToViewer){
  88712. this.mapViewer.attachToMainViewer(false); //取消分屏
  88713. viewer.updateScreenSize({forceUpdateSize:true, width, height}); //更新viewports相机透视
  88714. let {promise} = this.focusOnObject(info.measurement, 'measure', 0, {basePanoSize:1024} );//因画面比例更改,重新focus
  88715. promise.done(()=>{
  88716. begin();
  88717. });
  88718. }else {
  88719. begin();
  88720. }
  88721. });
  88722. }else {
  88723. screenshot();
  88724. }
  88725. /*
  88726. 测量线的截图因为要调用分屏的,会改变画面
  88727. 但是普通截图的话,不会改变画面
  88728. */
  88729. return deferred.promise()
  88730. }
  88731. focusOnObject(object, type, duration, o={} ) {
  88732. //飞向热点、测量线等 。
  88733. //console.log('focusOnObject: ', object, type)
  88734. let deferred = o.deferred || $.Deferred();
  88735. let target = new Vector3, //相机focus的位置
  88736. position = new Vector3, //相机最终位置
  88737. dis; //相机距离目标
  88738. duration = duration == void 0 ? 1000 : duration;
  88739. let camera = viewer.scene.getActiveCamera();
  88740. let cameraPos = camera.position.clone();
  88741. let getPosWithFullBound = (points, boundingBox, target, cameraPos )=>{//使boundingBox差不多占满屏幕时的相机到target的距离
  88742. // points 和 boundingBox 至少有一个
  88743. let scale;
  88744. if(o.dontChangeCamDir){
  88745. var inv = camera.matrixWorldInverse;
  88746. }else {
  88747. var cameraTemp = camera.clone();
  88748. cameraTemp.position.copy(cameraPos);
  88749. cameraTemp.lookAt(target);
  88750. cameraTemp.updateMatrix();
  88751. cameraTemp.updateMatrixWorld();
  88752. //对镜头的bound
  88753. var inv = cameraTemp.matrixWorldInverse;
  88754. }
  88755. var bound = new Box3();
  88756. if(points){//使用points得到的bound更小 //如果points和boundingbox的差别较大,尤其使target和points中心不一致,那么points不一定会刚好在boundingbox内
  88757. points.forEach(e=>{
  88758. var p = e.clone().applyMatrix4(inv);
  88759. bound.expandByPoint(p);
  88760. });
  88761. scale = 1.3;
  88762. }else {
  88763. bound = boundingBox.applyMatrix4(inv);
  88764. scale = 0.9;
  88765. }
  88766. let boundSize = bound.getSize(new Vector3);
  88767. {
  88768. boundSize.x *= scale; //稍微放大一些,不然会靠到屏幕边缘
  88769. boundSize.y *= scale;
  88770. let min = 0.0001;
  88771. boundSize.x = Math.max(min, boundSize.x);
  88772. boundSize.y = Math.max(min, boundSize.y);
  88773. }
  88774. let aspect = boundSize.x / boundSize.y;
  88775. if(camera.aspect > aspect){//视野更宽则用bound的纵向来决定
  88776. dis = boundSize.y/2/ Math.tan(MathUtils.degToRad(camera.fov / 2)) + boundSize.z/2;
  88777. }else {
  88778. let hfov = cameraLight.getHFOVForCamera(camera, true);
  88779. dis = boundSize.x/2 / Math.tan(hfov / 2) + boundSize.z/2;
  88780. }
  88781. dis = Math.max(0.1,dis);
  88782. //三个顶点以上的由于measure的中心不等于bound的中心,所以点会超出bound外。 且由于视椎近大远小,即使是两个点的,bound居中后线看上去仍旧不居中.
  88783. //获得相机最佳位置
  88784. let dir;
  88785. if(o.dontChangeCamDir){
  88786. dir = viewer.mainViewport.view.direction.negate();
  88787. }else {
  88788. dir = new Vector3().subVectors(cameraPos, target).normalize();
  88789. }
  88790. if(o.dontLookUp && dir.z < 0){
  88791. dir.negate();
  88792. }
  88793. position.copy(target).add(dir.multiplyScalar(dis));
  88794. if(false){//打开以检查box
  88795. if(!this.boundBox){//调试
  88796. this.boundBox = new Mesh(new BoxGeometry(1,1,1,1));
  88797. this.boundBox.material.wireframe = true;
  88798. this.boundBox.up.set(0,0,1);
  88799. //viewer.updateVisible(this.boundBox, 'hidden', true)//打开以检查box
  88800. this.setObjectLayers(this.boundBox,'sceneObjects');
  88801. this.scene.scene.add(this.boundBox);
  88802. }
  88803. this.boundBox.position.copy(target);
  88804. this.boundBox.scale.copy(boundSize);
  88805. this.boundBox.lookAt(position);
  88806. }
  88807. return position
  88808. };
  88809. if(this.images360.flying){
  88810. let f = ()=>{
  88811. this.focusOnObject(object, type, duration, $.extend(o,{deferred}));
  88812. this.images360.removeEventListener('cameraMoveDone',f);
  88813. };
  88814. this.images360.addEventListener('cameraMoveDone',f);
  88815. return {promise: deferred.promise() }
  88816. }
  88817. if (type == 'measure') {
  88818. target.copy(object.getCenter());
  88819. //试试改变位置,直视测量线。能避免倾斜角度造成的非常不居中、以及看不到面的情况
  88820. if(object.facePlane/* && window.focusMeasureFaceToIt */){
  88821. let normal;
  88822. if(object.facePlane){
  88823. normal = object.facePlane.normal.clone();
  88824. }
  88825. let angle = this.scene.view.direction.angleTo(normal);
  88826. let minDiff = MathUtils.degToRad(60);
  88827. //console.log('angle',angle)
  88828. if(angle>minDiff && angle<Math.PI-minDiff){//当几乎正对时就不执行
  88829. if(angle<Math.PI/2){ //在背面
  88830. normal.negate();
  88831. }
  88832. let dir = new Vector3().subVectors(camera.position, target).normalize();
  88833. let newDir = new Vector3().addVectors(dir,normal);//两个角度的中间
  88834. cameraPos.copy(target.clone().add(newDir));
  88835. }
  88836. }else if(object.points.length == 2){ //线段
  88837. let lineDir = new Vector3().subVectors(object.points[0],object.points[1]).normalize();
  88838. let angle = this.scene.view.direction.angleTo(lineDir);
  88839. let maxDiff = Math.PI*0.25;// 45度
  88840. if(angle<maxDiff || angle>Math.PI-maxDiff){//当几乎正对时就不执行
  88841. if(angle>Math.PI/2){ //令dir和lineDir成钝角
  88842. lineDir.negate();
  88843. }
  88844. let dir = new Vector3().subVectors(camera.position, target).normalize();
  88845. let mid = new Vector3().addVectors(lineDir, dir).normalize(); //中间法向量(如果刚好dir和lineDir反向,那得到的为零向量,就不移动了,但一般不会酱紫吧)
  88846. let newDir = new Vector3().addVectors(dir, mid);
  88847. cameraPos.copy(target.clone().add(newDir));
  88848. }
  88849. }else {
  88850. console.error('measure 没有facePlane points点数还不为2?');
  88851. }
  88852. position = getPosWithFullBound(object.points, null, target, cameraPos );
  88853. if(this.mapViewer/* .attachedToViewer */){
  88854. //console.log('mapFocusOn: '+target.toArray())
  88855. const minBound = new Vector2$1(4,4);//针对垂直线,在地图上只有一个点
  88856. //原始的bound
  88857. let boundOri = new Box3();
  88858. object.points.forEach(e=>{
  88859. boundOri.expandByPoint(e);
  88860. });
  88861. let boundSizeOri = boundOri.getSize(new Vector3);
  88862. let boundSizeMap = boundSizeOri.clone().multiplyScalar(2);
  88863. boundSizeMap.x = Math.max(minBound.x, boundSizeMap.x );
  88864. boundSizeMap.y = Math.max(minBound.y, boundSizeMap.y );
  88865. this.mapViewer.moveTo(target.clone(), boundSizeMap, duration);
  88866. }
  88867. if(Potree.settings.displayMode == 'showPointCloud'){ //点云
  88868. let minDis = 0.3;
  88869. //if(o.checkIntersect){
  88870. let checkIntersect = ( )=>{
  88871. let intersect = this.inputHandler.ifBlockedByIntersect(position, null , true, target);// 不一定准确
  88872. if(intersect){
  88873. let blockCount = 0, unblockCount = 0, visi;
  88874. for(let i=0;i<object.points.length;i++){ //如果顶点超过一半不可见,就要更改位置
  88875. let p = object.points[i];
  88876. let blocked = this.inputHandler.ifBlockedByIntersect(p, 0.3 , true, position, 4);
  88877. if(blocked){
  88878. blockCount ++;
  88879. if(blockCount / object.points.length >= 0.5){
  88880. visi = false;
  88881. break
  88882. }
  88883. }else {
  88884. unblockCount ++;
  88885. if(unblockCount / object.points.length > 0.5){
  88886. visi = true;
  88887. break
  88888. }
  88889. }
  88890. }
  88891. if(visi == void 0){
  88892. visi = unblockCount / object.points.length > 0.5;
  88893. }
  88894. let shrink = ()=>{
  88895. let dir = new Vector3().subVectors(position, target).normalize().multiplyScalar(intersect.distance);
  88896. position.copy(target).add(dir);
  88897. console.log('checkIntersect newPos', position.clone() );
  88898. };
  88899. if(!visi){//更改位置距离target如果小于最小距离,需要反向。 否则直接缩短距离。
  88900. if(intersect.distance < minDis ){
  88901. console.log('检测到intersect 反向', intersect.distance );
  88902. let position1 = position.clone();
  88903. let dir = new Vector3().subVectors(position, target);
  88904. position.copy(target).sub(dir);
  88905. let intersect2 = this.inputHandler.ifBlockedByIntersect(position, null , true, target);// 不一定准确
  88906. if(intersect2){
  88907. if(intersect2.distance < intersect.distance ){
  88908. position.copy(position1);//恢复
  88909. }
  88910. shrink();
  88911. }
  88912. }else {
  88913. shrink();
  88914. }
  88915. }
  88916. }
  88917. };
  88918. checkIntersect();
  88919. //}
  88920. }else if(Potree.settings.displayMode == 'showPanos'){//全景 (比较难校准)
  88921. let pano = viewer.images360.fitPanoTowardPoint({
  88922. /*point : target, //不使用目标点来判断是因为缺少measure角度的信息。比如虽然可以靠近线的中心,但是线朝向屏幕,那几乎就是一个点了。
  88923. //bestDistance : dis * 0.5, //乘以小数是为了尽量靠近
  88924. boundSphere: boundOri.getBoundingSphere(new THREE.Sphere), */
  88925. target,
  88926. point : position,
  88927. bestDistance : 0 ,
  88928. checkIntersect: o.checkIntersect
  88929. });
  88930. if(pano){
  88931. viewer.images360.flyToPano({pano, target, duration, deferred, dontMoveMap:true , basePanoSize:o.basePanoSize});//dontMoveMap不要移动map,否则flytopano会自动在map中focus到漫游点的位置,而非测量线了
  88932. }
  88933. if(viewer.images360.currentPano == pano){
  88934. let dis1 = viewer.images360.currentPano.position.distanceTo(target);
  88935. let dis2 = position.distanceTo(target);
  88936. console.log('dis1 / dis2',dis1 / dis2, 'dis1-dis2', dis1-dis2);
  88937. return {mag: (dis1 / dis2 > 1.5 && dis1-dis2>10)? 'tooFar' : 'posNoChange', promise : deferred.promise() }
  88938. }else {
  88939. return {promise : deferred.promise()}
  88940. }
  88941. //出现过到达位置后测量线标签闪烁的情况
  88942. }
  88943. } else if (type == 'tag' || type == 'point') {
  88944. //dimension = 1
  88945. target.copy(object.position);
  88946. let bestDistance = o.distance || 3;
  88947. if(!o.dontMoveMap && this.mapViewer){
  88948. //console.log('mapFocusOn: '+target.toArray())
  88949. this.mapViewer.moveTo(target.clone(), null, duration);
  88950. }
  88951. if(Potree.settings.displayMode == 'showPointCloud'){
  88952. if(o.dontChangePos){
  88953. position.copy(cameraPos);
  88954. }else {
  88955. dis = bestDistance;
  88956. let dir = o.direction ? o.direction.clone().negate() : this.mainViewport.view.direction.negate();// */new THREE.Vector3().subVectors(camera.position, target).normalize()
  88957. if(o.dontLookUp && dir.z<0) dir.z *= -1;
  88958. position.copy(target).add(dir.multiplyScalar(dis));
  88959. }
  88960. /* if(o.checkIntersect){//识别被点云遮住的话
  88961. let ifShelter
  88962. while(1){
  88963. ifShelter = this.inputHandler.ifBlockedByIntersect(target, o.checkMargin, true, position)
  88964. if(ifShelter){
  88965. if(dis > 0.5){
  88966. dis --
  88967. dir.dot(ifShelter.normal)>0 ? dir.copy(ifShelter.normal).negate() : dir.copy(ifShelter.normal);
  88968. position.copy(target).add(dir.multiplyScalar(dis))
  88969. }
  88970. }
  88971. }
  88972. } */
  88973. }else if(Potree.settings.displayMode == 'showPanos'){
  88974. let pano = viewer.images360.fitPanoTowardPoint({
  88975. point : target,
  88976. bestDistance //越近越好,但不要太近,bestDistance左右差不多
  88977. });
  88978. pano && viewer.images360.flyToPano({pano, target, duration, deferred, dontMoveMap:true , basePanoSize:o.basePanoSize });
  88979. return {promise:deferred.promise() }
  88980. }
  88981. }else if(object.boundingBox && type == 'boundingBox'){//使屏幕刚好看全boundingBox
  88982. target = object.boundingBox.getCenter(new Vector3);
  88983. position = getPosWithFullBound(object.points, object.boundingBox, target, cameraPos );
  88984. if(Potree.settings.displayMode == 'showPanos'){//全景 (比较难校准)
  88985. let pano = viewer.images360.fitPanoTowardPoint({
  88986. point : position,
  88987. bestDistance : 0 ,
  88988. });
  88989. pano && viewer.images360.flyToPano({pano, target, duration, deferred, dontMoveMap:true , basePanoSize:o.basePanoSize});//dontMoveMap不要移动map,否则flytopano会自动在map中focus到漫游点的位置,而非测量线了
  88990. if(!pano){
  88991. console.error('no pano');
  88992. }
  88993. return {promise:deferred.promise() }
  88994. //出现过到达位置后测量线标签闪烁的情况
  88995. }else {
  88996. /* if(o.dontChangeCamDir){
  88997. target = null
  88998. } */
  88999. }
  89000. }
  89001. /*} else if(dimension == 2){//线
  89002. }else if(dimension == 3){//面
  89003. }else{//立体
  89004. } */
  89005. viewer.scene.view.setView({position, target, duration, callback:()=>{
  89006. //console.log('focusOnObjectSuccess: '+object.name, type)
  89007. deferred.resolve();
  89008. }
  89009. });
  89010. this.dispatchEvent({type:'focusOnObject', CamTarget:target, position}); //给controls发送信息
  89011. return {promise:deferred.promise()}
  89012. }
  89013. flyToDataset(o={}){
  89014. var pointcloud;
  89015. if(o instanceof Object3D) pointcloud = o;
  89016. else if(o.pointcloud) pointcloud = o.pointcloud;
  89017. else pointcloud = this.scene.pointclouds.find(p => p.dataset_id == o.id);
  89018. let duration = o.duration == void 0 ? 1000 : o.duration;
  89019. var center = pointcloud.bound.getCenter(new Vector3);
  89020. let position;
  89021. let getPano = ()=>{//获取离中心最近的pano
  89022. let request = [];
  89023. let rank = [
  89024. Images360.scoreFunctions.distanceSquared({position: center})
  89025. ];
  89026. let r = Common.sortByScore(pointcloud.panos, request, rank);
  89027. if(r && r.length){
  89028. return r[0].item
  89029. }
  89030. };
  89031. if(Potree.settings.displayMode == 'showPanos'){
  89032. let pano = getPano();
  89033. if(pano){
  89034. if(pano == this.images360.currentPano) return 'posNoChange'
  89035. this.images360.flyToPano({
  89036. pano
  89037. });
  89038. }else return false
  89039. }else {
  89040. let target;
  89041. position = center;
  89042. if(pointcloud.panosBound){
  89043. let panosCenter = pointcloud.panosBound.center; //pano集中的地方,也就是真正有点云的地方
  89044. position = panosCenter.clone();
  89045. /* let ratio = 0.2
  89046. position.z = center.z * ratio + panosCenter.z * (1-ratio) //因为panos一般比较低,为了不让相机朝下时看不到点云,加一丢丢中心高度
  89047. */
  89048. let pano = getPano();
  89049. if(pano){
  89050. target = pano.position; //针对像隧道一样的场景, 中心点还是panosCenter都在没有点云的地方,所以还是看向其中一个漫游点好。
  89051. position.z = target.z; //水平, 避免朝上或朝下
  89052. }
  89053. }
  89054. if(this.modules.Clip.editing){
  89055. position.z = center.z; //剪裁时在中心高度,因为以点云为重点
  89056. this.modules.Clip.bus.dispatchEvent({type:'flyToPos', position });
  89057. }else {
  89058. if(math.closeTo(position, this.images360.position)) return 'posNoChange'
  89059. viewer.scene.view.setView({position, target, duration });
  89060. o.dontMoveMap || viewer.mapViewer.moveTo(position.clone(), null , duration);
  89061. }
  89062. }
  89063. return true
  89064. }
  89065. resolveTimings(timestamp){
  89066. if(Potree.measureTimings){
  89067. if(!this.toggle){
  89068. this.toggle = timestamp;
  89069. }
  89070. let duration = timestamp - this.toggle;
  89071. if(duration > 1000.0){
  89072. let measures = performance.getEntriesByType("measure");
  89073. let names = new Set();
  89074. for(let measure of measures){
  89075. names.add(measure.name);
  89076. }
  89077. let groups = new Map();
  89078. for(let name of names){
  89079. groups.set(name, {
  89080. measures: [],
  89081. sum: 0,
  89082. n: 0,
  89083. min: Infinity,
  89084. max: -Infinity
  89085. });
  89086. }
  89087. for(let measure of measures){
  89088. let group = groups.get(measure.name);
  89089. group.measures.push(measure);
  89090. group.sum += measure.duration;
  89091. group.n++;
  89092. group.min = Math.min(group.min, measure.duration);
  89093. group.max = Math.max(group.max, measure.duration);
  89094. }
  89095. let glQueries = Potree.resolveQueries(this.renderer.getContext());
  89096. for(let [key, value] of glQueries){
  89097. let group = {
  89098. measures: value.map(v => {return {duration: v}}),
  89099. sum: value.reduce( (a, i) => a + i, 0),
  89100. n: value.length,
  89101. min: Math.min(...value),
  89102. max: Math.max(...value)
  89103. };
  89104. let groupname = `[tq] ${key}`;
  89105. groups.set(groupname, group);
  89106. names.add(groupname);
  89107. }
  89108. for(let [name, group] of groups){
  89109. group.mean = group.sum / group.n;
  89110. group.measures.sort( (a, b) => a.duration - b.duration );
  89111. if(group.n === 1){
  89112. group.median = group.measures[0].duration;
  89113. }else if(group.n > 1){
  89114. group.median = group.measures[parseInt(group.n / 2)].duration;
  89115. }
  89116. }
  89117. let cn = Array.from(names).reduce( (a, i) => Math.max(a, i.length), 0) + 5;
  89118. let cmin = 10;
  89119. let cmed = 10;
  89120. let cmax = 10;
  89121. let csam = 6;
  89122. let message = ` ${"NAME".padEnd(cn)} |`
  89123. + ` ${"MIN".padStart(cmin)} |`
  89124. + ` ${"MEDIAN".padStart(cmed)} |`
  89125. + ` ${"MAX".padStart(cmax)} |`
  89126. + ` ${"SAMPLES".padStart(csam)} \n`;
  89127. message += ` ${"-".repeat(message.length) }\n`;
  89128. names = Array.from(names).sort();
  89129. for(let name of names){
  89130. let group = groups.get(name);
  89131. let min = group.min.toFixed(3);
  89132. let median = group.median.toFixed(3);
  89133. let max = group.max.toFixed(3);
  89134. let n = group.n;
  89135. message += ` ${name.padEnd(cn)} |`
  89136. + ` ${min.padStart(cmin)} |`
  89137. + ` ${median.padStart(cmed)} |`
  89138. + ` ${max.padStart(cmax)} |`
  89139. + ` ${n.toString().padStart(csam)}\n`;
  89140. }
  89141. message += `\n`;
  89142. console.log(message);
  89143. performance.clearMarks();
  89144. performance.clearMeasures();
  89145. this.toggle = timestamp;
  89146. }
  89147. }
  89148. }
  89149. loop(timestamp){
  89150. if(this.stats){
  89151. this.stats.begin();
  89152. }
  89153. if(Potree.measureTimings){
  89154. performance.mark("loop-start");
  89155. }
  89156. this.update(this.clock.getDelta(), timestamp);
  89157. this.magnifier.render();
  89158. this.render();
  89159. // let vrActive = viewer.renderer.xr.isPresenting;
  89160. // if(vrActive){
  89161. // this.update(this.clock.getDelta(), timestamp);
  89162. // this.render();
  89163. // }else{
  89164. // this.update(this.clock.getDelta(), timestamp);
  89165. // this.render();
  89166. // }
  89167. if(Potree.measureTimings){
  89168. performance.mark("loop-end");
  89169. performance.measure("loop", "loop-start", "loop-end");
  89170. }
  89171. this.resolveTimings(timestamp);
  89172. Potree.framenumber++;
  89173. if(this.stats){
  89174. this.stats.end();
  89175. }
  89176. }
  89177. postError(content, params = {}){
  89178. let message = this.postMessage(content, params);
  89179. message.element.addClass("potree_message_error");
  89180. return message;
  89181. }
  89182. postMessage(content, params = {}){
  89183. let message = new Message(content);
  89184. let animationDuration = 100;
  89185. message.element.css("display", "none");
  89186. message.elClose.click( () => {
  89187. message.element.slideToggle(animationDuration);
  89188. let index = this.messages.indexOf(message);
  89189. if(index >= 0){
  89190. this.messages.splice(index, 1);
  89191. }
  89192. });
  89193. this.elMessages.prepend(message.element);
  89194. message.element.slideToggle(animationDuration);
  89195. this.messages.push(message);
  89196. if(params.duration !== undefined){
  89197. let fadeDuration = 500;
  89198. let slideOutDuration = 200;
  89199. setTimeout(() => {
  89200. message.element.animate({
  89201. opacity: 0
  89202. }, fadeDuration);
  89203. message.element.slideToggle(slideOutDuration);
  89204. }, params.duration);
  89205. }
  89206. return message;
  89207. }
  89208. getBoundingBox (pointclouds) {
  89209. //可以直接返回viewer.bound
  89210. if(!this.bound){
  89211. this.updateModelBound();
  89212. }
  89213. return this.bound.boundingBox.clone()//this.scene.getBoundingBox(pointclouds);
  89214. };
  89215. updateModelBound(){
  89216. this.bound = Utils.computePointcloudsBound(this.scene.pointclouds);
  89217. if(Potree.settings.boundAddObjs){//加上obj的bound
  89218. this.objs.children.forEach(e=>{
  89219. this.bound.boundingBox.union(e.boundingBox.clone().applyMatrix4(e.matrixWorld));
  89220. });
  89221. this.bound.boundingBox.getSize(this.bound.boundSize);
  89222. this.bound.boundingBox.getCenter(this.bound.center);
  89223. }
  89224. viewer.farWhenShowPano = this.bound.boundSize.length() * 10;//全景漫游时要能看到整个skybox 原本*2的但对于距离特远的数据集需要乘大一些否则会黑面
  89225. let boundPlane = new Box3();
  89226. boundPlane.expandByPoint(this.bound.boundingBox.min.clone());//最低高度为bound的最低
  89227. boundPlane.expandByPoint(this.bound.boundingBox.max.clone().setZ(this.bound.center.z));//最高高度为bound的中心高度
  89228. FirstPersonControls.boundPlane = boundPlane;
  89229. FirstPersonControls.standardSpeed = MathUtils.clamp( Math.sqrt(this.bound.boundSize.length() )/ 100 , 0.02,0.5); //在这个boundPlane中的速度
  89230. viewer.scene.pointclouds.forEach(e=>{//海拔范围
  89231. e.material.heightMin = this.bound.boundingBox.min.z;
  89232. e.material.heightMax = this.bound.boundingBox.max.z;
  89233. });
  89234. this.dispatchEvent({type:'updateModelBound'});
  89235. }
  89236. waitForLoad(object, isLoadedCallback){//等待加载时显示loading。主要是贴图
  89237. this.waitQueue.push({
  89238. object,
  89239. isLoadedCallback,
  89240. });
  89241. 1 === this.waitQueue.length && this.dispatchEvent({type:"loading", show:true});
  89242. }
  89243. ifAllLoaded(object){
  89244. if(this.waitQueue.length>0){
  89245. this.waitQueue = this.waitQueue.filter(function(e) {
  89246. return !e.isLoadedCallback()
  89247. });
  89248. }
  89249. 0 === this.waitQueue.length && this.dispatchEvent({type:"loading", show:false});
  89250. }
  89251. setView(o={}){
  89252. let callback = ()=>{
  89253. if(o.displayMode){
  89254. Potree.settings.displayMode = o.displayMode;
  89255. }
  89256. o.callback && o.callback();
  89257. };
  89258. if(o.pano != void 0){//pano 权重高于 position
  89259. this.images360.flyToPano(o);
  89260. }else {
  89261. this.scene.view.setView($.extend({},o, {callback}));
  89262. }
  89263. }
  89264. //设置点云为标准模式
  89265. setPointStandardMat(state, pointDensity, fitPointsize){
  89266. console.log('setPointStandardMat',state);
  89267. if(state){
  89268. if(this.pointStatesBefore){
  89269. return console.error('已设置过pointStatesBefore!')
  89270. }
  89271. this.pointStatesBefore = {
  89272. opacity : new Map(),
  89273. size: new Map(),
  89274. density:Potree.settings.pointDensity,
  89275. useEDL:this.getEDLEnabled(),
  89276. shape: viewer.scene.pointclouds[0].material.shape
  89277. };
  89278. viewer.scene.pointclouds.forEach(e=>{
  89279. this.pointStatesBefore.opacity.set(e, e.temp.pointOpacity); //因为更改pointDensity时会自动变opacity,所以这项最先获取
  89280. this.pointStatesBefore.colorType = e.material.activeAttributeName;
  89281. fitPointsize && this.pointStatesBefore.size.set(e,e.temp.pointSize); //这项不一定有用,因为会被后期覆盖
  89282. });
  89283. if(pointDensity)Potree.settings.pointDensity = pointDensity; //万一之后切换到全景模式怎么办
  89284. if(fitPointsize)Potree.settings.sizeFitToLevel = true;
  89285. viewer.scene.pointclouds.forEach(e=>{
  89286. e.material.activeAttributeName = 'rgba';
  89287. e.material.shape = Potree.PointShape['SQUARE'];
  89288. fitPointsize && e.changePointSize(Potree.config.material.realPointSize, true);
  89289. e.changePointOpacity(1);
  89290. });
  89291. viewer.setEDLEnabled(false);
  89292. }else {
  89293. if(!this.pointStatesBefore){
  89294. return console.error('未设置过pointStatesBefore!')
  89295. }
  89296. Potree.settings.sizeFitToLevel = false;
  89297. if(pointDensity)Potree.settings.pointDensity = this.pointStatesBefore.pointDensity;
  89298. viewer.scene.pointclouds.forEach(e=>{
  89299. e.material.activeAttributeName = this.pointStatesBefore.colorType;
  89300. e.changePointOpacity(this.pointStatesBefore.opacity.get(e));
  89301. e.material.shape = this.pointStatesBefore.shape;
  89302. let size = this.pointStatesBefore.size.get(e);
  89303. if(size) e.changePointSize(size);
  89304. });
  89305. viewer.setEDLEnabled(this.pointStatesBefore.useEDL);
  89306. this.pointStatesBefore = null;
  89307. }
  89308. }
  89309. //调试时显示transformControl来调节object
  89310. transformObject(object){
  89311. let seleted = viewer.inputHandler.selection[0];
  89312. if(!object){//取消
  89313. seleted && viewer.inputHandler.toggleSelection(seleted);
  89314. return
  89315. }
  89316. if(seleted && seleted != object){//要更换,先取消
  89317. return this.transformObject(null)
  89318. }
  89319. if(!object.boundingBox){
  89320. object.boundingBox = new Box3(); //任意大小 只是为了显示黄色外框
  89321. //??? computeBoundingBox
  89322. }
  89323. if(!viewer.inputHandler.selection.includes(object)){
  89324. viewer.inputHandler.toggleSelection(object);
  89325. }
  89326. }
  89327. pointInWhichPointcloud(pos){//选择最接近中心的那个 使用boundSphere
  89328. let result = Common.sortByScore(this.scene.pointclouds,[],[
  89329. (pointcloud)=>{
  89330. var size = pointcloud.pcoGeometry.tightBoundingBox.getSize(new Vector3);
  89331. var center = pointcloud.bound.getCenter(new Vector3);
  89332. var length = size.length() / 2;
  89333. var dis = pos.distanceTo(center);
  89334. return length / dis //到数据集中心的距离占数据集大小越小越好
  89335. }
  89336. ]);
  89337. //若要求更准确的话,可以使用ifContainsPoint判断一下是否在bound中
  89338. let r = result && result[0];
  89339. return r.score > 1 ? result[0].item : null
  89340. }
  89341. /* addObjectTest1(){//加水管
  89342. if(Potree.settings.number == 't-8KbK1JjubE'){
  89343. let boundingBox = new THREE.Box3()
  89344. boundingBox.min.set(-1,-1,-1); boundingBox.max.set(1,1,1)
  89345. let radius = 0.08;
  89346. let radialSegments = 5
  89347. let radSegments = Math.PI*2 / radialSegments
  89348. var circlePts = [];//横截面
  89349. for(let i=0;i<radialSegments;i++){
  89350. let angle = radSegments * i;
  89351. circlePts.push(new THREE.Vector2(radius * Math.cos(angle), radius * Math.sin(angle) ))
  89352. }
  89353. var count = 0
  89354. var addMesh = (color, path, height)=>{//height:在path之上的高度,负数代表在path之下
  89355. var name = 'cylinder'+count
  89356. var mat = new THREE.MeshStandardMaterial({color, depthTest:false, roughness:0.4,metalness:0.5}) 
  89357. let linePath = path.map(e=>new THREE.Vector3().copy(e).setZ(e.z+height))
  89358. let geo = MeshDraw.getExtrudeGeo( circlePts, null,{ extrudePath:linePath, tension:0.2} )
  89359. var mesh = new THREE.Mesh(geo,mat);
  89360. mesh.name = name
  89361. window[name] = mesh
  89362. mesh.boundingBox = boundingBox
  89363. mesh.matrixAutoUpdate = false
  89364. mesh.matrix.copy(viewer.scene.pointclouds[0].transformMatrix)
  89365. mesh.matrixWorldNeedsUpdate = true
  89366. this.scene.scene.add(mesh);
  89367. count ++
  89368. }
  89369. let linePath, height
  89370. //地上管子 黄色
  89371. 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}
  89372. ,{"x":43.58,"y":27.7,"z":-0.97},{"x":40.22,"y":35.37,"z":-0.67}// 拐弯向右
  89373. , {"x":39.18,"y":36.71,"z":0.35},{"x":38.69,"y":36.04,"z":18.04} // 拐弯向上
  89374. ]
  89375. height = radius + 0.05;
  89376. addMesh('#b86', linePath, height)
  89377. //地下管子 藍色
  89378. 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}
  89379. ]
  89380. height = -0.5;
  89381. addMesh('#48a', linePath, height)
  89382. }
  89383. }
  89384. */
  89385. /* createRoomEv(){
  89386. const environment = new RoomEnvironment();
  89387. const pmremGenerator = new THREE.PMREMGenerator( this.renderer );
  89388. }
  89389. */
  89390. loadModel(fileInfo, done, onProgress_, onError){
  89391. let boundingBox = new Box3();
  89392. if(!Potree.settings.boundAddObjs){
  89393. boundingBox.min.set(-0.5,-0.5,-0.5); boundingBox.max.set(0.5,0.5,0.5);
  89394. }
  89395. let fileType = fileInfo.objurl ? 'obj' : 'glb';
  89396. let loadDone = (object, total, url)=>{
  89397. //object.scale.set(1,1,1);//先获取原始的大小时的boundingBox
  89398. object.updateMatrixWorld();
  89399. let weight = Math.round((total / 1024 / 1024) * 100) / 100;
  89400. if(fileInfo.id != void 0)object.dataset_id = fileInfo.id;
  89401. console.log(url.split('/').pop() ,/* fileInfo.id, */ '加载完毕, 模型数据量:' + weight + 'M');
  89402. this.setObjectLayers(object,'model');
  89403. object.traverse( ( child )=>{
  89404. if ( child instanceof Mesh ) {
  89405. child.renderOrder = Potree.config.renderOrders.model;
  89406. if(Potree.settings.boundAddObjs){
  89407. child.geometry.computeBoundingBox();
  89408. //console.log(child.matrixWorld.clone())
  89409. boundingBox.union(child.geometry.boundingBox.clone().applyMatrix4(child.matrixWorld)); //但感觉如果最外层object大小不为1,要还原下scale再乘
  89410. }//获取在scale为1时,表现出的大小
  89411. Common.makeTexDontResize(child.material.map);
  89412. //console.log(child.name, 'roughness',child.material.roughness,'metalness',child.material.metalness)
  89413. /* child.depthMat = child.material.clone()
  89414. child.standardMat = child.material
  89415. child.depthMat.onBeforeCompile = function ( shader ) {
  89416. console.log('vertexShader',shader.vertexShader)
  89417. console.log('fragmentShader',shader.fragmentShader)
  89418. shader.fragmentShader = `
  89419. ${shader.fragmentShader.replace(
  89420. 'gl_FragColor = vec4( outgoingLight, diffuseColor.a );',
  89421. 'diffuseColor.a = log(vViewPosition.z); gl_FragColor = vec4( outgoingLight, diffuseColor.a );'
  89422. )}
  89423. `;
  89424. console.log('fragmentShader1',shader.fragmentShader)
  89425. }; */
  89426. //暂时用这种材质:
  89427. if(fileInfo.unlit && (!(child.material instanceof MeshBasicMaterial) || fileType == 'glb')){
  89428. //let material = new THREE.MeshBasicMaterial({map:child.material.map})
  89429. let material = new BasicMaterial({map : child.material.map}); //很奇怪glb的图会使原本的MeshBasicMaterial 会偏暗,所以自己重新写
  89430. //child.material.dispose()
  89431. child.material = material;
  89432. }
  89433. if(child.material instanceof MeshStandardMaterial){
  89434. child.material.roughness = 0.6;
  89435. child.material.metalness = 0.3;
  89436. }
  89437. }
  89438. } );
  89439. object.name = fileInfo.name != void 0 ? fileInfo.name : 'obj';
  89440. this.objs.add(object);
  89441. object.boundingBox = boundingBox; //未乘上matrixWorld的本地boundingBox
  89442. if(fileInfo.transform){
  89443. let setTransfrom = (name)=>{
  89444. let value = fileInfo.transform[name];
  89445. if(!value)return
  89446. if(value instanceof Array){
  89447. object[name].fromArray(value);
  89448. }else {
  89449. object[name].copy(value);
  89450. }
  89451. };
  89452. setTransfrom('position');
  89453. setTransfrom('rotation');
  89454. setTransfrom('scale');
  89455. }
  89456. if(fileInfo.moveWithPointcloud){
  89457. object.updateMatrix();
  89458. object.matrixAutoUpdate = false;
  89459. object.matrix.premultiply(viewer.scene.pointclouds[0].transformMatrix); //默认跟随第一个数据集
  89460. object.matrixWorldNeedsUpdate = true;
  89461. }
  89462. done && done(object);
  89463. };
  89464. let onProgress = function ( xhr ) {
  89465. if ( xhr.lengthComputable ) {
  89466. let percentComplete = xhr.loaded / xhr.total * 100;
  89467. //console.log( Math.round(percentComplete, 2) + '% downloaded' );
  89468. onProgress_ && onProgress_(percentComplete);
  89469. }
  89470. };
  89471. if(fileType == 'obj'){
  89472. /* manager.onProgress = function ( item, loaded, total ) {
  89473. console.log( item, loaded, total );
  89474. }; */
  89475. /* let onError = function ( xhr ) {
  89476. }; */
  89477. loaders.mtlLoader.load( fileInfo.mtlurl , (materials)=>{
  89478. materials.preload();
  89479. loaders.objLoader.setMaterials( materials ).load(fileInfo.objurl, (object, total)=>{
  89480. loadDone(object, total, fileInfo.objurl);
  89481. });
  89482. } , onProgress, onError );
  89483. }else if(fileType == 'glb'){
  89484. loaders.glbLoader.unlitMat = true;//!!fileInfo.unlit
  89485. loaders.glbLoader.load(fileInfo.glburl, ( gltf, total )=>{ //.setPath( Potree.resourcePath + '/models/glb/' );
  89486. //console.log('loadGLTF', gltf)
  89487. loadDone(gltf.scene, total, fileInfo.glburl);
  89488. }, onProgress, onError);
  89489. }
  89490. /* viewer.onGUILoaded(() => {
  89491. // Add entries to object list in sidebar
  89492. let tree = $(`#jstree_scene`);
  89493. let parentNode = "other";
  89494. let bunnyID = tree.jstree('create_node', parentNode, {
  89495. text: "Bunny Textured",
  89496. icon: `${Potree.resourcePath}/icons/triangle.svg`,
  89497. data: object
  89498. },
  89499. "last", false, false);
  89500. tree.jstree(object.visible ? "check_node" : "uncheck_node", bunnyID);
  89501. //tree.jstree("open_node", parentNode);
  89502. }); */
  89503. }
  89504. removeObj(object){
  89505. this.objs.remove(object);
  89506. if(Potree.settings.boundAddObjs){
  89507. this.updateModelBound();
  89508. }
  89509. }
  89510. loadGLTF(name='87b3a367bc3e4273832cb4fa398782e5.glb'){
  89511. const loader = new GLTFLoader(undefined, this.renderer).setPath( Potree.resourcePath + '/models/glb/' );
  89512. /*
  89513. coffeemat.glb
  89514. ModernJPHouseSofa44216499.glb
  89515. ModernJPHouseSofa44105209.glb
  89516. 87ecd10fb0374ea6b3e0bf24c6459e3c.glb
  89517. 87b3a367bc3e4273832cb4fa398782e5.glb
  89518. */
  89519. loader.load(name, ( gltf )=>{
  89520. console.log('loadGLTF', gltf);
  89521. this.objs.add(gltf.scene);
  89522. });
  89523. }
  89524. addFire(){
  89525. if(Potree.settings.number == 't-CwfhfqJ'){
  89526. let position = Potree.Utils.datasetPosTransform({
  89527. pointcloud:viewer.scene.pointclouds[0],
  89528. position: new Vector3(4.4318,-0.580291847759, -0.78),
  89529. fromDataset:true
  89530. });
  89531. viewer.modules.ParticleEditor.addParticle( {
  89532. type:'fire',
  89533. positions:[position],
  89534. radius:0.42,
  89535. height:10,
  89536. });
  89537. viewer.modules.ParticleEditor.addParticle( {
  89538. type:'smoke',
  89539. positions: [ new Vector3().addVectors(position,new Vector3(0,0,0.3))],
  89540. positionStyle : 'sphere' ,
  89541. positionRadius : 0.3,
  89542. sizeTween: [[0, 0.3, 0.9, 1], [0.05, 0.1, 1, 0.8]],
  89543. opacityBase : 0.2,
  89544. opacityTween :[ [0, 0.3, 0.7, 0.95, 1], [0, 0.2, 1 , 0.1, 0] ],
  89545. velocityBase : new Vector3( 0, 0, 1),
  89546. velocitySpread : new Vector3( 0.2, 0.2, -0.3),
  89547. accelerationBase : 0.2,
  89548. accelerationSpread : 0.7,
  89549. radius:0,
  89550. //particlesPerSecond : 30,
  89551. particleDeathAge : 3.0,
  89552. });
  89553. viewer.modules.ParticleEditor.addParticle( {
  89554. type:'explode',
  89555. name:'fire splash',
  89556. position: new Vector3().addVectors(position,new Vector3(0,0,0.3)),
  89557. size: 0.1,
  89558. sizeRange: 0.3,
  89559. sizeTween:[[0, 0.05, 0.3, 0.45], [0, 0.02, 0.1, 0.05] ],
  89560. opacityTween: [[0, 0.05, 0.3, 0.45], [1, 1, 0.5, 0]] ,
  89561. speed : 1, //sphere
  89562. speedRange : 4,
  89563. radius: 0.1,
  89564. acceleration : 0.3,
  89565. accelerationRange : 1,
  89566. particleSpaceTime:0,
  89567. strength:4,
  89568. });
  89569. }
  89570. }
  89571. addVideo11(){
  89572. if(Potree.settings.number != 'SS-fckI7CClKC')return
  89573. var video = $(`<video controls="controls" loop autoplay x5-playsinline="" webkit-playsinline="true" playsinline="true" controlslist="nodownload"></video>`)[0];
  89574. video.setAttribute("crossOrigin", 'Anonymous');
  89575. //video.src = Potree.resourcePath+'/video/SS-fckI7CClKC/19.mp4'
  89576. var map = new VideoTexture(video);
  89577. var plane = this.videoPlane = new Mesh(new PlaneGeometry(1, 1, 1, 1), new MeshBasicMaterial({
  89578. color:"#ffffff",
  89579. transparent: !0,
  89580. depthTest:false,
  89581. opacity:0.7,
  89582. side:2,
  89583. map
  89584. }));
  89585. plane.visible = false;
  89586. plane.geometry.computeBoundingBox();
  89587. plane.boundingBox = plane.geometry.boundingBox.clone();//.applyMatrix4()
  89588. plane.boundingBox.max.z = 1;
  89589. plane.boundingBox.max.y = -0.4;
  89590. plane.boundingBox.max.x = 1;
  89591. /* plane.position.copy(this.images360.panos[19].position);
  89592. plane.lookAt(plane.position.clone().setX(0))
  89593. 9:
  89594. viewer.videoPlane.rotation.set(-1.432978005954197, 1.2296264545169697, 3.0098547630197667)
  89595. viewer.videoPlane.position.set( 6.532456676287381, -9.806373049095631, -0.024205281024294284)
  89596. //viewer.transformObject(viewer.videoPlane)
  89597. //19:
  89598. viewer.videoPlane.rotation.set( 1.627167773445286, -1.172425902600188, 0.04682299709711613)
  89599. viewer.videoPlane.position.set( -9.558613948539932,-1.042301166581578, 0.08159683876743667) */
  89600. video.addEventListener('loadeddata', function(e) {
  89601. video.play();
  89602. //plane.scale.set(video.videoWidth/1000,video.videoHeight/1000,1) // 1080 * 1920
  89603. console.log('video loadeddata');
  89604. });
  89605. plane.scale.set(1080/1000,1920/1000,1); // 1080 * 1920
  89606. var startPlay = ()=>{
  89607. video.play();
  89608. //video.pause()
  89609. //video.currentTime = 0.1;
  89610. this.removeEventListener('global_mousedown', startPlay);
  89611. };
  89612. this.addEventListener('global_mousedown', startPlay);
  89613. var videoInfo = {
  89614. 9:{
  89615. rotation:[-1.432978005954197, 1.2296264545169697, 3.0098547630197667],
  89616. position:[6.532456676287381, -9.806373049095631, -0.024205281024294284]
  89617. },
  89618. 19:{
  89619. rotation:[1.627167773445286, -1.172425902600188, 0.04682299709711613],
  89620. position:[-9.558613948539932,-1.042301166581578, 0.08159683876743667]
  89621. },
  89622. };
  89623. /* this.images360.addEventListener('cameraMoveDone',(e)=>{
  89624. let info = videoInfo[this.images360.currentPano.id]
  89625. if(info ){
  89626. plane.visible = true;
  89627. plane.material.opacity = 1;
  89628. plane.position.fromArray(info.position)
  89629. plane.rotation.fromArray(info.rotation)
  89630. }
  89631. }) */
  89632. this.images360.addEventListener('flyToPano' ,(e)=>{//飞之前
  89633. if(Potree.settings.displayMode != 'showPanos') return
  89634. let info = videoInfo[e.toPano.pano.id];
  89635. if(info ){ //出现
  89636. setTimeout(()=>{
  89637. plane.visible = true;
  89638. plane.position.fromArray(info.position);
  89639. plane.rotation.fromArray(info.rotation);
  89640. video.src = Potree.resourcePath+`/video/${Potree.settings.number}/${e.toPano.pano.id}.mp4`;
  89641. video.play();
  89642. video.currentTime = 0;
  89643. Potree.settings.zoom.enabled = false;
  89644. transitions.start(lerp.property(plane.material, "opacity", 1/* , (e)=>{console.log('fadeIn',e)} */) , e.toPano.duration*0.4 , ()=>{
  89645. }, 0, easing['easeInOutQuad']);
  89646. }, e.toPano.duration*0.6); //时间上不能和消失的重叠 延迟
  89647. }
  89648. //消失
  89649. transitions.start(lerp.property(plane.material, "opacity", 0, /* (e)=>{console.log('fadeOut',e)} */) , e.toPano.duration*0.4, ()=>{
  89650. if(!info){
  89651. plane.visible = false;
  89652. video.pause();
  89653. Potree.settings.zoom.enabled = true;
  89654. }
  89655. }, 0, easing['easeInOutQuad']);
  89656. });
  89657. this.images360.addEventListener('endChangeMode',(e)=>{ //暂时不处理初始加载时就在有视频的点位上的情况
  89658. if(e.mode == 'showPanos'){
  89659. let info = videoInfo[this.images360.currentPano.id];
  89660. if(info ){ //出现
  89661. plane.visible = true;
  89662. plane.position.fromArray(info.position);
  89663. plane.rotation.fromArray(info.rotation);
  89664. plane.material.opacity = 0;
  89665. video.src = Potree.resourcePath+`/video/${Potree.settings.number}/${this.images360.currentPano.id}.mp4`;
  89666. video.play();
  89667. video.currentTime = 0;
  89668. Potree.settings.zoom.enabled = false;
  89669. transitions.start(lerp.property(plane.material, "opacity", 1, (e)=>{console.log('fadeIn',e);}) , 300 , ()=>{
  89670. }, 0, easing['easeInOutQuad']);
  89671. }
  89672. }else {
  89673. plane.visible = false;
  89674. Potree.settings.zoom.enabled = true;
  89675. }
  89676. });
  89677. this.scene.scene.add(plane);
  89678. }
  89679. ////////////////////////
  89680. addVideo(){
  89681. if(Potree.settings.number != 'SS-t-P6zBR73Gke')return
  89682. var geo = new PlaneGeometry(1, 1, 1, 1);
  89683. var videoInfo = this.videoInfo = [
  89684. /* {
  89685. id: 45,
  89686. url: 'https://laser-oss.4dkankan.com/testdata/SS-t-P6zBR73Gke/temp/poi/2022/05/09/c02a2c1e-8420-4f34-b951-5f7a07abe932.mp4',
  89687. rotation:[-1.629007730553656, 0.042029565584517974, -3.1345506775116627],
  89688. position:[ 9.467649296794061, -0.7596961214872837, -0.12477576310191862],
  89689. scale:[4.52209111454416,3.3888400031207984,1],
  89690. }, */
  89691. {
  89692. id: '40-2',
  89693. url: 'https://laser-oss.4dkankan.com/testdata/SS-t-P6zBR73Gke/temp/poi/2022/05/10/0aabafee-36b8-455d-9c11-0780bf694786.mp4',
  89694. rotation:[-1.494468618954883, -1.4987317433158989, -3.061254983446741],
  89695. position:[ 19.801820617361624, 2.884673619844108, -0.03362305858221648],
  89696. scale:[3.5741423153151763, 2.8738725275578703, 1],
  89697. },
  89698. {
  89699. id: 40,
  89700. /* rotation:[-1.534692822378723, 0.01083403560862361, 3.141535283661569],
  89701. position:[17.2934294239949861, 2.413510747928117, -0.008057029580231356], */
  89702. url: 'https://laser-oss.4dkankan.com/testdata/SS-t-P6zBR73Gke/temp/poi/2022/05/09/7896d6ef-a2d6-4fd7-949c-768782a5b484.mp4',
  89703. rotation:[-1.5487684197910518, 0.021848470169552752, -3.1387534893955236],
  89704. position:[17.277316608096, 2.0840432922115846, -0.0931149415437065],
  89705. scale:[2.0821757723834047, 0.6129478480765236, 1],
  89706. visibles: [40]
  89707. },
  89708. ];
  89709. let add = (info)=>{
  89710. var video = $(`<video controls="controls" loop autoplay x5-playsinline="" webkit-playsinline="true" playsinline="true" controlslist="nodownload"></video>`)[0];
  89711. video.setAttribute("crossOrigin", 'Anonymous');
  89712. video.src = info.url || Potree.resourcePath+`/video/${Potree.settings.number}/${info.id}.mp4`;
  89713. var map = new VideoTexture(video);
  89714. var plane = this.videoPlane = new Mesh(geo, new MeshBasicMaterial({
  89715. color:"#ffffff",
  89716. transparent: !0,
  89717. depthTest:false,
  89718. opacity:0 ,
  89719. //side:2,
  89720. map
  89721. }));
  89722. plane.position.fromArray(info.position);
  89723. plane.rotation.fromArray(info.rotation);
  89724. info.scale && plane.scale.fromArray(info.scale);
  89725. this.scene.scene.add(plane);
  89726. info.plane = plane;
  89727. plane.boundingBox = new Box3(new Vector3(0,-0.5,0),new Vector3(1,-0.4,0.2));
  89728. video.addEventListener('loadeddata', function(e) {
  89729. video.play();
  89730. if(!info.visibles/* ||!viewer.images360.currentPano || info.visibles.includes(viewer.images360.currentPano.id) */){
  89731. plane.material.opacity = 1;
  89732. }
  89733. info.scale || plane.scale.set(video.videoWidth/1000,video.videoHeight/1000,1); // 1080 * 1920
  89734. console.log('video loadeddata', info.id);
  89735. });
  89736. if(info.visibles){
  89737. this.images360.addEventListener('flyToPano' ,(e)=>{//飞之前
  89738. if(info.visibles.includes(e.toPano.pano.id)){ //出现
  89739. setTimeout(()=>{
  89740. plane.visible = true;
  89741. video.currentTime = 0;
  89742. video.play();
  89743. if(video.paused){
  89744. var startPlay = ()=>{
  89745. plane.visible && video.play();
  89746. this.removeEventListener('global_mousedown', startPlay);
  89747. };
  89748. this.addEventListener('global_mousedown', startPlay);
  89749. }
  89750. Potree.settings.zoom.enabled = false;
  89751. transitions.start(lerp.property(plane.material, "opacity", 1 ) , e.toPano.duration*0.4 , ()=>{
  89752. }, 0, easing['easeInOutQuad']);
  89753. }, e.toPano.duration*0.6); //时间上不能和消失的重叠 延迟
  89754. }else {
  89755. //消失
  89756. transitions.start(lerp.property(plane.material, "opacity", 0, ) , e.toPano.duration*0.4, ()=>{
  89757. if(!info){
  89758. plane.visible = false;
  89759. video.pause();
  89760. Potree.settings.zoom.enabled = true;
  89761. }
  89762. }, 0, easing['easeInOutQuad']);
  89763. }
  89764. });
  89765. }
  89766. var startPlay = ()=>{
  89767. video.play();
  89768. //video.pause()
  89769. //video.currentTime = 0.1;
  89770. this.removeEventListener('global_mousedown', startPlay);
  89771. };
  89772. this.addEventListener('global_mousedown', startPlay);
  89773. Potree.settings.isTest && plane.addEventListener('select',(e)=>{console.log(e);});
  89774. };
  89775. videoInfo.forEach(info=>{
  89776. add(info);
  89777. });
  89778. /* var video = $(`<video controls="controls" loop autoplay x5-playsinline="" webkit-playsinline="true" playsinline="true" controlslist="nodownload"></video>`)[0]
  89779. video.setAttribute("crossOrigin", 'Anonymous')
  89780. video.src = Potree.resourcePath+'/video/SS-t-P6zBR73Gke/40.mp4'
  89781. var map = new THREE.VideoTexture(video);
  89782. var plane = this.videoPlane = new THREE.Mesh(geo, new THREE.MeshBasicMaterial({
  89783. color:"#ffffff",
  89784. transparent: !0,
  89785. depthTest:false,
  89786. opacity:0.7,
  89787. side:2,
  89788. map
  89789. }))
  89790. //plane.visible = false
  89791. this.scene.scene.add(plane)
  89792. plane.geometry.computeBoundingBox();
  89793. plane.boundingBox = plane.geometry.boundingBox.clone()//.applyMatrix4()
  89794. plane.boundingBox.max.z = 0.3
  89795. plane.boundingBox.max.y = -0.4
  89796. plane.boundingBox.max.x = 1
  89797. plane.position.copy(this.images360.panos[40].position);
  89798. plane.lookAt(plane.position.clone().setX(0))
  89799. plane.rotation.set(-1.534692822378723, 0.01083403560862361, 3.141535283661569)
  89800. plane.position.set( 17.2934294239949861, 2.413510747928117, -0.008057029580231356)
  89801. //viewer.transformObject(viewer.videoPlane)
  89802. //19:
  89803. video.addEventListener('loadeddata', function(e) {
  89804. video.play()
  89805. plane.scale.set(video.videoWidth/1000,video.videoHeight/1000,1) // 1080 * 1920
  89806. console.log('video loadeddata')
  89807. })
  89808. //plane.scale.set(1080/1000,1920/1000,1) // 1080 * 1920
  89809. var startPlay = ()=>{
  89810. video.play()
  89811. //video.pause()
  89812. //video.currentTime = 0.1;
  89813. this.removeEventListener('global_mousedown', startPlay)
  89814. }
  89815. this.addEventListener('global_mousedown', startPlay)
  89816. */
  89817. /* this.images360.addEventListener('flyToPano' ,(e)=>{//飞之前
  89818. if(Potree.settings.displayMode != 'showPanos') return
  89819. let info = videoInfo[e.toPano.pano.id]
  89820. if(info ){ //出现
  89821. setTimeout(()=>{
  89822. plane.visible = true;
  89823. plane.position.fromArray(info.position)
  89824. plane.rotation.fromArray(info.rotation)
  89825. video.src = Potree.resourcePath+`/video/${Potree.settings.number}/${e.toPano.pano.id}.mp4`
  89826. video.play();
  89827. video.currentTime = 0
  89828. Potree.settings.zoom.enabled = false
  89829. transitions.start(lerp.property(plane.material, "opacity", 1 ) , e.toPano.duration*0.4 , ()=>{
  89830. }, 0, easing['easeInOutQuad'])
  89831. }, e.toPano.duration*0.6) //时间上不能和消失的重叠 延迟
  89832. }
  89833. //消失
  89834. transitions.start(lerp.property(plane.material, "opacity", 0, ) , e.toPano.duration*0.4, ()=>{
  89835. if(!info){
  89836. plane.visible = false
  89837. video.pause()
  89838. Potree.settings.zoom.enabled = true
  89839. }
  89840. }, 0, easing['easeInOutQuad'])
  89841. })
  89842. this.images360.addEventListener('endChangeMode',(e)=>{ //暂时不处理初始加载时就在有视频的点位上的情况
  89843. if(e.mode == 'showPanos'){
  89844. let info = videoInfo[this.images360.currentPano.id]
  89845. if(info ){ //出现
  89846. plane.visible = true;
  89847. plane.position.fromArray(info.position)
  89848. plane.rotation.fromArray(info.rotation)
  89849. plane.material.opacity = 0
  89850. video.src = Potree.resourcePath+`/video/${Potree.settings.number}/${this.images360.currentPano.id}.mp4`
  89851. video.play();
  89852. video.currentTime = 0
  89853. Potree.settings.zoom.enabled = false
  89854. transitions.start(lerp.property(plane.material, "opacity", 1, (e)=>{console.log('fadeIn',e)}) , 300 , ()=>{
  89855. }, 0, easing['easeInOutQuad'])
  89856. }
  89857. }else{
  89858. plane.visible = false;
  89859. Potree.settings.zoom.enabled = true
  89860. }
  89861. })
  89862. */
  89863. }
  89864. };
  89865. //------ CLIP 默认clipTask都是clipInside ----------------------
  89866. /*
  89867. 并集相当于加法,交集相当于加法。 所有结果都能展开成多个乘积相加。
  89868. 假设有4个clipBoxes,ABCD, 如果是 A*B + C*D ,那么这是最终结果。 如果是 (A+B)*(C+D) = A*C+A*D+B*C+B*D
  89869. */
  89870. let Clips = {
  89871. boxes : [],
  89872. unionGroups : [], //二维数组。最外层要求并集,里层要求交集(如果只有一个元素就是本身)。总结起来就是要求一堆交集的并集
  89873. shaderParams:{},
  89874. needsUpdate : true,
  89875. addClip(box, clipMethod){
  89876. //不允许重复
  89877. if(this.boxes.includes(box)){
  89878. return console.warn('addClip重复添加了box',box)
  89879. }
  89880. boxes.push(box);
  89881. if(clipMethod == 'any'){//并
  89882. this.unionGroups.push([box]);
  89883. }else if(clipMethod == 'all'){//交
  89884. this.unionGroups.forEach(mixGroup=>mixGroup.push(box));
  89885. }
  89886. this.needsUpdate = true;
  89887. },
  89888. removeClip(box){
  89889. if(!this.boxes.includes(box)){
  89890. return console.warn('removeClip没有找到该box',box)
  89891. }
  89892. var newGroups = [];
  89893. this.unionGroups.forEach(mixGroup=>{
  89894. if(mixGroup.length == 1 && mixGroup[0] == box)return;//直接删除
  89895. newGroups.push(mixGroup.filter(e=>e!=box));
  89896. });
  89897. this.unionGroups = newGroups;
  89898. this.needsUpdate = true;
  89899. }
  89900. ,
  89901. clearClip(){
  89902. this.boxes = [];
  89903. this.unionGroups = [];
  89904. this.needsUpdate = true;
  89905. }
  89906. ,
  89907. updateShaderParams(){//没写完 - - 见 pointcloud clip.vs
  89908. /*
  89909. uniform mat4 clipBoxes[num_clipboxes];
  89910. uniform int clipBoxGroupCount;
  89911. uniform int mixClipIndices[clipboxGroupItemCount]; //把所有的要求都直接放到数组内
  89912. */
  89913. //这里需要转为Float32Array..? 参考material.setClipBoxes
  89914. let everyClipGroupCount = this.unionGroups.map(e=>e.length);
  89915. let mixClipIndices = [];
  89916. this.unionGroups.forEach(e=>{
  89917. mixClipIndices.push(...e);
  89918. });
  89919. this.shaderParams = {
  89920. num_clipboxes : this.boxes.length,
  89921. clipBoxGroupCount : this.unionGroups.length,
  89922. everyClipGroupCount,
  89923. clipBoxIndexCount: mixClipIndices.length,
  89924. mixClipIndices
  89925. };
  89926. }
  89927. ,
  89928. getShaderParams(){//每次要传递参数到shader中,执行这个就好
  89929. if(this.needsUpdate){
  89930. this.updateShaderParams();
  89931. }
  89932. return this.shaderParams
  89933. }
  89934. };
  89935. /* setTimeout(()=>{
  89936. if( Potree.settings.number == 't-YLZ5XAALl7' || 't-e2Kb2iU' ){
  89937. let transform = {
  89938. 't-YLZ5XAALl7' : {
  89939. rotation : [0, 0, 0.002326740152215126],
  89940. position : [0.421017820930033, -0.22730084679456727, 0.0068952417582]
  89941. },
  89942. 't-e2Kb2iU' : {
  89943. rotation : [0.06595546058095993, -0.026986798620029413, 0.8429662590573239],
  89944. position : [ -502.6216232179794, 1051.5690392495885, 15.48490744053752]
  89945. },
  89946. }
  89947. var path = `${Potree.resourcePath}/models/${Potree.settings.number}/`
  89948. viewer.loadObj({
  89949. objurl: path+'pipe.obj',
  89950. mtlurl: path+'pipe.mtl',
  89951. transform : transform[Potree.settings.number]
  89952. })
  89953. }
  89954. },1000)
  89955. //if(!Potree.settings.isOfficial){
  89956. if(number == 't-e2Kb2iU') {
  89957. setTimeout(//暂时延迟,等focus第一个点之后
  89958. ()=>{
  89959. viewer.loadProject(Potree.scriptPath + "/data/"+ number +"/potree.json5", ()=>{
  89960. viewer.scene.cameraAnimations[0].play()
  89961. })
  89962. },
  89963. 3000)
  89964. }
  89965. */
  89966. OrthographicCamera.prototype.zoomTo = function( node, factor = 1){
  89967. if ( !node.geometry && !node.boundingBox) {
  89968. return;
  89969. }
  89970. // TODO
  89971. //let minWS = new THREE.Vector4(node.boundingBox.min.x, node.boundingBox.min.y, node.boundingBox.min.z, 1);
  89972. //let minVS = minWS.applyMatrix4(this.matrixWorldInverse);
  89973. //let right = node.boundingBox.max.x;
  89974. //let bottom = node.boundingBox.min.y;
  89975. //let top = node.boundingBox.max.y;
  89976. this.updateProjectionMatrix();
  89977. };
  89978. PerspectiveCamera.prototype.zoomTo = function (node, factor) {
  89979. if (!node.geometry && !node.boundingSphere && !node.boundingBox) {
  89980. return;
  89981. }
  89982. if (node.geometry && node.geometry.boundingSphere === null) {
  89983. node.geometry.computeBoundingSphere();
  89984. }
  89985. node.updateMatrixWorld();
  89986. let bs;
  89987. if (node.boundingSphere) {
  89988. bs = node.boundingSphere;
  89989. } else if (node.geometry && node.geometry.boundingSphere) {
  89990. bs = node.geometry.boundingSphere;
  89991. } else {
  89992. bs = node.boundingBox.getBoundingSphere(new Sphere());
  89993. }
  89994. let _factor = factor || 1;
  89995. bs = bs.clone().applyMatrix4(node.matrixWorld);
  89996. let radius = bs.radius;
  89997. let fovr = this.fov * Math.PI / 180;
  89998. if (this.aspect < 1) {
  89999. fovr = fovr * this.aspect;
  90000. }
  90001. let distanceFactor = Math.abs(radius / Math.sin(fovr / 2)) * _factor;
  90002. let offset = this.getWorldDirection(new Vector3()).multiplyScalar(-distanceFactor);
  90003. this.position.copy(bs.center.clone().add(offset));
  90004. };
  90005. Ray.prototype.distanceToPlaneWithNegative = function (plane) {
  90006. let denominator = plane.normal.dot(this.direction);
  90007. if (denominator === 0) {
  90008. // line is coplanar, return origin
  90009. if (plane.distanceToPoint(this.origin) === 0) {
  90010. return 0;
  90011. }
  90012. // Null is preferable to undefined since undefined means.... it is undefined
  90013. return null;
  90014. }
  90015. let t = -(this.origin.dot(plane.normal) + plane.constant) / denominator;
  90016. return t;
  90017. };
  90018. const workerPool = new WorkerPool();
  90019. const version = {
  90020. major: 1,
  90021. minor: 8,
  90022. suffix: '.0'
  90023. };
  90024. let lru = new LRU();
  90025. //console.log('Potree ' + version.major + '.' + version.minor + version.suffix);
  90026. let pointBudget = 1 * 1000 * 1000;
  90027. let framenumber = 0;
  90028. let numNodesLoading = 0;
  90029. let maxNodesLoading = 4;
  90030. const debug = {};
  90031. exports.scriptPath = "";
  90032. if (document.currentScript && document.currentScript.src) {
  90033. exports.scriptPath = new URL(document.currentScript.src + '/..').href;
  90034. if (exports.scriptPath.slice(-1) === '/') {
  90035. exports.scriptPath = exports.scriptPath.slice(0, -1);
  90036. }
  90037. } 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)) })){
  90038. 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;
  90039. if (exports.scriptPath.slice(-1) === '/') {
  90040. exports.scriptPath = exports.scriptPath.slice(0, -1);
  90041. }
  90042. }else {
  90043. 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?');
  90044. }
  90045. let resourcePath = exports.scriptPath + '/resources';
  90046. //add:
  90047. async function loadFile(path, callback, onError){
  90048. if(Potree.fileServer){
  90049. Potree.fileServer.get(path).then(data=>{
  90050. callback && callback(data);
  90051. }).catch(onError);
  90052. }else {
  90053. try{
  90054. let response = await fetch(path);
  90055. let text = await response.text();
  90056. var data = JSON.parse(text);
  90057. if(data.data) data = data.data;
  90058. callback && callback(data);
  90059. return data
  90060. }catch(e){
  90061. onError && onError(e);
  90062. }
  90063. }
  90064. //查询: http://192.168.0.26:8080/doc.html#/default/filter-%E6%BC%AB%E6%B8%B8%E7%82%B9/filterUsingGET
  90065. }
  90066. async function loadDatasets(callback,sceneCode,onError){//之后直接把path写进来
  90067. let path;
  90068. sceneCode = sceneCode || Potree.settings.number;
  90069. if(Potree.fileServer){
  90070. path = `/laser/dataset/${sceneCode}/getDataSet`;
  90071. }else {
  90072. //path = `${Potree.settings.urls.prefix2}/indoor/${Potree.settings.number}/api/datasets`
  90073. //现在只能加载得了本地的了
  90074. path = `${Potree.settings.urls.prefix4}laser/dataset/${sceneCode}/getDataSet`;
  90075. //path = `${Potree.scriptPath}/data/${sceneCode}/getDataSet.json`
  90076. }
  90077. return loadFile(path, callback,onError)
  90078. }
  90079. //目前上传平面图后如果不点击保存按钮,数据还是旧的不生效
  90080. async function loadMapEntity(datasetId, force){
  90081. if(!Potree.settings.floorplanEnable && !force && Potree.fileServer )return /* 等待平面图类型定义好会加载 */
  90082. let loaded = 0;
  90083. let needLoads = datasetId == 'all' ? viewer.scene.pointclouds.map(e=>e.dataset_id) : [datasetId];
  90084. let callback = (dataset_id, floorplanType, data )=>{
  90085. //要防止旧的比新的先获取到导致覆盖新的,因为两种type随时可能切换
  90086. if(floorplanType != Potree.settings.floorplanType[dataset_id]) return //如果请求的floorplanType不是当前最新的floorplanType就返回
  90087. var map = viewer.mapViewer.mapLayer.maps.find(e => e.name == 'floorplan_'+ dataset_id);
  90088. if(map){
  90089. viewer.mapViewer.mapLayer.removeMap(map);
  90090. }
  90091. var mapNew = viewer.mapViewer.mapLayer.addMapEntity(data.data || data, dataset_id);
  90092. if(map){
  90093. mapNew.visibleReasons = map.visibleReasons;
  90094. mapNew.unvisibleReasons = map.unvisibleReasons;
  90095. }
  90096. loaded ++;
  90097. };
  90098. needLoads.forEach(dataset_id=>{
  90099. let floorplanType = Potree.settings.floorplanType[dataset_id];
  90100. if(!floorplanType)return
  90101. var path;
  90102. if(Potree.fileServer){
  90103. path = `/laser/tiledMap/${Potree.settings.number}/tiledMap/${floorplanType}/${dataset_id}`;
  90104. }else {
  90105. path = `${Potree.settings.urls.prefix2}/indoor/${Potree.settings.number}/api/tiled_maps`;
  90106. }
  90107. Potree.settings.floorplanRequests[dataset_id] = true; //开始加载了
  90108. return loadFile(path, callback.bind(this, dataset_id, floorplanType) )
  90109. });
  90110. }
  90111. async function loadPanos(datasetId, callback){
  90112. var path;
  90113. let query = `?datasetId=${datasetId}`; //`?lat=${center.lat}&lon=${center.lon}&radius=200000`
  90114. if(Potree.fileServer){
  90115. path = `/laser/filter/${Potree.settings.number}/query` + query;
  90116. }else {
  90117. //path = `${Potree.settings.urls.prefix2}/indoor/${Potree.settings.number}/api/images/filter` + query
  90118. //path = `${Potree.scriptPath}/data/${Potree.settings.number}/panos-${datasetId}.json`
  90119. path = `${Potree.settings.urls.prefix4}laser/filter/${Potree.settings.number}/query` + query;
  90120. }
  90121. return loadFile(path, callback)
  90122. }
  90123. async function loadPanosInfo(callback){
  90124. var path;
  90125. if(Potree.fileServer){
  90126. }else {
  90127. path = `${Potree.scriptPath}/data/panoEdit/vision_edit.txt`;
  90128. }
  90129. return loadFile(path, callback)
  90130. }
  90131. //site_model
  90132. /* {
  90133. "area": 2503.30551910935,
  90134. "attributes": {},
  90135. "center": [
  90136. 113.59568277455075,
  90137. 22.366566635195288,
  90138. 12.78751625
  90139. ],
  90140. "children": [],
  90141. "geometry_hash": 1891071345,
  90142. "id": 10,
  90143. "name": "港湾一号",
  90144. "parentId": null,
  90145. "polygon": {
  90146. "coordinates": [
  90147. [
  90148. [
  90149. 113.59590810534583,
  90150. 22.36679132753878
  90151. ],
  90152. [
  90153. 113.59590810534583,
  90154. 22.366807172528629
  90155. ],
  90156. [
  90157. 113.59545610274934,
  90158. 22.366807172528629
  90159. ],
  90160. [
  90161. 113.59545610274934,
  90162. 22.36679132753878
  90163. ]
  90164. ]
  90165. ],
  90166. "type": "Polygon"
  90167. },
  90168. "type": "BUILDING",
  90169. "volume": null,
  90170. "z_max": null,
  90171. "z_min": null
  90172. }
  90173. */
  90174. function Log(value, color, fontSize){
  90175. color = color || '#13f';
  90176. fontSize = fontSize || 14;
  90177. console.warn(`%c${value}`, `color:${color};font-size:${fontSize}px`);
  90178. }
  90179. function loadPointCloud$1(path, name, sceneCode, timeStamp, callback, onError){
  90180. let loaded = function(e){
  90181. e.pointcloud.name = name;
  90182. e.pointcloud.sceneCode = sceneCode; //对应4dkk的场景码
  90183. callback(e);
  90184. };
  90185. let promise = new Promise( resolve => {
  90186. // load pointcloud
  90187. if (!path){
  90188. // TODO: callback? comment? Hello? Bueller? Anyone?
  90189. } else if (path.indexOf('ept.json') > 0) {
  90190. EptLoader.load(path, function(geometry) {
  90191. if (!geometry) {
  90192. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  90193. }
  90194. else {
  90195. let pointcloud = new PointCloudOctree(geometry);
  90196. //loaded(pointcloud);
  90197. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  90198. }
  90199. });
  90200. } else if (path.indexOf('cloud.js') > 0) {
  90201. POCLoader.load(path, timeStamp, function (geometry) {
  90202. if (!geometry) {
  90203. //callback({type: 'loading_failed'});
  90204. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  90205. onError && onError();
  90206. } else {
  90207. let pointcloud = new PointCloudOctree(geometry);
  90208. // loaded(pointcloud);
  90209. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  90210. }
  90211. });
  90212. }/* else if (path.indexOf('metadata.json') > 0) { //部分浏览器(如uc)不支持NodeLoader中的1n的大数据写法
  90213. Potree.OctreeLoader.load(path).then(e => {
  90214. let geometry = e.geometry;
  90215. if(!geometry){
  90216. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  90217. }else{
  90218. let pointcloud = new PointCloudOctree(geometry);
  90219. let aPosition = pointcloud.getAttribute("position");
  90220. let material = pointcloud.material;
  90221. material.elevationRange = [
  90222. aPosition.range[0][2],
  90223. aPosition.range[1][2],
  90224. ];
  90225. // loaded(pointcloud);
  90226. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  90227. }
  90228. });
  90229. OctreeLoader.load(path, function (geometry) {
  90230. if (!geometry) {
  90231. //callback({type: 'loading_failed'});
  90232. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  90233. } else {
  90234. let pointcloud = new PointCloudOctree(geometry);
  90235. // loaded(pointcloud);
  90236. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  90237. }
  90238. });
  90239. } */else if (path.indexOf('.vpc') > 0) {
  90240. PointCloudArena4DGeometry.load(path, function (geometry) {
  90241. if (!geometry) {
  90242. //callback({type: 'loading_failed'});
  90243. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  90244. } else {
  90245. let pointcloud = new PointCloudArena4D(geometry);
  90246. // loaded(pointcloud);
  90247. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  90248. }
  90249. });
  90250. } else {
  90251. //callback({'type': 'loading_failed'});
  90252. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  90253. }
  90254. });
  90255. if(callback){
  90256. promise.then(pointcloud => {
  90257. loaded(pointcloud);
  90258. });
  90259. }else {
  90260. return promise;
  90261. }
  90262. };
  90263. // add selectgroup
  90264. (function($){
  90265. $.fn.extend({
  90266. selectgroup: function(args = {}){
  90267. let elGroup = $(this);
  90268. let rootID = elGroup.prop("id");
  90269. let groupID = `${rootID}`;
  90270. let groupTitle = (args.title !== undefined) ? args.title : "";
  90271. let elButtons = [];
  90272. elGroup.find("option").each((index, value) => {
  90273. let buttonID = $(value).prop("id");
  90274. let label = $(value).html();
  90275. let optionValue = $(value).prop("value");
  90276. let elButton = $(`
  90277. <span style="flex-grow: 1; display: inherit">
  90278. <label for="${buttonID}" class="ui-button" style="width: 100%; padding: .4em .1em">${label}</label>
  90279. <input type="radio" name="${groupID}" id="${buttonID}" value="${optionValue}" style="display: none"/>
  90280. </span>
  90281. `);
  90282. let elLabel = elButton.find("label");
  90283. let elInput = elButton.find("input");
  90284. elInput.change( () => {
  90285. elGroup.find("label").removeClass("ui-state-active");
  90286. elGroup.find("label").addClass("ui-state-default");
  90287. if(elInput.is(":checked")){
  90288. elLabel.addClass("ui-state-active");
  90289. }else {
  90290. //elLabel.addClass("ui-state-default");
  90291. }
  90292. });
  90293. elButtons.push(elButton);
  90294. });
  90295. let elFieldset = $(`
  90296. <fieldset style="border: none; margin: 0px; padding: 0px">
  90297. <legend>${groupTitle}</legend>
  90298. <span style="display: flex">
  90299. </span>
  90300. </fieldset>
  90301. `);
  90302. let elButtonContainer = elFieldset.find("span");
  90303. for(let elButton of elButtons){
  90304. elButtonContainer.append(elButton);
  90305. }
  90306. elButtonContainer.find("label").each( (index, value) => {
  90307. $(value).css("margin", "0px");
  90308. $(value).css("border-radius", "0px");
  90309. $(value).css("border", "1px solid black");
  90310. $(value).css("border-left", "none");
  90311. });
  90312. elButtonContainer.find("label:first").each( (index, value) => {
  90313. $(value).css("border-radius", "4px 0px 0px 4px");
  90314. });
  90315. elButtonContainer.find("label:last").each( (index, value) => {
  90316. $(value).css("border-radius", "0px 4px 4px 0px");
  90317. $(value).css("border-left", "none");
  90318. });
  90319. elGroup.empty();
  90320. elGroup.append(elFieldset);
  90321. }
  90322. });
  90323. })(jQuery);
  90324. exports.Action = Action;
  90325. exports.Alignment = Alignment;
  90326. exports.AnimationPath = AnimationPath;
  90327. exports.Annotation = Annotation;
  90328. exports.Box3Helper = Box3Helper$1;
  90329. exports.BoxVolume = BoxVolume;
  90330. exports.Buttons = Buttons;
  90331. exports.CameraAnimation = CameraAnimation;
  90332. exports.CameraMode = CameraMode;
  90333. exports.ClassificationScheme = ClassificationScheme;
  90334. exports.ClipMethod = ClipMethod;
  90335. exports.ClipTask = ClipTask;
  90336. exports.ClipVolume = ClipVolume;
  90337. exports.ClippingTool = ClippingTool;
  90338. exports.Compass = Compass;
  90339. exports.DeviceOrientationControls = DeviceOrientationControls;
  90340. exports.DownloadStatus = DownloadStatus;
  90341. exports.EarthControls = EarthControls;
  90342. exports.ElevationGradientRepeat = ElevationGradientRepeat;
  90343. exports.Enum = Enum;
  90344. exports.EnumItem = EnumItem;
  90345. exports.EptBinaryLoader = EptBinaryLoader;
  90346. exports.EptKey = EptKey;
  90347. exports.EptLaszipLoader = EptLaszipLoader;
  90348. exports.EptLazBatcher = EptLazBatcher;
  90349. exports.EptLoader = EptLoader;
  90350. exports.EptZstandardLoader = EptZstandardLoader;
  90351. exports.EventDispatcher = EventDispatcher$1;
  90352. exports.EyeDomeLightingMaterial = EyeDomeLightingMaterial;
  90353. exports.Features = Features;
  90354. exports.FirstPersonControls = FirstPersonControls;
  90355. exports.GLCubeFaces = GLCubeFaces$1;
  90356. exports.GeoPackageLoader = GeoPackageLoader;
  90357. exports.Geopackage = Geopackage$1;
  90358. exports.Gradients = Gradients;
  90359. exports.HierarchicalSlider = HierarchicalSlider;
  90360. exports.Images360 = Images360;
  90361. exports.KeyCodes = KeyCodes;
  90362. exports.LRU = LRU;
  90363. exports.LRUItem = LRUItem;
  90364. exports.LengthUnits = LengthUnits;
  90365. exports.Log = Log;
  90366. exports.Measure = Measure;
  90367. exports.MeasuringTool = MeasuringTool;
  90368. exports.Message = Message;
  90369. exports.ModelManagerEvents = ModelManagerEvents;
  90370. exports.NormalizationEDLMaterial = NormalizationEDLMaterial;
  90371. exports.NormalizationMaterial = NormalizationMaterial;
  90372. exports.OrbitControls = OrbitControls;
  90373. exports.OrientedImage = OrientedImage;
  90374. exports.OrientedImageLoader = OrientedImageLoader;
  90375. exports.OrientedImages = OrientedImages;
  90376. exports.POCLoader = POCLoader;
  90377. exports.PanoRendererEvents = PanoRendererEvents;
  90378. exports.PanoSizeClass = PanoSizeClass;
  90379. exports.PanoramaEvents = PanoramaEvents;
  90380. exports.PathAnimation = PathAnimation;
  90381. exports.PointAttribute = PointAttribute;
  90382. exports.PointAttributeTypes = PointAttributeTypes;
  90383. exports.PointAttributes = PointAttributes;
  90384. exports.PointCloudEptGeometry = PointCloudEptGeometry;
  90385. exports.PointCloudEptGeometryNode = PointCloudEptGeometryNode;
  90386. exports.PointCloudMaterial = PointCloudMaterial$1;
  90387. exports.PointCloudOctree = PointCloudOctree;
  90388. exports.PointCloudOctreeGeometry = PointCloudOctreeGeometry;
  90389. exports.PointCloudOctreeGeometryNode = PointCloudOctreeGeometryNode;
  90390. exports.PointCloudOctreeNode = PointCloudOctreeNode;
  90391. exports.PointCloudSM = PointCloudSM;
  90392. exports.PointCloudTree = PointCloudTree;
  90393. exports.PointCloudTreeNode = PointCloudTreeNode;
  90394. exports.PointShape = PointShape;
  90395. exports.PointSizeType = PointSizeType;
  90396. exports.Points = Points$1;
  90397. exports.PolygonClipVolume = PolygonClipVolume;
  90398. exports.Profile = Profile;
  90399. exports.ProfileData = ProfileData;
  90400. exports.ProfileRequest = ProfileRequest;
  90401. exports.ProfileTool = ProfileTool;
  90402. exports.Renderer = Renderer;
  90403. exports.Scene = Scene$1;
  90404. exports.SceneRendererEvents = SceneRendererEvents;
  90405. exports.ScreenBoxSelectTool = ScreenBoxSelectTool;
  90406. exports.ShapefileLoader = ShapefileLoader;
  90407. exports.SphereVolume = SphereVolume;
  90408. exports.SpotLightHelper = SpotLightHelper$1;
  90409. exports.TileDownloaderEvents = TileDownloaderEvents;
  90410. exports.TransformationTool = TransformationTool;
  90411. exports.TreeType = TreeType;
  90412. exports.Utils = Utils;
  90413. exports.VRControls = VRControls;
  90414. exports.Vectors = Vectors;
  90415. exports.Vectors2 = Vectors2;
  90416. exports.Version = Version;
  90417. exports.Viewer = Viewer;
  90418. exports.Volume = Volume;
  90419. exports.VolumeTool = VolumeTool;
  90420. exports.WorkerPool = WorkerPool;
  90421. exports.XHRFactory = XHRFactory;
  90422. exports.config = config$1;
  90423. exports.debug = debug;
  90424. exports.framenumber = framenumber;
  90425. exports.loadDatasets = loadDatasets;
  90426. exports.loadFile = loadFile;
  90427. exports.loadMapEntity = loadMapEntity;
  90428. exports.loadPanos = loadPanos;
  90429. exports.loadPanosInfo = loadPanosInfo;
  90430. exports.loadPointCloud = loadPointCloud$1;
  90431. exports.loadProject = loadProject;
  90432. exports.lru = lru;
  90433. exports.maxNodesLoading = maxNodesLoading;
  90434. exports.mergeEditStart = mergeEditStart;
  90435. exports.numNodesLoading = numNodesLoading;
  90436. exports.panoEditStart = panoEditStart;
  90437. exports.pointBudget = pointBudget;
  90438. exports.resourcePath = resourcePath;
  90439. exports.saveProject = saveProject;
  90440. exports.settings = settings;
  90441. exports.start = start;
  90442. exports.updatePointClouds = updatePointClouds;
  90443. exports.updateVisibility = updateVisibility;
  90444. exports.updateVisibilityStructures = updateVisibilityStructures;
  90445. exports.version = version;
  90446. exports.workerPool = workerPool;
  90447. Object.defineProperty(exports, '__esModule', { value: true });
  90448. })));
  90449. //# sourceMappingURL=potree.js.map