Scene.cs 260 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Diagnostics;
  30. using System.Drawing;
  31. using System.Drawing.Imaging;
  32. using System.IO;
  33. using System.Runtime;
  34. using System.Text;
  35. using System.Threading;
  36. using System.Timers;
  37. using System.Xml;
  38. using Nini.Config;
  39. using OpenMetaverse;
  40. using OpenMetaverse.Packets;
  41. using OpenMetaverse.Imaging;
  42. using OpenMetaverse.StructuredData;
  43. using OpenSim.Framework;
  44. using OpenSim.Framework.Monitoring;
  45. using OpenSim.Services.Interfaces;
  46. using OpenSim.Framework.Console;
  47. using OpenSim.Region.Framework.Interfaces;
  48. using OpenSim.Region.Framework.Scenes.Scripting;
  49. using OpenSim.Region.Framework.Scenes.Serialization;
  50. using OpenSim.Region.PhysicsModules.SharedBase;
  51. using Timer = System.Timers.Timer;
  52. using TPFlags = OpenSim.Framework.Constants.TeleportFlags;
  53. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  54. using PermissionMask = OpenSim.Framework.PermissionMask;
  55. namespace OpenSim.Region.Framework.Scenes
  56. {
  57. public delegate bool FilterAvatarList(ScenePresence avatar);
  58. public partial class Scene : SceneBase
  59. {
  60. private const long DEFAULT_MIN_TIME_FOR_PERSISTENCE = 60L;
  61. private const long DEFAULT_MAX_TIME_FOR_PERSISTENCE = 600L;
  62. public delegate void SynchronizeSceneHandler(Scene scene);
  63. #region Fields
  64. /// <summary>
  65. /// Show debug information about animations.
  66. /// </summary>
  67. public bool DebugAnimations { get; set; }
  68. /// <summary>
  69. /// Show debug information about teleports.
  70. /// </summary>
  71. public bool DebugTeleporting { get; set; }
  72. /// <summary>
  73. /// Show debug information about the scene loop.
  74. /// </summary>
  75. public bool DebugUpdates { get; set; }
  76. /// <summary>
  77. /// If true then the scene is saved to persistent storage periodically, every m_update_backup frames and
  78. /// if objects meet required conditions (m_dontPersistBefore and m_dontPersistAfter).
  79. /// </summary>
  80. /// <remarks>
  81. /// Even if false, the scene will still be saved on clean shutdown.
  82. /// FIXME: Currently, setting this to false will mean that objects are not periodically returned from parcels.
  83. /// This needs to be fixed.
  84. /// </remarks>
  85. public bool PeriodicBackup { get; set; }
  86. /// <summary>
  87. /// If false then the scene is never saved to persistence storage even if PeriodicBackup == true and even
  88. /// if the scene is being shut down for the final time.
  89. /// </summary>
  90. public bool UseBackup { get; set; }
  91. /// <summary>
  92. /// If false then physical objects are disabled, though collisions will continue as normal.
  93. /// </summary>
  94. public bool PhysicsEnabled
  95. {
  96. get
  97. {
  98. return m_physicsEnabled;
  99. }
  100. set
  101. {
  102. m_physicsEnabled = value;
  103. if (PhysicsScene != null)
  104. {
  105. IPhysicsParameters physScene = PhysicsScene as IPhysicsParameters;
  106. if (physScene != null)
  107. physScene.SetPhysicsParameter(
  108. "Active", m_physicsEnabled.ToString(), PhysParameterEntry.APPLY_TO_NONE);
  109. }
  110. }
  111. }
  112. private bool m_physicsEnabled;
  113. /// <summary>
  114. /// If false then scripts are not enabled on the smiulator
  115. /// </summary>
  116. public bool ScriptsEnabled
  117. {
  118. get { return m_scripts_enabled; }
  119. set
  120. {
  121. if (m_scripts_enabled != value)
  122. {
  123. if (!value)
  124. {
  125. m_log.Info("Stopping all Scripts in Scene");
  126. EntityBase[] entities = Entities.GetEntities();
  127. foreach (EntityBase ent in entities)
  128. {
  129. if (ent is SceneObjectGroup)
  130. ((SceneObjectGroup)ent).RemoveScriptInstances(false);
  131. }
  132. }
  133. else
  134. {
  135. m_log.Info("Starting all Scripts in Scene");
  136. EntityBase[] entities = Entities.GetEntities();
  137. foreach (EntityBase ent in entities)
  138. {
  139. if (ent is SceneObjectGroup)
  140. {
  141. SceneObjectGroup sog = (SceneObjectGroup)ent;
  142. sog.CreateScriptInstances(0, false, DefaultScriptEngine, 0);
  143. sog.ResumeScripts();
  144. }
  145. }
  146. }
  147. m_scripts_enabled = value;
  148. }
  149. }
  150. }
  151. private bool m_scripts_enabled;
  152. public bool ClampNegativeZ
  153. {
  154. get { return m_clampNegativeZ; }
  155. }
  156. private bool m_clampNegativeZ = false;
  157. /// <summary>
  158. /// Used to prevent simultaneous calls to code that adds and removes agents.
  159. /// </summary>
  160. private object m_removeClientLock = new object();
  161. /// <summary>
  162. /// Statistical information for this scene.
  163. /// </summary>
  164. public SimStatsReporter StatsReporter { get; private set; }
  165. /// <summary>
  166. /// Controls whether physics can be applied to prims. Even if false, prims still have entries in a
  167. /// PhysicsScene in order to perform collision detection
  168. /// </summary>
  169. public bool PhysicalPrims { get; private set; }
  170. /// <summary>
  171. /// Controls whether prims can be collided with.
  172. /// </summary>
  173. /// <remarks>
  174. /// If this is set to false then prims cannot be subject to physics either.
  175. /// </summary>
  176. public bool CollidablePrims { get; private set; }
  177. /// <summary>
  178. /// Minimum value of the size of a non-physical prim in each axis
  179. /// </summary>
  180. public float m_minNonphys = 0.001f;
  181. /// <summary>
  182. /// Maximum value of the size of a non-physical prim in each axis
  183. /// </summary>
  184. public float m_maxNonphys = 256;
  185. /// <summary>
  186. /// Minimum value of the size of a physical prim in each axis
  187. /// </summary>
  188. public float m_minPhys = 0.01f;
  189. /// <summary>
  190. /// Maximum value of the size of a physical prim in each axis
  191. /// </summary>
  192. public float m_maxPhys = 10;
  193. /// <summary>
  194. /// Max prims an object will hold
  195. /// </summary>
  196. public int m_linksetCapacity = 0;
  197. public bool m_clampPrimSize;
  198. public bool m_trustBinaries;
  199. public bool m_allowScriptCrossings = true;
  200. /// <summary>
  201. /// use legacy sittarget offsets to avoid contents breaks
  202. /// to compensate for SL bug
  203. /// </summary>
  204. public bool LegacySitOffsets = true;
  205. /// <summary>
  206. /// Can avatars cross from and to this region?
  207. /// </summary>
  208. public bool AllowAvatarCrossing { get; set; }
  209. /// Max prims an Physical object will hold
  210. /// </summary>
  211. ///
  212. public int m_linksetPhysCapacity = 0;
  213. /// <summary>
  214. /// When placed outside the region's border, do we transfer the objects or
  215. /// do we keep simulating them here?
  216. /// </summary>
  217. public bool DisableObjectTransfer { get; set; }
  218. public bool m_useFlySlow;
  219. public bool m_useTrashOnDelete = true;
  220. protected float m_defaultDrawDistance = 255f;
  221. protected float m_defaultCullingDrawDistance = 16f;
  222. public float DefaultDrawDistance
  223. {
  224. get { return ObjectsCullingByDistance?m_defaultCullingDrawDistance:m_defaultDrawDistance; }
  225. }
  226. protected float m_maxDrawDistance = 512.0f;
  227. // protected float m_maxDrawDistance = 256.0f;
  228. public float MaxDrawDistance
  229. {
  230. get { return m_maxDrawDistance; }
  231. }
  232. protected float m_maxRegionViewDistance = 255f;
  233. public float MaxRegionViewDistance
  234. {
  235. get { return m_maxRegionViewDistance; }
  236. }
  237. protected float m_minRegionViewDistance = 96f;
  238. public float MinRegionViewDistance
  239. {
  240. get { return m_minRegionViewDistance; }
  241. }
  242. private List<string> m_AllowedViewers = new List<string>();
  243. private List<string> m_BannedViewers = new List<string>();
  244. // TODO: need to figure out how allow client agents but deny
  245. // root agents when ACL denies access to root agent
  246. public bool m_strictAccessControl = true;
  247. public bool m_seeIntoBannedRegion = false;
  248. public int MaxUndoCount = 5;
  249. public bool SeeIntoRegion { get; set; }
  250. // Using this for RegionReady module to prevent LoginsDisabled from changing under our feet;
  251. public bool LoginLock = false;
  252. public bool StartDisabled = false;
  253. public bool LoadingPrims;
  254. public IXfer XferManager;
  255. // the minimum time that must elapse before a changed object will be considered for persisted
  256. public long m_dontPersistBefore = DEFAULT_MIN_TIME_FOR_PERSISTENCE * 10000000L;
  257. // the maximum time that must elapse before a changed object will be considered for persisted
  258. public long m_persistAfter = DEFAULT_MAX_TIME_FOR_PERSISTENCE * 10000000L;
  259. protected int m_splitRegionID;
  260. protected Timer m_restartWaitTimer = new Timer();
  261. protected Timer m_timerWatchdog = new Timer();
  262. protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
  263. protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
  264. protected string m_simulatorVersion = "OpenSimulator Server";
  265. protected AgentCircuitManager m_authenticateHandler;
  266. protected SceneCommunicationService m_sceneGridService;
  267. protected ISnmpModule m_snmpService = null;
  268. protected ISimulationDataService m_SimulationDataService;
  269. protected IEstateDataService m_EstateDataService;
  270. protected IAssetService m_AssetService;
  271. protected IAuthorizationService m_AuthorizationService;
  272. protected IInventoryService m_InventoryService;
  273. protected IGridService m_GridService;
  274. protected ILibraryService m_LibraryService;
  275. protected ISimulationService m_simulationService;
  276. protected IAuthenticationService m_AuthenticationService;
  277. protected IPresenceService m_PresenceService;
  278. protected IUserAccountService m_UserAccountService;
  279. protected IAvatarService m_AvatarService;
  280. protected IGridUserService m_GridUserService;
  281. protected IAgentPreferencesService m_AgentPreferencesService;
  282. protected IXMLRPC m_xmlrpcModule;
  283. protected IWorldComm m_worldCommModule;
  284. protected IAvatarFactoryModule m_AvatarFactory;
  285. protected IConfigSource m_config;
  286. protected IRegionSerialiserModule m_serialiser;
  287. protected IDialogModule m_dialogModule;
  288. protected ICapabilitiesModule m_capsModule;
  289. protected IGroupsModule m_groupsModule;
  290. private Dictionary<string, string> m_extraSettings;
  291. /// <summary>
  292. /// Current scene frame number
  293. /// </summary>
  294. public uint Frame
  295. {
  296. get;
  297. protected set;
  298. }
  299. /// <summary>
  300. /// Frame time
  301. /// </remarks>
  302. public float FrameTime { get; private set; }
  303. public int FrameTimeWarnPercent { get; private set; }
  304. public int FrameTimeCritPercent { get; private set; }
  305. // Normalize the frame related stats to nominal 55fps for viewer and scripts option
  306. // see SimStatsReporter.cs
  307. public bool Normalized55FPS { get; private set; }
  308. private int m_update_physics = 1;
  309. private int m_update_entitymovement = 1;
  310. private int m_update_objects = 1;
  311. private int m_update_presences = 1; // Update scene presence movements
  312. private int m_update_events = 1;
  313. private int m_update_backup = 200;
  314. private int m_update_terrain = 1000;
  315. private int m_update_coarse_locations = 5;
  316. private int m_update_temp_cleaning = 180;
  317. private float agentMS;
  318. private float frameMS;
  319. private float physicsMS2;
  320. private float physicsMS;
  321. private float otherMS;
  322. private float tempOnRezMS;
  323. private float eventMS;
  324. private float backupMS;
  325. private float terrainMS;
  326. private float landMS;
  327. /// <summary>
  328. /// Tick at which the last frame was processed.
  329. /// </summary>
  330. private int m_lastFrameTick;
  331. /// <summary>
  332. /// Total script execution time (in Stopwatch Ticks) since the last frame
  333. /// </summary>
  334. private long m_scriptExecutionTime = 0;
  335. /// <summary>
  336. /// Signals whether temporary objects are currently being cleaned up. Needed because this is launched
  337. /// asynchronously from the update loop.
  338. /// </summary>
  339. private bool m_cleaningTemps = false;
  340. private bool m_sendingCoarseLocations = false; // same for async course locations sending
  341. /// <summary>
  342. /// Used to control main scene thread looping time when not updating via timer.
  343. /// </summary>
  344. private ManualResetEvent m_updateWaitEvent = new ManualResetEvent(false);
  345. // TODO: Possibly stop other classes being able to manipulate this directly.
  346. private SceneGraph m_sceneGraph;
  347. private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing
  348. private volatile bool m_backingup;
  349. private Dictionary<UUID, ReturnInfo> m_returns = new Dictionary<UUID, ReturnInfo>();
  350. private HashSet<UUID> m_groupsWithTargets = new HashSet<UUID>();
  351. private string m_defaultScriptEngine;
  352. private int m_unixStartTime;
  353. public int UnixStartTime
  354. {
  355. get { return m_unixStartTime; }
  356. }
  357. /// <summary>
  358. /// Tick at which the last login occurred.
  359. /// </summary>
  360. private int m_LastLogin;
  361. private int m_lastIncoming;
  362. private int m_lastOutgoing;
  363. private int m_hbRestarts = 0;
  364. /// <summary>
  365. /// Thread that runs the scene loop.
  366. /// </summary>
  367. private Thread m_heartbeatThread;
  368. /// <summary>
  369. /// True if these scene is in the process of shutting down or is shutdown.
  370. /// </summary>
  371. public bool ShuttingDown
  372. {
  373. get { return m_shuttingDown; }
  374. }
  375. private volatile bool m_shuttingDown;
  376. /// <summary>
  377. /// Is the scene active?
  378. /// </summary>
  379. /// <remarks>
  380. /// If false, update loop is not being run, though after setting to false update may still
  381. /// be active for a period (and IsRunning will still be true). Updates can still be triggered manually if
  382. /// the scene is not active.
  383. /// </remarks>
  384. public bool Active
  385. {
  386. get { return m_active; }
  387. set
  388. {
  389. if (value)
  390. {
  391. if (!m_active)
  392. Start(false);
  393. }
  394. else
  395. {
  396. // This appears assymetric with Start() above but is not - setting m_active = false stops the loops
  397. // XXX: Possibly this should be in an explicit Stop() method for symmetry.
  398. m_active = false;
  399. }
  400. }
  401. }
  402. private volatile bool m_active;
  403. /// <summary>
  404. /// If true then updates are running. This may be true for a short period after a scene is de-activated.
  405. /// </summary>
  406. public bool IsRunning { get { return m_isRunning; } }
  407. private volatile bool m_isRunning;
  408. private bool m_firstHeartbeat = true;
  409. // private UpdatePrioritizationSchemes m_priorityScheme = UpdatePrioritizationSchemes.Time;
  410. // private bool m_reprioritizationEnabled = true;
  411. // private double m_reprioritizationInterval = 5000.0;
  412. // private double m_rootReprioritizationDistance = 10.0;
  413. // private double m_childReprioritizationDistance = 20.0;
  414. private Timer m_mapGenerationTimer = new Timer();
  415. private bool m_generateMaptiles;
  416. protected int m_lastHealth = -1;
  417. protected int m_lastUsers = -1;
  418. #endregion Fields
  419. #region Properties
  420. /* Used by the loadbalancer plugin on GForge */
  421. public int SplitRegionID
  422. {
  423. get { return m_splitRegionID; }
  424. set { m_splitRegionID = value; }
  425. }
  426. public new float TimeDilation
  427. {
  428. get { return m_sceneGraph.PhysicsScene.TimeDilation; }
  429. }
  430. public void setThreadCount(int inUseThreads)
  431. {
  432. // Just pass the thread count information on its way as the Scene
  433. // does not require the value for anything at this time
  434. StatsReporter.SetThreadCount(inUseThreads);
  435. }
  436. public SceneCommunicationService SceneGridService
  437. {
  438. get { return m_sceneGridService; }
  439. }
  440. public ISnmpModule SnmpService
  441. {
  442. get
  443. {
  444. if (m_snmpService == null)
  445. {
  446. m_snmpService = RequestModuleInterface<ISnmpModule>();
  447. }
  448. return m_snmpService;
  449. }
  450. }
  451. public ISimulationDataService SimulationDataService
  452. {
  453. get
  454. {
  455. if (m_SimulationDataService == null)
  456. {
  457. m_SimulationDataService = RequestModuleInterface<ISimulationDataService>();
  458. if (m_SimulationDataService == null)
  459. {
  460. throw new Exception("No ISimulationDataService available.");
  461. }
  462. }
  463. return m_SimulationDataService;
  464. }
  465. }
  466. public IEstateDataService EstateDataService
  467. {
  468. get
  469. {
  470. if (m_EstateDataService == null)
  471. {
  472. m_EstateDataService = RequestModuleInterface<IEstateDataService>();
  473. if (m_EstateDataService == null)
  474. {
  475. throw new Exception("No IEstateDataService available.");
  476. }
  477. }
  478. return m_EstateDataService;
  479. }
  480. }
  481. public IAssetService AssetService
  482. {
  483. get
  484. {
  485. if (m_AssetService == null)
  486. {
  487. m_AssetService = RequestModuleInterface<IAssetService>();
  488. if (m_AssetService == null)
  489. {
  490. throw new Exception("No IAssetService available.");
  491. }
  492. }
  493. return m_AssetService;
  494. }
  495. }
  496. public IAuthorizationService AuthorizationService
  497. {
  498. get
  499. {
  500. if (m_AuthorizationService == null)
  501. {
  502. m_AuthorizationService = RequestModuleInterface<IAuthorizationService>();
  503. //if (m_AuthorizationService == null)
  504. //{
  505. // // don't throw an exception if no authorization service is set for the time being
  506. // m_log.InfoFormat("[SCENE]: No Authorization service is configured");
  507. //}
  508. }
  509. return m_AuthorizationService;
  510. }
  511. }
  512. public IInventoryService InventoryService
  513. {
  514. get
  515. {
  516. if (m_InventoryService == null)
  517. {
  518. m_InventoryService = RequestModuleInterface<IInventoryService>();
  519. if (m_InventoryService == null)
  520. {
  521. throw new Exception("No IInventoryService available. This could happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. Please also check that you have the correct version of your inventory service dll. Sometimes old versions of this dll will still exist. Do a clean checkout and re-create the opensim.ini from the opensim.ini.example.");
  522. }
  523. }
  524. return m_InventoryService;
  525. }
  526. }
  527. public IGridService GridService
  528. {
  529. get
  530. {
  531. if (m_GridService == null)
  532. {
  533. m_GridService = RequestModuleInterface<IGridService>();
  534. if (m_GridService == null)
  535. {
  536. throw new Exception("No IGridService available. This could happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. Please also check that you have the correct version of your inventory service dll. Sometimes old versions of this dll will still exist. Do a clean checkout and re-create the opensim.ini from the opensim.ini.example.");
  537. }
  538. }
  539. return m_GridService;
  540. }
  541. }
  542. public ILibraryService LibraryService
  543. {
  544. get
  545. {
  546. if (m_LibraryService == null)
  547. m_LibraryService = RequestModuleInterface<ILibraryService>();
  548. return m_LibraryService;
  549. }
  550. }
  551. public ISimulationService SimulationService
  552. {
  553. get
  554. {
  555. if (m_simulationService == null)
  556. m_simulationService = RequestModuleInterface<ISimulationService>();
  557. return m_simulationService;
  558. }
  559. }
  560. public IAuthenticationService AuthenticationService
  561. {
  562. get
  563. {
  564. if (m_AuthenticationService == null)
  565. m_AuthenticationService = RequestModuleInterface<IAuthenticationService>();
  566. return m_AuthenticationService;
  567. }
  568. }
  569. public IPresenceService PresenceService
  570. {
  571. get
  572. {
  573. if (m_PresenceService == null)
  574. m_PresenceService = RequestModuleInterface<IPresenceService>();
  575. return m_PresenceService;
  576. }
  577. }
  578. public IUserAccountService UserAccountService
  579. {
  580. get
  581. {
  582. if (m_UserAccountService == null)
  583. m_UserAccountService = RequestModuleInterface<IUserAccountService>();
  584. return m_UserAccountService;
  585. }
  586. }
  587. public IAvatarService AvatarService
  588. {
  589. get
  590. {
  591. if (m_AvatarService == null)
  592. m_AvatarService = RequestModuleInterface<IAvatarService>();
  593. return m_AvatarService;
  594. }
  595. }
  596. public IGridUserService GridUserService
  597. {
  598. get
  599. {
  600. if (m_GridUserService == null)
  601. m_GridUserService = RequestModuleInterface<IGridUserService>();
  602. return m_GridUserService;
  603. }
  604. }
  605. public IAgentPreferencesService AgentPreferencesService
  606. {
  607. get
  608. {
  609. if (m_AgentPreferencesService == null)
  610. m_AgentPreferencesService = RequestModuleInterface<IAgentPreferencesService>();
  611. return m_AgentPreferencesService;
  612. }
  613. }
  614. public IAttachmentsModule AttachmentsModule { get; set; }
  615. public IEntityTransferModule EntityTransferModule { get; private set; }
  616. public IAgentAssetTransactions AgentTransactionsModule { get; private set; }
  617. public IUserManagement UserManagementModule { get; private set; }
  618. public IAvatarFactoryModule AvatarFactory
  619. {
  620. get { return m_AvatarFactory; }
  621. }
  622. public ICapabilitiesModule CapsModule
  623. {
  624. get { return m_capsModule; }
  625. }
  626. public int MonitorFrameTime { get { return (int)frameMS; } }
  627. public int MonitorPhysicsUpdateTime { get { return (int)physicsMS; } }
  628. public int MonitorPhysicsSyncTime { get { return (int)physicsMS2; } }
  629. public int MonitorOtherTime { get { return (int)otherMS; } }
  630. public int MonitorTempOnRezTime { get { return (int)tempOnRezMS; } }
  631. public int MonitorEventTime { get { return (int)eventMS; } } // This may need to be divided into each event?
  632. public int MonitorBackupTime { get { return (int)backupMS; } }
  633. public int MonitorTerrainTime { get { return (int)terrainMS; } }
  634. public int MonitorLandTime { get { return (int)landMS; } }
  635. public int MonitorLastFrameTick { get { return m_lastFrameTick; } }
  636. public UpdatePrioritizationSchemes UpdatePrioritizationScheme { get; set; }
  637. public bool IsReprioritizationEnabled { get; set; }
  638. public float ReprioritizationInterval { get; set; }
  639. public float ReprioritizationDistance { get; set; }
  640. private float m_minReprioritizationDistance = 32f;
  641. public bool ObjectsCullingByDistance = false;
  642. private ExpiringCache<UUID, UUID> TeleportTargetsCoolDown = new ExpiringCache<UUID, UUID>();
  643. public AgentCircuitManager AuthenticateHandler
  644. {
  645. get { return m_authenticateHandler; }
  646. }
  647. // an instance to the physics plugin's Scene object.
  648. public PhysicsScene PhysicsScene
  649. {
  650. get { return m_sceneGraph.PhysicsScene; }
  651. set
  652. {
  653. // If we're not doing the initial set
  654. // Then we've got to remove the previous
  655. // event handler
  656. if (PhysicsScene != null && PhysicsScene.SupportsNINJAJoints)
  657. {
  658. PhysicsScene.OnJointMoved -= jointMoved;
  659. PhysicsScene.OnJointDeactivated -= jointDeactivated;
  660. PhysicsScene.OnJointErrorMessage -= jointErrorMessage;
  661. }
  662. m_sceneGraph.PhysicsScene = value;
  663. if (PhysicsScene != null && m_sceneGraph.PhysicsScene.SupportsNINJAJoints)
  664. {
  665. // register event handlers to respond to joint movement/deactivation
  666. PhysicsScene.OnJointMoved += jointMoved;
  667. PhysicsScene.OnJointDeactivated += jointDeactivated;
  668. PhysicsScene.OnJointErrorMessage += jointErrorMessage;
  669. }
  670. }
  671. }
  672. public string DefaultScriptEngine
  673. {
  674. get { return m_defaultScriptEngine; }
  675. }
  676. public EntityManager Entities
  677. {
  678. get { return m_sceneGraph.Entities; }
  679. }
  680. // used in sequence see: SpawnPoint()
  681. private int m_SpawnPoint;
  682. // can be closest/random/sequence
  683. public string SpawnPointRouting
  684. {
  685. get;
  686. private set;
  687. }
  688. // allow landmarks to pass
  689. public bool TelehubAllowLandmarks
  690. {
  691. get;
  692. private set;
  693. }
  694. #endregion Properties
  695. #region Constructors
  696. public Scene(RegionInfo regInfo, AgentCircuitManager authen,
  697. ISimulationDataService simDataService, IEstateDataService estateDataService,
  698. IConfigSource config, string simulatorVersion)
  699. : this(regInfo)
  700. {
  701. m_config = config;
  702. FrameTime = 0.0908f;
  703. FrameTimeWarnPercent = 60;
  704. FrameTimeCritPercent = 40;
  705. Normalized55FPS = true;
  706. SeeIntoRegion = true;
  707. Random random = new Random();
  708. m_lastAllocatedLocalId = (int)(random.NextDouble() * (uint.MaxValue / 4));
  709. m_lastAllocatedIntId = (int)(random.NextDouble() * (int.MaxValue / 4));
  710. m_authenticateHandler = authen;
  711. m_sceneGridService = new SceneCommunicationService();
  712. m_SimulationDataService = simDataService;
  713. m_EstateDataService = estateDataService;
  714. m_lastIncoming = 0;
  715. m_lastOutgoing = 0;
  716. m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
  717. m_asyncSceneObjectDeleter.Enabled = true;
  718. m_asyncInventorySender = new AsyncInventorySender(this);
  719. #region Region Settings
  720. // Load region settings
  721. // LoadRegionSettings creates new region settings in persistence if they don't already exist for this region.
  722. // However, in this case, the default textures are not set in memory properly, so we need to do it here and
  723. // resave.
  724. // FIXME: It shouldn't be up to the database plugins to create this data - we should do it when a new
  725. // region is set up and avoid these gyrations.
  726. RegionSettings rs = simDataService.LoadRegionSettings(RegionInfo.RegionID);
  727. m_extraSettings = simDataService.GetExtra(RegionInfo.RegionID);
  728. bool updatedTerrainTextures = false;
  729. if (rs.TerrainTexture1 == UUID.Zero)
  730. {
  731. rs.TerrainTexture1 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_1;
  732. updatedTerrainTextures = true;
  733. }
  734. if (rs.TerrainTexture2 == UUID.Zero)
  735. {
  736. rs.TerrainTexture2 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_2;
  737. updatedTerrainTextures = true;
  738. }
  739. if (rs.TerrainTexture3 == UUID.Zero)
  740. {
  741. rs.TerrainTexture3 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_3;
  742. updatedTerrainTextures = true;
  743. }
  744. if (rs.TerrainTexture4 == UUID.Zero)
  745. {
  746. rs.TerrainTexture4 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_4;
  747. updatedTerrainTextures = true;
  748. }
  749. if (updatedTerrainTextures)
  750. rs.Save();
  751. RegionInfo.RegionSettings = rs;
  752. if (estateDataService != null)
  753. RegionInfo.EstateSettings = estateDataService.LoadEstateSettings(RegionInfo.RegionID, false);
  754. #endregion Region Settings
  755. //Bind Storage Manager functions to some land manager functions for this scene
  756. EventManager.OnLandObjectAdded +=
  757. new EventManager.LandObjectAdded(simDataService.StoreLandObject);
  758. EventManager.OnLandObjectRemoved +=
  759. new EventManager.LandObjectRemoved(simDataService.RemoveLandObject);
  760. RegisterDefaultSceneEvents();
  761. // XXX: Don't set the public property since we don't want to activate here. This needs to be handled
  762. // better in the future.
  763. m_scripts_enabled = !RegionInfo.RegionSettings.DisableScripts;
  764. PhysicsEnabled = !RegionInfo.RegionSettings.DisablePhysics;
  765. m_simulatorVersion = simulatorVersion + " (" + Util.GetRuntimeInformation() + ")";
  766. #region Region Config
  767. // Region config overrides global config
  768. //
  769. if (m_config.Configs["Startup"] != null)
  770. {
  771. IConfig startupConfig = m_config.Configs["Startup"];
  772. StartDisabled = startupConfig.GetBoolean("StartDisabled", false);
  773. m_defaultDrawDistance = startupConfig.GetFloat("DefaultDrawDistance", m_defaultDrawDistance);
  774. m_maxDrawDistance = startupConfig.GetFloat("MaxDrawDistance", m_maxDrawDistance);
  775. m_maxRegionViewDistance = startupConfig.GetFloat("MaxRegionsViewDistance", m_maxRegionViewDistance);
  776. m_minRegionViewDistance = startupConfig.GetFloat("MinRegionsViewDistance", m_minRegionViewDistance);
  777. // old versions compatibility
  778. LegacySitOffsets = startupConfig.GetBoolean("LegacySitOffsets", LegacySitOffsets);
  779. if (m_defaultDrawDistance > m_maxDrawDistance)
  780. m_defaultDrawDistance = m_maxDrawDistance;
  781. if (m_maxRegionViewDistance > m_maxDrawDistance)
  782. m_maxRegionViewDistance = m_maxDrawDistance;
  783. if(m_minRegionViewDistance < 96f)
  784. m_minRegionViewDistance = 96f;
  785. if(m_minRegionViewDistance > m_maxRegionViewDistance)
  786. m_minRegionViewDistance = m_maxRegionViewDistance;
  787. UseBackup = startupConfig.GetBoolean("UseSceneBackup", UseBackup);
  788. if (!UseBackup)
  789. m_log.InfoFormat("[SCENE]: Backup has been disabled for {0}", RegionInfo.RegionName);
  790. //Animation states
  791. m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
  792. SeeIntoRegion = startupConfig.GetBoolean("see_into_region", SeeIntoRegion);
  793. MaxUndoCount = startupConfig.GetInt("MaxPrimUndos", 20);
  794. PhysicalPrims = startupConfig.GetBoolean("physical_prim", true);
  795. CollidablePrims = startupConfig.GetBoolean("collidable_prim", true);
  796. m_minNonphys = startupConfig.GetFloat("NonPhysicalPrimMin", m_minNonphys);
  797. if (RegionInfo.NonphysPrimMin > 0)
  798. {
  799. m_minNonphys = RegionInfo.NonphysPrimMin;
  800. }
  801. // don't allow nonsense values
  802. if(m_minNonphys < 0.001f)
  803. m_minNonphys = 0.001f;
  804. m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", m_maxNonphys);
  805. if (RegionInfo.NonphysPrimMax > 0)
  806. {
  807. m_maxNonphys = RegionInfo.NonphysPrimMax;
  808. }
  809. if (m_maxNonphys > 65536)
  810. m_maxNonphys = 65536;
  811. m_minPhys = startupConfig.GetFloat("PhysicalPrimMin", m_minPhys);
  812. if (RegionInfo.PhysPrimMin > 0)
  813. {
  814. m_minPhys = RegionInfo.PhysPrimMin;
  815. }
  816. if(m_minPhys < 0.01f)
  817. m_minPhys = 0.01f;
  818. m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys);
  819. if (RegionInfo.PhysPrimMax > 0)
  820. {
  821. m_maxPhys = RegionInfo.PhysPrimMax;
  822. }
  823. if (m_maxPhys > 2048)
  824. m_maxPhys = 2048;
  825. m_linksetCapacity = startupConfig.GetInt("LinksetPrims", m_linksetCapacity);
  826. if (RegionInfo.LinksetCapacity > 0)
  827. {
  828. m_linksetCapacity = RegionInfo.LinksetCapacity;
  829. }
  830. m_linksetPhysCapacity = startupConfig.GetInt("LinksetPhysPrims", m_linksetPhysCapacity);
  831. SpawnPointRouting = startupConfig.GetString("SpawnPointRouting", "closest");
  832. TelehubAllowLandmarks = startupConfig.GetBoolean("TelehubAllowLandmark", false);
  833. // Here, if clamping is requested in either global or
  834. // local config, it will be used
  835. //
  836. m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize);
  837. if (RegionInfo.ClampPrimSize)
  838. {
  839. m_clampPrimSize = true;
  840. }
  841. m_clampNegativeZ = startupConfig.GetBoolean("ClampNegativeZ", m_clampNegativeZ);
  842. m_useTrashOnDelete = startupConfig.GetBoolean("UseTrashOnDelete",m_useTrashOnDelete);
  843. m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries);
  844. m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
  845. m_dontPersistBefore = startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
  846. m_dontPersistBefore *= 10000000;
  847. m_persistAfter = startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
  848. m_persistAfter *= 10000000;
  849. m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "XEngine");
  850. m_log.InfoFormat("[SCENE]: Default script engine {0}", m_defaultScriptEngine);
  851. m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl);
  852. m_seeIntoBannedRegion = startupConfig.GetBoolean("SeeIntoBannedRegion", m_seeIntoBannedRegion);
  853. string[] possibleMapConfigSections = new string[] { "Map", "Startup" };
  854. m_generateMaptiles
  855. = Util.GetConfigVarFromSections<bool>(config, "GenerateMaptiles", possibleMapConfigSections, true);
  856. if (m_generateMaptiles)
  857. {
  858. int maptileRefresh = Util.GetConfigVarFromSections<int>(config, "MaptileRefresh", possibleMapConfigSections, 0);
  859. m_log.InfoFormat("[SCENE]: Region {0}, WORLD MAP refresh time set to {1} seconds", RegionInfo.RegionName, maptileRefresh);
  860. if (maptileRefresh != 0)
  861. {
  862. m_mapGenerationTimer.Interval = maptileRefresh * 1000;
  863. m_mapGenerationTimer.Elapsed += RegenerateMaptileAndReregister;
  864. m_mapGenerationTimer.AutoReset = false;
  865. m_mapGenerationTimer.Start();
  866. }
  867. }
  868. else
  869. {
  870. string tile
  871. = Util.GetConfigVarFromSections<string>(
  872. config, "MaptileStaticUUID", possibleMapConfigSections, UUID.Zero.ToString());
  873. UUID tileID;
  874. if (tile != UUID.Zero.ToString() && UUID.TryParse(tile, out tileID))
  875. {
  876. RegionInfo.RegionSettings.TerrainImageID = tileID;
  877. }
  878. else
  879. {
  880. RegionInfo.RegionSettings.TerrainImageID = RegionInfo.MaptileStaticUUID;
  881. m_log.InfoFormat("[SCENE]: Region {0}, maptile set to {1}", RegionInfo.RegionName, RegionInfo.MaptileStaticUUID.ToString());
  882. }
  883. }
  884. string[] possibleAccessControlConfigSections = new string[] { "Startup", "AccessControl"};
  885. string grant
  886. = Util.GetConfigVarFromSections<string>(
  887. config, "AllowedClients", possibleAccessControlConfigSections, string.Empty);
  888. if (grant.Length > 0)
  889. {
  890. foreach (string viewer in grant.Split(','))
  891. {
  892. m_AllowedViewers.Add(viewer.Trim().ToLower());
  893. }
  894. }
  895. grant
  896. = Util.GetConfigVarFromSections<string>(
  897. config, "DeniedClients", possibleAccessControlConfigSections, String.Empty);
  898. // Deal with the mess of someone having used a different word at some point
  899. if (grant == String.Empty)
  900. grant = Util.GetConfigVarFromSections<string>(
  901. config, "BannedClients", possibleAccessControlConfigSections, String.Empty);
  902. if (grant.Length > 0)
  903. {
  904. foreach (string viewer in grant.Split(','))
  905. {
  906. m_BannedViewers.Add(viewer.Trim().ToLower());
  907. }
  908. }
  909. FrameTime = startupConfig.GetFloat( "FrameTime", FrameTime);
  910. FrameTimeWarnPercent = startupConfig.GetInt( "FrameTimeWarnPercent", FrameTimeWarnPercent);
  911. FrameTimeCritPercent = startupConfig.GetInt( "FrameTimeCritPercent", FrameTimeCritPercent);
  912. Normalized55FPS = startupConfig.GetBoolean( "Normalized55FPS", Normalized55FPS);
  913. m_update_backup = startupConfig.GetInt("UpdateStorageEveryNFrames", m_update_backup);
  914. m_update_coarse_locations = startupConfig.GetInt("UpdateCoarseLocationsEveryNFrames", m_update_coarse_locations);
  915. m_update_entitymovement = startupConfig.GetInt("UpdateEntityMovementEveryNFrames", m_update_entitymovement);
  916. m_update_events = startupConfig.GetInt("UpdateEventsEveryNFrames", m_update_events);
  917. m_update_objects = startupConfig.GetInt("UpdateObjectsEveryNFrames", m_update_objects);
  918. m_update_physics = startupConfig.GetInt("UpdatePhysicsEveryNFrames", m_update_physics);
  919. m_update_presences = startupConfig.GetInt("UpdateAgentsEveryNFrames", m_update_presences);
  920. m_update_terrain = startupConfig.GetInt("UpdateTerrainEveryNFrames", m_update_terrain);
  921. m_update_temp_cleaning = startupConfig.GetInt("UpdateTempCleaningEveryNSeconds", m_update_temp_cleaning);
  922. }
  923. #endregion Region Config
  924. IConfig entityTransferConfig = m_config.Configs["EntityTransfer"];
  925. if (entityTransferConfig != null)
  926. {
  927. AllowAvatarCrossing = entityTransferConfig.GetBoolean("AllowAvatarCrossing", AllowAvatarCrossing);
  928. DisableObjectTransfer = entityTransferConfig.GetBoolean("DisableObjectTransfer", false);
  929. }
  930. #region Interest Management
  931. IConfig interestConfig = m_config.Configs["InterestManagement"];
  932. if (interestConfig != null)
  933. {
  934. string update_prioritization_scheme = interestConfig.GetString("UpdatePrioritizationScheme", "Time").Trim().ToLower();
  935. try
  936. {
  937. UpdatePrioritizationScheme = (UpdatePrioritizationSchemes)Enum.Parse(typeof(UpdatePrioritizationSchemes), update_prioritization_scheme, true);
  938. }
  939. catch (Exception)
  940. {
  941. m_log.Warn("[PRIORITIZER]: UpdatePrioritizationScheme was not recognized, setting to default BestAvatarResponsiveness");
  942. UpdatePrioritizationScheme = UpdatePrioritizationSchemes.BestAvatarResponsiveness;
  943. }
  944. IsReprioritizationEnabled
  945. = interestConfig.GetBoolean("ReprioritizationEnabled", IsReprioritizationEnabled);
  946. ReprioritizationInterval
  947. = interestConfig.GetFloat("ReprioritizationInterval", ReprioritizationInterval);
  948. ReprioritizationDistance
  949. = interestConfig.GetFloat("RootReprioritizationDistance", ReprioritizationDistance);
  950. if(ReprioritizationDistance < m_minReprioritizationDistance)
  951. ReprioritizationDistance = m_minReprioritizationDistance;
  952. ObjectsCullingByDistance
  953. = interestConfig.GetBoolean("ObjectsCullingByDistance", ObjectsCullingByDistance);
  954. }
  955. m_log.DebugFormat("[SCENE]: Using the {0} prioritization scheme", UpdatePrioritizationScheme);
  956. #endregion Interest Management
  957. StatsReporter = new SimStatsReporter(this);
  958. StatsReporter.OnSendStatsResult += SendSimStatsPackets;
  959. StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;
  960. IConfig restartConfig = config.Configs["RestartModule"];
  961. if (restartConfig != null)
  962. {
  963. string markerPath = restartConfig.GetString("MarkerPath", String.Empty);
  964. if (markerPath != String.Empty)
  965. {
  966. string path = Path.Combine(markerPath, RegionInfo.RegionID.ToString() + ".started");
  967. try
  968. {
  969. string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
  970. FileStream fs = File.Create(path);
  971. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  972. Byte[] buf = enc.GetBytes(pidstring);
  973. fs.Write(buf, 0, buf.Length);
  974. fs.Close();
  975. }
  976. catch (Exception)
  977. {
  978. }
  979. }
  980. }
  981. StartTimerWatchdog();
  982. }
  983. public Scene(RegionInfo regInfo)
  984. : base(regInfo)
  985. {
  986. m_sceneGraph = new SceneGraph(this);
  987. // If the scene graph has an Unrecoverable error, restart this sim.
  988. // Currently the only thing that causes it to happen is two kinds of specific
  989. // Physics based crashes.
  990. //
  991. // Out of memory
  992. // Operating system has killed the plugin
  993. m_sceneGraph.UnRecoverableError
  994. += () =>
  995. {
  996. m_log.ErrorFormat("[SCENE]: Restarting region {0} due to unrecoverable physics crash", Name);
  997. RestartNow();
  998. };
  999. PhysicalPrims = true;
  1000. CollidablePrims = true;
  1001. PhysicsEnabled = true;
  1002. AllowAvatarCrossing = true;
  1003. PeriodicBackup = true;
  1004. UseBackup = true;
  1005. IsReprioritizationEnabled = true;
  1006. UpdatePrioritizationScheme = UpdatePrioritizationSchemes.BestAvatarResponsiveness;
  1007. ReprioritizationInterval = 5000;
  1008. ReprioritizationDistance = m_minReprioritizationDistance;
  1009. m_eventManager = new EventManager();
  1010. m_permissions = new ScenePermissions(this);
  1011. }
  1012. #endregion
  1013. #region Startup / Close Methods
  1014. /// <value>
  1015. /// The scene graph for this scene
  1016. /// </value>
  1017. /// TODO: Possibly stop other classes being able to manipulate this directly.
  1018. public SceneGraph SceneGraph
  1019. {
  1020. get { return m_sceneGraph; }
  1021. }
  1022. /// <summary>
  1023. /// Called by the module loader when all modules are loaded, after each module's
  1024. /// RegionLoaded hook is called. This is the earliest time where RequestModuleInterface
  1025. /// may be used.
  1026. /// </summary>
  1027. public void AllModulesLoaded()
  1028. {
  1029. IDialogModule dm = RequestModuleInterface<IDialogModule>();
  1030. if (dm != null)
  1031. m_eventManager.OnPermissionError += dm.SendAlertToUser;
  1032. ISimulatorFeaturesModule fm = RequestModuleInterface<ISimulatorFeaturesModule>();
  1033. if (fm != null)
  1034. {
  1035. OSD openSimExtras;
  1036. OSDMap openSimExtrasMap;
  1037. if (!fm.TryGetFeature("OpenSimExtras", out openSimExtras))
  1038. openSimExtras = new OSDMap();
  1039. float statisticsFPSfactor = 1.0f;
  1040. if(Normalized55FPS)
  1041. statisticsFPSfactor = 55.0f * FrameTime;
  1042. openSimExtrasMap = (OSDMap)openSimExtras;
  1043. openSimExtrasMap["SimulatorFPS"] = OSD.FromReal(1.0f / FrameTime);
  1044. openSimExtrasMap["SimulatorFPSFactor"] = OSD.FromReal(statisticsFPSfactor);
  1045. openSimExtrasMap["SimulatorFPSWarnPercent"] = OSD.FromInteger(FrameTimeWarnPercent);
  1046. openSimExtrasMap["SimulatorFPSCritPercent"] = OSD.FromInteger(FrameTimeCritPercent);
  1047. fm.AddFeature("OpenSimExtras", openSimExtrasMap);
  1048. }
  1049. }
  1050. protected virtual void RegisterDefaultSceneEvents()
  1051. {
  1052. // m_eventManager.OnSignificantClientMovement += HandleOnSignificantClientMovement;
  1053. }
  1054. public override string GetSimulatorVersion()
  1055. {
  1056. return m_simulatorVersion;
  1057. }
  1058. /// <summary>
  1059. /// Process the fact that a neighbouring region has come up.
  1060. /// </summary>
  1061. /// <remarks>
  1062. /// We only add it to the neighbor list if it's within 1 region from here.
  1063. /// Agents may have draw distance values that cross two regions though, so
  1064. /// we add it to the notify list regardless of distance. We'll check
  1065. /// the agent's draw distance before notifying them though.
  1066. /// </remarks>
  1067. /// <param name="otherRegion">RegionInfo handle for the new region.</param>
  1068. /// <returns>True after all operations complete, throws exceptions otherwise.</returns>
  1069. public override void OtherRegionUp(GridRegion otherRegion)
  1070. {
  1071. if (RegionInfo.RegionHandle != otherRegion.RegionHandle)
  1072. {
  1073. if (isNeighborRegion(otherRegion))
  1074. {
  1075. // Let the grid service module know, so this can be cached
  1076. m_eventManager.TriggerOnRegionUp(otherRegion);
  1077. try
  1078. {
  1079. ForEachRootScenePresence(delegate(ScenePresence agent)
  1080. {
  1081. List<ulong> old = new List<ulong>();
  1082. old.Add(otherRegion.RegionHandle);
  1083. agent.DropOldNeighbours(old);
  1084. if (EntityTransferModule != null && agent.PresenceType != PresenceType.Npc)
  1085. EntityTransferModule.EnableChildAgent(agent, otherRegion);
  1086. });
  1087. }
  1088. catch (NullReferenceException)
  1089. {
  1090. // This means that we're not booted up completely yet.
  1091. // This shouldn't happen too often anymore.
  1092. m_log.Error("[SCENE]: Couldn't inform client of regionup because we got a null reference exception");
  1093. }
  1094. }
  1095. else
  1096. {
  1097. m_log.InfoFormat(
  1098. "[SCENE]: Got notice about far away Region: {0} at ({1}, {2})",
  1099. otherRegion.RegionName, otherRegion.RegionLocX, otherRegion.RegionLocY);
  1100. }
  1101. }
  1102. }
  1103. public bool isNeighborRegion(GridRegion otherRegion)
  1104. {
  1105. int tmp = otherRegion.RegionLocX - (int)RegionInfo.WorldLocX;
  1106. if (tmp < -otherRegion.RegionSizeX && tmp > RegionInfo.RegionSizeX)
  1107. return false;
  1108. tmp = otherRegion.RegionLocY - (int)RegionInfo.WorldLocY;
  1109. if (tmp < -otherRegion.RegionSizeY && tmp > RegionInfo.RegionSizeY)
  1110. return false;
  1111. return true;
  1112. }
  1113. public void AddNeighborRegion(RegionInfo region)
  1114. {
  1115. lock (m_neighbours)
  1116. {
  1117. if (!CheckNeighborRegion(region))
  1118. {
  1119. m_neighbours.Add(region);
  1120. }
  1121. }
  1122. }
  1123. public bool CheckNeighborRegion(RegionInfo region)
  1124. {
  1125. bool found = false;
  1126. lock (m_neighbours)
  1127. {
  1128. foreach (RegionInfo reg in m_neighbours)
  1129. {
  1130. if (reg.RegionHandle == region.RegionHandle)
  1131. {
  1132. found = true;
  1133. break;
  1134. }
  1135. }
  1136. }
  1137. return found;
  1138. }
  1139. // Alias IncomingHelloNeighbour OtherRegionUp, for now
  1140. public GridRegion IncomingHelloNeighbour(RegionInfo neighbour)
  1141. {
  1142. OtherRegionUp(new GridRegion(neighbour));
  1143. return new GridRegion(RegionInfo);
  1144. }
  1145. // This causes the region to restart immediatley.
  1146. public void RestartNow()
  1147. {
  1148. IConfig startupConfig = m_config.Configs["Startup"];
  1149. if (startupConfig != null)
  1150. {
  1151. if (startupConfig.GetBoolean("InworldRestartShutsDown", false))
  1152. {
  1153. MainConsole.Instance.RunCommand("shutdown");
  1154. return;
  1155. }
  1156. }
  1157. m_log.InfoFormat("[REGION]: Restarting region {0}", Name);
  1158. Close();
  1159. base.Restart();
  1160. }
  1161. // This is a helper function that notifies root agents in this region that a new sim near them has come up
  1162. // This is in the form of a timer because when an instance of OpenSim.exe is started,
  1163. // Even though the sims initialize, they don't listen until 'all of the sims are initialized'
  1164. // If we tell an agent about a sim that's not listening yet, the agent will not be able to connect to it.
  1165. // subsequently the agent will never see the region come back online.
  1166. public void RestartNotifyWaitElapsed(object sender, ElapsedEventArgs e)
  1167. {
  1168. m_restartWaitTimer.Stop();
  1169. lock (m_regionRestartNotifyList)
  1170. {
  1171. foreach (RegionInfo region in m_regionRestartNotifyList)
  1172. {
  1173. GridRegion r = new GridRegion(region);
  1174. try
  1175. {
  1176. ForEachRootScenePresence(delegate(ScenePresence agent)
  1177. {
  1178. if (EntityTransferModule != null && agent.PresenceType != PresenceType.Npc)
  1179. EntityTransferModule.EnableChildAgent(agent, r);
  1180. });
  1181. }
  1182. catch (NullReferenceException)
  1183. {
  1184. // This means that we're not booted up completely yet.
  1185. // This shouldn't happen too often anymore.
  1186. }
  1187. }
  1188. // Reset list to nothing.
  1189. m_regionRestartNotifyList.Clear();
  1190. }
  1191. }
  1192. public int GetInaccurateNeighborCount()
  1193. {
  1194. return m_neighbours.Count;
  1195. }
  1196. // This is the method that shuts down the scene.
  1197. public override void Close()
  1198. {
  1199. if (m_shuttingDown)
  1200. {
  1201. m_log.WarnFormat("[SCENE]: Ignoring close request because already closing {0}", Name);
  1202. return;
  1203. }
  1204. IEtcdModule etcd = RequestModuleInterface<IEtcdModule>();
  1205. if (etcd != null)
  1206. {
  1207. etcd.Delete("Health");
  1208. etcd.Delete("HealthFlags");
  1209. etcd.Delete("RootAgents");
  1210. }
  1211. m_log.InfoFormat("[SCENE]: Closing down the single simulator: {0}", RegionInfo.RegionName);
  1212. StatsReporter.Close();
  1213. m_restartTimer.Stop();
  1214. m_restartTimer.Close();
  1215. if (!GridService.DeregisterRegion(RegionInfo.RegionID))
  1216. m_log.WarnFormat("[SCENE]: Deregister from grid failed for region {0}", Name);
  1217. // Kick all ROOT agents with the message, 'The simulator is going down'
  1218. ForEachScenePresence(delegate(ScenePresence avatar)
  1219. {
  1220. avatar.RemoveNeighbourRegion(RegionInfo.RegionHandle);
  1221. if (!avatar.IsChildAgent)
  1222. avatar.ControllingClient.Kick("The simulator is going down.");
  1223. avatar.ControllingClient.SendShutdownConnectionNotice();
  1224. });
  1225. // Stop updating the scene objects and agents.
  1226. m_shuttingDown = true;
  1227. // Wait here, or the kick messages won't actually get to the agents before the scene terminates.
  1228. // We also need to wait to avoid a race condition with the scene update loop which might not yet
  1229. // have checked ShuttingDown.
  1230. Thread.Sleep(500);
  1231. // Stop all client threads.
  1232. ForEachScenePresence(delegate(ScenePresence avatar) { CloseAgent(avatar.UUID, false); });
  1233. m_log.Debug("[SCENE]: TriggerSceneShuttingDown");
  1234. EventManager.TriggerSceneShuttingDown(this);
  1235. m_log.Debug("[SCENE]: Persisting changed objects");
  1236. Backup(true);
  1237. m_log.Debug("[SCENE]: Closing scene");
  1238. m_sceneGraph.Close();
  1239. base.Close();
  1240. // XEngine currently listens to the EventManager.OnShutdown event to trigger script stop and persistence.
  1241. // Therefore. we must dispose of the PhysicsScene after this to prevent a window where script code can
  1242. // attempt to reference a null or disposed physics scene.
  1243. if (PhysicsScene != null)
  1244. {
  1245. m_log.Debug("[SCENE]: Dispose Physics");
  1246. PhysicsScene phys = PhysicsScene;
  1247. // remove the physics engine from both Scene and SceneGraph
  1248. PhysicsScene = null;
  1249. phys.Dispose();
  1250. phys = null;
  1251. }
  1252. }
  1253. public override void Start()
  1254. {
  1255. Start(true);
  1256. }
  1257. /// <summary>
  1258. /// Start the scene
  1259. /// </summary>
  1260. /// <param name='startScripts'>
  1261. /// Start the scripts within the scene.
  1262. /// </param>
  1263. public void Start(bool startScripts)
  1264. {
  1265. if (IsRunning)
  1266. return;
  1267. m_isRunning = true;
  1268. m_active = true;
  1269. m_unixStartTime = Util.UnixTimeSinceEpoch();
  1270. // m_log.DebugFormat("[SCENE]: Starting Heartbeat timer for {0}", RegionInfo.RegionName);
  1271. if (m_heartbeatThread != null)
  1272. {
  1273. m_hbRestarts++;
  1274. if(m_hbRestarts > 10)
  1275. Environment.Exit(1);
  1276. m_log.ErrorFormat("[SCENE]: Restarting heartbeat thread because it hasn't reported in in region {0}", RegionInfo.RegionName);
  1277. //int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
  1278. //System.Diagnostics.Process proc = new System.Diagnostics.Process();
  1279. //proc.EnableRaisingEvents=false;
  1280. //proc.StartInfo.FileName = "/bin/kill";
  1281. //proc.StartInfo.Arguments = "-QUIT " + pid.ToString();
  1282. //proc.Start();
  1283. //proc.WaitForExit();
  1284. //Thread.Sleep(1000);
  1285. //Environment.Exit(1);
  1286. m_heartbeatThread.Abort();
  1287. Watchdog.AbortThread(m_heartbeatThread.ManagedThreadId);
  1288. m_heartbeatThread = null;
  1289. }
  1290. GC.Collect();
  1291. GC.WaitForPendingFinalizers();
  1292. GC.Collect();
  1293. // tell physics to finish building actor
  1294. m_sceneGraph.ProcessPhysicsPreSimulation();
  1295. m_heartbeatThread = WorkManager.StartThread(
  1296. Heartbeat, string.Format("Heartbeat-({0})", RegionInfo.RegionName.Replace(" ", "_")), ThreadPriority.Normal, false,
  1297. false, null, 20000, false);
  1298. StartScripts();
  1299. }
  1300. /// <summary>
  1301. /// Sets up references to modules required by the scene
  1302. /// </summary>
  1303. public void SetModuleInterfaces()
  1304. {
  1305. m_xmlrpcModule = RequestModuleInterface<IXMLRPC>();
  1306. m_worldCommModule = RequestModuleInterface<IWorldComm>();
  1307. XferManager = RequestModuleInterface<IXfer>();
  1308. m_AvatarFactory = RequestModuleInterface<IAvatarFactoryModule>();
  1309. AttachmentsModule = RequestModuleInterface<IAttachmentsModule>();
  1310. m_serialiser = RequestModuleInterface<IRegionSerialiserModule>();
  1311. m_dialogModule = RequestModuleInterface<IDialogModule>();
  1312. m_capsModule = RequestModuleInterface<ICapabilitiesModule>();
  1313. EntityTransferModule = RequestModuleInterface<IEntityTransferModule>();
  1314. m_groupsModule = RequestModuleInterface<IGroupsModule>();
  1315. AgentTransactionsModule = RequestModuleInterface<IAgentAssetTransactions>();
  1316. UserManagementModule = RequestModuleInterface<IUserManagement>();
  1317. }
  1318. #endregion
  1319. #region Update Methods
  1320. /// <summary>
  1321. /// Activate the various loops necessary to continually update the scene.
  1322. /// </summary>
  1323. private void Heartbeat()
  1324. {
  1325. m_eventManager.TriggerOnRegionStarted(this);
  1326. // The first frame can take a very long time due to physics actors being added on startup. Therefore,
  1327. // don't turn on the watchdog alarm for this thread until the second frame, in order to prevent false
  1328. // alarms for scenes with many objects.
  1329. Update(1);
  1330. Watchdog.GetCurrentThreadInfo().AlarmIfTimeout = true;
  1331. m_lastFrameTick = Util.EnvironmentTickCount();
  1332. Update(-1);
  1333. Watchdog.RemoveThread();
  1334. }
  1335. public override void Update(int frames)
  1336. {
  1337. long? endFrame = null;
  1338. if (frames >= 0)
  1339. endFrame = Frame + frames;
  1340. float physicsFPS = 0f;
  1341. float frameTimeMS = FrameTime * 1000.0f;
  1342. int previousFrameTick;
  1343. double tmpMS;
  1344. double tmpMS2;
  1345. double framestart;
  1346. float sleepMS;
  1347. float sleepError = 0;
  1348. while (!m_shuttingDown && ((endFrame == null && Active) || Frame < endFrame))
  1349. {
  1350. framestart = Util.GetTimeStampMS();
  1351. ++Frame;
  1352. // m_log.DebugFormat("[SCENE]: Processing frame {0} in {1}", Frame, RegionInfo.RegionName);
  1353. otherMS = agentMS = tempOnRezMS = eventMS = backupMS = terrainMS = landMS = 0f;
  1354. try
  1355. {
  1356. EventManager.TriggerRegionHeartbeatStart(this);
  1357. // Apply taints in terrain module to terrain in physics scene
  1358. tmpMS = Util.GetTimeStampMS();
  1359. if (Frame % 4 == 0)
  1360. {
  1361. CheckTerrainUpdates();
  1362. }
  1363. if (Frame % m_update_terrain == 0)
  1364. {
  1365. UpdateTerrain();
  1366. }
  1367. tmpMS2 = Util.GetTimeStampMS();
  1368. terrainMS = (float)(tmpMS2 - tmpMS);
  1369. tmpMS = tmpMS2;
  1370. if (PhysicsEnabled && Frame % m_update_physics == 0)
  1371. m_sceneGraph.UpdatePreparePhysics();
  1372. tmpMS2 = Util.GetTimeStampMS();
  1373. physicsMS2 = (float)(tmpMS2 - tmpMS);
  1374. tmpMS = tmpMS2;
  1375. /*
  1376. // Apply any pending avatar force input to the avatar's velocity
  1377. if (Frame % m_update_entitymovement == 0)
  1378. m_sceneGraph.UpdateScenePresenceMovement();
  1379. */
  1380. if (Frame % (m_update_coarse_locations) == 0 && !m_sendingCoarseLocations)
  1381. {
  1382. m_sendingCoarseLocations = true;
  1383. WorkManager.RunInThreadPool(
  1384. delegate
  1385. {
  1386. List<Vector3> coarseLocations;
  1387. List<UUID> avatarUUIDs;
  1388. SceneGraph.GetCoarseLocations(out coarseLocations, out avatarUUIDs, 60);
  1389. // Send coarse locations to clients
  1390. ForEachScenePresence(delegate(ScenePresence presence)
  1391. {
  1392. presence.SendCoarseLocations(coarseLocations, avatarUUIDs);
  1393. });
  1394. m_sendingCoarseLocations = false;
  1395. }, null, string.Format("SendCoarseLocations ({0})", Name));
  1396. }
  1397. // Get the simulation frame time that the avatar force input
  1398. // took
  1399. tmpMS2 = Util.GetTimeStampMS();
  1400. agentMS = (float)(tmpMS2 - tmpMS);
  1401. tmpMS = tmpMS2;
  1402. // Perform the main physics update. This will do the actual work of moving objects and avatars according to their
  1403. // velocity
  1404. if (Frame % m_update_physics == 0)
  1405. {
  1406. if (PhysicsEnabled)
  1407. physicsFPS = m_sceneGraph.UpdatePhysics(FrameTime);
  1408. }
  1409. tmpMS2 = Util.GetTimeStampMS();
  1410. physicsMS = (float)(tmpMS2 - tmpMS);
  1411. tmpMS = tmpMS2;
  1412. // Check if any objects have reached their targets
  1413. CheckAtTargets();
  1414. // Update SceneObjectGroups that have scheduled themselves for updates
  1415. // Objects queue their updates onto all scene presences
  1416. if (Frame % m_update_objects == 0)
  1417. m_sceneGraph.UpdateObjectGroups();
  1418. tmpMS2 = Util.GetTimeStampMS();
  1419. otherMS = (float)(tmpMS2 - tmpMS);
  1420. tmpMS = tmpMS2;
  1421. // Run through all ScenePresences looking for updates
  1422. // Presence updates and queued object updates for each presence are sent to clients
  1423. if (Frame % m_update_presences == 0)
  1424. m_sceneGraph.UpdatePresences();
  1425. tmpMS2 = Util.GetTimeStampMS();
  1426. agentMS += (float)(tmpMS2 - tmpMS);
  1427. tmpMS = tmpMS2;
  1428. // Delete temp-on-rez stuff
  1429. if (Frame % m_update_temp_cleaning == 0 && !m_cleaningTemps)
  1430. {
  1431. m_cleaningTemps = true;
  1432. WorkManager.RunInThreadPool(
  1433. delegate { CleanTempObjects(); m_cleaningTemps = false; }, null, string.Format("CleanTempObjects ({0})", Name));
  1434. tmpMS2 = Util.GetTimeStampMS();
  1435. tempOnRezMS = (float)(tmpMS2 - tmpMS); // bad.. counts the FireAndForget, not CleanTempObjects
  1436. tmpMS = tmpMS2;
  1437. }
  1438. if (Frame % m_update_events == 0)
  1439. {
  1440. UpdateEvents();
  1441. tmpMS2 = Util.GetTimeStampMS();
  1442. eventMS = (float)(tmpMS2 - tmpMS);
  1443. tmpMS = tmpMS2;
  1444. }
  1445. if (PeriodicBackup && Frame % m_update_backup == 0)
  1446. {
  1447. UpdateStorageBackup();
  1448. tmpMS2 = Util.GetTimeStampMS();
  1449. backupMS = (float)(tmpMS2 - tmpMS);
  1450. tmpMS = tmpMS2;
  1451. }
  1452. //if (Frame % m_update_land == 0)
  1453. //{
  1454. // int ldMS = Util.EnvironmentTickCount();
  1455. // UpdateLand();
  1456. // landMS = Util.EnvironmentTickCountSubtract(ldMS);
  1457. //}
  1458. if (!LoginsEnabled && Frame == 20)
  1459. {
  1460. GC.Collect();
  1461. GC.WaitForPendingFinalizers();
  1462. GC.Collect();
  1463. if (!LoginLock)
  1464. {
  1465. if (!StartDisabled)
  1466. {
  1467. m_log.InfoFormat("[REGION]: Enabling logins for {0}", RegionInfo.RegionName);
  1468. LoginsEnabled = true;
  1469. }
  1470. m_sceneGridService.InformNeighborsThatRegionisUp(
  1471. RequestModuleInterface<INeighbourService>(), RegionInfo);
  1472. // Region ready should always be set
  1473. Ready = true;
  1474. IConfig restartConfig = m_config.Configs["RestartModule"];
  1475. if (restartConfig != null)
  1476. {
  1477. string markerPath = restartConfig.GetString("MarkerPath", String.Empty);
  1478. if (markerPath != String.Empty)
  1479. {
  1480. string path = Path.Combine(markerPath, RegionInfo.RegionID.ToString() + ".ready");
  1481. try
  1482. {
  1483. string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
  1484. FileStream fs = File.Create(path);
  1485. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  1486. Byte[] buf = enc.GetBytes(pidstring);
  1487. fs.Write(buf, 0, buf.Length);
  1488. fs.Close();
  1489. }
  1490. catch (Exception)
  1491. {
  1492. }
  1493. }
  1494. }
  1495. }
  1496. else
  1497. {
  1498. // This handles a case of a region having no scripts for the RegionReady module
  1499. if (m_sceneGraph.GetActiveScriptsCount() == 0)
  1500. {
  1501. // In this case, we leave it to the IRegionReadyModule to enable logins
  1502. // LoginLock can currently only be set by a region module implementation.
  1503. // If somehow this hasn't been done then the quickest way to bugfix is to see the
  1504. // NullReferenceException
  1505. IRegionReadyModule rrm = RequestModuleInterface<IRegionReadyModule>();
  1506. rrm.TriggerRegionReady(this);
  1507. }
  1508. }
  1509. }
  1510. }
  1511. catch (Exception e)
  1512. {
  1513. m_log.ErrorFormat(
  1514. "[SCENE]: Failed on region {0} with exception {1}{2}",
  1515. RegionInfo.RegionName, e.Message, e.StackTrace);
  1516. }
  1517. EventManager.TriggerRegionHeartbeatEnd(this);
  1518. m_firstHeartbeat = false;
  1519. Watchdog.UpdateThread();
  1520. otherMS += tempOnRezMS + eventMS + backupMS + terrainMS + landMS;
  1521. tmpMS = Util.GetTimeStampMS();
  1522. previousFrameTick = m_lastFrameTick;
  1523. m_lastFrameTick = (int)(tmpMS + 0.5);
  1524. // estimate sleep time
  1525. tmpMS2 = tmpMS - framestart;
  1526. tmpMS2 = (double)frameTimeMS - tmpMS2 - sleepError;
  1527. // reuse frameMS as temporary
  1528. frameMS = (float)tmpMS2;
  1529. // sleep if we can
  1530. if (tmpMS2 > 0)
  1531. {
  1532. Thread.Sleep((int)(tmpMS2 + 0.5));
  1533. tmpMS2 = Util.GetTimeStampMS();
  1534. sleepMS = (float)(tmpMS2 - tmpMS);
  1535. sleepError = sleepMS - frameMS;
  1536. Util.Clamp(sleepError, 0.0f, 20f);
  1537. frameMS = (float)(tmpMS2 - framestart);
  1538. }
  1539. else
  1540. {
  1541. tmpMS2 = Util.GetTimeStampMS();
  1542. frameMS = (float)(tmpMS2 - framestart);
  1543. sleepMS = 0.0f;
  1544. sleepError = 0.0f;
  1545. }
  1546. // script time is not scene frame time, but is displayed per frame
  1547. float scriptTimeMS = GetAndResetScriptExecutionTime();
  1548. StatsReporter.AddFrameStats(TimeDilation, physicsFPS, agentMS,
  1549. physicsMS + physicsMS2, otherMS , sleepMS, frameMS, scriptTimeMS);
  1550. // if (Frame%m_update_avatars == 0)
  1551. // UpdateInWorldTime();
  1552. // Optionally warn if a frame takes double the amount of time that it should.
  1553. if (DebugUpdates
  1554. && Util.EnvironmentTickCountSubtract(
  1555. m_lastFrameTick, previousFrameTick) > (int)(FrameTime * 1000 * 2))
  1556. m_log.WarnFormat(
  1557. "[SCENE]: Frame took {0} ms (desired max {1} ms) in {2}",
  1558. Util.EnvironmentTickCountSubtract(m_lastFrameTick, previousFrameTick),
  1559. FrameTime * 1000,
  1560. RegionInfo.RegionName);
  1561. }
  1562. }
  1563. /// <summary>
  1564. /// Adds the execution time of one script to the total scripts execution time for this region.
  1565. /// </summary>
  1566. /// <param name="ticks">Elapsed Stopwatch ticks</param>
  1567. public void AddScriptExecutionTime(long ticks)
  1568. {
  1569. StatsReporter.addScriptEvents(1);
  1570. Interlocked.Add(ref m_scriptExecutionTime, ticks);
  1571. }
  1572. /// <summary>
  1573. /// Returns the total execution time of all the scripts in the region since the last call
  1574. /// (in milliseconds), and clears the value in preparation for the next call.
  1575. /// </summary>
  1576. /// <returns>Time in milliseconds</returns>
  1577. // Warning: this is now called from StatsReporter, and can't be shared
  1578. public long GetAndResetScriptExecutionTime()
  1579. {
  1580. long ticks = Interlocked.Exchange(ref m_scriptExecutionTime, 0);
  1581. return (ticks * 1000L) / Stopwatch.Frequency;
  1582. }
  1583. public void AddGroupTarget(SceneObjectGroup grp)
  1584. {
  1585. lock (m_groupsWithTargets)
  1586. m_groupsWithTargets.Add(grp.UUID);
  1587. }
  1588. public void RemoveGroupTarget(SceneObjectGroup grp)
  1589. {
  1590. lock (m_groupsWithTargets)
  1591. m_groupsWithTargets.Remove(grp.UUID);
  1592. }
  1593. private void CheckAtTargets()
  1594. {
  1595. List<UUID> objs = null;
  1596. lock (m_groupsWithTargets)
  1597. {
  1598. if (m_groupsWithTargets.Count != 0)
  1599. objs = new List<UUID>(m_groupsWithTargets);
  1600. }
  1601. if (objs != null)
  1602. {
  1603. for(int i = 0; i< objs.Count; ++i)
  1604. {
  1605. UUID entry = objs[i];
  1606. SceneObjectGroup grp = GetSceneObjectGroup(entry);
  1607. if (grp == null)
  1608. m_groupsWithTargets.Remove(entry);
  1609. else
  1610. grp.checkAtTargets();
  1611. }
  1612. }
  1613. }
  1614. /// <summary>
  1615. /// Send out simstats data to all clients
  1616. /// </summary>
  1617. /// <param name="stats">Stats on the Simulator's performance</param>
  1618. private void SendSimStatsPackets(SimStats stats)
  1619. {
  1620. ForEachRootClient(delegate(IClientAPI client)
  1621. {
  1622. client.SendSimStats(stats);
  1623. });
  1624. }
  1625. /// <summary>
  1626. /// Update the terrain if it needs to be updated.
  1627. /// </summary>
  1628. private void UpdateTerrain()
  1629. {
  1630. EventManager.TriggerTerrainTick();
  1631. }
  1632. private void CheckTerrainUpdates()
  1633. {
  1634. EventManager.TriggerTerrainCheckUpdates();
  1635. }
  1636. /// <summary>
  1637. /// Back up queued up changes
  1638. /// </summary>
  1639. private void UpdateStorageBackup()
  1640. {
  1641. if (!m_backingup)
  1642. {
  1643. WorkManager.RunInThreadPool(o => Backup(false), null, string.Format("BackupWorker ({0})", Name), false);
  1644. }
  1645. }
  1646. /// <summary>
  1647. /// Sends out the OnFrame event to the modules
  1648. /// </summary>
  1649. private void UpdateEvents()
  1650. {
  1651. m_eventManager.TriggerOnFrame();
  1652. }
  1653. /// <summary>
  1654. /// Backup the scene.
  1655. /// </summary>
  1656. /// <remarks>
  1657. /// This acts as the main method of the backup thread. In a regression test whether the backup thread is not
  1658. /// running independently this can be invoked directly.
  1659. /// </remarks>
  1660. /// <param name="forced">
  1661. /// If true, then any changes that have not yet been persisted are persisted. If false,
  1662. /// then the persistence decision is left to the backup code (in some situations, such as object persistence,
  1663. /// it's much more efficient to backup multiple changes at once rather than every single one).
  1664. /// <returns></returns>
  1665. public void Backup(bool forced)
  1666. {
  1667. lock (m_returns)
  1668. {
  1669. if(m_backingup)
  1670. {
  1671. m_log.WarnFormat("[Scene] Backup of {0} already running. New call skipped", RegionInfo.RegionName);
  1672. return;
  1673. }
  1674. m_backingup = true;
  1675. try
  1676. {
  1677. EventManager.TriggerOnBackup(SimulationDataService, forced);
  1678. if(m_returns.Count == 0)
  1679. return;
  1680. IMessageTransferModule tr = RequestModuleInterface<IMessageTransferModule>();
  1681. if (tr == null)
  1682. return;
  1683. uint unixtime = (uint)Util.UnixTimeSinceEpoch();
  1684. uint estateid = RegionInfo.EstateSettings.ParentEstateID;
  1685. Guid regionguid = RegionInfo.RegionID.Guid;
  1686. foreach (KeyValuePair<UUID, ReturnInfo> ret in m_returns)
  1687. {
  1688. GridInstantMessage msg = new GridInstantMessage();
  1689. msg.fromAgentID = Guid.Empty; // From server
  1690. msg.toAgentID = ret.Key.Guid;
  1691. msg.imSessionID = Guid.NewGuid();
  1692. msg.timestamp = unixtime;
  1693. msg.fromAgentName = "Server";
  1694. msg.dialog = 19; // Object msg
  1695. msg.fromGroup = false;
  1696. msg.offline = 1;
  1697. msg.ParentEstateID = estateid;
  1698. msg.Position = Vector3.Zero;
  1699. msg.RegionID = regionguid;
  1700. // We must fill in a null-terminated 'empty' string here since bytes[0] will crash viewer 3.
  1701. msg.binaryBucket = new Byte[1] {0};
  1702. if (ret.Value.count > 1)
  1703. msg.message = string.Format("Your {0} objects were returned from {1} in region {2} due to {3}", ret.Value.count, ret.Value.location.ToString(), RegionInfo.RegionName, ret.Value.reason);
  1704. else
  1705. msg.message = string.Format("Your object {0} was returned from {1} in region {2} due to {3}", ret.Value.objectName, ret.Value.location.ToString(), RegionInfo.RegionName, ret.Value.reason);
  1706. tr.SendInstantMessage(msg, delegate(bool success) { });
  1707. }
  1708. m_returns.Clear();
  1709. }
  1710. finally
  1711. {
  1712. m_backingup = false;
  1713. }
  1714. }
  1715. }
  1716. /// <summary>
  1717. /// Synchronous force backup. For deletes and links/unlinks
  1718. /// </summary>
  1719. /// <param name="group">Object to be backed up</param>
  1720. public void ForceSceneObjectBackup(SceneObjectGroup group)
  1721. {
  1722. if (group != null)
  1723. {
  1724. group.HasGroupChanged = true;
  1725. group.ProcessBackup(SimulationDataService, true);
  1726. }
  1727. }
  1728. /// <summary>
  1729. /// Tell an agent that their object has been returned.
  1730. /// </summary>
  1731. /// <remarks>
  1732. /// The actual return is handled by the caller.
  1733. /// </remarks>
  1734. /// <param name="agentID">Avatar Unique Id</param>
  1735. /// <param name="objectName">Name of object returned</param>
  1736. /// <param name="location">Location of object returned</param>
  1737. /// <param name="reason">Reasion for object return</param>
  1738. public void AddReturn(UUID agentID, string objectName, Vector3 location, string reason)
  1739. {
  1740. lock (m_returns)
  1741. {
  1742. if (m_returns.ContainsKey(agentID))
  1743. {
  1744. ReturnInfo info = m_returns[agentID];
  1745. info.count++;
  1746. m_returns[agentID] = info;
  1747. }
  1748. else
  1749. {
  1750. ReturnInfo info = new ReturnInfo();
  1751. info.count = 1;
  1752. info.objectName = objectName;
  1753. info.location = location;
  1754. info.reason = reason;
  1755. m_returns[agentID] = info;
  1756. }
  1757. }
  1758. }
  1759. #endregion
  1760. #region Load Terrain
  1761. /// <summary>
  1762. /// Store the terrain in the persistant data store
  1763. /// </summary>
  1764. public void SaveTerrain()
  1765. {
  1766. SimulationDataService.StoreTerrain(Heightmap.GetTerrainData(), RegionInfo.RegionID);
  1767. }
  1768. /// <summary>
  1769. /// Store the terrain in the persistant data store
  1770. /// </summary>
  1771. public void SaveBakedTerrain()
  1772. {
  1773. if(Bakedmap != null)
  1774. SimulationDataService.StoreBakedTerrain(Bakedmap.GetTerrainData(), RegionInfo.RegionID);
  1775. }
  1776. public void StoreWindlightProfile(RegionLightShareData wl)
  1777. {
  1778. RegionInfo.WindlightSettings = wl;
  1779. SimulationDataService.StoreRegionWindlightSettings(wl);
  1780. m_eventManager.TriggerOnSaveNewWindlightProfile();
  1781. }
  1782. public void LoadWindlightProfile()
  1783. {
  1784. RegionInfo.WindlightSettings = SimulationDataService.LoadRegionWindlightSettings(RegionInfo.RegionID);
  1785. m_eventManager.TriggerOnSaveNewWindlightProfile();
  1786. }
  1787. /// <summary>
  1788. /// Loads the World heightmap
  1789. /// </summary>
  1790. public override void LoadWorldMap()
  1791. {
  1792. try
  1793. {
  1794. Bakedmap = null;
  1795. TerrainData map = SimulationDataService.LoadBakedTerrain(RegionInfo.RegionID, (int)RegionInfo.RegionSizeX, (int)RegionInfo.RegionSizeY, (int)RegionInfo.RegionSizeZ);
  1796. if (map != null)
  1797. {
  1798. Bakedmap = new TerrainChannel(map);
  1799. }
  1800. }
  1801. catch (Exception e)
  1802. {
  1803. m_log.WarnFormat(
  1804. "[TERRAIN]: Scene.cs: LoadWorldMap() baked terrain - Failed with exception {0}{1}", e.Message, e.StackTrace);
  1805. }
  1806. try
  1807. {
  1808. TerrainData map = SimulationDataService.LoadTerrain(RegionInfo.RegionID, (int)RegionInfo.RegionSizeX, (int)RegionInfo.RegionSizeY, (int)RegionInfo.RegionSizeZ);
  1809. if (map == null)
  1810. {
  1811. if(Bakedmap != null)
  1812. {
  1813. m_log.Warn("[TERRAIN]: terrain not found. Used stored baked terrain.");
  1814. Heightmap = Bakedmap.MakeCopy();
  1815. SimulationDataService.StoreTerrain(Heightmap.GetTerrainData(), RegionInfo.RegionID);
  1816. }
  1817. else
  1818. {
  1819. // This should be in the Terrain module, but it isn't because
  1820. // the heightmap is needed _way_ before the modules are initialized...
  1821. IConfig terrainConfig = m_config.Configs["Terrain"];
  1822. String m_InitialTerrain = "pinhead-island";
  1823. if (terrainConfig != null)
  1824. m_InitialTerrain = terrainConfig.GetString("InitialTerrain", m_InitialTerrain);
  1825. m_log.InfoFormat("[TERRAIN]: No default terrain. Generating a new terrain {0}.", m_InitialTerrain);
  1826. Heightmap = new TerrainChannel(m_InitialTerrain, (int)RegionInfo.RegionSizeX, (int)RegionInfo.RegionSizeY, (int)RegionInfo.RegionSizeZ);
  1827. SimulationDataService.StoreTerrain(Heightmap.GetTerrainData(), RegionInfo.RegionID);
  1828. }
  1829. }
  1830. else
  1831. {
  1832. Heightmap = new TerrainChannel(map);
  1833. }
  1834. }
  1835. catch (IOException e)
  1836. {
  1837. m_log.WarnFormat(
  1838. "[TERRAIN]: Scene.cs: LoadWorldMap() - Regenerating as failed with exception {0}{1}",
  1839. e.Message, e.StackTrace);
  1840. #pragma warning disable 0162
  1841. if ((int)Constants.RegionSize != 256)
  1842. {
  1843. Heightmap = new TerrainChannel();
  1844. SimulationDataService.StoreTerrain(Heightmap.GetTerrainData(), RegionInfo.RegionID);
  1845. }
  1846. }
  1847. catch (Exception e)
  1848. {
  1849. m_log.WarnFormat(
  1850. "[TERRAIN]: Scene.cs: LoadWorldMap() - Failed with exception {0}{1}", e.Message, e.StackTrace);
  1851. }
  1852. if(Bakedmap == null && Heightmap != null)
  1853. {
  1854. Bakedmap = Heightmap.MakeCopy();
  1855. SimulationDataService.StoreBakedTerrain(Bakedmap.GetTerrainData(), RegionInfo.RegionID);
  1856. }
  1857. }
  1858. /// <summary>
  1859. /// Register this region with a grid service
  1860. /// </summary>
  1861. /// <exception cref="System.Exception">Thrown if registration of the region itself fails.</exception>
  1862. public void RegisterRegionWithGrid()
  1863. {
  1864. m_sceneGridService.SetScene(this);
  1865. //// Unfortunately this needs to be here and it can't be async.
  1866. //// The map tile image is stored in RegionSettings, but it also needs to be
  1867. //// stored in the GridService, because that's what the world map module uses
  1868. //// to send the map image UUIDs (of other regions) to the viewer...
  1869. if (m_generateMaptiles)
  1870. RegenerateMaptile();
  1871. GridRegion region = new GridRegion(RegionInfo);
  1872. string error = GridService.RegisterRegion(RegionInfo.ScopeID, region);
  1873. // m_log.DebugFormat("[SCENE]: RegisterRegionWithGrid. name={0},id={1},loc=<{2},{3}>,size=<{4},{5}>",
  1874. // m_regionName,
  1875. // RegionInfo.RegionID,
  1876. // RegionInfo.RegionLocX, RegionInfo.RegionLocY,
  1877. // RegionInfo.RegionSizeX, RegionInfo.RegionSizeY);
  1878. if (error != String.Empty)
  1879. throw new Exception(error);
  1880. }
  1881. #endregion
  1882. #region Load Land
  1883. /// <summary>
  1884. /// Loads all Parcel data from the datastore for region identified by regionID
  1885. /// </summary>
  1886. /// <param name="regionID">Unique Identifier of the Region to load parcel data for</param>
  1887. public void loadAllLandObjectsFromStorage(UUID regionID)
  1888. {
  1889. m_log.Info("[SCENE]: Loading land objects from storage");
  1890. List<LandData> landData = SimulationDataService.LoadLandObjects(regionID);
  1891. if (LandChannel != null)
  1892. {
  1893. if (landData.Count == 0)
  1894. {
  1895. EventManager.TriggerNoticeNoLandDataFromStorage();
  1896. }
  1897. else
  1898. {
  1899. EventManager.TriggerIncomingLandDataFromStorage(landData);
  1900. }
  1901. }
  1902. else
  1903. {
  1904. m_log.Error("[SCENE]: Land Channel is not defined. Cannot load from storage!");
  1905. }
  1906. }
  1907. #endregion
  1908. #region Primitives Methods
  1909. /// <summary>
  1910. /// Loads the World's objects
  1911. /// </summary>
  1912. /// <param name="regionID"></param>
  1913. public virtual void LoadPrimsFromStorage(UUID regionID)
  1914. {
  1915. LoadingPrims = true;
  1916. m_log.Info("[SCENE]: Loading objects from datastore");
  1917. List<SceneObjectGroup> PrimsFromDB = SimulationDataService.LoadObjects(regionID);
  1918. m_log.InfoFormat("[SCENE]: Loaded {0} objects from the datastore", PrimsFromDB.Count);
  1919. foreach (SceneObjectGroup group in PrimsFromDB)
  1920. {
  1921. AddRestoredSceneObject(group, true, true);
  1922. EventManager.TriggerOnSceneObjectLoaded(group);
  1923. SceneObjectPart rootPart = group.GetPart(group.UUID);
  1924. rootPart.Flags &= ~PrimFlags.Scripted;
  1925. rootPart.TrimPermissions();
  1926. group.InvalidateDeepEffectivePerms();
  1927. // Don't do this here - it will get done later on when sculpt data is loaded.
  1928. // group.CheckSculptAndLoad();
  1929. }
  1930. LoadingPrims = false;
  1931. EventManager.TriggerPrimsLoaded(this);
  1932. }
  1933. public bool SupportsRayCastFiltered()
  1934. {
  1935. if (PhysicsScene == null)
  1936. return false;
  1937. return PhysicsScene.SupportsRaycastWorldFiltered();
  1938. }
  1939. public object RayCastFiltered(Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags filter)
  1940. {
  1941. if (PhysicsScene == null)
  1942. return null;
  1943. return PhysicsScene.RaycastWorld(position, direction, length, Count, filter);
  1944. }
  1945. /// <summary>
  1946. /// Gets a new rez location based on the raycast and the size of the object that is being rezzed.
  1947. /// </summary>
  1948. /// <param name="RayStart"></param>
  1949. /// <param name="RayEnd"></param>
  1950. /// <param name="RayTargetID"></param>
  1951. /// <param name="rot"></param>
  1952. /// <param name="bypassRayCast"></param>
  1953. /// <param name="RayEndIsIntersection"></param>
  1954. /// <param name="frontFacesOnly"></param>
  1955. /// <param name="scale"></param>
  1956. /// <param name="FaceCenter"></param>
  1957. /// <returns></returns>
  1958. public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter)
  1959. {
  1960. Vector3 dir = RayEnd - RayStart;
  1961. float wheight = (float)RegionInfo.RegionSettings.WaterHeight;
  1962. Vector3 wpos = Vector3.Zero;
  1963. // Check for water surface intersection from above
  1964. if ((RayStart.Z > wheight) && (RayEnd.Z < wheight))
  1965. {
  1966. float ratio = (wheight - RayStart.Z) / dir.Z;
  1967. wpos.X = RayStart.X + (ratio * dir.X);
  1968. wpos.Y = RayStart.Y + (ratio * dir.Y);
  1969. wpos.Z = wheight;
  1970. }
  1971. Vector3 pos = Vector3.Zero;
  1972. if (RayEndIsIntersection != (byte)1)
  1973. {
  1974. float dist = dir.Length();
  1975. if (dist != 0)
  1976. {
  1977. Vector3 direction = dir * (1 / dist);
  1978. dist += 1.0f;
  1979. if (SupportsRayCastFiltered())
  1980. {
  1981. RayFilterFlags rayfilter = RayFilterFlags.BackFaceCull;
  1982. rayfilter |= RayFilterFlags.land;
  1983. rayfilter |= RayFilterFlags.physical;
  1984. rayfilter |= RayFilterFlags.nonphysical;
  1985. rayfilter |= RayFilterFlags.LSLPhantom; // ubODE will only see volume detectors
  1986. // get some more contacts ???
  1987. int physcount = 4;
  1988. List<ContactResult> physresults =
  1989. (List<ContactResult>)RayCastFiltered(RayStart, direction, dist, physcount, rayfilter);
  1990. if (physresults != null && physresults.Count > 0)
  1991. {
  1992. // look for terrain ?
  1993. if(RayTargetID == UUID.Zero)
  1994. {
  1995. foreach (ContactResult r in physresults)
  1996. {
  1997. if (r.ConsumerID == 0)
  1998. {
  1999. pos = r.Normal * scale;
  2000. pos *= 0.5f;
  2001. pos = r.Pos + pos;
  2002. if (wpos.Z > pos.Z) pos = wpos;
  2003. return pos;
  2004. }
  2005. }
  2006. }
  2007. else
  2008. {
  2009. foreach (ContactResult r in physresults)
  2010. {
  2011. SceneObjectPart part = GetSceneObjectPart(r.ConsumerID);
  2012. if (part == null)
  2013. continue;
  2014. if (part.UUID == RayTargetID)
  2015. {
  2016. pos = r.Normal * scale;
  2017. pos *= 0.5f;
  2018. pos = r.Pos + pos;
  2019. if (wpos.Z > pos.Z) pos = wpos;
  2020. return pos;
  2021. }
  2022. }
  2023. }
  2024. // else the first we got
  2025. pos = physresults[0].Normal * scale;
  2026. pos *= 0.5f;
  2027. pos = physresults[0].Pos + pos;
  2028. if (wpos.Z > pos.Z)
  2029. pos = wpos;
  2030. return pos;
  2031. }
  2032. }
  2033. if (RayTargetID != UUID.Zero)
  2034. {
  2035. SceneObjectPart target = GetSceneObjectPart(RayTargetID);
  2036. Ray NewRay = new Ray(RayStart, direction);
  2037. if (target != null)
  2038. {
  2039. pos = target.AbsolutePosition;
  2040. // Ray Trace against target here
  2041. EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter);
  2042. // Un-comment out the following line to Get Raytrace results printed to the console.
  2043. // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  2044. float ScaleOffset = 0.5f;
  2045. // If we hit something
  2046. if (ei.HitTF)
  2047. {
  2048. Vector3 scaleComponent = ei.AAfaceNormal;
  2049. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  2050. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  2051. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  2052. ScaleOffset = Math.Abs(ScaleOffset);
  2053. Vector3 intersectionpoint = ei.ipoint;
  2054. Vector3 normal = ei.normal;
  2055. // Set the position to the intersection point
  2056. Vector3 offset = (normal * (ScaleOffset / 2f));
  2057. pos = (intersectionpoint + offset);
  2058. //Seems to make no sense to do this as this call is used for rezzing from inventory as well, and with inventory items their size is not always 0.5f
  2059. //And in cases when we weren't rezzing from inventory we were re-adding the 0.25 straight after calling this method
  2060. // Un-offset the prim (it gets offset later by the consumer method)
  2061. //pos.Z -= 0.25F;
  2062. if (wpos.Z > pos.Z) pos = wpos;
  2063. return pos;
  2064. }
  2065. }
  2066. else
  2067. {
  2068. // We don't have a target here, so we're going to raytrace all the objects in the scene.
  2069. EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(NewRay, true, false);
  2070. // Un-comment the following line to print the raytrace results to the console.
  2071. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  2072. if (ei.HitTF)
  2073. {
  2074. pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  2075. }
  2076. else
  2077. {
  2078. // fall back to our stupid functionality
  2079. pos = RayEnd;
  2080. }
  2081. if (wpos.Z > pos.Z) pos = wpos;
  2082. return pos;
  2083. }
  2084. }
  2085. }
  2086. }
  2087. // fall back to our stupid functionality
  2088. pos = RayEnd;
  2089. //increase height so its above the ground.
  2090. //should be getting the normal of the ground at the rez point and using that?
  2091. pos.Z += scale.Z / 2f;
  2092. // return pos;
  2093. // check against posible water intercept
  2094. if (wpos.Z > pos.Z) pos = wpos;
  2095. return pos;
  2096. }
  2097. /// <summary>
  2098. /// Create a New SceneObjectGroup/Part by raycasting
  2099. /// </summary>
  2100. /// <param name="ownerID"></param>
  2101. /// <param name="groupID"></param>
  2102. /// <param name="RayEnd"></param>
  2103. /// <param name="rot"></param>
  2104. /// <param name="shape"></param>
  2105. /// <param name="bypassRaycast"></param>
  2106. /// <param name="RayStart"></param>
  2107. /// <param name="RayTargetID"></param>
  2108. /// <param name="RayEndIsIntersection"></param>
  2109. public virtual void AddNewPrim(UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot, PrimitiveBaseShape shape,
  2110. byte bypassRaycast, Vector3 RayStart, UUID RayTargetID,
  2111. byte RayEndIsIntersection)
  2112. {
  2113. Vector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection, true, new Vector3(0.5f, 0.5f, 0.5f), false);
  2114. if (Permissions.CanRezObject(1, ownerID, pos))
  2115. {
  2116. // rez ON the ground, not IN the ground
  2117. // pos.Z += 0.25F; The rez point should now be correct so that its not in the ground
  2118. AddNewPrim(ownerID, groupID, pos, rot, shape);
  2119. }
  2120. else
  2121. {
  2122. IClientAPI client = null;
  2123. if (TryGetClient(ownerID, out client))
  2124. client.SendAlertMessage("You cannot create objects here.");
  2125. }
  2126. }
  2127. public virtual SceneObjectGroup AddNewPrim(
  2128. UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
  2129. {
  2130. //m_log.DebugFormat(
  2131. // "[SCENE]: Scene.AddNewPrim() pcode {0} called for {1} in {2}", shape.PCode, ownerID, RegionInfo.RegionName);
  2132. SceneObjectGroup sceneObject = null;
  2133. // If an entity creator has been registered for this prim type then use that
  2134. if (m_entityCreators.ContainsKey((PCode)shape.PCode))
  2135. {
  2136. sceneObject = m_entityCreators[(PCode)shape.PCode].CreateEntity(ownerID, groupID, pos, rot, shape);
  2137. }
  2138. else
  2139. {
  2140. // Otherwise, use this default creation code;
  2141. sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
  2142. sceneObject.SetGroup(groupID, null);
  2143. AddNewSceneObject(sceneObject, true);
  2144. if (AgentPreferencesService != null) // This will override the brave new full perm world!
  2145. {
  2146. AgentPrefs prefs = AgentPreferencesService.GetAgentPreferences(ownerID);
  2147. // Only apply user selected prefs if the user set them
  2148. if (prefs != null && prefs.PermNextOwner != 0)
  2149. {
  2150. sceneObject.RootPart.GroupMask = (uint)prefs.PermGroup;
  2151. sceneObject.RootPart.EveryoneMask = (uint)prefs.PermEveryone;
  2152. sceneObject.RootPart.NextOwnerMask = (uint)prefs.PermNextOwner;
  2153. }
  2154. }
  2155. }
  2156. if (UserManagementModule != null)
  2157. sceneObject.RootPart.CreatorIdentification = UserManagementModule.GetUserUUI(ownerID);
  2158. sceneObject.InvalidateDeepEffectivePerms();;
  2159. sceneObject.ScheduleGroupForFullAnimUpdate();
  2160. return sceneObject;
  2161. }
  2162. /// <summary>
  2163. /// Add an object into the scene that has come from storage
  2164. /// </summary>
  2165. ///
  2166. /// <param name="sceneObject"></param>
  2167. /// <param name="attachToBackup">
  2168. /// If true, changes to the object will be reflected in its persisted data
  2169. /// If false, the persisted data will not be changed even if the object in the scene is changed
  2170. /// </param>
  2171. /// <param name="alreadyPersisted">
  2172. /// If true, we won't persist this object until it changes
  2173. /// If false, we'll persist this object immediately
  2174. /// </param>
  2175. /// <param name="sendClientUpdates">
  2176. /// If true, we send updates to the client to tell it about this object
  2177. /// If false, we leave it up to the caller to do this
  2178. /// </param>
  2179. /// <returns>
  2180. /// true if the object was added, false if an object with the same uuid was already in the scene
  2181. /// </returns>
  2182. public bool AddRestoredSceneObject(
  2183. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted, bool sendClientUpdates)
  2184. {
  2185. if (m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, sendClientUpdates))
  2186. {
  2187. sceneObject.IsDeleted = false;
  2188. EventManager.TriggerObjectAddedToScene(sceneObject);
  2189. return true;
  2190. }
  2191. return false;
  2192. }
  2193. /// <summary>
  2194. /// Add an object into the scene that has come from storage
  2195. /// </summary>
  2196. ///
  2197. /// <param name="sceneObject"></param>
  2198. /// <param name="attachToBackup">
  2199. /// If true, changes to the object will be reflected in its persisted data
  2200. /// If false, the persisted data will not be changed even if the object in the scene is changed
  2201. /// </param>
  2202. /// <param name="alreadyPersisted">
  2203. /// If true, we won't persist this object until it changes
  2204. /// If false, we'll persist this object immediately
  2205. /// </param>
  2206. /// <returns>
  2207. /// true if the object was added, false if an object with the same uuid was already in the scene
  2208. /// </returns>
  2209. public bool AddRestoredSceneObject(
  2210. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted)
  2211. {
  2212. return AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, true);
  2213. }
  2214. /// <summary>
  2215. /// Add a newly created object to the scene. Updates are also sent to viewers.
  2216. /// </summary>
  2217. /// <param name="sceneObject"></param>
  2218. /// <param name="attachToBackup">
  2219. /// If true, the object is made persistent into the scene.
  2220. /// If false, the object will not persist over server restarts
  2221. /// </param>
  2222. /// <returns>true if the object was added. false if not</returns>
  2223. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup)
  2224. {
  2225. return AddNewSceneObject(sceneObject, attachToBackup, true);
  2226. }
  2227. /// <summary>
  2228. /// Add a newly created object to the scene
  2229. /// </summary>
  2230. /// <param name="sceneObject"></param>
  2231. /// <param name="attachToBackup">
  2232. /// If true, the object is made persistent into the scene.
  2233. /// If false, the object will not persist over server restarts
  2234. /// </param>
  2235. /// <param name="sendClientUpdates">
  2236. /// If true, updates for the new scene object are sent to all viewers in range.
  2237. /// If false, it is left to the caller to schedule the update
  2238. /// </param>
  2239. /// <returns>true if the object was added. false if not</returns>
  2240. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup, bool sendClientUpdates)
  2241. {
  2242. if (m_sceneGraph.AddNewSceneObject(sceneObject, attachToBackup, sendClientUpdates))
  2243. {
  2244. EventManager.TriggerObjectAddedToScene(sceneObject);
  2245. return true;
  2246. }
  2247. return false;
  2248. }
  2249. /// <summary>
  2250. /// Add a newly created object to the scene.
  2251. /// </summary>
  2252. /// <remarks>
  2253. /// This method does not send updates to the client - callers need to handle this themselves.
  2254. /// </remarks>
  2255. /// <param name="sceneObject"></param>
  2256. /// <param name="attachToBackup"></param>
  2257. /// <param name="pos">Position of the object. If null then the position stored in the object is used.</param>
  2258. /// <param name="rot">Rotation of the object. If null then the rotation stored in the object is used.</param>
  2259. /// <param name="vel">Velocity of the object. This parameter only has an effect if the object is physical</param>
  2260. /// <returns></returns>
  2261. public bool AddNewSceneObject(
  2262. SceneObjectGroup sceneObject, bool attachToBackup, Vector3? pos, Quaternion? rot, Vector3 vel)
  2263. {
  2264. if (m_sceneGraph.AddNewSceneObject(sceneObject, attachToBackup, pos, rot, vel))
  2265. {
  2266. EventManager.TriggerObjectAddedToScene(sceneObject);
  2267. return true;
  2268. }
  2269. return false;
  2270. }
  2271. /// <summary>
  2272. /// Delete every object from the scene. This does not include attachments worn by avatars.
  2273. /// </summary>
  2274. public void DeleteAllSceneObjects()
  2275. {
  2276. DeleteAllSceneObjects(false);
  2277. }
  2278. /// <summary>
  2279. /// Delete every object from the scene. This does not include attachments worn by avatars.
  2280. /// </summary>
  2281. public void DeleteAllSceneObjects(bool exceptNoCopy)
  2282. {
  2283. List<SceneObjectGroup> toReturn = new List<SceneObjectGroup>();
  2284. lock (Entities)
  2285. {
  2286. EntityBase[] entities = Entities.GetEntities();
  2287. foreach (EntityBase e in entities)
  2288. {
  2289. if (e is SceneObjectGroup)
  2290. {
  2291. SceneObjectGroup sog = (SceneObjectGroup)e;
  2292. if (sog != null && !sog.IsAttachment)
  2293. {
  2294. if (!exceptNoCopy || ((sog.EffectiveOwnerPerms & (uint)PermissionMask.Copy) != 0))
  2295. {
  2296. DeleteSceneObject((SceneObjectGroup)e, false);
  2297. }
  2298. else
  2299. {
  2300. toReturn.Add((SceneObjectGroup)e);
  2301. }
  2302. }
  2303. }
  2304. }
  2305. }
  2306. if (toReturn.Count > 0)
  2307. {
  2308. returnObjects(toReturn.ToArray(), null);
  2309. }
  2310. }
  2311. /// <summary>
  2312. /// Synchronously delete the given object from the scene.
  2313. /// </summary>
  2314. /// <remarks>
  2315. /// Scripts are also removed.
  2316. /// </remarks>
  2317. /// <param name="group">Object Id</param>
  2318. /// <param name="silent">Suppress broadcasting changes to other clients.</param>
  2319. public void DeleteSceneObject(SceneObjectGroup group, bool silent)
  2320. {
  2321. DeleteSceneObject(group, silent, true);
  2322. }
  2323. /// <summary>
  2324. /// Synchronously delete the given object from the scene.
  2325. /// </summary>
  2326. /// <param name="group">Object Id</param>
  2327. /// <param name="silent">Suppress broadcasting changes to other clients.</param>
  2328. /// <param name="removeScripts">If true, then scripts are removed. If false, then they are only stopped.</para>
  2329. public void DeleteSceneObject(SceneObjectGroup group, bool silent, bool removeScripts)
  2330. {
  2331. // m_log.DebugFormat("[SCENE]: Deleting scene object {0} {1}", group.Name, group.UUID);
  2332. if (removeScripts)
  2333. group.RemoveScriptInstances(true);
  2334. else
  2335. group.StopScriptInstances();
  2336. SceneObjectPart[] partList = group.Parts;
  2337. for(int i = 0; i < partList.Length; ++i)
  2338. {
  2339. SceneObjectPart part = partList[i];
  2340. if (removeScripts)
  2341. part.Inventory.SendReleaseScriptsControl();
  2342. if (part.KeyframeMotion != null)
  2343. {
  2344. part.KeyframeMotion.Delete();
  2345. part.KeyframeMotion = null;
  2346. }
  2347. if (part.IsJoint() && ((part.Flags & PrimFlags.Physics) != 0))
  2348. {
  2349. PhysicsScene.RequestJointDeletion(part.Name); // FIXME: what if the name changed?
  2350. }
  2351. else if (part.PhysActor != null)
  2352. {
  2353. part.RemoveFromPhysics();
  2354. }
  2355. }
  2356. if (UnlinkSceneObject(group, false))
  2357. {
  2358. EventManager.TriggerObjectBeingRemovedFromScene(group);
  2359. EventManager.TriggerParcelPrimCountTainted();
  2360. }
  2361. group.DeleteGroupFromScene(silent);
  2362. // use this to mean also full delete
  2363. if (removeScripts)
  2364. group.Clear();
  2365. partList = null;
  2366. // m_log.DebugFormat("[SCENE]: Exit DeleteSceneObject() for {0} {1}", group.Name, group.UUID);
  2367. }
  2368. /// <summary>
  2369. /// Unlink the given object from the scene. Unlike delete, this just removes the record of the object - the
  2370. /// object itself is not destroyed.
  2371. /// </summary>
  2372. /// <param name="so">The scene object.</param>
  2373. /// <param name="softDelete">If true, only deletes from scene, but keeps the object in the database.</param>
  2374. /// <returns>true if the object was in the scene, false if it was not</returns>
  2375. public bool UnlinkSceneObject(SceneObjectGroup so, bool softDelete)
  2376. {
  2377. if (m_sceneGraph.DeleteSceneObject(so.UUID, softDelete))
  2378. {
  2379. if (!softDelete)
  2380. {
  2381. // If the group contains prims whose SceneGroupID is incorrect then force a
  2382. // database update, because RemoveObject() works by searching on the SceneGroupID.
  2383. // This is an expensive thing to do so only do it if absolutely necessary.
  2384. if (so.GroupContainsForeignPrims)
  2385. ForceSceneObjectBackup(so);
  2386. so.DetachFromBackup();
  2387. SimulationDataService.RemoveObject(so.UUID, RegionInfo.RegionID);
  2388. }
  2389. // We need to keep track of this state in case this group is still queued for further backup.
  2390. so.IsDeleted = true;
  2391. return true;
  2392. }
  2393. return false;
  2394. }
  2395. /* not in use, outdate by async method
  2396. /// <summary>
  2397. /// Move the given scene object into a new region depending on which region its absolute position has moved
  2398. /// into.
  2399. ///
  2400. /// </summary>
  2401. /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
  2402. /// <param name="grp">the scene object that we're crossing</param>
  2403. public void CrossPrimGroupIntoNewRegion(Vector3 attemptedPosition, SceneObjectGroup grp, bool silent)
  2404. {
  2405. if (grp == null)
  2406. return;
  2407. if (grp.IsDeleted)
  2408. return;
  2409. if (grp.RootPart.DIE_AT_EDGE)
  2410. {
  2411. // We remove the object here
  2412. try
  2413. {
  2414. DeleteSceneObject(grp, false);
  2415. }
  2416. catch (Exception)
  2417. {
  2418. m_log.Warn("[SCENE]: exception when trying to remove the prim that crossed the border.");
  2419. }
  2420. return;
  2421. }
  2422. if (grp.RootPart.RETURN_AT_EDGE)
  2423. {
  2424. // We remove the object here
  2425. try
  2426. {
  2427. List<SceneObjectGroup> objects = new List<SceneObjectGroup>();
  2428. objects.Add(grp);
  2429. SceneObjectGroup[] objectsArray = objects.ToArray();
  2430. returnObjects(objectsArray, UUID.Zero);
  2431. }
  2432. catch (Exception)
  2433. {
  2434. m_log.Warn("[SCENE]: exception when trying to return the prim that crossed the border.");
  2435. }
  2436. return;
  2437. }
  2438. if (EntityTransferModule != null)
  2439. EntityTransferModule.Cross(grp, attemptedPosition, silent);
  2440. }
  2441. */
  2442. // Simple test to see if a position is in the current region.
  2443. // This test is mostly used to see if a region crossing is necessary.
  2444. // Assuming the position is relative to the region so anything outside its bounds.
  2445. // Return 'true' if position inside region.
  2446. public bool PositionIsInCurrentRegion(Vector3 pos)
  2447. {
  2448. float t = pos.X;
  2449. if (t < 0 || t >= RegionInfo.RegionSizeX)
  2450. return false;
  2451. t = pos.Y;
  2452. if (t < 0 || t >= RegionInfo.RegionSizeY)
  2453. return false;
  2454. return true;
  2455. }
  2456. /// <summary>
  2457. /// Called when objects or attachments cross the border, or teleport, between regions.
  2458. /// </summary>
  2459. /// <param name="sog"></param>
  2460. /// <returns></returns>
  2461. public bool IncomingCreateObject(Vector3 newPosition, ISceneObject sog)
  2462. {
  2463. //m_log.DebugFormat(" >>> IncomingCreateObject(sog) <<< {0} deleted? {1} isAttach? {2}", ((SceneObjectGroup)sog).AbsolutePosition,
  2464. // ((SceneObjectGroup)sog).IsDeleted, ((SceneObjectGroup)sog).RootPart.IsAttachment);
  2465. SceneObjectGroup newObject;
  2466. try
  2467. {
  2468. newObject = (SceneObjectGroup)sog;
  2469. }
  2470. catch (Exception e)
  2471. {
  2472. m_log.WarnFormat("[INTERREGION]: Problem casting object, exception {0}{1}", e.Message, e.StackTrace);
  2473. return false;
  2474. }
  2475. if (!EntityTransferModule.HandleIncomingSceneObject(newObject, newPosition))
  2476. return false;
  2477. // Do this as late as possible so that listeners have full access to the incoming object
  2478. EventManager.TriggerOnIncomingSceneObject(newObject);
  2479. return true;
  2480. }
  2481. /// <summary>
  2482. /// Adds a Scene Object group to the Scene.
  2483. /// Verifies that the creator of the object is not banned from the simulator.
  2484. /// Checks if the item is an Attachment
  2485. /// </summary>
  2486. /// <param name="sceneObject"></param>
  2487. /// <returns>True if the SceneObjectGroup was added, False if it was not</returns>
  2488. public bool AddSceneObject(SceneObjectGroup sceneObject)
  2489. {
  2490. if (sceneObject.OwnerID == UUID.Zero)
  2491. {
  2492. m_log.ErrorFormat("[SCENE]: Owner ID for {0} was zero", sceneObject.UUID);
  2493. return false;
  2494. }
  2495. // If the user is banned, we won't let any of their objects
  2496. // enter. Period.
  2497. //
  2498. int flags = GetUserFlags(sceneObject.OwnerID);
  2499. if (RegionInfo.EstateSettings.IsBanned(sceneObject.OwnerID, flags))
  2500. {
  2501. m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", sceneObject.OwnerID);
  2502. return false;
  2503. }
  2504. // Force allocation of new LocalId
  2505. //
  2506. SceneObjectPart[] parts = sceneObject.Parts;
  2507. for (int i = 0; i < parts.Length; i++)
  2508. parts[i].LocalId = 0;
  2509. if (sceneObject.IsAttachmentCheckFull()) // Attachment
  2510. {
  2511. sceneObject.RootPart.AddFlag(PrimFlags.TemporaryOnRez);
  2512. // Don't sent a full update here because this will cause full updates to be sent twice for
  2513. // attachments on region crossings, resulting in viewer glitches.
  2514. AddRestoredSceneObject(sceneObject, false, false, false);
  2515. // Handle attachment special case
  2516. SceneObjectPart RootPrim = sceneObject.RootPart;
  2517. // Fix up attachment Parent Local ID
  2518. ScenePresence sp = GetScenePresence(sceneObject.OwnerID);
  2519. if (sp != null)
  2520. {
  2521. SceneObjectGroup grp = sceneObject;
  2522. // m_log.DebugFormat(
  2523. // "[ATTACHMENT]: Received attachment {0}, inworld asset id {1}", grp.FromItemID, grp.UUID);
  2524. // m_log.DebugFormat(
  2525. // "[ATTACHMENT]: Attach to avatar {0} at position {1}", sp.UUID, grp.AbsolutePosition);
  2526. // We must currently not resume scripts at this stage since AttachmentsModule does not have the
  2527. // information that this is due to a teleport/border cross rather than an ordinary attachment.
  2528. // We currently do this in Scene.MakeRootAgent() instead.
  2529. bool attached = false;
  2530. if (AttachmentsModule != null)
  2531. attached = AttachmentsModule.AttachObject(sp, grp, 0, false, false, true);
  2532. if (attached)
  2533. RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  2534. else
  2535. m_log.DebugFormat("[SCENE]: Attachment {0} arrived but failed to attach, setting to temp", sceneObject.UUID);
  2536. }
  2537. else
  2538. {
  2539. m_log.DebugFormat("[SCENE]: Attachment {0} arrived and scene presence was not found, setting to temp", sceneObject.UUID);
  2540. // RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  2541. // RootPrim.AddFlag(PrimFlags.TemporaryOnRez);
  2542. }
  2543. if (sceneObject.OwnerID == UUID.Zero)
  2544. {
  2545. m_log.ErrorFormat("[SCENE]: Owner ID for {0} was zero after attachment processing. BUG!", sceneObject.UUID);
  2546. return false;
  2547. }
  2548. }
  2549. else
  2550. {
  2551. if (sceneObject.OwnerID == UUID.Zero)
  2552. {
  2553. m_log.ErrorFormat("[SCENE]: Owner ID for non-attachment {0} was zero", sceneObject.UUID);
  2554. return false;
  2555. }
  2556. AddRestoredSceneObject(sceneObject, true, false);
  2557. }
  2558. return true;
  2559. }
  2560. private int GetStateSource(SceneObjectGroup sog)
  2561. {
  2562. if(!sog.IsAttachmentCheckFull())
  2563. return 2; // StateSource.PrimCrossing
  2564. ScenePresence sp = GetScenePresence(sog.OwnerID);
  2565. if (sp != null)
  2566. return sp.GetStateSource();
  2567. return 2; // StateSource.PrimCrossing
  2568. }
  2569. public int GetUserFlags(UUID user)
  2570. {
  2571. //Unfortunately the SP approach means that the value is cached until region is restarted
  2572. /*
  2573. ScenePresence sp;
  2574. if (TryGetScenePresence(user, out sp))
  2575. {
  2576. return sp.UserFlags;
  2577. }
  2578. else
  2579. {
  2580. */
  2581. UserAccount uac = UserAccountService.GetUserAccount(RegionInfo.ScopeID, user);
  2582. if (uac == null)
  2583. return 0;
  2584. return uac.UserFlags;
  2585. //}
  2586. }
  2587. #endregion
  2588. #region Add/Remove Avatar Methods
  2589. public override ISceneAgent AddNewAgent(IClientAPI client, PresenceType type)
  2590. {
  2591. ScenePresence sp;
  2592. bool vialogin;
  2593. bool reallyNew = true;
  2594. // Update the number of users attempting to login
  2595. StatsReporter.UpdateUsersLoggingIn(true);
  2596. // Validation occurs in LLUDPServer
  2597. //
  2598. // XXX: A race condition exists here where two simultaneous calls to AddNewAgent can interfere with
  2599. // each other. In practice, this does not currently occur in the code.
  2600. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode);
  2601. // We lock here on AgentCircuitData to prevent a race condition between the thread adding a new connection
  2602. // and a simultaneous one that removes it (as can happen if the client is closed at a particular point
  2603. // whilst connecting).
  2604. //
  2605. // It would be easier to lock across all NewUserConnection(), AddNewAgent() and
  2606. // RemoveClient() calls for all agents, but this would allow a slow call (e.g. because of slow service
  2607. // response in some module listening to AddNewAgent()) from holding up unrelated agent calls.
  2608. //
  2609. // In practice, the lock (this) in LLUDPServer.AddNewClient() currently lock across all
  2610. // AddNewClient() operations (though not other ops).
  2611. // In the future this can be relieved once locking per agent (not necessarily on AgentCircuitData) is improved.
  2612. lock (aCircuit)
  2613. {
  2614. vialogin
  2615. = (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0
  2616. || (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0;
  2617. CheckHeartbeat();
  2618. sp = GetScenePresence(client.AgentId);
  2619. if (sp == null)
  2620. {
  2621. m_log.DebugFormat(
  2622. "[SCENE]: Adding new child scene presence {0} {1} to scene {2} at pos {3}, tpflags: {4}",
  2623. client.Name, client.AgentId, RegionInfo.RegionName, client.StartPos,
  2624. ((TPFlags)aCircuit.teleportFlags).ToString());
  2625. m_clientManager.Add(client);
  2626. SubscribeToClientEvents(client);
  2627. sp = m_sceneGraph.CreateAndAddChildScenePresence(client, aCircuit.Appearance, type);
  2628. sp.TeleportFlags = (TPFlags)aCircuit.teleportFlags;
  2629. m_eventManager.TriggerOnNewPresence(sp);
  2630. }
  2631. else
  2632. {
  2633. // We must set this here so that TriggerOnNewClient and TriggerOnClientLogin can determine whether the
  2634. // client is for a root or child agent.
  2635. // XXX: This may be better set for a new client before that client is added to the client manager.
  2636. // But need to know what happens in the case where a ScenePresence is already present (and if this
  2637. // actually occurs).
  2638. m_log.WarnFormat(
  2639. "[SCENE]: Already found {0} scene presence for {1} in {2} when asked to add new scene presence",
  2640. sp.IsChildAgent ? "child" : "root", sp.Name, RegionInfo.RegionName);
  2641. reallyNew = false;
  2642. }
  2643. client.SceneAgent = sp;
  2644. // This is currently also being done earlier in NewUserConnection for real users to see if this
  2645. // resolves problems where HG agents are occasionally seen by others as "Unknown user" in chat and other
  2646. // places. However, we still need to do it here for NPCs.
  2647. CacheUserName(sp, aCircuit);
  2648. if (reallyNew)
  2649. EventManager.TriggerOnNewClient(client);
  2650. if (vialogin)
  2651. EventManager.TriggerOnClientLogin(client);
  2652. }
  2653. // User has logged into the scene so update the list of users logging
  2654. // in
  2655. StatsReporter.UpdateUsersLoggingIn(false);
  2656. m_LastLogin = Util.EnvironmentTickCount();
  2657. return sp;
  2658. }
  2659. /// <summary>
  2660. /// Returns the Home URI of the agent, or null if unknown.
  2661. /// </summary>
  2662. public string GetAgentHomeURI(UUID agentID)
  2663. {
  2664. AgentCircuitData circuit = AuthenticateHandler.GetAgentCircuitData(agentID);
  2665. if (circuit != null && circuit.ServiceURLs != null && circuit.ServiceURLs.ContainsKey("HomeURI"))
  2666. return circuit.ServiceURLs["HomeURI"].ToString();
  2667. else
  2668. return null;
  2669. }
  2670. /// <summary>
  2671. /// Cache the user name for later use.
  2672. /// </summary>
  2673. /// <param name="sp"></param>
  2674. /// <param name="aCircuit"></param>
  2675. private void CacheUserName(ScenePresence sp, AgentCircuitData aCircuit)
  2676. {
  2677. if (UserManagementModule != null)
  2678. {
  2679. string first = aCircuit.firstname, last = aCircuit.lastname;
  2680. if (sp != null && sp.PresenceType == PresenceType.Npc)
  2681. {
  2682. UserManagementModule.AddUser(aCircuit.AgentID, first, last, true);
  2683. }
  2684. else
  2685. {
  2686. string homeURL = string.Empty;
  2687. if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  2688. homeURL = aCircuit.ServiceURLs["HomeURI"].ToString();
  2689. if (aCircuit.lastname.StartsWith("@"))
  2690. {
  2691. string[] parts = aCircuit.firstname.Split('.');
  2692. if (parts.Length >= 2)
  2693. {
  2694. first = parts[0];
  2695. last = parts[1];
  2696. }
  2697. }
  2698. UserManagementModule.AddUser(aCircuit.AgentID, first, last, homeURL);
  2699. }
  2700. }
  2701. }
  2702. private bool VerifyClient(AgentCircuitData aCircuit, System.Net.IPEndPoint ep, out bool vialogin)
  2703. {
  2704. vialogin = false;
  2705. // Do the verification here
  2706. if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0)
  2707. {
  2708. m_log.DebugFormat("[SCENE]: Incoming client {0} {1} in region {2} via HG login", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2709. vialogin = true;
  2710. IUserAgentVerificationModule userVerification = RequestModuleInterface<IUserAgentVerificationModule>();
  2711. if (userVerification != null && ep != null)
  2712. {
  2713. if (!userVerification.VerifyClient(aCircuit, ep.Address.ToString()))
  2714. {
  2715. // uh-oh, this is fishy
  2716. m_log.DebugFormat("[SCENE]: User Client Verification for {0} {1} in {2} returned false", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2717. return false;
  2718. }
  2719. else
  2720. m_log.DebugFormat("[SCENE]: User Client Verification for {0} {1} in {2} returned true", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2721. }
  2722. }
  2723. else if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0)
  2724. {
  2725. m_log.DebugFormat("[SCENE]: Incoming client {0} {1} in region {2} via regular login. Client IP verification not performed.",
  2726. aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2727. vialogin = true;
  2728. }
  2729. return true;
  2730. }
  2731. // Called by Caps, on the first HTTP contact from the client
  2732. public override bool CheckClient(UUID agentID, System.Net.IPEndPoint ep)
  2733. {
  2734. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(agentID);
  2735. if (aCircuit == null)
  2736. return false;
  2737. bool vialogin = false;
  2738. if (VerifyClient(aCircuit, ep, out vialogin))
  2739. return true;
  2740. // if it doesn't pass, we remove the agentcircuitdata altogether
  2741. // and the scene presence and the client, if they exist
  2742. try
  2743. {
  2744. ScenePresence sp = WaitGetScenePresence(agentID);
  2745. if (sp != null)
  2746. {
  2747. PresenceService.LogoutAgent(sp.ControllingClient.SessionId);
  2748. CloseAgent(sp.UUID, false);
  2749. }
  2750. // BANG! SLASH!
  2751. m_authenticateHandler.RemoveCircuit(agentID);
  2752. }
  2753. catch (Exception e)
  2754. {
  2755. m_log.DebugFormat("[SCENE]: Exception while closing aborted client: {0}", e.StackTrace);
  2756. }
  2757. return false;
  2758. }
  2759. /// <summary>
  2760. /// Register for events from the client
  2761. /// </summary>
  2762. /// <param name="client">The IClientAPI of the connected client</param>
  2763. public virtual void SubscribeToClientEvents(IClientAPI client)
  2764. {
  2765. SubscribeToClientTerrainEvents(client);
  2766. SubscribeToClientPrimEvents(client);
  2767. SubscribeToClientPrimRezEvents(client);
  2768. SubscribeToClientInventoryEvents(client);
  2769. SubscribeToClientTeleportEvents(client);
  2770. SubscribeToClientScriptEvents(client);
  2771. SubscribeToClientParcelEvents(client);
  2772. SubscribeToClientGridEvents(client);
  2773. SubscribeToClientNetworkEvents(client);
  2774. }
  2775. public virtual void SubscribeToClientTerrainEvents(IClientAPI client)
  2776. {
  2777. // client.OnRegionHandShakeReply += SendLayerData;
  2778. }
  2779. public virtual void SubscribeToClientPrimEvents(IClientAPI client)
  2780. {
  2781. client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimGroupPosition;
  2782. client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition;
  2783. client.onClientChangeObject += m_sceneGraph.ClientChangeObject;
  2784. client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimGroupRotation;
  2785. client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimGroupRotation;
  2786. client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation;
  2787. client.OnUpdatePrimSingleRotationPosition += m_sceneGraph.UpdatePrimSingleRotationPosition;
  2788. client.OnUpdatePrimScale += m_sceneGraph.UpdatePrimScale;
  2789. client.OnUpdatePrimGroupScale += m_sceneGraph.UpdatePrimGroupScale;
  2790. client.OnUpdateExtraParams += m_sceneGraph.UpdateExtraParam;
  2791. client.OnUpdatePrimShape += m_sceneGraph.UpdatePrimShape;
  2792. client.OnUpdatePrimTexture += m_sceneGraph.UpdatePrimTexture;
  2793. client.OnObjectRequest += RequestPrim;
  2794. client.OnObjectSelect += SelectPrim;
  2795. client.OnObjectDeselect += DeselectPrim;
  2796. client.OnDeRezObject += DeRezObjects;
  2797. client.OnObjectName += m_sceneGraph.PrimName;
  2798. client.OnObjectClickAction += m_sceneGraph.PrimClickAction;
  2799. client.OnObjectMaterial += m_sceneGraph.PrimMaterial;
  2800. client.OnLinkObjects += LinkObjects;
  2801. client.OnDelinkObjects += DelinkObjects;
  2802. client.OnObjectDuplicate += DuplicateObject;
  2803. client.OnObjectDuplicateOnRay += doObjectDuplicateOnRay;
  2804. client.OnUpdatePrimFlags += m_sceneGraph.UpdatePrimFlags;
  2805. client.OnRequestObjectPropertiesFamily += m_sceneGraph.RequestObjectPropertiesFamily;
  2806. client.OnObjectPermissions += HandleObjectPermissionsUpdate;
  2807. client.OnGrabObject += ProcessObjectGrab;
  2808. client.OnGrabUpdate += ProcessObjectGrabUpdate;
  2809. client.OnDeGrabObject += ProcessObjectDeGrab;
  2810. client.OnSpinStart += ProcessSpinStart;
  2811. client.OnSpinUpdate += ProcessSpinObject;
  2812. client.OnSpinStop += ProcessSpinObjectStop;
  2813. client.OnUndo += m_sceneGraph.HandleUndo;
  2814. client.OnRedo += m_sceneGraph.HandleRedo;
  2815. client.OnObjectDescription += m_sceneGraph.PrimDescription;
  2816. client.OnObjectIncludeInSearch += m_sceneGraph.MakeObjectSearchable;
  2817. client.OnObjectOwner += ObjectOwner;
  2818. client.OnObjectGroupRequest += HandleObjectGroupUpdate;
  2819. }
  2820. public virtual void SubscribeToClientPrimRezEvents(IClientAPI client)
  2821. {
  2822. client.OnAddPrim += AddNewPrim;
  2823. client.OnRezObject += RezObject;
  2824. }
  2825. public virtual void SubscribeToClientInventoryEvents(IClientAPI client)
  2826. {
  2827. client.OnLinkInventoryItem += HandleLinkInventoryItem;
  2828. client.OnCreateNewInventoryFolder += HandleCreateInventoryFolder;
  2829. client.OnUpdateInventoryFolder += HandleUpdateInventoryFolder;
  2830. client.OnMoveInventoryFolder += HandleMoveInventoryFolder; // 2; //!!
  2831. client.OnFetchInventoryDescendents += HandleFetchInventoryDescendents;
  2832. client.OnPurgeInventoryDescendents += HandlePurgeInventoryDescendents; // 2; //!!
  2833. client.OnFetchInventory += m_asyncInventorySender.HandleFetchInventory;
  2834. client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
  2835. client.OnCopyInventoryItem += CopyInventoryItem;
  2836. client.OnMoveItemsAndLeaveCopy += MoveInventoryItemsLeaveCopy;
  2837. client.OnMoveInventoryItem += MoveInventoryItem;
  2838. client.OnRemoveInventoryItem += RemoveInventoryItem;
  2839. client.OnRemoveInventoryFolder += RemoveInventoryFolder;
  2840. client.OnRezScript += RezScript;
  2841. client.OnRequestTaskInventory += RequestTaskInventory;
  2842. client.OnRemoveTaskItem += RemoveTaskInventory;
  2843. client.OnUpdateTaskInventory += UpdateTaskInventory;
  2844. client.OnMoveTaskItem += ClientMoveTaskInventoryItem;
  2845. }
  2846. public virtual void SubscribeToClientTeleportEvents(IClientAPI client)
  2847. {
  2848. client.OnTeleportLocationRequest += RequestTeleportLocation;
  2849. }
  2850. public virtual void SubscribeToClientScriptEvents(IClientAPI client)
  2851. {
  2852. client.OnScriptReset += ProcessScriptReset;
  2853. client.OnGetScriptRunning += GetScriptRunning;
  2854. client.OnSetScriptRunning += SetScriptRunning;
  2855. }
  2856. public virtual void SubscribeToClientParcelEvents(IClientAPI client)
  2857. {
  2858. client.OnParcelReturnObjectsRequest += LandChannel.ReturnObjectsInParcel;
  2859. client.OnParcelSetOtherCleanTime += LandChannel.SetParcelOtherCleanTime;
  2860. client.OnParcelBuy += ProcessParcelBuy;
  2861. }
  2862. public virtual void SubscribeToClientGridEvents(IClientAPI client)
  2863. {
  2864. //client.OnNameFromUUIDRequest += HandleUUIDNameRequest;
  2865. client.OnMoneyTransferRequest += ProcessMoneyTransferRequest;
  2866. }
  2867. public virtual void SubscribeToClientNetworkEvents(IClientAPI client)
  2868. {
  2869. client.OnNetworkStatsUpdate += StatsReporter.AddPacketsStats;
  2870. client.OnViewerEffect += ProcessViewerEffect;
  2871. }
  2872. /// <summary>
  2873. /// Unsubscribe the client from events.
  2874. /// </summary>
  2875. /// FIXME: Not called anywhere!
  2876. /// <param name="client">The IClientAPI of the client</param>
  2877. public virtual void UnSubscribeToClientEvents(IClientAPI client)
  2878. {
  2879. UnSubscribeToClientTerrainEvents(client);
  2880. UnSubscribeToClientPrimEvents(client);
  2881. UnSubscribeToClientPrimRezEvents(client);
  2882. UnSubscribeToClientInventoryEvents(client);
  2883. UnSubscribeToClientTeleportEvents(client);
  2884. UnSubscribeToClientScriptEvents(client);
  2885. UnSubscribeToClientParcelEvents(client);
  2886. UnSubscribeToClientGridEvents(client);
  2887. UnSubscribeToClientNetworkEvents(client);
  2888. }
  2889. public virtual void UnSubscribeToClientTerrainEvents(IClientAPI client)
  2890. {
  2891. // client.OnRegionHandShakeReply -= SendLayerData;
  2892. }
  2893. public virtual void UnSubscribeToClientPrimEvents(IClientAPI client)
  2894. {
  2895. client.OnUpdatePrimGroupPosition -= m_sceneGraph.UpdatePrimGroupPosition;
  2896. client.OnUpdatePrimSinglePosition -= m_sceneGraph.UpdatePrimSinglePosition;
  2897. client.onClientChangeObject -= m_sceneGraph.ClientChangeObject;
  2898. client.OnUpdatePrimGroupRotation -= m_sceneGraph.UpdatePrimGroupRotation;
  2899. client.OnUpdatePrimGroupMouseRotation -= m_sceneGraph.UpdatePrimGroupRotation;
  2900. client.OnUpdatePrimSingleRotation -= m_sceneGraph.UpdatePrimSingleRotation;
  2901. client.OnUpdatePrimSingleRotationPosition -= m_sceneGraph.UpdatePrimSingleRotationPosition;
  2902. client.OnUpdatePrimScale -= m_sceneGraph.UpdatePrimScale;
  2903. client.OnUpdatePrimGroupScale -= m_sceneGraph.UpdatePrimGroupScale;
  2904. client.OnUpdateExtraParams -= m_sceneGraph.UpdateExtraParam;
  2905. client.OnUpdatePrimShape -= m_sceneGraph.UpdatePrimShape;
  2906. client.OnUpdatePrimTexture -= m_sceneGraph.UpdatePrimTexture;
  2907. client.OnObjectRequest -= RequestPrim;
  2908. client.OnObjectSelect -= SelectPrim;
  2909. client.OnObjectDeselect -= DeselectPrim;
  2910. client.OnDeRezObject -= DeRezObjects;
  2911. client.OnObjectName -= m_sceneGraph.PrimName;
  2912. client.OnObjectClickAction -= m_sceneGraph.PrimClickAction;
  2913. client.OnObjectMaterial -= m_sceneGraph.PrimMaterial;
  2914. client.OnLinkObjects -= LinkObjects;
  2915. client.OnDelinkObjects -= DelinkObjects;
  2916. client.OnObjectDuplicate -= DuplicateObject;
  2917. client.OnObjectDuplicateOnRay -= doObjectDuplicateOnRay;
  2918. client.OnUpdatePrimFlags -= m_sceneGraph.UpdatePrimFlags;
  2919. client.OnRequestObjectPropertiesFamily -= m_sceneGraph.RequestObjectPropertiesFamily;
  2920. client.OnObjectPermissions -= HandleObjectPermissionsUpdate;
  2921. client.OnGrabObject -= ProcessObjectGrab;
  2922. client.OnGrabUpdate -= ProcessObjectGrabUpdate;
  2923. client.OnDeGrabObject -= ProcessObjectDeGrab;
  2924. client.OnSpinStart -= ProcessSpinStart;
  2925. client.OnSpinUpdate -= ProcessSpinObject;
  2926. client.OnSpinStop -= ProcessSpinObjectStop;
  2927. client.OnUndo -= m_sceneGraph.HandleUndo;
  2928. client.OnRedo -= m_sceneGraph.HandleRedo;
  2929. client.OnObjectDescription -= m_sceneGraph.PrimDescription;
  2930. client.OnObjectIncludeInSearch -= m_sceneGraph.MakeObjectSearchable;
  2931. client.OnObjectOwner -= ObjectOwner;
  2932. }
  2933. public virtual void UnSubscribeToClientPrimRezEvents(IClientAPI client)
  2934. {
  2935. client.OnAddPrim -= AddNewPrim;
  2936. client.OnRezObject -= RezObject;
  2937. }
  2938. public virtual void UnSubscribeToClientInventoryEvents(IClientAPI client)
  2939. {
  2940. client.OnCreateNewInventoryFolder -= HandleCreateInventoryFolder;
  2941. client.OnUpdateInventoryFolder -= HandleUpdateInventoryFolder;
  2942. client.OnMoveInventoryFolder -= HandleMoveInventoryFolder; // 2; //!!
  2943. client.OnFetchInventoryDescendents -= HandleFetchInventoryDescendents;
  2944. client.OnPurgeInventoryDescendents -= HandlePurgeInventoryDescendents; // 2; //!!
  2945. client.OnFetchInventory -= m_asyncInventorySender.HandleFetchInventory;
  2946. client.OnUpdateInventoryItem -= UpdateInventoryItemAsset;
  2947. client.OnCopyInventoryItem -= CopyInventoryItem;
  2948. client.OnMoveInventoryItem -= MoveInventoryItem;
  2949. client.OnRemoveInventoryItem -= RemoveInventoryItem;
  2950. client.OnRemoveInventoryFolder -= RemoveInventoryFolder;
  2951. client.OnRezScript -= RezScript;
  2952. client.OnRequestTaskInventory -= RequestTaskInventory;
  2953. client.OnRemoveTaskItem -= RemoveTaskInventory;
  2954. client.OnUpdateTaskInventory -= UpdateTaskInventory;
  2955. client.OnMoveTaskItem -= ClientMoveTaskInventoryItem;
  2956. }
  2957. public virtual void UnSubscribeToClientTeleportEvents(IClientAPI client)
  2958. {
  2959. client.OnTeleportLocationRequest -= RequestTeleportLocation;
  2960. //client.OnTeleportLandmarkRequest -= RequestTeleportLandmark;
  2961. //client.OnTeleportHomeRequest -= TeleportClientHome;
  2962. }
  2963. public virtual void UnSubscribeToClientScriptEvents(IClientAPI client)
  2964. {
  2965. client.OnScriptReset -= ProcessScriptReset;
  2966. client.OnGetScriptRunning -= GetScriptRunning;
  2967. client.OnSetScriptRunning -= SetScriptRunning;
  2968. }
  2969. public virtual void UnSubscribeToClientParcelEvents(IClientAPI client)
  2970. {
  2971. client.OnParcelReturnObjectsRequest -= LandChannel.ReturnObjectsInParcel;
  2972. client.OnParcelSetOtherCleanTime -= LandChannel.SetParcelOtherCleanTime;
  2973. client.OnParcelBuy -= ProcessParcelBuy;
  2974. }
  2975. public virtual void UnSubscribeToClientGridEvents(IClientAPI client)
  2976. {
  2977. //client.OnNameFromUUIDRequest -= HandleUUIDNameRequest;
  2978. client.OnMoneyTransferRequest -= ProcessMoneyTransferRequest;
  2979. }
  2980. public virtual void UnSubscribeToClientNetworkEvents(IClientAPI client)
  2981. {
  2982. client.OnNetworkStatsUpdate -= StatsReporter.AddPacketsStats;
  2983. client.OnViewerEffect -= ProcessViewerEffect;
  2984. }
  2985. /// <summary>
  2986. /// Teleport an avatar to their home region
  2987. /// </summary>
  2988. /// <param name="agentId">The avatar's Unique ID</param>
  2989. /// <param name="client">The IClientAPI for the client</param>
  2990. public virtual bool TeleportClientHome(UUID agentId, IClientAPI client)
  2991. {
  2992. if (EntityTransferModule != null)
  2993. {
  2994. return EntityTransferModule.TeleportHome(agentId, client);
  2995. }
  2996. else
  2997. {
  2998. m_log.DebugFormat("[SCENE]: Unable to teleport user home: no AgentTransferModule is active");
  2999. client.SendTeleportFailed("Unable to perform teleports on this simulator.");
  3000. }
  3001. return false;
  3002. }
  3003. /// <summary>
  3004. /// Duplicates object specified by localID. This is the event handler for IClientAPI.
  3005. /// </summary>
  3006. /// <param name="originalPrim">ID of object to duplicate</param>
  3007. /// <param name="offset"></param>
  3008. /// <param name="flags"></param>
  3009. /// <param name="AgentID">Agent doing the duplication</param>
  3010. /// <param name="GroupID">Group of new object</param>
  3011. public void DuplicateObject(uint originalPrim, Vector3 offset, uint flags, UUID AgentID, UUID GroupID)
  3012. {
  3013. bool createSelected = (flags & (uint)PrimFlags.CreateSelected) != 0;
  3014. SceneObjectGroup copy = SceneGraph.DuplicateObject(originalPrim, offset, AgentID,
  3015. GroupID, Quaternion.Identity, createSelected);
  3016. if (copy != null)
  3017. EventManager.TriggerObjectAddedToScene(copy);
  3018. }
  3019. /// <summary>
  3020. /// Duplicates object specified by localID at position raycasted against RayTargetObject using
  3021. /// RayEnd and RayStart to determine what the angle of the ray is
  3022. /// </summary>
  3023. /// <param name="localID">ID of object to duplicate</param>
  3024. /// <param name="dupeFlags"></param>
  3025. /// <param name="AgentID">Agent doing the duplication</param>
  3026. /// <param name="GroupID">Group of new object</param>
  3027. /// <param name="RayTargetObj">The target of the Ray</param>
  3028. /// <param name="RayEnd">The ending of the ray (farthest away point)</param>
  3029. /// <param name="RayStart">The Beginning of the ray (closest point)</param>
  3030. /// <param name="BypassRaycast">Bool to bypass raycasting</param>
  3031. /// <param name="RayEndIsIntersection">The End specified is the place to add the object</param>
  3032. /// <param name="CopyCenters">Position the object at the center of the face that it's colliding with</param>
  3033. /// <param name="CopyRotates">Rotate the object the same as the localID object</param>
  3034. public void doObjectDuplicateOnRay(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID,
  3035. UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart,
  3036. bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates)
  3037. {
  3038. Vector3 pos;
  3039. const bool frontFacesOnly = true;
  3040. //m_log.Info("HITTARGET: " + RayTargetObj.ToString() + ", COPYTARGET: " + localID.ToString());
  3041. SceneObjectPart target = GetSceneObjectPart(localID);
  3042. SceneObjectPart target2 = GetSceneObjectPart(RayTargetObj);
  3043. bool createSelected = (dupeFlags & (uint)PrimFlags.CreateSelected) != 0;
  3044. if (target != null && target2 != null)
  3045. {
  3046. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  3047. pos = target2.AbsolutePosition;
  3048. //m_log.Info("[OBJECT_REZ]: TargetPos: " + pos.ToString() + ", RayStart: " + RayStart.ToString() + ", RayEnd: " + RayEnd.ToString() + ", Volume: " + Util.GetDistanceTo(RayStart,RayEnd).ToString() + ", mag1: " + Util.GetMagnitude(RayStart).ToString() + ", mag2: " + Util.GetMagnitude(RayEnd).ToString());
  3049. // TODO: Raytrace better here
  3050. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  3051. Ray NewRay = new Ray(RayStart,direction);
  3052. // Ray Trace against target here
  3053. EntityIntersection ei = target2.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, CopyCenters);
  3054. // Un-comment out the following line to Get Raytrace results printed to the console.
  3055. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  3056. float ScaleOffset = 0.5f;
  3057. // If we hit something
  3058. if (ei.HitTF)
  3059. {
  3060. Vector3 scale = target.Scale;
  3061. Vector3 scaleComponent = ei.AAfaceNormal;
  3062. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  3063. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  3064. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  3065. ScaleOffset = Math.Abs(ScaleOffset);
  3066. Vector3 intersectionpoint = ei.ipoint;
  3067. Vector3 normal = ei.normal;
  3068. Vector3 offset = normal * (ScaleOffset / 2f);
  3069. pos = intersectionpoint + offset;
  3070. // stick in offset format from the original prim
  3071. pos = pos - target.ParentGroup.AbsolutePosition;
  3072. SceneObjectGroup copy;
  3073. if (CopyRotates)
  3074. {
  3075. Quaternion worldRot = target2.GetWorldRotation();
  3076. // SceneObjectGroup obj = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  3077. copy = m_sceneGraph.DuplicateObject(localID, pos, AgentID, GroupID, worldRot, createSelected);
  3078. //obj.Rotation = worldRot;
  3079. //obj.UpdateGroupRotationR(worldRot);
  3080. }
  3081. else
  3082. {
  3083. copy = m_sceneGraph.DuplicateObject(localID, pos, AgentID, GroupID, Quaternion.Identity, createSelected);
  3084. }
  3085. if (copy != null)
  3086. EventManager.TriggerObjectAddedToScene(copy);
  3087. }
  3088. }
  3089. }
  3090. /// <summary>
  3091. /// Get the avatar appearance for the given client.
  3092. /// </summary>
  3093. /// <param name="client"></param>
  3094. /// <param name="appearance"></param>
  3095. public void GetAvatarAppearance(IClientAPI client, out AvatarAppearance appearance)
  3096. {
  3097. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode);
  3098. if (aCircuit == null)
  3099. {
  3100. m_log.DebugFormat("[APPEARANCE] Client did not supply a circuit. Non-Linden? Creating default appearance.");
  3101. appearance = new AvatarAppearance();
  3102. return;
  3103. }
  3104. appearance = aCircuit.Appearance;
  3105. if (appearance == null)
  3106. {
  3107. m_log.DebugFormat("[APPEARANCE]: Appearance not found in {0}, returning default", RegionInfo.RegionName);
  3108. appearance = new AvatarAppearance();
  3109. }
  3110. }
  3111. /// <summary>
  3112. /// Remove the given client from the scene.
  3113. /// </summary>
  3114. /// <remarks>
  3115. /// Only clientstack code should call this directly. All other code should call IncomingCloseAgent() instead
  3116. /// to properly operate the state machine and avoid race conditions with other close requests (such as directly
  3117. /// from viewers).
  3118. /// </remarks>
  3119. /// <param name='agentID'>ID of agent to close</param>
  3120. /// <param name='closeChildAgents'>
  3121. /// Close the neighbour child agents associated with this client.
  3122. /// </param>
  3123. ///
  3124. private object m_removeClientPrivLock = new Object();
  3125. public void RemoveClient(UUID agentID, bool closeChildAgents)
  3126. {
  3127. AgentCircuitData acd = m_authenticateHandler.GetAgentCircuitData(agentID);
  3128. // Shouldn't be necessary since RemoveClient() is currently only called by IClientAPI.Close() which
  3129. // in turn is only called by Scene.IncomingCloseAgent() which checks whether the presence exists or not
  3130. // However, will keep for now just in case.
  3131. if (acd == null)
  3132. {
  3133. m_log.ErrorFormat(
  3134. "[SCENE]: No agent circuit found for {0} in {1}, aborting Scene.RemoveClient", agentID, Name);
  3135. return;
  3136. }
  3137. // TODO: Can we now remove this lock?
  3138. lock (m_removeClientPrivLock)
  3139. {
  3140. bool isChildAgent = false;
  3141. ScenePresence avatar = GetScenePresence(agentID);
  3142. // Shouldn't be necessary since RemoveClient() is currently only called by IClientAPI.Close() which
  3143. // in turn is only called by Scene.IncomingCloseAgent() which checks whether the presence exists or not
  3144. // However, will keep for now just in case.
  3145. if (avatar == null)
  3146. {
  3147. m_log.ErrorFormat(
  3148. "[SCENE]: Called RemoveClient() with agent ID {0} but no such presence is in the scene.", agentID);
  3149. m_authenticateHandler.RemoveCircuit(agentID);
  3150. return;
  3151. }
  3152. try
  3153. {
  3154. isChildAgent = avatar.IsChildAgent;
  3155. m_log.DebugFormat(
  3156. "[SCENE]: Removing {0} agent {1} {2} from {3}",
  3157. isChildAgent ? "child" : "root", avatar.Name, agentID, Name);
  3158. // Don't do this to root agents, it's not nice for the viewer
  3159. if (closeChildAgents && isChildAgent)
  3160. {
  3161. // Tell a single agent to disconnect from the region.
  3162. // Let's do this via UDP
  3163. avatar.ControllingClient.SendShutdownConnectionNotice();
  3164. }
  3165. // Only applies to root agents.
  3166. if (avatar.ParentID != 0)
  3167. {
  3168. avatar.StandUp();
  3169. }
  3170. m_sceneGraph.removeUserCount(!isChildAgent);
  3171. // TODO: We shouldn't use closeChildAgents here - it's being used by the NPC module to stop
  3172. // unnecessary operations. This should go away once NPCs have no accompanying IClientAPI
  3173. if (closeChildAgents && CapsModule != null)
  3174. CapsModule.RemoveCaps(agentID, avatar.ControllingClient.CircuitCode);
  3175. if (closeChildAgents && !isChildAgent)
  3176. {
  3177. List<ulong> regions = avatar.KnownRegionHandles;
  3178. regions.Remove(RegionInfo.RegionHandle);
  3179. // This ends up being done asynchronously so that a logout isn't held up where there are many present but unresponsive neighbours.
  3180. m_sceneGridService.SendCloseChildAgentConnections(agentID, acd.SessionID.ToString(), regions);
  3181. }
  3182. m_eventManager.TriggerClientClosed(agentID, this);
  3183. // m_log.Debug("[Scene]TriggerClientClosed done");
  3184. m_eventManager.TriggerOnRemovePresence(agentID);
  3185. // m_log.Debug("[Scene]TriggerOnRemovePresence done");
  3186. if (!isChildAgent)
  3187. {
  3188. if (AttachmentsModule != null)
  3189. {
  3190. // m_log.Debug("[Scene]DeRezAttachments");
  3191. AttachmentsModule.DeRezAttachments(avatar);
  3192. // m_log.Debug("[Scene]DeRezAttachments done");
  3193. }
  3194. ForEachClient(
  3195. delegate(IClientAPI client)
  3196. {
  3197. //We can safely ignore null reference exceptions. It means the avatar is dead and cleaned up anyway
  3198. try { client.SendKillObject(new List<uint> { avatar.LocalId }); }
  3199. catch (NullReferenceException) { }
  3200. });
  3201. }
  3202. // It's possible for child agents to have transactions if changes are being made cross-border.
  3203. if (AgentTransactionsModule != null)
  3204. {
  3205. // m_log.Debug("[Scene]RemoveAgentAssetTransactions");
  3206. AgentTransactionsModule.RemoveAgentAssetTransactions(agentID);
  3207. }
  3208. m_log.Debug("[Scene] The avatar has left the building");
  3209. }
  3210. catch (Exception e)
  3211. {
  3212. m_log.Error(
  3213. string.Format("[SCENE]: Exception removing {0} from {1}. Cleaning up. Exception ", avatar.Name, Name), e);
  3214. }
  3215. finally
  3216. {
  3217. try
  3218. {
  3219. // Always clean these structures up so that any failure above doesn't cause them to remain in the
  3220. // scene with possibly bad effects (e.g. continually timing out on unacked packets and triggering
  3221. // the same cleanup exception continually.
  3222. m_authenticateHandler.RemoveCircuit(agentID);
  3223. m_sceneGraph.RemoveScenePresence(agentID);
  3224. m_clientManager.Remove(agentID);
  3225. avatar.Close();
  3226. }
  3227. catch (Exception e)
  3228. {
  3229. m_log.Error(
  3230. string.Format("[SCENE]: Exception in final clean up of {0} in {1}. Exception ", avatar.Name, Name), e);
  3231. }
  3232. }
  3233. }
  3234. //m_log.InfoFormat("[SCENE] Memory pre GC {0}", System.GC.GetTotalMemory(false));
  3235. //m_log.InfoFormat("[SCENE] Memory post GC {0}", System.GC.GetTotalMemory(true));
  3236. }
  3237. /// <summary>
  3238. /// Removes region from an avatar's known region list. This coincides with child agents. For each child agent, there will be a known region entry.
  3239. ///
  3240. /// </summary>
  3241. /// <param name="avatarID"></param>
  3242. /// <param name="regionslst"></param>
  3243. public void HandleRemoveKnownRegionsFromAvatar(UUID avatarID, List<ulong> regionslst)
  3244. {
  3245. ScenePresence av = GetScenePresence(avatarID);
  3246. if (av != null)
  3247. {
  3248. lock (av)
  3249. {
  3250. for (int i = 0; i < regionslst.Count; i++)
  3251. {
  3252. av.RemoveNeighbourRegion(regionslst[i]);
  3253. }
  3254. }
  3255. }
  3256. }
  3257. #endregion
  3258. #region Entities
  3259. public void SendKillObject(List<uint> localIDs)
  3260. {
  3261. List<uint> deleteIDs = new List<uint>();
  3262. foreach (uint localID in localIDs)
  3263. {
  3264. SceneObjectPart part = GetSceneObjectPart(localID);
  3265. if (part != null && part.ParentGroup != null &&
  3266. part.ParentGroup.RootPart == part)
  3267. deleteIDs.Add(localID);
  3268. }
  3269. ForEachClient(c => c.SendKillObject(deleteIDs));
  3270. }
  3271. #endregion
  3272. #region RegionComms
  3273. /// <summary>
  3274. /// Do the work necessary to initiate a new user connection for a particular scene.
  3275. /// </summary>
  3276. /// <param name="agent">CircuitData of the agent who is connecting</param>
  3277. /// <param name="teleportFlags"></param>
  3278. /// <param name="source">Source region (may be null)</param>
  3279. /// <param name="reason">Outputs the reason for the false response on this string</param>
  3280. /// <returns>True if the region accepts this agent. False if it does not. False will
  3281. /// also return a reason.</returns>
  3282. public bool NewUserConnection(AgentCircuitData agent, uint teleportFlags, GridRegion source, out string reason)
  3283. {
  3284. return NewUserConnection(agent, teleportFlags, source, out reason, true);
  3285. }
  3286. /// <summary>
  3287. /// Do the work necessary to initiate a new user connection for a particular scene.
  3288. /// </summary>
  3289. /// <remarks>
  3290. /// The return bool should allow for connections to be refused, but as not all calling paths
  3291. /// take proper notice of it yet, we still allowed banned users in.
  3292. ///
  3293. /// At the moment this method consists of setting up the caps infrastructure
  3294. /// The return bool should allow for connections to be refused, but as not all calling paths
  3295. /// take proper notice of it let, we allowed banned users in still.
  3296. ///
  3297. /// This method is called by the login service (in the case of login) or another simulator (in the case of region
  3298. /// cross or teleport) to initiate the connection. It is not triggered by the viewer itself - the connection
  3299. /// is activated later when the viewer sends the initial UseCircuitCodePacket UDP packet (in the case of
  3300. /// the LLUDP stack).
  3301. /// </remarks>
  3302. /// <param name="acd">CircuitData of the agent who is connecting</param>
  3303. /// <param name="source">Source region (may be null)</param>
  3304. /// <param name="reason">Outputs the reason for the false response on this string</param>
  3305. /// <param name="requirePresenceLookup">True for normal presence. False for NPC
  3306. /// or other applications where a full grid/Hypergrid presence may not be required.</param>
  3307. /// <returns>True if the region accepts this agent. False if it does not. False will
  3308. /// also return a reason.</returns>
  3309. ///
  3310. private object m_newUserConnLock = new object();
  3311. public bool NewUserConnection(AgentCircuitData acd, uint teleportFlags, GridRegion source, out string reason, bool requirePresenceLookup)
  3312. {
  3313. bool vialogin = ((teleportFlags & (uint)TPFlags.ViaLogin) != 0 ||
  3314. (teleportFlags & (uint)TPFlags.ViaHGLogin) != 0);
  3315. bool viahome = ((teleportFlags & (uint)TPFlags.ViaHome) != 0);
  3316. // bool godlike = ((teleportFlags & (uint)TPFlags.Godlike) != 0);
  3317. reason = String.Empty;
  3318. //Teleport flags:
  3319. //
  3320. // TeleportFlags.ViaGodlikeLure - Border Crossing
  3321. // TeleportFlags.ViaLogin - Login
  3322. // TeleportFlags.TeleportFlags.ViaLure - Teleport request sent by another user
  3323. // TeleportFlags.ViaLandmark | TeleportFlags.ViaLocation | TeleportFlags.ViaLandmark | TeleportFlags.Default - Regular Teleport
  3324. // Don't disable this log message - it's too helpful
  3325. string curViewer = Util.GetViewerName(acd);
  3326. m_log.DebugFormat(
  3327. "[SCENE]: Region {0} told of incoming {1} agent {2} {3} {4} (circuit code {5}, IP {6}, viewer {7}, teleportflags ({8}), position {9}. {10}",
  3328. RegionInfo.RegionName,
  3329. (acd.child ? "child" : "root"),
  3330. acd.firstname,
  3331. acd.lastname,
  3332. acd.AgentID,
  3333. acd.circuitcode,
  3334. acd.IPAddress,
  3335. curViewer,
  3336. ((TPFlags)teleportFlags).ToString(),
  3337. acd.startpos,
  3338. (source == null) ? "" : string.Format("From region {0} ({1}){2}", source.RegionName, source.RegionID, (source.RawServerURI == null) ? "" : " @ " + source.ServerURI)
  3339. );
  3340. // m_log.DebugFormat("NewUserConnection stack {0}", Environment.StackTrace);
  3341. if (!LoginsEnabled)
  3342. {
  3343. reason = "Logins to this region are disabled";
  3344. return false;
  3345. }
  3346. //Check if the viewer is banned or in the viewer access list
  3347. //We check if the substring is listed for higher flexebility
  3348. bool ViewerDenied = true;
  3349. //Check if the specific viewer is listed in the allowed viewer list
  3350. if (m_AllowedViewers.Count > 0)
  3351. {
  3352. foreach (string viewer in m_AllowedViewers)
  3353. {
  3354. if (viewer == curViewer.Substring(0, Math.Min(viewer.Length, curViewer.Length)).Trim().ToLower())
  3355. {
  3356. ViewerDenied = false;
  3357. break;
  3358. }
  3359. }
  3360. }
  3361. else
  3362. {
  3363. ViewerDenied = false;
  3364. }
  3365. //Check if the viewer is in the banned list
  3366. if (m_BannedViewers.Count > 0)
  3367. {
  3368. foreach (string viewer in m_BannedViewers)
  3369. {
  3370. if (viewer == curViewer.Substring(0, Math.Min(viewer.Length, curViewer.Length)).Trim().ToLower())
  3371. {
  3372. ViewerDenied = true;
  3373. break;
  3374. }
  3375. }
  3376. }
  3377. if (ViewerDenied)
  3378. {
  3379. m_log.DebugFormat(
  3380. "[SCENE]: Access denied for {0} {1} using {2}",
  3381. acd.firstname, acd.lastname, curViewer);
  3382. reason = "Access denied, your viewer is banned by the region owner";
  3383. return false;
  3384. }
  3385. ScenePresence sp;
  3386. lock (m_removeClientLock)
  3387. {
  3388. sp = GetScenePresence(acd.AgentID);
  3389. // We need to ensure that we are not already removing the scene presence before we ask it not to be
  3390. // closed.
  3391. if (sp != null && sp.IsChildAgent
  3392. && (sp.LifecycleState == ScenePresenceState.Running
  3393. || sp.LifecycleState == ScenePresenceState.PreRemove))
  3394. {
  3395. m_log.DebugFormat(
  3396. "[SCENE]: Reusing existing child scene presence for {0}, state {1} in {2}",
  3397. sp.Name, sp.LifecycleState, Name);
  3398. // In the case where, for example, an A B C D region layout, an avatar may
  3399. // teleport from A -> D, but then -> C before A has asked B to close its old child agent. When C
  3400. // renews the lease on the child agent at B, we must make sure that the close from A does not succeed.
  3401. //
  3402. // XXX: In the end, this should not be necessary if child agents are closed without delay on
  3403. // teleport, since realistically, the close request should always be processed before any other
  3404. // region tried to re-establish a child agent. This is much simpler since the logic below is
  3405. // vulnerable to an issue when a viewer quits a region without sending a proper logout but then
  3406. // re-establishes the connection on a relogin. This could wrongly set the DoNotCloseAfterTeleport
  3407. // flag when no teleport had taken place (and hence no close was going to come).
  3408. // if (!acd.ChildrenCapSeeds.ContainsKey(RegionInfo.RegionHandle))
  3409. // {
  3410. // m_log.DebugFormat(
  3411. // "[SCENE]: Setting DoNotCloseAfterTeleport for child scene presence {0} in {1} because source will attempt close.",
  3412. // sp.Name, Name);
  3413. //
  3414. // sp.DoNotCloseAfterTeleport = true;
  3415. // }
  3416. // else if (EntityTransferModule.IsInTransit(sp.UUID))
  3417. sp.LifecycleState = ScenePresenceState.Running;
  3418. if (EntityTransferModule.IsInTransit(sp.UUID))
  3419. {
  3420. sp.DoNotCloseAfterTeleport = true;
  3421. m_log.DebugFormat(
  3422. "[SCENE]: Set DoNotCloseAfterTeleport for child scene presence {0} in {1} because this region will attempt end-of-teleport close from a previous close.",
  3423. sp.Name, Name);
  3424. }
  3425. }
  3426. }
  3427. // Need to poll here in case we are currently deleting an sp. Letting threads run over each other will
  3428. // allow unpredictable things to happen.
  3429. if (sp != null)
  3430. {
  3431. const int polls = 10;
  3432. const int pollInterval = 1000;
  3433. int pollsLeft = polls;
  3434. while (sp.LifecycleState == ScenePresenceState.Removing && pollsLeft-- > 0)
  3435. Thread.Sleep(pollInterval);
  3436. if (sp.LifecycleState == ScenePresenceState.Removing)
  3437. {
  3438. m_log.WarnFormat(
  3439. "[SCENE]: Agent {0} in {1} was still being removed after {2}s. Aborting NewUserConnection.",
  3440. sp.Name, Name, polls * pollInterval / 1000);
  3441. return false;
  3442. }
  3443. else if (polls != pollsLeft)
  3444. {
  3445. m_log.DebugFormat(
  3446. "[SCENE]: NewUserConnection for agent {0} in {1} had to wait {2}s for in-progress removal to complete on an old presence.",
  3447. sp.Name, Name, polls * pollInterval / 1000);
  3448. }
  3449. }
  3450. // TODO: can we remove this lock?
  3451. lock (m_newUserConnLock)
  3452. {
  3453. if (sp != null && !sp.IsChildAgent)
  3454. {
  3455. // We have a root agent. Is it in transit?
  3456. if (!EntityTransferModule.IsInTransit(sp.UUID))
  3457. {
  3458. // We have a zombie from a crashed session.
  3459. // Or the same user is trying to be root twice here, won't work.
  3460. // Kill it.
  3461. m_log.WarnFormat(
  3462. "[SCENE]: Existing root scene presence detected for {0} {1} in {2} when connecting. Removing existing presence.",
  3463. sp.Name, sp.UUID, RegionInfo.RegionName);
  3464. if (sp.ControllingClient != null)
  3465. CloseAgent(sp.UUID, true);
  3466. sp = null;
  3467. }
  3468. //else
  3469. // m_log.WarnFormat("[SCENE]: Existing root scene presence for {0} {1} in {2}, but agent is in trasit", sp.Name, sp.UUID, RegionInfo.RegionName);
  3470. }
  3471. // Optimistic: add or update the circuit data with the new agent circuit data and teleport flags.
  3472. // We need the circuit data here for some of the subsequent checks. (groups, for example)
  3473. // If the checks fail, we remove the circuit.
  3474. acd.teleportFlags = teleportFlags;
  3475. if (vialogin)
  3476. {
  3477. IUserAccountCacheModule cache = RequestModuleInterface<IUserAccountCacheModule>();
  3478. if (cache != null)
  3479. // cache.Remove(acd.firstname + " " + acd.lastname);
  3480. cache.Remove(acd.AgentID);
  3481. // Remove any preexisting circuit - we don't want duplicates
  3482. // This is a stab at preventing avatar "ghosting"
  3483. m_authenticateHandler.RemoveCircuit(acd.AgentID);
  3484. }
  3485. m_authenticateHandler.AddNewCircuit(acd.circuitcode, acd);
  3486. if (sp == null) // We don't have an [child] agent here already
  3487. {
  3488. if (requirePresenceLookup)
  3489. {
  3490. try
  3491. {
  3492. if (!VerifyUserPresence(acd, out reason))
  3493. {
  3494. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3495. return false;
  3496. }
  3497. }
  3498. catch (Exception e)
  3499. {
  3500. m_log.ErrorFormat(
  3501. "[SCENE]: Exception verifying presence {0}{1}", e.Message, e.StackTrace);
  3502. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3503. return false;
  3504. }
  3505. }
  3506. try
  3507. {
  3508. if (!AuthorizeUser(acd, (vialogin ? false : SeeIntoRegion), out reason))
  3509. {
  3510. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3511. return false;
  3512. }
  3513. }
  3514. catch (Exception e)
  3515. {
  3516. m_log.ErrorFormat(
  3517. "[SCENE]: Exception authorizing user {0}{1}", e.Message, e.StackTrace);
  3518. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3519. return false;
  3520. }
  3521. m_log.InfoFormat(
  3522. "[SCENE]: Region {0} authenticated and authorized incoming {1} agent {2} {3} {4} (circuit code {5})",
  3523. Name, (acd.child ? "child" : "root"), acd.firstname, acd.lastname,
  3524. acd.AgentID, acd.circuitcode);
  3525. if (CapsModule != null)
  3526. {
  3527. CapsModule.SetAgentCapsSeeds(acd);
  3528. CapsModule.CreateCaps(acd.AgentID, acd.circuitcode);
  3529. }
  3530. }
  3531. else
  3532. {
  3533. // Let the SP know how we got here. This has a lot of interesting
  3534. // uses down the line.
  3535. sp.TeleportFlags = (TPFlags)teleportFlags;
  3536. if (sp.IsChildAgent)
  3537. {
  3538. m_log.DebugFormat(
  3539. "[SCENE]: Adjusting known seeds for existing agent {0} in {1}",
  3540. acd.AgentID, RegionInfo.RegionName);
  3541. if (CapsModule != null)
  3542. {
  3543. CapsModule.SetAgentCapsSeeds(acd);
  3544. CapsModule.CreateCaps(acd.AgentID, acd.circuitcode);
  3545. }
  3546. sp.AdjustKnownSeeds();
  3547. }
  3548. }
  3549. // Try caching an incoming user name much earlier on to see if this helps with an issue
  3550. // where HG users are occasionally seen by others as "Unknown User" because their UUIDName
  3551. // request for the HG avatar appears to trigger before the user name is cached.
  3552. CacheUserName(null, acd);
  3553. }
  3554. if (CapsModule != null)
  3555. {
  3556. CapsModule.ActivateCaps(acd.circuitcode);
  3557. }
  3558. // if (vialogin)
  3559. // {
  3560. // CleanDroppedAttachments();
  3561. // }
  3562. if(teleportFlags != (uint) TPFlags.Default)
  3563. {
  3564. // Make sure root avatar position is in the region
  3565. if (acd.startpos.X < 0)
  3566. acd.startpos.X = 1f;
  3567. else if (acd.startpos.X >= RegionInfo.RegionSizeX)
  3568. acd.startpos.X = RegionInfo.RegionSizeX - 1f;
  3569. if (acd.startpos.Y < 0)
  3570. acd.startpos.Y = 1f;
  3571. else if (acd.startpos.Y >= RegionInfo.RegionSizeY)
  3572. acd.startpos.Y = RegionInfo.RegionSizeY - 1f;
  3573. }
  3574. // only check access, actual relocations will happen later on ScenePresence MakeRoot
  3575. // allow child agents creation
  3576. // if(!godlike && teleportFlags != (uint) TPFlags.Default)
  3577. if(teleportFlags != (uint) TPFlags.Default)
  3578. {
  3579. bool checkTeleHub;
  3580. // don't check hubs if via home or via lure
  3581. if((teleportFlags & (uint) TPFlags.ViaHome) != 0
  3582. || (teleportFlags & (uint) TPFlags.ViaLure) != 0)
  3583. checkTeleHub = false;
  3584. else
  3585. checkTeleHub = vialogin
  3586. || (TelehubAllowLandmarks == true ? false : ((teleportFlags & (uint)TPFlags.ViaLandmark) != 0 ))
  3587. || (teleportFlags & (uint) TPFlags.ViaLocation) != 0;
  3588. if(!CheckLandPositionAccess(acd.AgentID, true, checkTeleHub, acd.startpos, out reason))
  3589. {
  3590. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3591. return false;
  3592. }
  3593. }
  3594. return true;
  3595. }
  3596. private bool IsPositionAllowed(UUID agentID, Vector3 pos, ref string reason)
  3597. {
  3598. ILandObject land = LandChannel.GetLandObject(pos);
  3599. if (land == null)
  3600. return true;
  3601. if (land.IsBannedFromLand(agentID) || land.IsRestrictedFromLand(agentID))
  3602. {
  3603. reason = "You are banned from the region.";
  3604. return false;
  3605. }
  3606. return true;
  3607. }
  3608. public bool TestLandRestrictions(UUID agentID, out string reason, ref float posX, ref float posY)
  3609. {
  3610. if (posX < 0)
  3611. posX = 0;
  3612. else if (posX >= RegionInfo.RegionSizeX)
  3613. posX = RegionInfo.RegionSizeX - 0.5f;
  3614. if (posY < 0)
  3615. posY = 0;
  3616. else if (posY >= RegionInfo.RegionSizeY)
  3617. posY = RegionInfo.RegionSizeY - 0.5f;
  3618. reason = String.Empty;
  3619. if (Permissions.IsGod(agentID))
  3620. return true;
  3621. ILandObject land = LandChannel.GetLandObject(posX, posY);
  3622. if (land == null)
  3623. return false;
  3624. bool banned = land.IsBannedFromLand(agentID);
  3625. bool restricted = land.IsRestrictedFromLand(agentID);
  3626. if (banned || restricted)
  3627. {
  3628. ILandObject nearestParcel = GetNearestAllowedParcel(agentID, posX, posY);
  3629. Vector2? newPosition = null;
  3630. if (nearestParcel != null)
  3631. {
  3632. //Move agent to nearest allowed
  3633. // Vector2 newPosition = GetParcelSafeCorner(nearestParcel);
  3634. newPosition = nearestParcel.GetNearestPoint(new Vector3(posX, posY,0));
  3635. }
  3636. if(newPosition == null)
  3637. {
  3638. if (banned)
  3639. {
  3640. reason = "Cannot regioncross into banned parcel.";
  3641. }
  3642. else
  3643. {
  3644. reason = String.Format("Denied access to private region {0}: You are not on the access list for that region.",
  3645. RegionInfo.RegionName);
  3646. }
  3647. return false;
  3648. }
  3649. else
  3650. {
  3651. posX = newPosition.Value.X;
  3652. posY = newPosition.Value.Y;
  3653. }
  3654. }
  3655. reason = "";
  3656. return true;
  3657. }
  3658. /// <summary>
  3659. /// Verifies that the user has a presence on the Grid
  3660. /// </summary>
  3661. /// <param name="agent">Circuit Data of the Agent we're verifying</param>
  3662. /// <param name="reason">Outputs the reason for the false response on this string</param>
  3663. /// <returns>True if the user has a session on the grid. False if it does not. False will
  3664. /// also return a reason.</returns>
  3665. public virtual bool VerifyUserPresence(AgentCircuitData agent, out string reason)
  3666. {
  3667. reason = String.Empty;
  3668. IPresenceService presence = RequestModuleInterface<IPresenceService>();
  3669. if (presence == null)
  3670. {
  3671. reason = String.Format("Failed to verify user presence in the grid for {0} {1} in region {2}. Presence service does not exist.", agent.firstname, agent.lastname, RegionInfo.RegionName);
  3672. return false;
  3673. }
  3674. OpenSim.Services.Interfaces.PresenceInfo pinfo = presence.GetAgent(agent.SessionID);
  3675. if (pinfo == null)
  3676. {
  3677. reason = String.Format("Failed to verify user presence in the grid for {0} {1}, access denied to region {2}.", agent.firstname, agent.lastname, RegionInfo.RegionName);
  3678. return false;
  3679. }
  3680. return true;
  3681. }
  3682. /// <summary>
  3683. /// Verify if the user can connect to this region. Checks the banlist and ensures that the region is set for public access
  3684. /// </summary>
  3685. /// <param name="agent">The circuit data for the agent</param>
  3686. /// <param name="reason">outputs the reason to this string</param>
  3687. /// <returns>True if the region accepts this agent. False if it does not. False will
  3688. /// also return a reason.</returns>
  3689. protected virtual bool AuthorizeUser(AgentCircuitData agent, bool bypassAccessControl, out string reason)
  3690. {
  3691. reason = String.Empty;
  3692. if (!m_strictAccessControl)
  3693. return true;
  3694. if (Permissions.IsGod(agent.AgentID))
  3695. return true;
  3696. if (AuthorizationService != null)
  3697. {
  3698. if (!AuthorizationService.IsAuthorizedForRegion(
  3699. agent.AgentID.ToString(), agent.firstname, agent.lastname, RegionInfo.RegionID.ToString(), out reason))
  3700. {
  3701. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because: {4}",
  3702. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName, reason);
  3703. return false;
  3704. }
  3705. }
  3706. // We only test the things below when we want to cut off
  3707. // child agents from being present in the scene for which their root
  3708. // agent isn't allowed. Otherwise, we allow child agents. The test for
  3709. // the root is done elsewhere (QueryAccess)
  3710. if (!bypassAccessControl)
  3711. {
  3712. if(RegionInfo.EstateSettings == null)
  3713. {
  3714. // something is broken? let it get in
  3715. m_log.ErrorFormat("[CONNECTION BEGIN]: Estate Settings is null!");
  3716. return true;
  3717. }
  3718. // check estate ban
  3719. int flags = GetUserFlags(agent.AgentID);
  3720. if (RegionInfo.EstateSettings.IsBanned(agent.AgentID, flags))
  3721. {
  3722. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist",
  3723. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3724. reason = String.Format("Denied access to region {0}: You have been banned from that region.",
  3725. RegionInfo.RegionName);
  3726. return false;
  3727. }
  3728. // public access
  3729. if (RegionInfo.EstateSettings.PublicAccess)
  3730. return true;
  3731. // in access list / owner / manager
  3732. if (RegionInfo.EstateSettings.HasAccess(agent.AgentID))
  3733. return true;
  3734. // finally test groups
  3735. bool groupAccess = false;
  3736. // some say GOTO is ugly
  3737. if(m_groupsModule == null) // if no groups refuse
  3738. goto Label_GroupsDone;
  3739. UUID[] estateGroups = RegionInfo.EstateSettings.EstateGroups;
  3740. if(estateGroups == null)
  3741. {
  3742. m_log.ErrorFormat("[CONNECTION BEGIN]: Estate GroupMembership is null!");
  3743. goto Label_GroupsDone;
  3744. }
  3745. if(estateGroups.Length == 0)
  3746. goto Label_GroupsDone;
  3747. List<UUID> agentGroups = new List<UUID>();
  3748. GroupMembershipData[] GroupMembership = m_groupsModule.GetMembershipData(agent.AgentID);
  3749. if(GroupMembership == null)
  3750. {
  3751. m_log.ErrorFormat("[CONNECTION BEGIN]: GroupMembership is null!");
  3752. goto Label_GroupsDone;
  3753. }
  3754. if(GroupMembership.Length == 0)
  3755. goto Label_GroupsDone;
  3756. for(int i = 0;i < GroupMembership.Length;i++)
  3757. agentGroups.Add(GroupMembership[i].GroupID);
  3758. foreach(UUID group in estateGroups)
  3759. {
  3760. if(agentGroups.Contains(group))
  3761. {
  3762. groupAccess = true;
  3763. break;
  3764. }
  3765. }
  3766. Label_GroupsDone:
  3767. if (!groupAccess)
  3768. {
  3769. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user does not have access to the estate",
  3770. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3771. reason = String.Format("Denied access to private region {0}: You do not have access to that region.",
  3772. RegionInfo.RegionName);
  3773. return false;
  3774. }
  3775. }
  3776. return true;
  3777. }
  3778. /// <summary>
  3779. /// Update an AgentCircuitData object with new information
  3780. /// </summary>
  3781. /// <param name="data">Information to update the AgentCircuitData with</param>
  3782. public void UpdateCircuitData(AgentCircuitData data)
  3783. {
  3784. m_authenticateHandler.UpdateAgentData(data);
  3785. }
  3786. /// <summary>
  3787. /// Change the Circuit Code for the user's Circuit Data
  3788. /// </summary>
  3789. /// <param name="oldcc">The old Circuit Code. Must match a previous circuit code</param>
  3790. /// <param name="newcc">The new Circuit Code. Must not be an already existing circuit code</param>
  3791. /// <returns>True if we successfully changed it. False if we did not</returns>
  3792. public bool ChangeCircuitCode(uint oldcc, uint newcc)
  3793. {
  3794. return m_authenticateHandler.TryChangeCiruitCode(oldcc, newcc);
  3795. }
  3796. // /// <summary>
  3797. // /// The Grid has requested that we log-off a user. Log them off.
  3798. // /// </summary>
  3799. // /// <param name="AvatarID">Unique ID of the avatar to log-off</param>
  3800. // /// <param name="RegionSecret">SecureSessionID of the user, or the RegionSecret text when logging on to the grid</param>
  3801. // /// <param name="message">message to display to the user. Reason for being logged off</param>
  3802. // public void HandleLogOffUserFromGrid(UUID AvatarID, UUID RegionSecret, string message)
  3803. // {
  3804. // ScenePresence loggingOffUser = GetScenePresence(AvatarID);
  3805. // if (loggingOffUser != null)
  3806. // {
  3807. // UUID localRegionSecret = UUID.Zero;
  3808. // bool parsedsecret = UUID.TryParse(RegionInfo.regionSecret, out localRegionSecret);
  3809. //
  3810. // // Region Secret is used here in case a new sessionid overwrites an old one on the user server.
  3811. // // Will update the user server in a few revisions to use it.
  3812. //
  3813. // if (RegionSecret == loggingOffUser.ControllingClient.SecureSessionId || (parsedsecret && RegionSecret == localRegionSecret))
  3814. // {
  3815. // m_sceneGridService.SendCloseChildAgentConnections(loggingOffUser.UUID, loggingOffUser.KnownRegionHandles);
  3816. // loggingOffUser.ControllingClient.Kick(message);
  3817. // // Give them a second to receive the message!
  3818. // Thread.Sleep(1000);
  3819. // loggingOffUser.ControllingClient.Close();
  3820. // }
  3821. // else
  3822. // {
  3823. // m_log.Info("[USERLOGOFF]: System sending the LogOff user message failed to sucessfully authenticate");
  3824. // }
  3825. // }
  3826. // else
  3827. // {
  3828. // m_log.InfoFormat("[USERLOGOFF]: Got a logoff request for {0} but the user isn't here. The user might already have been logged out", AvatarID.ToString());
  3829. // }
  3830. // }
  3831. // /// <summary>
  3832. // /// Triggered when an agent crosses into this sim. Also happens on initial login.
  3833. // /// </summary>
  3834. // /// <param name="agentID"></param>
  3835. // /// <param name="position"></param>
  3836. // /// <param name="isFlying"></param>
  3837. // public virtual void AgentCrossing(UUID agentID, Vector3 position, bool isFlying)
  3838. // {
  3839. // ScenePresence presence = GetScenePresence(agentID);
  3840. // if (presence != null)
  3841. // {
  3842. // try
  3843. // {
  3844. // presence.MakeRootAgent(position, isFlying);
  3845. // }
  3846. // catch (Exception e)
  3847. // {
  3848. // m_log.ErrorFormat("[SCENE]: Unable to do agent crossing, exception {0}{1}", e.Message, e.StackTrace);
  3849. // }
  3850. // }
  3851. // else
  3852. // {
  3853. // m_log.ErrorFormat(
  3854. // "[SCENE]: Could not find presence for agent {0} crossing into scene {1}",
  3855. // agentID, RegionInfo.RegionName);
  3856. // }
  3857. // }
  3858. /// <summary>
  3859. /// We've got an update about an agent that sees into this region,
  3860. /// send it to ScenePresence for processing It's the full data.
  3861. /// </summary>
  3862. /// <param name="cAgentData">Agent that contains all of the relevant things about an agent.
  3863. /// Appearance, animations, position, etc.</param>
  3864. /// <returns>true if we handled it.</returns>
  3865. public virtual bool IncomingUpdateChildAgent(AgentData cAgentData)
  3866. {
  3867. m_log.DebugFormat(
  3868. "[SCENE]: Incoming child agent update for {0} in {1}", cAgentData.AgentID, RegionInfo.RegionName);
  3869. if (!LoginsEnabled)
  3870. {
  3871. // reason = "Logins Disabled";
  3872. m_log.DebugFormat(
  3873. "[SCENE]: update for {0} in {1} refused: Logins Disabled", cAgentData.AgentID, RegionInfo.RegionName);
  3874. return false;
  3875. }
  3876. int flags = GetUserFlags(cAgentData.AgentID);
  3877. if (RegionInfo.EstateSettings.IsBanned(cAgentData.AgentID, flags))
  3878. {
  3879. m_log.DebugFormat("[SCENE]: Denying root agent entry to {0}: banned", cAgentData.AgentID);
  3880. return false;
  3881. }
  3882. // TODO: This check should probably be in QueryAccess().
  3883. ILandObject nearestParcel = GetNearestAllowedParcel(cAgentData.AgentID,
  3884. (float)RegionInfo.RegionSizeX * 0.5f, (float)RegionInfo.RegionSizeY * 0.5f);
  3885. if (nearestParcel == null)
  3886. {
  3887. m_log.InfoFormat(
  3888. "[SCENE]: Denying root agent entry to {0} in {1}: no allowed parcel",
  3889. cAgentData.AgentID, RegionInfo.RegionName);
  3890. return false;
  3891. }
  3892. // We have to wait until the viewer contacts this region
  3893. // after receiving the EnableSimulator HTTP Event Queue message (for the v1 teleport protocol)
  3894. // or TeleportFinish (for the v2 teleport protocol). This triggers the viewer to send
  3895. // a UseCircuitCode packet which in turn calls AddNewAgent which finally creates the ScenePresence.
  3896. ScenePresence sp = WaitGetScenePresence(cAgentData.AgentID);
  3897. if (sp != null)
  3898. {
  3899. if (!sp.IsChildAgent)
  3900. {
  3901. m_log.WarnFormat("[SCENE]: Ignoring a child update on a root agent {0} {1} in {2}",
  3902. sp.Name, sp.UUID, Name);
  3903. return false;
  3904. }
  3905. if (cAgentData.SessionID != sp.ControllingClient.SessionId)
  3906. {
  3907. m_log.WarnFormat(
  3908. "[SCENE]: Attempt to update agent {0} with diferent session id {1} != {2}",
  3909. sp.UUID, sp.ControllingClient.SessionId, cAgentData.SessionID);
  3910. return false;
  3911. }
  3912. sp.UpdateChildAgent(cAgentData);
  3913. int ntimes = 100;
  3914. if (cAgentData.SenderWantsToWaitForRoot)
  3915. {
  3916. while (sp.IsChildAgent && ntimes-- > 0)
  3917. Thread.Sleep(250);
  3918. if (sp.IsChildAgent)
  3919. {
  3920. m_log.WarnFormat(
  3921. "[SCENE]: Found presence {0} {1} unexpectedly still child in {2}",
  3922. sp.Name, sp.UUID, Name);
  3923. return false;
  3924. }
  3925. }
  3926. return true;
  3927. }
  3928. return false;
  3929. }
  3930. /// <summary>
  3931. /// We've got an update about an agent that sees into this region,
  3932. /// send it to ScenePresence for processing It's only positional data
  3933. /// </summary>
  3934. /// <param name="cAgentData">AgentPosition that contains agent positional data so we can know what to send</param>
  3935. /// <returns>true if we handled it.</returns>
  3936. public virtual bool IncomingUpdateChildAgent(AgentPosition cAgentData)
  3937. {
  3938. // m_log.DebugFormat(
  3939. // "[SCENE PRESENCE]: IncomingChildAgentDataUpdate POSITION for {0} in {1}, position {2}",
  3940. // cAgentData.AgentID, Name, cAgentData.Position);
  3941. ScenePresence childAgentUpdate = GetScenePresence(cAgentData.AgentID);
  3942. if (childAgentUpdate != null)
  3943. {
  3944. // if (childAgentUpdate.ControllingClient.SessionId != cAgentData.SessionID)
  3945. // // Only warn for now
  3946. // m_log.WarnFormat("[SCENE]: Attempt at updating position of agent {0} with invalid session id {1}. Neighbor running older version?",
  3947. // childAgentUpdate.UUID, cAgentData.SessionID);
  3948. // I can't imagine *yet* why we would get an update if the agent is a root agent..
  3949. // however to avoid a race condition crossing borders..
  3950. if (childAgentUpdate.IsChildAgent)
  3951. {
  3952. //Send Data to ScenePresence
  3953. childAgentUpdate.UpdateChildAgent(cAgentData);
  3954. // Not Implemented:
  3955. //TODO: Do we need to pass the message on to one of our neighbors?
  3956. }
  3957. return true;
  3958. }
  3959. return false;
  3960. }
  3961. /// <summary>
  3962. /// Poll until the requested ScenePresence appears or we timeout.
  3963. /// </summary>
  3964. /// <returns>The scene presence is found, else null.</returns>
  3965. /// <param name='agentID'></param>
  3966. protected virtual ScenePresence WaitGetScenePresence(UUID agentID)
  3967. {
  3968. int ntimes = 120; // 30s
  3969. ScenePresence sp = null;
  3970. while ((sp = GetScenePresence(agentID)) == null && (ntimes-- > 0))
  3971. Thread.Sleep(250);
  3972. if (sp == null)
  3973. m_log.WarnFormat(
  3974. "[SCENE PRESENCE]: Did not find presence with id {0} in {1} before timeout",
  3975. agentID, RegionInfo.RegionName);
  3976. return sp;
  3977. }
  3978. /// <summary>
  3979. /// Authenticated close (via network)
  3980. /// </summary>
  3981. /// <param name="agentID"></param>
  3982. /// <param name="force"></param>
  3983. /// <param name="auth_token"></param>
  3984. /// <returns></returns>
  3985. public bool CloseAgent(UUID agentID, bool force, string auth_token)
  3986. {
  3987. //m_log.DebugFormat("[SCENE]: Processing incoming close agent {0} in region {1} with auth_token {2}", agentID, RegionInfo.RegionName, auth_token);
  3988. // Check that the auth_token is valid
  3989. AgentCircuitData acd = AuthenticateHandler.GetAgentCircuitData(agentID);
  3990. if (acd == null)
  3991. {
  3992. m_log.DebugFormat(
  3993. "[SCENE]: Request to close agent {0} but no such agent in scene {1}. May have been closed previously.",
  3994. agentID, Name);
  3995. return false;
  3996. }
  3997. if (acd.SessionID.ToString() == auth_token)
  3998. {
  3999. return CloseAgent(agentID, force);
  4000. }
  4001. else
  4002. {
  4003. m_log.WarnFormat(
  4004. "[SCENE]: Request to close agent {0} with invalid authorization token {1} in {2}",
  4005. agentID, auth_token, Name);
  4006. }
  4007. return false;
  4008. }
  4009. /// <summary>
  4010. /// Tell a single client to prepare to close.
  4011. /// </summary>
  4012. /// <remarks>
  4013. /// This should only be called if we may close the client but there will be some delay in so doing. Meant for
  4014. /// internal use - other callers should almost certainly called CloseClient().
  4015. /// </remarks>
  4016. /// <param name="sp"></param>
  4017. /// <returns>true if pre-close state notification was successful. false if the agent
  4018. /// was not in a state where it could transition to pre-close.</returns>
  4019. public bool IncomingPreCloseClient(ScenePresence sp)
  4020. {
  4021. lock (m_removeClientLock)
  4022. {
  4023. // We need to avoid a race condition where in, for example, an A B C D region layout, an avatar may
  4024. // teleport from A -> D, but then -> C before A has asked B to close its old child agent. We do not
  4025. // want to obey this close since C may have renewed the child agent lease on B.
  4026. if (sp.DoNotCloseAfterTeleport)
  4027. {
  4028. m_log.DebugFormat(
  4029. "[SCENE]: Not pre-closing {0} agent {1} in {2} since another simulator has re-established the child connection",
  4030. sp.IsChildAgent ? "child" : "root", sp.Name, Name);
  4031. // Need to reset the flag so that a subsequent close after another teleport can succeed.
  4032. sp.DoNotCloseAfterTeleport = false;
  4033. return false;
  4034. }
  4035. if (sp.LifecycleState != ScenePresenceState.Running)
  4036. {
  4037. m_log.DebugFormat(
  4038. "[SCENE]: Called IncomingPreCloseAgent() for {0} in {1} but presence is already in state {2}",
  4039. sp.Name, Name, sp.LifecycleState);
  4040. return false;
  4041. }
  4042. sp.LifecycleState = ScenePresenceState.PreRemove;
  4043. return true;
  4044. }
  4045. }
  4046. /// <summary>
  4047. /// Tell a single agent to disconnect from the region.
  4048. /// </summary>
  4049. /// <param name="agentID"></param>
  4050. /// <param name="force">
  4051. /// Force the agent to close even if it might be in the middle of some other operation. You do not want to
  4052. /// force unless you are absolutely sure that the agent is dead and a normal close is not working.
  4053. /// </param>
  4054. public override bool CloseAgent(UUID agentID, bool force)
  4055. {
  4056. ScenePresence sp;
  4057. lock (m_removeClientLock)
  4058. {
  4059. sp = GetScenePresence(agentID);
  4060. if (sp == null)
  4061. {
  4062. // If there is no scene presence, we may be handling a dead
  4063. // client. These can keep an avatar from reentering a region
  4064. // and since they don't get cleaned up they will stick
  4065. // around until region restart. So, if there is no SP,
  4066. // remove the client as well.
  4067. IClientAPI client = null;
  4068. if (m_clientManager.TryGetValue(agentID, out client))
  4069. {
  4070. m_clientManager.Remove(agentID);
  4071. if (CapsModule != null)
  4072. CapsModule.RemoveCaps(agentID, 0);
  4073. m_log.DebugFormat( "[SCENE]: Dead client for agent ID {0} was cleaned up in {1}", agentID, Name);
  4074. return true;
  4075. }
  4076. m_log.DebugFormat(
  4077. "[SCENE]: Called CloseClient() with agent ID {0} but no such presence is in {1}",
  4078. agentID, Name);
  4079. return false;
  4080. }
  4081. if (sp.LifecycleState != ScenePresenceState.Running && sp.LifecycleState != ScenePresenceState.PreRemove)
  4082. {
  4083. m_log.DebugFormat(
  4084. "[SCENE]: Called CloseClient() for {0} in {1} but presence is already in state {2}",
  4085. sp.Name, Name, sp.LifecycleState);
  4086. return false;
  4087. }
  4088. // We need to avoid a race condition where in, for example, an A B C D region layout, an avatar may
  4089. // teleport from A -> D, but then -> C before A has asked B to close its old child agent. We do not
  4090. // want to obey this close since C may have renewed the child agent lease on B.
  4091. if (sp.DoNotCloseAfterTeleport)
  4092. {
  4093. m_log.DebugFormat(
  4094. "[SCENE]: Not closing {0} agent {1} in {2} since another simulator has re-established the child connection",
  4095. sp.IsChildAgent ? "child" : "root", sp.Name, Name);
  4096. // Need to reset the flag so that a subsequent close after another teleport can succeed.
  4097. sp.DoNotCloseAfterTeleport = false;
  4098. return false;
  4099. }
  4100. sp.LifecycleState = ScenePresenceState.Removing;
  4101. }
  4102. if (sp != null)
  4103. {
  4104. sp.ControllingClient.Close(force, force);
  4105. if(sp.IsNPC && UserManagementModule != null)
  4106. UserManagementModule.RemoveUser(sp.UUID);
  4107. return true;
  4108. }
  4109. return true;
  4110. }
  4111. /// <summary>
  4112. /// Tries to teleport agent within region.
  4113. /// </summary>
  4114. /// <param name="remoteClient"></param>
  4115. /// <param name="position"></param>
  4116. /// <param name="lookAt"></param>
  4117. /// <param name="teleportFlags"></param>
  4118. public void RequestLocalTeleport(ScenePresence sp, Vector3 position, Vector3 vel,
  4119. Vector3 lookat, int flags)
  4120. {
  4121. sp.LocalTeleport(position, vel, lookat, flags);
  4122. }
  4123. /// <summary>
  4124. /// Tries to teleport agent to another region.
  4125. /// </summary>
  4126. /// <remarks>
  4127. /// The region name must exactly match that given.
  4128. /// </remarks>
  4129. /// <param name="remoteClient"></param>
  4130. /// <param name="regionName"></param>
  4131. /// <param name="position"></param>
  4132. /// <param name="lookAt"></param>
  4133. /// <param name="teleportFlags"></param>
  4134. public void RequestTeleportLocation(IClientAPI remoteClient, string regionName, Vector3 position,
  4135. Vector3 lookat, uint teleportFlags)
  4136. {
  4137. if (EntityTransferModule == null)
  4138. {
  4139. m_log.DebugFormat("[SCENE]: Unable to perform teleports: no AgentTransferModule is active");
  4140. return;
  4141. }
  4142. ScenePresence sp = GetScenePresence(remoteClient.AgentId);
  4143. if (sp == null || sp.IsDeleted || sp.IsInTransit)
  4144. return;
  4145. ulong regionHandle = 0;
  4146. if(regionName == RegionInfo.RegionName)
  4147. regionHandle = RegionInfo.RegionHandle;
  4148. else
  4149. {
  4150. GridRegion region = GridService.GetRegionByName(RegionInfo.ScopeID, regionName);
  4151. if (region != null)
  4152. regionHandle = region.RegionHandle;
  4153. }
  4154. if(regionHandle == 0)
  4155. {
  4156. // can't find the region: Tell viewer and abort
  4157. remoteClient.SendTeleportFailed("The region '" + regionName + "' could not be found.");
  4158. return;
  4159. }
  4160. EntityTransferModule.Teleport(sp, regionHandle, position, lookat, teleportFlags);
  4161. }
  4162. /// <summary>
  4163. /// Tries to teleport agent to other region.
  4164. /// </summary>
  4165. /// <param name="remoteClient"></param>
  4166. /// <param name="regionHandle"></param>
  4167. /// <param name="position"></param>
  4168. /// <param name="lookAt"></param>
  4169. /// <param name="teleportFlags"></param>
  4170. public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, Vector3 position,
  4171. Vector3 lookAt, uint teleportFlags)
  4172. {
  4173. if (EntityTransferModule == null)
  4174. {
  4175. m_log.DebugFormat("[SCENE]: Unable to perform teleports: no AgentTransferModule is active");
  4176. return;
  4177. }
  4178. ScenePresence sp = GetScenePresence(remoteClient.AgentId);
  4179. if (sp == null || sp.IsDeleted || sp.IsInTransit)
  4180. return;
  4181. EntityTransferModule.Teleport(sp, regionHandle, position, lookAt, teleportFlags);
  4182. }
  4183. public bool CrossAgentToNewRegion(ScenePresence agent, bool isFlying)
  4184. {
  4185. if (EntityTransferModule != null)
  4186. {
  4187. return EntityTransferModule.Cross(agent, isFlying);
  4188. }
  4189. else
  4190. {
  4191. m_log.DebugFormat("[SCENE]: Unable to cross agent to neighbouring region, because there is no AgentTransferModule");
  4192. }
  4193. return false;
  4194. }
  4195. public void SendOutChildAgentUpdates(AgentPosition cadu, ScenePresence presence)
  4196. {
  4197. m_sceneGridService.SendChildAgentDataUpdate(cadu, presence);
  4198. }
  4199. #endregion
  4200. #region Other Methods
  4201. protected override IConfigSource GetConfig()
  4202. {
  4203. return m_config;
  4204. }
  4205. #endregion
  4206. public void HandleObjectPermissionsUpdate(IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set)
  4207. {
  4208. // Check for spoofing.. since this is permissions we're talking about here!
  4209. if ((controller.SessionId == sessionID) && (controller.AgentId == agentID))
  4210. {
  4211. // Tell the object to do permission update
  4212. if (localId != 0)
  4213. {
  4214. SceneObjectGroup chObjectGroup = GetGroupByPrim(localId);
  4215. if (chObjectGroup != null)
  4216. {
  4217. chObjectGroup.UpdatePermissions(agentID, field, localId, mask, set);
  4218. }
  4219. }
  4220. }
  4221. }
  4222. /// <summary>
  4223. /// Causes all clients to get a full object update on all of the objects in the scene.
  4224. /// </summary>
  4225. public void ForceClientUpdate()
  4226. {
  4227. EntityBase[] entityList = GetEntities();
  4228. foreach (EntityBase ent in entityList)
  4229. {
  4230. if (ent is SceneObjectGroup)
  4231. {
  4232. ((SceneObjectGroup)ent).ScheduleGroupForFullUpdate();
  4233. }
  4234. }
  4235. }
  4236. /// <summary>
  4237. /// This is currently only used for scale (to scale to MegaPrim size)
  4238. /// There is a console command that calls this in OpenSimMain
  4239. /// </summary>
  4240. /// <param name="cmdparams"></param>
  4241. public void HandleEditCommand(string[] cmdparams)
  4242. {
  4243. m_log.DebugFormat("Searching for Primitive: '{0}'", cmdparams[2]);
  4244. EntityBase[] entityList = GetEntities();
  4245. foreach (EntityBase ent in entityList)
  4246. {
  4247. if (ent is SceneObjectGroup)
  4248. {
  4249. SceneObjectPart part = ((SceneObjectGroup)ent).GetPart(((SceneObjectGroup)ent).UUID);
  4250. if (part != null)
  4251. {
  4252. if (part.Name == cmdparams[2])
  4253. {
  4254. part.Resize(
  4255. new Vector3(Convert.ToSingle(cmdparams[3]), Convert.ToSingle(cmdparams[4]),
  4256. Convert.ToSingle(cmdparams[5])));
  4257. m_log.DebugFormat("Edited scale of Primitive: {0}", part.Name);
  4258. }
  4259. }
  4260. }
  4261. }
  4262. }
  4263. #region Script Handling Methods
  4264. /// <summary>
  4265. /// Console command handler to send script command to script engine.
  4266. /// </summary>
  4267. /// <param name="args"></param>
  4268. public void SendCommandToPlugins(string[] args)
  4269. {
  4270. m_eventManager.TriggerOnPluginConsole(args);
  4271. }
  4272. public LandData GetLandData(float x, float y)
  4273. {
  4274. ILandObject parcel = LandChannel.GetLandObject(x, y);
  4275. if (parcel == null)
  4276. return null;
  4277. return parcel.LandData;
  4278. }
  4279. /// <summary>
  4280. /// Get LandData by position.
  4281. /// </summary>
  4282. /// <param name="pos"></param>
  4283. /// <returns></returns>
  4284. public LandData GetLandData(Vector3 pos)
  4285. {
  4286. return GetLandData(pos.X, pos.Y);
  4287. }
  4288. public LandData GetLandData(uint x, uint y)
  4289. {
  4290. // m_log.DebugFormat("[SCENE]: returning land for {0},{1}", x, y);
  4291. ILandObject parcel = LandChannel.GetLandObject((int)x, (int)y);
  4292. if (parcel == null)
  4293. return null;
  4294. return parcel.LandData;
  4295. }
  4296. #endregion
  4297. #region Script Engine
  4298. public bool LSLScriptDanger(SceneObjectPart part, Vector3 pos)
  4299. {
  4300. ILandObject parcel = LandChannel.GetLandObject(pos.X, pos.Y);
  4301. if (parcel == null)
  4302. return true;
  4303. LandData ldata = parcel.LandData;
  4304. if (ldata == null)
  4305. return true;
  4306. uint landflags = ldata.Flags;
  4307. uint mask = (uint)(ParcelFlags.CreateObjects | ParcelFlags.AllowAPrimitiveEntry);
  4308. if((landflags & mask) != mask)
  4309. return true;
  4310. if((landflags & (uint)ParcelFlags.AllowOtherScripts) != 0)
  4311. return false;
  4312. if(part == null)
  4313. return true;
  4314. if(part.GroupID == ldata.GroupID && (landflags & (uint)ParcelFlags.AllowGroupScripts) != 0)
  4315. return false;
  4316. return true;
  4317. }
  4318. private bool ScriptDanger(SceneObjectPart part, Vector3 pos)
  4319. {
  4320. if (part == null)
  4321. return false;
  4322. ILandObject parcel = LandChannel.GetLandObject(pos.X, pos.Y);
  4323. if (parcel != null)
  4324. {
  4325. if ((parcel.LandData.Flags & (uint)ParcelFlags.AllowOtherScripts) != 0)
  4326. return true;
  4327. if ((part.OwnerID == parcel.LandData.OwnerID) || Permissions.IsGod(part.OwnerID))
  4328. return true;
  4329. if (((parcel.LandData.Flags & (uint)ParcelFlags.AllowGroupScripts) != 0)
  4330. && (parcel.LandData.GroupID != UUID.Zero) && (parcel.LandData.GroupID == part.GroupID))
  4331. return true;
  4332. }
  4333. else
  4334. {
  4335. if (pos.X > 0f && pos.X < RegionInfo.RegionSizeX && pos.Y > 0f && pos.Y < RegionInfo.RegionSizeY)
  4336. return true;
  4337. }
  4338. return false;
  4339. }
  4340. public bool PipeEventsForScript(uint localID)
  4341. {
  4342. SceneObjectPart part = GetSceneObjectPart(localID);
  4343. if (part != null)
  4344. {
  4345. SceneObjectPart parent = part.ParentGroup.RootPart;
  4346. return ScriptDanger(parent, parent.GetWorldPosition());
  4347. }
  4348. else
  4349. {
  4350. return false;
  4351. }
  4352. }
  4353. #endregion
  4354. #region SceneGraph wrapper methods
  4355. public void SwapRootAgentCount(bool rootChildChildRootTF)
  4356. {
  4357. m_sceneGraph.SwapRootChildAgent(rootChildChildRootTF);
  4358. }
  4359. public void AddPhysicalPrim(int num)
  4360. {
  4361. m_sceneGraph.AddPhysicalPrim(num);
  4362. }
  4363. public void RemovePhysicalPrim(int num)
  4364. {
  4365. m_sceneGraph.RemovePhysicalPrim(num);
  4366. }
  4367. public int GetRootAgentCount()
  4368. {
  4369. return m_sceneGraph.GetRootAgentCount();
  4370. }
  4371. public int GetChildAgentCount()
  4372. {
  4373. return m_sceneGraph.GetChildAgentCount();
  4374. }
  4375. /// <summary>
  4376. /// Request a scene presence by UUID. Fast, indexed lookup.
  4377. /// </summary>
  4378. /// <param name="agentID"></param>
  4379. /// <returns>null if the presence was not found</returns>
  4380. public ScenePresence GetScenePresence(UUID agentID)
  4381. {
  4382. return m_sceneGraph.GetScenePresence(agentID);
  4383. }
  4384. /// <summary>
  4385. /// Request the scene presence by name.
  4386. /// </summary>
  4387. /// <param name="firstName"></param>
  4388. /// <param name="lastName"></param>
  4389. /// <returns>null if the presence was not found</returns>
  4390. public ScenePresence GetScenePresence(string firstName, string lastName)
  4391. {
  4392. return m_sceneGraph.GetScenePresence(firstName, lastName);
  4393. }
  4394. /// <summary>
  4395. /// Request the scene presence by localID.
  4396. /// </summary>
  4397. /// <param name="localID"></param>
  4398. /// <returns>null if the presence was not found</returns>
  4399. public ScenePresence GetScenePresence(uint localID)
  4400. {
  4401. return m_sceneGraph.GetScenePresence(localID);
  4402. }
  4403. /// <summary>
  4404. /// Gets all the scene presences in this scene.
  4405. /// </summary>
  4406. /// <remarks>
  4407. /// This method will return both root and child scene presences.
  4408. ///
  4409. /// Consider using ForEachScenePresence() or ForEachRootScenePresence() if possible since these will not
  4410. /// involving creating a new List object.
  4411. /// </remarks>
  4412. /// <returns>
  4413. /// A list of the scene presences. Adding or removing from the list will not affect the presences in the scene.
  4414. /// </returns>
  4415. public List<ScenePresence> GetScenePresences()
  4416. {
  4417. return new List<ScenePresence>(m_sceneGraph.GetScenePresences());
  4418. }
  4419. /// <summary>
  4420. /// Performs action on all avatars in the scene (root scene presences)
  4421. /// Avatars may be an NPC or a 'real' client.
  4422. /// </summary>
  4423. /// <param name="action"></param>
  4424. public void ForEachRootScenePresence(Action<ScenePresence> action)
  4425. {
  4426. m_sceneGraph.ForEachRootScenePresence(action);
  4427. }
  4428. /// <summary>
  4429. /// Performs action on all scene presences (root and child)
  4430. /// </summary>
  4431. /// <param name="action"></param>
  4432. public void ForEachScenePresence(Action<ScenePresence> action)
  4433. {
  4434. m_sceneGraph.ForEachScenePresence(action);
  4435. }
  4436. /// <summary>
  4437. /// Get all the scene object groups.
  4438. /// </summary>
  4439. /// <returns>
  4440. /// The scene object groups. If the scene is empty then an empty list is returned.
  4441. /// </returns>
  4442. public List<SceneObjectGroup> GetSceneObjectGroups()
  4443. {
  4444. return m_sceneGraph.GetSceneObjectGroups();
  4445. }
  4446. /// <summary>
  4447. /// Get a group via its UUID
  4448. /// </summary>
  4449. /// <param name="fullID"></param>
  4450. /// <returns>null if no group with that id exists</returns>
  4451. public SceneObjectGroup GetSceneObjectGroup(UUID fullID)
  4452. {
  4453. return m_sceneGraph.GetSceneObjectGroup(fullID);
  4454. }
  4455. /// <summary>
  4456. /// Get a group via its local ID
  4457. /// </summary>
  4458. /// <remarks>This will only return a group if the local ID matches a root part</remarks>
  4459. /// <param name="localID"></param>
  4460. /// <returns>null if no group with that id exists</returns>
  4461. public SceneObjectGroup GetSceneObjectGroup(uint localID)
  4462. {
  4463. return m_sceneGraph.GetSceneObjectGroup(localID);
  4464. }
  4465. /// <summary>
  4466. /// Get a group by name from the scene (will return the first
  4467. /// found, if there are more than one prim with the same name)
  4468. /// </summary>
  4469. /// <param name="name"></param>
  4470. /// <returns>null if no group with that name exists</returns>
  4471. public SceneObjectGroup GetSceneObjectGroup(string name)
  4472. {
  4473. return m_sceneGraph.GetSceneObjectGroup(name);
  4474. }
  4475. /// <summary>
  4476. /// Attempt to get the SOG via its UUID
  4477. /// </summary>
  4478. /// <param name="fullID"></param>
  4479. /// <param name="sog"></param>
  4480. /// <returns></returns>
  4481. public bool TryGetSceneObjectGroup(UUID fullID, out SceneObjectGroup sog)
  4482. {
  4483. sog = GetSceneObjectGroup(fullID);
  4484. return sog != null;
  4485. }
  4486. /// <summary>
  4487. /// Get a prim by name from the scene (will return the first
  4488. /// found, if there are more than one prim with the same name)
  4489. /// </summary>
  4490. /// <param name="name"></param>
  4491. /// <returns></returns>
  4492. public SceneObjectPart GetSceneObjectPart(string name)
  4493. {
  4494. return m_sceneGraph.GetSceneObjectPart(name);
  4495. }
  4496. /// <summary>
  4497. /// Get a prim via its local id
  4498. /// </summary>
  4499. /// <param name="localID"></param>
  4500. /// <returns></returns>
  4501. public SceneObjectPart GetSceneObjectPart(uint localID)
  4502. {
  4503. return m_sceneGraph.GetSceneObjectPart(localID);
  4504. }
  4505. /// <summary>
  4506. /// Get a prim via its UUID
  4507. /// </summary>
  4508. /// <param name="fullID"></param>
  4509. /// <returns></returns>
  4510. public SceneObjectPart GetSceneObjectPart(UUID fullID)
  4511. {
  4512. return m_sceneGraph.GetSceneObjectPart(fullID);
  4513. }
  4514. /// <summary>
  4515. /// Attempt to get a prim via its UUID
  4516. /// </summary>
  4517. /// <param name="fullID"></param>
  4518. /// <param name="sop"></param>
  4519. /// <returns></returns>
  4520. public bool TryGetSceneObjectPart(UUID fullID, out SceneObjectPart sop)
  4521. {
  4522. sop = GetSceneObjectPart(fullID);
  4523. return sop != null;
  4524. }
  4525. /// <summary>
  4526. /// Get a scene object group that contains the prim with the given local id
  4527. /// </summary>
  4528. /// <param name="localID"></param>
  4529. /// <returns>null if no scene object group containing that prim is found</returns>
  4530. public SceneObjectGroup GetGroupByPrim(uint localID)
  4531. {
  4532. return m_sceneGraph.GetGroupByPrim(localID);
  4533. }
  4534. /// <summary>
  4535. /// Get a scene object group that contains the prim with the given uuid
  4536. /// </summary>
  4537. /// <param name="fullID"></param>
  4538. /// <returns>null if no scene object group containing that prim is found</returns>
  4539. public SceneObjectGroup GetGroupByPrim(UUID fullID)
  4540. {
  4541. return m_sceneGraph.GetGroupByPrim(fullID);
  4542. }
  4543. public override bool TryGetScenePresence(UUID agentID, out ScenePresence sp)
  4544. {
  4545. return m_sceneGraph.TryGetScenePresence(agentID, out sp);
  4546. }
  4547. public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
  4548. {
  4549. return m_sceneGraph.TryGetAvatarByName(avatarName, out avatar);
  4550. }
  4551. /// <summary>
  4552. /// Perform an action on all clients with an avatar in this scene (root only)
  4553. /// </summary>
  4554. /// <param name="action"></param>
  4555. public void ForEachRootClient(Action<IClientAPI> action)
  4556. {
  4557. ForEachRootScenePresence(delegate(ScenePresence presence)
  4558. {
  4559. action(presence.ControllingClient);
  4560. });
  4561. }
  4562. /// <summary>
  4563. /// Perform an action on all clients connected to the region (root and child)
  4564. /// </summary>
  4565. /// <param name="action"></param>
  4566. public void ForEachClient(Action<IClientAPI> action)
  4567. {
  4568. m_clientManager.ForEach(action);
  4569. }
  4570. public int GetNumberOfClients()
  4571. {
  4572. return m_clientManager.Count;
  4573. }
  4574. public bool TryGetClient(UUID avatarID, out IClientAPI client)
  4575. {
  4576. return m_clientManager.TryGetValue(avatarID, out client);
  4577. }
  4578. public bool TryGetClient(System.Net.IPEndPoint remoteEndPoint, out IClientAPI client)
  4579. {
  4580. return m_clientManager.TryGetValue(remoteEndPoint, out client);
  4581. }
  4582. public void ForEachSOG(Action<SceneObjectGroup> action)
  4583. {
  4584. m_sceneGraph.ForEachSOG(action);
  4585. }
  4586. /// <summary>
  4587. /// Returns a list of the entities in the scene. This is a new list so operations perform on the list itself
  4588. /// will not affect the original list of objects in the scene.
  4589. /// </summary>
  4590. /// <returns></returns>
  4591. public EntityBase[] GetEntities()
  4592. {
  4593. return m_sceneGraph.GetEntities();
  4594. }
  4595. #endregion
  4596. // Commented pending deletion since this method no longer appears to do anything at all
  4597. // public bool NeedSceneCacheClear(UUID agentID)
  4598. // {
  4599. // IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  4600. // if (inv == null)
  4601. // return true;
  4602. //
  4603. // return inv.NeedSceneCacheClear(agentID, this);
  4604. // }
  4605. public void CleanTempObjects()
  4606. {
  4607. DateTime now = DateTime.UtcNow;
  4608. EntityBase[] entities = GetEntities();
  4609. foreach (EntityBase obj in entities)
  4610. {
  4611. if (obj is SceneObjectGroup)
  4612. {
  4613. SceneObjectGroup grp = (SceneObjectGroup)obj;
  4614. if (!grp.IsDeleted)
  4615. {
  4616. if ((grp.RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
  4617. {
  4618. if (grp.GetSittingAvatarsCount() == 0 && grp.RootPart.Expires <= now)
  4619. DeleteSceneObject(grp, false);
  4620. }
  4621. }
  4622. }
  4623. }
  4624. }
  4625. public void DeleteFromStorage(UUID uuid)
  4626. {
  4627. SimulationDataService.RemoveObject(uuid, RegionInfo.RegionID);
  4628. }
  4629. public int GetHealth(out int flags, out string message)
  4630. {
  4631. // Returns:
  4632. // 1 = sim is up and accepting http requests. The heartbeat has
  4633. // stopped and the sim is probably locked up, but a remote
  4634. // admin restart may succeed
  4635. //
  4636. // 2 = Sim is up and the heartbeat is running. The sim is likely
  4637. // usable for people within
  4638. //
  4639. // 3 = Sim is up and one packet thread is running. Sim is
  4640. // unstable and will not accept new logins
  4641. //
  4642. // 4 = Sim is up and both packet threads are running. Sim is
  4643. // likely usable
  4644. //
  4645. // 5 = We have seen a new user enter within the past 4 minutes
  4646. // which can be seen as positive confirmation of sim health
  4647. //
  4648. int health = 1; // Start at 1, means we're up
  4649. flags = 0;
  4650. message = String.Empty;
  4651. CheckHeartbeat();
  4652. if (m_firstHeartbeat || (m_lastIncoming == 0 && m_lastOutgoing == 0))
  4653. {
  4654. // We're still starting
  4655. // 0 means "in startup", it can't happen another way, since
  4656. // to get here, we must be able to accept http connections
  4657. return 0;
  4658. }
  4659. if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) < 2000)
  4660. {
  4661. health+=1;
  4662. flags |= 1;
  4663. }
  4664. if (Util.EnvironmentTickCountSubtract(m_lastIncoming) < 2000)
  4665. {
  4666. health+=1;
  4667. flags |= 2;
  4668. }
  4669. if (Util.EnvironmentTickCountSubtract(m_lastOutgoing) < 2000)
  4670. {
  4671. health+=1;
  4672. flags |= 4;
  4673. }
  4674. /*
  4675. else
  4676. {
  4677. int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
  4678. System.Diagnostics.Process proc = new System.Diagnostics.Process();
  4679. proc.EnableRaisingEvents=false;
  4680. proc.StartInfo.FileName = "/bin/kill";
  4681. proc.StartInfo.Arguments = "-QUIT " + pid.ToString();
  4682. proc.Start();
  4683. proc.WaitForExit();
  4684. Thread.Sleep(1000);
  4685. Environment.Exit(1);
  4686. }
  4687. */
  4688. if (flags != 7)
  4689. return health;
  4690. // A login in the last 4 mins? We can't be doing too badly
  4691. //
  4692. if (Util.EnvironmentTickCountSubtract(m_LastLogin) < 240000)
  4693. health++;
  4694. else
  4695. return health;
  4696. return health;
  4697. }
  4698. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  4699. // update non-physical objects like the joint proxy objects that represent the position
  4700. // of the joints in the scene.
  4701. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  4702. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  4703. // from within the OdePhysicsScene.
  4704. protected internal void jointMoved(PhysicsJoint joint)
  4705. {
  4706. // m_parentScene.PhysicsScene.DumpJointInfo(); // non-thread-locked version; we should already be in a lock (OdeLock) when this callback is invoked
  4707. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  4708. if (jointProxyObject == null)
  4709. {
  4710. jointErrorMessage(joint, "WARNING, joint proxy not found, name " + joint.ObjectNameInScene);
  4711. return;
  4712. }
  4713. // now update the joint proxy object in the scene to have the position of the joint as returned by the physics engine
  4714. SceneObjectPart trackedBody = GetSceneObjectPart(joint.TrackedBodyName); // FIXME: causes a sequential lookup
  4715. if (trackedBody == null) return; // the actor may have been deleted but the joint still lingers around a few frames waiting for deletion. during this time, trackedBody is NULL to prevent further motion of the joint proxy.
  4716. jointProxyObject.Velocity = trackedBody.Velocity;
  4717. jointProxyObject.AngularVelocity = trackedBody.AngularVelocity;
  4718. switch (joint.Type)
  4719. {
  4720. case PhysicsJointType.Ball:
  4721. {
  4722. Vector3 jointAnchor = PhysicsScene.GetJointAnchor(joint);
  4723. Vector3 proxyPos = jointAnchor;
  4724. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  4725. }
  4726. break;
  4727. case PhysicsJointType.Hinge:
  4728. {
  4729. Vector3 jointAnchor = PhysicsScene.GetJointAnchor(joint);
  4730. // Normally, we would just ask the physics scene to return the axis for the joint.
  4731. // Unfortunately, ODE sometimes returns <0,0,0> for the joint axis, which should
  4732. // never occur. Therefore we cannot rely on ODE to always return a correct joint axis.
  4733. // Therefore the following call does not always work:
  4734. //PhysicsVector phyJointAxis = _PhyScene.GetJointAxis(joint);
  4735. // instead we compute the joint orientation by saving the original joint orientation
  4736. // relative to one of the jointed bodies, and applying this transformation
  4737. // to the current position of the jointed bodies (the tracked body) to compute the
  4738. // current joint orientation.
  4739. if (joint.TrackedBodyName == null)
  4740. {
  4741. jointErrorMessage(joint, "joint.TrackedBodyName is null, joint " + joint.ObjectNameInScene);
  4742. }
  4743. Vector3 proxyPos = jointAnchor;
  4744. Quaternion q = trackedBody.RotationOffset * joint.LocalRotation;
  4745. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  4746. jointProxyObject.ParentGroup.UpdateGroupRotationR(q); // schedules the entire group for a terse update
  4747. }
  4748. break;
  4749. }
  4750. }
  4751. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  4752. // update non-physical objects like the joint proxy objects that represent the position
  4753. // of the joints in the scene.
  4754. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  4755. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  4756. // from within the OdePhysicsScene.
  4757. protected internal void jointDeactivated(PhysicsJoint joint)
  4758. {
  4759. //m_log.Debug("[NINJA] SceneGraph.jointDeactivated, joint:" + joint.ObjectNameInScene);
  4760. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  4761. if (jointProxyObject == null)
  4762. {
  4763. jointErrorMessage(joint, "WARNING, trying to deactivate (stop interpolation of) joint proxy, but not found, name " + joint.ObjectNameInScene);
  4764. return;
  4765. }
  4766. // turn the proxy non-physical, which also stops its client-side interpolation
  4767. bool wasUsingPhysics = ((jointProxyObject.Flags & PrimFlags.Physics) != 0);
  4768. if (wasUsingPhysics)
  4769. {
  4770. jointProxyObject.UpdatePrimFlags(false, false, true, false,false); // FIXME: possible deadlock here; check to make sure all the scene alterations set into motion here won't deadlock
  4771. }
  4772. }
  4773. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  4774. // alert the user of errors by using the debug channel in the same way that scripts alert
  4775. // the user of compile errors.
  4776. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  4777. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  4778. // from within the OdePhysicsScene.
  4779. public void jointErrorMessage(PhysicsJoint joint, string message)
  4780. {
  4781. if (joint != null)
  4782. {
  4783. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  4784. return;
  4785. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  4786. if (jointProxyObject != null)
  4787. {
  4788. SimChat(Utils.StringToBytes("[NINJA]: " + message),
  4789. ChatTypeEnum.DebugChannel,
  4790. 2147483647,
  4791. jointProxyObject.AbsolutePosition,
  4792. jointProxyObject.Name,
  4793. jointProxyObject.UUID,
  4794. false);
  4795. joint.ErrorMessageCount++;
  4796. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  4797. {
  4798. SimChat(Utils.StringToBytes("[NINJA]: Too many messages for this joint, suppressing further messages."),
  4799. ChatTypeEnum.DebugChannel,
  4800. 2147483647,
  4801. jointProxyObject.AbsolutePosition,
  4802. jointProxyObject.Name,
  4803. jointProxyObject.UUID,
  4804. false);
  4805. }
  4806. }
  4807. else
  4808. {
  4809. // couldn't find the joint proxy object; the error message is silently suppressed
  4810. }
  4811. }
  4812. }
  4813. public Scene ConsoleScene()
  4814. {
  4815. if (MainConsole.Instance == null)
  4816. return null;
  4817. if (MainConsole.Instance.ConsoleScene is Scene)
  4818. return (Scene)MainConsole.Instance.ConsoleScene;
  4819. return null;
  4820. }
  4821. // Get terrain height at the specified <x,y> location.
  4822. // Presumes the underlying implementation is a heightmap which is a 1m grid.
  4823. // Finds heightmap grid points before and after the point and
  4824. // does a linear approximation of the height at this intermediate point.
  4825. public float GetGroundHeight(float x, float y)
  4826. {
  4827. if (x < 0)
  4828. x = 0;
  4829. if (x >= Heightmap.Width)
  4830. x = Heightmap.Width - 1;
  4831. if (y < 0)
  4832. y = 0;
  4833. if (y >= Heightmap.Height)
  4834. y = Heightmap.Height - 1;
  4835. Vector3 p0 = new Vector3(x, y, (float)Heightmap[(int)x, (int)y]);
  4836. Vector3 p1 = p0;
  4837. Vector3 p2 = p0;
  4838. p1.X += 1.0f;
  4839. if (p1.X < Heightmap.Width)
  4840. p1.Z = (float)Heightmap[(int)p1.X, (int)p1.Y];
  4841. p2.Y += 1.0f;
  4842. if (p2.Y < Heightmap.Height)
  4843. p2.Z = (float)Heightmap[(int)p2.X, (int)p2.Y];
  4844. Vector3 v0 = new Vector3(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);
  4845. Vector3 v1 = new Vector3(p2.X - p0.X, p2.Y - p0.Y, p2.Z - p0.Z);
  4846. v0.Normalize();
  4847. v1.Normalize();
  4848. Vector3 vsn = new Vector3();
  4849. vsn.X = (v0.Y * v1.Z) - (v0.Z * v1.Y);
  4850. vsn.Y = (v0.Z * v1.X) - (v0.X * v1.Z);
  4851. vsn.Z = (v0.X * v1.Y) - (v0.Y * v1.X);
  4852. vsn.Normalize();
  4853. float xdiff = x - (float)((int)x);
  4854. float ydiff = y - (float)((int)y);
  4855. return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + p0.Z;
  4856. }
  4857. private void CheckHeartbeat()
  4858. {
  4859. if (m_firstHeartbeat)
  4860. return;
  4861. if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) > 5000)
  4862. Start();
  4863. }
  4864. public override ISceneObject DeserializeObject(string representation)
  4865. {
  4866. return SceneObjectSerializer.FromXml2Format(representation);
  4867. }
  4868. public override bool AllowScriptCrossings
  4869. {
  4870. get { return m_allowScriptCrossings; }
  4871. }
  4872. public Vector3 GetNearestAllowedPosition(ScenePresence avatar)
  4873. {
  4874. return GetNearestAllowedPosition(avatar, null);
  4875. }
  4876. public Vector3 GetNearestAllowedPosition(ScenePresence avatar, ILandObject excludeParcel)
  4877. {
  4878. Vector3 pos = avatar.AbsolutePosition;
  4879. ILandObject nearestParcel = GetNearestAllowedParcel(avatar.UUID, pos.X, pos.Y, excludeParcel);
  4880. if (nearestParcel != null)
  4881. {
  4882. Vector2? nearestPoint = null;
  4883. Vector3 dir = -avatar.Velocity;
  4884. float dirlen = dir.Length();
  4885. if(dirlen > 1.0f)
  4886. //Try to get a location that feels like where they came from
  4887. nearestPoint = nearestParcel.GetNearestPointAlongDirection(pos, dir);
  4888. if (nearestPoint == null)
  4889. nearestPoint = nearestParcel.GetNearestPoint(pos);
  4890. if (nearestPoint != null)
  4891. {
  4892. return GetPositionAtAvatarHeightOrGroundHeight(avatar,
  4893. nearestPoint.Value.X, nearestPoint.Value.Y);
  4894. }
  4895. ILandObject dest = LandChannel.GetLandObject(avatar.lastKnownAllowedPosition.X, avatar.lastKnownAllowedPosition.Y);
  4896. if (dest != excludeParcel)
  4897. {
  4898. // Ultimate backup if we have no idea where they are and
  4899. // the last allowed position was in another parcel
  4900. m_log.Debug("Have no idea where they are, sending them to: " + avatar.lastKnownAllowedPosition.ToString());
  4901. return avatar.lastKnownAllowedPosition;
  4902. }
  4903. // else fall through to region edge
  4904. }
  4905. //Go to the edge, this happens in teleporting to a region with no available parcels
  4906. Vector3 nearestRegionEdgePoint = GetNearestRegionEdgePosition(avatar);
  4907. //Debug.WriteLine("They are really in a place they don't belong, sending them to: " + nearestRegionEdgePoint.ToString());
  4908. return nearestRegionEdgePoint;
  4909. }
  4910. private Vector3 GetParcelCenterAtGround(ILandObject parcel)
  4911. {
  4912. Vector2 center = parcel.CenterPoint;
  4913. return GetPositionAtGround(center.X, center.Y);
  4914. }
  4915. public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y)
  4916. {
  4917. return GetNearestAllowedParcel(avatarId, x, y, null);
  4918. }
  4919. public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y, ILandObject excludeParcel)
  4920. {
  4921. if(LandChannel == null)
  4922. return null;
  4923. List<ILandObject> all = LandChannel.AllParcels();
  4924. if(all == null || all.Count == 0)
  4925. return null;
  4926. float minParcelDistanceSQ = float.MaxValue;
  4927. ILandObject nearestParcel = null;
  4928. Vector2 curCenter;
  4929. float parcelDistanceSQ;
  4930. foreach (var parcel in all)
  4931. {
  4932. if (parcel != excludeParcel && !parcel.IsEitherBannedOrRestricted(avatarId))
  4933. {
  4934. curCenter = parcel.CenterPoint;
  4935. curCenter.X -= x;
  4936. curCenter.Y -= y;
  4937. parcelDistanceSQ = curCenter.LengthSquared();
  4938. if (parcelDistanceSQ < minParcelDistanceSQ)
  4939. {
  4940. minParcelDistanceSQ = parcelDistanceSQ;
  4941. nearestParcel = parcel;
  4942. }
  4943. }
  4944. }
  4945. return nearestParcel;
  4946. }
  4947. private Vector2 GetParcelSafeCorner(ILandObject parcel)
  4948. {
  4949. Vector2 place = parcel.StartPoint;
  4950. place.X += 2f;
  4951. place.Y += 2f;
  4952. return place;
  4953. }
  4954. private Vector3 GetNearestRegionEdgePosition(ScenePresence avatar)
  4955. {
  4956. float posX = avatar.AbsolutePosition.X;
  4957. float posY = avatar.AbsolutePosition.Y;
  4958. float regionSizeX = RegionInfo.RegionSizeX;
  4959. float halfRegionSizeX = regionSizeX * 0.5f;
  4960. float regionSizeY = RegionInfo.RegionSizeY;
  4961. float halfRegionSizeY = regionSizeY * 0.5f;
  4962. float xdistance = posX < halfRegionSizeX ? posX : regionSizeX - posX;
  4963. float ydistance = posY < halfRegionSizeY ? posY : regionSizeY - posY;
  4964. //find out what vertical edge to go to
  4965. if (xdistance < ydistance)
  4966. {
  4967. if (posX < halfRegionSizeX)
  4968. return GetPositionAtAvatarHeightOrGroundHeight(avatar, 0.5f, posY);
  4969. else
  4970. return GetPositionAtAvatarHeightOrGroundHeight(avatar, regionSizeX - 0.5f, posY);
  4971. }
  4972. //find out what horizontal edge to go to
  4973. else
  4974. {
  4975. if (posY < halfRegionSizeY)
  4976. return GetPositionAtAvatarHeightOrGroundHeight(avatar, posX, 0.5f);
  4977. else
  4978. return GetPositionAtAvatarHeightOrGroundHeight(avatar, posX, regionSizeY - 0.5f);
  4979. }
  4980. }
  4981. private Vector3 GetPositionAtAvatarHeightOrGroundHeight(ScenePresence avatar, float x, float y)
  4982. {
  4983. Vector3 ground = GetPositionAtGround(x, y);
  4984. if(avatar.Appearance != null)
  4985. ground.Z += avatar.Appearance.AvatarHeight * 0.5f;
  4986. else
  4987. ground.Z += 0.8f;
  4988. if (avatar.AbsolutePosition.Z > ground.Z)
  4989. {
  4990. ground.Z = avatar.AbsolutePosition.Z;
  4991. }
  4992. return ground;
  4993. }
  4994. private Vector3 GetPositionAtGround(float x, float y)
  4995. {
  4996. return new Vector3(x, y, GetGroundHeight(x, y));
  4997. }
  4998. public List<UUID> GetEstateRegions(int estateID)
  4999. {
  5000. IEstateDataService estateDataService = EstateDataService;
  5001. if (estateDataService == null)
  5002. return new List<UUID>(0);
  5003. return estateDataService.GetRegions(estateID);
  5004. }
  5005. public void ReloadEstateData()
  5006. {
  5007. IEstateDataService estateDataService = EstateDataService;
  5008. if (estateDataService != null)
  5009. {
  5010. RegionInfo.EstateSettings = estateDataService.LoadEstateSettings(RegionInfo.RegionID, false);
  5011. TriggerEstateSunUpdate();
  5012. }
  5013. }
  5014. public void TriggerEstateSunUpdate()
  5015. {
  5016. EventManager.TriggerEstateToolsSunUpdate(RegionInfo.RegionHandle);
  5017. }
  5018. private void HandleReloadEstate(string module, string[] cmd)
  5019. {
  5020. if (MainConsole.Instance.ConsoleScene == null ||
  5021. (MainConsole.Instance.ConsoleScene is Scene &&
  5022. (Scene)MainConsole.Instance.ConsoleScene == this))
  5023. {
  5024. ReloadEstateData();
  5025. }
  5026. }
  5027. /// <summary>
  5028. /// Get the volume of space that will encompass all the given objects.
  5029. /// </summary>
  5030. /// <param name="objects"></param>
  5031. /// <param name="minX"></param>
  5032. /// <param name="maxX"></param>
  5033. /// <param name="minY"></param>
  5034. /// <param name="maxY"></param>
  5035. /// <param name="minZ"></param>
  5036. /// <param name="maxZ"></param>
  5037. /// <returns></returns>
  5038. public static Vector3[] GetCombinedBoundingBox(
  5039. List<SceneObjectGroup> objects,
  5040. out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ)
  5041. {
  5042. minX = float.MaxValue;
  5043. maxX = float.MinValue;
  5044. minY = float.MaxValue;
  5045. maxY = float.MinValue;
  5046. minZ = float.MaxValue;
  5047. maxZ = float.MinValue;
  5048. List<Vector3> offsets = new List<Vector3>();
  5049. foreach (SceneObjectGroup g in objects)
  5050. {
  5051. float ominX, ominY, ominZ, omaxX, omaxY, omaxZ;
  5052. Vector3 vec = g.AbsolutePosition;
  5053. g.GetAxisAlignedBoundingBoxRaw(out ominX, out omaxX, out ominY, out omaxY, out ominZ, out omaxZ);
  5054. // m_log.DebugFormat(
  5055. // "[SCENE]: For {0} found AxisAlignedBoundingBoxRaw {1}, {2}",
  5056. // g.Name, new Vector3(ominX, ominY, ominZ), new Vector3(omaxX, omaxY, omaxZ));
  5057. ominX += vec.X;
  5058. omaxX += vec.X;
  5059. ominY += vec.Y;
  5060. omaxY += vec.Y;
  5061. ominZ += vec.Z;
  5062. omaxZ += vec.Z;
  5063. if (minX > ominX)
  5064. minX = ominX;
  5065. if (minY > ominY)
  5066. minY = ominY;
  5067. if (minZ > ominZ)
  5068. minZ = ominZ;
  5069. if (maxX < omaxX)
  5070. maxX = omaxX;
  5071. if (maxY < omaxY)
  5072. maxY = omaxY;
  5073. if (maxZ < omaxZ)
  5074. maxZ = omaxZ;
  5075. }
  5076. foreach (SceneObjectGroup g in objects)
  5077. {
  5078. Vector3 vec = g.AbsolutePosition;
  5079. vec.X -= minX;
  5080. vec.Y -= minY;
  5081. vec.Z -= minZ;
  5082. offsets.Add(vec);
  5083. }
  5084. return offsets.ToArray();
  5085. }
  5086. /// <summary>
  5087. /// Regenerate the maptile for this scene.
  5088. /// </summary>
  5089. /// <param name="sender"></param>
  5090. /// <param name="e"></param>
  5091. private void RegenerateMaptile()
  5092. {
  5093. IWorldMapModule mapModule = RequestModuleInterface<IWorldMapModule>();
  5094. if (mapModule != null)
  5095. mapModule.GenerateMaptile();
  5096. }
  5097. // public void CleanDroppedAttachments()
  5098. // {
  5099. // List<SceneObjectGroup> objectsToDelete =
  5100. // new List<SceneObjectGroup>();
  5101. //
  5102. // lock (m_cleaningAttachments)
  5103. // {
  5104. // ForEachSOG(delegate (SceneObjectGroup grp)
  5105. // {
  5106. // if (grp.RootPart.Shape.PCode == 0 && grp.RootPart.Shape.State != 0 && (!objectsToDelete.Contains(grp)))
  5107. // {
  5108. // UUID agentID = grp.OwnerID;
  5109. // if (agentID == UUID.Zero)
  5110. // {
  5111. // objectsToDelete.Add(grp);
  5112. // return;
  5113. // }
  5114. //
  5115. // ScenePresence sp = GetScenePresence(agentID);
  5116. // if (sp == null)
  5117. // {
  5118. // objectsToDelete.Add(grp);
  5119. // return;
  5120. // }
  5121. // }
  5122. // });
  5123. // }
  5124. //
  5125. // foreach (SceneObjectGroup grp in objectsToDelete)
  5126. // {
  5127. // m_log.InfoFormat("[SCENE]: Deleting dropped attachment {0} of user {1}", grp.UUID, grp.OwnerID);
  5128. // DeleteSceneObject(grp, true);
  5129. // }
  5130. // }
  5131. public void ThreadAlive(int threadCode)
  5132. {
  5133. switch(threadCode)
  5134. {
  5135. case 1: // Incoming
  5136. m_lastIncoming = Util.EnvironmentTickCount();
  5137. break;
  5138. case 2: // Incoming
  5139. m_lastOutgoing = Util.EnvironmentTickCount();
  5140. break;
  5141. }
  5142. }
  5143. public void RegenerateMaptileAndReregister(object sender, ElapsedEventArgs e)
  5144. {
  5145. RegenerateMaptile();
  5146. GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
  5147. GC.Collect();
  5148. GC.WaitForPendingFinalizers();
  5149. GC.Collect();
  5150. GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.Default;
  5151. // We need to propagate the new image UUID to the grid service
  5152. // so that all simulators can retrieve it
  5153. string error = GridService.RegisterRegion(RegionInfo.ScopeID, new GridRegion(RegionInfo));
  5154. if (error != string.Empty)
  5155. throw new Exception(error);
  5156. if(m_generateMaptiles)
  5157. m_mapGenerationTimer.Start();
  5158. }
  5159. /// <summary>
  5160. /// This method is called across the simulation connector to
  5161. /// determine if a given agent is allowed in this region
  5162. /// AS A ROOT AGENT
  5163. /// </summary>
  5164. /// <remarks>
  5165. /// Returning false here will prevent them
  5166. /// from logging into the region, teleporting into the region
  5167. /// or corssing the broder walking, but will NOT prevent
  5168. /// child agent creation, thereby emulating the SL behavior.
  5169. /// </remarks>
  5170. /// <param name='agentID'>The visitor's User ID</param>
  5171. /// <param name="agentHomeURI">The visitor's Home URI (may be null)</param>
  5172. /// <param name='position'></param>
  5173. /// <param name='reason'></param>
  5174. /// <returns></returns>
  5175. public bool QueryAccess(UUID agentID, string agentHomeURI, bool viaTeleport, Vector3 position, List<UUID> features, out string reason)
  5176. {
  5177. reason = string.Empty;
  5178. if (Permissions.IsGod(agentID))
  5179. return true;
  5180. if (!AllowAvatarCrossing && !viaTeleport)
  5181. {
  5182. reason = "Region Crossing not allowed";
  5183. return false;
  5184. }
  5185. bool isAdmin = Permissions.IsAdministrator(agentID);
  5186. bool isManager = Permissions.IsEstateManager(agentID);
  5187. // FIXME: Root agent count is currently known to be inaccurate. This forces a recount before we check.
  5188. // However, the long term fix is to make sure root agent count is always accurate.
  5189. m_sceneGraph.RecalculateStats();
  5190. int num = m_sceneGraph.GetRootAgentCount();
  5191. if (num >= RegionInfo.RegionSettings.AgentLimit)
  5192. {
  5193. if (!(isAdmin || isManager))
  5194. {
  5195. reason = "The region is full";
  5196. m_log.DebugFormat(
  5197. "[SCENE]: Denying presence with id {0} entry into {1} since region is at agent limit of {2}",
  5198. agentID, RegionInfo.RegionName, RegionInfo.RegionSettings.AgentLimit);
  5199. return false;
  5200. }
  5201. }
  5202. ScenePresence presence = GetScenePresence(agentID);
  5203. IClientAPI client = null;
  5204. AgentCircuitData aCircuit = null;
  5205. if (presence != null)
  5206. {
  5207. client = presence.ControllingClient;
  5208. if (client != null)
  5209. aCircuit = client.RequestClientInfo();
  5210. }
  5211. // We may be called before there is a presence or a client.
  5212. // Fake AgentCircuitData to keep IAuthorizationModule smiling
  5213. if (client == null)
  5214. {
  5215. aCircuit = new AgentCircuitData();
  5216. aCircuit.AgentID = agentID;
  5217. aCircuit.firstname = String.Empty;
  5218. aCircuit.lastname = String.Empty;
  5219. }
  5220. try
  5221. {
  5222. if (!AuthorizeUser(aCircuit, false, out reason))
  5223. {
  5224. //m_log.DebugFormat("[SCENE]: Denying access for {0}", agentID);
  5225. // reason = "Region authorization fail";
  5226. return false;
  5227. }
  5228. }
  5229. catch (Exception e)
  5230. {
  5231. m_log.DebugFormat("[SCENE]: Exception authorizing agent: {0} " + e.StackTrace, e.Message);
  5232. reason = "Error authorizing agent: " + e.Message;
  5233. return false;
  5234. }
  5235. // last check aditional land access restrictions and relocations
  5236. // if crossing (viaTeleport false) check only the specified parcel
  5237. return CheckLandPositionAccess(agentID, viaTeleport, true, position, out reason);
  5238. }
  5239. // check access to land.
  5240. public bool CheckLandPositionAccess(UUID agentID, bool NotCrossing, bool checkTeleHub, Vector3 position, out string reason)
  5241. {
  5242. reason = string.Empty;
  5243. if (Permissions.IsGod(agentID))
  5244. return true;
  5245. // Permissions.IsAdministrator is the same as IsGod for now
  5246. // bool isAdmin = Permissions.IsAdministrator(agentID);
  5247. // if(isAdmin)
  5248. // return true;
  5249. // also honor estate managers access rights
  5250. bool isManager = Permissions.IsEstateManager(agentID);
  5251. if(isManager)
  5252. return true;
  5253. if (NotCrossing)
  5254. {
  5255. if (!RegionInfo.EstateSettings.AllowDirectTeleport)
  5256. {
  5257. SceneObjectGroup telehub;
  5258. if (RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = GetSceneObjectGroup (RegionInfo.RegionSettings.TelehubObject)) != null && checkTeleHub)
  5259. {
  5260. bool banned = true;
  5261. bool validTelehub = false;
  5262. List<SpawnPoint> spawnPoints = RegionInfo.RegionSettings.SpawnPoints();
  5263. Vector3 spawnPoint;
  5264. ILandObject land = null;
  5265. Vector3 telehubPosition = telehub.AbsolutePosition;
  5266. if(spawnPoints.Count == 0)
  5267. {
  5268. // will this ever happen?
  5269. // if so use the telehub object position
  5270. spawnPoint = telehubPosition;
  5271. land = LandChannel.GetLandObject(spawnPoint.X, spawnPoint.Y);
  5272. if(land != null && !land.IsEitherBannedOrRestricted(agentID))
  5273. {
  5274. banned = false;
  5275. validTelehub = true;
  5276. }
  5277. }
  5278. else
  5279. {
  5280. Quaternion telehubRotation = telehub.GroupRotation;
  5281. foreach (SpawnPoint spawn in spawnPoints)
  5282. {
  5283. spawnPoint = spawn.GetLocation(telehubPosition, telehubRotation);
  5284. land = LandChannel.GetLandObject(spawnPoint.X, spawnPoint.Y);
  5285. if (land == null)
  5286. continue;
  5287. validTelehub = true;
  5288. if (!land.IsEitherBannedOrRestricted(agentID))
  5289. {
  5290. banned = false;
  5291. break;
  5292. }
  5293. }
  5294. }
  5295. if(validTelehub)
  5296. {
  5297. if (banned)
  5298. {
  5299. reason = "No suitable landing point found";
  5300. return false;
  5301. }
  5302. else
  5303. return true;
  5304. }
  5305. // possible broken telehub, fall into normal check
  5306. }
  5307. }
  5308. float posX = position.X;
  5309. float posY = position.Y;
  5310. // allow position relocation
  5311. if (!TestLandRestrictions(agentID, out reason, ref posX, ref posY))
  5312. {
  5313. // m_log.DebugFormat("[SCENE]: Denying {0} because they are banned on all parcels", agentID);
  5314. reason = "You dont have access to the region parcels";
  5315. return false;
  5316. }
  5317. }
  5318. else // check for query region crossing only
  5319. {
  5320. // no relocation allowed on crossings
  5321. ILandObject land = LandChannel.GetLandObject(position.X, position.Y);
  5322. if (land == null)
  5323. {
  5324. reason = "No parcel found";
  5325. return false;
  5326. }
  5327. bool banned = land.IsBannedFromLand(agentID);
  5328. bool restricted = land.IsRestrictedFromLand(agentID);
  5329. if (banned || restricted)
  5330. {
  5331. if (banned)
  5332. reason = "You are banned from the parcel";
  5333. else
  5334. reason = "The parcel is restricted";
  5335. return false;
  5336. }
  5337. }
  5338. return true;
  5339. }
  5340. public void StartTimerWatchdog()
  5341. {
  5342. m_timerWatchdog.Interval = 1000;
  5343. m_timerWatchdog.Elapsed += TimerWatchdog;
  5344. m_timerWatchdog.AutoReset = true;
  5345. m_timerWatchdog.Start();
  5346. }
  5347. public void TimerWatchdog(object sender, ElapsedEventArgs e)
  5348. {
  5349. CheckHeartbeat();
  5350. IEtcdModule etcd = RequestModuleInterface<IEtcdModule>();
  5351. int flags;
  5352. string message;
  5353. if (etcd != null)
  5354. {
  5355. int health = GetHealth(out flags, out message);
  5356. if (health != m_lastHealth)
  5357. {
  5358. m_lastHealth = health;
  5359. etcd.Store("Health", health.ToString(), 300000);
  5360. etcd.Store("HealthFlags", flags.ToString(), 300000);
  5361. }
  5362. int roots = 0;
  5363. foreach (ScenePresence sp in GetScenePresences())
  5364. if (!sp.IsChildAgent && !sp.IsNPC)
  5365. roots++;
  5366. if (m_lastUsers != roots)
  5367. {
  5368. m_lastUsers = roots;
  5369. etcd.Store("RootAgents", roots.ToString(), 300000);
  5370. }
  5371. }
  5372. }
  5373. /// This method deals with movement when an avatar is automatically moving (but this is distinct from the
  5374. /// autopilot that moves an avatar to a sit target!.
  5375. /// </summary>
  5376. /// <remarks>
  5377. /// This is not intended as a permament location for this method.
  5378. /// </remarks>
  5379. /// <param name="presence"></param>
  5380. /* move to target is now done on presence update
  5381. private void HandleOnSignificantClientMovement(ScenePresence presence)
  5382. {
  5383. if (presence.MovingToTarget)
  5384. {
  5385. double distanceToTarget = Util.GetDistanceTo(presence.AbsolutePosition, presence.MoveToPositionTarget);
  5386. // m_log.DebugFormat(
  5387. // "[SCENE]: Abs pos of {0} is {1}, target {2}, distance {3}",
  5388. // presence.Name, presence.AbsolutePosition, presence.MoveToPositionTarget, distanceToTarget);
  5389. // Check the error term of the current position in relation to the target position
  5390. if (distanceToTarget <= ScenePresence.SIGNIFICANT_MOVEMENT)
  5391. {
  5392. // We are close enough to the target
  5393. // m_log.DebugFormat("[SCENEE]: Stopping autopilot of {0}", presence.Name);
  5394. presence.Velocity = Vector3.Zero;
  5395. presence.AbsolutePosition = presence.MoveToPositionTarget;
  5396. presence.ResetMoveToTarget();
  5397. if (presence.Flying)
  5398. {
  5399. // A horrible hack to stop the avatar dead in its tracks rather than having them overshoot
  5400. // the target if flying.
  5401. // We really need to be more subtle (slow the avatar as it approaches the target) or at
  5402. // least be able to set collision status once, rather than 5 times to give it enough
  5403. // weighting so that that PhysicsActor thinks it really is colliding.
  5404. for (int i = 0; i < 5; i++)
  5405. presence.IsColliding = true;
  5406. if (presence.LandAtTarget)
  5407. presence.Flying = false;
  5408. // Vector3 targetPos = presence.MoveToPositionTarget;
  5409. // float terrainHeight = (float)presence.Scene.Heightmap[(int)targetPos.X, (int)targetPos.Y];
  5410. // if (targetPos.Z - terrainHeight < 0.2)
  5411. // {
  5412. // presence.Flying = false;
  5413. // }
  5414. }
  5415. // m_log.DebugFormat(
  5416. // "[SCENE]: AgentControlFlags {0}, MovementFlag {1} for {2}",
  5417. // presence.AgentControlFlags, presence.MovementFlag, presence.Name);
  5418. }
  5419. else
  5420. {
  5421. // m_log.DebugFormat(
  5422. // "[SCENE]: Updating npc {0} at {1} for next movement to {2}",
  5423. // presence.Name, presence.AbsolutePosition, presence.MoveToPositionTarget);
  5424. Vector3 agent_control_v3 = new Vector3();
  5425. presence.HandleMoveToTargetUpdate(1, ref agent_control_v3);
  5426. presence.AddNewMovement(agent_control_v3);
  5427. }
  5428. }
  5429. }
  5430. */
  5431. // manage and select spawn points in sequence
  5432. public int SpawnPoint()
  5433. {
  5434. int spawnpoints = RegionInfo.RegionSettings.SpawnPoints().Count;
  5435. if (spawnpoints == 0)
  5436. return 0;
  5437. m_SpawnPoint++;
  5438. if (m_SpawnPoint > spawnpoints)
  5439. m_SpawnPoint = 1;
  5440. return m_SpawnPoint - 1;
  5441. }
  5442. private void HandleGcCollect(string module, string[] args)
  5443. {
  5444. GC.Collect();
  5445. }
  5446. /// <summary>
  5447. /// Wrappers to get physics modules retrieve assets.
  5448. /// </summary>
  5449. /// <remarks>
  5450. /// Has to be done this way
  5451. /// because we can't assign the asset service to physics directly - at the
  5452. /// time physics are instantiated it's not registered but it will be by
  5453. /// the time the first prim exists.
  5454. /// </remarks>
  5455. /// <param name="assetID"></param>
  5456. /// <param name="callback"></param>
  5457. public void PhysicsRequestAsset(UUID assetID, AssetReceivedDelegate callback)
  5458. {
  5459. AssetService.Get(assetID.ToString(), callback, PhysicsAssetReceived);
  5460. }
  5461. private void PhysicsAssetReceived(string id, Object sender, AssetBase asset)
  5462. {
  5463. AssetReceivedDelegate callback = (AssetReceivedDelegate)sender;
  5464. callback(asset);
  5465. }
  5466. public string GetExtraSetting(string name)
  5467. {
  5468. if (m_extraSettings == null)
  5469. return String.Empty;
  5470. string val;
  5471. if (!m_extraSettings.TryGetValue(name, out val))
  5472. return String.Empty;
  5473. return val;
  5474. }
  5475. public void StoreExtraSetting(string name, string val)
  5476. {
  5477. if (m_extraSettings == null)
  5478. return;
  5479. string oldVal;
  5480. if (m_extraSettings.TryGetValue(name, out oldVal))
  5481. {
  5482. if (oldVal == val)
  5483. return;
  5484. }
  5485. m_extraSettings[name] = val;
  5486. m_SimulationDataService.SaveExtra(RegionInfo.RegionID, name, val);
  5487. m_eventManager.TriggerExtraSettingChanged(this, name, val);
  5488. }
  5489. public void RemoveExtraSetting(string name)
  5490. {
  5491. if (m_extraSettings == null)
  5492. return;
  5493. if (!m_extraSettings.ContainsKey(name))
  5494. return;
  5495. m_extraSettings.Remove(name);
  5496. m_SimulationDataService.RemoveExtra(RegionInfo.RegionID, name);
  5497. m_eventManager.TriggerExtraSettingChanged(this, name, String.Empty);
  5498. }
  5499. public bool InTeleportTargetsCoolDown(UUID sourceID, UUID targetID, double timeout)
  5500. {
  5501. lock(TeleportTargetsCoolDown)
  5502. {
  5503. UUID lastSource = UUID.Zero;
  5504. TeleportTargetsCoolDown.TryGetValue(targetID, out lastSource);
  5505. if(lastSource == UUID.Zero)
  5506. {
  5507. TeleportTargetsCoolDown.Add(targetID, sourceID, timeout);
  5508. return false;
  5509. }
  5510. TeleportTargetsCoolDown.AddOrUpdate(targetID, sourceID, timeout);
  5511. return lastSource == sourceID;
  5512. }
  5513. }
  5514. }
  5515. }