Scene.cs 236 KB

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