1
0

Scene.cs 246 KB

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