Scene.cs 126 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the 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.Threading;
  32. using System.Timers;
  33. using Axiom.Math;
  34. using libsecondlife;
  35. using libsecondlife.Packets;
  36. using OpenJPEGNet;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Communications;
  39. using OpenSim.Framework.Communications.Cache;
  40. using OpenSim.Framework.Servers;
  41. using OpenSim.Region.Environment.Interfaces;
  42. using OpenSim.Region.Environment.Modules.World.Terrain;
  43. using OpenSim.Region.Environment.Scenes.Scripting;
  44. using OpenSim.Region.Physics.Manager;
  45. using Caps=OpenSim.Framework.Communications.Capabilities.Caps;
  46. using Image=System.Drawing.Image;
  47. using Timer=System.Timers.Timer;
  48. namespace OpenSim.Region.Environment.Scenes
  49. {
  50. public delegate bool FilterAvatarList(ScenePresence avatar);
  51. public partial class Scene : SceneBase
  52. {
  53. public delegate void SynchronizeSceneHandler(Scene scene);
  54. public SynchronizeSceneHandler SynchronizeScene = null;
  55. public int splitID = 0;
  56. #region Fields
  57. protected Timer m_heartbeatTimer = new Timer();
  58. protected Timer m_restartWaitTimer = new Timer();
  59. protected SimStatsReporter m_statsReporter;
  60. protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
  61. protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
  62. public InnerScene m_innerScene;
  63. private Random Rand = new Random();
  64. private uint _primCount = 720000;
  65. private readonly Mutex _primAllocateMutex = new Mutex(false);
  66. private int m_timePhase = 24;
  67. private readonly Mutex updateLock;
  68. public bool m_physicalPrim;
  69. public bool m_seeIntoRegionFromNeighbor;
  70. public int MaxUndoCount = 5;
  71. private int m_RestartTimerCounter;
  72. private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing
  73. private int m_incrementsof15seconds = 0;
  74. public string m_simulatorVersion = "OpenSimulator 0.5";
  75. protected ModuleLoader m_moduleLoader;
  76. protected StorageManager m_storageManager;
  77. protected AgentCircuitManager m_authenticateHandler;
  78. public CommunicationsManager CommsManager;
  79. // protected XferManager xferManager;
  80. protected SceneCommunicationService m_sceneGridService;
  81. protected SceneXmlLoader m_sceneXmlLoader;
  82. /// <summary>
  83. /// Each agent has its own capabilities handler.
  84. /// </summary>
  85. protected Dictionary<LLUUID, Caps> m_capsHandlers = new Dictionary<LLUUID, Caps>();
  86. protected BaseHttpServer m_httpListener;
  87. protected Dictionary<string, IRegionModule> Modules = new Dictionary<string, IRegionModule>();
  88. public Dictionary<Type, object> ModuleInterfaces = new Dictionary<Type, object>();
  89. protected Dictionary<string, object> ModuleAPIMethods = new Dictionary<string, object>();
  90. public Dictionary<string, ICommander> m_moduleCommanders = new Dictionary<string, ICommander>();
  91. //API module interfaces
  92. public IXfer XferManager;
  93. protected IHttpRequests m_httpRequestModule;
  94. protected ISimChat m_simChatModule;
  95. protected IXMLRPC m_xmlrpcModule;
  96. protected IWorldComm m_worldCommModule;
  97. protected IAvatarFactory m_AvatarFactory;
  98. // Central Update Loop
  99. protected int m_fps = 10;
  100. protected int m_frame = 0;
  101. protected float m_timespan = 0.089f;
  102. protected DateTime m_lastupdate = DateTime.Now;
  103. protected float m_timedilation = 1.0f;
  104. private int m_update_physics = 1;
  105. private int m_update_entitymovement = 1;
  106. private int m_update_entities = 1; // Run through all objects checking for updates
  107. private int m_update_entitiesquick = 200; // Run through objects that have scheduled updates checking for updates
  108. private int m_update_presences = 1; // Update scene presence movements
  109. private int m_update_events = 1;
  110. private int m_update_backup = 200;
  111. private int m_update_terrain = 50;
  112. private int m_update_land = 1;
  113. private int frameMS = 0;
  114. private int physicsMS2 = 0;
  115. private int physicsMS = 0;
  116. private int otherMS = 0;
  117. private bool m_physics_enabled = true;
  118. private bool m_scripts_enabled = true;
  119. #endregion
  120. #region Properties
  121. public AgentCircuitManager AuthenticateHandler
  122. {
  123. get { return m_authenticateHandler; }
  124. }
  125. protected readonly EstateManager m_estateManager;
  126. // an instance to the physics plugin's Scene object.
  127. public PhysicsScene PhysicsScene
  128. {
  129. set { m_innerScene.PhysicsScene = value; }
  130. get { return (m_innerScene.PhysicsScene); }
  131. }
  132. // This gets locked so things stay thread safe.
  133. public object SyncRoot
  134. {
  135. get { return m_innerScene.m_syncRoot; }
  136. }
  137. public EstateManager EstateManager
  138. {
  139. get { return m_estateManager; }
  140. }
  141. public float TimeDilation
  142. {
  143. get { return m_timedilation; }
  144. }
  145. protected readonly PermissionManager m_permissionManager;
  146. // This is the instance to the permissions manager.
  147. // This manages permissions to clients on in world objects
  148. public PermissionManager PermissionsMngr
  149. {
  150. get { return m_permissionManager; }
  151. }
  152. public int TimePhase
  153. {
  154. get { return m_timePhase; }
  155. }
  156. // Local reference to the objects in the scene (which are held in innerScene)
  157. // public Dictionary<LLUUID, SceneObjectGroup> Objects
  158. // {
  159. // get { return m_innerScene.SceneObjects; }
  160. // }
  161. // Reference to all of the agents in the scene (root and child)
  162. protected Dictionary<LLUUID, ScenePresence> m_scenePresences
  163. {
  164. get { return m_innerScene.ScenePresences; }
  165. set { m_innerScene.ScenePresences = value; }
  166. }
  167. // protected Dictionary<LLUUID, SceneObjectGroup> m_sceneObjects
  168. // {
  169. // get { return m_innerScene.SceneObjects; }
  170. // set { m_innerScene.SceneObjects = value; }
  171. // }
  172. public Dictionary<LLUUID, EntityBase> Entities
  173. {
  174. get { return m_innerScene.Entities; }
  175. set { m_innerScene.Entities = value; }
  176. }
  177. public Dictionary<LLUUID, ScenePresence> m_restorePresences
  178. {
  179. get { return m_innerScene.RestorePresences; }
  180. set { m_innerScene.RestorePresences = value; }
  181. }
  182. public int objectCapacity = 45000;
  183. #endregion
  184. #region Constructors
  185. public Scene(RegionInfo regInfo, AgentCircuitManager authen, PermissionManager permissionManager,
  186. CommunicationsManager commsMan, SceneCommunicationService sceneGridService,
  187. AssetCache assetCach, StorageManager storeManager, BaseHttpServer httpServer,
  188. ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim, bool SeeIntoRegionFromNeighbor)
  189. {
  190. updateLock = new Mutex(false);
  191. m_moduleLoader = moduleLoader;
  192. m_authenticateHandler = authen;
  193. CommsManager = commsMan;
  194. m_sceneGridService = sceneGridService;
  195. m_sceneGridService.debugRegionName = regInfo.RegionName;
  196. m_storageManager = storeManager;
  197. AssetCache = assetCach;
  198. m_regInfo = regInfo;
  199. m_regionHandle = m_regInfo.RegionHandle;
  200. m_regionName = m_regInfo.RegionName;
  201. m_datastore = m_regInfo.DataStore;
  202. m_physicalPrim = physicalPrim;
  203. m_seeIntoRegionFromNeighbor = SeeIntoRegionFromNeighbor;
  204. m_eventManager = new EventManager();
  205. //Bind Storage Manager functions to some land manager functions for this scene
  206. EventManager.OnLandObjectAdded +=
  207. new EventManager.LandObjectAdded(m_storageManager.DataStore.StoreLandObject);
  208. EventManager.OnLandObjectRemoved +=
  209. new EventManager.LandObjectRemoved(m_storageManager.DataStore.RemoveLandObject);
  210. m_estateManager = new EstateManager(this, m_regInfo);
  211. m_permissionManager = permissionManager;
  212. m_permissionManager.Initialise(this);
  213. m_innerScene = new InnerScene(this, m_regInfo, m_permissionManager);
  214. // If the Inner scene has an Unrecoverable error, restart this sim.
  215. // Currently the only thing that causes it to happen is two kinds of specific
  216. // Physics based crashes.
  217. //
  218. // Out of memory
  219. // Operating system has killed the plugin
  220. m_innerScene.UnRecoverableError += RestartNow;
  221. m_sceneXmlLoader = new SceneXmlLoader(this, m_innerScene, m_regInfo);
  222. RegisterDefaultSceneEvents();
  223. m_log.Info("[SCENE]: Creating new entitities instance");
  224. Entities = new Dictionary<LLUUID, EntityBase>();
  225. m_scenePresences = new Dictionary<LLUUID, ScenePresence>();
  226. //m_sceneObjects = new Dictionary<LLUUID, SceneObjectGroup>();
  227. m_restorePresences = new Dictionary<LLUUID, ScenePresence>();
  228. m_httpListener = httpServer;
  229. m_dumpAssetsToFile = dumpAssetsToFile;
  230. if ((RegionInfo.EstateSettings.regionFlags & Simulator.RegionFlags.SkipScripts) == Simulator.RegionFlags.SkipScripts)
  231. {
  232. m_scripts_enabled = false;
  233. }
  234. else
  235. {
  236. m_scripts_enabled = true;
  237. }
  238. if ((RegionInfo.EstateSettings.regionFlags & Simulator.RegionFlags.SkipPhysics) == Simulator.RegionFlags.SkipPhysics)
  239. {
  240. m_physics_enabled = false;
  241. }
  242. else
  243. {
  244. m_physics_enabled = true;
  245. }
  246. m_statsReporter = new SimStatsReporter(regInfo);
  247. m_statsReporter.OnSendStatsResult += SendSimStatsPackets;
  248. m_statsReporter.SetObjectCapacity(objectCapacity);
  249. string OSString = "";
  250. if (System.Environment.OSVersion.Platform != PlatformID.Unix)
  251. {
  252. OSString = System.Environment.OSVersion.ToString();
  253. }
  254. else
  255. {
  256. OSString = Util.ReadEtcIssue();
  257. }
  258. if (OSString.Length > 45)
  259. {
  260. OSString = OSString.Substring(0, 45);
  261. }
  262. m_simulatorVersion = "OpenSimulator v0.5-SVN on " + OSString + " ChilTasks:" + m_seeIntoRegionFromNeighbor.ToString() + " PhysPrim:" + m_physicalPrim.ToString();
  263. }
  264. #endregion
  265. #region Startup / Close Methods
  266. protected virtual void RegisterDefaultSceneEvents()
  267. {
  268. m_eventManager.OnPermissionError += SendPermissionAlert;
  269. }
  270. public override string GetSimulatorVersion()
  271. {
  272. return m_simulatorVersion;
  273. }
  274. public override bool OtherRegionUp(RegionInfo otherRegion)
  275. {
  276. // Another region is up.
  277. // Gets called from Grid Comms (SceneCommunicationService<---RegionListener<----LocalBackEnd<----OGS1)
  278. // We have to tell all our ScenePresences about it..
  279. // and add it to the neighbor list.
  280. // We only add it to the neighbor list if it's within 1 region from here.
  281. // Agents may have draw distance values that cross two regions though, so
  282. // we add it to the notify list regardless of distance.
  283. // We'll check the agent's draw distance before notifying them though.
  284. if (RegionInfo.RegionHandle != otherRegion.RegionHandle)
  285. {
  286. for (int i = 0; i < m_neighbours.Count; i++)
  287. {
  288. // The purpose of this loop is to re-update the known neighbors
  289. // when another region comes up on top of another one.
  290. // The latest region in that location ends up in the
  291. // 'known neighbors list'
  292. // Additionally, the commFailTF property gets reset to false.
  293. if (m_neighbours[i].RegionHandle == otherRegion.RegionHandle)
  294. {
  295. lock (m_neighbours)
  296. {
  297. m_neighbours[i] = otherRegion;
  298. }
  299. }
  300. }
  301. // If the value isn't in the neighbours, add it.
  302. // If the RegionInfo isn't exact but is for the same XY World location,
  303. // then the above loop will fix that.
  304. if (!(m_neighbours.Contains(otherRegion)))
  305. {
  306. lock (m_neighbours)
  307. {
  308. m_neighbours.Add(otherRegion);
  309. }
  310. }
  311. // If these are cast to INT because long + negative values + abs returns invalid data
  312. int resultX = Math.Abs((int)otherRegion.RegionLocX - (int)RegionInfo.RegionLocX);
  313. int resultY = Math.Abs((int)otherRegion.RegionLocY - (int)RegionInfo.RegionLocY);
  314. if ((resultX <= 1) &&
  315. (resultY <= 1))
  316. {
  317. try
  318. {
  319. ForEachScenePresence(delegate(ScenePresence agent)
  320. {
  321. // If agent is a root agent.
  322. if (!agent.IsChildAgent)
  323. {
  324. //agent.ControllingClient.new
  325. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  326. InformClientOfNeighbor(agent, otherRegion);
  327. }
  328. }
  329. );
  330. }
  331. catch (NullReferenceException)
  332. {
  333. // This means that we're not booted up completely yet.
  334. // This shouldn't happen too often anymore.
  335. m_log.Error("[SCENE]: Couldn't inform client of regionup because we got a null reference exception");
  336. }
  337. }
  338. else
  339. {
  340. m_log.Info("[INTERGRID]: Got notice about far away Region: " + otherRegion.RegionName.ToString() +
  341. " at (" + otherRegion.RegionLocX.ToString() + ", " +
  342. otherRegion.RegionLocY.ToString() + ")");
  343. }
  344. }
  345. return true;
  346. }
  347. // Given float seconds, this will restart the region.
  348. public virtual void Restart(float seconds)
  349. {
  350. // notifications are done in 15 second increments
  351. // so .. if the number of seconds is less then 15 seconds, it's not really a restart request
  352. // It's a 'Cancel restart' request.
  353. // RestartNow() does immediate restarting.
  354. if (seconds < 15)
  355. {
  356. m_restartTimer.Stop();
  357. SendGeneralAlert("Restart Aborted");
  358. }
  359. else
  360. {
  361. // Now we figure out what to set the timer to that does the notifications and calls, RestartNow()
  362. m_restartTimer.Interval = 15000;
  363. m_incrementsof15seconds = (int)seconds / 15;
  364. m_RestartTimerCounter = 0;
  365. m_restartTimer.AutoReset = true;
  366. m_restartTimer.Elapsed += new ElapsedEventHandler(RestartTimer_Elapsed);
  367. m_log.Error("[REGION]: Restarting Region in " + (seconds / 60) + " minutes");
  368. m_restartTimer.Start();
  369. SendRegionMessageFromEstateTools(LLUUID.Random(), LLUUID.Random(), String.Empty, RegionInfo.RegionName + ": Restarting in 2 Minutes");
  370. //SendGeneralAlert(RegionInfo.RegionName + ": Restarting in 2 Minutes");
  371. }
  372. }
  373. // The Restart timer has occured.
  374. // We have to figure out if this is a notification or if the number of seconds specified in Restart
  375. // have elapsed.
  376. // If they have elapsed, call RestartNow()
  377. public void RestartTimer_Elapsed(object sender, ElapsedEventArgs e)
  378. {
  379. m_RestartTimerCounter++;
  380. if (m_RestartTimerCounter <= m_incrementsof15seconds)
  381. {
  382. if (m_RestartTimerCounter == 4 || m_RestartTimerCounter == 6 || m_RestartTimerCounter == 7)
  383. SendRegionMessageFromEstateTools(LLUUID.Random(), LLUUID.Random(), String.Empty, RegionInfo.RegionName + ": Restarting in " +
  384. ((8 - m_RestartTimerCounter) * 15) + " seconds");
  385. // SendGeneralAlert(RegionInfo.RegionName + ": Restarting in " + ((8 - m_RestartTimerCounter)*15) +
  386. //" seconds");
  387. }
  388. else
  389. {
  390. m_restartTimer.Stop();
  391. m_restartTimer.AutoReset = false;
  392. RestartNow();
  393. }
  394. }
  395. // This causes the region to restart immediatley.
  396. public void RestartNow()
  397. {
  398. if (PhysicsScene != null)
  399. {
  400. PhysicsScene.Dispose();
  401. }
  402. m_log.Error("[REGION]: Closing");
  403. Close();
  404. m_log.Error("[REGION]: Firing Region Restart Message");
  405. base.Restart(0);
  406. }
  407. // This is a helper function that notifies root agents in this region that a new sim near them has come up
  408. // This is in the form of a timer because when an instance of OpenSim.exe is started,
  409. // Even though the sims initialize, they don't listen until 'all of the sims are initialized'
  410. // If we tell an agent about a sim that's not listening yet, the agent will not be able to connect to it.
  411. // subsequently the agent will never see the region come back online.
  412. public void RestartNotifyWaitElapsed(object sender, ElapsedEventArgs e)
  413. {
  414. m_restartWaitTimer.Stop();
  415. lock (m_regionRestartNotifyList)
  416. {
  417. foreach (RegionInfo region in m_regionRestartNotifyList)
  418. {
  419. try
  420. {
  421. ForEachScenePresence(delegate(ScenePresence agent)
  422. {
  423. // If agent is a root agent.
  424. if (!agent.IsChildAgent)
  425. {
  426. //agent.ControllingClient.new
  427. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  428. InformClientOfNeighbor(agent, region);
  429. }
  430. }
  431. );
  432. }
  433. catch (NullReferenceException)
  434. {
  435. // This means that we're not booted up completely yet.
  436. // This shouldn't happen too often anymore.
  437. }
  438. }
  439. // Reset list to nothing.
  440. m_regionRestartNotifyList.Clear();
  441. }
  442. }
  443. public void SetSceneCoreDebug(bool ScriptEngine, bool CollisionEvents, bool PhysicsEngine)
  444. {
  445. if (m_scripts_enabled != !ScriptEngine)
  446. {
  447. // Tedd! Here's the method to disable the scripting engine!
  448. if (ScriptEngine)
  449. {
  450. m_log.Info("Stopping all Scripts in Scene");
  451. lock (Entities)
  452. {
  453. foreach (EntityBase ent in Entities.Values)
  454. {
  455. if (ent is SceneObjectGroup)
  456. {
  457. ((SceneObjectGroup)ent).StopScripts();
  458. }
  459. }
  460. }
  461. }
  462. else
  463. {
  464. m_log.Info("Starting all Scripts in Scene");
  465. lock (Entities)
  466. {
  467. foreach (EntityBase ent in Entities.Values)
  468. {
  469. if (ent is SceneObjectGroup)
  470. {
  471. ((SceneObjectGroup)ent).StartScripts();
  472. }
  473. }
  474. }
  475. }
  476. m_scripts_enabled = !ScriptEngine;
  477. m_log.Info("[TOTEDD]: Here is the method to trigger disabling of the scripting engine");
  478. }
  479. if (m_physics_enabled != !PhysicsEngine)
  480. {
  481. m_physics_enabled = !PhysicsEngine;
  482. }
  483. }
  484. // This is the method that shuts down the scene.
  485. public override void Close()
  486. {
  487. m_log.Warn("[SCENE]: Closing down the single simulator: " + RegionInfo.RegionName);
  488. // Kick all ROOT agents with the message, 'The simulator is going down'
  489. ForEachScenePresence(delegate(ScenePresence avatar)
  490. {
  491. if (avatar.KnownChildRegions.Contains(RegionInfo.RegionHandle))
  492. avatar.KnownChildRegions.Remove(RegionInfo.RegionHandle);
  493. if (!avatar.IsChildAgent)
  494. avatar.ControllingClient.Kick("The simulator is going down.");
  495. avatar.ControllingClient.OutPacket(PacketPool.Instance.GetPacket(PacketType.DisableSimulator),
  496. ThrottleOutPacketType.Task);
  497. });
  498. // Wait here, or the kick messages won't actually get to the agents before the scene terminates.
  499. Thread.Sleep(500);
  500. // Stop all client threads.
  501. ForEachScenePresence(delegate(ScenePresence avatar) { avatar.ControllingClient.Close(true); });
  502. // Stop updating the scene objects and agents.
  503. m_heartbeatTimer.Close();
  504. // close the inner scene
  505. m_innerScene.Close();
  506. // De-register with region communications (events cleanup)
  507. UnRegisterReginWithComms();
  508. // Shut down all non shared modules.
  509. foreach (IRegionModule module in Modules.Values)
  510. {
  511. if (!module.IsSharedModule)
  512. {
  513. module.Close();
  514. }
  515. }
  516. Modules.Clear();
  517. // call the base class Close method.
  518. base.Close();
  519. }
  520. /// <summary>
  521. /// Start the timer which triggers regular scene updates
  522. /// </summary>
  523. public void StartTimer()
  524. {
  525. m_log.Debug("[SCENE]: Starting timer");
  526. m_heartbeatTimer.Enabled = true;
  527. m_heartbeatTimer.Interval = (int)(m_timespan * 1000);
  528. m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat);
  529. }
  530. public void SetModuleInterfaces()
  531. {
  532. m_simChatModule = RequestModuleInterface<ISimChat>();
  533. m_httpRequestModule = RequestModuleInterface<IHttpRequests>();
  534. m_xmlrpcModule = RequestModuleInterface<IXMLRPC>();
  535. m_worldCommModule = RequestModuleInterface<IWorldComm>();
  536. XferManager = RequestModuleInterface<IXfer>();
  537. m_AvatarFactory = RequestModuleInterface<IAvatarFactory>();
  538. }
  539. #endregion
  540. #region Update Methods
  541. /// <summary>
  542. /// Performs per-frame updates regularly
  543. /// </summary>
  544. /// <param name="sender"></param>
  545. /// <param name="e"></param>
  546. private void Heartbeat(object sender, EventArgs e)
  547. {
  548. Update();
  549. }
  550. /// <summary>
  551. /// Performs per-frame updates on the scene, this should be the central scene loop
  552. /// </summary>
  553. public override void Update()
  554. {
  555. TimeSpan SinceLastFrame = DateTime.Now - m_lastupdate;
  556. // Aquire a lock so only one update call happens at once
  557. updateLock.WaitOne();
  558. float physicsFPS = 0;
  559. int agentsInScene = m_innerScene.GetRootAgentCount() + m_innerScene.GetChildAgentCount();
  560. if (agentsInScene > 21)
  561. {
  562. if (m_update_entities == 1)
  563. {
  564. m_update_entities = 5;
  565. m_statsReporter.SetUpdateMS(6000);
  566. }
  567. }
  568. else
  569. {
  570. if (m_update_entities == 5)
  571. {
  572. m_update_entities = 1;
  573. m_statsReporter.SetUpdateMS(3000);
  574. }
  575. }
  576. frameMS = System.Environment.TickCount;
  577. try
  578. {
  579. // Increment the frame counter
  580. m_frame++;
  581. // Loop it
  582. if (m_frame == Int32.MaxValue)
  583. m_frame = 0;
  584. physicsMS2 = System.Environment.TickCount;
  585. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  586. m_innerScene.UpdatePreparePhysics();
  587. physicsMS2 = System.Environment.TickCount - physicsMS2;
  588. if (m_frame % m_update_entitymovement == 0)
  589. m_innerScene.UpdateEntityMovement();
  590. physicsMS = System.Environment.TickCount;
  591. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  592. physicsFPS = m_innerScene.UpdatePhysics(
  593. Math.Max(SinceLastFrame.TotalSeconds, m_timespan)
  594. );
  595. if (m_frame % m_update_physics == 0 && SynchronizeScene != null)
  596. SynchronizeScene(this);
  597. physicsMS = System.Environment.TickCount - physicsMS;
  598. physicsMS += physicsMS2;
  599. otherMS = System.Environment.TickCount;
  600. // run through all entities looking for updates (slow)
  601. if (m_frame % m_update_entities == 0)
  602. m_innerScene.UpdateEntities();
  603. // run through entities that have scheduled themselves for
  604. // updates looking for updates(faster)
  605. if (m_frame % m_update_entitiesquick == 0)
  606. m_innerScene.ProcessUpdates();
  607. // Run through scenepresences looking for updates
  608. if (m_frame % m_update_presences == 0)
  609. m_innerScene.UpdatePresences();
  610. if (Region_Status != RegionStatus.SlaveScene)
  611. {
  612. if (m_frame % m_update_events == 0)
  613. UpdateEvents();
  614. if (m_frame % m_update_backup == 0)
  615. UpdateStorageBackup();
  616. if (m_frame % m_update_terrain == 0)
  617. UpdateTerrain();
  618. if (m_frame % m_update_land == 0)
  619. UpdateLand();
  620. otherMS = System.Environment.TickCount - otherMS;
  621. // if (m_frame%m_update_avatars == 0)
  622. // UpdateInWorldTime();
  623. m_statsReporter.AddPhysicsFPS(physicsFPS);
  624. m_statsReporter.AddTimeDilation(m_timedilation);
  625. m_statsReporter.AddFPS(1);
  626. m_statsReporter.AddInPackets(0);
  627. m_statsReporter.SetRootAgents(m_innerScene.GetRootAgentCount());
  628. m_statsReporter.SetChildAgents(m_innerScene.GetChildAgentCount());
  629. m_statsReporter.SetObjects(m_innerScene.GetTotalObjects());
  630. m_statsReporter.SetActiveObjects(m_innerScene.GetActiveObjects());
  631. frameMS = System.Environment.TickCount - frameMS;
  632. m_statsReporter.addFrameMS(frameMS);
  633. m_statsReporter.addPhysicsMS(physicsMS);
  634. m_statsReporter.addOtherMS(otherMS);
  635. m_statsReporter.SetActiveScripts(m_innerScene.GetActiveScripts());
  636. m_statsReporter.addScriptLines(m_innerScene.GetScriptLPS());
  637. }
  638. }
  639. catch (NotImplementedException)
  640. {
  641. throw;
  642. }
  643. catch (AccessViolationException e)
  644. {
  645. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  646. }
  647. catch (NullReferenceException e)
  648. {
  649. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  650. }
  651. catch (InvalidOperationException e)
  652. {
  653. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  654. }
  655. catch (Exception e)
  656. {
  657. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  658. }
  659. finally
  660. {
  661. updateLock.ReleaseMutex();
  662. // Get actual time dilation
  663. float tmpval = (m_timespan / (float)SinceLastFrame.TotalSeconds);
  664. // If actual time dilation is greater then one, we're catching up, so subtract
  665. // the amount that's greater then 1 from the time dilation
  666. if (tmpval > 1.0)
  667. {
  668. tmpval = tmpval - (tmpval - 1.0f);
  669. }
  670. m_timedilation = tmpval;
  671. m_lastupdate = DateTime.Now;
  672. }
  673. }
  674. private void SendSimStatsPackets(SimStatsPacket pack)
  675. {
  676. List<ScenePresence> StatSendAgents = GetScenePresences();
  677. foreach (ScenePresence agent in StatSendAgents)
  678. {
  679. if (!agent.IsChildAgent)
  680. {
  681. pack.Header.Reliable = false;
  682. agent.ControllingClient.OutPacket(pack, ThrottleOutPacketType.Task);
  683. }
  684. }
  685. }
  686. private void UpdateLand()
  687. {
  688. if (LandChannel != null)
  689. {
  690. if (LandChannel.isLandPrimCountTainted())
  691. {
  692. LandChannel.performParcelPrimCountUpdate();
  693. }
  694. }
  695. }
  696. private void UpdateTerrain()
  697. {
  698. EventManager.TriggerTerrainTick();
  699. }
  700. private void UpdateStorageBackup()
  701. {
  702. Backup();
  703. }
  704. private void UpdateEvents()
  705. {
  706. m_eventManager.TriggerOnFrame();
  707. }
  708. /// <summary>
  709. /// Perform delegate action on all clients subscribing to updates from this region.
  710. /// </summary>
  711. /// <returns></returns>
  712. internal void Broadcast(Action<IClientAPI> whatToDo)
  713. {
  714. ForEachScenePresence(delegate(ScenePresence presence) { whatToDo(presence.ControllingClient); });
  715. }
  716. /// <summary>
  717. ///
  718. /// </summary>
  719. /// <returns></returns>
  720. public bool Backup()
  721. {
  722. EventManager.TriggerOnBackup(m_storageManager.DataStore);
  723. return true;
  724. }
  725. #endregion
  726. #region Load Terrain
  727. public void ExportWorldMap(string fileName)
  728. {
  729. List<MapBlockData> mapBlocks =
  730. m_sceneGridService.RequestNeighbourMapBlocks((int)(RegionInfo.RegionLocX - 9),
  731. (int)(RegionInfo.RegionLocY - 9),
  732. (int)(RegionInfo.RegionLocX + 9),
  733. (int)(RegionInfo.RegionLocY + 9));
  734. List<AssetBase> textures = new List<AssetBase>();
  735. List<Image> bitImages = new List<Image>();
  736. foreach (MapBlockData mapBlock in mapBlocks)
  737. {
  738. AssetBase texAsset = AssetCache.GetAsset(mapBlock.MapImageId, true);
  739. if (texAsset != null)
  740. {
  741. textures.Add(texAsset);
  742. }
  743. else
  744. {
  745. texAsset = AssetCache.GetAsset(mapBlock.MapImageId, true);
  746. if (texAsset != null)
  747. {
  748. textures.Add(texAsset);
  749. }
  750. }
  751. }
  752. foreach (AssetBase asset in textures)
  753. {
  754. Image image = OpenJPEG.DecodeToImage(asset.Data);
  755. bitImages.Add(image);
  756. }
  757. Bitmap mapTexture = new Bitmap(2560, 2560);
  758. Graphics g = Graphics.FromImage(mapTexture);
  759. SolidBrush sea = new SolidBrush(Color.DarkBlue);
  760. g.FillRectangle(sea, 0, 0, 2560, 2560);
  761. for (int i = 0; i < mapBlocks.Count; i++)
  762. {
  763. ushort x = (ushort)((mapBlocks[i].X - RegionInfo.RegionLocX) + 10);
  764. ushort y = (ushort)((mapBlocks[i].Y - RegionInfo.RegionLocY) + 10);
  765. g.DrawImage(bitImages[i], (x * 128), (y * 128), 128, 128);
  766. }
  767. mapTexture.Save(fileName, ImageFormat.Jpeg);
  768. }
  769. public void SaveTerrain()
  770. {
  771. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  772. }
  773. /// <summary>
  774. /// Loads the World heightmap
  775. /// </summary>
  776. ///
  777. public override void LoadWorldMap()
  778. {
  779. try
  780. {
  781. double[,] map = m_storageManager.DataStore.LoadTerrain(RegionInfo.RegionID);
  782. if (map == null)
  783. {
  784. m_log.Info("[TERRAIN]: No default terrain. Generating a new terrain.");
  785. Heightmap = new TerrainChannel();
  786. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  787. }
  788. else
  789. {
  790. Heightmap = new TerrainChannel(map);
  791. }
  792. }
  793. catch (Exception e)
  794. {
  795. m_log.Warn("[terrain]: Scene.cs: LoadWorldMap() - Failed with exception " + e.ToString());
  796. }
  797. }
  798. public void RegisterRegionWithGrid()
  799. {
  800. RegisterCommsEvents();
  801. // These two 'commands' *must be* next to each other or sim rebooting fails.
  802. m_sceneGridService.RegisterRegion(RegionInfo);
  803. m_sceneGridService.InformNeighborsThatRegionisUp(RegionInfo);
  804. Dictionary<string, string> dGridSettings = m_sceneGridService.GetGridSettings();
  805. if (dGridSettings.ContainsKey("allow_forceful_banlines"))
  806. {
  807. if (dGridSettings["allow_forceful_banlines"] != "TRUE")
  808. {
  809. m_log.Info("[GRID]: Grid is disabling forceful parcel banlists");
  810. LandChannel.allowedForcefulBans = false;
  811. }
  812. else
  813. {
  814. m_log.Info("[GRID]: Grid is allowing forceful parcel banlists");
  815. LandChannel.allowedForcefulBans = true;
  816. }
  817. }
  818. }
  819. /// <summary>
  820. ///
  821. /// </summary>
  822. public void CreateTerrainTexture(bool temporary)
  823. {
  824. //create a texture asset of the terrain
  825. IMapImageGenerator terrain = RequestModuleInterface<IMapImageGenerator>();
  826. // Cannot create a map for a nonexistant heightmap yet.
  827. if (Heightmap == null)
  828. return;
  829. if (terrain == null)
  830. {
  831. Bitmap mapbmp = new Bitmap(256, 256);
  832. double[,] hm = Heightmap.GetDoubles();
  833. float heightvalue = 0;
  834. Color prim = Color.FromArgb(120, 120, 120);
  835. LLVector3 RayEnd = new LLVector3(0, 0, 0);
  836. LLVector3 RayStart = new LLVector3(0, 0, 0);
  837. LLVector3 direction = new LLVector3(0, 0, -1);
  838. //Vector3 AXOrigin = new Vector3();
  839. //Vector3 AXdirection = new Vector3();
  840. Ray testRay = new Ray();
  841. EntityIntersection rt = new EntityIntersection();
  842. float low = 255;
  843. float high = 0;
  844. for (int x = 0; x < 256; x++)
  845. {
  846. for (int y = 0; y < 256; y++)
  847. {
  848. float hmval = (float)hm[x, y];
  849. if (hmval < low)
  850. low = hmval;
  851. if (hmval > high)
  852. high = hmval;
  853. }
  854. }
  855. float mid = (high + low) * 0.5f;
  856. for (int x = 0; x < 256; x++)
  857. {
  858. //int tc = System.Environment.TickCount;
  859. for (int y = 0; y < 256; y++)
  860. {
  861. //RayEnd = new LLVector3(x, y, 0);
  862. //RayStart = new LLVector3(x, y, 255);
  863. //direction = LLVector3.Norm(RayEnd - RayStart);
  864. //AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  865. //AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  866. //testRay = new Ray(AXOrigin, AXdirection);
  867. //rt = m_innerScene.GetClosestIntersectingPrim(testRay);
  868. //if (rt.HitTF)
  869. //{
  870. //mapbmp.SetPixel(x, y, prim);
  871. //}
  872. //else
  873. //{
  874. float tmpval = (float)hm[x, y];
  875. heightvalue = (float)hm[x, y];
  876. if ((float)heightvalue > m_regInfo.EstateSettings.waterHeight)
  877. {
  878. // scale height value
  879. heightvalue = low + mid * (heightvalue - low) / mid;
  880. if (heightvalue > 255)
  881. heightvalue = 255;
  882. if (heightvalue < 0)
  883. heightvalue = 0;
  884. Color green = Color.FromArgb((int)heightvalue, 100, (int)heightvalue);
  885. // Y flip the cordinates
  886. mapbmp.SetPixel(x, (256 - y) - 1, green);
  887. }
  888. else
  889. {
  890. // Y flip the cordinates
  891. heightvalue = m_regInfo.EstateSettings.waterHeight - heightvalue;
  892. if (heightvalue > 19)
  893. heightvalue = 19;
  894. if (heightvalue < 0)
  895. heightvalue = 0;
  896. heightvalue = 100 - (heightvalue * 100) / 19;
  897. if (heightvalue > 255)
  898. heightvalue = 255;
  899. if (heightvalue < 0)
  900. heightvalue = 0;
  901. Color water = Color.FromArgb((int)heightvalue, (int)heightvalue, 255);
  902. mapbmp.SetPixel(x, (256 - y) - 1, water);
  903. }
  904. //}
  905. }
  906. //tc = System.Environment.TickCount - tc;
  907. //m_log.Info("[MAPTILE]: Completed One row in " + tc + " ms");
  908. }
  909. byte[] data;
  910. try
  911. {
  912. data = OpenJPEG.EncodeFromImage(mapbmp, false);
  913. }
  914. catch (Exception)
  915. {
  916. return;
  917. }
  918. m_regInfo.EstateSettings.terrainImageID = LLUUID.Random();
  919. AssetBase asset = new AssetBase();
  920. asset.FullID = m_regInfo.EstateSettings.terrainImageID;
  921. asset.Data = data;
  922. asset.Name = "terrainImage";
  923. asset.Description = RegionInfo.RegionName;
  924. asset.Type = 0;
  925. asset.Temporary = temporary;
  926. AssetCache.AddAsset(asset);
  927. }
  928. else
  929. {
  930. byte[] data = terrain.WriteJpeg2000Image("defaultstripe.png");
  931. if (data != null)
  932. {
  933. m_regInfo.EstateSettings.terrainImageID = LLUUID.Random();
  934. AssetBase asset = new AssetBase();
  935. asset.FullID = m_regInfo.EstateSettings.terrainImageID;
  936. asset.Data = data;
  937. asset.Name = "terrainImage";
  938. asset.Description = RegionInfo.RegionName;
  939. asset.Type = 0;
  940. asset.Temporary = temporary;
  941. AssetCache.AddAsset(asset);
  942. }
  943. }
  944. }
  945. #endregion
  946. #region Load Land
  947. public void loadAllLandObjectsFromStorage(LLUUID regionID)
  948. {
  949. m_log.Info("[SCENE]: Loading land objects from storage");
  950. List<LandData> landData = m_storageManager.DataStore.LoadLandObjects(regionID);
  951. if (landData.Count == 0)
  952. {
  953. LandChannel.NoLandDataFromStorage();
  954. }
  955. else
  956. {
  957. LandChannel.IncomingLandObjectsFromStorage(landData);
  958. }
  959. }
  960. #endregion
  961. #region Primitives Methods
  962. /// <summary>
  963. /// Loads the World's objects
  964. /// </summary>
  965. public virtual void LoadPrimsFromStorage(bool m_permissions, LLUUID regionID)
  966. {
  967. m_log.Info("[SCENE]: Loading objects from datastore");
  968. List<SceneObjectGroup> PrimsFromDB = m_storageManager.DataStore.LoadObjects(regionID);
  969. foreach (SceneObjectGroup group in PrimsFromDB)
  970. {
  971. AddEntityFromStorage(group);
  972. SceneObjectPart rootPart = group.GetChildPart(group.UUID);
  973. rootPart.ObjectFlags &= ~(uint)LLObject.ObjectFlags.Scripted;
  974. rootPart.TrimPermissions();
  975. group.ApplyPhysics(m_physicalPrim);
  976. //rootPart.DoPhysicsPropertyUpdate(UsePhysics, true);
  977. }
  978. m_log.Info("[SCENE]: Loaded " + PrimsFromDB.Count.ToString() + " SceneObject(s)");
  979. }
  980. /// <summary>
  981. /// Returns a new unallocated primitive ID
  982. /// </summary>
  983. /// <returns>A brand new primitive ID</returns>
  984. public uint PrimIDAllocate()
  985. {
  986. uint myID;
  987. _primAllocateMutex.WaitOne();
  988. ++_primCount;
  989. myID = _primCount;
  990. _primAllocateMutex.ReleaseMutex();
  991. return myID;
  992. }
  993. public LLVector3 GetNewRezLocation(LLVector3 RayStart, LLVector3 RayEnd, LLUUID RayTargetID, LLQuaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, LLVector3 scale, bool FaceCenter)
  994. {
  995. LLVector3 pos = LLVector3.Zero;
  996. if (RayEndIsIntersection == (byte)1)
  997. {
  998. pos = RayEnd;
  999. return pos;
  1000. }
  1001. if (RayTargetID != LLUUID.Zero)
  1002. {
  1003. SceneObjectPart target = GetSceneObjectPart(RayTargetID);
  1004. LLVector3 direction = LLVector3.Norm(RayEnd - RayStart);
  1005. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  1006. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  1007. if (target != null)
  1008. {
  1009. pos = target.AbsolutePosition;
  1010. //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());
  1011. // TODO: Raytrace better here
  1012. //EntityIntersection ei = m_innerScene.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  1013. Ray NewRay = new Ray(AXOrigin, AXdirection);
  1014. // Ray Trace against target here
  1015. EntityIntersection ei = target.TestIntersectionOBB(NewRay, new Quaternion(1,0,0,0), frontFacesOnly, FaceCenter);
  1016. // Un-comment out the following line to Get Raytrace results printed to the console.
  1017. // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1018. float ScaleOffset = 0.5f;
  1019. // If we hit something
  1020. if (ei.HitTF)
  1021. {
  1022. LLVector3 scaleComponent = new LLVector3(ei.AAfaceNormal.x, ei.AAfaceNormal.y, ei.AAfaceNormal.z);
  1023. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  1024. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  1025. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  1026. ScaleOffset = Math.Abs(ScaleOffset);
  1027. LLVector3 intersectionpoint = new LLVector3(ei.ipoint.x, ei.ipoint.y, ei.ipoint.z);
  1028. LLVector3 normal = new LLVector3(ei.normal.x, ei.normal.y, ei.normal.z);
  1029. // Set the position to the intersection point
  1030. LLVector3 offset = (normal * (ScaleOffset / 2f));
  1031. pos = (intersectionpoint + offset);
  1032. // Un-offset the prim (it gets offset later by the consumer method)
  1033. pos.Z -= 0.25F;
  1034. }
  1035. return pos;
  1036. }
  1037. else
  1038. {
  1039. // We don't have a target here, so we're going to raytrace all the objects in the scene.
  1040. EntityIntersection ei = m_innerScene.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false);
  1041. // Un-comment the following line to print the raytrace results to the console.
  1042. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1043. if (ei.HitTF)
  1044. {
  1045. pos = new LLVector3(ei.ipoint.x, ei.ipoint.y, ei.ipoint.z);
  1046. }
  1047. return pos;
  1048. }
  1049. }
  1050. else
  1051. {
  1052. // fall back to our stupid functionality
  1053. pos = RayEnd;
  1054. return pos;
  1055. }
  1056. }
  1057. public virtual void AddNewPrim(LLUUID ownerID, LLVector3 RayEnd, LLQuaternion rot, PrimitiveBaseShape shape,
  1058. byte bypassRaycast, LLVector3 RayStart, LLUUID RayTargetID,
  1059. byte RayEndIsIntersection)
  1060. {
  1061. LLVector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection, true, new LLVector3(0.5f,0.5f,0.5f), false);
  1062. if (PermissionsMngr.CanRezObject(ownerID, pos))
  1063. {
  1064. // rez ON the ground, not IN the ground
  1065. pos.Z += 0.25F;
  1066. AddNewPrim(ownerID, pos, rot, shape);
  1067. }
  1068. }
  1069. public virtual SceneObjectGroup AddNewPrim(LLUUID ownerID, LLVector3 pos, LLQuaternion rot, PrimitiveBaseShape shape)
  1070. {
  1071. SceneObjectGroup sceneOb =
  1072. new SceneObjectGroup(this, m_regionHandle, ownerID, PrimIDAllocate(), pos, rot, shape);
  1073. AddEntity(sceneOb);
  1074. SceneObjectPart rootPart = sceneOb.GetChildPart(sceneOb.UUID);
  1075. // if grass or tree, make phantom
  1076. //rootPart.TrimPermissions();
  1077. if ((rootPart.Shape.PCode == (byte)PCode.Grass) || (rootPart.Shape.PCode == (byte)PCode.Tree) || (rootPart.Shape.PCode == (byte)PCode.NewTree))
  1078. {
  1079. rootPart.AddFlag(LLObject.ObjectFlags.Phantom);
  1080. //rootPart.ObjectFlags += (uint)LLObject.ObjectFlags.Phantom;
  1081. }
  1082. // if not phantom, add to physics
  1083. sceneOb.ApplyPhysics(m_physicalPrim);
  1084. m_innerScene.AddToUpdateList(sceneOb);
  1085. return sceneOb;
  1086. }
  1087. public SceneObjectGroup AddTree(LLVector3 scale, LLQuaternion rotation, LLVector3 position,
  1088. Tree treeType, bool newTree)
  1089. {
  1090. LLUUID uuid = this.RegionInfo.MasterAvatarAssignedUUID;
  1091. PrimitiveBaseShape treeShape = new PrimitiveBaseShape();
  1092. treeShape.PathCurve = 16;
  1093. treeShape.PathEnd = 49900;
  1094. treeShape.PCode = newTree ? (byte)PCode.NewTree : (byte)PCode.Tree;
  1095. treeShape.Scale = scale;
  1096. treeShape.State = (byte)treeType;
  1097. return AddNewPrim(uuid, position, rotation, treeShape);
  1098. }
  1099. public void RemovePrim(uint localID, LLUUID avatar_deleter)
  1100. {
  1101. m_innerScene.RemovePrim(localID, avatar_deleter);
  1102. }
  1103. public void AddEntityFromStorage(SceneObjectGroup sceneObject)
  1104. {
  1105. m_innerScene.AddEntityFromStorage(sceneObject);
  1106. }
  1107. public void AddEntity(SceneObjectGroup sceneObject)
  1108. {
  1109. m_innerScene.AddEntity(sceneObject);
  1110. }
  1111. public void RemoveEntity(SceneObjectGroup sceneObject)
  1112. {
  1113. if (Entities.ContainsKey(sceneObject.UUID))
  1114. {
  1115. LandChannel.removePrimFromLandPrimCounts(sceneObject);
  1116. Entities.Remove(sceneObject.UUID);
  1117. LandChannel.setPrimsTainted();
  1118. m_innerScene.RemoveAPrimCount();
  1119. }
  1120. }
  1121. /// <summary>
  1122. /// Called by a prim when it has been created/cloned, so that its events can be subscribed to
  1123. /// </summary>
  1124. /// <param name="prim"></param>
  1125. public void AcknowledgeNewPrim(SceneObjectGroup prim)
  1126. {
  1127. prim.OnPrimCountTainted += LandChannel.setPrimsTainted;
  1128. }
  1129. public void LoadPrimsFromXml(string fileName, bool newIdsFlag, LLVector3 loadOffset)
  1130. {
  1131. m_sceneXmlLoader.LoadPrimsFromXml(fileName, newIdsFlag, loadOffset);
  1132. }
  1133. public void SavePrimsToXml(string fileName)
  1134. {
  1135. m_sceneXmlLoader.SavePrimsToXml(fileName);
  1136. }
  1137. public void LoadPrimsFromXml2(string fileName)
  1138. {
  1139. m_sceneXmlLoader.LoadPrimsFromXml2(fileName);
  1140. }
  1141. public void SavePrimsToXml2(string fileName)
  1142. {
  1143. m_sceneXmlLoader.SavePrimsToXml2(fileName);
  1144. }
  1145. /// <summary>
  1146. /// Locate New region Handle and offset the prim position for the new region
  1147. ///
  1148. /// </summary>
  1149. /// <param name="position">current position of Group</param>
  1150. /// <param name="grp">Scene Object Group that we're crossing</param>
  1151. public void CrossPrimGroupIntoNewRegion(LLVector3 position, SceneObjectGroup grp)
  1152. {
  1153. m_log.Warn("Prim crossing: " + grp.UUID.ToString());
  1154. int thisx = (int)RegionInfo.RegionLocX;
  1155. int thisy = (int)RegionInfo.RegionLocY;
  1156. ulong newRegionHandle = 0;
  1157. LLVector3 pos = position;
  1158. if (position.X > Constants.RegionSize + 0.1f)
  1159. {
  1160. pos.X = ((pos.X - Constants.RegionSize));
  1161. newRegionHandle = Util.UIntsToLong((uint)((thisx + 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize));
  1162. // x + 1
  1163. }
  1164. else if (position.X < -0.1f)
  1165. {
  1166. pos.X = ((pos.X + Constants.RegionSize));
  1167. newRegionHandle = Util.UIntsToLong((uint)((thisx - 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize));
  1168. // x - 1
  1169. }
  1170. if (position.Y > Constants.RegionSize + 0.1f)
  1171. {
  1172. pos.Y = ((pos.Y - Constants.RegionSize));
  1173. newRegionHandle = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy + 1) * Constants.RegionSize));
  1174. // y + 1
  1175. }
  1176. else if (position.Y < -1f)
  1177. {
  1178. pos.Y = ((pos.Y + Constants.RegionSize));
  1179. newRegionHandle = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy - 1) * Constants.RegionSize));
  1180. // y - 1
  1181. }
  1182. // Offset the positions for the new region across the border
  1183. grp.OffsetForNewRegion(pos);
  1184. CrossPrimGroupIntoNewRegion(newRegionHandle, grp);
  1185. }
  1186. public void CrossPrimGroupIntoNewRegion(ulong newRegionHandle, SceneObjectGroup grp)
  1187. {
  1188. int primcrossingXMLmethod = 0;
  1189. if (newRegionHandle != 0)
  1190. {
  1191. bool successYN = false;
  1192. successYN = m_sceneGridService.PrimCrossToNeighboringRegion(newRegionHandle, grp.UUID, m_sceneXmlLoader.SavePrimGroupToXML2String(grp), primcrossingXMLmethod);
  1193. if (successYN)
  1194. {
  1195. // We remove the object here
  1196. try
  1197. {
  1198. DeleteSceneObjectGroup(grp);
  1199. }
  1200. catch (Exception)
  1201. {
  1202. m_log.Warn("[DATABASE]: exception when trying to remove the prim that crossed the border.");
  1203. }
  1204. }
  1205. else
  1206. {
  1207. m_log.Warn("[INTERREGION]: Prim Crossing Failed!");
  1208. if (grp.RootPart != null)
  1209. {
  1210. if (grp.RootPart.PhysActor != null)
  1211. {
  1212. grp.RootPart.PhysActor.CrossingFailure();
  1213. }
  1214. }
  1215. }
  1216. }
  1217. }
  1218. public bool IncomingInterRegionPrimGroup(ulong regionHandle, LLUUID primID, string objXMLData, int XMLMethod)
  1219. {
  1220. m_log.Warn("{[INTERREGION]: A new prim arrived from a neighbor");
  1221. if (XMLMethod == 0)
  1222. {
  1223. m_sceneXmlLoader.LoadGroupFromXml2String(objXMLData);
  1224. SceneObjectPart RootPrim = GetSceneObjectPart(primID);
  1225. if (RootPrim != null)
  1226. {
  1227. if (RootPrim.Shape.PCode == (byte)PCode.Prim)
  1228. {
  1229. SceneObjectGroup grp = RootPrim.ParentGroup;
  1230. if (grp != null)
  1231. {
  1232. if (RootPrim.Shape.State != 0)
  1233. {
  1234. // Attachment
  1235. ScenePresence sp = GetScenePresence(grp.OwnerID);
  1236. if (sp != null)
  1237. {
  1238. // hack assetID until we get assetID into the XML format.
  1239. // LastOwnerID is used for group deeding, so when you do stuff
  1240. // with the deeded object, it goes back to them
  1241. grp.SetFromAssetID(grp.RootPart.LastOwnerID);
  1242. m_innerScene.AttachObject(sp.ControllingClient, grp.LocalId, (uint)0, grp.GroupRotation, grp.AbsolutePosition);
  1243. }
  1244. }
  1245. }
  1246. }
  1247. }
  1248. return true;
  1249. }
  1250. else
  1251. {
  1252. return false;
  1253. }
  1254. }
  1255. #endregion
  1256. #region Add/Remove Avatar Methods
  1257. /// <summary>
  1258. ///
  1259. /// </summary>
  1260. /// <param name="client"></param
  1261. /// <param name="child"></param>
  1262. public override void AddNewClient(IClientAPI client, bool child)
  1263. {
  1264. m_log.DebugFormat(
  1265. "[CONNECTION DEBUGGING]: Creating new client for {0} at {1}",
  1266. client.AgentId, RegionInfo.RegionName);
  1267. SubscribeToClientEvents(client);
  1268. ScenePresence presence = null;
  1269. if (m_restorePresences.ContainsKey(client.AgentId))
  1270. {
  1271. m_log.Info("[REGION]: Restore Scene Presence");
  1272. presence = m_restorePresences[client.AgentId];
  1273. m_restorePresences.Remove(client.AgentId);
  1274. presence.initializeScenePresence(client, RegionInfo, this);
  1275. m_innerScene.AddScenePresence(presence);
  1276. lock (m_restorePresences)
  1277. {
  1278. Monitor.PulseAll(m_restorePresences);
  1279. }
  1280. }
  1281. else
  1282. {
  1283. m_log.Info("[REGION]: Add New Scene Presence");
  1284. m_estateManager.sendRegionHandshake(client);
  1285. CreateAndAddScenePresence(client, child);
  1286. LandChannel.sendParcelOverlay(client);
  1287. CommsManager.UserProfileCacheService.AddNewUser(client.AgentId);
  1288. }
  1289. }
  1290. protected virtual void SubscribeToClientEvents(IClientAPI client)
  1291. {
  1292. client.OnRegionHandShakeReply += SendLayerData;
  1293. //remoteClient.OnRequestWearables += new GenericCall(this.GetInitialPrims);
  1294. // client.OnRequestWearables += InformClientOfNeighbours;
  1295. client.OnAddPrim += AddNewPrim;
  1296. client.OnUpdatePrimGroupPosition += m_innerScene.UpdatePrimPosition;
  1297. client.OnUpdatePrimSinglePosition += m_innerScene.UpdatePrimSinglePosition;
  1298. client.OnUpdatePrimGroupRotation += m_innerScene.UpdatePrimRotation;
  1299. client.OnUpdatePrimGroupMouseRotation += m_innerScene.UpdatePrimRotation;
  1300. client.OnUpdatePrimSingleRotation += m_innerScene.UpdatePrimSingleRotation;
  1301. client.OnUpdatePrimScale += m_innerScene.UpdatePrimScale;
  1302. client.OnUpdatePrimGroupScale += m_innerScene.UpdatePrimGroupScale;
  1303. client.OnUpdateExtraParams += m_innerScene.UpdateExtraParam;
  1304. client.OnUpdatePrimShape += m_innerScene.UpdatePrimShape;
  1305. client.OnRequestMapBlocks += RequestMapBlocks;
  1306. client.OnUpdatePrimTexture += m_innerScene.UpdatePrimTexture;
  1307. client.OnTeleportLocationRequest += RequestTeleportLocation;
  1308. client.OnTeleportLandmarkRequest += RequestTeleportLandmark;
  1309. client.OnObjectSelect += SelectPrim;
  1310. client.OnObjectDeselect += DeselectPrim;
  1311. client.OnGrabUpdate += m_innerScene.MoveObject;
  1312. client.OnDeRezObject += DeRezObject;
  1313. client.OnRezObject += RezObject;
  1314. client.OnRezSingleAttachmentFromInv += m_innerScene.RezSingleAttachment;
  1315. client.OnDetachAttachmentIntoInv += m_innerScene.DetachSingleAttachmentToInv;
  1316. client.OnObjectAttach += m_innerScene.AttachObject;
  1317. client.OnObjectDetach += m_innerScene.DetachObject;
  1318. client.OnNameFromUUIDRequest += CommsManager.HandleUUIDNameRequest;
  1319. client.OnObjectDescription += m_innerScene.PrimDescription;
  1320. client.OnObjectName += m_innerScene.PrimName;
  1321. client.OnLinkObjects += m_innerScene.LinkObjects;
  1322. client.OnDelinkObjects += m_innerScene.DelinkObjects;
  1323. client.OnObjectDuplicate += m_innerScene.DuplicateObject;
  1324. client.OnObjectDuplicateOnRay += doObjectDuplicateOnRay;
  1325. client.OnUpdatePrimFlags += m_innerScene.UpdatePrimFlags;
  1326. client.OnRequestObjectPropertiesFamily += m_innerScene.RequestObjectPropertiesFamily;
  1327. client.OnParcelPropertiesRequest += new ParcelPropertiesRequest(LandChannel.handleParcelPropertiesRequest);
  1328. client.OnParcelDivideRequest += new ParcelDivideRequest(LandChannel.handleParcelDivideRequest);
  1329. client.OnParcelJoinRequest += new ParcelJoinRequest(LandChannel.handleParcelJoinRequest);
  1330. client.OnParcelPropertiesUpdateRequest +=
  1331. new ParcelPropertiesUpdateRequest(LandChannel.handleParcelPropertiesUpdateRequest);
  1332. client.OnParcelSelectObjects += new ParcelSelectObjects(LandChannel.handleParcelSelectObjectsRequest);
  1333. client.OnParcelObjectOwnerRequest +=
  1334. new ParcelObjectOwnerRequest(LandChannel.handleParcelObjectOwnersRequest);
  1335. client.OnParcelAccessListRequest += new ParcelAccessListRequest(LandChannel.handleParcelAccessRequest);
  1336. client.OnParcelAccessListUpdateRequest +=
  1337. new ParcelAccessListUpdateRequest(LandChannel.handleParcelAccessUpdateRequest);
  1338. client.OnEstateOwnerMessage += new EstateOwnerMessageRequest(m_estateManager.handleEstateOwnerMessage);
  1339. client.OnRegionInfoRequest += m_estateManager.HandleRegionInfoRequest;
  1340. client.OnEstateCovenantRequest += m_estateManager.HandleEstateCovenantRequest;
  1341. client.OnRequestGodlikePowers += handleRequestGodlikePowers;
  1342. client.OnGodKickUser += HandleGodlikeKickUser;
  1343. client.OnObjectPermissions += HandleObjectPermissionsUpdate;
  1344. client.OnCreateNewInventoryItem += CreateNewInventoryItem;
  1345. client.OnCreateNewInventoryFolder += CommsManager.UserProfileCacheService.HandleCreateInventoryFolder;
  1346. client.OnUpdateInventoryFolder += CommsManager.UserProfileCacheService.HandleUpdateInventoryFolder;
  1347. client.OnMoveInventoryFolder += CommsManager.UserProfileCacheService.HandleMoveInventoryFolder;
  1348. client.OnFetchInventoryDescendents += CommsManager.UserProfileCacheService.HandleFetchInventoryDescendents;
  1349. client.OnPurgeInventoryDescendents += CommsManager.UserProfileCacheService.HandlePurgeInventoryDescendents;
  1350. client.OnFetchInventory += CommsManager.UserProfileCacheService.HandleFetchInventory;
  1351. client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
  1352. client.OnCopyInventoryItem += CopyInventoryItem;
  1353. client.OnMoveInventoryItem += MoveInventoryItem;
  1354. client.OnRemoveInventoryItem += RemoveInventoryItem;
  1355. client.OnRemoveInventoryFolder += RemoveInventoryFolder;
  1356. // client.OnAssetUploadRequest += CommsManager.TransactionsManager.HandleUDPUploadRequest;
  1357. // client.OnXferReceive += CommsManager.TransactionsManager.HandleXfer;
  1358. client.OnRezScript += RezScript;
  1359. client.OnRequestTaskInventory += RequestTaskInventory;
  1360. client.OnRemoveTaskItem += RemoveTaskInventory;
  1361. client.OnUpdateTaskInventory += UpdateTaskInventory;
  1362. client.OnMoveTaskItem += MoveTaskInventoryItem;
  1363. client.OnGrabObject += ProcessObjectGrab;
  1364. client.OnDeGrabObject += ProcessObjectDeGrab;
  1365. client.OnMoneyTransferRequest += ProcessMoneyTransferRequest;
  1366. client.OnParcelBuy += ProcessParcelBuy;
  1367. client.OnAvatarPickerRequest += ProcessAvatarPickerRequest;
  1368. client.OnPacketStats += AddPacketStats;
  1369. client.OnObjectIncludeInSearch += m_innerScene.MakeObjectSearchable;
  1370. client.OnTeleportHomeRequest += TeleportClientHome;
  1371. client.OnSetStartLocationRequest += SetHomeRezPoint;
  1372. client.OnUndo += m_innerScene.HandleUndo;
  1373. EventManager.TriggerOnNewClient(client);
  1374. }
  1375. public virtual void TeleportClientHome(LLUUID AgentId, IClientAPI client)
  1376. {
  1377. UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(AgentId);
  1378. if (UserProfile != null)
  1379. {
  1380. ulong homeRegion = UserProfile.HomeRegion;
  1381. LLVector3 homePostion = new LLVector3(UserProfile.HomeLocationX,UserProfile.HomeLocationY,UserProfile.HomeLocationZ);
  1382. LLVector3 homeLookat = new LLVector3(UserProfile.HomeLookAt);
  1383. RequestTeleportLocation(client, homeRegion, homePostion,homeLookat,(uint)0);
  1384. }
  1385. }
  1386. public void doObjectDuplicateOnRay(uint localID, uint dupeFlags, LLUUID AgentID, LLUUID GroupID,
  1387. LLUUID RayTargetObj, LLVector3 RayEnd, LLVector3 RayStart,
  1388. bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates)
  1389. {
  1390. LLVector3 pos = LLVector3.Zero;
  1391. bool frontFacesOnly = true;
  1392. SceneObjectPart target = GetSceneObjectPart(localID);
  1393. if (target != null)
  1394. {
  1395. LLVector3 direction = LLVector3.Norm(RayEnd - RayStart);
  1396. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  1397. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  1398. if (target != null)
  1399. {
  1400. if (target.ParentGroup != null)
  1401. {
  1402. pos = target.AbsolutePosition;
  1403. //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());
  1404. // TODO: Raytrace better here
  1405. //EntityIntersection ei = m_innerScene.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  1406. Ray NewRay = new Ray(AXOrigin, AXdirection);
  1407. // Ray Trace against target here
  1408. EntityIntersection ei = target.TestIntersectionOBB(NewRay, new Quaternion(1, 0, 0, 0), frontFacesOnly, false);
  1409. // Un-comment out the following line to Get Raytrace results printed to the console.
  1410. // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1411. float ScaleOffset = 0.5f;
  1412. // If we hit something
  1413. if (ei.HitTF)
  1414. {
  1415. LLVector3 scale = target.Scale;
  1416. LLVector3 scaleComponent = new LLVector3(ei.AAfaceNormal.x, ei.AAfaceNormal.y, ei.AAfaceNormal.z);
  1417. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  1418. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  1419. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  1420. ScaleOffset = Math.Abs(ScaleOffset);
  1421. LLVector3 intersectionpoint = new LLVector3(ei.ipoint.x, ei.ipoint.y, ei.ipoint.z);
  1422. if (CopyCenters)
  1423. {
  1424. // now we cast a ray from inside the prim(absolute position) to one of it's faces along the face normal.
  1425. LLVector3 direction2 = LLVector3.Norm(pos - target.AbsolutePosition);
  1426. Vector3 AXOrigin2 = new Vector3(target.AbsolutePosition.X, target.AbsolutePosition.Y, target.AbsolutePosition.Z);
  1427. Vector3 AXdirection2 = ei.AAfaceNormal;
  1428. Ray NewRay2 = new Ray(AXOrigin2, AXdirection2);
  1429. EntityIntersection ei2 = target.TestIntersectionOBB(NewRay2, new Quaternion(1, 0, 0, 0), false, CopyCenters);
  1430. if (ei2.HitTF)
  1431. {
  1432. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei2.HitTF.ToString() + " Point: " + ei2.ipoint.ToString() + " Normal: " + ei2.normal.ToString());
  1433. pos = new LLVector3(ei2.ipoint.x,ei2.ipoint.y,ei2.ipoint.z);
  1434. }
  1435. }
  1436. LLVector3 normal = new LLVector3(ei.normal.x, ei.normal.y, ei.normal.z);
  1437. // Set the position to the intersection point
  1438. LLVector3 offset = (normal * (ScaleOffset / 2f));
  1439. pos = (intersectionpoint + offset);
  1440. // stick in offset format from the original prim
  1441. pos = pos - target.ParentGroup.AbsolutePosition;
  1442. m_innerScene.DuplicateObject(target.ParentGroup.LocalId, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID);
  1443. }
  1444. return;
  1445. }
  1446. return;
  1447. }
  1448. }
  1449. }
  1450. public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, LLVector3 position, LLVector3 lookAt, uint flags)
  1451. {
  1452. UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(remoteClient.AgentId);
  1453. if (UserProfile != null)
  1454. {
  1455. // I know I'm ignoring the regionHandle provided by the teleport location request.
  1456. // reusing the TeleportLocationRequest delegate, so regionHandle isn't valid
  1457. UserProfile.HomeRegion = RegionInfo.RegionHandle;
  1458. // We cast these to an int so as not to cause a breaking change with old regions
  1459. // Newer regions treat this as a float on the ExpectUser method.. so we need to wait a few
  1460. // releases before setting these to floats. (r4257)
  1461. UserProfile.HomeLocationX = (int)position.X;
  1462. UserProfile.HomeLocationY = (int)position.Y;
  1463. UserProfile.HomeLocationZ = (int)position.Z;
  1464. UserProfile.HomeLookAtX = (int)lookAt.X;
  1465. UserProfile.HomeLookAtY = (int)lookAt.Y;
  1466. UserProfile.HomeLookAtZ = (int)lookAt.Z;
  1467. CommsManager.UserService.UpdateUserProfileProperties(UserProfile);
  1468. remoteClient.SendAgentAlertMessage("Set home to here if supported by login service",false);
  1469. }
  1470. else
  1471. {
  1472. remoteClient.SendAgentAlertMessage("Set Home request Failed",false);
  1473. }
  1474. }
  1475. protected virtual ScenePresence CreateAndAddScenePresence(IClientAPI client, bool child)
  1476. {
  1477. ScenePresence avatar = null;
  1478. AvatarAppearance appearance;
  1479. GetAvatarAppearance(client, out appearance);
  1480. avatar = m_innerScene.CreateAndAddScenePresence(client, child, appearance);
  1481. if (avatar.IsChildAgent)
  1482. {
  1483. avatar.OnSignificantClientMovement += LandChannel.handleSignificantClientMovement;
  1484. }
  1485. return avatar;
  1486. }
  1487. protected void GetAvatarAppearance(IClientAPI client, out AvatarAppearance appearance)
  1488. {
  1489. if (m_AvatarFactory == null ||
  1490. !m_AvatarFactory.TryGetAvatarAppearance(client.AgentId, out appearance))
  1491. {
  1492. //not found Appearance
  1493. m_log.Warn("[AVATAR DEBUGGING]: Couldn't fetch avatar appearance from factory, please report this to the opensim mantis");
  1494. byte[] visualParams;
  1495. AvatarWearable[] wearables;
  1496. GetDefaultAvatarAppearance(out wearables, out visualParams);
  1497. appearance = new AvatarAppearance(client.AgentId, wearables, visualParams);
  1498. }
  1499. }
  1500. /// <summary>
  1501. /// Remove the given client from the scene.
  1502. /// </summary>
  1503. /// <param name="agentID"></param>
  1504. public override void RemoveClient(LLUUID agentID)
  1505. {
  1506. bool childagentYN = false;
  1507. ScenePresence avatar = GetScenePresence(agentID);
  1508. if (avatar != null)
  1509. {
  1510. childagentYN = avatar.IsChildAgent;
  1511. }
  1512. try
  1513. {
  1514. if (avatar.IsChildAgent)
  1515. {
  1516. m_innerScene.removeUserCount(false);
  1517. }
  1518. else
  1519. {
  1520. m_innerScene.removeUserCount(true);
  1521. m_sceneGridService.LogOffUser(agentID, RegionInfo.RegionID, RegionInfo.RegionHandle,
  1522. avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y,
  1523. avatar.AbsolutePosition.Z);
  1524. List<ulong> childknownRegions = new List<ulong>();
  1525. List<ulong> ckn = avatar.GetKnownRegionList();
  1526. for (int i = 0; i < ckn.Count; i++)
  1527. {
  1528. childknownRegions.Add(ckn[i]);
  1529. }
  1530. m_sceneGridService.SendCloseChildAgentConnections(agentID, childknownRegions);
  1531. RemoveCapsHandler(agentID);
  1532. CommsManager.UserProfileCacheService.RemoveUser(agentID);
  1533. }
  1534. m_eventManager.TriggerClientClosed(agentID);
  1535. }
  1536. catch (NullReferenceException)
  1537. {
  1538. // We don't know which count to remove it from
  1539. // Avatar is already disposed :/
  1540. }
  1541. m_eventManager.TriggerOnRemovePresence(agentID);
  1542. Broadcast(delegate(IClientAPI client)
  1543. {
  1544. try
  1545. {
  1546. client.SendKillObject(avatar.RegionHandle, avatar.LocalId);
  1547. }
  1548. catch (NullReferenceException)
  1549. {
  1550. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  1551. }
  1552. });
  1553. ForEachScenePresence(
  1554. delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  1555. IAgentAssetTransactions agentTransactions = this.RequestModuleInterface<IAgentAssetTransactions>();
  1556. if (agentTransactions != null)
  1557. {
  1558. agentTransactions.RemoveAgentAssetTransactions(agentID);
  1559. }
  1560. lock (m_scenePresences)
  1561. {
  1562. if (m_scenePresences.Remove(agentID))
  1563. {
  1564. //m_log.InfoFormat("[SCENE] Removed scene presence {0}", agentID);
  1565. }
  1566. else
  1567. {
  1568. m_log.WarnFormat("[SCENE] Tried to remove non-existent scene presence with agent ID {0} from scene ScenePresences list", agentID);
  1569. }
  1570. }
  1571. lock (Entities)
  1572. {
  1573. if (Entities.Remove(agentID))
  1574. {
  1575. //m_log.InfoFormat("[SCENE] Removed scene presence {0} from entities list", agentID);
  1576. }
  1577. else
  1578. {
  1579. m_log.WarnFormat("[SCENE] Tried to remove non-existent scene presence with agent ID {0} from scene Entities list", agentID);
  1580. }
  1581. }
  1582. try
  1583. {
  1584. avatar.Close();
  1585. }
  1586. catch (NullReferenceException)
  1587. {
  1588. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  1589. }
  1590. catch (Exception e)
  1591. {
  1592. m_log.Error("[SCENE] Scene.cs:RemoveClient exception: " + e.ToString());
  1593. }
  1594. // Remove client agent from profile, so new logins will work
  1595. if (!childagentYN)
  1596. {
  1597. m_sceneGridService.ClearUserAgent(agentID);
  1598. }
  1599. //m_log.InfoFormat("[SCENE] Memory pre GC {0}", System.GC.GetTotalMemory(false));
  1600. //m_log.InfoFormat("[SCENE] Memory post GC {0}", System.GC.GetTotalMemory(true));
  1601. }
  1602. public void HandleRemoveKnownRegionsFromAvatar(LLUUID avatarID, List<ulong> regionslst)
  1603. {
  1604. ScenePresence av = GetScenePresence(avatarID);
  1605. if (av != null)
  1606. {
  1607. lock (av)
  1608. {
  1609. for (int i = 0; i < regionslst.Count; i++)
  1610. {
  1611. av.KnownChildRegions.Remove(regionslst[i]);
  1612. }
  1613. }
  1614. }
  1615. }
  1616. public override void CloseAllAgents(uint circuitcode)
  1617. {
  1618. // Called by ClientView to kill all circuit codes
  1619. ClientManager.CloseAllAgents(circuitcode);
  1620. }
  1621. public void NotifyMyCoarseLocationChange()
  1622. {
  1623. ForEachScenePresence(delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  1624. }
  1625. #endregion
  1626. #region Entities
  1627. /// <summary>
  1628. ///
  1629. /// </summary>
  1630. /// <param name="entID"></param>
  1631. /// <returns></returns>
  1632. public bool DeleteEntity(LLUUID entID)
  1633. {
  1634. if (Entities.ContainsKey(entID))
  1635. {
  1636. Entities.Remove(entID);
  1637. m_storageManager.DataStore.RemoveObject(entID, m_regInfo.RegionID);
  1638. m_innerScene.RemoveAPrimCount();
  1639. return true;
  1640. }
  1641. return false;
  1642. }
  1643. public void SendKillObject(uint localID)
  1644. {
  1645. Broadcast(delegate(IClientAPI client) { client.SendKillObject(m_regionHandle, localID); });
  1646. }
  1647. #endregion
  1648. #region RegionComms
  1649. /// <summary>
  1650. ///
  1651. /// </summary>
  1652. public void RegisterCommsEvents()
  1653. {
  1654. m_sceneGridService.OnExpectUser += NewUserConnection;
  1655. m_sceneGridService.OnAvatarCrossingIntoRegion += AgentCrossing;
  1656. m_sceneGridService.OnCloseAgentConnection += CloseConnection;
  1657. m_sceneGridService.OnRegionUp += OtherRegionUp;
  1658. m_sceneGridService.OnChildAgentUpdate += IncomingChildAgentDataUpdate;
  1659. m_sceneGridService.OnExpectPrim += IncomingInterRegionPrimGroup;
  1660. m_sceneGridService.OnRemoveKnownRegionFromAvatar += HandleRemoveKnownRegionsFromAvatar;
  1661. m_sceneGridService.KillObject = SendKillObject;
  1662. }
  1663. /// <summary>
  1664. ///
  1665. /// </summary>
  1666. public void UnRegisterReginWithComms()
  1667. {
  1668. m_sceneGridService.OnRemoveKnownRegionFromAvatar -= HandleRemoveKnownRegionsFromAvatar;
  1669. m_sceneGridService.OnExpectPrim -= IncomingInterRegionPrimGroup;
  1670. m_sceneGridService.OnChildAgentUpdate -= IncomingChildAgentDataUpdate;
  1671. m_sceneGridService.OnRegionUp -= OtherRegionUp;
  1672. m_sceneGridService.OnExpectUser -= NewUserConnection;
  1673. m_sceneGridService.OnAvatarCrossingIntoRegion -= AgentCrossing;
  1674. m_sceneGridService.OnCloseAgentConnection -= CloseConnection;
  1675. m_sceneGridService.Close();
  1676. }
  1677. /// <summary>
  1678. /// Do the work necessary to initiate a new user connection.
  1679. /// At the moment, this consists of setting up the caps infrastructure
  1680. /// </summary>
  1681. /// <param name="regionHandle"></param>
  1682. /// <param name="agent"></param>
  1683. public void NewUserConnection(ulong regionHandle, AgentCircuitData agent)
  1684. {
  1685. if (regionHandle == m_regInfo.RegionHandle)
  1686. {
  1687. capsPaths[agent.AgentID] = agent.CapsPath;
  1688. if (!agent.child)
  1689. {
  1690. AddCapsHandler(agent.AgentID);
  1691. // Honor parcel landing type and position.
  1692. ILandObject land = LandChannel.getLandObject(agent.startpos.X, agent.startpos.Y);
  1693. if (land != null)
  1694. {
  1695. if (land.landData.landingType == (byte)1 && land.landData.userLocation != LLVector3.Zero)
  1696. {
  1697. agent.startpos = land.landData.userLocation;
  1698. }
  1699. }
  1700. }
  1701. m_log.DebugFormat(
  1702. "[CONNECTION DEBUGGING]: Creating new circuit code ({0}) for avatar {1} at {2}",
  1703. agent.circuitcode, agent.AgentID, RegionInfo.RegionName);
  1704. m_authenticateHandler.AddNewCircuit(agent.circuitcode, agent);
  1705. }
  1706. else
  1707. {
  1708. m_log.WarnFormat(
  1709. "[CONNECTION DEBUGGING]: Skipping this region for welcoming avatar {0} [{1}] at {2}",
  1710. agent.AgentID, regionHandle, RegionInfo.RegionName);
  1711. }
  1712. }
  1713. /// <summary>
  1714. /// Add a caps handler for the given agent. If the CAPS handler already exists for this agent,
  1715. /// then it is replaced by a new CAPS handler.
  1716. ///
  1717. /// FIXME: On login this is called twice, once for the login and once when the connection is made.
  1718. /// This is somewhat innefficient and should be fixed. The initial login creation is necessary
  1719. /// since the client asks for capabilities immediately after being informed of the seed.
  1720. /// </summary>
  1721. /// <param name="agentId"></param>
  1722. /// <param name="capsObjectPath"></param>
  1723. public void AddCapsHandler(LLUUID agentId)
  1724. {
  1725. String capsObjectPath = GetCapsPath(agentId);
  1726. m_log.DebugFormat(
  1727. "[CAPS]: Setting up CAPS handler for root agent {0} in {1}",
  1728. agentId, RegionInfo.RegionName);
  1729. Caps cap =
  1730. new Caps(AssetCache, m_httpListener, m_regInfo.ExternalHostName, m_httpListener.Port,
  1731. capsObjectPath, agentId, m_dumpAssetsToFile, RegionInfo.RegionName);
  1732. cap.RegisterHandlers();
  1733. EventManager.TriggerOnRegisterCaps(agentId, cap);
  1734. cap.AddNewInventoryItem = AddInventoryItem;
  1735. cap.ItemUpdatedCall = CapsUpdateInventoryItemAsset;
  1736. cap.TaskScriptUpdatedCall = CapsUpdateTaskInventoryScriptAsset;
  1737. cap.CAPSFetchInventoryDescendents = CommsManager.UserProfileCacheService.HandleFetchInventoryDescendentsCAPS;
  1738. cap.GetClient = m_innerScene.GetControllingClient;
  1739. m_capsHandlers[agentId] = cap;
  1740. }
  1741. /// <summary>
  1742. /// Remove the caps handler for a given agent.
  1743. /// </summary>
  1744. /// <param name="agentId"></param>
  1745. public void RemoveCapsHandler(LLUUID agentId)
  1746. {
  1747. lock (m_capsHandlers)
  1748. {
  1749. if (m_capsHandlers.ContainsKey(agentId))
  1750. {
  1751. m_log.DebugFormat(
  1752. "[CAPS]: Removing CAPS handler for root agent {0} in {1}",
  1753. agentId, RegionInfo.RegionName);
  1754. m_capsHandlers[agentId].DeregisterHandlers();
  1755. EventManager.TriggerOnDeregisterCaps(agentId, m_capsHandlers[agentId]);
  1756. m_capsHandlers.Remove(agentId);
  1757. }
  1758. else
  1759. {
  1760. m_log.WarnFormat(
  1761. "[CAPS]: Received request to remove CAPS handler for root agent {0} in {1}, but no such CAPS handler found!",
  1762. agentId, RegionInfo.RegionName);
  1763. }
  1764. }
  1765. }
  1766. /// <summary>
  1767. ///
  1768. /// </summary>
  1769. /// <param name="regionHandle"></param>
  1770. /// <param name="agentID"></param>
  1771. /// <param name="position"></param>
  1772. /// <param name="isFlying"></param>
  1773. public virtual void AgentCrossing(ulong regionHandle, LLUUID agentID, LLVector3 position, bool isFlying)
  1774. {
  1775. if (regionHandle == m_regInfo.RegionHandle)
  1776. {
  1777. if (m_scenePresences.ContainsKey(agentID))
  1778. {
  1779. try
  1780. {
  1781. m_scenePresences[agentID].MakeRootAgent(position, isFlying);
  1782. }
  1783. catch (Exception e)
  1784. {
  1785. m_log.Info("[SCENE]: Unable to do Agent Crossing.");
  1786. m_log.Debug("[SCENE]: " + e.ToString());
  1787. }
  1788. //m_innerScene.SwapRootChildAgent(false);
  1789. }
  1790. }
  1791. }
  1792. public virtual bool IncomingChildAgentDataUpdate(ulong regionHandle, ChildAgentDataUpdate cAgentData)
  1793. {
  1794. ScenePresence childAgentUpdate = GetScenePresence(new LLUUID(cAgentData.AgentID));
  1795. if (childAgentUpdate != null)
  1796. {
  1797. // I can't imagine *yet* why we would get an update if the agent is a root agent..
  1798. // however to avoid a race condition crossing borders..
  1799. if (childAgentUpdate.IsChildAgent)
  1800. {
  1801. uint rRegionX = (uint)(cAgentData.regionHandle >> 40);
  1802. uint rRegionY = (((uint)(cAgentData.regionHandle)) >> 8);
  1803. uint tRegionX = RegionInfo.RegionLocX;
  1804. uint tRegionY = RegionInfo.RegionLocY;
  1805. //Send Data to ScenePresence
  1806. childAgentUpdate.ChildAgentDataUpdate(cAgentData, tRegionX, tRegionY, rRegionX, rRegionY);
  1807. // Not Implemented:
  1808. //TODO: Do we need to pass the message on to one of our neighbors?
  1809. }
  1810. return true;
  1811. }
  1812. return false;
  1813. }
  1814. /// <summary>
  1815. /// Tell a single agent to disconnect from the region.
  1816. /// </summary>
  1817. /// <param name="regionHandle"></param>
  1818. /// <param name="agentID"></param>
  1819. public bool CloseConnection(ulong regionHandle, LLUUID agentID)
  1820. {
  1821. if (regionHandle == m_regionHandle)
  1822. {
  1823. ScenePresence presence = m_innerScene.GetScenePresence(agentID);
  1824. if (presence != null)
  1825. {
  1826. if (presence.IsChildAgent)
  1827. {
  1828. m_innerScene.removeUserCount(false);
  1829. }
  1830. else
  1831. {
  1832. m_innerScene.removeUserCount(true);
  1833. }
  1834. // Tell a single agent to disconnect from the region.
  1835. DisableSimulatorPacket disable = (DisableSimulatorPacket)PacketPool.Instance.GetPacket(PacketType.DisableSimulator);
  1836. presence.ControllingClient.OutPacket(disable, ThrottleOutPacketType.Unknown);
  1837. presence.ControllingClient.Close(true);
  1838. }
  1839. }
  1840. return true;
  1841. }
  1842. /// <summary>
  1843. /// Tell neighboring regions about this agent
  1844. /// When the regions respond with a true value,
  1845. /// tell the agents about the region.
  1846. ///
  1847. /// We have to tell the regions about the agents first otherwise it'll deny them access
  1848. ///
  1849. /// </summary>
  1850. /// <param name="presence"></param>
  1851. public void InformClientOfNeighbours(ScenePresence presence)
  1852. {
  1853. m_sceneGridService.EnableNeighbourChildAgents(presence, m_neighbours);
  1854. }
  1855. /// <summary>
  1856. /// Tell a neighboring region about this agent
  1857. /// </summary>
  1858. /// <param name="presence"></param>
  1859. /// <param name="region"></param>
  1860. public void InformClientOfNeighbor(ScenePresence presence, RegionInfo region)
  1861. {
  1862. m_sceneGridService.InformNeighborChildAgent(presence, region, m_neighbours);
  1863. }
  1864. /// <summary>
  1865. /// Requests information about this region from gridcomms
  1866. /// </summary>
  1867. /// <param name="regionHandle"></param>
  1868. /// <returns></returns>
  1869. public RegionInfo RequestNeighbouringRegionInfo(ulong regionHandle)
  1870. {
  1871. return m_sceneGridService.RequestNeighbouringRegionInfo(regionHandle);
  1872. }
  1873. /// <summary>
  1874. /// Requests textures for map from minimum region to maximum region in world cordinates
  1875. /// </summary>
  1876. /// <param name="remoteClient"></param>
  1877. /// <param name="minX"></param>
  1878. /// <param name="minY"></param>
  1879. /// <param name="maxX"></param>
  1880. /// <param name="maxY"></param>
  1881. public void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY)
  1882. {
  1883. m_sceneGridService.RequestMapBlocks(remoteClient, minX, minY, maxX, maxX);
  1884. }
  1885. /// <summary>
  1886. /// Tries to teleport agent to other region.
  1887. /// </summary>
  1888. /// <param name="remoteClient"></param>
  1889. /// <param name="regionHandle"></param>
  1890. /// <param name="position"></param>
  1891. /// <param name="lookAt"></param>
  1892. /// <param name="flags"></param>
  1893. public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, LLVector3 position,
  1894. LLVector3 lookAt, uint flags)
  1895. {
  1896. if (m_scenePresences.ContainsKey(remoteClient.AgentId))
  1897. {
  1898. m_sceneGridService.RequestTeleportToLocation(m_scenePresences[remoteClient.AgentId], regionHandle,
  1899. position, lookAt, flags);
  1900. }
  1901. }
  1902. /// <summary>
  1903. /// Tries to teleport agent to landmark.
  1904. /// </summary>
  1905. /// <param name="remoteClient"></param>
  1906. /// <param name="regionHandle"></param>
  1907. /// <param name="position"></param>
  1908. public void RequestTeleportLandmark(IClientAPI remoteClient, ulong regionHandle, LLVector3 position)
  1909. {
  1910. if (m_scenePresences.ContainsKey(remoteClient.AgentId))
  1911. {
  1912. m_sceneGridService.RequestTeleportToLocation(m_scenePresences[remoteClient.AgentId], regionHandle,
  1913. position, LLVector3.Zero, 0);
  1914. }
  1915. }
  1916. /// <summary>
  1917. /// Agent is crossing the border into a neighbouring region. Tell the neighbour about it!
  1918. /// </summary>
  1919. /// <param name="regionHandle"></param>
  1920. /// <param name="agentID"></param>
  1921. /// <param name="position"></param>
  1922. /// <param name="isFlying"></param>
  1923. /// <returns></returns>
  1924. public bool InformNeighbourOfCrossing(ulong regionHandle, LLUUID agentID, LLVector3 position, bool isFlying)
  1925. {
  1926. return m_sceneGridService.CrossToNeighbouringRegion(regionHandle, agentID, position, isFlying);
  1927. }
  1928. public void SendOutChildAgentUpdates(ChildAgentDataUpdate cadu, ScenePresence presence)
  1929. {
  1930. m_sceneGridService.SendChildAgentDataUpdate(cadu, presence);
  1931. }
  1932. #endregion
  1933. #region Module Methods
  1934. /// <summary>
  1935. ///
  1936. /// </summary>
  1937. /// <param name="name"></param>
  1938. /// <param name="module"></param>
  1939. public void AddModule(string name, IRegionModule module)
  1940. {
  1941. if (!Modules.ContainsKey(name))
  1942. {
  1943. Modules.Add(name, module);
  1944. }
  1945. }
  1946. public void RegisterModuleCommander(string name, ICommander commander)
  1947. {
  1948. lock (m_moduleCommanders)
  1949. {
  1950. m_moduleCommanders.Add(name, commander);
  1951. }
  1952. }
  1953. public ICommander GetCommander(string name)
  1954. {
  1955. lock (m_moduleCommanders)
  1956. {
  1957. return m_moduleCommanders[name];
  1958. }
  1959. }
  1960. public Dictionary<string, ICommander> GetCommanders()
  1961. {
  1962. return m_moduleCommanders;
  1963. }
  1964. /// <summary>
  1965. ///
  1966. /// </summary>
  1967. /// <param name="mod"></param>
  1968. public void RegisterModuleInterface<M>(M mod)
  1969. {
  1970. if (!ModuleInterfaces.ContainsKey(typeof(M)))
  1971. {
  1972. ModuleInterfaces.Add(typeof(M), mod);
  1973. }
  1974. }
  1975. /// <summary>
  1976. ///
  1977. /// </summary>
  1978. /// <returns></returns>
  1979. public T RequestModuleInterface<T>()
  1980. {
  1981. if (ModuleInterfaces.ContainsKey(typeof(T)))
  1982. {
  1983. return (T)ModuleInterfaces[typeof(T)];
  1984. }
  1985. else
  1986. {
  1987. return default(T);
  1988. }
  1989. }
  1990. public void SetObjectCapacity(int objects)
  1991. {
  1992. if (m_statsReporter != null)
  1993. {
  1994. m_statsReporter.SetObjectCapacity(objects);
  1995. }
  1996. objectCapacity = objects;
  1997. }
  1998. public List<FriendListItem> GetFriendList(LLUUID avatarID)
  1999. {
  2000. return CommsManager.GetUserFriendList(avatarID);
  2001. }
  2002. #endregion
  2003. #region Other Methods
  2004. /// <summary>
  2005. ///
  2006. /// </summary>
  2007. /// <param name="phase"></param>
  2008. public void SetTimePhase(int phase)
  2009. {
  2010. m_timePhase = phase;
  2011. }
  2012. /// <summary>
  2013. ///
  2014. /// </summary>
  2015. /// <param name="avatarID"></param>
  2016. /// <param name="objectName"></param>
  2017. /// <param name="objectID"></param>
  2018. /// <param name="ownerID"></param>
  2019. /// <param name="groupOwned"></param>
  2020. /// <param name="message"></param>
  2021. /// <param name="url"></param>
  2022. public void SendUrlToUser(LLUUID avatarID, string objectName, LLUUID objectID, LLUUID ownerID, bool groupOwned,
  2023. string message, string url)
  2024. {
  2025. if (m_scenePresences.ContainsKey(avatarID))
  2026. {
  2027. m_scenePresences[avatarID].ControllingClient.SendLoadURL(objectName, objectID, ownerID, groupOwned,
  2028. message, url);
  2029. }
  2030. }
  2031. public void SendDialogToUser(LLUUID avatarID, string objectName, LLUUID objectID, LLUUID ownerID, string message, LLUUID TextureID, int ch, string[] buttonlabels)
  2032. {
  2033. if (m_scenePresences.ContainsKey(avatarID))
  2034. {
  2035. m_scenePresences[avatarID].ControllingClient.SendDialog(objectName, objectID, ownerID, message, TextureID, ch, buttonlabels);
  2036. }
  2037. }
  2038. /// <summary>
  2039. ///
  2040. /// </summary>
  2041. /// <param name="url"></param>
  2042. /// <param name="type"></param>
  2043. /// <param name="body"></param>
  2044. /// <returns></returns>
  2045. public LLUUID MakeHttpRequest(string url, string type, string body)
  2046. {
  2047. if (m_httpRequestModule != null)
  2048. {
  2049. return m_httpRequestModule.MakeHttpRequest(url, type, body);
  2050. }
  2051. return LLUUID.Zero;
  2052. }
  2053. /// <summary>
  2054. /// This method is a way for the Friends Module to create an instant
  2055. /// message to the avatar and for Instant Messages that travel across
  2056. /// gridcomms to make it to the Instant Message Module.
  2057. ///
  2058. /// Friendship establishment and groups are unfortunately tied with instant messaging and
  2059. /// there's no way to separate them completely.
  2060. /// </summary>
  2061. /// <param name="message">object containing the instant message data</param>
  2062. /// <returns>void</returns>
  2063. public void TriggerGridInstantMessage(GridInstantMessage message, InstantMessageReceiver options)
  2064. {
  2065. m_eventManager.TriggerGridInstantMessage(message, options);
  2066. }
  2067. public virtual void StoreAddFriendship(LLUUID ownerID, LLUUID friendID, uint perms)
  2068. {
  2069. // TODO: m_sceneGridService.DoStuff;
  2070. m_sceneGridService.AddNewUserFriend(ownerID, friendID, perms);
  2071. }
  2072. public virtual void StoreUpdateFriendship(LLUUID ownerID, LLUUID friendID, uint perms)
  2073. {
  2074. // TODO: m_sceneGridService.DoStuff;
  2075. m_sceneGridService.UpdateUserFriendPerms(ownerID, friendID, perms);
  2076. }
  2077. public virtual void StoreRemoveFriendship(LLUUID ownerID, LLUUID ExfriendID)
  2078. {
  2079. // TODO: m_sceneGridService.DoStuff;
  2080. m_sceneGridService.RemoveUserFriend(ownerID, ExfriendID);
  2081. }
  2082. public virtual List<FriendListItem> StoreGetFriendsForUser(LLUUID ownerID)
  2083. {
  2084. // TODO: m_sceneGridService.DoStuff;
  2085. return m_sceneGridService.GetUserFriendList(ownerID);
  2086. }
  2087. public void AddPacketStats(int inPackets, int outPackets, int unAckedBytes)
  2088. {
  2089. m_statsReporter.AddInPackets(inPackets);
  2090. m_statsReporter.AddOutPackets(outPackets);
  2091. m_statsReporter.AddunAckedBytes(unAckedBytes);
  2092. }
  2093. public void AddAgentTime(int ms)
  2094. {
  2095. m_statsReporter.addFrameMS(ms);
  2096. m_statsReporter.addAgentMS(ms);
  2097. }
  2098. public void AddAgentUpdates(int count)
  2099. {
  2100. m_statsReporter.AddAgentUpdates(count);
  2101. }
  2102. public void AddPendingDownloads(int count)
  2103. {
  2104. m_statsReporter.addPendingDownload(count);
  2105. }
  2106. #endregion
  2107. #region Console Commands
  2108. #region Alert Methods
  2109. private void SendPermissionAlert(LLUUID user, string reason)
  2110. {
  2111. SendAlertToUser(user, reason, false);
  2112. }
  2113. /// <summary>
  2114. ///
  2115. /// </summary>
  2116. /// <param name="message"></param>
  2117. public void SendGeneralAlert(string message)
  2118. {
  2119. List<ScenePresence> presenceList = GetScenePresences();
  2120. foreach (ScenePresence presence in presenceList)
  2121. {
  2122. presence.ControllingClient.SendAlertMessage(message);
  2123. }
  2124. }
  2125. /// <summary>
  2126. ///
  2127. /// </summary>
  2128. /// <param name="agentID"></param>
  2129. /// <param name="message"></param>
  2130. /// <param name="modal"></param>
  2131. public void SendAlertToUser(LLUUID agentID, string message, bool modal)
  2132. {
  2133. if (m_scenePresences.ContainsKey(agentID))
  2134. {
  2135. m_scenePresences[agentID].ControllingClient.SendAgentAlertMessage(message, modal);
  2136. }
  2137. }
  2138. /// <summary>
  2139. ///
  2140. /// </summary>
  2141. /// <param name="agentID"></param>
  2142. /// <param name="sessionID"></param>
  2143. /// <param name="token"></param>
  2144. /// <param name="controllingClient"></param>
  2145. public void handleRequestGodlikePowers(LLUUID agentID, LLUUID sessionID, LLUUID token, bool godLike,
  2146. IClientAPI controllingClient)
  2147. {
  2148. // First check that this is the sim owner
  2149. if (m_permissionManager.GenericEstatePermission(agentID))
  2150. {
  2151. // User needs to be logged into this sim
  2152. if (m_scenePresences.ContainsKey(agentID))
  2153. {
  2154. // Next we check for spoofing.....
  2155. LLUUID testSessionID = m_scenePresences[agentID].ControllingClient.SessionId;
  2156. if (sessionID == testSessionID)
  2157. {
  2158. if (sessionID == controllingClient.SessionId)
  2159. {
  2160. //m_log.Info("godlike: " + godLike.ToString());
  2161. m_scenePresences[agentID].GrantGodlikePowers(agentID, testSessionID, token, godLike);
  2162. }
  2163. }
  2164. }
  2165. }
  2166. else
  2167. {
  2168. m_scenePresences[agentID].ControllingClient.SendAgentAlertMessage("Request for god powers denied", false);
  2169. }
  2170. }
  2171. /// <summary>
  2172. /// Sends a Big Blue Box message on the upper right of the screen to the client
  2173. /// for all agents in the region
  2174. /// </summary>
  2175. /// <param name="FromAvatarID">The person sending the message</param>
  2176. /// <param name="fromSessionID">The session of the person sending the message</param>
  2177. /// <param name="FromAvatarName">The name of the person doing the sending</param>
  2178. /// <param name="Message">The Message being sent to the user</param>
  2179. public void SendRegionMessageFromEstateTools(LLUUID FromAvatarID, LLUUID fromSessionID, String FromAvatarName, String Message)
  2180. {
  2181. List<ScenePresence> presenceList = GetScenePresences();
  2182. foreach (ScenePresence presence in presenceList)
  2183. {
  2184. if (!presence.IsChildAgent)
  2185. presence.ControllingClient.SendBlueBoxMessage(FromAvatarID, fromSessionID, FromAvatarName, Message);
  2186. }
  2187. }
  2188. /// <summary>
  2189. /// Sends a Big Blue Box message on the upper right of the screen to the client
  2190. /// for all agents in the estate
  2191. /// </summary>
  2192. /// <param name="FromAvatarID">The person sending the message</param>
  2193. /// <param name="fromSessionID">The session of the person sending the message</param>
  2194. /// <param name="FromAvatarName">The name of the person doing the sending</param>
  2195. /// <param name="Message">The Message being sent to the user</param>
  2196. public void SendEstateMessageFromEstateTools(LLUUID FromAvatarID, LLUUID fromSessionID, String FromAvatarName, String Message)
  2197. {
  2198. ClientManager.ForEachClient(delegate(IClientAPI controller)
  2199. {
  2200. controller.SendBlueBoxMessage(FromAvatarID, fromSessionID, FromAvatarName, Message);
  2201. }
  2202. );
  2203. }
  2204. /// <summary>
  2205. /// Kicks User specified from the simulator. This logs them off of the grid
  2206. /// If the client gets the UUID: 44e87126e7944ded05b37c42da3d5cdb it assumes
  2207. /// that you're kicking it even if the avatar's UUID isn't the UUID that the
  2208. /// agent is assigned
  2209. /// </summary>
  2210. /// <param name="godID">The person doing the kicking</param>
  2211. /// <param name="sessionID">The session of the person doing the kicking</param>
  2212. /// <param name="agentID">the person that is being kicked</param>
  2213. /// <param name="kickflags">This isn't used apparently</param>
  2214. /// <param name="reason">The message to send to the user after it's been turned into a field</param>
  2215. public void HandleGodlikeKickUser(LLUUID godID, LLUUID sessionID, LLUUID agentID, uint kickflags, byte[] reason)
  2216. {
  2217. // For some reason the client sends this seemingly hard coded UUID for kicking everyone. Dun-know.
  2218. LLUUID kickUserID = new LLUUID("44e87126e7944ded05b37c42da3d5cdb");
  2219. if (m_scenePresences.ContainsKey(agentID) || agentID == kickUserID)
  2220. {
  2221. if (m_permissionManager.GenericEstatePermission(godID))
  2222. {
  2223. if (agentID == kickUserID)
  2224. {
  2225. ClientManager.ForEachClient(delegate(IClientAPI controller)
  2226. {
  2227. if (controller.AgentId != godID)
  2228. controller.Kick(Helpers.FieldToUTF8String(reason));
  2229. }
  2230. );
  2231. // This is a bit crude. It seems the client will be null before it actually stops the thread
  2232. // The thread will kill itself eventually :/
  2233. // Is there another way to make sure *all* clients get this 'inter region' message?
  2234. ClientManager.ForEachClient(delegate(IClientAPI controller)
  2235. {
  2236. ScenePresence p = GetScenePresence(controller.AgentId);
  2237. bool childagent = !p.Equals(null) && p.IsChildAgent;
  2238. if (controller.AgentId != godID && !childagent)
  2239. // Do we really want to kick the initiator of this madness?
  2240. {
  2241. controller.Close(true);
  2242. }
  2243. }
  2244. );
  2245. }
  2246. else
  2247. {
  2248. if (m_scenePresences[agentID].IsChildAgent)
  2249. {
  2250. m_innerScene.removeUserCount(false);
  2251. }
  2252. else
  2253. {
  2254. m_innerScene.removeUserCount(true);
  2255. }
  2256. m_scenePresences[agentID].ControllingClient.Kick(Helpers.FieldToUTF8String(reason));
  2257. m_scenePresences[agentID].ControllingClient.Close(true);
  2258. }
  2259. }
  2260. else
  2261. {
  2262. if (m_scenePresences.ContainsKey(godID))
  2263. m_scenePresences[godID].ControllingClient.SendAgentAlertMessage("Kick request denied", false);
  2264. }
  2265. }
  2266. }
  2267. public void HandleObjectPermissionsUpdate(IClientAPI controller, LLUUID agentID, LLUUID sessionID, byte field, uint localId, uint mask, byte set)
  2268. {
  2269. // Check for spoofing.. since this is permissions we're talking about here!
  2270. if ((controller.SessionId == sessionID) && (controller.AgentId == agentID))
  2271. {
  2272. // Tell the object to do permission update
  2273. if (localId != 0)
  2274. {
  2275. SceneObjectGroup chObjectGroup = GetGroupByPrim(localId);
  2276. if (chObjectGroup != null)
  2277. {
  2278. chObjectGroup.UpdatePermissions(agentID, field, localId, mask, set);
  2279. }
  2280. }
  2281. }
  2282. }
  2283. /// <summary>
  2284. ///
  2285. /// </summary>
  2286. /// <param name="firstName"></param>
  2287. /// <param name="lastName"></param>
  2288. /// <param name="message"></param>
  2289. /// <param name="modal"></param>
  2290. public void SendAlertToUser(string firstName, string lastName, string message, bool modal)
  2291. {
  2292. List<ScenePresence> presenceList = GetScenePresences();
  2293. foreach (ScenePresence presence in presenceList)
  2294. {
  2295. if ((presence.Firstname == firstName) && (presence.Lastname == lastName))
  2296. {
  2297. presence.ControllingClient.SendAgentAlertMessage(message, modal);
  2298. break;
  2299. }
  2300. }
  2301. }
  2302. /// <summary>
  2303. ///
  2304. /// </summary>
  2305. /// <param name="commandParams"></param>
  2306. public void HandleAlertCommand(string[] commandParams)
  2307. {
  2308. if (commandParams[0] == "general")
  2309. {
  2310. string message = CombineParams(commandParams, 1);
  2311. SendGeneralAlert(message);
  2312. }
  2313. else
  2314. {
  2315. string message = CombineParams(commandParams, 2);
  2316. SendAlertToUser(commandParams[0], commandParams[1], message, false);
  2317. }
  2318. }
  2319. private string CombineParams(string[] commandParams, int pos)
  2320. {
  2321. string result = String.Empty;
  2322. for (int i = pos; i < commandParams.Length; i++)
  2323. {
  2324. result += commandParams[i] + " ";
  2325. }
  2326. return result;
  2327. }
  2328. #endregion
  2329. /// <summary>
  2330. /// Causes all clients to get a full object update on all of the objects in the scene.
  2331. /// </summary>
  2332. public void ForceClientUpdate()
  2333. {
  2334. List<EntityBase> EntitieList = GetEntities();
  2335. foreach (EntityBase ent in EntitieList)
  2336. {
  2337. if (ent is SceneObjectGroup)
  2338. {
  2339. ((SceneObjectGroup)ent).ScheduleGroupForFullUpdate();
  2340. }
  2341. }
  2342. }
  2343. /// <summary>
  2344. /// This is currently only used for scale (to scale to MegaPrim size)
  2345. /// There is a console command that calls this in OpenSimMain
  2346. /// </summary>
  2347. /// <param name="cmdparams"></param>
  2348. public void HandleEditCommand(string[] cmdparams)
  2349. {
  2350. Console.WriteLine("Searching for Primitive: '" + cmdparams[0] + "'");
  2351. List<EntityBase> EntitieList = GetEntities();
  2352. foreach (EntityBase ent in EntitieList)
  2353. {
  2354. if (ent is SceneObjectGroup)
  2355. {
  2356. SceneObjectPart part = ((SceneObjectGroup)ent).GetChildPart(((SceneObjectGroup)ent).UUID);
  2357. if (part != null)
  2358. {
  2359. if (part.Name == cmdparams[0])
  2360. {
  2361. part.Resize(
  2362. new LLVector3(Convert.ToSingle(cmdparams[1]), Convert.ToSingle(cmdparams[2]),
  2363. Convert.ToSingle(cmdparams[3])));
  2364. Console.WriteLine("Edited scale of Primitive: " + part.Name);
  2365. }
  2366. }
  2367. }
  2368. }
  2369. }
  2370. /// <summary>
  2371. /// Shows various details about the sim based on the parameters supplied by the console command in openSimMain.
  2372. /// </summary>
  2373. /// <param name="showWhat"></param>
  2374. public void Show(string showWhat)
  2375. {
  2376. switch (showWhat)
  2377. {
  2378. case "users":
  2379. m_log.Error("Current Region: " + RegionInfo.RegionName);
  2380. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}{6,-16}", "Firstname", "Lastname",
  2381. "Agent ID", "Session ID", "Circuit", "IP", "World");
  2382. foreach (ScenePresence scenePresence in GetAvatars())
  2383. {
  2384. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}{6,-16}",
  2385. scenePresence.Firstname,
  2386. scenePresence.Lastname,
  2387. scenePresence.UUID,
  2388. scenePresence.ControllingClient.AgentId,
  2389. "Unknown",
  2390. "Unknown",
  2391. RegionInfo.RegionName);
  2392. }
  2393. break;
  2394. case "modules":
  2395. m_log.Error("The currently loaded modules in " + RegionInfo.RegionName + " are:");
  2396. foreach (IRegionModule module in Modules.Values)
  2397. {
  2398. if (!module.IsSharedModule)
  2399. {
  2400. m_log.Error("Region Module: " + module.Name);
  2401. }
  2402. }
  2403. break;
  2404. }
  2405. }
  2406. #endregion
  2407. #region Script Handling Methods
  2408. /// <summary>
  2409. /// Console command handler to send script command to script engine.
  2410. /// </summary>
  2411. /// <param name="args"></param>
  2412. public void SendCommandToPlugins(string[] args)
  2413. {
  2414. m_eventManager.TriggerOnPluginConsole(args);
  2415. }
  2416. public double GetLandHeight(int x, int y)
  2417. {
  2418. return Heightmap[x, y];
  2419. }
  2420. public LLUUID GetLandOwner(float x, float y)
  2421. {
  2422. ILandObject land = LandChannel.getLandObject(x, y);
  2423. if (land == null)
  2424. {
  2425. return LLUUID.Zero;
  2426. }
  2427. else
  2428. {
  2429. return land.landData.ownerID;
  2430. }
  2431. }
  2432. public LandData GetLandData(float x, float y)
  2433. {
  2434. return LandChannel.getLandObject(x, y).landData;
  2435. }
  2436. public void SetLandMusicURL(float x, float y, string url)
  2437. {
  2438. ILandObject land = LandChannel.getLandObject(x, y);
  2439. if (land == null)
  2440. {
  2441. return;
  2442. }
  2443. else
  2444. {
  2445. land.landData.musicURL = url;
  2446. return;
  2447. }
  2448. }
  2449. public void SetLandMediaURL(float x, float y, string url)
  2450. {
  2451. ILandObject land = LandChannel.getLandObject(x, y);
  2452. if (land == null)
  2453. {
  2454. return;
  2455. }
  2456. else
  2457. {
  2458. land.landData.mediaURL = url;
  2459. return;
  2460. }
  2461. }
  2462. #endregion
  2463. #region Script Engine
  2464. private List<ScriptEngineInterface> ScriptEngines = new List<ScriptEngineInterface>();
  2465. private bool m_dumpAssetsToFile;
  2466. /// <summary>
  2467. ///
  2468. /// </summary>
  2469. /// <param name="scriptEngine"></param>
  2470. public void AddScriptEngine(ScriptEngineInterface scriptEngine)
  2471. {
  2472. ScriptEngines.Add(scriptEngine);
  2473. scriptEngine.InitializeEngine(this);
  2474. }
  2475. public void TriggerObjectChanged(uint localID, uint change)
  2476. {
  2477. m_eventManager.TriggerOnScriptChangedEvent(localID, change);
  2478. }
  2479. public void TriggerAtTargetEvent(uint localID, uint handle, LLVector3 targetpos, LLVector3 currentpos)
  2480. {
  2481. m_eventManager.TriggerAtTargetEvent(localID, handle, targetpos, currentpos);
  2482. }
  2483. public void TriggerNotAtTargetEvent(uint localID)
  2484. {
  2485. m_eventManager.TriggerNotAtTargetEvent(localID);
  2486. }
  2487. private bool scriptDanger(SceneObjectPart part,LLVector3 pos)
  2488. {
  2489. ILandObject parcel = LandChannel.getLandObject(pos.X, pos.Y);
  2490. if (part != null)
  2491. {
  2492. if (parcel != null)
  2493. {
  2494. if ((parcel.landData.landFlags & (uint)Parcel.ParcelFlags.AllowOtherScripts) != 0)
  2495. {
  2496. return true;
  2497. }
  2498. else if ((parcel.landData.landFlags & (uint)Parcel.ParcelFlags.AllowGroupScripts) != 0)
  2499. {
  2500. if (part.OwnerID == parcel.landData.ownerID || (parcel.landData.isGroupOwned && part.GroupID == parcel.landData.groupID) || PermissionsMngr.GenericEstatePermission(part.OwnerID))
  2501. {
  2502. return true;
  2503. }
  2504. else
  2505. {
  2506. return false;
  2507. }
  2508. }
  2509. else
  2510. {
  2511. if (part.OwnerID == parcel.landData.ownerID)
  2512. {
  2513. return true;
  2514. }
  2515. else
  2516. {
  2517. return false;
  2518. }
  2519. }
  2520. }
  2521. else
  2522. {
  2523. if (pos.X > 0f && pos.X < Constants.RegionSize && pos.Y > 0f && pos.Y < Constants.RegionSize)
  2524. {
  2525. // The only time parcel != null when an object is inside a region is when
  2526. // there is nothing behind the landchannel. IE, no land plugin loaded.
  2527. return true;
  2528. }
  2529. else
  2530. {
  2531. // The object is outside of this region. Stop piping events to it.
  2532. return false;
  2533. }
  2534. }
  2535. }
  2536. else
  2537. {
  2538. return false;
  2539. }
  2540. }
  2541. public bool scriptDanger(uint localID, LLVector3 pos)
  2542. {
  2543. SceneObjectPart part = GetSceneObjectPart(localID);
  2544. if (part != null)
  2545. {
  2546. return scriptDanger(part, pos);
  2547. }
  2548. else
  2549. {
  2550. return false;
  2551. }
  2552. }
  2553. public bool pipeEventsForScript(uint localID)
  2554. {
  2555. SceneObjectPart part = GetSceneObjectPart(localID);
  2556. if (part != null)
  2557. {
  2558. LLVector3 pos = part.GetWorldPosition();
  2559. return scriptDanger(part, pos);
  2560. }
  2561. else
  2562. {
  2563. return false;
  2564. }
  2565. }
  2566. #endregion
  2567. #region InnerScene wrapper methods
  2568. /// <summary>
  2569. ///
  2570. /// </summary>
  2571. /// <param name="localID"></param>
  2572. /// <returns></returns>
  2573. public LLUUID ConvertLocalIDToFullID(uint localID)
  2574. {
  2575. return m_innerScene.ConvertLocalIDToFullID(localID);
  2576. }
  2577. public void SwapRootAgentCount(bool rootChildChildRootTF)
  2578. {
  2579. m_innerScene.SwapRootChildAgent(rootChildChildRootTF);
  2580. }
  2581. public void AddPhysicalPrim(int num)
  2582. {
  2583. m_innerScene.AddPhysicalPrim(num);
  2584. }
  2585. public void RemovePhysicalPrim(int num)
  2586. {
  2587. m_innerScene.RemovePhysicalPrim(num);
  2588. }
  2589. /// <summary>
  2590. ///
  2591. /// </summary>
  2592. /// <param name="presence"></param>
  2593. public void SendAllSceneObjectsToClient(ScenePresence presence)
  2594. {
  2595. m_innerScene.SendAllSceneObjectsToClient(presence);
  2596. }
  2597. //The idea is to have a group of method that return a list of avatars meeting some requirement
  2598. // ie it could be all m_scenePresences within a certain range of the calling prim/avatar.
  2599. /// <summary>
  2600. ///
  2601. /// </summary>
  2602. /// <returns></returns>
  2603. public List<ScenePresence> GetAvatars()
  2604. {
  2605. return m_innerScene.GetAvatars();
  2606. }
  2607. /// <summary>
  2608. /// Request a List of all m_scenePresences in this World
  2609. /// </summary>
  2610. /// <returns></returns>
  2611. public List<ScenePresence> GetScenePresences()
  2612. {
  2613. return m_innerScene.GetScenePresences();
  2614. }
  2615. /// <summary>
  2616. /// Request a filtered list of m_scenePresences in this World
  2617. /// </summary>
  2618. /// <param name="filter"></param>
  2619. /// <returns></returns>
  2620. public List<ScenePresence> GetScenePresences(FilterAvatarList filter)
  2621. {
  2622. return m_innerScene.GetScenePresences(filter);
  2623. }
  2624. /// <summary>
  2625. /// Request a Avatar by UUID
  2626. /// </summary>
  2627. /// <param name="avatarID"></param>
  2628. /// <returns></returns>
  2629. public ScenePresence GetScenePresence(LLUUID avatarID)
  2630. {
  2631. return m_innerScene.GetScenePresence(avatarID);
  2632. }
  2633. /// <summary>
  2634. /// Request an Avatar's Child Status - used by ClientView when a 'kick everyone' or 'estate message' occurs
  2635. /// </summary>
  2636. /// <param name="avatarID">AvatarID to lookup</param>
  2637. /// <returns></returns>
  2638. public override bool PresenceChildStatus(LLUUID avatarID)
  2639. {
  2640. ScenePresence cp = GetScenePresence(avatarID);
  2641. return cp.IsChildAgent;
  2642. }
  2643. /// <summary>
  2644. ///
  2645. /// </summary>
  2646. /// <param name="action"></param>
  2647. public void ForEachScenePresence(Action<ScenePresence> action)
  2648. {
  2649. // We don't want to try to send messages if there are no avatar.
  2650. if (!(m_scenePresences.Equals(null)))
  2651. {
  2652. try
  2653. {
  2654. List<ScenePresence> presenceList = GetScenePresences();
  2655. foreach (ScenePresence presence in presenceList)
  2656. {
  2657. action(presence);
  2658. }
  2659. }
  2660. catch (Exception e)
  2661. {
  2662. m_log.Info("[BUG]: " + e.ToString());
  2663. }
  2664. }
  2665. }
  2666. /// <summary>
  2667. /// Delete this object from the scene.
  2668. /// </summary>
  2669. /// <param name="group"></param>
  2670. public void DeleteSceneObjectGroup(SceneObjectGroup group)
  2671. {
  2672. SceneObjectPart rootPart = (group).GetChildPart(group.UUID);
  2673. if (rootPart.PhysActor != null)
  2674. {
  2675. PhysicsScene.RemovePrim(rootPart.PhysActor);
  2676. rootPart.PhysActor = null;
  2677. }
  2678. m_storageManager.DataStore.RemoveObject(group.UUID, m_regInfo.RegionID);
  2679. group.DeleteGroup();
  2680. lock (Entities)
  2681. {
  2682. Entities.Remove(group.UUID);
  2683. m_innerScene.RemoveAPrimCount();
  2684. }
  2685. group.DeleteParts();
  2686. // In case anybody else retains a reference to this group, signal deletion by changing the name
  2687. // to null. We can't zero out the UUID because this is taken from the root part, which has already
  2688. // been removed.
  2689. // FIXME: This is a really poor temporary solution, since it still leaves plenty of scope for race
  2690. // conditions where a user deletes an entity while it is being stored. Really, the update
  2691. // code needs a redesign.
  2692. group.Name = null;
  2693. }
  2694. /// <summary>
  2695. ///
  2696. /// </summary>
  2697. /// <param name="action"></param>
  2698. // public void ForEachObject(Action<SceneObjectGroup> action)
  2699. // {
  2700. // List<SceneObjectGroup> presenceList;
  2701. //
  2702. // lock (m_sceneObjects)
  2703. // {
  2704. // presenceList = new List<SceneObjectGroup>(m_sceneObjects.Values);
  2705. // }
  2706. //
  2707. // foreach (SceneObjectGroup presence in presenceList)
  2708. // {
  2709. // action(presence);
  2710. // }
  2711. // }
  2712. /// <summary>
  2713. ///
  2714. /// </summary>
  2715. /// <param name="localID"></param>
  2716. /// <returns></returns>
  2717. public SceneObjectPart GetSceneObjectPart(uint localID)
  2718. {
  2719. return m_innerScene.GetSceneObjectPart(localID);
  2720. }
  2721. /// <summary>
  2722. ///
  2723. /// </summary>
  2724. /// <param name="fullID"></param>
  2725. /// <returns></returns>
  2726. public SceneObjectPart GetSceneObjectPart(LLUUID fullID)
  2727. {
  2728. return m_innerScene.GetSceneObjectPart(fullID);
  2729. }
  2730. internal bool TryGetAvatar(LLUUID avatarId, out ScenePresence avatar)
  2731. {
  2732. return m_innerScene.TryGetAvatar(avatarId, out avatar);
  2733. }
  2734. internal bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
  2735. {
  2736. return m_innerScene.TryGetAvatarByName(avatarName, out avatar);
  2737. }
  2738. internal void ForEachClient(Action<IClientAPI> action)
  2739. {
  2740. m_innerScene.ForEachClient(action);
  2741. }
  2742. public List<EntityBase> GetEntities()
  2743. {
  2744. return m_innerScene.GetEntities();
  2745. }
  2746. #endregion
  2747. #region BaseHTTPServer wrapper methods
  2748. public bool AddHTTPHandler(string method, GenericHTTPMethod handler)
  2749. {
  2750. return m_httpListener.AddHTTPHandler(method, handler);
  2751. }
  2752. public bool AddXmlRPCHandler(string method, XmlRpcMethod handler)
  2753. {
  2754. return m_httpListener.AddXmlRPCHandler(method, handler);
  2755. }
  2756. public void AddStreamHandler(IRequestHandler handler)
  2757. {
  2758. m_httpListener.AddStreamHandler(handler);
  2759. }
  2760. public void RemoveStreamHandler(string httpMethod, string path)
  2761. {
  2762. m_httpListener.RemoveStreamHandler(httpMethod, path);
  2763. }
  2764. public void RemoveHTTPHandler(string httpMethod, string path)
  2765. {
  2766. m_httpListener.RemoveHTTPHandler(httpMethod, path);
  2767. }
  2768. #endregion
  2769. #region Avatar Appearance Default
  2770. public static void GetDefaultAvatarAppearance(out AvatarWearable[] wearables, out byte[] visualParams)
  2771. {
  2772. visualParams = GetDefaultVisualParams();
  2773. wearables = AvatarWearable.DefaultWearables;
  2774. }
  2775. private static byte[] GetDefaultVisualParams()
  2776. {
  2777. byte[] visualParams;
  2778. visualParams = new byte[218];
  2779. for (int i = 0; i < 218; i++)
  2780. {
  2781. visualParams[i] = 100;
  2782. }
  2783. return visualParams;
  2784. }
  2785. #endregion
  2786. }
  2787. }