Scene.cs 189 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635
  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 OpenSim 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.Drawing;
  30. using System.Drawing.Imaging;
  31. using System.IO;
  32. using System.Xml;
  33. using System.Threading;
  34. using System.Timers;
  35. using OpenMetaverse;
  36. using OpenMetaverse.Imaging;
  37. using OpenMetaverse.Packets;
  38. using OpenSim.Framework;
  39. using OpenSim.Framework.Communications;
  40. using OpenSim.Framework.Communications.Cache;
  41. using OpenSim.Framework.Servers;
  42. using OpenSim.Region.Environment.Interfaces;
  43. using OpenSim.Region.Interfaces;
  44. using OpenSim.Region.Environment.Modules.World.Terrain;
  45. using OpenSim.Region.Environment.Scenes.Scripting;
  46. using OpenSim.Region.Physics.Manager;
  47. using Nini.Config;
  48. using Caps = OpenSim.Framework.Communications.Capabilities.Caps;
  49. using Image = System.Drawing.Image;
  50. using TPFlags = OpenSim.Framework.Constants.TeleportFlags;
  51. using Timer = System.Timers.Timer;
  52. using OSD = OpenMetaverse.StructuredData.OSD;
  53. namespace OpenSim.Region.Environment.Scenes
  54. {
  55. public delegate bool FilterAvatarList(ScenePresence avatar);
  56. public partial class Scene : SceneBase
  57. {
  58. public delegate void SynchronizeSceneHandler(Scene scene);
  59. public SynchronizeSceneHandler SynchronizeScene = null;
  60. public int splitID = 0;
  61. private const long DEFAULT_MIN_TIME_FOR_PERSISTENCE = 60L;
  62. private const long DEFAULT_MAX_TIME_FOR_PERSISTENCE = 600L;
  63. #region Fields
  64. protected Timer m_restartWaitTimer = new Timer();
  65. public SimStatsReporter StatsReporter;
  66. protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
  67. protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
  68. /// <value>
  69. /// The scene graph for this scene
  70. /// </value>
  71. /// TODO: Possibly stop other classes being able to manipulate this directly.
  72. public SceneGraph m_sceneGraph;
  73. private int m_timePhase = 24;
  74. /// <summary>
  75. /// Are we applying physics to any of the prims in this scene?
  76. /// </summary>
  77. public bool m_physicalPrim;
  78. public float m_maxNonphys = 65536;
  79. public float m_maxPhys = 10;
  80. public bool m_clampPrimSize = false;
  81. public bool m_trustBinaries = false;
  82. public bool m_allowScriptCrossings = false;
  83. public bool m_seeIntoRegionFromNeighbor;
  84. public int MaxUndoCount = 5;
  85. private int m_RestartTimerCounter;
  86. private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing
  87. private int m_incrementsof15seconds = 0;
  88. private volatile bool m_backingup = false;
  89. private Dictionary<UUID, ReturnInfo> m_returns = new Dictionary<UUID, ReturnInfo>();
  90. protected string m_simulatorVersion = "OpenSimulator Server";
  91. protected ModuleLoader m_moduleLoader;
  92. protected StorageManager m_storageManager;
  93. protected AgentCircuitManager m_authenticateHandler;
  94. public CommunicationsManager CommsManager;
  95. protected SceneCommunicationService m_sceneGridService;
  96. public SceneCommunicationService SceneGridService
  97. {
  98. get { return m_sceneGridService; }
  99. }
  100. /// <summary>
  101. /// Each agent has its own capabilities handler.
  102. /// </summary>
  103. protected Dictionary<UUID, Caps> m_capsHandlers = new Dictionary<UUID, Caps>();
  104. protected BaseHttpServer m_httpListener;
  105. /// <value>
  106. /// All the region modules attached to this scene.
  107. /// </value>
  108. public Dictionary<string, IRegionModule> Modules
  109. {
  110. get { return m_modules; }
  111. }
  112. protected Dictionary<string, IRegionModule> m_modules = new Dictionary<string, IRegionModule>();
  113. /// <value>
  114. /// The module interfaces available from this scene.
  115. /// </value>
  116. protected Dictionary<Type, List<object> > ModuleInterfaces = new Dictionary<Type, List<object> >();
  117. protected Dictionary<string, object> ModuleAPIMethods = new Dictionary<string, object>();
  118. protected Dictionary<string, ICommander> m_moduleCommanders = new Dictionary<string, ICommander>();
  119. //API module interfaces
  120. public IXfer XferManager;
  121. protected IHttpRequests m_httpRequestModule;
  122. protected IXMLRPC m_xmlrpcModule;
  123. protected IWorldComm m_worldCommModule;
  124. protected IAvatarFactory m_AvatarFactory;
  125. protected IConfigSource m_config;
  126. protected IRegionSerialiserModule m_serialiser;
  127. protected IInterregionCommsOut m_interregionCommsOut;
  128. protected IInterregionCommsIn m_interregionCommsIn;
  129. // Central Update Loop
  130. protected int m_fps = 10;
  131. protected int m_frame = 0;
  132. protected float m_timespan = 0.089f;
  133. protected DateTime m_lastupdate = DateTime.Now;
  134. protected float m_timedilation = 1.0f;
  135. private int m_update_physics = 1;
  136. private int m_update_entitymovement = 1;
  137. private int m_update_entities = 1; // Run through all objects checking for updates
  138. private int m_update_entitiesquick = 200; // Run through objects that have scheduled updates checking for updates
  139. private int m_update_presences = 1; // Update scene presence movements
  140. private int m_update_events = 1;
  141. private int m_update_backup = 200;
  142. private int m_update_terrain = 50;
  143. private int m_update_land = 1;
  144. private int frameMS = 0;
  145. private int physicsMS2 = 0;
  146. private int physicsMS = 0;
  147. private int otherMS = 0;
  148. private bool m_physics_enabled = true;
  149. private bool m_scripts_enabled = true;
  150. private string m_defaultScriptEngine;
  151. private int m_LastLogin = 0;
  152. private Thread HeartbeatThread;
  153. private volatile bool shuttingdown = false;
  154. private object m_deleting_scene_object = new object();
  155. // the minimum time that must elapse before a changed object will be considered for persisted
  156. public long m_dontPersistBefore = DEFAULT_MIN_TIME_FOR_PERSISTENCE * 10000000L;
  157. // the maximum time that must elapse before a changed object will be considered for persisted
  158. public long m_persistAfter = DEFAULT_MAX_TIME_FOR_PERSISTENCE * 10000000L;
  159. #endregion
  160. #region Properties
  161. public AgentCircuitManager AuthenticateHandler
  162. {
  163. get { return m_authenticateHandler; }
  164. }
  165. // an instance to the physics plugin's Scene object.
  166. public PhysicsScene PhysicsScene
  167. {
  168. get { return m_sceneGraph.PhysicsScene; }
  169. set
  170. {
  171. // If we're not doing the initial set
  172. // Then we've got to remove the previous
  173. // event handler
  174. if (PhysicsScene != null && PhysicsScene.SupportsNINJAJoints)
  175. {
  176. PhysicsScene.OnJointMoved -= jointMoved;
  177. PhysicsScene.OnJointDeactivated -= jointDeactivated;
  178. PhysicsScene.OnJointErrorMessage -= jointErrorMessage;
  179. }
  180. m_sceneGraph.PhysicsScene = value;
  181. if (PhysicsScene != null && m_sceneGraph.PhysicsScene.SupportsNINJAJoints)
  182. {
  183. // register event handlers to respond to joint movement/deactivation
  184. PhysicsScene.OnJointMoved += jointMoved;
  185. PhysicsScene.OnJointDeactivated += jointDeactivated;
  186. PhysicsScene.OnJointErrorMessage += jointErrorMessage;
  187. }
  188. }
  189. }
  190. // This gets locked so things stay thread safe.
  191. public object SyncRoot
  192. {
  193. get { return m_sceneGraph.m_syncRoot; }
  194. }
  195. public float TimeDilation
  196. {
  197. get { return m_timedilation; }
  198. }
  199. /// <summary>
  200. /// This is for llGetRegionFPS
  201. /// </summary>
  202. public float SimulatorFPS
  203. {
  204. get { return StatsReporter.getLastReportedSimFPS(); }
  205. }
  206. public int TimePhase
  207. {
  208. get { return m_timePhase; }
  209. }
  210. public string DefaultScriptEngine
  211. {
  212. get { return m_defaultScriptEngine; }
  213. }
  214. // Local reference to the objects in the scene (which are held in the scenegraph)
  215. // public Dictionary<UUID, SceneObjectGroup> Objects
  216. // {
  217. // get { return m_sceneGraph.SceneObjects; }
  218. // }
  219. // Reference to all of the agents in the scene (root and child)
  220. protected Dictionary<UUID, ScenePresence> m_scenePresences
  221. {
  222. get { return m_sceneGraph.ScenePresences; }
  223. set { m_sceneGraph.ScenePresences = value; }
  224. }
  225. // protected Dictionary<UUID, SceneObjectGroup> m_sceneObjects
  226. // {
  227. // get { return m_sceneGraph.SceneObjects; }
  228. // set { m_sceneGraph.SceneObjects = value; }
  229. // }
  230. public EntityManager Entities
  231. {
  232. get { return m_sceneGraph.Entities; }
  233. }
  234. public Dictionary<UUID, ScenePresence> m_restorePresences
  235. {
  236. get { return m_sceneGraph.RestorePresences; }
  237. set { m_sceneGraph.RestorePresences = value; }
  238. }
  239. public int objectCapacity = 45000;
  240. /// <value>
  241. /// Registered classes that are capable of creating entities.
  242. /// </value>
  243. protected Dictionary<PCode, IEntityCreator> m_entityCreators = new Dictionary<PCode, IEntityCreator>();
  244. #endregion
  245. #region Constructors
  246. public Scene(RegionInfo regInfo, AgentCircuitManager authen,
  247. CommunicationsManager commsMan, SceneCommunicationService sceneGridService,
  248. AssetCache assetCach, StorageManager storeManager, BaseHttpServer httpServer,
  249. ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim,
  250. bool SeeIntoRegionFromNeighbor, IConfigSource config, string simulatorVersion)
  251. {
  252. m_config = config;
  253. Random random = new Random();
  254. m_lastAllocatedLocalId = (uint)(random.NextDouble() * (double)(uint.MaxValue/2))+(uint)(uint.MaxValue/4);
  255. m_moduleLoader = moduleLoader;
  256. m_authenticateHandler = authen;
  257. CommsManager = commsMan;
  258. m_sceneGridService = sceneGridService;
  259. m_storageManager = storeManager;
  260. AssetCache = assetCach;
  261. m_regInfo = regInfo;
  262. m_regionHandle = m_regInfo.RegionHandle;
  263. m_regionName = m_regInfo.RegionName;
  264. m_datastore = m_regInfo.DataStore;
  265. m_physicalPrim = physicalPrim;
  266. m_seeIntoRegionFromNeighbor = SeeIntoRegionFromNeighbor;
  267. m_eventManager = new EventManager();
  268. m_permissions = new ScenePermissions(this);
  269. m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
  270. m_asyncSceneObjectDeleter.Enabled = true;
  271. // Load region settings
  272. m_regInfo.RegionSettings = m_storageManager.DataStore.LoadRegionSettings(m_regInfo.RegionID);
  273. if (m_storageManager.EstateDataStore != null)
  274. m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(m_regInfo.RegionID);
  275. //Bind Storage Manager functions to some land manager functions for this scene
  276. EventManager.OnLandObjectAdded +=
  277. new EventManager.LandObjectAdded(m_storageManager.DataStore.StoreLandObject);
  278. EventManager.OnLandObjectRemoved +=
  279. new EventManager.LandObjectRemoved(m_storageManager.DataStore.RemoveLandObject);
  280. m_sceneGraph = new SceneGraph(this, m_regInfo);
  281. // If the scene graph has an Unrecoverable error, restart this sim.
  282. // Currently the only thing that causes it to happen is two kinds of specific
  283. // Physics based crashes.
  284. //
  285. // Out of memory
  286. // Operating system has killed the plugin
  287. m_sceneGraph.UnRecoverableError += RestartNow;
  288. RegisterDefaultSceneEvents();
  289. m_httpListener = httpServer;
  290. m_dumpAssetsToFile = dumpAssetsToFile;
  291. m_scripts_enabled = !RegionInfo.RegionSettings.DisableScripts;
  292. m_physics_enabled = !RegionInfo.RegionSettings.DisablePhysics;
  293. StatsReporter = new SimStatsReporter(this);
  294. StatsReporter.OnSendStatsResult += SendSimStatsPackets;
  295. StatsReporter.SetObjectCapacity(objectCapacity);
  296. m_simulatorVersion = simulatorVersion
  297. + " (OS " + Util.GetOperatingSystemInformation() + ")"
  298. + " ChilTasks:" + m_seeIntoRegionFromNeighbor.ToString()
  299. + " PhysPrim:" + m_physicalPrim.ToString();
  300. try
  301. {
  302. // Region config overrides global config
  303. //
  304. IConfig startupConfig = m_config.Configs["Startup"];
  305. m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", 65536.0f);
  306. if (RegionInfo.NonphysPrimMax > 0)
  307. m_maxNonphys = RegionInfo.NonphysPrimMax;
  308. m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", 10.0f);
  309. if (RegionInfo.PhysPrimMax > 0)
  310. m_maxPhys = RegionInfo.PhysPrimMax;
  311. // Here, if clamping is requested in either global or
  312. // local config, it will be used
  313. //
  314. m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", false);
  315. if (RegionInfo.ClampPrimSize)
  316. m_clampPrimSize = true;
  317. m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", false);
  318. m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", false);
  319. m_dontPersistBefore =
  320. startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
  321. m_dontPersistBefore *= 10000000;
  322. m_persistAfter =
  323. startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
  324. m_persistAfter *= 10000000;
  325. m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "DotNetEngine");
  326. }
  327. catch
  328. {
  329. m_log.Warn("[SCENE]: Failed to load StartupConfig");
  330. }
  331. }
  332. #endregion
  333. #region Startup / Close Methods
  334. public bool ShuttingDown
  335. {
  336. get { return shuttingdown; }
  337. }
  338. protected virtual void RegisterDefaultSceneEvents()
  339. {
  340. m_eventManager.OnPermissionError += SendPermissionAlert;
  341. }
  342. public override string GetSimulatorVersion()
  343. {
  344. return m_simulatorVersion;
  345. }
  346. /// <summary>
  347. /// Another region is up. Gets called from Grid Comms:
  348. /// (OGS1 -> LocalBackEnd -> RegionListened -> SceneCommunicationService)
  349. /// We have to tell all our ScenePresences about it, and add it to the
  350. /// neighbor list.
  351. ///
  352. /// We only add it to the neighbor list if it's within 1 region from here.
  353. /// Agents may have draw distance values that cross two regions though, so
  354. /// we add it to the notify list regardless of distance. We'll check
  355. /// the agent's draw distance before notifying them though.
  356. /// </summary>
  357. /// <param name="otherRegion">RegionInfo handle for the new region.</param>
  358. /// <returns>True after all operations complete, throws exceptions otherwise.</returns>
  359. public override bool OtherRegionUp(RegionInfo otherRegion)
  360. {
  361. if (RegionInfo.RegionHandle != otherRegion.RegionHandle)
  362. {
  363. for (int i = 0; i < m_neighbours.Count; i++)
  364. {
  365. // The purpose of this loop is to re-update the known neighbors
  366. // when another region comes up on top of another one.
  367. // The latest region in that location ends up in the
  368. // 'known neighbors list'
  369. // Additionally, the commFailTF property gets reset to false.
  370. if (m_neighbours[i].RegionHandle == otherRegion.RegionHandle)
  371. {
  372. lock (m_neighbours)
  373. {
  374. m_neighbours[i] = otherRegion;
  375. }
  376. }
  377. }
  378. // If the value isn't in the neighbours, add it.
  379. // If the RegionInfo isn't exact but is for the same XY World location,
  380. // then the above loop will fix that.
  381. if (!(CheckNeighborRegion(otherRegion)))
  382. {
  383. lock (m_neighbours)
  384. {
  385. m_neighbours.Add(otherRegion);
  386. //m_log.Info("[UP]: " + otherRegion.RegionHandle.ToString());
  387. }
  388. }
  389. // If these are cast to INT because long + negative values + abs returns invalid data
  390. int resultX = Math.Abs((int)otherRegion.RegionLocX - (int)RegionInfo.RegionLocX);
  391. int resultY = Math.Abs((int)otherRegion.RegionLocY - (int)RegionInfo.RegionLocY);
  392. if (resultX <= 1 && resultY <= 1)
  393. {
  394. try
  395. {
  396. ForEachScenePresence(delegate(ScenePresence agent)
  397. {
  398. // If agent is a root agent.
  399. if (!agent.IsChildAgent)
  400. {
  401. //agent.ControllingClient.new
  402. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  403. InformClientOfNeighbor(agent, otherRegion);
  404. }
  405. }
  406. );
  407. }
  408. catch (NullReferenceException)
  409. {
  410. // This means that we're not booted up completely yet.
  411. // This shouldn't happen too often anymore.
  412. m_log.Error("[SCENE]: Couldn't inform client of regionup because we got a null reference exception");
  413. }
  414. }
  415. else
  416. {
  417. m_log.Info("[INTERGRID]: Got notice about far away Region: " + otherRegion.RegionName.ToString() +
  418. " at (" + otherRegion.RegionLocX.ToString() + ", " +
  419. otherRegion.RegionLocY.ToString() + ")");
  420. }
  421. }
  422. return true;
  423. }
  424. public void AddNeighborRegion(RegionInfo region)
  425. {
  426. lock (m_neighbours)
  427. {
  428. if (!CheckNeighborRegion(region))
  429. {
  430. m_neighbours.Add(region);
  431. }
  432. }
  433. }
  434. public bool CheckNeighborRegion(RegionInfo region)
  435. {
  436. bool found = false;
  437. lock (m_neighbours)
  438. {
  439. foreach (RegionInfo reg in m_neighbours)
  440. {
  441. if (reg.RegionHandle == region.RegionHandle)
  442. {
  443. found = true;
  444. break;
  445. }
  446. }
  447. }
  448. return found;
  449. }
  450. /// <summary>
  451. /// Given float seconds, this will restart the region.
  452. /// </summary>
  453. /// <param name="seconds">float indicating duration before restart.</param>
  454. public virtual void Restart(float seconds)
  455. {
  456. // notifications are done in 15 second increments
  457. // so .. if the number of seconds is less then 15 seconds, it's not really a restart request
  458. // It's a 'Cancel restart' request.
  459. // RestartNow() does immediate restarting.
  460. if (seconds < 15)
  461. {
  462. m_restartTimer.Stop();
  463. SendGeneralAlert("Restart Aborted");
  464. }
  465. else
  466. {
  467. // Now we figure out what to set the timer to that does the notifications and calls, RestartNow()
  468. m_restartTimer.Interval = 15000;
  469. m_incrementsof15seconds = (int)seconds / 15;
  470. m_RestartTimerCounter = 0;
  471. m_restartTimer.AutoReset = true;
  472. m_restartTimer.Elapsed += new ElapsedEventHandler(RestartTimer_Elapsed);
  473. m_log.Error("[REGION]: Restarting Region in " + (seconds / 60) + " minutes");
  474. m_restartTimer.Start();
  475. SendRegionMessageFromEstateTools(UUID.Random(), UUID.Random(), String.Empty, RegionInfo.RegionName + ": Restarting in 2 Minutes");
  476. //SendGeneralAlert(RegionInfo.RegionName + ": Restarting in 2 Minutes");
  477. }
  478. }
  479. // The Restart timer has occured.
  480. // We have to figure out if this is a notification or if the number of seconds specified in Restart
  481. // have elapsed.
  482. // If they have elapsed, call RestartNow()
  483. public void RestartTimer_Elapsed(object sender, ElapsedEventArgs e)
  484. {
  485. m_RestartTimerCounter++;
  486. if (m_RestartTimerCounter <= m_incrementsof15seconds)
  487. {
  488. if (m_RestartTimerCounter == 4 || m_RestartTimerCounter == 6 || m_RestartTimerCounter == 7)
  489. SendRegionMessageFromEstateTools(UUID.Random(), UUID.Random(), String.Empty, RegionInfo.RegionName + ": Restarting in " +
  490. ((8 - m_RestartTimerCounter) * 15) + " seconds");
  491. // SendGeneralAlert(RegionInfo.RegionName + ": Restarting in " + ((8 - m_RestartTimerCounter)*15) +
  492. //" seconds");
  493. }
  494. else
  495. {
  496. m_restartTimer.Stop();
  497. m_restartTimer.AutoReset = false;
  498. RestartNow();
  499. }
  500. }
  501. // This causes the region to restart immediatley.
  502. public void RestartNow()
  503. {
  504. if (PhysicsScene != null)
  505. {
  506. PhysicsScene.Dispose();
  507. }
  508. m_log.Error("[REGION]: Closing");
  509. Close();
  510. m_log.Error("[REGION]: Firing Region Restart Message");
  511. base.Restart(0);
  512. }
  513. // This is a helper function that notifies root agents in this region that a new sim near them has come up
  514. // This is in the form of a timer because when an instance of OpenSim.exe is started,
  515. // Even though the sims initialize, they don't listen until 'all of the sims are initialized'
  516. // If we tell an agent about a sim that's not listening yet, the agent will not be able to connect to it.
  517. // subsequently the agent will never see the region come back online.
  518. public void RestartNotifyWaitElapsed(object sender, ElapsedEventArgs e)
  519. {
  520. m_restartWaitTimer.Stop();
  521. lock (m_regionRestartNotifyList)
  522. {
  523. foreach (RegionInfo region in m_regionRestartNotifyList)
  524. {
  525. try
  526. {
  527. ForEachScenePresence(delegate(ScenePresence agent)
  528. {
  529. // If agent is a root agent.
  530. if (!agent.IsChildAgent)
  531. {
  532. //agent.ControllingClient.new
  533. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  534. InformClientOfNeighbor(agent, region);
  535. }
  536. }
  537. );
  538. }
  539. catch (NullReferenceException)
  540. {
  541. // This means that we're not booted up completely yet.
  542. // This shouldn't happen too often anymore.
  543. }
  544. }
  545. // Reset list to nothing.
  546. m_regionRestartNotifyList.Clear();
  547. }
  548. }
  549. public void SetSceneCoreDebug(bool ScriptEngine, bool CollisionEvents, bool PhysicsEngine)
  550. {
  551. if (m_scripts_enabled != !ScriptEngine)
  552. {
  553. // Tedd! Here's the method to disable the scripting engine!
  554. if (ScriptEngine)
  555. {
  556. m_log.Info("Stopping all Scripts in Scene");
  557. foreach (EntityBase ent in Entities)
  558. {
  559. if (ent is SceneObjectGroup)
  560. {
  561. ((SceneObjectGroup) ent).RemoveScriptInstances();
  562. }
  563. }
  564. }
  565. else
  566. {
  567. m_log.Info("Starting all Scripts in Scene");
  568. lock (Entities)
  569. {
  570. foreach (EntityBase ent in Entities)
  571. {
  572. if (ent is SceneObjectGroup)
  573. {
  574. ((SceneObjectGroup)ent).CreateScriptInstances(0, false, DefaultScriptEngine, 0);
  575. }
  576. }
  577. }
  578. }
  579. m_scripts_enabled = !ScriptEngine;
  580. m_log.Info("[TOTEDD]: Here is the method to trigger disabling of the scripting engine");
  581. }
  582. if (m_physics_enabled != !PhysicsEngine)
  583. {
  584. m_physics_enabled = !PhysicsEngine;
  585. }
  586. }
  587. public int GetInaccurateNeighborCount()
  588. {
  589. lock (m_neighbours)
  590. {
  591. return m_neighbours.Count;
  592. }
  593. }
  594. // This is the method that shuts down the scene.
  595. public override void Close()
  596. {
  597. m_log.InfoFormat("[SCENE]: Closing down the single simulator: {0}", RegionInfo.RegionName);
  598. // Kick all ROOT agents with the message, 'The simulator is going down'
  599. ForEachScenePresence(delegate(ScenePresence avatar)
  600. {
  601. if (avatar.KnownChildRegionHandles.Contains(RegionInfo.RegionHandle))
  602. avatar.KnownChildRegionHandles.Remove(RegionInfo.RegionHandle);
  603. if (!avatar.IsChildAgent)
  604. avatar.ControllingClient.Kick("The simulator is going down.");
  605. avatar.ControllingClient.SendShutdownConnectionNotice();
  606. });
  607. // Wait here, or the kick messages won't actually get to the agents before the scene terminates.
  608. Thread.Sleep(500);
  609. // Stop all client threads.
  610. ForEachScenePresence(delegate(ScenePresence avatar) { avatar.ControllingClient.Close(true); });
  611. // Stop updating the scene objects and agents.
  612. //m_heartbeatTimer.Close();
  613. shuttingdown = true;
  614. m_log.Debug("[SCENE]: Persisting changed objects");
  615. List<EntityBase> entities = GetEntities();
  616. foreach (EntityBase entity in entities)
  617. {
  618. if (!entity.IsDeleted && entity is SceneObjectGroup && ((SceneObjectGroup)entity).HasGroupChanged)
  619. {
  620. ((SceneObjectGroup)entity).ProcessBackup(m_storageManager.DataStore);
  621. }
  622. }
  623. m_sceneGraph.Close();
  624. // De-register with region communications (events cleanup)
  625. UnRegisterRegionWithComms();
  626. // Shut down all non shared modules.
  627. foreach (IRegionModule module in Modules.Values)
  628. {
  629. if (!module.IsSharedModule)
  630. {
  631. module.Close();
  632. }
  633. }
  634. Modules.Clear();
  635. // call the base class Close method.
  636. base.Close();
  637. }
  638. /// <summary>
  639. /// Start the timer which triggers regular scene updates
  640. /// </summary>
  641. public void StartTimer()
  642. {
  643. //m_log.Debug("[SCENE]: Starting timer");
  644. //m_heartbeatTimer.Enabled = true;
  645. //m_heartbeatTimer.Interval = (int)(m_timespan * 1000);
  646. //m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat);
  647. HeartbeatThread = new Thread(new ParameterizedThreadStart(Heartbeat));
  648. HeartbeatThread.SetApartmentState(ApartmentState.MTA);
  649. HeartbeatThread.Name = "Heartbeat";
  650. HeartbeatThread.Priority = ThreadPriority.AboveNormal;
  651. ThreadTracker.Add(HeartbeatThread);
  652. HeartbeatThread.Start();
  653. }
  654. /// <summary>
  655. /// Sets up references to modules required by the scene
  656. /// </summary>
  657. public void SetModuleInterfaces()
  658. {
  659. m_httpRequestModule = RequestModuleInterface<IHttpRequests>();
  660. m_xmlrpcModule = RequestModuleInterface<IXMLRPC>();
  661. m_worldCommModule = RequestModuleInterface<IWorldComm>();
  662. XferManager = RequestModuleInterface<IXfer>();
  663. m_AvatarFactory = RequestModuleInterface<IAvatarFactory>();
  664. m_serialiser = RequestModuleInterface<IRegionSerialiserModule>();
  665. m_interregionCommsOut = RequestModuleInterface<IInterregionCommsOut>();
  666. m_interregionCommsIn = RequestModuleInterface<IInterregionCommsIn>();
  667. }
  668. #endregion
  669. #region Update Methods
  670. /// <summary>
  671. /// Performs per-frame updates regularly
  672. /// </summary>
  673. /// <param name="sender"></param>
  674. /// <param name="e"></param>
  675. private void Heartbeat(object sender)
  676. {
  677. Update();
  678. }
  679. /// <summary>
  680. /// Performs per-frame updates on the scene, this should be the central scene loop
  681. /// </summary>
  682. public override void Update()
  683. {
  684. int maintc = 0;
  685. while (!shuttingdown)
  686. {
  687. maintc = System.Environment.TickCount;
  688. TimeSpan SinceLastFrame = DateTime.Now - m_lastupdate;
  689. // Aquire a lock so only one update call happens at once
  690. //updateLock.WaitOne();
  691. float physicsFPS = 0;
  692. //m_log.Info("sadfadf" + m_neighbours.Count.ToString());
  693. int agentsInScene = m_sceneGraph.GetRootAgentCount() + m_sceneGraph.GetChildAgentCount();
  694. if (agentsInScene > 21)
  695. {
  696. if (m_update_entities == 1)
  697. {
  698. m_update_entities = 5;
  699. StatsReporter.SetUpdateMS(6000);
  700. }
  701. }
  702. else
  703. {
  704. if (m_update_entities == 5)
  705. {
  706. m_update_entities = 1;
  707. StatsReporter.SetUpdateMS(3000);
  708. }
  709. }
  710. frameMS = System.Environment.TickCount;
  711. try
  712. {
  713. // Increment the frame counter
  714. m_frame++;
  715. // Loop it
  716. if (m_frame == Int32.MaxValue)
  717. m_frame = 0;
  718. physicsMS2 = System.Environment.TickCount;
  719. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  720. m_sceneGraph.UpdatePreparePhysics();
  721. physicsMS2 = System.Environment.TickCount - physicsMS2;
  722. if (m_frame % m_update_entitymovement == 0)
  723. m_sceneGraph.UpdateEntityMovement();
  724. physicsMS = System.Environment.TickCount;
  725. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  726. physicsFPS = m_sceneGraph.UpdatePhysics(
  727. Math.Max(SinceLastFrame.TotalSeconds, m_timespan)
  728. );
  729. if (m_frame % m_update_physics == 0 && SynchronizeScene != null)
  730. SynchronizeScene(this);
  731. physicsMS = System.Environment.TickCount - physicsMS;
  732. physicsMS += physicsMS2;
  733. otherMS = System.Environment.TickCount;
  734. // run through all entities looking for updates (slow)
  735. if (m_frame % m_update_entities == 0)
  736. m_sceneGraph.UpdateEntities();
  737. // run through entities that have scheduled themselves for
  738. // updates looking for updates(faster)
  739. if (m_frame % m_update_entitiesquick == 0)
  740. m_sceneGraph.ProcessUpdates();
  741. // Run through scenepresences looking for updates
  742. if (m_frame % m_update_presences == 0)
  743. m_sceneGraph.UpdatePresences();
  744. // Delete temp-on-rez stuff
  745. if (m_frame % m_update_backup == 0)
  746. CleanTempObjects();
  747. if (Region_Status != RegionStatus.SlaveScene)
  748. {
  749. if (m_frame % m_update_events == 0)
  750. UpdateEvents();
  751. if (m_frame % m_update_backup == 0)
  752. {
  753. UpdateStorageBackup();
  754. }
  755. if (m_frame % m_update_terrain == 0)
  756. UpdateTerrain();
  757. if (m_frame % m_update_land == 0)
  758. UpdateLand();
  759. otherMS = System.Environment.TickCount - otherMS;
  760. // if (m_frame%m_update_avatars == 0)
  761. // UpdateInWorldTime();
  762. StatsReporter.AddPhysicsFPS(physicsFPS);
  763. StatsReporter.AddTimeDilation(m_timedilation);
  764. StatsReporter.AddFPS(1);
  765. StatsReporter.AddInPackets(0);
  766. StatsReporter.SetRootAgents(m_sceneGraph.GetRootAgentCount());
  767. StatsReporter.SetChildAgents(m_sceneGraph.GetChildAgentCount());
  768. StatsReporter.SetObjects(m_sceneGraph.GetTotalObjectsCount());
  769. StatsReporter.SetActiveObjects(m_sceneGraph.GetActiveObjectsCount());
  770. frameMS = System.Environment.TickCount - frameMS;
  771. StatsReporter.addFrameMS(frameMS);
  772. StatsReporter.addPhysicsMS(physicsMS);
  773. StatsReporter.addOtherMS(otherMS);
  774. StatsReporter.SetActiveScripts(m_sceneGraph.GetActiveScriptsCount());
  775. StatsReporter.addScriptLines(m_sceneGraph.GetScriptLPS());
  776. }
  777. }
  778. catch (NotImplementedException)
  779. {
  780. throw;
  781. }
  782. catch (AccessViolationException e)
  783. {
  784. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  785. }
  786. //catch (NullReferenceException e)
  787. //{
  788. // m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  789. //}
  790. catch (InvalidOperationException e)
  791. {
  792. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  793. }
  794. catch (Exception e)
  795. {
  796. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  797. }
  798. finally
  799. {
  800. //updateLock.ReleaseMutex();
  801. // Get actual time dilation
  802. float tmpval = (m_timespan / (float)SinceLastFrame.TotalSeconds);
  803. // If actual time dilation is greater then one, we're catching up, so subtract
  804. // the amount that's greater then 1 from the time dilation
  805. if (tmpval > 1.0)
  806. {
  807. tmpval = tmpval - (tmpval - 1.0f);
  808. }
  809. m_timedilation = tmpval;
  810. m_lastupdate = DateTime.Now;
  811. }
  812. maintc = System.Environment.TickCount - maintc;
  813. maintc = (int)(m_timespan * 1000) - maintc;
  814. if ((maintc < (m_timespan * 1000)) && maintc > 0)
  815. Thread.Sleep(maintc);
  816. }
  817. }
  818. private void SendSimStatsPackets(SimStats stats)
  819. {
  820. List<ScenePresence> StatSendAgents = GetScenePresences();
  821. foreach (ScenePresence agent in StatSendAgents)
  822. {
  823. if (!agent.IsChildAgent)
  824. {
  825. agent.ControllingClient.SendSimStats(stats);
  826. }
  827. }
  828. }
  829. private void UpdateLand()
  830. {
  831. if (LandChannel != null)
  832. {
  833. if (LandChannel.IsLandPrimCountTainted())
  834. {
  835. EventManager.TriggerParcelPrimCountUpdate();
  836. }
  837. }
  838. }
  839. private void UpdateTerrain()
  840. {
  841. EventManager.TriggerTerrainTick();
  842. }
  843. private void UpdateStorageBackup()
  844. {
  845. if (!m_backingup)
  846. {
  847. m_backingup = true;
  848. Thread backupthread = new Thread(Backup);
  849. backupthread.Name = "BackupWriter";
  850. backupthread.IsBackground = true;
  851. backupthread.Start();
  852. }
  853. }
  854. private void UpdateEvents()
  855. {
  856. m_eventManager.TriggerOnFrame();
  857. }
  858. /// <summary>
  859. /// Perform delegate action on all clients subscribing to updates from this region.
  860. /// </summary>
  861. /// <returns></returns>
  862. internal void Broadcast(Action<IClientAPI> whatToDo)
  863. {
  864. ForEachScenePresence(delegate(ScenePresence presence) { whatToDo(presence.ControllingClient); });
  865. }
  866. /// <summary>
  867. /// Backup the scene. This acts as the main method of the backup thread.
  868. /// </summary>
  869. /// <returns></returns>
  870. public void Backup()
  871. {
  872. lock (m_returns)
  873. {
  874. EventManager.TriggerOnBackup(m_storageManager.DataStore);
  875. m_backingup = false;
  876. foreach (KeyValuePair<UUID, ReturnInfo> ret in m_returns)
  877. {
  878. UUID transaction = UUID.Random();
  879. GridInstantMessage msg = new GridInstantMessage();
  880. msg.fromAgentID = new Guid(UUID.Zero.ToString()); // From server
  881. msg.toAgentID = new Guid(ret.Key.ToString());
  882. msg.imSessionID = new Guid(transaction.ToString());
  883. msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
  884. msg.fromAgentName = "Server";
  885. msg.dialog = (byte)19; // Object msg
  886. msg.fromGroup = false;
  887. msg.offline = (byte)1;
  888. msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID;
  889. msg.Position = Vector3.Zero;
  890. msg.RegionID = RegionInfo.RegionID.Guid;
  891. msg.binaryBucket = new byte[0];
  892. if (ret.Value.count > 1)
  893. 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);
  894. else
  895. 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);
  896. IMessageTransferModule tr = RequestModuleInterface<IMessageTransferModule>();
  897. if (tr != null)
  898. tr.SendInstantMessage(msg, delegate(bool success) {} );
  899. }
  900. m_returns.Clear();
  901. }
  902. }
  903. public void AddReturn(UUID agentID, string objectName, Vector3 location, string reason)
  904. {
  905. lock (m_returns)
  906. {
  907. if (m_returns.ContainsKey(agentID))
  908. {
  909. ReturnInfo info = m_returns[agentID];
  910. info.count++;
  911. m_returns[agentID] = info;
  912. }
  913. else
  914. {
  915. ReturnInfo info = new ReturnInfo();
  916. info.count = 1;
  917. info.objectName = objectName;
  918. info.location = location;
  919. info.reason = reason;
  920. m_returns[agentID] = info;
  921. }
  922. }
  923. }
  924. #endregion
  925. #region Load Terrain
  926. public void ExportWorldMap(string fileName)
  927. {
  928. List<MapBlockData> mapBlocks =
  929. m_sceneGridService.RequestNeighbourMapBlocks((int)(RegionInfo.RegionLocX - 9),
  930. (int)(RegionInfo.RegionLocY - 9),
  931. (int)(RegionInfo.RegionLocX + 9),
  932. (int)(RegionInfo.RegionLocY + 9));
  933. List<AssetBase> textures = new List<AssetBase>();
  934. List<Image> bitImages = new List<Image>();
  935. foreach (MapBlockData mapBlock in mapBlocks)
  936. {
  937. AssetBase texAsset = AssetCache.GetAsset(mapBlock.MapImageId, true);
  938. if (texAsset != null)
  939. {
  940. textures.Add(texAsset);
  941. }
  942. else
  943. {
  944. texAsset = AssetCache.GetAsset(mapBlock.MapImageId, true);
  945. if (texAsset != null)
  946. {
  947. textures.Add(texAsset);
  948. }
  949. }
  950. }
  951. foreach (AssetBase asset in textures)
  952. {
  953. ManagedImage managedImage;
  954. Image image;
  955. if (OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image))
  956. bitImages.Add(image);
  957. }
  958. Bitmap mapTexture = new Bitmap(2560, 2560);
  959. Graphics g = Graphics.FromImage(mapTexture);
  960. SolidBrush sea = new SolidBrush(Color.DarkBlue);
  961. g.FillRectangle(sea, 0, 0, 2560, 2560);
  962. for (int i = 0; i < mapBlocks.Count; i++)
  963. {
  964. ushort x = (ushort)((mapBlocks[i].X - RegionInfo.RegionLocX) + 10);
  965. ushort y = (ushort)((mapBlocks[i].Y - RegionInfo.RegionLocY) + 10);
  966. g.DrawImage(bitImages[i], (x * 128), (y * 128), 128, 128);
  967. }
  968. mapTexture.Save(fileName, ImageFormat.Jpeg);
  969. }
  970. public void SaveTerrain()
  971. {
  972. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  973. }
  974. /// <summary>
  975. /// Loads the World heightmap
  976. /// </summary>
  977. public override void LoadWorldMap()
  978. {
  979. try
  980. {
  981. double[,] map = m_storageManager.DataStore.LoadTerrain(RegionInfo.RegionID);
  982. if (map == null)
  983. {
  984. m_log.Info("[TERRAIN]: No default terrain. Generating a new terrain.");
  985. Heightmap = new TerrainChannel();
  986. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  987. }
  988. else
  989. {
  990. Heightmap = new TerrainChannel(map);
  991. }
  992. }
  993. catch (Exception e)
  994. {
  995. m_log.Warn("[TERRAIN]: Scene.cs: LoadWorldMap() - Failed with exception " + e.ToString());
  996. }
  997. }
  998. /// <summary>
  999. /// Register this region with a grid service
  1000. /// </summary>
  1001. /// <exception cref="System.Exception">Thrown if registration of the region itself fails.</exception>
  1002. public void RegisterRegionWithGrid()
  1003. {
  1004. RegisterCommsEvents();
  1005. // These two 'commands' *must be* next to each other or sim rebooting fails.
  1006. m_sceneGridService.RegisterRegion(m_interregionCommsOut, RegionInfo);
  1007. m_sceneGridService.InformNeighborsThatRegionisUp(RegionInfo);
  1008. Dictionary<string, string> dGridSettings = m_sceneGridService.GetGridSettings();
  1009. if (dGridSettings.ContainsKey("allow_forceful_banlines"))
  1010. {
  1011. if (dGridSettings["allow_forceful_banlines"] != "TRUE")
  1012. {
  1013. m_log.Info("[GRID]: Grid is disabling forceful parcel banlists");
  1014. EventManager.TriggerSetAllowForcefulBan(false);
  1015. }
  1016. else
  1017. {
  1018. m_log.Info("[GRID]: Grid is allowing forceful parcel banlists");
  1019. EventManager.TriggerSetAllowForcefulBan(true);
  1020. }
  1021. }
  1022. }
  1023. /// <summary>
  1024. ///
  1025. /// </summary>
  1026. public void CreateTerrainTexture(bool temporary)
  1027. {
  1028. //create a texture asset of the terrain
  1029. IMapImageGenerator terrain = RequestModuleInterface<IMapImageGenerator>();
  1030. // Cannot create a map for a nonexistant heightmap yet.
  1031. if (Heightmap == null)
  1032. return;
  1033. if (terrain == null)
  1034. {
  1035. #region Fallback default maptile generation
  1036. int tc = System.Environment.TickCount;
  1037. m_log.Info("[MAPTILE]: Generating Maptile Step 1: Terrain");
  1038. Bitmap mapbmp = new Bitmap(256, 256);
  1039. double[,] hm = Heightmap.GetDoubles();
  1040. bool ShadowDebugContinue = true;
  1041. //Color prim = Color.FromArgb(120, 120, 120);
  1042. //Vector3 RayEnd = new Vector3(0, 0, 0);
  1043. //Vector3 RayStart = new Vector3(0, 0, 0);
  1044. //Vector3 direction = new Vector3(0, 0, -1);
  1045. //Vector3 AXOrigin = new Vector3();
  1046. //Vector3 AXdirection = new Vector3();
  1047. //Ray testRay = new Ray();
  1048. //EntityIntersection rt = new EntityIntersection();
  1049. bool terraincorruptedwarningsaid = false;
  1050. float low = 255;
  1051. float high = 0;
  1052. for (int x = 0; x < 256; x++)
  1053. {
  1054. for (int y = 0; y < 256; y++)
  1055. {
  1056. float hmval = (float)hm[x, y];
  1057. if (hmval < low)
  1058. low = hmval;
  1059. if (hmval > high)
  1060. high = hmval;
  1061. }
  1062. }
  1063. float mid = (high + low) * 0.5f;
  1064. // temporary initializer
  1065. float hfvalue = (float)m_regInfo.RegionSettings.WaterHeight;
  1066. float hfvaluecompare = hfvalue;
  1067. float hfdiff = hfvalue;
  1068. int hfdiffi = 0;
  1069. for (int x = 0; x < 256; x++)
  1070. {
  1071. //int tc = System.Environment.TickCount;
  1072. for (int y = 0; y < 256; y++)
  1073. {
  1074. //RayEnd = new Vector3(x, y, 0);
  1075. //RayStart = new Vector3(x, y, 255);
  1076. //direction = Vector3.Norm(RayEnd - RayStart);
  1077. //AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  1078. //AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  1079. //testRay = new Ray(AXOrigin, AXdirection);
  1080. //rt = m_sceneGraph.GetClosestIntersectingPrim(testRay);
  1081. //if (rt.HitTF)
  1082. //{
  1083. //mapbmp.SetPixel(x, y, prim);
  1084. //}
  1085. //else
  1086. //{
  1087. //float tmpval = (float)hm[x, y];
  1088. float heightvalue = (float)hm[x, y];
  1089. if (heightvalue > (float)m_regInfo.RegionSettings.WaterHeight)
  1090. {
  1091. // scale height value
  1092. heightvalue = low + mid * (heightvalue - low) / mid;
  1093. if (heightvalue > 255)
  1094. heightvalue = 255;
  1095. if (heightvalue < 0)
  1096. heightvalue = 0;
  1097. if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue))
  1098. heightvalue = 0;
  1099. try
  1100. {
  1101. Color green = Color.FromArgb((int)heightvalue, 100, (int)heightvalue);
  1102. // Y flip the cordinates
  1103. mapbmp.SetPixel(x, (256 - y) - 1, green);
  1104. //X
  1105. // .
  1106. //
  1107. // Shade the terrain for shadows
  1108. if ((x - 1 > 0) && (y - 1 > 0))
  1109. {
  1110. hfvalue = (float)hm[x, y];
  1111. hfvaluecompare = (float)hm[x - 1, y - 1];
  1112. if (Single.IsInfinity(hfvalue) || Single.IsNaN(hfvalue))
  1113. hfvalue = 0;
  1114. if (Single.IsInfinity(hfvaluecompare) || Single.IsNaN(hfvaluecompare))
  1115. hfvaluecompare = 0;
  1116. hfdiff = hfvaluecompare - hfvalue;
  1117. if (hfdiff > 0.3f)
  1118. {
  1119. }
  1120. else if (hfdiff < -0.3f)
  1121. {
  1122. // We have to desaturate and blacken the land at the same time
  1123. // we use floats, colors use bytes, so shrink are space down to
  1124. // 0-255
  1125. try
  1126. {
  1127. hfdiffi = Math.Abs((int)((hfdiff * 4) + (hfdiff * 0.5))) + 1;
  1128. if (hfdiff % 1 != 0)
  1129. {
  1130. hfdiffi = hfdiffi + Math.Abs((int)(((hfdiff % 1) * 0.5f) * 10f) - 1);
  1131. }
  1132. }
  1133. catch (System.OverflowException)
  1134. {
  1135. m_log.Debug("[MAPTILE]: Shadow failed at value: " + hfdiff.ToString());
  1136. ShadowDebugContinue = false;
  1137. }
  1138. if (ShadowDebugContinue)
  1139. {
  1140. if ((256 - y) - 1 > 0)
  1141. {
  1142. Color Shade = mapbmp.GetPixel(x - 1, (256 - y) - 1);
  1143. int r = Shade.R;
  1144. int g = Shade.G;
  1145. int b = Shade.B;
  1146. Shade = Color.FromArgb((r - hfdiffi > 0) ? r - hfdiffi : 0, (g - hfdiffi > 0) ? g - hfdiffi : 0, (b - hfdiffi > 0) ? b - hfdiffi : 0);
  1147. //Console.WriteLine("d:" + hfdiff.ToString() + ", i:" + hfdiffi + ", pos: " + x + "," + y + " - R:" + Shade.R.ToString() + ", G:" + Shade.G.ToString() + ", B:" + Shade.G.ToString());
  1148. mapbmp.SetPixel(x - 1, (256 - y) - 1, Shade);
  1149. }
  1150. }
  1151. }
  1152. }
  1153. }
  1154. catch (System.ArgumentException)
  1155. {
  1156. if (!terraincorruptedwarningsaid)
  1157. {
  1158. m_log.WarnFormat("[MAPIMAGE]: Your terrain is corrupted in region {0}, it might take a few minutes to generate the map image depending on the corruption level", RegionInfo.RegionName);
  1159. terraincorruptedwarningsaid = true;
  1160. }
  1161. Color black = Color.Black;
  1162. mapbmp.SetPixel(x, (256 - y) - 1, black);
  1163. }
  1164. }
  1165. else
  1166. {
  1167. // Y flip the cordinates
  1168. heightvalue = (float)m_regInfo.RegionSettings.WaterHeight - heightvalue;
  1169. if (heightvalue > 19)
  1170. heightvalue = 19;
  1171. if (heightvalue < 0)
  1172. heightvalue = 0;
  1173. heightvalue = 100 - (heightvalue * 100) / 19;
  1174. if (heightvalue > 255)
  1175. heightvalue = 255;
  1176. if (heightvalue < 0)
  1177. heightvalue = 0;
  1178. if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue))
  1179. heightvalue = 0;
  1180. try
  1181. {
  1182. Color water = Color.FromArgb((int)heightvalue, (int)heightvalue, 255);
  1183. mapbmp.SetPixel(x, (256 - y) - 1, water);
  1184. }
  1185. catch (System.ArgumentException)
  1186. {
  1187. if (!terraincorruptedwarningsaid)
  1188. {
  1189. m_log.WarnFormat("[MAPIMAGE]: Your terrain is corrupted in region {0}, it might take a few minutes to generate the map image depending on the corruption level", RegionInfo.RegionName);
  1190. terraincorruptedwarningsaid = true;
  1191. }
  1192. Color black = Color.Black;
  1193. mapbmp.SetPixel(x, (256 - y) - 1, black);
  1194. }
  1195. }
  1196. }
  1197. //}
  1198. //tc = System.Environment.TickCount - tc;
  1199. //m_log.Info("[MAPTILE]: Completed One row in " + tc + " ms");
  1200. }
  1201. m_log.Info("[MAPTILE]: Generating Maptile Step 1: Done in " + (System.Environment.TickCount - tc) + " ms");
  1202. bool drawPrimVolume = true;
  1203. try
  1204. {
  1205. IConfig startupConfig = m_config.Configs["Startup"];
  1206. drawPrimVolume = startupConfig.GetBoolean("DrawPrimOnMapTile", true);
  1207. }
  1208. catch
  1209. {
  1210. m_log.Warn("[MAPTILE]: Failed to load StartupConfig");
  1211. }
  1212. if (drawPrimVolume)
  1213. {
  1214. tc = System.Environment.TickCount;
  1215. m_log.Info("[MAPTILE]: Generating Maptile Step 2: Object Volume Profile");
  1216. List<EntityBase> objs = GetEntities();
  1217. lock (objs)
  1218. {
  1219. foreach (EntityBase obj in objs)
  1220. {
  1221. // Only draw the contents of SceneObjectGroup
  1222. if (obj is SceneObjectGroup)
  1223. {
  1224. SceneObjectGroup mapdot = (SceneObjectGroup)obj;
  1225. Color mapdotspot = Color.Gray; // Default color when prim color is white
  1226. // Loop over prim in group
  1227. foreach (SceneObjectPart part in mapdot.Children.Values)
  1228. {
  1229. if (part == null)
  1230. continue;
  1231. // Draw if the object is at least 1 meter wide in any direction
  1232. if (part.Scale.X > 1f || part.Scale.Y > 1f || part.Scale.Z > 1f)
  1233. {
  1234. // Try to get the RGBA of the default texture entry..
  1235. //
  1236. try
  1237. {
  1238. if (part == null)
  1239. continue;
  1240. if (part.Shape == null)
  1241. continue;
  1242. if (part.Shape.PCode == (byte)PCode.Tree || part.Shape.PCode == (byte)PCode.NewTree)
  1243. continue; // eliminates trees from this since we don't really have a good tree representation
  1244. // if you want tree blocks on the map comment the above line and uncomment the below line
  1245. //mapdotspot = Color.PaleGreen;
  1246. if (part.Shape.Textures == null)
  1247. continue;
  1248. if (part.Shape.Textures.DefaultTexture == null)
  1249. continue;
  1250. Color4 texcolor = part.Shape.Textures.DefaultTexture.RGBA;
  1251. // Not sure why some of these are null, oh well.
  1252. int colorr = 255 - (int)(texcolor.R * 255f);
  1253. int colorg = 255 - (int)(texcolor.G * 255f);
  1254. int colorb = 255 - (int)(texcolor.B * 255f);
  1255. if (!(colorr == 255 && colorg == 255 && colorb == 255))
  1256. {
  1257. //Try to set the map spot color
  1258. try
  1259. {
  1260. // If the color gets goofy somehow, skip it *shakes fist at Color4
  1261. mapdotspot = Color.FromArgb(colorr, colorg, colorb);
  1262. }
  1263. catch (ArgumentException)
  1264. {
  1265. }
  1266. }
  1267. }
  1268. catch (IndexOutOfRangeException)
  1269. {
  1270. // Windows Array
  1271. }
  1272. catch (ArgumentOutOfRangeException)
  1273. {
  1274. // Mono Array
  1275. }
  1276. Vector3 pos = part.GetWorldPosition();
  1277. // skip prim outside of retion
  1278. if (pos.X < 0f || pos.X > 256f || pos.Y < 0f || pos.Y > 256f)
  1279. continue;
  1280. // skip prim in non-finite position
  1281. if (Single.IsNaN(pos.X) || Single.IsNaN(pos.Y) || Single.IsInfinity(pos.X)
  1282. || Single.IsInfinity(pos.Y))
  1283. continue;
  1284. // Figure out if object is under 256m above the height of the terrain
  1285. bool isBelow256AboveTerrain = false;
  1286. try
  1287. {
  1288. isBelow256AboveTerrain = (pos.Z < ((float)hm[(int)pos.X, (int)pos.Y] + 256f));
  1289. }
  1290. catch (Exception)
  1291. {
  1292. }
  1293. if (isBelow256AboveTerrain)
  1294. {
  1295. // Translate scale by rotation so scale is represented properly when object is rotated
  1296. Vector3 scale = part.Shape.Scale;
  1297. Quaternion rot = part.GetWorldRotation();
  1298. scale *= rot;
  1299. // negative scales don't work in this situation
  1300. scale.X = Math.Abs(scale.X);
  1301. scale.Y = Math.Abs(scale.Y);
  1302. scale.Z = Math.Abs(scale.Z);
  1303. // This scaling isn't very accurate and doesn't take into account the face rotation :P
  1304. int mapdrawstartX = (int)(pos.X - scale.X);
  1305. int mapdrawstartY = (int)(pos.Y - scale.Y);
  1306. int mapdrawendX = (int)(pos.X + scale.X);
  1307. int mapdrawendY = (int)(pos.Y + scale.Y);
  1308. // If object is beyond the edge of the map, don't draw it to avoid errors
  1309. if (mapdrawstartX < 0 || mapdrawstartX > 255 || mapdrawendX < 0 || mapdrawendX > 255
  1310. || mapdrawstartY < 0 || mapdrawstartY > 255 || mapdrawendY < 0
  1311. || mapdrawendY > 255)
  1312. continue;
  1313. int wy = 0;
  1314. bool breakYN = false; // If we run into an error drawing, break out of the
  1315. // loop so we don't lag to death on error handling
  1316. for (int wx = mapdrawstartX; wx < mapdrawendX; wx++)
  1317. {
  1318. for (wy = mapdrawstartY; wy < mapdrawendY; wy++)
  1319. {
  1320. //m_log.InfoFormat("[MAPDEBUG]: {0},{1}({2})", wx, (255 - wy),wy);
  1321. try
  1322. {
  1323. // Remember, flip the y!
  1324. mapbmp.SetPixel(wx, (255 - wy), mapdotspot);
  1325. }
  1326. catch (ArgumentException)
  1327. {
  1328. breakYN = true;
  1329. }
  1330. if (breakYN)
  1331. break;
  1332. }
  1333. if (breakYN)
  1334. break;
  1335. }
  1336. } // Object is within 256m Z of terrain
  1337. } // object is at least a meter wide
  1338. } // loop over group children
  1339. } // entitybase is sceneobject group
  1340. } // foreach loop over entities
  1341. } // lock entities objs
  1342. m_log.Info("[MAPTILE]: Generating Maptile Step 2: Done in " + (System.Environment.TickCount - tc) + " ms");
  1343. } // end if drawPrimOnMaptle
  1344. byte[] data;
  1345. try
  1346. {
  1347. data = OpenJPEG.EncodeFromImage(mapbmp, false);
  1348. }
  1349. catch (Exception)
  1350. {
  1351. return;
  1352. }
  1353. LazySaveGeneratedMaptile(data,temporary);
  1354. #endregion
  1355. }
  1356. else
  1357. {
  1358. // Use the module to generate the maptile.
  1359. byte[] data = terrain.WriteJpeg2000Image("defaultstripe.png");
  1360. if (data != null)
  1361. {
  1362. LazySaveGeneratedMaptile(data,temporary);
  1363. }
  1364. }
  1365. }
  1366. public void LazySaveGeneratedMaptile(byte[] data, bool temporary)
  1367. {
  1368. // Overwrites the local Asset cache with new maptile data
  1369. // Assets are single write, this causes the asset server to ignore this update,
  1370. // but the local asset cache does not
  1371. // this is on purpose! The net result of this is the region always has the most up to date
  1372. // map tile while protecting the (grid) asset database from bloat caused by a new asset each
  1373. // time a mapimage is generated!
  1374. UUID lastMapRegionUUID = m_regInfo.lastMapUUID;
  1375. int lastMapRefresh = 0;
  1376. int twoDays = 172800;
  1377. int RefreshSeconds = twoDays;
  1378. try
  1379. {
  1380. lastMapRefresh = Convert.ToInt32(m_regInfo.lastMapRefresh);
  1381. }
  1382. catch (ArgumentException)
  1383. {
  1384. }
  1385. catch (FormatException)
  1386. {
  1387. }
  1388. catch (OverflowException)
  1389. {
  1390. }
  1391. UUID TerrainImageUUID = UUID.Random();
  1392. if (lastMapRegionUUID == UUID.Zero || (lastMapRefresh + RefreshSeconds) < Util.UnixTimeSinceEpoch())
  1393. {
  1394. m_regInfo.SaveLastMapUUID(TerrainImageUUID);
  1395. m_log.Warn("[MAPTILE]: STORING MAPTILE IMAGE");
  1396. }
  1397. else
  1398. {
  1399. TerrainImageUUID = lastMapRegionUUID;
  1400. m_log.Warn("[MAPTILE]: REUSING OLD MAPTILE IMAGE ID");
  1401. }
  1402. m_regInfo.RegionSettings.TerrainImageID = TerrainImageUUID;
  1403. AssetBase asset = new AssetBase();
  1404. asset.FullID = m_regInfo.RegionSettings.TerrainImageID;
  1405. asset.Data = data;
  1406. asset.Name = "terrainImage_" + m_regInfo.RegionID.ToString() + "_" + lastMapRefresh.ToString();
  1407. asset.Description = RegionInfo.RegionName;
  1408. asset.Type = 0;
  1409. asset.Temporary = temporary;
  1410. AssetCache.AddAsset(asset);
  1411. }
  1412. #endregion
  1413. #region Load Land
  1414. public void loadAllLandObjectsFromStorage(UUID regionID)
  1415. {
  1416. m_log.Info("[SCENE]: Loading land objects from storage");
  1417. List<LandData> landData = m_storageManager.DataStore.LoadLandObjects(regionID);
  1418. if (LandChannel != null)
  1419. {
  1420. if (landData.Count == 0)
  1421. {
  1422. EventManager.TriggerNoticeNoLandDataFromStorage();
  1423. }
  1424. else
  1425. {
  1426. EventManager.TriggerIncomingLandDataFromStorage(landData);
  1427. }
  1428. }
  1429. else
  1430. {
  1431. m_log.Error("[SCENE]: Land Channel is not defined. Cannot load from storage!");
  1432. }
  1433. }
  1434. #endregion
  1435. #region Primitives Methods
  1436. /// <summary>
  1437. /// Loads the World's objects
  1438. /// </summary>
  1439. public virtual void LoadPrimsFromStorage(UUID regionID)
  1440. {
  1441. m_log.Info("[SCENE]: Loading objects from datastore");
  1442. List<SceneObjectGroup> PrimsFromDB = m_storageManager.DataStore.LoadObjects(regionID);
  1443. foreach (SceneObjectGroup group in PrimsFromDB)
  1444. {
  1445. if (group.RootPart == null)
  1446. {
  1447. m_log.ErrorFormat("[SCENE] Found a SceneObjectGroup with m_rootPart == null and {0} children",
  1448. group.Children == null ? 0 : group.Children.Count);
  1449. }
  1450. AddRestoredSceneObject(group, true, true);
  1451. SceneObjectPart rootPart = group.GetChildPart(group.UUID);
  1452. rootPart.ObjectFlags &= ~(uint)PrimFlags.Scripted;
  1453. rootPart.TrimPermissions();
  1454. group.CheckSculptAndLoad();
  1455. //rootPart.DoPhysicsPropertyUpdate(UsePhysics, true);
  1456. }
  1457. m_log.Info("[SCENE]: Loaded " + PrimsFromDB.Count.ToString() + " SceneObject(s)");
  1458. }
  1459. public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter)
  1460. {
  1461. Vector3 pos = Vector3.Zero;
  1462. if (RayEndIsIntersection == (byte)1)
  1463. {
  1464. pos = RayEnd;
  1465. return pos;
  1466. }
  1467. if (RayTargetID != UUID.Zero)
  1468. {
  1469. SceneObjectPart target = GetSceneObjectPart(RayTargetID);
  1470. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  1471. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  1472. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  1473. if (target != null)
  1474. {
  1475. pos = target.AbsolutePosition;
  1476. //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());
  1477. // TODO: Raytrace better here
  1478. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  1479. Ray NewRay = new Ray(AXOrigin, AXdirection);
  1480. // Ray Trace against target here
  1481. EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter);
  1482. // Un-comment out the following line to Get Raytrace results printed to the console.
  1483. // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1484. float ScaleOffset = 0.5f;
  1485. // If we hit something
  1486. if (ei.HitTF)
  1487. {
  1488. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  1489. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  1490. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  1491. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  1492. ScaleOffset = Math.Abs(ScaleOffset);
  1493. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  1494. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  1495. // Set the position to the intersection point
  1496. Vector3 offset = (normal * (ScaleOffset / 2f));
  1497. pos = (intersectionpoint + offset);
  1498. // Un-offset the prim (it gets offset later by the consumer method)
  1499. pos.Z -= 0.25F;
  1500. }
  1501. return pos;
  1502. }
  1503. else
  1504. {
  1505. // We don't have a target here, so we're going to raytrace all the objects in the scene.
  1506. EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false);
  1507. // Un-comment the following line to print the raytrace results to the console.
  1508. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1509. if (ei.HitTF)
  1510. {
  1511. pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  1512. } else
  1513. {
  1514. // fall back to our stupid functionality
  1515. pos = RayEnd;
  1516. }
  1517. return pos;
  1518. }
  1519. }
  1520. else
  1521. {
  1522. // fall back to our stupid functionality
  1523. pos = RayEnd;
  1524. return pos;
  1525. }
  1526. }
  1527. public virtual void AddNewPrim(UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot, PrimitiveBaseShape shape,
  1528. byte bypassRaycast, Vector3 RayStart, UUID RayTargetID,
  1529. byte RayEndIsIntersection)
  1530. {
  1531. Vector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection, true, new Vector3(0.5f, 0.5f, 0.5f), false);
  1532. if (Permissions.CanRezObject(1, ownerID, pos))
  1533. {
  1534. // rez ON the ground, not IN the ground
  1535. pos.Z += 0.25F;
  1536. AddNewPrim(ownerID, groupID, pos, rot, shape);
  1537. }
  1538. }
  1539. public virtual SceneObjectGroup AddNewPrim(
  1540. UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
  1541. {
  1542. //m_log.DebugFormat(
  1543. // "[SCENE]: Scene.AddNewPrim() pcode {0} called for {1} in {2}", shape.PCode, ownerID, RegionInfo.RegionName);
  1544. // If an entity creator has been registered for this prim type then use that
  1545. if (m_entityCreators.ContainsKey((PCode)shape.PCode))
  1546. return m_entityCreators[(PCode)shape.PCode].CreateEntity(ownerID, groupID, pos, rot, shape);
  1547. // Otherwise, use this default creation code;
  1548. SceneObjectGroup sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
  1549. AddNewSceneObject(sceneObject, true);
  1550. sceneObject.SetGroup(groupID, null);
  1551. return sceneObject;
  1552. }
  1553. /// <summary>
  1554. /// Add an object into the scene that has come from storage
  1555. /// </summary>
  1556. /// <param name="sceneObject"></param>
  1557. /// <param name="attachToBackup">
  1558. /// If true, changes to the object will be reflected in its persisted data
  1559. /// If false, the persisted data will not be changed even if the object in the scene is changed
  1560. /// </param>
  1561. /// <param name="alreadyPersisted">
  1562. /// If true, we won't persist this object until it changes
  1563. /// If false, we'll persist this object immediately
  1564. /// </param>
  1565. /// <returns>
  1566. /// true if the object was added, false if an object with the same uuid was already in the scene
  1567. /// </returns>
  1568. public bool AddRestoredSceneObject(
  1569. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted)
  1570. {
  1571. return m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted);
  1572. }
  1573. /// <summary>
  1574. /// Add a newly created object to the scene
  1575. /// </summary>
  1576. /// <param name="sceneObject"></param>
  1577. /// <param name="attachToBackup">
  1578. /// If true, the object is made persistent into the scene.
  1579. /// If false, the object will not persist over server restarts
  1580. /// </param>
  1581. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup)
  1582. {
  1583. return m_sceneGraph.AddNewSceneObject(sceneObject, attachToBackup);
  1584. }
  1585. /// <summary>
  1586. /// Delete every object from the scene
  1587. /// </summary>
  1588. public void DeleteAllSceneObjects()
  1589. {
  1590. lock (Entities)
  1591. {
  1592. ICollection<EntityBase> entities = new List<EntityBase>(Entities);
  1593. foreach (EntityBase e in entities)
  1594. {
  1595. if (e is SceneObjectGroup)
  1596. DeleteSceneObject((SceneObjectGroup)e, false);
  1597. }
  1598. }
  1599. }
  1600. /// <summary>
  1601. /// Synchronously delete the given object from the scene.
  1602. /// </summary>
  1603. /// <param name="group"></param>
  1604. public void DeleteSceneObject(SceneObjectGroup group, bool silent)
  1605. {
  1606. //SceneObjectPart rootPart = group.GetChildPart(group.UUID);
  1607. // Serialise calls to RemoveScriptInstances to avoid
  1608. // deadlocking on m_parts inside SceneObjectGroup
  1609. lock (m_deleting_scene_object)
  1610. {
  1611. group.RemoveScriptInstances();
  1612. }
  1613. foreach (SceneObjectPart part in group.Children.Values)
  1614. {
  1615. if (part.IsJoint() && ((part.ObjectFlags&(uint)PrimFlags.Physics) != 0) )
  1616. {
  1617. PhysicsScene.RequestJointDeletion(part.Name); // FIXME: what if the name changed?
  1618. }
  1619. else if (part.PhysActor != null)
  1620. {
  1621. PhysicsScene.RemovePrim(part.PhysActor);
  1622. part.PhysActor = null;
  1623. }
  1624. }
  1625. // if (rootPart.PhysActor != null)
  1626. // {
  1627. // PhysicsScene.RemovePrim(rootPart.PhysActor);
  1628. // rootPart.PhysActor = null;
  1629. // }
  1630. if (UnlinkSceneObject(group.UUID, false))
  1631. {
  1632. EventManager.TriggerObjectBeingRemovedFromScene(group);
  1633. EventManager.TriggerParcelPrimCountTainted();
  1634. }
  1635. group.DeleteGroup(silent);
  1636. }
  1637. /// <summary>
  1638. /// Unlink the given object from the scene. Unlike delete, this just removes the record of the object - the
  1639. /// object itself is not destroyed.
  1640. /// </summary>
  1641. /// <param name="uuid"></param>
  1642. /// <returns>true if the object was in the scene, false if it was not</returns>
  1643. public bool UnlinkSceneObject(UUID uuid, bool resultOfLinkingObjects)
  1644. {
  1645. if (m_sceneGraph.DeleteSceneObject(uuid, resultOfLinkingObjects))
  1646. {
  1647. if (!resultOfLinkingObjects)
  1648. m_storageManager.DataStore.RemoveObject(uuid,
  1649. m_regInfo.RegionID);
  1650. return true;
  1651. }
  1652. return false;
  1653. }
  1654. /// <summary>
  1655. /// Move the given scene object into a new region depending on which region its absolute position has moved
  1656. /// into.
  1657. ///
  1658. /// This method locates the new region handle and offsets the prim position for the new region
  1659. /// </summary>
  1660. /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
  1661. /// <param name="grp">the scene object that we're crossing</param>
  1662. public void CrossPrimGroupIntoNewRegion(Vector3 attemptedPosition, SceneObjectGroup grp, bool silent)
  1663. {
  1664. if (grp == null)
  1665. return;
  1666. if (grp.IsDeleted)
  1667. return;
  1668. if (grp.RootPart.DIE_AT_EDGE)
  1669. {
  1670. // We remove the object here
  1671. try
  1672. {
  1673. DeleteSceneObject(grp, false);
  1674. }
  1675. catch (Exception)
  1676. {
  1677. m_log.Warn("[DATABASE]: exception when trying to remove the prim that crossed the border.");
  1678. }
  1679. return;
  1680. }
  1681. int thisx = (int)RegionInfo.RegionLocX;
  1682. int thisy = (int)RegionInfo.RegionLocY;
  1683. ulong newRegionHandle = 0;
  1684. Vector3 pos = attemptedPosition;
  1685. if (attemptedPosition.X > Constants.RegionSize + 0.1f)
  1686. {
  1687. pos.X = ((pos.X - Constants.RegionSize));
  1688. newRegionHandle
  1689. = Util.UIntsToLong((uint)((thisx + 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize));
  1690. // x + 1
  1691. }
  1692. else if (attemptedPosition.X < -0.1f)
  1693. {
  1694. pos.X = ((pos.X + Constants.RegionSize));
  1695. newRegionHandle
  1696. = Util.UIntsToLong((uint)((thisx - 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize));
  1697. // x - 1
  1698. }
  1699. if (attemptedPosition.Y > Constants.RegionSize + 0.1f)
  1700. {
  1701. pos.Y = ((pos.Y - Constants.RegionSize));
  1702. newRegionHandle
  1703. = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy + 1) * Constants.RegionSize));
  1704. // y + 1
  1705. }
  1706. else if (attemptedPosition.Y < -0.1f)
  1707. {
  1708. pos.Y = ((pos.Y + Constants.RegionSize));
  1709. newRegionHandle
  1710. = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy - 1) * Constants.RegionSize));
  1711. // y - 1
  1712. }
  1713. // Offset the positions for the new region across the border
  1714. Vector3 oldGroupPosition = grp.RootPart.GroupPosition;
  1715. grp.OffsetForNewRegion(pos);
  1716. // If we fail to cross the border, then reset the position of the scene object on that border.
  1717. if (!CrossPrimGroupIntoNewRegion(newRegionHandle, grp, silent))
  1718. {
  1719. grp.OffsetForNewRegion(oldGroupPosition);
  1720. grp.ScheduleGroupForFullUpdate();
  1721. }
  1722. }
  1723. /// <summary>
  1724. /// Move the given scene object into a new region
  1725. /// </summary>
  1726. /// <param name="newRegionHandle"></param>
  1727. /// <param name="grp">Scene Object Group that we're crossing</param>
  1728. /// <returns>
  1729. /// true if the crossing itself was successful, false on failure
  1730. /// FIMXE: we still return true if the crossing object was not successfully deleted from the originating region
  1731. /// </returns>
  1732. public bool CrossPrimGroupIntoNewRegion(ulong newRegionHandle, SceneObjectGroup grp, bool silent)
  1733. {
  1734. bool successYN = false;
  1735. grp.RootPart.UpdateFlag = 0;
  1736. int primcrossingXMLmethod = 0;
  1737. if (newRegionHandle != 0)
  1738. {
  1739. string objectState = grp.GetStateSnapshot();
  1740. successYN
  1741. = m_sceneGridService.PrimCrossToNeighboringRegion(
  1742. newRegionHandle, grp.UUID, m_serialiser.SaveGroupToXml2(grp), primcrossingXMLmethod);
  1743. if (successYN && (objectState != "") && m_allowScriptCrossings)
  1744. {
  1745. successYN = m_sceneGridService.PrimCrossToNeighboringRegion(
  1746. newRegionHandle, grp.UUID, objectState, 100);
  1747. }
  1748. if (successYN)
  1749. {
  1750. // We remove the object here
  1751. try
  1752. {
  1753. DeleteSceneObject(grp, silent);
  1754. }
  1755. catch (Exception e)
  1756. {
  1757. m_log.ErrorFormat(
  1758. "[INTERREGION]: Exception deleting the old object left behind on a border crossing for {0}, {1}",
  1759. grp, e);
  1760. }
  1761. }
  1762. else
  1763. {
  1764. if (!grp.IsDeleted)
  1765. {
  1766. if (grp.RootPart.PhysActor != null)
  1767. {
  1768. grp.RootPart.PhysActor.CrossingFailure();
  1769. }
  1770. }
  1771. m_log.ErrorFormat("[INTERREGION]: Prim crossing failed for {0}", grp);
  1772. }
  1773. }
  1774. else
  1775. {
  1776. m_log.Error("[INTERREGION]: region handle was unexpectedly 0 in Scene.CrossPrimGroupIntoNewRegion()");
  1777. }
  1778. return successYN;
  1779. }
  1780. /// <summary>
  1781. /// Handle a scene object that is crossing into this region from another.
  1782. /// </summary>
  1783. /// <param name="regionHandle"></param>
  1784. /// <param name="primID"></param>
  1785. /// <param name="objXMLData"></param>
  1786. /// <param name="XMLMethod"></param>
  1787. /// <returns></returns>
  1788. public bool IncomingInterRegionPrimGroup(UUID primID, string objXMLData, int XMLMethod)
  1789. {
  1790. if (XMLMethod == 0)
  1791. {
  1792. m_log.DebugFormat("[INTERREGION]: A new prim {0} arrived from a neighbor", primID);
  1793. SceneObjectGroup sceneObject = m_serialiser.DeserializeGroupFromXml2(objXMLData);
  1794. // If the user is banned, we won't let any of their objects
  1795. // enter. Period.
  1796. //
  1797. if (m_regInfo.EstateSettings.IsBanned(sceneObject.OwnerID))
  1798. {
  1799. m_log.Info("[INTERREGION]: Denied prim crossing for "+
  1800. "banned avatar");
  1801. return false;
  1802. }
  1803. // Force allocation of new LocalId
  1804. //
  1805. foreach (SceneObjectPart p in sceneObject.Children.Values)
  1806. p.LocalId = 0;
  1807. if (sceneObject.RootPart.Shape.PCode == (byte)PCode.Prim)
  1808. {
  1809. if (sceneObject.RootPart.Shape.State != 0)
  1810. {
  1811. // Fix up attachment Parent Local ID
  1812. //
  1813. ScenePresence sp = GetScenePresence(sceneObject.OwnerID);
  1814. uint parentLocalID = 0;
  1815. if (sp != null)
  1816. parentLocalID = sp.LocalId;
  1817. sceneObject.RootPart.IsAttachment = true;
  1818. sceneObject.RootPart.SetParentLocalId(parentLocalID);
  1819. AddRestoredSceneObject(sceneObject, false, false);
  1820. // Handle attachment special case
  1821. //
  1822. SceneObjectPart RootPrim = GetSceneObjectPart(primID);
  1823. if (RootPrim != null)
  1824. {
  1825. SceneObjectGroup grp = RootPrim.ParentGroup;
  1826. RootPrim.SetParentLocalId(parentLocalID);
  1827. if (grp != null)
  1828. {
  1829. m_log.DebugFormat("[ATTACHMENT]: Received "+
  1830. "attachment {0}, inworld asset id {1}",
  1831. grp.RootPart.LastOwnerID.ToString(),
  1832. grp.UUID.ToString());
  1833. if (sp != null)
  1834. {
  1835. grp.SetFromAssetID(grp.RootPart.LastOwnerID);
  1836. m_log.DebugFormat("[ATTACHMENT]: Attach "+
  1837. "to avatar {0}",
  1838. sp.UUID.ToString());
  1839. AttachObject(sp.ControllingClient,
  1840. grp.LocalId, (uint)0,
  1841. grp.GroupRotation,
  1842. grp.AbsolutePosition, false);
  1843. grp.SendGroupFullUpdate();
  1844. }
  1845. else
  1846. {
  1847. RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  1848. RootPrim.AddFlag(PrimFlags.TemporaryOnRez);
  1849. }
  1850. }
  1851. }
  1852. }
  1853. else
  1854. {
  1855. AddRestoredSceneObject(sceneObject, true, false);
  1856. if (!Permissions.CanObjectEntry(sceneObject.UUID,
  1857. true, sceneObject.AbsolutePosition))
  1858. {
  1859. // Deny non attachments based on parcel settings
  1860. //
  1861. m_log.Info("[INTERREGION]: Denied prim crossing "+
  1862. "because of parcel settings");
  1863. DeleteSceneObject(sceneObject, false);
  1864. return false;
  1865. }
  1866. }
  1867. }
  1868. }
  1869. else if ((XMLMethod == 100) && m_allowScriptCrossings)
  1870. {
  1871. m_log.Warn("[INTERREGION]: Prim state data arrived from a neighbor");
  1872. XmlDocument doc = new XmlDocument();
  1873. doc.LoadXml(objXMLData);
  1874. XmlNodeList rootL = doc.GetElementsByTagName("ScriptData");
  1875. if (rootL.Count == 1)
  1876. {
  1877. XmlNode rootNode = rootL[0];
  1878. if (rootNode != null)
  1879. {
  1880. XmlNodeList partL = rootNode.ChildNodes;
  1881. foreach (XmlNode part in partL)
  1882. {
  1883. XmlNodeList nodeL = part.ChildNodes;
  1884. switch (part.Name)
  1885. {
  1886. case "Assemblies":
  1887. foreach (XmlNode asm in nodeL)
  1888. {
  1889. string fn = asm.Attributes.GetNamedItem("Filename").Value;
  1890. Byte[] filedata = Convert.FromBase64String(asm.InnerText);
  1891. string path = Path.Combine("ScriptEngines", RegionInfo.RegionID.ToString());
  1892. path = Path.Combine(path, fn);
  1893. if (!File.Exists(path))
  1894. {
  1895. FileStream fs = File.Create(path);
  1896. fs.Write(filedata, 0, filedata.Length);
  1897. fs.Close();
  1898. }
  1899. }
  1900. break;
  1901. case "ScriptStates":
  1902. foreach (XmlNode st in nodeL)
  1903. {
  1904. string id = st.Attributes.GetNamedItem("UUID").Value;
  1905. UUID uuid = new UUID(id);
  1906. XmlNode state = st.ChildNodes[0];
  1907. XmlDocument sdoc = new XmlDocument();
  1908. XmlNode sxmlnode = sdoc.CreateNode(
  1909. XmlNodeType.XmlDeclaration,
  1910. "", "");
  1911. sdoc.AppendChild(sxmlnode);
  1912. XmlNode newnode = sdoc.ImportNode(state, true);
  1913. sdoc.AppendChild(newnode);
  1914. string spath = Path.Combine("ScriptEngines", RegionInfo.RegionID.ToString());
  1915. spath = Path.Combine(spath, uuid.ToString());
  1916. FileStream sfs = File.Create(spath + ".state");
  1917. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  1918. Byte[] buf = enc.GetBytes(sdoc.InnerXml);
  1919. sfs.Write(buf, 0, buf.Length);
  1920. sfs.Close();
  1921. }
  1922. break;
  1923. }
  1924. }
  1925. }
  1926. }
  1927. SceneObjectPart RootPrim = GetSceneObjectPart(primID);
  1928. RootPrim.ParentGroup.CreateScriptInstances(0, false, DefaultScriptEngine, 1);
  1929. return true;
  1930. }
  1931. return true;
  1932. }
  1933. #endregion
  1934. #region Add/Remove Avatar Methods
  1935. public override void AddNewClient(IClientAPI client)
  1936. {
  1937. SubscribeToClientEvents(client);
  1938. ScenePresence presence;
  1939. if (m_restorePresences.ContainsKey(client.AgentId))
  1940. {
  1941. m_log.DebugFormat("[SCENE]: Restoring agent {0} {1} in {2}", client.Name, client.AgentId, RegionInfo.RegionName);
  1942. presence = m_restorePresences[client.AgentId];
  1943. m_restorePresences.Remove(client.AgentId);
  1944. // This is one of two paths to create avatars that are
  1945. // used. This tends to get called more in standalone
  1946. // than grid, not really sure why, but as such needs
  1947. // an explicity appearance lookup here.
  1948. AvatarAppearance appearance = null;
  1949. GetAvatarAppearance(client, out appearance);
  1950. presence.Appearance = appearance;
  1951. presence.initializeScenePresence(client, RegionInfo, this);
  1952. m_sceneGraph.AddScenePresence(presence);
  1953. lock (m_restorePresences)
  1954. {
  1955. Monitor.PulseAll(m_restorePresences);
  1956. }
  1957. }
  1958. else
  1959. {
  1960. m_log.DebugFormat(
  1961. "[SCENE]: Adding new child agent {0} for new user connection in {1}",
  1962. client.Name, RegionInfo.RegionName);
  1963. CommsManager.UserProfileCacheService.AddNewUser(client.AgentId);
  1964. CreateAndAddScenePresence(client);
  1965. }
  1966. m_LastLogin = System.Environment.TickCount;
  1967. EventManager.TriggerOnNewClient(client);
  1968. }
  1969. protected virtual void SubscribeToClientEvents(IClientAPI client)
  1970. {
  1971. client.OnRegionHandShakeReply += SendLayerData;
  1972. client.OnAddPrim += AddNewPrim;
  1973. client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimPosition;
  1974. client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition;
  1975. client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimRotation;
  1976. client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimRotation;
  1977. client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation;
  1978. client.OnUpdatePrimScale += m_sceneGraph.UpdatePrimScale;
  1979. client.OnUpdatePrimGroupScale += m_sceneGraph.UpdatePrimGroupScale;
  1980. client.OnUpdateExtraParams += m_sceneGraph.UpdateExtraParam;
  1981. client.OnUpdatePrimShape += m_sceneGraph.UpdatePrimShape;
  1982. client.OnUpdatePrimTexture += m_sceneGraph.UpdatePrimTexture;
  1983. client.OnTeleportLocationRequest += RequestTeleportLocation;
  1984. client.OnTeleportLandmarkRequest += RequestTeleportLandmark;
  1985. client.OnObjectSelect += SelectPrim;
  1986. client.OnObjectDeselect += DeselectPrim;
  1987. client.OnGrabUpdate += m_sceneGraph.MoveObject;
  1988. client.OnDeRezObject += DeRezObject;
  1989. client.OnRezObject += RezObject;
  1990. client.OnRezSingleAttachmentFromInv += RezSingleAttachment;
  1991. client.OnDetachAttachmentIntoInv += DetachSingleAttachmentToInv;
  1992. client.OnObjectAttach += m_sceneGraph.AttachObject;
  1993. client.OnObjectDetach += m_sceneGraph.DetachObject;
  1994. client.OnObjectDrop += m_sceneGraph.DropObject;
  1995. client.OnNameFromUUIDRequest += CommsManager.HandleUUIDNameRequest;
  1996. client.OnObjectDescription += m_sceneGraph.PrimDescription;
  1997. client.OnObjectName += m_sceneGraph.PrimName;
  1998. client.OnObjectClickAction += m_sceneGraph.PrimClickAction;
  1999. client.OnObjectMaterial += m_sceneGraph.PrimMaterial;
  2000. client.OnLinkObjects += m_sceneGraph.LinkObjects;
  2001. client.OnDelinkObjects += m_sceneGraph.DelinkObjects;
  2002. client.OnObjectDuplicate += m_sceneGraph.DuplicateObject;
  2003. client.OnObjectDuplicateOnRay += doObjectDuplicateOnRay;
  2004. client.OnUpdatePrimFlags += m_sceneGraph.UpdatePrimFlags;
  2005. client.OnRequestObjectPropertiesFamily += m_sceneGraph.RequestObjectPropertiesFamily;
  2006. client.OnRequestGodlikePowers += handleRequestGodlikePowers;
  2007. client.OnGodKickUser += HandleGodlikeKickUser;
  2008. client.OnObjectPermissions += HandleObjectPermissionsUpdate;
  2009. client.OnCreateNewInventoryItem += CreateNewInventoryItem;
  2010. client.OnCreateNewInventoryFolder += HandleCreateInventoryFolder;
  2011. client.OnUpdateInventoryFolder += HandleUpdateInventoryFolder;
  2012. client.OnMoveInventoryFolder += HandleMoveInventoryFolder;
  2013. client.OnFetchInventoryDescendents += HandleFetchInventoryDescendents;
  2014. client.OnPurgeInventoryDescendents += HandlePurgeInventoryDescendents;
  2015. client.OnFetchInventory += HandleFetchInventory;
  2016. client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
  2017. client.OnCopyInventoryItem += CopyInventoryItem;
  2018. client.OnMoveInventoryItem += MoveInventoryItem;
  2019. client.OnRemoveInventoryItem += RemoveInventoryItem;
  2020. client.OnRemoveInventoryFolder += RemoveInventoryFolder;
  2021. client.OnRezScript += RezScript;
  2022. client.OnRequestTaskInventory += RequestTaskInventory;
  2023. client.OnRemoveTaskItem += RemoveTaskInventory;
  2024. client.OnUpdateTaskInventory += UpdateTaskInventory;
  2025. client.OnMoveTaskItem += ClientMoveTaskInventoryItem;
  2026. client.OnGrabObject += ProcessObjectGrab;
  2027. client.OnDeGrabObject += ProcessObjectDeGrab;
  2028. client.OnMoneyTransferRequest += ProcessMoneyTransferRequest;
  2029. client.OnParcelBuy += ProcessParcelBuy;
  2030. client.OnAvatarPickerRequest += ProcessAvatarPickerRequest;
  2031. client.OnObjectIncludeInSearch += m_sceneGraph.MakeObjectSearchable;
  2032. client.OnTeleportHomeRequest += TeleportClientHome;
  2033. client.OnSetStartLocationRequest += SetHomeRezPoint;
  2034. client.OnUndo += m_sceneGraph.HandleUndo;
  2035. client.OnObjectGroupRequest += m_sceneGraph.HandleObjectGroupUpdate;
  2036. client.OnParcelReturnObjectsRequest += LandChannel.ReturnObjectsInParcel;
  2037. client.OnParcelSetOtherCleanTime += LandChannel.SetParcelOtherCleanTime;
  2038. client.OnObjectSaleInfo += ObjectSaleInfo;
  2039. client.OnScriptReset += ProcessScriptReset;
  2040. client.OnGetScriptRunning += GetScriptRunning;
  2041. client.OnSetScriptRunning += SetScriptRunning;
  2042. client.OnRegionHandleRequest += RegionHandleRequest;
  2043. client.OnUnackedTerrain += TerrainUnAcked;
  2044. client.OnObjectOwner += ObjectOwner;
  2045. if (StatsReporter != null)
  2046. client.OnNetworkStatsUpdate += StatsReporter.AddPacketsFromClientStats;
  2047. // EventManager.TriggerOnNewClient(client);
  2048. }
  2049. /// <summary>
  2050. /// Teleport an avatar to their home region
  2051. /// </summary>
  2052. /// <param name="agentId"></param>
  2053. /// <param name="client"></param>
  2054. public virtual void TeleportClientHome(UUID agentId, IClientAPI client)
  2055. {
  2056. UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(agentId);
  2057. if (UserProfile != null)
  2058. {
  2059. RegionInfo regionInfo = CommsManager.GridService.RequestNeighbourInfo(UserProfile.HomeRegionID);
  2060. if (regionInfo == null)
  2061. {
  2062. regionInfo = CommsManager.GridService.RequestNeighbourInfo(UserProfile.HomeRegion);
  2063. if (regionInfo != null) // home region can be away temporarily, too
  2064. {
  2065. UserProfile.HomeRegionID = regionInfo.RegionID;
  2066. CommsManager.UserService.UpdateUserProfile(UserProfile);
  2067. }
  2068. }
  2069. if (regionInfo == null)
  2070. {
  2071. // can't find the Home region: Tell viewer and abort
  2072. client.SendTeleportFailed("Your home-region could not be found.");
  2073. return;
  2074. }
  2075. RequestTeleportLocation(
  2076. client, regionInfo.RegionHandle, UserProfile.HomeLocation, UserProfile.HomeLookAt,
  2077. (uint)(TPFlags.SetLastToTarget | TPFlags.ViaHome));
  2078. }
  2079. }
  2080. public void doObjectDuplicateOnRay(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID,
  2081. UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart,
  2082. bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates)
  2083. {
  2084. Vector3 pos;
  2085. const bool frontFacesOnly = true;
  2086. //m_log.Info("HITTARGET: " + RayTargetObj.ToString() + ", COPYTARGET: " + localID.ToString());
  2087. SceneObjectPart target = GetSceneObjectPart(localID);
  2088. SceneObjectPart target2 = GetSceneObjectPart(RayTargetObj);
  2089. if (target != null && target2 != null)
  2090. {
  2091. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  2092. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  2093. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  2094. if (target2.ParentGroup != null)
  2095. {
  2096. pos = target2.AbsolutePosition;
  2097. //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());
  2098. // TODO: Raytrace better here
  2099. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  2100. Ray NewRay = new Ray(AXOrigin, AXdirection);
  2101. // Ray Trace against target here
  2102. EntityIntersection ei = target2.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, CopyCenters);
  2103. // Un-comment out the following line to Get Raytrace results printed to the console.
  2104. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  2105. float ScaleOffset = 0.5f;
  2106. // If we hit something
  2107. if (ei.HitTF)
  2108. {
  2109. Vector3 scale = target.Scale;
  2110. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  2111. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  2112. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  2113. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  2114. ScaleOffset = Math.Abs(ScaleOffset);
  2115. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  2116. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  2117. Vector3 offset = normal * (ScaleOffset / 2f);
  2118. pos = intersectionpoint + offset;
  2119. // stick in offset format from the original prim
  2120. pos = pos - target.ParentGroup.AbsolutePosition;
  2121. if (CopyRotates)
  2122. {
  2123. Quaternion worldRot = target2.GetWorldRotation();
  2124. // SceneObjectGroup obj = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  2125. m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  2126. //obj.Rotation = worldRot;
  2127. //obj.UpdateGroupRotation(worldRot);
  2128. }
  2129. else
  2130. {
  2131. m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID);
  2132. }
  2133. }
  2134. return;
  2135. }
  2136. return;
  2137. }
  2138. }
  2139. public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags)
  2140. {
  2141. UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(remoteClient.AgentId);
  2142. if (UserProfile != null)
  2143. {
  2144. // I know I'm ignoring the regionHandle provided by the teleport location request.
  2145. // reusing the TeleportLocationRequest delegate, so regionHandle isn't valid
  2146. UserProfile.HomeRegionID = RegionInfo.RegionID;
  2147. // TODO: The next line can be removed, as soon as only homeRegionID based UserServers are around.
  2148. // TODO: The HomeRegion property can be removed then, too
  2149. UserProfile.HomeRegion = RegionInfo.RegionHandle;
  2150. UserProfile.HomeLocation = position;
  2151. UserProfile.HomeLookAt = lookAt;
  2152. CommsManager.UserService.UpdateUserProfile(UserProfile);
  2153. // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot.
  2154. remoteClient.SendAgentAlertMessage("Home position set.",false);
  2155. }
  2156. else
  2157. {
  2158. remoteClient.SendAgentAlertMessage("Set Home request Failed",false);
  2159. }
  2160. }
  2161. /// <summary>
  2162. /// Create a child agent scene presence and add it to this scene.
  2163. /// </summary>
  2164. /// <param name="client"></param>
  2165. /// <returns></returns>
  2166. protected virtual ScenePresence CreateAndAddScenePresence(IClientAPI client)
  2167. {
  2168. AvatarAppearance appearance = null;
  2169. GetAvatarAppearance(client, out appearance);
  2170. ScenePresence avatar = m_sceneGraph.CreateAndAddChildScenePresence(client, appearance);
  2171. //avatar.KnownRegions = GetChildrenSeeds(avatar.UUID);
  2172. return avatar;
  2173. }
  2174. /// <summary>
  2175. /// Get the avatar apperance for the given client.
  2176. /// </summary>
  2177. /// <param name="client"></param>
  2178. /// <param name="appearance"></param>
  2179. public void GetAvatarAppearance(IClientAPI client, out AvatarAppearance appearance)
  2180. {
  2181. appearance = new AvatarAppearance();
  2182. try
  2183. {
  2184. if (m_AvatarFactory != null)
  2185. {
  2186. if (m_AvatarFactory.TryGetAvatarAppearance(client.AgentId, out appearance))
  2187. return;
  2188. }
  2189. }
  2190. catch (Exception e)
  2191. {
  2192. m_log.ErrorFormat("[APPEARANCE]: Problem fetching appearance for avatar {0}, {1}",
  2193. client.Name, e);
  2194. }
  2195. m_log.Warn("[APPEARANCE]: Appearance not found, returning default");
  2196. }
  2197. /// <summary>
  2198. /// Remove the given client from the scene.
  2199. /// </summary>
  2200. /// <param name="agentID"></param>
  2201. public override void RemoveClient(UUID agentID)
  2202. {
  2203. bool childagentYN = false;
  2204. ScenePresence avatar = GetScenePresence(agentID);
  2205. if (avatar != null)
  2206. {
  2207. childagentYN = avatar.IsChildAgent;
  2208. }
  2209. try
  2210. {
  2211. m_log.DebugFormat(
  2212. "[SCENE]: Removing {0} agent {1} from region {2}",
  2213. (childagentYN ? "child" : "root"), agentID, RegionInfo.RegionName);
  2214. m_sceneGraph.removeUserCount(!childagentYN);
  2215. RemoveCapsHandler(agentID);
  2216. if (avatar.Scene.NeedSceneCacheClear(avatar.UUID))
  2217. {
  2218. m_log.InfoFormat("[SCENE]: User {0} is going to another region, profile cache removed in {1}", avatar.UUID, RegionInfo.RegionName);
  2219. CommsManager.UserProfileCacheService.RemoveUser(agentID);
  2220. }
  2221. if (!avatar.IsChildAgent)
  2222. {
  2223. m_sceneGridService.LogOffUser(agentID, RegionInfo.RegionID, RegionInfo.RegionHandle, avatar.AbsolutePosition, avatar.Lookat);
  2224. //List<ulong> childknownRegions = new List<ulong>();
  2225. //List<ulong> ckn = avatar.KnownChildRegionHandles;
  2226. //for (int i = 0; i < ckn.Count; i++)
  2227. //{
  2228. // childknownRegions.Add(ckn[i]);
  2229. //}
  2230. List<ulong> regions = new List<ulong>(avatar.KnownChildRegionHandles);
  2231. regions.Remove(RegionInfo.RegionHandle);
  2232. m_sceneGridService.SendCloseChildAgentConnections(agentID, regions);
  2233. }
  2234. m_eventManager.TriggerClientClosed(agentID);
  2235. }
  2236. catch (NullReferenceException)
  2237. {
  2238. // We don't know which count to remove it from
  2239. // Avatar is already disposed :/
  2240. }
  2241. m_eventManager.TriggerOnRemovePresence(agentID);
  2242. Broadcast(delegate(IClientAPI client)
  2243. {
  2244. try
  2245. {
  2246. client.SendKillObject(avatar.RegionHandle, avatar.LocalId);
  2247. }
  2248. catch (NullReferenceException)
  2249. {
  2250. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  2251. }
  2252. });
  2253. ForEachScenePresence(
  2254. delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  2255. IAgentAssetTransactions agentTransactions = this.RequestModuleInterface<IAgentAssetTransactions>();
  2256. if (agentTransactions != null)
  2257. {
  2258. agentTransactions.RemoveAgentAssetTransactions(agentID);
  2259. }
  2260. m_sceneGraph.RemoveScenePresence(agentID);
  2261. try
  2262. {
  2263. avatar.Close();
  2264. }
  2265. catch (NullReferenceException)
  2266. {
  2267. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  2268. }
  2269. catch (Exception e)
  2270. {
  2271. m_log.Error("[SCENE] Scene.cs:RemoveClient exception: " + e.ToString());
  2272. }
  2273. // Remove client agent from profile, so new logins will work
  2274. if (!childagentYN)
  2275. {
  2276. m_sceneGridService.ClearUserAgent(agentID);
  2277. }
  2278. //m_log.InfoFormat("[SCENE] Memory pre GC {0}", System.GC.GetTotalMemory(false));
  2279. //m_log.InfoFormat("[SCENE] Memory post GC {0}", System.GC.GetTotalMemory(true));
  2280. }
  2281. public void HandleRemoveKnownRegionsFromAvatar(UUID avatarID, List<ulong> regionslst)
  2282. {
  2283. ScenePresence av = GetScenePresence(avatarID);
  2284. if (av != null)
  2285. {
  2286. lock (av)
  2287. {
  2288. for (int i = 0; i < regionslst.Count; i++)
  2289. {
  2290. av.KnownChildRegionHandles.Remove(regionslst[i]);
  2291. }
  2292. }
  2293. }
  2294. }
  2295. public override void CloseAllAgents(uint circuitcode)
  2296. {
  2297. // Called by ClientView to kill all circuit codes
  2298. ClientManager.CloseAllAgents(circuitcode);
  2299. }
  2300. public void NotifyMyCoarseLocationChange()
  2301. {
  2302. ForEachScenePresence(delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  2303. }
  2304. #endregion
  2305. #region Entities
  2306. public void SendKillObject(uint localID)
  2307. {
  2308. SceneObjectPart part = GetSceneObjectPart(localID);
  2309. if (part != null) // It is a prim
  2310. {
  2311. if (part.ParentGroup != null && !part.ParentGroup.IsDeleted) // Valid
  2312. {
  2313. if (part.ParentGroup.RootPart != part) // Child part
  2314. return;
  2315. }
  2316. }
  2317. Broadcast(delegate(IClientAPI client) { client.SendKillObject(m_regionHandle, localID); });
  2318. }
  2319. #endregion
  2320. #region RegionComms
  2321. /// <summary>
  2322. /// Register the methods that should be invoked when this scene receives various incoming events
  2323. /// </summary>
  2324. public void RegisterCommsEvents()
  2325. {
  2326. m_sceneGridService.OnExpectUser += NewUserConnection;
  2327. m_sceneGridService.OnAvatarCrossingIntoRegion += AgentCrossing;
  2328. m_sceneGridService.OnCloseAgentConnection += IncomingCloseAgent;
  2329. m_sceneGridService.OnRegionUp += OtherRegionUp;
  2330. //m_sceneGridService.OnChildAgentUpdate += IncomingChildAgentDataUpdate;
  2331. m_sceneGridService.OnExpectPrim += IncomingInterRegionPrimGroup;
  2332. //m_sceneGridService.OnRemoveKnownRegionFromAvatar += HandleRemoveKnownRegionsFromAvatar;
  2333. m_sceneGridService.OnLogOffUser += HandleLogOffUserFromGrid;
  2334. m_sceneGridService.KiPrimitive += SendKillObject;
  2335. m_sceneGridService.OnGetLandData += GetLandData;
  2336. if (m_interregionCommsIn != null)
  2337. {
  2338. m_log.Debug("[SCENE]: Registering with InterregionCommsIn");
  2339. m_interregionCommsIn.OnChildAgentUpdate += IncomingChildAgentDataUpdate;
  2340. }
  2341. else
  2342. m_log.Debug("[SCENE]: Unable to register with InterregionCommsIn");
  2343. }
  2344. /// <summary>
  2345. /// Deregister this scene from receiving incoming region events
  2346. /// </summary>
  2347. public void UnRegisterRegionWithComms()
  2348. {
  2349. m_sceneGridService.KiPrimitive -= SendKillObject;
  2350. m_sceneGridService.OnLogOffUser -= HandleLogOffUserFromGrid;
  2351. //m_sceneGridService.OnRemoveKnownRegionFromAvatar -= HandleRemoveKnownRegionsFromAvatar;
  2352. m_sceneGridService.OnExpectPrim -= IncomingInterRegionPrimGroup;
  2353. //m_sceneGridService.OnChildAgentUpdate -= IncomingChildAgentDataUpdate;
  2354. m_sceneGridService.OnRegionUp -= OtherRegionUp;
  2355. m_sceneGridService.OnExpectUser -= NewUserConnection;
  2356. m_sceneGridService.OnAvatarCrossingIntoRegion -= AgentCrossing;
  2357. m_sceneGridService.OnCloseAgentConnection -= IncomingCloseAgent;
  2358. m_sceneGridService.OnGetLandData -= GetLandData;
  2359. if (m_interregionCommsIn != null)
  2360. m_interregionCommsIn.OnChildAgentUpdate -= IncomingChildAgentDataUpdate;
  2361. m_sceneGridService.Close();
  2362. }
  2363. /// <summary>
  2364. /// Do the work necessary to initiate a new user connection for a particular scene.
  2365. /// At the moment, this consists of setting up the caps infrastructure
  2366. /// </summary>
  2367. /// <param name="regionHandle"></param>
  2368. /// <param name="agent"></param>
  2369. public void NewUserConnection(AgentCircuitData agent)
  2370. {
  2371. if (m_regInfo.EstateSettings.IsBanned(agent.AgentID))
  2372. {
  2373. m_log.WarnFormat(
  2374. "[CONNECTION DEBUGGING]: Denied access to: {0} at {1} because the user is on the region banlist",
  2375. agent.AgentID, RegionInfo.RegionName);
  2376. }
  2377. /// Diva: Horrible stuff!
  2378. capsPaths[agent.AgentID] = agent.CapsPath;
  2379. childrenSeeds[agent.AgentID] = ((agent.ChildrenCapSeeds == null) ? new Dictionary<ulong, string>() : agent.ChildrenCapSeeds);
  2380. ScenePresence sp = m_sceneGraph.GetScenePresence(agent.AgentID);
  2381. if (sp != null)
  2382. {
  2383. m_log.DebugFormat("[CONNECTION DEBUGGING]: Updated agent {0} in {1}", agent.AgentID, RegionInfo.RegionName);
  2384. sp.AdjustKnownSeeds();
  2385. sp.AbsolutePosition = agent.startpos;
  2386. return;
  2387. }
  2388. m_log.DebugFormat("[CONNECTION DEBUGGING]: Adding NewUserConnection for {0} in {1} with CC of {2}, pos={3}", agent.AgentID,
  2389. RegionInfo.RegionName, agent.circuitcode, agent.startpos.ToString());
  2390. AddCapsHandler(agent.AgentID);
  2391. if (!agent.child)
  2392. {
  2393. // Honor parcel landing type and position.
  2394. ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
  2395. if (land != null)
  2396. {
  2397. if (land.landData.LandingType == (byte)1 && land.landData.UserLocation != Vector3.Zero)
  2398. {
  2399. agent.startpos = land.landData.UserLocation;
  2400. }
  2401. }
  2402. }
  2403. m_authenticateHandler.AddNewCircuit(agent.circuitcode, agent);
  2404. // rewrite session_id
  2405. CachedUserInfo userinfo = CommsManager.UserProfileCacheService.GetUserDetails(agent.AgentID);
  2406. if (userinfo != null)
  2407. {
  2408. userinfo.SessionID = agent.SessionID;
  2409. }
  2410. else
  2411. {
  2412. m_log.WarnFormat("[USERINFO CACHE]: We couldn't find a User Info record for {0}. This is usually an indication that the UUID we're looking up is invalid", agent.AgentID);
  2413. }
  2414. }
  2415. public void UpdateCircuitData(AgentCircuitData data)
  2416. {
  2417. m_authenticateHandler.UpdateAgentData(data);
  2418. }
  2419. public bool ChangeCircuitCode(uint oldcc, uint newcc)
  2420. {
  2421. return m_authenticateHandler.TryChangeCiruitCode(oldcc, newcc);
  2422. }
  2423. protected void HandleLogOffUserFromGrid(UUID AvatarID, UUID RegionSecret, string message)
  2424. {
  2425. ScenePresence loggingOffUser = null;
  2426. loggingOffUser = GetScenePresence(AvatarID);
  2427. if (loggingOffUser != null)
  2428. {
  2429. if (RegionSecret == loggingOffUser.ControllingClient.SecureSessionId)
  2430. {
  2431. m_sceneGridService.SendCloseChildAgentConnections(loggingOffUser.UUID, new List<ulong>(loggingOffUser.KnownRegions.Keys));
  2432. loggingOffUser.ControllingClient.Kick(message);
  2433. // Give them a second to receive the message!
  2434. System.Threading.Thread.Sleep(1000);
  2435. loggingOffUser.ControllingClient.Close(true);
  2436. }
  2437. else
  2438. {
  2439. m_log.Info("[USERLOGOFF]: System sending the LogOff user message failed to sucessfully authenticate");
  2440. }
  2441. }
  2442. else
  2443. {
  2444. 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());
  2445. }
  2446. }
  2447. /// <summary>
  2448. /// Add a caps handler for the given agent. If the CAPS handler already exists for this agent,
  2449. /// then it is replaced by a new CAPS handler.
  2450. ///
  2451. /// FIXME: On login this is called twice, once for the login and once when the connection is made.
  2452. /// This is somewhat innefficient and should be fixed. The initial login creation is necessary
  2453. /// since the client asks for capabilities immediately after being informed of the seed.
  2454. /// </summary>
  2455. /// <param name="agentId"></param>
  2456. /// <param name="capsObjectPath"></param>
  2457. public void AddCapsHandler(UUID agentId)
  2458. {
  2459. if (RegionInfo.EstateSettings.IsBanned(agentId))
  2460. return;
  2461. String capsObjectPath = GetCapsPath(agentId);
  2462. m_log.DebugFormat(
  2463. "[CAPS]: Setting up CAPS handler for agent {0} in {1}",
  2464. agentId, RegionInfo.RegionName);
  2465. Caps cap = null;
  2466. if (m_capsHandlers.TryGetValue(agentId, out cap))
  2467. {
  2468. m_log.DebugFormat("[CAPS] Attempt at registering twice for the same agent {0}. {1}. Ignoring.", agentId, capsObjectPath);
  2469. return;
  2470. }
  2471. cap = new Caps(AssetCache, m_httpListener, m_regInfo.ExternalHostName, m_httpListener.Port,
  2472. capsObjectPath, agentId, m_dumpAssetsToFile, RegionInfo.RegionName);
  2473. cap.RegisterHandlers();
  2474. EventManager.TriggerOnRegisterCaps(agentId, cap);
  2475. cap.AddNewInventoryItem = AddUploadedInventoryItem;
  2476. cap.ItemUpdatedCall = CapsUpdateInventoryItemAsset;
  2477. cap.TaskScriptUpdatedCall = CapsUpdateTaskInventoryScriptAsset;
  2478. cap.CAPSFetchInventoryDescendents = HandleFetchInventoryDescendentsCAPS;
  2479. cap.GetClient = m_sceneGraph.GetControllingClient;
  2480. m_capsHandlers[agentId] = cap;
  2481. }
  2482. public Caps GetCapsHandlerForUser(UUID agentId)
  2483. {
  2484. lock (m_capsHandlers)
  2485. {
  2486. if (m_capsHandlers.ContainsKey(agentId))
  2487. {
  2488. return m_capsHandlers[agentId];
  2489. }
  2490. }
  2491. return null;
  2492. }
  2493. /// <summary>
  2494. /// Remove the caps handler for a given agent.
  2495. /// </summary>
  2496. /// <param name="agentId"></param>
  2497. public void RemoveCapsHandler(UUID agentId)
  2498. {
  2499. if (childrenSeeds.ContainsKey(agentId))
  2500. {
  2501. //Console.WriteLine(" !!! Removing seeds for {0} in {1}", agentId, RegionInfo.RegionName);
  2502. childrenSeeds.Remove(agentId);
  2503. }
  2504. lock (m_capsHandlers)
  2505. {
  2506. if (m_capsHandlers.ContainsKey(agentId))
  2507. {
  2508. m_log.DebugFormat(
  2509. "[CAPS]: Removing CAPS handler for root agent {0} in {1}",
  2510. agentId, RegionInfo.RegionName);
  2511. m_capsHandlers[agentId].DeregisterHandlers();
  2512. EventManager.TriggerOnDeregisterCaps(agentId, m_capsHandlers[agentId]);
  2513. m_capsHandlers.Remove(agentId);
  2514. }
  2515. else
  2516. {
  2517. m_log.WarnFormat(
  2518. "[CAPS]: Received request to remove CAPS handler for root agent {0} in {1}, but no such CAPS handler found!",
  2519. agentId, RegionInfo.RegionName);
  2520. }
  2521. }
  2522. }
  2523. /// <summary>
  2524. /// Triggered when an agent crosses into this sim. Also happens on initial login.
  2525. /// </summary>
  2526. /// <param name="agentID"></param>
  2527. /// <param name="position"></param>
  2528. /// <param name="isFlying"></param>
  2529. public virtual void AgentCrossing(UUID agentID, Vector3 position, bool isFlying)
  2530. {
  2531. ScenePresence presence;
  2532. lock (m_scenePresences)
  2533. {
  2534. m_scenePresences.TryGetValue(agentID, out presence);
  2535. }
  2536. if (presence != null)
  2537. {
  2538. try
  2539. {
  2540. presence.MakeRootAgent(position, isFlying);
  2541. }
  2542. catch (Exception e)
  2543. {
  2544. m_log.ErrorFormat("[SCENE]: Unable to do agent crossing, exception {0}", e);
  2545. }
  2546. }
  2547. else
  2548. {
  2549. m_log.ErrorFormat(
  2550. "[SCENE]: Could not find presence for agent {0} crossing into scene {1}",
  2551. agentID, RegionInfo.RegionName);
  2552. }
  2553. }
  2554. public virtual bool IncomingChildAgentDataUpdate(AgentData cAgentData)
  2555. {
  2556. //Console.WriteLine(" XXX Scene IncomingChildAgentDataUpdate FULL in " + RegionInfo.RegionName);
  2557. ScenePresence childAgentUpdate = GetScenePresence(cAgentData.AgentID);
  2558. if (childAgentUpdate != null)
  2559. {
  2560. childAgentUpdate.ChildAgentDataUpdate(cAgentData);
  2561. return true;
  2562. }
  2563. return false;
  2564. }
  2565. public virtual bool IncomingChildAgentDataUpdate(AgentPosition cAgentData)
  2566. {
  2567. //Console.WriteLine(" XXX Scene IncomingChildAgentDataUpdate POSITION in " + RegionInfo.RegionName);
  2568. ScenePresence childAgentUpdate = GetScenePresence(cAgentData.AgentID);
  2569. if (childAgentUpdate != null)
  2570. {
  2571. // I can't imagine *yet* why we would get an update if the agent is a root agent..
  2572. // however to avoid a race condition crossing borders..
  2573. if (childAgentUpdate.IsChildAgent)
  2574. {
  2575. uint rRegionX = (uint)(cAgentData.RegionHandle >> 40);
  2576. uint rRegionY = (((uint)(cAgentData.RegionHandle)) >> 8);
  2577. uint tRegionX = RegionInfo.RegionLocX;
  2578. uint tRegionY = RegionInfo.RegionLocY;
  2579. //Send Data to ScenePresence
  2580. childAgentUpdate.ChildAgentDataUpdate(cAgentData, tRegionX, tRegionY, rRegionX, rRegionY);
  2581. // Not Implemented:
  2582. //TODO: Do we need to pass the message on to one of our neighbors?
  2583. }
  2584. return true;
  2585. }
  2586. return false;
  2587. }
  2588. public virtual bool IncomingReleaseAgent(UUID id)
  2589. {
  2590. return m_sceneGridService.ReleaseAgent(id);
  2591. }
  2592. public void SendReleaseAgent(ulong regionHandle, UUID id, string uri)
  2593. {
  2594. m_interregionCommsOut.SendReleaseAgent(regionHandle, id, uri);
  2595. }
  2596. /// <summary>
  2597. /// Tell a single agent to disconnect from the region.
  2598. /// </summary>
  2599. /// <param name="regionHandle"></param>
  2600. /// <param name="agentID"></param>
  2601. public bool IncomingCloseAgent(UUID agentID)
  2602. {
  2603. ScenePresence presence = m_sceneGraph.GetScenePresence(agentID);
  2604. if (presence != null)
  2605. {
  2606. // Nothing is removed here, so down count it as such
  2607. if (presence.IsChildAgent)
  2608. {
  2609. m_sceneGraph.removeUserCount(false);
  2610. }
  2611. else
  2612. {
  2613. m_sceneGraph.removeUserCount(true);
  2614. }
  2615. // Don't do this to root agents on logout, it's not nice for the viewer
  2616. if (presence.IsChildAgent)
  2617. {
  2618. // Tell a single agent to disconnect from the region.
  2619. IEventQueue eq = RequestModuleInterface<IEventQueue>();
  2620. if (eq != null)
  2621. {
  2622. OSD Item = EventQueueHelper.DisableSimulator(RegionInfo.RegionHandle);
  2623. eq.Enqueue(Item, agentID);
  2624. }
  2625. else
  2626. presence.ControllingClient.SendShutdownConnectionNotice();
  2627. }
  2628. presence.ControllingClient.Close(true);
  2629. return true;
  2630. }
  2631. // Agent not here
  2632. return false;
  2633. }
  2634. /// <summary>
  2635. /// Tell neighboring regions about this agent
  2636. /// When the regions respond with a true value,
  2637. /// tell the agents about the region.
  2638. ///
  2639. /// We have to tell the regions about the agents first otherwise it'll deny them access
  2640. ///
  2641. /// </summary>
  2642. /// <param name="presence"></param>
  2643. public void InformClientOfNeighbours(ScenePresence presence)
  2644. {
  2645. m_sceneGridService.EnableNeighbourChildAgents(presence, m_neighbours);
  2646. }
  2647. /// <summary>
  2648. /// Tell a neighboring region about this agent
  2649. /// </summary>
  2650. /// <param name="presence"></param>
  2651. /// <param name="region"></param>
  2652. public void InformClientOfNeighbor(ScenePresence presence, RegionInfo region)
  2653. {
  2654. m_sceneGridService.InformNeighborChildAgent(presence, region, m_neighbours);
  2655. }
  2656. /// <summary>
  2657. /// Requests information about this region from gridcomms
  2658. /// </summary>
  2659. /// <param name="regionHandle"></param>
  2660. /// <returns></returns>
  2661. public RegionInfo RequestNeighbouringRegionInfo(ulong regionHandle)
  2662. {
  2663. return m_sceneGridService.RequestNeighbouringRegionInfo(regionHandle);
  2664. }
  2665. /// <summary>
  2666. /// Requests textures for map from minimum region to maximum region in world cordinates
  2667. /// </summary>
  2668. /// <param name="remoteClient"></param>
  2669. /// <param name="minX"></param>
  2670. /// <param name="minY"></param>
  2671. /// <param name="maxX"></param>
  2672. /// <param name="maxY"></param>
  2673. public void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY)
  2674. {
  2675. m_log.InfoFormat("[MAPBLOCK]: {0}-{1}, {2}-{3}", minX, minY, maxX, maxY);
  2676. m_sceneGridService.RequestMapBlocks(remoteClient, minX, minY, maxX, maxY);
  2677. }
  2678. /// <summary>
  2679. /// Tries to teleport agent to other region.
  2680. /// </summary>
  2681. /// <param name="remoteClient"></param>
  2682. /// <param name="regionName"></param>
  2683. /// <param name="position"></param>
  2684. /// <param name="lookAt"></param>
  2685. /// <param name="teleportFlags"></param>
  2686. public void RequestTeleportLocation(IClientAPI remoteClient, string regionName, Vector3 position,
  2687. Vector3 lookat, uint teleportFlags)
  2688. {
  2689. RegionInfo regionInfo = m_sceneGridService.RequestClosestRegion(regionName);
  2690. if (regionInfo == null)
  2691. {
  2692. // can't find the region: Tell viewer and abort
  2693. remoteClient.SendTeleportFailed("The region '" + regionName + "' could not be found.");
  2694. return;
  2695. }
  2696. RequestTeleportLocation(remoteClient, regionInfo.RegionHandle, position, lookat, teleportFlags);
  2697. }
  2698. /// <summary>
  2699. /// Tries to teleport agent to other region.
  2700. /// </summary>
  2701. /// <param name="remoteClient"></param>
  2702. /// <param name="regionHandle"></param>
  2703. /// <param name="position"></param>
  2704. /// <param name="lookAt"></param>
  2705. /// <param name="teleportFlags"></param>
  2706. public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, Vector3 position,
  2707. Vector3 lookAt, uint teleportFlags)
  2708. {
  2709. lock (m_scenePresences)
  2710. {
  2711. if (m_scenePresences.ContainsKey(remoteClient.AgentId))
  2712. {
  2713. m_sceneGridService.RequestTeleportToLocation(m_scenePresences[remoteClient.AgentId], regionHandle,
  2714. position, lookAt, teleportFlags);
  2715. }
  2716. }
  2717. }
  2718. /// <summary>
  2719. /// Tries to teleport agent to landmark.
  2720. /// </summary>
  2721. /// <param name="remoteClient"></param>
  2722. /// <param name="regionHandle"></param>
  2723. /// <param name="position"></param>
  2724. public void RequestTeleportLandmark(IClientAPI remoteClient, UUID regionID, Vector3 position)
  2725. {
  2726. RegionInfo info = CommsManager.GridService.RequestNeighbourInfo(regionID);
  2727. if (info == null)
  2728. {
  2729. // can't find the region: Tell viewer and abort
  2730. remoteClient.SendTeleportFailed("The teleport destination could not be found.");
  2731. return;
  2732. }
  2733. lock (m_scenePresences)
  2734. {
  2735. if (m_scenePresences.ContainsKey(remoteClient.AgentId))
  2736. {
  2737. m_sceneGridService.RequestTeleportToLocation(m_scenePresences[remoteClient.AgentId], info.RegionHandle,
  2738. position, Vector3.Zero, (uint)(TPFlags.SetLastToTarget | TPFlags.ViaLandmark));
  2739. }
  2740. }
  2741. }
  2742. /// <summary>
  2743. /// Agent is crossing the border into a neighbouring region. Tell the neighbour about it!
  2744. /// </summary>
  2745. /// <param name="regionHandle"></param>
  2746. /// <param name="agentID"></param>
  2747. /// <param name="position"></param>
  2748. /// <param name="isFlying"></param>
  2749. /// <returns></returns>
  2750. public bool InformNeighbourOfCrossing(ulong regionHandle, UUID agentID, Vector3 position, bool isFlying)
  2751. {
  2752. return m_sceneGridService.CrossToNeighbouringRegion(regionHandle, agentID, position, isFlying);
  2753. }
  2754. public void SendOutChildAgentUpdates(AgentPosition cadu, ScenePresence presence)
  2755. {
  2756. m_sceneGridService.SendChildAgentDataUpdate(cadu, presence);
  2757. }
  2758. #endregion
  2759. #region Module Methods
  2760. /// <summary>
  2761. /// Add a module to this scene.
  2762. /// </summary>
  2763. /// <param name="name"></param>
  2764. /// <param name="module"></param>
  2765. public void AddModule(string name, IRegionModule module)
  2766. {
  2767. if (!Modules.ContainsKey(name))
  2768. {
  2769. Modules.Add(name, module);
  2770. }
  2771. }
  2772. public void RegisterModuleCommander(string name, ICommander commander)
  2773. {
  2774. lock (m_moduleCommanders)
  2775. {
  2776. m_moduleCommanders.Add(name, commander);
  2777. }
  2778. }
  2779. public ICommander GetCommander(string name)
  2780. {
  2781. lock (m_moduleCommanders)
  2782. {
  2783. return m_moduleCommanders[name];
  2784. }
  2785. }
  2786. public Dictionary<string, ICommander> GetCommanders()
  2787. {
  2788. return m_moduleCommanders;
  2789. }
  2790. /// <summary>
  2791. /// Register an interface to a region module. This allows module methods to be called directly as
  2792. /// well as via events. If there is already a module registered for this interface, it is not replaced
  2793. /// (is this the best behaviour?)
  2794. /// </summary>
  2795. /// <param name="mod"></param>
  2796. public void RegisterModuleInterface<M>(M mod)
  2797. {
  2798. if (!ModuleInterfaces.ContainsKey(typeof(M)))
  2799. {
  2800. List<Object> l = new List<Object>();
  2801. l.Add(mod);
  2802. ModuleInterfaces.Add(typeof(M), l);
  2803. if (mod is IEntityCreator)
  2804. {
  2805. IEntityCreator entityCreator = (IEntityCreator)mod;
  2806. foreach (PCode pcode in entityCreator.CreationCapabilities)
  2807. {
  2808. m_entityCreators[pcode] = entityCreator;
  2809. }
  2810. }
  2811. }
  2812. }
  2813. public void StackModuleInterface<M>(M mod)
  2814. {
  2815. List<Object> l;
  2816. if (ModuleInterfaces.ContainsKey(typeof(M)))
  2817. l = ModuleInterfaces[typeof(M)];
  2818. else
  2819. l = new List<Object>();
  2820. if (l.Contains(mod))
  2821. return;
  2822. l.Add(mod);
  2823. if (mod is IEntityCreator)
  2824. {
  2825. IEntityCreator entityCreator = (IEntityCreator)mod;
  2826. foreach (PCode pcode in entityCreator.CreationCapabilities)
  2827. {
  2828. m_entityCreators[pcode] = entityCreator;
  2829. }
  2830. }
  2831. ModuleInterfaces[typeof(M)] = l;
  2832. }
  2833. /// <summary>
  2834. /// For the given interface, retrieve the region module which implements it.
  2835. /// </summary>
  2836. /// <returns>null if there is no registered module implementing that interface</returns>
  2837. public override T RequestModuleInterface<T>()
  2838. {
  2839. if (ModuleInterfaces.ContainsKey(typeof(T)))
  2840. {
  2841. return (T)ModuleInterfaces[typeof(T)][0];
  2842. }
  2843. else
  2844. {
  2845. return default(T);
  2846. }
  2847. }
  2848. /// <summary>
  2849. /// For the given interface, retrieve an array of region modules that implement it.
  2850. /// </summary>
  2851. /// <returns>an empty array if there are no registered modules implementing that interface</returns>
  2852. public override T[] RequestModuleInterfaces<T>()
  2853. {
  2854. if (ModuleInterfaces.ContainsKey(typeof(T)))
  2855. {
  2856. List<T> ret = new List<T>();
  2857. foreach (Object o in ModuleInterfaces[typeof(T)])
  2858. ret.Add((T)o);
  2859. return ret.ToArray();
  2860. }
  2861. else
  2862. {
  2863. return new T[] { default(T) };
  2864. }
  2865. }
  2866. public void SetObjectCapacity(int objects)
  2867. {
  2868. // Region specific config overrides global
  2869. //
  2870. if (RegionInfo.ObjectCapacity != 0)
  2871. objects = RegionInfo.ObjectCapacity;
  2872. if (StatsReporter != null)
  2873. {
  2874. StatsReporter.SetObjectCapacity(objects);
  2875. }
  2876. objectCapacity = objects;
  2877. }
  2878. public List<FriendListItem> GetFriendList(UUID avatarID)
  2879. {
  2880. return CommsManager.GetUserFriendList(avatarID);
  2881. }
  2882. public Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos(List<UUID> uuids)
  2883. {
  2884. return CommsManager.GetFriendRegionInfos(uuids);
  2885. }
  2886. public List<UUID> InformFriendsInOtherRegion(UUID agentId, ulong destRegionHandle, List<UUID> friends, bool online)
  2887. {
  2888. return CommsManager.InformFriendsInOtherRegion(agentId, destRegionHandle, friends, online);
  2889. }
  2890. public bool TriggerTerminateFriend(ulong regionHandle, UUID agentID, UUID exFriendID)
  2891. {
  2892. return CommsManager.TriggerTerminateFriend(regionHandle, agentID, exFriendID);
  2893. }
  2894. #endregion
  2895. #region Other Methods
  2896. /// <summary>
  2897. ///
  2898. /// </summary>
  2899. /// <param name="phase"></param>
  2900. public void SetTimePhase(int phase)
  2901. {
  2902. m_timePhase = phase;
  2903. }
  2904. /// <summary>
  2905. ///
  2906. /// </summary>
  2907. /// <param name="avatarID"></param>
  2908. /// <param name="objectName"></param>
  2909. /// <param name="objectID"></param>
  2910. /// <param name="ownerID"></param>
  2911. /// <param name="groupOwned"></param>
  2912. /// <param name="message"></param>
  2913. /// <param name="url"></param>
  2914. public void SendUrlToUser(UUID avatarID, string objectName, UUID objectID, UUID ownerID, bool groupOwned,
  2915. string message, string url)
  2916. {
  2917. lock (m_scenePresences)
  2918. {
  2919. if (m_scenePresences.ContainsKey(avatarID))
  2920. {
  2921. m_scenePresences[avatarID].ControllingClient.SendLoadURL(objectName, objectID, ownerID, groupOwned,
  2922. message, url);
  2923. }
  2924. }
  2925. }
  2926. public void SendDialogToUser(UUID avatarID, string objectName, UUID objectID, UUID ownerID, string message, UUID TextureID, int ch, string[] buttonlabels)
  2927. {
  2928. lock (m_scenePresences)
  2929. {
  2930. if (m_scenePresences.ContainsKey(avatarID))
  2931. {
  2932. m_scenePresences[avatarID].ControllingClient.SendDialog(
  2933. objectName, objectID, ownerID, message, TextureID, ch, buttonlabels);
  2934. }
  2935. }
  2936. }
  2937. /// <summary>
  2938. ///
  2939. /// </summary>
  2940. /// <param name="url"></param>
  2941. /// <param name="type"></param>
  2942. /// <param name="body"></param>
  2943. /// <returns></returns>
  2944. public UUID MakeHttpRequest(string url, string type, string body)
  2945. {
  2946. if (m_httpRequestModule != null)
  2947. {
  2948. return m_httpRequestModule.MakeHttpRequest(url, type, body);
  2949. }
  2950. return UUID.Zero;
  2951. }
  2952. public virtual void StoreAddFriendship(UUID ownerID, UUID friendID, uint perms)
  2953. {
  2954. m_sceneGridService.AddNewUserFriend(ownerID, friendID, perms);
  2955. }
  2956. public virtual void StoreUpdateFriendship(UUID ownerID, UUID friendID, uint perms)
  2957. {
  2958. m_sceneGridService.UpdateUserFriendPerms(ownerID, friendID, perms);
  2959. }
  2960. public virtual void StoreRemoveFriendship(UUID ownerID, UUID ExfriendID)
  2961. {
  2962. m_sceneGridService.RemoveUserFriend(ownerID, ExfriendID);
  2963. }
  2964. public void AddPacketStats(int inPackets, int outPackets, int unAckedBytes)
  2965. {
  2966. StatsReporter.AddInPackets(inPackets);
  2967. StatsReporter.AddOutPackets(outPackets);
  2968. StatsReporter.AddunAckedBytes(unAckedBytes);
  2969. }
  2970. public void AddAgentTime(int ms)
  2971. {
  2972. StatsReporter.addFrameMS(ms);
  2973. StatsReporter.addAgentMS(ms);
  2974. }
  2975. public void AddAgentUpdates(int count)
  2976. {
  2977. StatsReporter.AddAgentUpdates(count);
  2978. }
  2979. public void AddPendingDownloads(int count)
  2980. {
  2981. StatsReporter.addPendingDownload(count);
  2982. }
  2983. #endregion
  2984. #region Console Commands
  2985. #region Alert Methods
  2986. private void SendPermissionAlert(UUID user, string reason)
  2987. {
  2988. SendAlertToUser(user, reason, false);
  2989. }
  2990. /// <summary>
  2991. /// Send an alert messages to all avatars in this scene.
  2992. /// </summary>
  2993. /// <param name="message"></param>
  2994. public void SendGeneralAlert(string message)
  2995. {
  2996. List<ScenePresence> presenceList = GetScenePresences();
  2997. foreach (ScenePresence presence in presenceList)
  2998. {
  2999. if (!presence.IsChildAgent)
  3000. presence.ControllingClient.SendAlertMessage(message);
  3001. }
  3002. }
  3003. /// <summary>
  3004. /// Send an alert message to a particular agent.
  3005. /// </summary>
  3006. /// <param name="agentID"></param>
  3007. /// <param name="message"></param>
  3008. /// <param name="modal"></param>
  3009. public void SendAlertToUser(UUID agentID, string message, bool modal)
  3010. {
  3011. lock (m_scenePresences)
  3012. {
  3013. if (m_scenePresences.ContainsKey(agentID))
  3014. {
  3015. m_scenePresences[agentID].ControllingClient.SendAgentAlertMessage(message, modal);
  3016. }
  3017. }
  3018. }
  3019. /// <summary>
  3020. /// Handle a request for admin rights
  3021. /// </summary>
  3022. /// <param name="agentID"></param>
  3023. /// <param name="sessionID"></param>
  3024. /// <param name="token"></param>
  3025. /// <param name="controllingClient"></param>
  3026. public void handleRequestGodlikePowers(UUID agentID, UUID sessionID, UUID token, bool godLike,
  3027. IClientAPI controllingClient)
  3028. {
  3029. lock (m_scenePresences)
  3030. {
  3031. // User needs to be logged into this sim
  3032. if (m_scenePresences.ContainsKey(agentID))
  3033. {
  3034. if (godLike == false)
  3035. {
  3036. m_scenePresences[agentID].GrantGodlikePowers(agentID, sessionID, token, godLike);
  3037. return;
  3038. }
  3039. // First check that this is the sim owner
  3040. if (Permissions.IsGod(agentID))
  3041. {
  3042. // Next we check for spoofing.....
  3043. UUID testSessionID = m_scenePresences[agentID].ControllingClient.SessionId;
  3044. if (sessionID == testSessionID)
  3045. {
  3046. if (sessionID == controllingClient.SessionId)
  3047. {
  3048. //m_log.Info("godlike: " + godLike.ToString());
  3049. m_scenePresences[agentID].GrantGodlikePowers(agentID, testSessionID, token, godLike);
  3050. }
  3051. }
  3052. }
  3053. else
  3054. {
  3055. m_scenePresences[agentID].ControllingClient.SendAgentAlertMessage("Request for god powers denied", false);
  3056. }
  3057. }
  3058. }
  3059. }
  3060. /// <summary>
  3061. /// Sends a Big Blue Box message on the upper right of the screen to the client
  3062. /// for all agents in the region
  3063. /// </summary>
  3064. /// <param name="FromAvatarID">The person sending the message</param>
  3065. /// <param name="fromSessionID">The session of the person sending the message</param>
  3066. /// <param name="FromAvatarName">The name of the person doing the sending</param>
  3067. /// <param name="Message">The Message being sent to the user</param>
  3068. public void SendRegionMessageFromEstateTools(UUID FromAvatarID, UUID fromSessionID, String FromAvatarName, String Message)
  3069. {
  3070. List<ScenePresence> presenceList = GetScenePresences();
  3071. foreach (ScenePresence presence in presenceList)
  3072. {
  3073. if (!presence.IsChildAgent)
  3074. presence.ControllingClient.SendBlueBoxMessage(FromAvatarID, FromAvatarName, Message);
  3075. }
  3076. }
  3077. /// <summary>
  3078. /// Sends a Big Blue Box message on the upper right of the screen to the client
  3079. /// for all agents in the estate
  3080. /// </summary>
  3081. /// <param name="FromAvatarID">The person sending the message</param>
  3082. /// <param name="fromSessionID">The session of the person sending the message</param>
  3083. /// <param name="FromAvatarName">The name of the person doing the sending</param>
  3084. /// <param name="Message">The Message being sent to the user</param>
  3085. public void SendEstateMessageFromEstateTools(UUID FromAvatarID, UUID fromSessionID, String FromAvatarName, String Message)
  3086. {
  3087. ClientManager.ForEachClient(delegate(IClientAPI controller)
  3088. {
  3089. controller.SendBlueBoxMessage(FromAvatarID, FromAvatarName, Message);
  3090. }
  3091. );
  3092. }
  3093. /// <summary>
  3094. /// Kicks User specified from the simulator. This logs them off of the grid
  3095. /// If the client gets the UUID: 44e87126e7944ded05b37c42da3d5cdb it assumes
  3096. /// that you're kicking it even if the avatar's UUID isn't the UUID that the
  3097. /// agent is assigned
  3098. /// </summary>
  3099. /// <param name="godID">The person doing the kicking</param>
  3100. /// <param name="sessionID">The session of the person doing the kicking</param>
  3101. /// <param name="agentID">the person that is being kicked</param>
  3102. /// <param name="kickflags">This isn't used apparently</param>
  3103. /// <param name="reason">The message to send to the user after it's been turned into a field</param>
  3104. public void HandleGodlikeKickUser(UUID godID, UUID sessionID, UUID agentID, uint kickflags, byte[] reason)
  3105. {
  3106. // For some reason the client sends this seemingly hard coded UUID for kicking everyone. Dun-know.
  3107. UUID kickUserID = new UUID("44e87126e7944ded05b37c42da3d5cdb");
  3108. lock (m_scenePresences)
  3109. {
  3110. if (m_scenePresences.ContainsKey(agentID) || agentID == kickUserID)
  3111. {
  3112. if (Permissions.IsGod(godID))
  3113. {
  3114. if (agentID == kickUserID)
  3115. {
  3116. ClientManager.ForEachClient(delegate(IClientAPI controller)
  3117. {
  3118. if (controller.AgentId != godID)
  3119. controller.Kick(Utils.BytesToString(reason));
  3120. }
  3121. );
  3122. // This is a bit crude. It seems the client will be null before it actually stops the thread
  3123. // The thread will kill itself eventually :/
  3124. // Is there another way to make sure *all* clients get this 'inter region' message?
  3125. ClientManager.ForEachClient(delegate(IClientAPI controller)
  3126. {
  3127. ScenePresence p = GetScenePresence(controller.AgentId);
  3128. bool childagent = p != null && p.IsChildAgent;
  3129. if (controller.AgentId != godID && !childagent)
  3130. // Do we really want to kick the initiator of this madness?
  3131. {
  3132. controller.Close(true);
  3133. }
  3134. }
  3135. );
  3136. }
  3137. else
  3138. {
  3139. m_sceneGraph.removeUserCount(!m_scenePresences[agentID].IsChildAgent);
  3140. m_scenePresences[agentID].ControllingClient.Kick(Utils.BytesToString(reason));
  3141. m_scenePresences[agentID].ControllingClient.Close(true);
  3142. }
  3143. }
  3144. else
  3145. {
  3146. if (m_scenePresences.ContainsKey(godID))
  3147. m_scenePresences[godID].ControllingClient.SendAgentAlertMessage("Kick request denied", false);
  3148. }
  3149. }
  3150. }
  3151. }
  3152. public void HandleObjectPermissionsUpdate(IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set)
  3153. {
  3154. // Check for spoofing.. since this is permissions we're talking about here!
  3155. if ((controller.SessionId == sessionID) && (controller.AgentId == agentID))
  3156. {
  3157. // Tell the object to do permission update
  3158. if (localId != 0)
  3159. {
  3160. SceneObjectGroup chObjectGroup = GetGroupByPrim(localId);
  3161. if (chObjectGroup != null)
  3162. {
  3163. chObjectGroup.UpdatePermissions(agentID, field, localId, mask, set);
  3164. }
  3165. }
  3166. }
  3167. }
  3168. /// <summary>
  3169. ///
  3170. /// </summary>
  3171. /// <param name="firstName"></param>
  3172. /// <param name="lastName"></param>
  3173. /// <param name="message"></param>
  3174. /// <param name="modal"></param>
  3175. public void SendAlertToUser(string firstName, string lastName, string message, bool modal)
  3176. {
  3177. List<ScenePresence> presenceList = GetScenePresences();
  3178. foreach (ScenePresence presence in presenceList)
  3179. {
  3180. if (presence.Firstname == firstName && presence.Lastname == lastName)
  3181. {
  3182. presence.ControllingClient.SendAgentAlertMessage(message, modal);
  3183. break;
  3184. }
  3185. }
  3186. }
  3187. /// <summary>
  3188. /// Handle an alert command from the console.
  3189. /// FIXME: Command parsing code really shouldn't be in this core Scene class.
  3190. /// </summary>
  3191. /// <param name="commandParams"></param>
  3192. public void HandleAlertCommand(string[] commandParams)
  3193. {
  3194. if (commandParams[0] == "general")
  3195. {
  3196. string message = CombineParams(commandParams, 1);
  3197. SendGeneralAlert(message);
  3198. }
  3199. else
  3200. {
  3201. string message = CombineParams(commandParams, 2);
  3202. SendAlertToUser(commandParams[0], commandParams[1], message, false);
  3203. }
  3204. }
  3205. private string CombineParams(string[] commandParams, int pos)
  3206. {
  3207. string result = String.Empty;
  3208. for (int i = pos; i < commandParams.Length; i++)
  3209. {
  3210. result += commandParams[i] + " ";
  3211. }
  3212. return result;
  3213. }
  3214. #endregion
  3215. /// <summary>
  3216. /// Causes all clients to get a full object update on all of the objects in the scene.
  3217. /// </summary>
  3218. public void ForceClientUpdate()
  3219. {
  3220. List<EntityBase> EntityList = GetEntities();
  3221. foreach (EntityBase ent in EntityList)
  3222. {
  3223. if (ent is SceneObjectGroup)
  3224. {
  3225. ((SceneObjectGroup)ent).ScheduleGroupForFullUpdate();
  3226. }
  3227. }
  3228. }
  3229. /// <summary>
  3230. /// This is currently only used for scale (to scale to MegaPrim size)
  3231. /// There is a console command that calls this in OpenSimMain
  3232. /// </summary>
  3233. /// <param name="cmdparams"></param>
  3234. public void HandleEditCommand(string[] cmdparams)
  3235. {
  3236. Console.WriteLine("Searching for Primitive: '" + cmdparams[0] + "'");
  3237. List<EntityBase> EntityList = GetEntities();
  3238. foreach (EntityBase ent in EntityList)
  3239. {
  3240. if (ent is SceneObjectGroup)
  3241. {
  3242. SceneObjectPart part = ((SceneObjectGroup)ent).GetChildPart(((SceneObjectGroup)ent).UUID);
  3243. if (part != null)
  3244. {
  3245. if (part.Name == cmdparams[0])
  3246. {
  3247. part.Resize(
  3248. new Vector3(Convert.ToSingle(cmdparams[1]), Convert.ToSingle(cmdparams[2]),
  3249. Convert.ToSingle(cmdparams[3])));
  3250. Console.WriteLine("Edited scale of Primitive: " + part.Name);
  3251. }
  3252. }
  3253. }
  3254. }
  3255. }
  3256. /// <summary>
  3257. /// Shows various details about the sim based on the parameters supplied by the console command in openSimMain.
  3258. /// </summary>
  3259. /// <param name="showParams">What to show</param>
  3260. public void Show(string[] showParams)
  3261. {
  3262. switch (showParams[0])
  3263. {
  3264. case "users":
  3265. m_log.Error("Current Region: " + RegionInfo.RegionName);
  3266. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}{6,-16}", "Firstname", "Lastname",
  3267. "Agent ID", "Session ID", "Circuit", "IP", "World");
  3268. foreach (ScenePresence scenePresence in GetAvatars())
  3269. {
  3270. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}{6,-16}",
  3271. scenePresence.Firstname,
  3272. scenePresence.Lastname,
  3273. scenePresence.UUID,
  3274. scenePresence.ControllingClient.AgentId,
  3275. "Unknown",
  3276. "Unknown",
  3277. RegionInfo.RegionName);
  3278. }
  3279. break;
  3280. case "modules":
  3281. m_log.Error("The currently loaded modules in " + RegionInfo.RegionName + " are:");
  3282. foreach (IRegionModule module in Modules.Values)
  3283. {
  3284. if (!module.IsSharedModule)
  3285. {
  3286. m_log.Error("Region Module: " + module.Name);
  3287. }
  3288. }
  3289. break;
  3290. }
  3291. }
  3292. #endregion
  3293. #region Script Handling Methods
  3294. /// <summary>
  3295. /// Console command handler to send script command to script engine.
  3296. /// </summary>
  3297. /// <param name="args"></param>
  3298. public void SendCommandToPlugins(string[] args)
  3299. {
  3300. m_eventManager.TriggerOnPluginConsole(args);
  3301. }
  3302. public double GetLandHeight(int x, int y)
  3303. {
  3304. return Heightmap[x, y];
  3305. }
  3306. public UUID GetLandOwner(float x, float y)
  3307. {
  3308. ILandObject land = LandChannel.GetLandObject(x, y);
  3309. if (land == null)
  3310. {
  3311. return UUID.Zero;
  3312. }
  3313. else
  3314. {
  3315. return land.landData.OwnerID;
  3316. }
  3317. }
  3318. public LandData GetLandData(float x, float y)
  3319. {
  3320. return LandChannel.GetLandObject(x, y).landData;
  3321. }
  3322. public LandData GetLandData(uint x, uint y)
  3323. {
  3324. m_log.DebugFormat("[SCENE] returning land for {0},{1}", x, y);
  3325. return LandChannel.GetLandObject((int)x, (int)y).landData;
  3326. }
  3327. public void SetLandMusicURL(float x, float y, string url)
  3328. {
  3329. ILandObject land = LandChannel.GetLandObject(x, y);
  3330. if (land == null)
  3331. {
  3332. return;
  3333. }
  3334. else
  3335. {
  3336. land.landData.MusicURL = url;
  3337. land.sendLandUpdateToAvatarsOverMe();
  3338. return;
  3339. }
  3340. }
  3341. public void SetLandMediaURL(float x, float y, string url)
  3342. {
  3343. ILandObject land = LandChannel.GetLandObject(x, y);
  3344. if (land == null)
  3345. {
  3346. return;
  3347. }
  3348. else
  3349. {
  3350. land.landData.MediaURL = url;
  3351. land.sendLandUpdateToAvatarsOverMe();
  3352. return;
  3353. }
  3354. }
  3355. public RegionInfo RequestClosestRegion(string name)
  3356. {
  3357. return m_sceneGridService.RequestClosestRegion(name);
  3358. }
  3359. #endregion
  3360. #region Script Engine
  3361. private List<ScriptEngineInterface> ScriptEngines = new List<ScriptEngineInterface>();
  3362. private bool m_dumpAssetsToFile;
  3363. /// <summary>
  3364. ///
  3365. /// </summary>
  3366. /// <param name="scriptEngine"></param>
  3367. public void AddScriptEngine(ScriptEngineInterface scriptEngine)
  3368. {
  3369. ScriptEngines.Add(scriptEngine);
  3370. scriptEngine.InitializeEngine(this);
  3371. }
  3372. public void TriggerObjectChanged(uint localID, uint change)
  3373. {
  3374. m_eventManager.TriggerOnScriptChangedEvent(localID, change);
  3375. }
  3376. public void TriggerAtTargetEvent(uint localID, uint handle, Vector3 targetpos, Vector3 currentpos)
  3377. {
  3378. m_eventManager.TriggerAtTargetEvent(localID, handle, targetpos, currentpos);
  3379. }
  3380. public void TriggerNotAtTargetEvent(uint localID)
  3381. {
  3382. m_eventManager.TriggerNotAtTargetEvent(localID);
  3383. }
  3384. private bool ScriptDanger(SceneObjectPart part,Vector3 pos)
  3385. {
  3386. ILandObject parcel = LandChannel.GetLandObject(pos.X, pos.Y);
  3387. if (part != null)
  3388. {
  3389. if (parcel != null)
  3390. {
  3391. if ((parcel.landData.Flags & (uint)Parcel.ParcelFlags.AllowOtherScripts) != 0)
  3392. {
  3393. return true;
  3394. }
  3395. else if ((parcel.landData.Flags & (uint)Parcel.ParcelFlags.AllowGroupScripts) != 0)
  3396. {
  3397. if (part.OwnerID == parcel.landData.OwnerID || (parcel.landData.IsGroupOwned && part.GroupID == parcel.landData.GroupID) || Permissions.IsGod(part.OwnerID))
  3398. {
  3399. return true;
  3400. }
  3401. else
  3402. {
  3403. return false;
  3404. }
  3405. }
  3406. else
  3407. {
  3408. if (part.OwnerID == parcel.landData.OwnerID)
  3409. {
  3410. return true;
  3411. }
  3412. else
  3413. {
  3414. return false;
  3415. }
  3416. }
  3417. }
  3418. else
  3419. {
  3420. if (pos.X > 0f && pos.X < Constants.RegionSize && pos.Y > 0f && pos.Y < Constants.RegionSize)
  3421. {
  3422. // The only time parcel != null when an object is inside a region is when
  3423. // there is nothing behind the landchannel. IE, no land plugin loaded.
  3424. return true;
  3425. }
  3426. else
  3427. {
  3428. // The object is outside of this region. Stop piping events to it.
  3429. return false;
  3430. }
  3431. }
  3432. }
  3433. else
  3434. {
  3435. return false;
  3436. }
  3437. }
  3438. public bool ScriptDanger(uint localID, Vector3 pos)
  3439. {
  3440. SceneObjectPart part = GetSceneObjectPart(localID);
  3441. if (part != null)
  3442. {
  3443. return ScriptDanger(part, pos);
  3444. }
  3445. else
  3446. {
  3447. return false;
  3448. }
  3449. }
  3450. public bool PipeEventsForScript(uint localID)
  3451. {
  3452. SceneObjectPart part = GetSceneObjectPart(localID);
  3453. if (part != null)
  3454. {
  3455. // Changed so that child prims of attachments return ScriptDanger for their parent, so that
  3456. // their scripts will actually run.
  3457. // -- Leaf, Tue Aug 12 14:17:05 EDT 2008
  3458. SceneObjectPart parent = part.ParentGroup.RootPart;
  3459. if (parent != null && parent.IsAttachment)
  3460. return ScriptDanger(parent, parent.GetWorldPosition());
  3461. else
  3462. return ScriptDanger(part, part.GetWorldPosition());
  3463. }
  3464. else
  3465. {
  3466. return false;
  3467. }
  3468. }
  3469. #endregion
  3470. #region SceneGraph wrapper methods
  3471. /// <summary>
  3472. ///
  3473. /// </summary>
  3474. /// <param name="localID"></param>
  3475. /// <returns></returns>
  3476. public UUID ConvertLocalIDToFullID(uint localID)
  3477. {
  3478. return m_sceneGraph.ConvertLocalIDToFullID(localID);
  3479. }
  3480. public void SwapRootAgentCount(bool rootChildChildRootTF)
  3481. {
  3482. m_sceneGraph.SwapRootChildAgent(rootChildChildRootTF);
  3483. }
  3484. public void AddPhysicalPrim(int num)
  3485. {
  3486. m_sceneGraph.AddPhysicalPrim(num);
  3487. }
  3488. public void RemovePhysicalPrim(int num)
  3489. {
  3490. m_sceneGraph.RemovePhysicalPrim(num);
  3491. }
  3492. //The idea is to have a group of method that return a list of avatars meeting some requirement
  3493. // ie it could be all m_scenePresences within a certain range of the calling prim/avatar.
  3494. /// <summary>
  3495. /// Return a list of all avatars in this region.
  3496. /// This list is a new object, so it can be iterated over without locking.
  3497. /// </summary>
  3498. /// <returns></returns>
  3499. public List<ScenePresence> GetAvatars()
  3500. {
  3501. return m_sceneGraph.GetAvatars();
  3502. }
  3503. /// <summary>
  3504. /// Return a list of all ScenePresences in this region. This returns child agents as well as root agents.
  3505. /// This list is a new object, so it can be iterated over without locking.
  3506. /// </summary>
  3507. /// <returns></returns>
  3508. public List<ScenePresence> GetScenePresences()
  3509. {
  3510. return m_sceneGraph.GetScenePresences();
  3511. }
  3512. /// <summary>
  3513. /// Request a filtered list of ScenePresences in this region.
  3514. /// This list is a new object, so it can be iterated over without locking.
  3515. /// </summary>
  3516. /// <param name="filter"></param>
  3517. /// <returns></returns>
  3518. public List<ScenePresence> GetScenePresences(FilterAvatarList filter)
  3519. {
  3520. return m_sceneGraph.GetScenePresences(filter);
  3521. }
  3522. /// <summary>
  3523. /// Request a scene presence by UUID
  3524. /// </summary>
  3525. /// <param name="avatarID"></param>
  3526. /// <returns></returns>
  3527. public ScenePresence GetScenePresence(UUID avatarID)
  3528. {
  3529. return m_sceneGraph.GetScenePresence(avatarID);
  3530. }
  3531. public override bool PresenceChildStatus(UUID avatarID)
  3532. {
  3533. ScenePresence cp = GetScenePresence(avatarID);
  3534. // FIXME: This is really crap - some logout code is relying on a NullReferenceException to halt its processing
  3535. // This needs to be fixed properly by cleaning up the logout code.
  3536. //if (cp != null)
  3537. // return cp.IsChildAgent;
  3538. //return false;
  3539. return cp.IsChildAgent;
  3540. }
  3541. /// <summary>
  3542. ///
  3543. /// </summary>
  3544. /// <param name="action"></param>
  3545. public void ForEachScenePresence(Action<ScenePresence> action)
  3546. {
  3547. // We don't want to try to send messages if there are no avatars.
  3548. if (m_scenePresences != null)
  3549. {
  3550. try
  3551. {
  3552. List<ScenePresence> presenceList = GetScenePresences();
  3553. foreach (ScenePresence presence in presenceList)
  3554. {
  3555. action(presence);
  3556. }
  3557. }
  3558. catch (Exception e)
  3559. {
  3560. m_log.Info("[BUG]: " + e.ToString());
  3561. }
  3562. }
  3563. }
  3564. /// <summary>
  3565. ///
  3566. /// </summary>
  3567. /// <param name="action"></param>
  3568. // public void ForEachObject(Action<SceneObjectGroup> action)
  3569. // {
  3570. // List<SceneObjectGroup> presenceList;
  3571. //
  3572. // lock (m_sceneObjects)
  3573. // {
  3574. // presenceList = new List<SceneObjectGroup>(m_sceneObjects.Values);
  3575. // }
  3576. //
  3577. // foreach (SceneObjectGroup presence in presenceList)
  3578. // {
  3579. // action(presence);
  3580. // }
  3581. // }
  3582. /// <summary>
  3583. /// Get a named prim contained in this scene (will return the first
  3584. /// found, if there are more than one prim with the same name)
  3585. /// </summary>
  3586. /// <param name="name"></param>
  3587. /// <returns></returns>
  3588. public SceneObjectPart GetSceneObjectPart(string name)
  3589. {
  3590. return m_sceneGraph.GetSceneObjectPart(name);
  3591. }
  3592. /// <summary>
  3593. /// Get a prim via its local id
  3594. /// </summary>
  3595. /// <param name="localID"></param>
  3596. /// <returns></returns>
  3597. public SceneObjectPart GetSceneObjectPart(uint localID)
  3598. {
  3599. return m_sceneGraph.GetSceneObjectPart(localID);
  3600. }
  3601. /// <summary>
  3602. /// Get a prim via its UUID
  3603. /// </summary>
  3604. /// <param name="fullID"></param>
  3605. /// <returns></returns>
  3606. public SceneObjectPart GetSceneObjectPart(UUID fullID)
  3607. {
  3608. return m_sceneGraph.GetSceneObjectPart(fullID);
  3609. }
  3610. internal bool TryGetAvatar(UUID avatarId, out ScenePresence avatar)
  3611. {
  3612. return m_sceneGraph.TryGetAvatar(avatarId, out avatar);
  3613. }
  3614. internal bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
  3615. {
  3616. return m_sceneGraph.TryGetAvatarByName(avatarName, out avatar);
  3617. }
  3618. public void ForEachClient(Action<IClientAPI> action)
  3619. {
  3620. m_sceneGraph.ForEachClient(action);
  3621. }
  3622. /// <summary>
  3623. /// Returns a list of the entities in the scene. This is a new list so operations perform on the list itself
  3624. /// will not affect the original list of objects in the scene.
  3625. /// </summary>
  3626. /// <returns></returns>
  3627. public List<EntityBase> GetEntities()
  3628. {
  3629. return m_sceneGraph.GetEntities();
  3630. }
  3631. #endregion
  3632. #region BaseHTTPServer wrapper methods
  3633. public bool AddHTTPHandler(string method, GenericHTTPMethod handler)
  3634. {
  3635. return m_httpListener.AddHTTPHandler(method, handler);
  3636. }
  3637. public bool AddXmlRPCHandler(string method, XmlRpcMethod handler)
  3638. {
  3639. return m_httpListener.AddXmlRPCHandler(method, handler);
  3640. }
  3641. public void AddStreamHandler(IRequestHandler handler)
  3642. {
  3643. m_httpListener.AddStreamHandler(handler);
  3644. }
  3645. public bool AddLLSDHandler(string path, LLSDMethod handler)
  3646. {
  3647. return m_httpListener.AddLLSDHandler(path, handler);
  3648. }
  3649. public void RemoveStreamHandler(string httpMethod, string path)
  3650. {
  3651. m_httpListener.RemoveStreamHandler(httpMethod, path);
  3652. }
  3653. public void RemoveHTTPHandler(string httpMethod, string path)
  3654. {
  3655. m_httpListener.RemoveHTTPHandler(httpMethod, path);
  3656. }
  3657. public bool RemoveLLSDHandler(string path, LLSDMethod handler)
  3658. {
  3659. return m_httpListener.RemoveLLSDHandler(path, handler);
  3660. }
  3661. #endregion
  3662. #region Avatar Appearance Default
  3663. public static void GetDefaultAvatarAppearance(out AvatarWearable[] wearables, out byte[] visualParams)
  3664. {
  3665. visualParams = GetDefaultVisualParams();
  3666. wearables = AvatarWearable.DefaultWearables;
  3667. }
  3668. private static byte[] GetDefaultVisualParams()
  3669. {
  3670. byte[] visualParams;
  3671. visualParams = new byte[218];
  3672. for (int i = 0; i < 218; i++)
  3673. {
  3674. visualParams[i] = 100;
  3675. }
  3676. return visualParams;
  3677. }
  3678. #endregion
  3679. public void ParcelMediaSetTime(float time)
  3680. {
  3681. //should be doing this by parcel, but as its only for testing
  3682. // The use of Thread.Sleep here causes the following compiler error under mono 1.2.4
  3683. // OpenSim/Region/Environment/Scenes/Scene.cs(3675,17): error CS0103: The name `Thread' does not exist
  3684. // in the context of `<>c__CompilerGenerated17'
  3685. // MW said it was okay to comment the body of this method out for now since the code is experimental
  3686. // and will be replaced anyway
  3687. // ForEachClient(delegate(IClientAPI client)
  3688. // {
  3689. // client.SendParcelMediaCommand((uint)(2), ParcelMediaCommandEnum.Pause, 0);
  3690. // Thread.Sleep(10);
  3691. // client.SendParcelMediaCommand((uint)(64), ParcelMediaCommandEnum.Time, time);
  3692. // Thread.Sleep(200);
  3693. // client.SendParcelMediaCommand((uint)(4), ParcelMediaCommandEnum.Play, 0);
  3694. // });
  3695. }
  3696. public void RegionHandleRequest(IClientAPI client, UUID regionID)
  3697. {
  3698. RegionInfo info;
  3699. if (regionID == RegionInfo.RegionID)
  3700. info = RegionInfo;
  3701. else
  3702. info = CommsManager.GridService.RequestNeighbourInfo(regionID);
  3703. if (info != null)
  3704. client.SendRegionHandle(regionID, info.RegionHandle);
  3705. }
  3706. public void TerrainUnAcked(IClientAPI client, int patchX, int patchY)
  3707. {
  3708. //Console.WriteLine("Terrain packet unacked, resending patch: " + patchX + " , " + patchY);
  3709. client.SendLayerData(patchX, patchY, Heightmap.GetFloatsSerialised());
  3710. }
  3711. public void SetRootAgentScene(UUID agentID)
  3712. {
  3713. IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  3714. if (inv == null)
  3715. return;
  3716. inv.SetRootAgentScene(agentID, this);
  3717. EventManager.TriggerSetRootAgentScene(agentID, this);
  3718. }
  3719. public bool NeedSceneCacheClear(UUID agentID)
  3720. {
  3721. IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  3722. if (inv == null)
  3723. return true;
  3724. return inv.NeedSceneCacheClear(agentID, this);
  3725. }
  3726. public void ObjectSaleInfo(IClientAPI client, UUID agentID, UUID sessionID, uint localID, byte saleType, int salePrice)
  3727. {
  3728. SceneObjectPart part = GetSceneObjectPart(localID);
  3729. if (part == null || part.ParentGroup == null)
  3730. return;
  3731. if (part.ParentGroup.IsDeleted)
  3732. return;
  3733. part = part.ParentGroup.RootPart;
  3734. part.ObjectSaleType = saleType;
  3735. part.SalePrice = salePrice;
  3736. part.ParentGroup.HasGroupChanged = true;
  3737. part.GetProperties(client);
  3738. }
  3739. public bool PerformObjectBuy(IClientAPI remoteClient, UUID categoryID,
  3740. uint localID, byte saleType)
  3741. {
  3742. SceneObjectPart part = GetSceneObjectPart(localID);
  3743. if (part == null)
  3744. return false;
  3745. if (part.ParentGroup == null)
  3746. return false;
  3747. SceneObjectGroup group = part.ParentGroup;
  3748. switch (saleType)
  3749. {
  3750. case 1: // Sell as original (in-place sale)
  3751. uint effectivePerms=group.GetEffectivePermissions();
  3752. if ((effectivePerms & (uint)PermissionMask.Transfer) == 0)
  3753. {
  3754. remoteClient.SendAgentAlertMessage("This item doesn't appear to be for sale", false);
  3755. return false;
  3756. }
  3757. group.SetOwnerId(remoteClient.AgentId);
  3758. group.SetRootPartOwner(part, remoteClient.AgentId,
  3759. remoteClient.ActiveGroupId);
  3760. List<SceneObjectPart> partList =
  3761. new List<SceneObjectPart>(group.Children.Values);
  3762. if (Permissions.PropagatePermissions())
  3763. {
  3764. foreach (SceneObjectPart child in partList)
  3765. {
  3766. child.Inventory.ChangeInventoryOwner(remoteClient.AgentId);
  3767. child.ApplyNextOwnerPermissions();
  3768. }
  3769. }
  3770. part.ObjectSaleType = 0;
  3771. part.SalePrice = 10;
  3772. group.HasGroupChanged = true;
  3773. part.GetProperties(remoteClient);
  3774. part.ScheduleFullUpdate();
  3775. break;
  3776. case 2: // Sell a copy
  3777. string sceneObjectXml = group.ToXmlString();
  3778. CachedUserInfo userInfo =
  3779. CommsManager.UserProfileCacheService.GetUserDetails(remoteClient.AgentId);
  3780. if (userInfo != null)
  3781. {
  3782. uint perms=group.GetEffectivePermissions();
  3783. if ((perms & (uint)PermissionMask.Transfer) == 0)
  3784. {
  3785. remoteClient.SendAgentAlertMessage("This item doesn't appear to be for sale", false);
  3786. return false;
  3787. }
  3788. AssetBase asset = CreateAsset(
  3789. group.GetPartName(localID),
  3790. group.GetPartDescription(localID),
  3791. (sbyte)AssetType.Object,
  3792. Utils.StringToBytes(sceneObjectXml));
  3793. AssetCache.AddAsset(asset);
  3794. InventoryItemBase item = new InventoryItemBase();
  3795. item.Creator = part.CreatorID;
  3796. item.ID = UUID.Random();
  3797. item.Owner = remoteClient.AgentId;
  3798. item.AssetID = asset.FullID;
  3799. item.Description = asset.Description;
  3800. item.Name = asset.Name;
  3801. item.AssetType = asset.Type;
  3802. item.InvType = (int)InventoryType.Object;
  3803. item.Folder = categoryID;
  3804. uint nextPerms=(perms & 7) << 13;
  3805. if ((nextPerms & (uint)PermissionMask.Copy) == 0)
  3806. perms &= ~(uint)PermissionMask.Copy;
  3807. if ((nextPerms & (uint)PermissionMask.Transfer) == 0)
  3808. perms &= ~(uint)PermissionMask.Transfer;
  3809. if ((nextPerms & (uint)PermissionMask.Modify) == 0)
  3810. perms &= ~(uint)PermissionMask.Modify;
  3811. item.BasePermissions = perms & part.NextOwnerMask;
  3812. item.CurrentPermissions = perms & part.NextOwnerMask;
  3813. item.NextPermissions = part.NextOwnerMask;
  3814. item.EveryOnePermissions = part.EveryoneMask &
  3815. part.NextOwnerMask;
  3816. item.GroupPermissions = part.GroupMask &
  3817. part.NextOwnerMask;
  3818. item.CurrentPermissions |= 8; // Slam!
  3819. item.CreationDate = Util.UnixTimeSinceEpoch();
  3820. userInfo.AddItem(item);
  3821. remoteClient.SendInventoryItemCreateUpdate(item);
  3822. }
  3823. else
  3824. {
  3825. remoteClient.SendAgentAlertMessage("Cannot buy now. Your inventory is unavailable", false);
  3826. return false;
  3827. }
  3828. break;
  3829. case 3: // Sell contents
  3830. List<UUID> invList = part.Inventory.GetInventoryList();
  3831. bool okToSell = true;
  3832. foreach (UUID invID in invList)
  3833. {
  3834. TaskInventoryItem item = part.Inventory.GetInventoryItem(invID);
  3835. if ((item.CurrentPermissions &
  3836. (uint)PermissionMask.Transfer) == 0)
  3837. {
  3838. okToSell = false;
  3839. break;
  3840. }
  3841. }
  3842. if (!okToSell)
  3843. {
  3844. remoteClient.SendAgentAlertMessage("This item's inventory doesn't appear to be for sale", false);
  3845. return false;
  3846. }
  3847. if (invList.Count > 0)
  3848. MoveTaskInventoryItems(remoteClient.AgentId, part.Name,
  3849. part, invList);
  3850. break;
  3851. }
  3852. return true;
  3853. }
  3854. public void CleanTempObjects()
  3855. {
  3856. List<EntityBase> objs = GetEntities();
  3857. foreach (EntityBase obj in objs)
  3858. {
  3859. if (obj is SceneObjectGroup)
  3860. {
  3861. SceneObjectGroup grp = (SceneObjectGroup)obj;
  3862. if (!grp.IsDeleted)
  3863. {
  3864. if ((grp.RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
  3865. {
  3866. if (grp.RootPart.Expires <= DateTime.Now)
  3867. DeleteSceneObject(grp, false);
  3868. }
  3869. }
  3870. }
  3871. }
  3872. }
  3873. public void DeleteFromStorage(UUID uuid)
  3874. {
  3875. m_storageManager.DataStore.RemoveObject(uuid, m_regInfo.RegionID);
  3876. }
  3877. public int GetHealth()
  3878. {
  3879. int health=1; // Start at 1, means we're up
  3880. // A login in the last 4 mins? We can't be doing too badly
  3881. //
  3882. if ((System.Environment.TickCount - m_LastLogin) < 240000)
  3883. health++;
  3884. return 0;
  3885. }
  3886. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  3887. // update non-physical objects like the joint proxy objects that represent the position
  3888. // of the joints in the scene.
  3889. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  3890. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  3891. // from within the OdePhysicsScene.
  3892. protected internal void jointMoved(PhysicsJoint joint)
  3893. {
  3894. // m_parentScene.PhysicsScene.DumpJointInfo(); // non-thread-locked version; we should already be in a lock (OdeLock) when this callback is invoked
  3895. // FIXME: this causes a sequential lookup of all objects in the scene; use a dictionary
  3896. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  3897. if (jointProxyObject == null)
  3898. {
  3899. jointErrorMessage(joint, "WARNING, joint proxy not found, name " + joint.ObjectNameInScene);
  3900. return;
  3901. }
  3902. // now update the joint proxy object in the scene to have the position of the joint as returned by the physics engine
  3903. SceneObjectPart trackedBody = GetSceneObjectPart(joint.TrackedBodyName); // FIXME: causes a sequential lookup
  3904. 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.
  3905. jointProxyObject.Velocity = trackedBody.Velocity;
  3906. jointProxyObject.RotationalVelocity = trackedBody.RotationalVelocity;
  3907. switch (joint.Type)
  3908. {
  3909. case PhysicsJointType.Ball:
  3910. {
  3911. PhysicsVector jointAnchor = PhysicsScene.GetJointAnchor(joint);
  3912. Vector3 proxyPos = new Vector3(jointAnchor.X, jointAnchor.Y, jointAnchor.Z);
  3913. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  3914. }
  3915. break;
  3916. case PhysicsJointType.Hinge:
  3917. {
  3918. PhysicsVector jointAnchor = PhysicsScene.GetJointAnchor(joint);
  3919. // Normally, we would just ask the physics scene to return the axis for the joint.
  3920. // Unfortunately, ODE sometimes returns <0,0,0> for the joint axis, which should
  3921. // never occur. Therefore we cannot rely on ODE to always return a correct joint axis.
  3922. // Therefore the following call does not always work:
  3923. //PhysicsVector phyJointAxis = _PhyScene.GetJointAxis(joint);
  3924. // instead we compute the joint orientation by saving the original joint orientation
  3925. // relative to one of the jointed bodies, and applying this transformation
  3926. // to the current position of the jointed bodies (the tracked body) to compute the
  3927. // current joint orientation.
  3928. if (joint.TrackedBodyName == null)
  3929. {
  3930. jointErrorMessage(joint, "joint.TrackedBodyName is null, joint " + joint.ObjectNameInScene);
  3931. }
  3932. Vector3 proxyPos = new Vector3(jointAnchor.X, jointAnchor.Y, jointAnchor.Z);
  3933. Quaternion q = trackedBody.RotationOffset * joint.LocalRotation;
  3934. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  3935. jointProxyObject.ParentGroup.UpdateGroupRotation(q); // schedules the entire group for a terse update
  3936. }
  3937. break;
  3938. }
  3939. }
  3940. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  3941. // update non-physical objects like the joint proxy objects that represent the position
  3942. // of the joints in the scene.
  3943. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  3944. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  3945. // from within the OdePhysicsScene.
  3946. protected internal void jointDeactivated(PhysicsJoint joint)
  3947. {
  3948. //m_log.Debug("[NINJA] SceneGraph.jointDeactivated, joint:" + joint.ObjectNameInScene);
  3949. // FIXME: this causes a sequential lookup of all objects in the scene; use a dictionary
  3950. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  3951. if (jointProxyObject == null)
  3952. {
  3953. jointErrorMessage(joint, "WARNING, trying to deactivate (stop interpolation of) joint proxy, but not found, name " + joint.ObjectNameInScene);
  3954. return;
  3955. }
  3956. // turn the proxy non-physical, which also stops its client-side interpolation
  3957. bool wasUsingPhysics = ((jointProxyObject.ObjectFlags & (uint)PrimFlags.Physics) != 0);
  3958. if (wasUsingPhysics)
  3959. {
  3960. 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
  3961. }
  3962. }
  3963. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  3964. // alert the user of errors by using the debug channel in the same way that scripts alert
  3965. // the user of compile errors.
  3966. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  3967. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  3968. // from within the OdePhysicsScene.
  3969. public void jointErrorMessage(PhysicsJoint joint, string message)
  3970. {
  3971. // FIXME: this causes a sequential lookup of all objects in the scene; use a dictionary
  3972. if (joint != null)
  3973. {
  3974. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  3975. return;
  3976. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  3977. if (jointProxyObject != null)
  3978. {
  3979. SimChat(Utils.StringToBytes("[NINJA] " + message),
  3980. ChatTypeEnum.DebugChannel,
  3981. 2147483647,
  3982. jointProxyObject.AbsolutePosition,
  3983. jointProxyObject.Name,
  3984. jointProxyObject.UUID,
  3985. false);
  3986. joint.ErrorMessageCount++;
  3987. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  3988. {
  3989. SimChat(Utils.StringToBytes("[NINJA] Too many messages for this joint, suppressing further messages."),
  3990. ChatTypeEnum.DebugChannel,
  3991. 2147483647,
  3992. jointProxyObject.AbsolutePosition,
  3993. jointProxyObject.Name,
  3994. jointProxyObject.UUID,
  3995. false);
  3996. }
  3997. }
  3998. else
  3999. {
  4000. // couldn't find the joint proxy object; the error message is silently suppressed
  4001. }
  4002. }
  4003. }
  4004. }
  4005. }