Scene.cs 259 KB

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