Scene.cs 154 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyrightD
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Drawing;
  30. using System.Drawing.Imaging;
  31. using System.IO;
  32. using System.Text;
  33. using System.Threading;
  34. using System.Timers;
  35. using System.Xml;
  36. using Nini.Config;
  37. using OpenMetaverse;
  38. using OpenMetaverse.Imaging;
  39. using OpenSim.Framework;
  40. using OpenSim.Services.Interfaces;
  41. using OpenSim.Framework.Communications;
  42. using OpenSim.Framework.Communications.Cache;
  43. using OpenSim.Framework.Communications.Clients;
  44. using OpenSim.Framework.Console;
  45. using OpenSim.Region.Framework.Interfaces;
  46. using OpenSim.Region.Framework.Scenes.Scripting;
  47. using OpenSim.Region.Framework.Scenes.Serialization;
  48. using OpenSim.Region.Physics.Manager;
  49. using Timer=System.Timers.Timer;
  50. using TPFlags = OpenSim.Framework.Constants.TeleportFlags;
  51. namespace OpenSim.Region.Framework.Scenes
  52. {
  53. public delegate bool FilterAvatarList(ScenePresence avatar);
  54. public partial class Scene : SceneBase
  55. {
  56. public delegate void SynchronizeSceneHandler(Scene scene);
  57. public SynchronizeSceneHandler SynchronizeScene = null;
  58. /* Used by the loadbalancer plugin on GForge */
  59. protected int m_splitRegionID = 0;
  60. public int SplitRegionID
  61. {
  62. get { return m_splitRegionID; }
  63. set { m_splitRegionID = value; }
  64. }
  65. private const long DEFAULT_MIN_TIME_FOR_PERSISTENCE = 60L;
  66. private const long DEFAULT_MAX_TIME_FOR_PERSISTENCE = 600L;
  67. #region Fields
  68. protected Timer m_restartWaitTimer = new Timer();
  69. protected Thread m_updateEntitiesThread;
  70. public SimStatsReporter StatsReporter;
  71. protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
  72. protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
  73. /// <value>
  74. /// The scene graph for this scene
  75. /// </value>
  76. /// TODO: Possibly stop other classes being able to manipulate this directly.
  77. private SceneGraph m_sceneGraph;
  78. /// <summary>
  79. /// Are we applying physics to any of the prims in this scene?
  80. /// </summary>
  81. public bool m_physicalPrim;
  82. public float m_maxNonphys = 256;
  83. public float m_maxPhys = 10;
  84. public bool m_clampPrimSize = false;
  85. public bool m_trustBinaries = false;
  86. public bool m_allowScriptCrossings = false;
  87. public bool m_useFlySlow = false;
  88. public bool m_usePreJump = false;
  89. public bool m_seeIntoRegionFromNeighbor;
  90. // TODO: need to figure out how allow client agents but deny
  91. // root agents when ACL denies access to root agent
  92. public bool m_strictAccessControl = true;
  93. public int MaxUndoCount = 5;
  94. private int m_RestartTimerCounter;
  95. private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing
  96. private int m_incrementsof15seconds = 0;
  97. private volatile bool m_backingup = false;
  98. private Dictionary<UUID, ReturnInfo> m_returns = new Dictionary<UUID, ReturnInfo>();
  99. protected string m_simulatorVersion = "OpenSimulator Server";
  100. protected ModuleLoader m_moduleLoader;
  101. protected StorageManager m_storageManager;
  102. protected AgentCircuitManager m_authenticateHandler;
  103. public CommunicationsManager CommsManager;
  104. protected SceneCommunicationService m_sceneGridService;
  105. public SceneCommunicationService SceneGridService
  106. {
  107. get { return m_sceneGridService; }
  108. }
  109. public IXfer XferManager;
  110. protected IAssetService m_AssetService = null;
  111. public IAssetService AssetService
  112. {
  113. get
  114. {
  115. if (m_AssetService == null)
  116. {
  117. m_AssetService = RequestModuleInterface<IAssetService>();
  118. if (m_AssetService == null)
  119. {
  120. throw new Exception("No IAssetService available.");
  121. }
  122. }
  123. return m_AssetService;
  124. }
  125. }
  126. protected IInventoryService m_InventoryService = null;
  127. public IInventoryService InventoryService
  128. {
  129. get
  130. {
  131. if (m_InventoryService == null)
  132. {
  133. m_InventoryService = RequestModuleInterface<IInventoryService>();
  134. if (m_InventoryService == null)
  135. {
  136. throw new Exception("No IInventoryService available. This could happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. Please also check that you have the correct version of your inventory service dll. Sometimes old versions of this dll will still exist. Do a clean checkout and re-create the opensim.ini from the opensim.ini.example.");
  137. }
  138. }
  139. return m_InventoryService;
  140. }
  141. }
  142. protected IXMLRPC m_xmlrpcModule;
  143. protected IWorldComm m_worldCommModule;
  144. protected IAvatarFactory m_AvatarFactory;
  145. protected IConfigSource m_config;
  146. protected IRegionSerialiserModule m_serialiser;
  147. protected IInterregionCommsOut m_interregionCommsOut;
  148. protected IInterregionCommsIn m_interregionCommsIn;
  149. protected IDialogModule m_dialogModule;
  150. protected ITeleportModule m_teleportModule;
  151. protected ICapabilitiesModule m_capsModule;
  152. public ICapabilitiesModule CapsModule
  153. {
  154. get { return m_capsModule; }
  155. }
  156. protected override IConfigSource GetConfig()
  157. {
  158. return m_config;
  159. }
  160. // Central Update Loop
  161. protected int m_fps = 10;
  162. protected int m_frame = 0;
  163. protected float m_timespan = 0.089f;
  164. protected DateTime m_lastupdate = DateTime.Now;
  165. private int m_update_physics = 1;
  166. private int m_update_entitymovement = 1;
  167. private int m_update_entities = 1; // Run through all objects checking for updates
  168. private int m_update_entitiesquick = 200; // Run through objects that have scheduled updates checking for updates
  169. private int m_update_presences = 1; // Update scene presence movements
  170. private int m_update_events = 1;
  171. private int m_update_backup = 200;
  172. private int m_update_terrain = 50;
  173. private int m_update_land = 1;
  174. private int frameMS = 0;
  175. private int physicsMS2 = 0;
  176. private int physicsMS = 0;
  177. private int otherMS = 0;
  178. private bool m_physics_enabled = true;
  179. private bool m_scripts_enabled = true;
  180. private string m_defaultScriptEngine;
  181. private int m_LastLogin = 0;
  182. private Thread HeartbeatThread;
  183. private volatile bool shuttingdown = false;
  184. private int m_lastUpdate = Environment.TickCount;
  185. private int m_maxPrimsPerFrame = 200;
  186. private object m_deleting_scene_object = new object();
  187. // the minimum time that must elapse before a changed object will be considered for persisted
  188. public long m_dontPersistBefore = DEFAULT_MIN_TIME_FOR_PERSISTENCE * 10000000L;
  189. // the maximum time that must elapse before a changed object will be considered for persisted
  190. public long m_persistAfter = DEFAULT_MAX_TIME_FOR_PERSISTENCE * 10000000L;
  191. #endregion
  192. #region Properties
  193. public AgentCircuitManager AuthenticateHandler
  194. {
  195. get { return m_authenticateHandler; }
  196. }
  197. public SceneGraph SceneContents
  198. {
  199. get { return m_sceneGraph; }
  200. }
  201. // an instance to the physics plugin's Scene object.
  202. public PhysicsScene PhysicsScene
  203. {
  204. get { return m_sceneGraph.PhysicsScene; }
  205. set
  206. {
  207. // If we're not doing the initial set
  208. // Then we've got to remove the previous
  209. // event handler
  210. if (PhysicsScene != null && PhysicsScene.SupportsNINJAJoints)
  211. {
  212. PhysicsScene.OnJointMoved -= jointMoved;
  213. PhysicsScene.OnJointDeactivated -= jointDeactivated;
  214. PhysicsScene.OnJointErrorMessage -= jointErrorMessage;
  215. }
  216. m_sceneGraph.PhysicsScene = value;
  217. if (PhysicsScene != null && m_sceneGraph.PhysicsScene.SupportsNINJAJoints)
  218. {
  219. // register event handlers to respond to joint movement/deactivation
  220. PhysicsScene.OnJointMoved += jointMoved;
  221. PhysicsScene.OnJointDeactivated += jointDeactivated;
  222. PhysicsScene.OnJointErrorMessage += jointErrorMessage;
  223. }
  224. }
  225. }
  226. // This gets locked so things stay thread safe.
  227. public object SyncRoot
  228. {
  229. get { return m_sceneGraph.m_syncRoot; }
  230. }
  231. public int MaxPrimsPerFrame
  232. {
  233. get { return m_maxPrimsPerFrame; }
  234. set { m_maxPrimsPerFrame = value; }
  235. }
  236. /// <summary>
  237. /// This is for llGetRegionFPS
  238. /// </summary>
  239. public float SimulatorFPS
  240. {
  241. get { return StatsReporter.getLastReportedSimFPS(); }
  242. }
  243. public string DefaultScriptEngine
  244. {
  245. get { return m_defaultScriptEngine; }
  246. }
  247. // Reference to all of the agents in the scene (root and child)
  248. protected Dictionary<UUID, ScenePresence> m_scenePresences
  249. {
  250. get { return m_sceneGraph.ScenePresences; }
  251. set { m_sceneGraph.ScenePresences = value; }
  252. }
  253. public EntityManager Entities
  254. {
  255. get { return m_sceneGraph.Entities; }
  256. }
  257. public Dictionary<UUID, ScenePresence> m_restorePresences
  258. {
  259. get { return m_sceneGraph.RestorePresences; }
  260. set { m_sceneGraph.RestorePresences = value; }
  261. }
  262. public int objectCapacity = 45000;
  263. #endregion
  264. #region Constructors
  265. public Scene(RegionInfo regInfo, AgentCircuitManager authen,
  266. CommunicationsManager commsMan, SceneCommunicationService sceneGridService,
  267. StorageManager storeManager,
  268. ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim,
  269. bool SeeIntoRegionFromNeighbor, IConfigSource config, string simulatorVersion)
  270. {
  271. m_config = config;
  272. Random random = new Random();
  273. m_lastAllocatedLocalId = (uint)(random.NextDouble() * (double)(uint.MaxValue/2))+(uint)(uint.MaxValue/4);
  274. m_moduleLoader = moduleLoader;
  275. m_authenticateHandler = authen;
  276. CommsManager = commsMan;
  277. m_sceneGridService = sceneGridService;
  278. m_storageManager = storeManager;
  279. m_regInfo = regInfo;
  280. m_regionHandle = m_regInfo.RegionHandle;
  281. m_regionName = m_regInfo.RegionName;
  282. m_datastore = m_regInfo.DataStore;
  283. m_physicalPrim = physicalPrim;
  284. m_seeIntoRegionFromNeighbor = SeeIntoRegionFromNeighbor;
  285. m_eventManager = new EventManager();
  286. m_permissions = new ScenePermissions(this);
  287. m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
  288. m_asyncSceneObjectDeleter.Enabled = true;
  289. // Load region settings
  290. m_regInfo.RegionSettings = m_storageManager.DataStore.LoadRegionSettings(m_regInfo.RegionID);
  291. if (m_storageManager.EstateDataStore != null)
  292. {
  293. m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(m_regInfo.RegionID);
  294. }
  295. //Bind Storage Manager functions to some land manager functions for this scene
  296. EventManager.OnLandObjectAdded +=
  297. new EventManager.LandObjectAdded(m_storageManager.DataStore.StoreLandObject);
  298. EventManager.OnLandObjectRemoved +=
  299. new EventManager.LandObjectRemoved(m_storageManager.DataStore.RemoveLandObject);
  300. m_sceneGraph = new SceneGraph(this, m_regInfo);
  301. // If the scene graph has an Unrecoverable error, restart this sim.
  302. // Currently the only thing that causes it to happen is two kinds of specific
  303. // Physics based crashes.
  304. //
  305. // Out of memory
  306. // Operating system has killed the plugin
  307. m_sceneGraph.UnRecoverableError += RestartNow;
  308. RegisterDefaultSceneEvents();
  309. DumpAssetsToFile = dumpAssetsToFile;
  310. m_scripts_enabled = !RegionInfo.RegionSettings.DisableScripts;
  311. m_physics_enabled = !RegionInfo.RegionSettings.DisablePhysics;
  312. StatsReporter = new SimStatsReporter(this);
  313. StatsReporter.OnSendStatsResult += SendSimStatsPackets;
  314. StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;
  315. StatsReporter.SetObjectCapacity(objectCapacity);
  316. m_simulatorVersion = simulatorVersion
  317. + " (OS " + Util.GetOperatingSystemInformation() + ")"
  318. + " ChilTasks:" + m_seeIntoRegionFromNeighbor.ToString()
  319. + " PhysPrim:" + m_physicalPrim.ToString();
  320. try
  321. {
  322. // Region config overrides global config
  323. //
  324. IConfig startupConfig = m_config.Configs["Startup"];
  325. //Animation states
  326. m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
  327. // TODO: Change default to true once the feature is supported
  328. m_usePreJump = startupConfig.GetBoolean("enableprejump", false);
  329. m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", m_maxNonphys);
  330. if (RegionInfo.NonphysPrimMax > 0)
  331. {
  332. m_maxNonphys = RegionInfo.NonphysPrimMax;
  333. }
  334. m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys);
  335. if (RegionInfo.PhysPrimMax > 0)
  336. {
  337. m_maxPhys = RegionInfo.PhysPrimMax;
  338. }
  339. // Here, if clamping is requested in either global or
  340. // local config, it will be used
  341. //
  342. m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize);
  343. if (RegionInfo.ClampPrimSize)
  344. {
  345. m_clampPrimSize = true;
  346. }
  347. m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries);
  348. m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
  349. m_dontPersistBefore =
  350. startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
  351. m_dontPersistBefore *= 10000000;
  352. m_persistAfter =
  353. startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
  354. m_persistAfter *= 10000000;
  355. m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "DotNetEngine");
  356. m_maxPrimsPerFrame = startupConfig.GetInt("MaxPrimsPerFrame", 200);
  357. IConfig packetConfig = m_config.Configs["PacketPool"];
  358. if (packetConfig != null)
  359. {
  360. PacketPool.Instance.RecyclePackets = packetConfig.GetBoolean("RecyclePackets", true);
  361. PacketPool.Instance.RecycleDataBlocks = packetConfig.GetBoolean("RecycleDataBlocks", true);
  362. }
  363. m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl);
  364. }
  365. catch
  366. {
  367. m_log.Warn("[SCENE]: Failed to load StartupConfig");
  368. }
  369. }
  370. /// <summary>
  371. /// Mock constructor for scene group persistency unit tests.
  372. /// SceneObjectGroup RegionId property is delegated to Scene.
  373. /// </summary>
  374. /// <param name="regInfo"></param>
  375. public Scene(RegionInfo regInfo)
  376. {
  377. m_regInfo = regInfo;
  378. m_eventManager = new EventManager();
  379. }
  380. #endregion
  381. #region Startup / Close Methods
  382. public bool ShuttingDown
  383. {
  384. get { return shuttingdown; }
  385. }
  386. /// <value>
  387. /// The scene graph for this scene
  388. /// </value>
  389. /// TODO: Possibly stop other classes being able to manipulate this directly.
  390. public SceneGraph SceneGraph
  391. {
  392. get { return m_sceneGraph; }
  393. }
  394. protected virtual void RegisterDefaultSceneEvents()
  395. {
  396. IDialogModule dm = RequestModuleInterface<IDialogModule>();
  397. if (dm != null)
  398. m_eventManager.OnPermissionError += dm.SendAlertToUser;
  399. }
  400. public override string GetSimulatorVersion()
  401. {
  402. return m_simulatorVersion;
  403. }
  404. /// <summary>
  405. /// Another region is up. Gets called from Grid Comms:
  406. /// (OGS1 -> LocalBackEnd -> RegionListened -> SceneCommunicationService)
  407. /// We have to tell all our ScenePresences about it, and add it to the
  408. /// neighbor list.
  409. ///
  410. /// We only add it to the neighbor list if it's within 1 region from here.
  411. /// Agents may have draw distance values that cross two regions though, so
  412. /// we add it to the notify list regardless of distance. We'll check
  413. /// the agent's draw distance before notifying them though.
  414. /// </summary>
  415. /// <param name="otherRegion">RegionInfo handle for the new region.</param>
  416. /// <returns>True after all operations complete, throws exceptions otherwise.</returns>
  417. public override bool OtherRegionUp(RegionInfo otherRegion)
  418. {
  419. m_log.InfoFormat("[SCENE]: Region {0} up in coords {1}-{2}", otherRegion.RegionName, otherRegion.RegionLocX, otherRegion.RegionLocY);
  420. if (RegionInfo.RegionHandle != otherRegion.RegionHandle)
  421. {
  422. for (int i = 0; i < m_neighbours.Count; i++)
  423. {
  424. // The purpose of this loop is to re-update the known neighbors
  425. // when another region comes up on top of another one.
  426. // The latest region in that location ends up in the
  427. // 'known neighbors list'
  428. // Additionally, the commFailTF property gets reset to false.
  429. if (m_neighbours[i].RegionHandle == otherRegion.RegionHandle)
  430. {
  431. lock (m_neighbours)
  432. {
  433. m_neighbours[i] = otherRegion;
  434. }
  435. }
  436. }
  437. // If the value isn't in the neighbours, add it.
  438. // If the RegionInfo isn't exact but is for the same XY World location,
  439. // then the above loop will fix that.
  440. if (!(CheckNeighborRegion(otherRegion)))
  441. {
  442. lock (m_neighbours)
  443. {
  444. m_neighbours.Add(otherRegion);
  445. //m_log.Info("[UP]: " + otherRegion.RegionHandle.ToString());
  446. }
  447. }
  448. // If these are cast to INT because long + negative values + abs returns invalid data
  449. int resultX = Math.Abs((int)otherRegion.RegionLocX - (int)RegionInfo.RegionLocX);
  450. int resultY = Math.Abs((int)otherRegion.RegionLocY - (int)RegionInfo.RegionLocY);
  451. if (resultX <= 1 && resultY <= 1)
  452. {
  453. try
  454. {
  455. ForEachScenePresence(delegate(ScenePresence agent)
  456. {
  457. // If agent is a root agent.
  458. if (!agent.IsChildAgent)
  459. {
  460. //agent.ControllingClient.new
  461. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  462. List<ulong> old = new List<ulong>();
  463. old.Add(otherRegion.RegionHandle);
  464. agent.DropOldNeighbours(old);
  465. InformClientOfNeighbor(agent, otherRegion);
  466. }
  467. }
  468. );
  469. }
  470. catch (NullReferenceException)
  471. {
  472. // This means that we're not booted up completely yet.
  473. // This shouldn't happen too often anymore.
  474. m_log.Error("[SCENE]: Couldn't inform client of regionup because we got a null reference exception");
  475. }
  476. }
  477. else
  478. {
  479. m_log.Info("[INTERGRID]: Got notice about far away Region: " + otherRegion.RegionName.ToString() +
  480. " at (" + otherRegion.RegionLocX.ToString() + ", " +
  481. otherRegion.RegionLocY.ToString() + ")");
  482. }
  483. }
  484. return true;
  485. }
  486. public void AddNeighborRegion(RegionInfo region)
  487. {
  488. lock (m_neighbours)
  489. {
  490. if (!CheckNeighborRegion(region))
  491. {
  492. m_neighbours.Add(region);
  493. }
  494. }
  495. }
  496. public bool CheckNeighborRegion(RegionInfo region)
  497. {
  498. bool found = false;
  499. lock (m_neighbours)
  500. {
  501. foreach (RegionInfo reg in m_neighbours)
  502. {
  503. if (reg.RegionHandle == region.RegionHandle)
  504. {
  505. found = true;
  506. break;
  507. }
  508. }
  509. }
  510. return found;
  511. }
  512. // Alias IncomingHelloNeighbour OtherRegionUp, for now
  513. public bool IncomingHelloNeighbour(RegionInfo neighbour)
  514. {
  515. return OtherRegionUp(neighbour);
  516. }
  517. /// <summary>
  518. /// Given float seconds, this will restart the region.
  519. /// </summary>
  520. /// <param name="seconds">float indicating duration before restart.</param>
  521. public virtual void Restart(float seconds)
  522. {
  523. // notifications are done in 15 second increments
  524. // so .. if the number of seconds is less then 15 seconds, it's not really a restart request
  525. // It's a 'Cancel restart' request.
  526. // RestartNow() does immediate restarting.
  527. if (seconds < 15)
  528. {
  529. m_restartTimer.Stop();
  530. m_dialogModule.SendGeneralAlert("Restart Aborted");
  531. }
  532. else
  533. {
  534. // Now we figure out what to set the timer to that does the notifications and calls, RestartNow()
  535. m_restartTimer.Interval = 15000;
  536. m_incrementsof15seconds = (int)seconds / 15;
  537. m_RestartTimerCounter = 0;
  538. m_restartTimer.AutoReset = true;
  539. m_restartTimer.Elapsed += new ElapsedEventHandler(RestartTimer_Elapsed);
  540. m_log.Info("[REGION]: Restarting Region in " + (seconds / 60) + " minutes");
  541. m_restartTimer.Start();
  542. m_dialogModule.SendNotificationToUsersInRegion(
  543. UUID.Random(), String.Empty, RegionInfo.RegionName + ": Restarting in 2 Minutes");
  544. }
  545. }
  546. // The Restart timer has occured.
  547. // We have to figure out if this is a notification or if the number of seconds specified in Restart
  548. // have elapsed.
  549. // If they have elapsed, call RestartNow()
  550. public void RestartTimer_Elapsed(object sender, ElapsedEventArgs e)
  551. {
  552. m_RestartTimerCounter++;
  553. if (m_RestartTimerCounter <= m_incrementsof15seconds)
  554. {
  555. if (m_RestartTimerCounter == 4 || m_RestartTimerCounter == 6 || m_RestartTimerCounter == 7)
  556. m_dialogModule.SendNotificationToUsersInRegion(
  557. UUID.Random(),
  558. String.Empty,
  559. RegionInfo.RegionName + ": Restarting in " + ((8 - m_RestartTimerCounter) * 15) + " seconds");
  560. }
  561. else
  562. {
  563. m_restartTimer.Stop();
  564. m_restartTimer.AutoReset = false;
  565. RestartNow();
  566. }
  567. }
  568. // This causes the region to restart immediatley.
  569. public void RestartNow()
  570. {
  571. if (PhysicsScene != null)
  572. {
  573. PhysicsScene.Dispose();
  574. }
  575. m_log.Error("[REGION]: Closing");
  576. Close();
  577. m_log.Error("[REGION]: Firing Region Restart Message");
  578. base.Restart(0);
  579. }
  580. // This is a helper function that notifies root agents in this region that a new sim near them has come up
  581. // This is in the form of a timer because when an instance of OpenSim.exe is started,
  582. // Even though the sims initialize, they don't listen until 'all of the sims are initialized'
  583. // If we tell an agent about a sim that's not listening yet, the agent will not be able to connect to it.
  584. // subsequently the agent will never see the region come back online.
  585. public void RestartNotifyWaitElapsed(object sender, ElapsedEventArgs e)
  586. {
  587. m_restartWaitTimer.Stop();
  588. lock (m_regionRestartNotifyList)
  589. {
  590. foreach (RegionInfo region in m_regionRestartNotifyList)
  591. {
  592. try
  593. {
  594. ForEachScenePresence(delegate(ScenePresence agent)
  595. {
  596. // If agent is a root agent.
  597. if (!agent.IsChildAgent)
  598. {
  599. //agent.ControllingClient.new
  600. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  601. InformClientOfNeighbor(agent, region);
  602. }
  603. }
  604. );
  605. }
  606. catch (NullReferenceException)
  607. {
  608. // This means that we're not booted up completely yet.
  609. // This shouldn't happen too often anymore.
  610. }
  611. }
  612. // Reset list to nothing.
  613. m_regionRestartNotifyList.Clear();
  614. }
  615. }
  616. public void SetSceneCoreDebug(bool ScriptEngine, bool CollisionEvents, bool PhysicsEngine)
  617. {
  618. if (m_scripts_enabled != !ScriptEngine)
  619. {
  620. // Tedd! Here's the method to disable the scripting engine!
  621. if (ScriptEngine)
  622. {
  623. m_log.Info("Stopping all Scripts in Scene");
  624. foreach (EntityBase ent in Entities)
  625. {
  626. if (ent is SceneObjectGroup)
  627. {
  628. ((SceneObjectGroup) ent).RemoveScriptInstances();
  629. }
  630. }
  631. }
  632. else
  633. {
  634. m_log.Info("Starting all Scripts in Scene");
  635. lock (Entities)
  636. {
  637. foreach (EntityBase ent in Entities)
  638. {
  639. if (ent is SceneObjectGroup)
  640. {
  641. ((SceneObjectGroup)ent).CreateScriptInstances(0, false, DefaultScriptEngine, 0);
  642. }
  643. }
  644. }
  645. }
  646. m_scripts_enabled = !ScriptEngine;
  647. m_log.Info("[TOTEDD]: Here is the method to trigger disabling of the scripting engine");
  648. }
  649. if (m_physics_enabled != !PhysicsEngine)
  650. {
  651. m_physics_enabled = !PhysicsEngine;
  652. }
  653. }
  654. public int GetInaccurateNeighborCount()
  655. {
  656. lock (m_neighbours)
  657. {
  658. return m_neighbours.Count;
  659. }
  660. }
  661. // This is the method that shuts down the scene.
  662. public override void Close()
  663. {
  664. m_log.InfoFormat("[SCENE]: Closing down the single simulator: {0}", RegionInfo.RegionName);
  665. // Kick all ROOT agents with the message, 'The simulator is going down'
  666. ForEachScenePresence(delegate(ScenePresence avatar)
  667. {
  668. if (avatar.KnownChildRegionHandles.Contains(RegionInfo.RegionHandle))
  669. avatar.KnownChildRegionHandles.Remove(RegionInfo.RegionHandle);
  670. if (!avatar.IsChildAgent)
  671. avatar.ControllingClient.Kick("The simulator is going down.");
  672. avatar.ControllingClient.SendShutdownConnectionNotice();
  673. });
  674. // Wait here, or the kick messages won't actually get to the agents before the scene terminates.
  675. Thread.Sleep(500);
  676. // Stop all client threads.
  677. ForEachScenePresence(delegate(ScenePresence avatar) { avatar.ControllingClient.Close(true); });
  678. // Stop updating the scene objects and agents.
  679. //m_heartbeatTimer.Close();
  680. shuttingdown = true;
  681. m_log.Debug("[SCENE]: Persisting changed objects");
  682. List<EntityBase> entities = GetEntities();
  683. foreach (EntityBase entity in entities)
  684. {
  685. if (!entity.IsDeleted && entity is SceneObjectGroup && ((SceneObjectGroup)entity).HasGroupChanged)
  686. {
  687. ((SceneObjectGroup)entity).ProcessBackup(m_storageManager.DataStore, false);
  688. }
  689. }
  690. m_sceneGraph.Close();
  691. // De-register with region communications (events cleanup)
  692. UnRegisterRegionWithComms();
  693. // call the base class Close method.
  694. base.Close();
  695. }
  696. /// <summary>
  697. /// Start the timer which triggers regular scene updates
  698. /// </summary>
  699. public void StartTimer()
  700. {
  701. //m_log.Debug("[SCENE]: Starting timer");
  702. //m_heartbeatTimer.Enabled = true;
  703. //m_heartbeatTimer.Interval = (int)(m_timespan * 1000);
  704. //m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat);
  705. HeartbeatThread = new Thread(new ParameterizedThreadStart(Heartbeat));
  706. HeartbeatThread.SetApartmentState(ApartmentState.MTA);
  707. HeartbeatThread.Name = string.Format("Heartbeat for region {0}", RegionInfo.RegionName);
  708. HeartbeatThread.Priority = ThreadPriority.AboveNormal;
  709. ThreadTracker.Add(HeartbeatThread);
  710. HeartbeatThread.Start();
  711. }
  712. /// <summary>
  713. /// Sets up references to modules required by the scene
  714. /// </summary>
  715. public void SetModuleInterfaces()
  716. {
  717. m_xmlrpcModule = RequestModuleInterface<IXMLRPC>();
  718. m_worldCommModule = RequestModuleInterface<IWorldComm>();
  719. XferManager = RequestModuleInterface<IXfer>();
  720. m_AvatarFactory = RequestModuleInterface<IAvatarFactory>();
  721. m_serialiser = RequestModuleInterface<IRegionSerialiserModule>();
  722. m_interregionCommsOut = RequestModuleInterface<IInterregionCommsOut>();
  723. m_interregionCommsIn = RequestModuleInterface<IInterregionCommsIn>();
  724. m_dialogModule = RequestModuleInterface<IDialogModule>();
  725. m_capsModule = RequestModuleInterface<ICapabilitiesModule>();
  726. m_teleportModule = RequestModuleInterface<ITeleportModule>();
  727. }
  728. #endregion
  729. #region Update Methods
  730. /// <summary>
  731. /// Performs per-frame updates regularly
  732. /// </summary>
  733. /// <param name="sender"></param>
  734. /// <param name="e"></param>
  735. private void Heartbeat(object sender)
  736. {
  737. Update();
  738. m_lastUpdate = Environment.TickCount;
  739. }
  740. /// <summary>
  741. /// Performs per-frame updates on the scene, this should be the central scene loop
  742. /// </summary>
  743. public override void Update()
  744. {
  745. int maintc = 0;
  746. while (!shuttingdown)
  747. {
  748. maintc = Environment.TickCount;
  749. TimeSpan SinceLastFrame = DateTime.Now - m_lastupdate;
  750. // Aquire a lock so only one update call happens at once
  751. //updateLock.WaitOne();
  752. float physicsFPS = 0;
  753. //m_log.Info("sadfadf" + m_neighbours.Count.ToString());
  754. int agentsInScene = m_sceneGraph.GetRootAgentCount() + m_sceneGraph.GetChildAgentCount();
  755. if (agentsInScene > 21)
  756. {
  757. if (m_update_entities == 1)
  758. {
  759. m_update_entities = 5;
  760. StatsReporter.SetUpdateMS(6000);
  761. }
  762. }
  763. else
  764. {
  765. if (m_update_entities == 5)
  766. {
  767. m_update_entities = 1;
  768. StatsReporter.SetUpdateMS(3000);
  769. }
  770. }
  771. frameMS = Environment.TickCount;
  772. try
  773. {
  774. // Increment the frame counter
  775. m_frame++;
  776. // Loop it
  777. if (m_frame == Int32.MaxValue)
  778. m_frame = 0;
  779. otherMS = Environment.TickCount;
  780. // run through all entities looking for updates (slow)
  781. if (m_frame % m_update_entities == 0)
  782. {
  783. /* // Adam Experimental
  784. if (m_updateEntitiesThread == null)
  785. {
  786. m_updateEntitiesThread = new Thread(m_sceneGraph.UpdateEntities);
  787. ThreadTracker.Add(m_updateEntitiesThread);
  788. }
  789. if (m_updateEntitiesThread.ThreadState == ThreadState.Stopped)
  790. m_updateEntitiesThread.Start();
  791. */
  792. m_sceneGraph.UpdateEntities();
  793. }
  794. // run through entities that have scheduled themselves for
  795. // updates looking for updates(faster)
  796. if (m_frame % m_update_entitiesquick == 0)
  797. m_sceneGraph.ProcessUpdates();
  798. // Run through scenepresences looking for updates
  799. if (m_frame % m_update_presences == 0)
  800. m_sceneGraph.UpdatePresences();
  801. physicsMS2 = Environment.TickCount;
  802. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  803. m_sceneGraph.UpdatePreparePhysics();
  804. physicsMS2 = Environment.TickCount - physicsMS2;
  805. if (m_frame % m_update_entitymovement == 0)
  806. m_sceneGraph.UpdateEntityMovement();
  807. physicsMS = Environment.TickCount;
  808. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  809. physicsFPS = m_sceneGraph.UpdatePhysics(
  810. Math.Max(SinceLastFrame.TotalSeconds, m_timespan)
  811. );
  812. if (m_frame % m_update_physics == 0 && SynchronizeScene != null)
  813. SynchronizeScene(this);
  814. physicsMS = Environment.TickCount - physicsMS;
  815. physicsMS += physicsMS2;
  816. // Delete temp-on-rez stuff
  817. if (m_frame % m_update_backup == 0)
  818. CleanTempObjects();
  819. if (RegionStatus != RegionStatus.SlaveScene)
  820. {
  821. if (m_frame % m_update_events == 0)
  822. UpdateEvents();
  823. if (m_frame % m_update_backup == 0)
  824. UpdateStorageBackup();
  825. if (m_frame % m_update_terrain == 0)
  826. UpdateTerrain();
  827. if (m_frame % m_update_land == 0)
  828. UpdateLand();
  829. otherMS = Environment.TickCount - otherMS;
  830. // if (m_frame%m_update_avatars == 0)
  831. // UpdateInWorldTime();
  832. StatsReporter.AddPhysicsFPS(physicsFPS);
  833. StatsReporter.AddTimeDilation(m_timedilation);
  834. StatsReporter.AddFPS(1);
  835. StatsReporter.AddInPackets(0);
  836. StatsReporter.SetRootAgents(m_sceneGraph.GetRootAgentCount());
  837. StatsReporter.SetChildAgents(m_sceneGraph.GetChildAgentCount());
  838. StatsReporter.SetObjects(m_sceneGraph.GetTotalObjectsCount());
  839. StatsReporter.SetActiveObjects(m_sceneGraph.GetActiveObjectsCount());
  840. frameMS = Environment.TickCount - frameMS;
  841. StatsReporter.addFrameMS(frameMS);
  842. StatsReporter.addPhysicsMS(physicsMS);
  843. StatsReporter.addOtherMS(otherMS);
  844. StatsReporter.SetActiveScripts(m_sceneGraph.GetActiveScriptsCount());
  845. StatsReporter.addScriptLines(m_sceneGraph.GetScriptLPS());
  846. }
  847. }
  848. catch (NotImplementedException)
  849. {
  850. throw;
  851. }
  852. catch (AccessViolationException e)
  853. {
  854. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  855. }
  856. //catch (NullReferenceException e)
  857. //{
  858. // m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  859. //}
  860. catch (InvalidOperationException e)
  861. {
  862. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  863. }
  864. catch (Exception e)
  865. {
  866. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  867. }
  868. finally
  869. {
  870. //updateLock.ReleaseMutex();
  871. // Get actual time dilation
  872. float tmpval = (m_timespan / (float)SinceLastFrame.TotalSeconds);
  873. // If actual time dilation is greater then one, we're catching up, so subtract
  874. // the amount that's greater then 1 from the time dilation
  875. if (tmpval > 1.0)
  876. {
  877. tmpval = tmpval - (tmpval - 1.0f);
  878. }
  879. m_timedilation = tmpval;
  880. m_lastupdate = DateTime.Now;
  881. }
  882. maintc = Environment.TickCount - maintc;
  883. maintc = (int)(m_timespan * 1000) - maintc;
  884. if ((maintc < (m_timespan * 1000)) && maintc > 0)
  885. Thread.Sleep(maintc);
  886. }
  887. }
  888. private void SendSimStatsPackets(SimStats stats)
  889. {
  890. List<ScenePresence> StatSendAgents = GetScenePresences();
  891. foreach (ScenePresence agent in StatSendAgents)
  892. {
  893. if (!agent.IsChildAgent)
  894. {
  895. agent.ControllingClient.SendSimStats(stats);
  896. }
  897. }
  898. }
  899. private void UpdateLand()
  900. {
  901. if (LandChannel != null)
  902. {
  903. if (LandChannel.IsLandPrimCountTainted())
  904. {
  905. EventManager.TriggerParcelPrimCountUpdate();
  906. }
  907. }
  908. }
  909. private void UpdateTerrain()
  910. {
  911. EventManager.TriggerTerrainTick();
  912. }
  913. private void UpdateStorageBackup()
  914. {
  915. if (!m_backingup)
  916. {
  917. m_backingup = true;
  918. Thread backupthread = new Thread(Backup);
  919. backupthread.Name = "BackupWriter";
  920. backupthread.IsBackground = true;
  921. backupthread.Start();
  922. }
  923. }
  924. private void UpdateEvents()
  925. {
  926. m_eventManager.TriggerOnFrame();
  927. }
  928. /// <summary>
  929. /// Perform delegate action on all clients subscribing to updates from this region.
  930. /// </summary>
  931. /// <returns></returns>
  932. public void Broadcast(Action<IClientAPI> whatToDo)
  933. {
  934. ForEachScenePresence(delegate(ScenePresence presence) { whatToDo(presence.ControllingClient); });
  935. }
  936. /// <summary>
  937. /// Backup the scene. This acts as the main method of the backup thread.
  938. /// </summary>
  939. /// <returns></returns>
  940. public void Backup()
  941. {
  942. lock (m_returns)
  943. {
  944. EventManager.TriggerOnBackup(m_storageManager.DataStore);
  945. m_backingup = false;
  946. foreach (KeyValuePair<UUID, ReturnInfo> ret in m_returns)
  947. {
  948. UUID transaction = UUID.Random();
  949. GridInstantMessage msg = new GridInstantMessage();
  950. msg.fromAgentID = new Guid(UUID.Zero.ToString()); // From server
  951. msg.toAgentID = new Guid(ret.Key.ToString());
  952. msg.imSessionID = new Guid(transaction.ToString());
  953. msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
  954. msg.fromAgentName = "Server";
  955. msg.dialog = (byte)19; // Object msg
  956. msg.fromGroup = false;
  957. msg.offline = (byte)1;
  958. msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID;
  959. msg.Position = Vector3.Zero;
  960. msg.RegionID = RegionInfo.RegionID.Guid;
  961. msg.binaryBucket = new byte[0];
  962. if (ret.Value.count > 1)
  963. msg.message = string.Format("Your {0} objects were returned from {1} in region {2} due to {3}", ret.Value.count, ret.Value.location.ToString(), RegionInfo.RegionName, ret.Value.reason);
  964. else
  965. msg.message = string.Format("Your object {0} was returned from {1} in region {2} due to {3}", ret.Value.objectName, ret.Value.location.ToString(), RegionInfo.RegionName, ret.Value.reason);
  966. IMessageTransferModule tr = RequestModuleInterface<IMessageTransferModule>();
  967. if (tr != null)
  968. tr.SendInstantMessage(msg, delegate(bool success) {});
  969. }
  970. m_returns.Clear();
  971. }
  972. }
  973. public void ForceSceneObjectBackup(SceneObjectGroup group)
  974. {
  975. if (group != null)
  976. {
  977. group.ProcessBackup(m_storageManager.DataStore, true);
  978. }
  979. }
  980. public void AddReturn(UUID agentID, string objectName, Vector3 location, string reason)
  981. {
  982. lock (m_returns)
  983. {
  984. if (m_returns.ContainsKey(agentID))
  985. {
  986. ReturnInfo info = m_returns[agentID];
  987. info.count++;
  988. m_returns[agentID] = info;
  989. }
  990. else
  991. {
  992. ReturnInfo info = new ReturnInfo();
  993. info.count = 1;
  994. info.objectName = objectName;
  995. info.location = location;
  996. info.reason = reason;
  997. m_returns[agentID] = info;
  998. }
  999. }
  1000. }
  1001. #endregion
  1002. #region Load Terrain
  1003. public void SaveTerrain()
  1004. {
  1005. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  1006. }
  1007. /// <summary>
  1008. /// Loads the World heightmap
  1009. /// </summary>
  1010. public override void LoadWorldMap()
  1011. {
  1012. try
  1013. {
  1014. double[,] map = m_storageManager.DataStore.LoadTerrain(RegionInfo.RegionID);
  1015. if (map == null)
  1016. {
  1017. m_log.Info("[TERRAIN]: No default terrain. Generating a new terrain.");
  1018. Heightmap = new TerrainChannel();
  1019. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  1020. }
  1021. else
  1022. {
  1023. Heightmap = new TerrainChannel(map);
  1024. }
  1025. }
  1026. catch (Exception e)
  1027. {
  1028. m_log.Warn("[TERRAIN]: Scene.cs: LoadWorldMap() - Failed with exception " + e.ToString());
  1029. }
  1030. }
  1031. /// <summary>
  1032. /// Register this region with a grid service
  1033. /// </summary>
  1034. /// <exception cref="System.Exception">Thrown if registration of the region itself fails.</exception>
  1035. public void RegisterRegionWithGrid()
  1036. {
  1037. RegisterCommsEvents();
  1038. // These two 'commands' *must be* next to each other or sim rebooting fails.
  1039. m_sceneGridService.RegisterRegion(m_interregionCommsOut, RegionInfo);
  1040. m_sceneGridService.InformNeighborsThatRegionisUp(RequestModuleInterface<INeighbourService>(), RegionInfo);
  1041. Dictionary<string, string> dGridSettings = m_sceneGridService.GetGridSettings();
  1042. if (dGridSettings.ContainsKey("allow_forceful_banlines"))
  1043. {
  1044. if (dGridSettings["allow_forceful_banlines"] != "TRUE")
  1045. {
  1046. m_log.Info("[GRID]: Grid is disabling forceful parcel banlists");
  1047. EventManager.TriggerSetAllowForcefulBan(false);
  1048. }
  1049. else
  1050. {
  1051. m_log.Info("[GRID]: Grid is allowing forceful parcel banlists");
  1052. EventManager.TriggerSetAllowForcefulBan(true);
  1053. }
  1054. }
  1055. }
  1056. /// <summary>
  1057. /// Create a terrain texture for this scene
  1058. /// </summary>
  1059. public void CreateTerrainTexture(bool temporary)
  1060. {
  1061. //create a texture asset of the terrain
  1062. IMapImageGenerator terrain = RequestModuleInterface<IMapImageGenerator>();
  1063. // Cannot create a map for a nonexistant heightmap yet.
  1064. if (Heightmap == null)
  1065. return;
  1066. if (terrain == null)
  1067. return;
  1068. byte[] data = terrain.WriteJpeg2000Image("defaultstripe.png");
  1069. if (data != null)
  1070. {
  1071. IWorldMapModule mapModule = RequestModuleInterface<IWorldMapModule>();
  1072. if (mapModule != null)
  1073. mapModule.LazySaveGeneratedMaptile(data, temporary);
  1074. }
  1075. }
  1076. #endregion
  1077. #region Load Land
  1078. public void loadAllLandObjectsFromStorage(UUID regionID)
  1079. {
  1080. m_log.Info("[SCENE]: Loading land objects from storage");
  1081. List<LandData> landData = m_storageManager.DataStore.LoadLandObjects(regionID);
  1082. if (LandChannel != null)
  1083. {
  1084. if (landData.Count == 0)
  1085. {
  1086. EventManager.TriggerNoticeNoLandDataFromStorage();
  1087. }
  1088. else
  1089. {
  1090. EventManager.TriggerIncomingLandDataFromStorage(landData);
  1091. }
  1092. }
  1093. else
  1094. {
  1095. m_log.Error("[SCENE]: Land Channel is not defined. Cannot load from storage!");
  1096. }
  1097. }
  1098. #endregion
  1099. #region Primitives Methods
  1100. /// <summary>
  1101. /// Loads the World's objects
  1102. /// </summary>
  1103. public virtual void LoadPrimsFromStorage(UUID regionID)
  1104. {
  1105. m_log.Info("[SCENE]: Loading objects from datastore");
  1106. List<SceneObjectGroup> PrimsFromDB = m_storageManager.DataStore.LoadObjects(regionID);
  1107. foreach (SceneObjectGroup group in PrimsFromDB)
  1108. {
  1109. if (group.RootPart == null)
  1110. {
  1111. m_log.ErrorFormat("[SCENE] Found a SceneObjectGroup with m_rootPart == null and {0} children",
  1112. group.Children == null ? 0 : group.Children.Count);
  1113. }
  1114. AddRestoredSceneObject(group, true, true);
  1115. SceneObjectPart rootPart = group.GetChildPart(group.UUID);
  1116. rootPart.ObjectFlags &= ~(uint)PrimFlags.Scripted;
  1117. rootPart.TrimPermissions();
  1118. group.CheckSculptAndLoad();
  1119. //rootPart.DoPhysicsPropertyUpdate(UsePhysics, true);
  1120. }
  1121. m_log.Info("[SCENE]: Loaded " + PrimsFromDB.Count.ToString() + " SceneObject(s)");
  1122. }
  1123. public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter)
  1124. {
  1125. Vector3 pos = Vector3.Zero;
  1126. if (RayEndIsIntersection == (byte)1)
  1127. {
  1128. pos = RayEnd;
  1129. return pos;
  1130. }
  1131. if (RayTargetID != UUID.Zero)
  1132. {
  1133. SceneObjectPart target = GetSceneObjectPart(RayTargetID);
  1134. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  1135. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  1136. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  1137. if (target != null)
  1138. {
  1139. pos = target.AbsolutePosition;
  1140. //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());
  1141. // TODO: Raytrace better here
  1142. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  1143. Ray NewRay = new Ray(AXOrigin, AXdirection);
  1144. // Ray Trace against target here
  1145. EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter);
  1146. // Un-comment out the following line to Get Raytrace results printed to the console.
  1147. // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1148. float ScaleOffset = 0.5f;
  1149. // If we hit something
  1150. if (ei.HitTF)
  1151. {
  1152. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  1153. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  1154. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  1155. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  1156. ScaleOffset = Math.Abs(ScaleOffset);
  1157. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  1158. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  1159. // Set the position to the intersection point
  1160. Vector3 offset = (normal * (ScaleOffset / 2f));
  1161. pos = (intersectionpoint + offset);
  1162. //Seems to make no sense to do this as this call is used for rezzing from inventory as well, and with inventory items their size is not always 0.5f
  1163. //And in cases when we weren't rezzing from inventory we were re-adding the 0.25 straight after calling this method
  1164. // Un-offset the prim (it gets offset later by the consumer method)
  1165. //pos.Z -= 0.25F;
  1166. }
  1167. return pos;
  1168. }
  1169. else
  1170. {
  1171. // We don't have a target here, so we're going to raytrace all the objects in the scene.
  1172. EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false);
  1173. // Un-comment the following line to print the raytrace results to the console.
  1174. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1175. if (ei.HitTF)
  1176. {
  1177. pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  1178. } else
  1179. {
  1180. // fall back to our stupid functionality
  1181. pos = RayEnd;
  1182. }
  1183. return pos;
  1184. }
  1185. }
  1186. else
  1187. {
  1188. // fall back to our stupid functionality
  1189. pos = RayEnd;
  1190. //increase height so its above the ground.
  1191. //should be getting the normal of the ground at the rez point and using that?
  1192. pos.Z += scale.Z / 2f;
  1193. return pos;
  1194. }
  1195. }
  1196. public virtual void AddNewPrim(UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot, PrimitiveBaseShape shape,
  1197. byte bypassRaycast, Vector3 RayStart, UUID RayTargetID,
  1198. byte RayEndIsIntersection)
  1199. {
  1200. Vector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection, true, new Vector3(0.5f, 0.5f, 0.5f), false);
  1201. if (Permissions.CanRezObject(1, ownerID, pos))
  1202. {
  1203. // rez ON the ground, not IN the ground
  1204. // pos.Z += 0.25F; The rez point should now be correct so that its not in the ground
  1205. AddNewPrim(ownerID, groupID, pos, rot, shape);
  1206. }
  1207. }
  1208. public virtual SceneObjectGroup AddNewPrim(
  1209. UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
  1210. {
  1211. //m_log.DebugFormat(
  1212. // "[SCENE]: Scene.AddNewPrim() pcode {0} called for {1} in {2}", shape.PCode, ownerID, RegionInfo.RegionName);
  1213. // If an entity creator has been registered for this prim type then use that
  1214. if (m_entityCreators.ContainsKey((PCode)shape.PCode))
  1215. return m_entityCreators[(PCode)shape.PCode].CreateEntity(ownerID, groupID, pos, rot, shape);
  1216. // Otherwise, use this default creation code;
  1217. SceneObjectGroup sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
  1218. AddNewSceneObject(sceneObject, true);
  1219. sceneObject.SetGroup(groupID, null);
  1220. return sceneObject;
  1221. }
  1222. /// <summary>
  1223. /// Add an object into the scene that has come from storage
  1224. /// </summary>
  1225. ///
  1226. /// <param name="sceneObject"></param>
  1227. /// <param name="attachToBackup">
  1228. /// If true, changes to the object will be reflected in its persisted data
  1229. /// If false, the persisted data will not be changed even if the object in the scene is changed
  1230. /// </param>
  1231. /// <param name="alreadyPersisted">
  1232. /// If true, we won't persist this object until it changes
  1233. /// If false, we'll persist this object immediately
  1234. /// </param>
  1235. /// <returns>
  1236. /// true if the object was added, false if an object with the same uuid was already in the scene
  1237. /// </returns>
  1238. public bool AddRestoredSceneObject(
  1239. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted)
  1240. {
  1241. return m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted);
  1242. }
  1243. /// <summary>
  1244. /// Add a newly created object to the scene
  1245. /// </summary>
  1246. /// <param name="sceneObject"></param>
  1247. /// <param name="attachToBackup">
  1248. /// If true, the object is made persistent into the scene.
  1249. /// If false, the object will not persist over server restarts
  1250. /// </param>
  1251. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup)
  1252. {
  1253. return m_sceneGraph.AddNewSceneObject(sceneObject, attachToBackup);
  1254. }
  1255. /// <summary>
  1256. /// Delete every object from the scene
  1257. /// </summary>
  1258. public void DeleteAllSceneObjects()
  1259. {
  1260. lock (Entities)
  1261. {
  1262. ICollection<EntityBase> entities = new List<EntityBase>(Entities);
  1263. foreach (EntityBase e in entities)
  1264. {
  1265. if (e is SceneObjectGroup)
  1266. DeleteSceneObject((SceneObjectGroup)e, false);
  1267. }
  1268. }
  1269. }
  1270. /// <summary>
  1271. /// Synchronously delete the given object from the scene.
  1272. /// </summary>
  1273. /// <param name="group">Object Id</param>
  1274. /// <param name="silent">Suppress broadcasting changes to other clients.</param>
  1275. public void DeleteSceneObject(SceneObjectGroup group, bool silent)
  1276. {
  1277. //SceneObjectPart rootPart = group.GetChildPart(group.UUID);
  1278. // Serialise calls to RemoveScriptInstances to avoid
  1279. // deadlocking on m_parts inside SceneObjectGroup
  1280. lock (m_deleting_scene_object)
  1281. {
  1282. group.RemoveScriptInstances();
  1283. }
  1284. foreach (SceneObjectPart part in group.Children.Values)
  1285. {
  1286. if (part.IsJoint() && ((part.ObjectFlags&(uint)PrimFlags.Physics) != 0))
  1287. {
  1288. PhysicsScene.RequestJointDeletion(part.Name); // FIXME: what if the name changed?
  1289. }
  1290. else if (part.PhysActor != null)
  1291. {
  1292. PhysicsScene.RemovePrim(part.PhysActor);
  1293. part.PhysActor = null;
  1294. }
  1295. }
  1296. // if (rootPart.PhysActor != null)
  1297. // {
  1298. // PhysicsScene.RemovePrim(rootPart.PhysActor);
  1299. // rootPart.PhysActor = null;
  1300. // }
  1301. if (UnlinkSceneObject(group.UUID, false))
  1302. {
  1303. EventManager.TriggerObjectBeingRemovedFromScene(group);
  1304. EventManager.TriggerParcelPrimCountTainted();
  1305. }
  1306. group.DeleteGroup(silent);
  1307. }
  1308. /// <summary>
  1309. /// Unlink the given object from the scene. Unlike delete, this just removes the record of the object - the
  1310. /// object itself is not destroyed.
  1311. /// </summary>
  1312. /// <param name="uuid">Id of object.</param>
  1313. /// <returns>true if the object was in the scene, false if it was not</returns>
  1314. /// <param name="softDelete">If true, only deletes from scene, but keeps object in database.</param>
  1315. public bool UnlinkSceneObject(UUID uuid, bool softDelete)
  1316. {
  1317. if (m_sceneGraph.DeleteSceneObject(uuid, softDelete))
  1318. {
  1319. if (!softDelete)
  1320. {
  1321. m_storageManager.DataStore.RemoveObject(uuid,
  1322. m_regInfo.RegionID);
  1323. }
  1324. return true;
  1325. }
  1326. return false;
  1327. }
  1328. /// <summary>
  1329. /// Move the given scene object into a new region depending on which region its absolute position has moved
  1330. /// into.
  1331. ///
  1332. /// This method locates the new region handle and offsets the prim position for the new region
  1333. /// </summary>
  1334. /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
  1335. /// <param name="grp">the scene object that we're crossing</param>
  1336. public void CrossPrimGroupIntoNewRegion(Vector3 attemptedPosition, SceneObjectGroup grp, bool silent)
  1337. {
  1338. if (grp == null)
  1339. return;
  1340. if (grp.IsDeleted)
  1341. return;
  1342. if (grp.RootPart.DIE_AT_EDGE)
  1343. {
  1344. // We remove the object here
  1345. try
  1346. {
  1347. DeleteSceneObject(grp, false);
  1348. }
  1349. catch (Exception)
  1350. {
  1351. m_log.Warn("[DATABASE]: exception when trying to remove the prim that crossed the border.");
  1352. }
  1353. return;
  1354. }
  1355. int thisx = (int)RegionInfo.RegionLocX;
  1356. int thisy = (int)RegionInfo.RegionLocY;
  1357. ulong newRegionHandle = 0;
  1358. Vector3 pos = attemptedPosition;
  1359. if (attemptedPosition.X > Constants.RegionSize + 0.1f)
  1360. {
  1361. pos.X = ((pos.X - Constants.RegionSize));
  1362. newRegionHandle
  1363. = Util.UIntsToLong((uint)((thisx + 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize));
  1364. // x + 1
  1365. }
  1366. else if (attemptedPosition.X < -0.1f)
  1367. {
  1368. pos.X = ((pos.X + Constants.RegionSize));
  1369. newRegionHandle
  1370. = Util.UIntsToLong((uint)((thisx - 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize));
  1371. // x - 1
  1372. }
  1373. if (attemptedPosition.Y > Constants.RegionSize + 0.1f)
  1374. {
  1375. pos.Y = ((pos.Y - Constants.RegionSize));
  1376. newRegionHandle
  1377. = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy + 1) * Constants.RegionSize));
  1378. // y + 1
  1379. }
  1380. else if (attemptedPosition.Y < -0.1f)
  1381. {
  1382. pos.Y = ((pos.Y + Constants.RegionSize));
  1383. newRegionHandle
  1384. = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy - 1) * Constants.RegionSize));
  1385. // y - 1
  1386. }
  1387. // Offset the positions for the new region across the border
  1388. Vector3 oldGroupPosition = grp.RootPart.GroupPosition;
  1389. grp.OffsetForNewRegion(pos);
  1390. // If we fail to cross the border, then reset the position of the scene object on that border.
  1391. if (!CrossPrimGroupIntoNewRegion(newRegionHandle, grp, silent))
  1392. {
  1393. grp.OffsetForNewRegion(oldGroupPosition);
  1394. grp.ScheduleGroupForFullUpdate();
  1395. }
  1396. }
  1397. /// <summary>
  1398. /// Move the given scene object into a new region
  1399. /// </summary>
  1400. /// <param name="newRegionHandle"></param>
  1401. /// <param name="grp">Scene Object Group that we're crossing</param>
  1402. /// <returns>
  1403. /// true if the crossing itself was successful, false on failure
  1404. /// FIMXE: we still return true if the crossing object was not successfully deleted from the originating region
  1405. /// </returns>
  1406. public bool CrossPrimGroupIntoNewRegion(ulong newRegionHandle, SceneObjectGroup grp, bool silent)
  1407. {
  1408. //m_log.Debug(" >>> CrossPrimGroupIntoNewRegion <<<");
  1409. bool successYN = false;
  1410. grp.RootPart.UpdateFlag = 0;
  1411. //int primcrossingXMLmethod = 0;
  1412. if (newRegionHandle != 0)
  1413. {
  1414. //string objectState = grp.GetStateSnapshot();
  1415. //successYN
  1416. // = m_sceneGridService.PrimCrossToNeighboringRegion(
  1417. // newRegionHandle, grp.UUID, m_serialiser.SaveGroupToXml2(grp), primcrossingXMLmethod);
  1418. //if (successYN && (objectState != "") && m_allowScriptCrossings)
  1419. //{
  1420. // successYN = m_sceneGridService.PrimCrossToNeighboringRegion(
  1421. // newRegionHandle, grp.UUID, objectState, 100);
  1422. //}
  1423. // And the new channel...
  1424. if (m_interregionCommsOut != null)
  1425. successYN = m_interregionCommsOut.SendCreateObject(newRegionHandle, grp, true);
  1426. if (successYN)
  1427. {
  1428. // We remove the object here
  1429. try
  1430. {
  1431. DeleteSceneObject(grp, silent);
  1432. }
  1433. catch (Exception e)
  1434. {
  1435. m_log.ErrorFormat(
  1436. "[INTERREGION]: Exception deleting the old object left behind on a border crossing for {0}, {1}",
  1437. grp, e);
  1438. }
  1439. }
  1440. else
  1441. {
  1442. if (!grp.IsDeleted)
  1443. {
  1444. if (grp.RootPart.PhysActor != null)
  1445. {
  1446. grp.RootPart.PhysActor.CrossingFailure();
  1447. }
  1448. }
  1449. m_log.ErrorFormat("[INTERREGION]: Prim crossing failed for {0}", grp);
  1450. }
  1451. }
  1452. else
  1453. {
  1454. m_log.Error("[INTERREGION]: region handle was unexpectedly 0 in Scene.CrossPrimGroupIntoNewRegion()");
  1455. }
  1456. return successYN;
  1457. }
  1458. /// <summary>
  1459. /// Handle a scene object that is crossing into this region from another.
  1460. /// NOTE: Unused as of 2009-02-09. Soon to be deleted.
  1461. /// </summary>
  1462. /// <param name="regionHandle"></param>
  1463. /// <param name="primID"></param>
  1464. /// <param name="objXMLData"></param>
  1465. /// <param name="XMLMethod"></param>
  1466. /// <returns></returns>
  1467. public bool IncomingInterRegionPrimGroup(UUID primID, string objXMLData, int XMLMethod)
  1468. {
  1469. if (XMLMethod == 0)
  1470. {
  1471. m_log.DebugFormat("[INTERREGION]: A new prim {0} arrived from a neighbor", primID);
  1472. SceneObjectGroup sceneObject = m_serialiser.DeserializeGroupFromXml2(objXMLData);
  1473. if (sceneObject.IsAttachment)
  1474. sceneObject.RootPart.ObjectFlags |= (uint)PrimFlags.Phantom;
  1475. return AddSceneObject(sceneObject);
  1476. }
  1477. else if ((XMLMethod == 100) && m_allowScriptCrossings)
  1478. {
  1479. m_log.Warn("[INTERREGION]: Prim state data arrived from a neighbor");
  1480. XmlDocument doc = new XmlDocument();
  1481. doc.LoadXml(objXMLData);
  1482. XmlNodeList rootL = doc.GetElementsByTagName("ScriptData");
  1483. if (rootL.Count == 1)
  1484. {
  1485. XmlNode rootNode = rootL[0];
  1486. if (rootNode != null)
  1487. {
  1488. XmlNodeList partL = rootNode.ChildNodes;
  1489. foreach (XmlNode part in partL)
  1490. {
  1491. XmlNodeList nodeL = part.ChildNodes;
  1492. switch (part.Name)
  1493. {
  1494. case "Assemblies":
  1495. foreach (XmlNode asm in nodeL)
  1496. {
  1497. string fn = asm.Attributes.GetNamedItem("Filename").Value;
  1498. Byte[] filedata = Convert.FromBase64String(asm.InnerText);
  1499. string path = Path.Combine("ScriptEngines", RegionInfo.RegionID.ToString());
  1500. path = Path.Combine(path, fn);
  1501. if (!File.Exists(path))
  1502. {
  1503. FileStream fs = File.Create(path);
  1504. fs.Write(filedata, 0, filedata.Length);
  1505. fs.Close();
  1506. }
  1507. }
  1508. break;
  1509. case "ScriptStates":
  1510. foreach (XmlNode st in nodeL)
  1511. {
  1512. string id = st.Attributes.GetNamedItem("UUID").Value;
  1513. UUID uuid = new UUID(id);
  1514. XmlNode state = st.ChildNodes[0];
  1515. XmlDocument sdoc = new XmlDocument();
  1516. XmlNode sxmlnode = sdoc.CreateNode(
  1517. XmlNodeType.XmlDeclaration,
  1518. "", "");
  1519. sdoc.AppendChild(sxmlnode);
  1520. XmlNode newnode = sdoc.ImportNode(state, true);
  1521. sdoc.AppendChild(newnode);
  1522. string spath = Path.Combine("ScriptEngines", RegionInfo.RegionID.ToString());
  1523. spath = Path.Combine(spath, uuid.ToString());
  1524. FileStream sfs = File.Create(spath + ".state");
  1525. ASCIIEncoding enc = new ASCIIEncoding();
  1526. Byte[] buf = enc.GetBytes(sdoc.InnerXml);
  1527. sfs.Write(buf, 0, buf.Length);
  1528. sfs.Close();
  1529. }
  1530. break;
  1531. }
  1532. }
  1533. }
  1534. }
  1535. SceneObjectPart RootPrim = GetSceneObjectPart(primID);
  1536. RootPrim.ParentGroup.CreateScriptInstances(0, false, DefaultScriptEngine, 1);
  1537. return true;
  1538. }
  1539. return true;
  1540. }
  1541. public bool IncomingCreateObject(ISceneObject sog)
  1542. {
  1543. //m_log.Debug(" >>> IncomingCreateObject <<< " + ((SceneObjectGroup)sog).AbsolutePosition + " deleted? " + ((SceneObjectGroup)sog).IsDeleted);
  1544. SceneObjectGroup newObject;
  1545. try
  1546. {
  1547. newObject = (SceneObjectGroup)sog;
  1548. }
  1549. catch (Exception e)
  1550. {
  1551. m_log.WarnFormat("[SCENE]: Problem casting object: {0}", e.Message);
  1552. return false;
  1553. }
  1554. if (!AddSceneObject(newObject))
  1555. {
  1556. m_log.DebugFormat("[SCENE]: Problem adding scene object {0} in {1} ", sog.UUID, RegionInfo.RegionName);
  1557. return false;
  1558. }
  1559. newObject.RootPart.ParentGroup.CreateScriptInstances(0, false, DefaultScriptEngine, 1);
  1560. return true;
  1561. }
  1562. public virtual bool IncomingCreateObject(UUID userID, UUID itemID)
  1563. {
  1564. ScenePresence sp = GetScenePresence(userID);
  1565. if (sp != null)
  1566. {
  1567. uint attPt = (uint)sp.Appearance.GetAttachpoint(itemID);
  1568. m_sceneGraph.RezSingleAttachment(sp.ControllingClient, itemID, attPt);
  1569. }
  1570. return false;
  1571. }
  1572. public bool AddSceneObject(SceneObjectGroup sceneObject)
  1573. {
  1574. // If the user is banned, we won't let any of their objects
  1575. // enter. Period.
  1576. //
  1577. if (m_regInfo.EstateSettings.IsBanned(sceneObject.OwnerID))
  1578. {
  1579. m_log.Info("[INTERREGION]: Denied prim crossing for " +
  1580. "banned avatar");
  1581. return false;
  1582. }
  1583. // Force allocation of new LocalId
  1584. //
  1585. foreach (SceneObjectPart p in sceneObject.Children.Values)
  1586. p.LocalId = 0;
  1587. if (sceneObject.RootPart.Shape.PCode == (byte)PCode.Prim)
  1588. {
  1589. if (sceneObject.RootPart.Shape.State != 0) // Attachment
  1590. {
  1591. sceneObject.RootPart.AddFlag(PrimFlags.TemporaryOnRez);
  1592. sceneObject.RootPart.AddFlag(PrimFlags.Phantom);
  1593. AddRestoredSceneObject(sceneObject, false, false);
  1594. // Handle attachment special case
  1595. SceneObjectPart RootPrim = sceneObject.RootPart;
  1596. // Fix up attachment Parent Local ID
  1597. ScenePresence sp = GetScenePresence(sceneObject.OwnerID);
  1598. //uint parentLocalID = 0;
  1599. if (sp != null)
  1600. {
  1601. //parentLocalID = sp.LocalId;
  1602. //sceneObject.RootPart.IsAttachment = true;
  1603. //sceneObject.RootPart.SetParentLocalId(parentLocalID);
  1604. SceneObjectGroup grp = sceneObject;
  1605. //RootPrim.SetParentLocalId(parentLocalID);
  1606. m_log.DebugFormat("[ATTACHMENT]: Received " +
  1607. "attachment {0}, inworld asset id {1}",
  1608. //grp.RootPart.LastOwnerID.ToString(),
  1609. grp.GetFromAssetID(),
  1610. grp.UUID.ToString());
  1611. //grp.SetFromAssetID(grp.RootPart.LastOwnerID);
  1612. m_log.DebugFormat("[ATTACHMENT]: Attach " +
  1613. "to avatar {0} at position {1}",
  1614. sp.UUID.ToString(), grp.AbsolutePosition);
  1615. AttachObject(sp.ControllingClient,
  1616. grp.LocalId, (uint)0,
  1617. grp.GroupRotation,
  1618. grp.AbsolutePosition, false);
  1619. RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  1620. grp.SendGroupFullUpdate();
  1621. }
  1622. else
  1623. {
  1624. RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  1625. RootPrim.AddFlag(PrimFlags.TemporaryOnRez);
  1626. }
  1627. }
  1628. else
  1629. {
  1630. AddRestoredSceneObject(sceneObject, true, false);
  1631. if (!Permissions.CanObjectEntry(sceneObject.UUID,
  1632. true, sceneObject.AbsolutePosition))
  1633. {
  1634. // Deny non attachments based on parcel settings
  1635. //
  1636. m_log.Info("[INTERREGION]: Denied prim crossing " +
  1637. "because of parcel settings");
  1638. DeleteSceneObject(sceneObject, false);
  1639. return false;
  1640. }
  1641. }
  1642. }
  1643. return true;
  1644. }
  1645. #endregion
  1646. #region Add/Remove Avatar Methods
  1647. public override void AddNewClient(IClientAPI client)
  1648. {
  1649. SubscribeToClientEvents(client);
  1650. ScenePresence presence;
  1651. if (m_restorePresences.ContainsKey(client.AgentId))
  1652. {
  1653. m_log.DebugFormat("[SCENE]: Restoring agent {0} {1} in {2}", client.Name, client.AgentId, RegionInfo.RegionName);
  1654. presence = m_restorePresences[client.AgentId];
  1655. m_restorePresences.Remove(client.AgentId);
  1656. // This is one of two paths to create avatars that are
  1657. // used. This tends to get called more in standalone
  1658. // than grid, not really sure why, but as such needs
  1659. // an explicity appearance lookup here.
  1660. AvatarAppearance appearance = null;
  1661. GetAvatarAppearance(client, out appearance);
  1662. presence.Appearance = appearance;
  1663. presence.initializeScenePresence(client, RegionInfo, this);
  1664. m_sceneGraph.AddScenePresence(presence);
  1665. lock (m_restorePresences)
  1666. {
  1667. Monitor.PulseAll(m_restorePresences);
  1668. }
  1669. }
  1670. else
  1671. {
  1672. m_log.DebugFormat(
  1673. "[SCENE]: Adding new child agent for {0} in {1}",
  1674. client.Name, RegionInfo.RegionName);
  1675. CommsManager.UserProfileCacheService.AddNewUser(client.AgentId);
  1676. CreateAndAddScenePresence(client);
  1677. }
  1678. m_LastLogin = Environment.TickCount;
  1679. EventManager.TriggerOnNewClient(client);
  1680. }
  1681. protected virtual void SubscribeToClientEvents(IClientAPI client)
  1682. {
  1683. client.OnRegionHandShakeReply += SendLayerData;
  1684. client.OnAddPrim += AddNewPrim;
  1685. client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimPosition;
  1686. client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition;
  1687. client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimRotation;
  1688. client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimRotation;
  1689. client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation;
  1690. client.OnUpdatePrimSingleRotationPosition += m_sceneGraph.UpdatePrimSingleRotationPosition;
  1691. client.OnUpdatePrimScale += m_sceneGraph.UpdatePrimScale;
  1692. client.OnUpdatePrimGroupScale += m_sceneGraph.UpdatePrimGroupScale;
  1693. client.OnUpdateExtraParams += m_sceneGraph.UpdateExtraParam;
  1694. client.OnUpdatePrimShape += m_sceneGraph.UpdatePrimShape;
  1695. client.OnUpdatePrimTexture += m_sceneGraph.UpdatePrimTexture;
  1696. client.OnTeleportLocationRequest += RequestTeleportLocation;
  1697. client.OnTeleportLandmarkRequest += RequestTeleportLandmark;
  1698. client.OnObjectSelect += SelectPrim;
  1699. client.OnObjectDeselect += DeselectPrim;
  1700. client.OnGrabUpdate += m_sceneGraph.MoveObject;
  1701. client.OnSpinStart += m_sceneGraph.SpinStart;
  1702. client.OnSpinUpdate += m_sceneGraph.SpinObject;
  1703. client.OnDeRezObject += DeRezObject;
  1704. client.OnRezObject += RezObject;
  1705. client.OnRezSingleAttachmentFromInv += RezSingleAttachment;
  1706. client.OnRezMultipleAttachmentsFromInv += RezMultipleAttachments;
  1707. client.OnDetachAttachmentIntoInv += DetachSingleAttachmentToInv;
  1708. client.OnObjectAttach += m_sceneGraph.AttachObject;
  1709. client.OnObjectDetach += m_sceneGraph.DetachObject;
  1710. client.OnObjectDrop += m_sceneGraph.DropObject;
  1711. client.OnNameFromUUIDRequest += CommsManager.HandleUUIDNameRequest;
  1712. client.OnObjectDescription += m_sceneGraph.PrimDescription;
  1713. client.OnObjectName += m_sceneGraph.PrimName;
  1714. client.OnObjectClickAction += m_sceneGraph.PrimClickAction;
  1715. client.OnObjectMaterial += m_sceneGraph.PrimMaterial;
  1716. client.OnLinkObjects += m_sceneGraph.LinkObjects;
  1717. client.OnDelinkObjects += m_sceneGraph.DelinkObjects;
  1718. client.OnObjectDuplicate += m_sceneGraph.DuplicateObject;
  1719. client.OnObjectDuplicateOnRay += doObjectDuplicateOnRay;
  1720. client.OnUpdatePrimFlags += m_sceneGraph.UpdatePrimFlags;
  1721. client.OnRequestObjectPropertiesFamily += m_sceneGraph.RequestObjectPropertiesFamily;
  1722. client.OnObjectPermissions += HandleObjectPermissionsUpdate;
  1723. client.OnCreateNewInventoryItem += CreateNewInventoryItem;
  1724. client.OnCreateNewInventoryFolder += HandleCreateInventoryFolder;
  1725. client.OnUpdateInventoryFolder += HandleUpdateInventoryFolder;
  1726. client.OnMoveInventoryFolder += HandleMoveInventoryFolder;
  1727. client.OnFetchInventoryDescendents += HandleFetchInventoryDescendents;
  1728. client.OnPurgeInventoryDescendents += HandlePurgeInventoryDescendents;
  1729. client.OnFetchInventory += HandleFetchInventory;
  1730. client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
  1731. client.OnCopyInventoryItem += CopyInventoryItem;
  1732. client.OnMoveInventoryItem += MoveInventoryItem;
  1733. client.OnRemoveInventoryItem += RemoveInventoryItem;
  1734. client.OnRemoveInventoryFolder += RemoveInventoryFolder;
  1735. client.OnRezScript += RezScript;
  1736. client.OnRequestTaskInventory += RequestTaskInventory;
  1737. client.OnRemoveTaskItem += RemoveTaskInventory;
  1738. client.OnUpdateTaskInventory += UpdateTaskInventory;
  1739. client.OnMoveTaskItem += ClientMoveTaskInventoryItem;
  1740. client.OnGrabObject += ProcessObjectGrab;
  1741. client.OnDeGrabObject += ProcessObjectDeGrab;
  1742. client.OnMoneyTransferRequest += ProcessMoneyTransferRequest;
  1743. client.OnParcelBuy += ProcessParcelBuy;
  1744. client.OnAvatarPickerRequest += ProcessAvatarPickerRequest;
  1745. client.OnObjectIncludeInSearch += m_sceneGraph.MakeObjectSearchable;
  1746. client.OnTeleportHomeRequest += TeleportClientHome;
  1747. client.OnSetStartLocationRequest += SetHomeRezPoint;
  1748. client.OnUndo += m_sceneGraph.HandleUndo;
  1749. client.OnObjectGroupRequest += m_sceneGraph.HandleObjectGroupUpdate;
  1750. client.OnParcelReturnObjectsRequest += LandChannel.ReturnObjectsInParcel;
  1751. client.OnParcelSetOtherCleanTime += LandChannel.SetParcelOtherCleanTime;
  1752. client.OnObjectSaleInfo += ObjectSaleInfo;
  1753. client.OnScriptReset += ProcessScriptReset;
  1754. client.OnGetScriptRunning += GetScriptRunning;
  1755. client.OnSetScriptRunning += SetScriptRunning;
  1756. client.OnRegionHandleRequest += RegionHandleRequest;
  1757. client.OnUnackedTerrain += TerrainUnAcked;
  1758. client.OnObjectOwner += ObjectOwner;
  1759. IGodsModule godsModule = RequestModuleInterface<IGodsModule>();
  1760. client.OnGodKickUser += godsModule.KickUser;
  1761. client.OnRequestGodlikePowers += godsModule.RequestGodlikePowers;
  1762. client.OnNetworkStatsUpdate += StatsReporter.AddPacketsStats;
  1763. // EventManager.TriggerOnNewClient(client);
  1764. }
  1765. /// <summary>
  1766. /// Teleport an avatar to their home region
  1767. /// </summary>
  1768. /// <param name="agentId"></param>
  1769. /// <param name="client"></param>
  1770. public virtual void TeleportClientHome(UUID agentId, IClientAPI client)
  1771. {
  1772. UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(agentId);
  1773. if (UserProfile != null)
  1774. {
  1775. RegionInfo regionInfo = CommsManager.GridService.RequestNeighbourInfo(UserProfile.HomeRegionID);
  1776. if (regionInfo == null)
  1777. {
  1778. regionInfo = CommsManager.GridService.RequestNeighbourInfo(UserProfile.HomeRegion);
  1779. if (regionInfo != null) // home region can be away temporarily, too
  1780. {
  1781. UserProfile.HomeRegionID = regionInfo.RegionID;
  1782. CommsManager.UserService.UpdateUserProfile(UserProfile);
  1783. }
  1784. }
  1785. if (regionInfo == null)
  1786. {
  1787. // can't find the Home region: Tell viewer and abort
  1788. client.SendTeleportFailed("Your home-region could not be found.");
  1789. return;
  1790. }
  1791. RequestTeleportLocation(
  1792. client, regionInfo.RegionHandle, UserProfile.HomeLocation, UserProfile.HomeLookAt,
  1793. (uint)(TPFlags.SetLastToTarget | TPFlags.ViaHome));
  1794. }
  1795. }
  1796. public void doObjectDuplicateOnRay(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID,
  1797. UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart,
  1798. bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates)
  1799. {
  1800. Vector3 pos;
  1801. const bool frontFacesOnly = true;
  1802. //m_log.Info("HITTARGET: " + RayTargetObj.ToString() + ", COPYTARGET: " + localID.ToString());
  1803. SceneObjectPart target = GetSceneObjectPart(localID);
  1804. SceneObjectPart target2 = GetSceneObjectPart(RayTargetObj);
  1805. if (target != null && target2 != null)
  1806. {
  1807. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  1808. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  1809. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  1810. if (target2.ParentGroup != null)
  1811. {
  1812. pos = target2.AbsolutePosition;
  1813. //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());
  1814. // TODO: Raytrace better here
  1815. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  1816. Ray NewRay = new Ray(AXOrigin, AXdirection);
  1817. // Ray Trace against target here
  1818. EntityIntersection ei = target2.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, CopyCenters);
  1819. // Un-comment out the following line to Get Raytrace results printed to the console.
  1820. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1821. float ScaleOffset = 0.5f;
  1822. // If we hit something
  1823. if (ei.HitTF)
  1824. {
  1825. Vector3 scale = target.Scale;
  1826. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  1827. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  1828. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  1829. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  1830. ScaleOffset = Math.Abs(ScaleOffset);
  1831. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  1832. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  1833. Vector3 offset = normal * (ScaleOffset / 2f);
  1834. pos = intersectionpoint + offset;
  1835. // stick in offset format from the original prim
  1836. pos = pos - target.ParentGroup.AbsolutePosition;
  1837. if (CopyRotates)
  1838. {
  1839. Quaternion worldRot = target2.GetWorldRotation();
  1840. // SceneObjectGroup obj = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  1841. m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  1842. //obj.Rotation = worldRot;
  1843. //obj.UpdateGroupRotation(worldRot);
  1844. }
  1845. else
  1846. {
  1847. m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID);
  1848. }
  1849. }
  1850. return;
  1851. }
  1852. return;
  1853. }
  1854. }
  1855. public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags)
  1856. {
  1857. UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(remoteClient.AgentId);
  1858. if (UserProfile != null)
  1859. {
  1860. // I know I'm ignoring the regionHandle provided by the teleport location request.
  1861. // reusing the TeleportLocationRequest delegate, so regionHandle isn't valid
  1862. UserProfile.HomeRegionID = RegionInfo.RegionID;
  1863. // TODO: The next line can be removed, as soon as only homeRegionID based UserServers are around.
  1864. // TODO: The HomeRegion property can be removed then, too
  1865. UserProfile.HomeRegion = RegionInfo.RegionHandle;
  1866. UserProfile.HomeLocation = position;
  1867. UserProfile.HomeLookAt = lookAt;
  1868. CommsManager.UserService.UpdateUserProfile(UserProfile);
  1869. // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot.
  1870. m_dialogModule.SendAlertToUser(remoteClient, "Home position set.");
  1871. }
  1872. else
  1873. {
  1874. m_dialogModule.SendAlertToUser(remoteClient, "Set Home request Failed.");
  1875. }
  1876. }
  1877. /// <summary>
  1878. /// Create a child agent scene presence and add it to this scene.
  1879. /// </summary>
  1880. /// <param name="client"></param>
  1881. /// <returns></returns>
  1882. protected virtual ScenePresence CreateAndAddScenePresence(IClientAPI client)
  1883. {
  1884. AvatarAppearance appearance = null;
  1885. GetAvatarAppearance(client, out appearance);
  1886. ScenePresence avatar = m_sceneGraph.CreateAndAddChildScenePresence(client, appearance);
  1887. //avatar.KnownRegions = GetChildrenSeeds(avatar.UUID);
  1888. m_eventManager.TriggerOnNewPresence(avatar);
  1889. return avatar;
  1890. }
  1891. /// <summary>
  1892. /// Get the avatar apperance for the given client.
  1893. /// </summary>
  1894. /// <param name="client"></param>
  1895. /// <param name="appearance"></param>
  1896. public void GetAvatarAppearance(IClientAPI client, out AvatarAppearance appearance)
  1897. {
  1898. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode);
  1899. if (aCircuit == null)
  1900. {
  1901. m_log.DebugFormat("[APPEARANCE] Client did not supply a circuit. Non-Linden? Creating default appearance.");
  1902. appearance = new AvatarAppearance(client.AgentId);
  1903. return;
  1904. }
  1905. appearance = aCircuit.Appearance;
  1906. if (appearance == null)
  1907. {
  1908. m_log.DebugFormat("[APPEARANCE]: Appearance not found in {0}, returning default", RegionInfo.RegionName);
  1909. appearance = new AvatarAppearance(client.AgentId);
  1910. }
  1911. }
  1912. /// <summary>
  1913. /// Remove the given client from the scene.
  1914. /// </summary>
  1915. /// <param name="agentID"></param>
  1916. public override void RemoveClient(UUID agentID)
  1917. {
  1918. bool childagentYN = false;
  1919. ScenePresence avatar = GetScenePresence(agentID);
  1920. if (avatar != null)
  1921. {
  1922. childagentYN = avatar.IsChildAgent;
  1923. if (avatar.ParentID != 0)
  1924. {
  1925. avatar.StandUp();
  1926. }
  1927. try
  1928. {
  1929. m_log.DebugFormat(
  1930. "[SCENE]: Removing {0} agent {1} from region {2}",
  1931. (childagentYN ? "child" : "root"), agentID, RegionInfo.RegionName);
  1932. m_sceneGraph.removeUserCount(!childagentYN);
  1933. CapsModule.RemoveCapsHandler(agentID);
  1934. if (avatar.Scene.NeedSceneCacheClear(avatar.UUID))
  1935. {
  1936. CommsManager.UserProfileCacheService.RemoveUser(agentID);
  1937. }
  1938. if (!avatar.IsChildAgent)
  1939. {
  1940. m_sceneGridService.LogOffUser(agentID, RegionInfo.RegionID, RegionInfo.RegionHandle, avatar.AbsolutePosition, avatar.Lookat);
  1941. //List<ulong> childknownRegions = new List<ulong>();
  1942. //List<ulong> ckn = avatar.KnownChildRegionHandles;
  1943. //for (int i = 0; i < ckn.Count; i++)
  1944. //{
  1945. // childknownRegions.Add(ckn[i]);
  1946. //}
  1947. List<ulong> regions = new List<ulong>(avatar.KnownChildRegionHandles);
  1948. regions.Remove(RegionInfo.RegionHandle);
  1949. m_sceneGridService.SendCloseChildAgentConnections(agentID, regions);
  1950. }
  1951. m_eventManager.TriggerClientClosed(agentID, this);
  1952. }
  1953. catch (NullReferenceException)
  1954. {
  1955. // We don't know which count to remove it from
  1956. // Avatar is already disposed :/
  1957. }
  1958. m_eventManager.TriggerOnRemovePresence(agentID);
  1959. Broadcast(delegate(IClientAPI client)
  1960. {
  1961. try
  1962. {
  1963. client.SendKillObject(avatar.RegionHandle, avatar.LocalId);
  1964. }
  1965. catch (NullReferenceException)
  1966. {
  1967. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  1968. }
  1969. });
  1970. ForEachScenePresence(
  1971. delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  1972. IAgentAssetTransactions agentTransactions = this.RequestModuleInterface<IAgentAssetTransactions>();
  1973. if (agentTransactions != null)
  1974. {
  1975. agentTransactions.RemoveAgentAssetTransactions(agentID);
  1976. }
  1977. m_sceneGraph.RemoveScenePresence(agentID);
  1978. try
  1979. {
  1980. avatar.Close();
  1981. }
  1982. catch (NullReferenceException)
  1983. {
  1984. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  1985. }
  1986. catch (Exception e)
  1987. {
  1988. m_log.Error("[SCENE] Scene.cs:RemoveClient exception: " + e.ToString());
  1989. }
  1990. // Remove client agent from profile, so new logins will work
  1991. if (!childagentYN)
  1992. {
  1993. m_sceneGridService.ClearUserAgent(agentID);
  1994. }
  1995. m_authenticateHandler.RemoveCircuit(avatar.ControllingClient.CircuitCode);
  1996. //m_log.InfoFormat("[SCENE] Memory pre GC {0}", System.GC.GetTotalMemory(false));
  1997. //m_log.InfoFormat("[SCENE] Memory post GC {0}", System.GC.GetTotalMemory(true));
  1998. }
  1999. }
  2000. public void HandleRemoveKnownRegionsFromAvatar(UUID avatarID, List<ulong> regionslst)
  2001. {
  2002. ScenePresence av = GetScenePresence(avatarID);
  2003. if (av != null)
  2004. {
  2005. lock (av)
  2006. {
  2007. for (int i = 0; i < regionslst.Count; i++)
  2008. {
  2009. av.KnownChildRegionHandles.Remove(regionslst[i]);
  2010. }
  2011. }
  2012. }
  2013. }
  2014. public override void CloseAllAgents(uint circuitcode)
  2015. {
  2016. // Called by ClientView to kill all circuit codes
  2017. ClientManager.CloseAllAgents(circuitcode);
  2018. }
  2019. public void NotifyMyCoarseLocationChange()
  2020. {
  2021. ForEachScenePresence(delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  2022. }
  2023. #endregion
  2024. #region Entities
  2025. public void SendKillObject(uint localID)
  2026. {
  2027. SceneObjectPart part = GetSceneObjectPart(localID);
  2028. if (part != null) // It is a prim
  2029. {
  2030. if (part.ParentGroup != null && !part.ParentGroup.IsDeleted) // Valid
  2031. {
  2032. if (part.ParentGroup.RootPart != part) // Child part
  2033. return;
  2034. }
  2035. }
  2036. Broadcast(delegate(IClientAPI client) { client.SendKillObject(m_regionHandle, localID); });
  2037. }
  2038. #endregion
  2039. #region RegionComms
  2040. /// <summary>
  2041. /// Register the methods that should be invoked when this scene receives various incoming events
  2042. /// </summary>
  2043. public void RegisterCommsEvents()
  2044. {
  2045. m_sceneGridService.OnExpectUser += HandleNewUserConnection;
  2046. m_sceneGridService.OnAvatarCrossingIntoRegion += AgentCrossing;
  2047. m_sceneGridService.OnCloseAgentConnection += IncomingCloseAgent;
  2048. m_sceneGridService.OnRegionUp += OtherRegionUp;
  2049. //m_sceneGridService.OnChildAgentUpdate += IncomingChildAgentDataUpdate;
  2050. m_sceneGridService.OnExpectPrim += IncomingInterRegionPrimGroup;
  2051. //m_sceneGridService.OnRemoveKnownRegionFromAvatar += HandleRemoveKnownRegionsFromAvatar;
  2052. m_sceneGridService.OnLogOffUser += HandleLogOffUserFromGrid;
  2053. m_sceneGridService.KiPrimitive += SendKillObject;
  2054. m_sceneGridService.OnGetLandData += GetLandData;
  2055. if (m_interregionCommsIn != null)
  2056. {
  2057. m_log.Debug("[SCENE]: Registering with InterregionCommsIn");
  2058. m_interregionCommsIn.OnChildAgentUpdate += IncomingChildAgentDataUpdate;
  2059. }
  2060. else
  2061. m_log.Debug("[SCENE]: Unable to register with InterregionCommsIn");
  2062. }
  2063. /// <summary>
  2064. /// Deregister this scene from receiving incoming region events
  2065. /// </summary>
  2066. public void UnRegisterRegionWithComms()
  2067. {
  2068. m_sceneGridService.KiPrimitive -= SendKillObject;
  2069. m_sceneGridService.OnLogOffUser -= HandleLogOffUserFromGrid;
  2070. //m_sceneGridService.OnRemoveKnownRegionFromAvatar -= HandleRemoveKnownRegionsFromAvatar;
  2071. m_sceneGridService.OnExpectPrim -= IncomingInterRegionPrimGroup;
  2072. //m_sceneGridService.OnChildAgentUpdate -= IncomingChildAgentDataUpdate;
  2073. m_sceneGridService.OnRegionUp -= OtherRegionUp;
  2074. m_sceneGridService.OnExpectUser -= HandleNewUserConnection;
  2075. m_sceneGridService.OnAvatarCrossingIntoRegion -= AgentCrossing;
  2076. m_sceneGridService.OnCloseAgentConnection -= IncomingCloseAgent;
  2077. m_sceneGridService.OnGetLandData -= GetLandData;
  2078. if (m_interregionCommsIn != null)
  2079. m_interregionCommsIn.OnChildAgentUpdate -= IncomingChildAgentDataUpdate;
  2080. m_sceneGridService.Close();
  2081. }
  2082. /// <summary>
  2083. /// A handler for the SceneCommunicationService event, to match that events return type of void.
  2084. /// Use NewUserConnection() directly if possible so the return type can refuse connections.
  2085. /// At the moment nothing actually seems to use this event,
  2086. /// as everything is switching to calling the NewUserConnection method directly.
  2087. /// </summary>
  2088. /// <param name="agent"></param>
  2089. public void HandleNewUserConnection(AgentCircuitData agent)
  2090. {
  2091. string reason;
  2092. NewUserConnection(agent, out reason);
  2093. }
  2094. /// <summary>
  2095. /// Do the work necessary to initiate a new user connection for a particular scene.
  2096. /// At the moment, this consists of setting up the caps infrastructure
  2097. /// The return bool should allow for connections to be refused, but as not all calling paths
  2098. /// take proper notice of it let, we allowed banned users in still.
  2099. /// </summary>
  2100. /// <param name="regionHandle"></param>
  2101. /// <param name="agent"></param>
  2102. /// <param name="reason"></param>
  2103. public bool NewUserConnection(AgentCircuitData agent, out string reason)
  2104. {
  2105. // Don't disable this log message - it's too helpful
  2106. m_log.InfoFormat(
  2107. "[CONNECTION BEGIN]: Region {0} told of incoming {1} agent {2} {3} {4} (circuit code {5})",
  2108. RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.firstname, agent.lastname,
  2109. agent.AgentID, agent.circuitcode);
  2110. reason = String.Empty;
  2111. if (!AuthenticateUser(agent, out reason))
  2112. return false;
  2113. if (!AuthorizeUser(agent, out reason))
  2114. return false;
  2115. m_log.InfoFormat(
  2116. "[CONNECTION BEGIN]: Region {0} authenticated and authorized incoming {1} agent {2} {3} {4} (circuit code {5})",
  2117. RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.firstname, agent.lastname,
  2118. agent.AgentID, agent.circuitcode);
  2119. CapsModule.NewUserConnection(agent);
  2120. ScenePresence sp = m_sceneGraph.GetScenePresence(agent.AgentID);
  2121. if (sp != null)
  2122. {
  2123. m_log.DebugFormat(
  2124. "[SCENE]: Adjusting known seeds for existing agent {0} in {1}",
  2125. agent.AgentID, RegionInfo.RegionName);
  2126. sp.AdjustKnownSeeds();
  2127. return true;
  2128. }
  2129. CapsModule.AddCapsHandler(agent.AgentID);
  2130. if (!agent.child)
  2131. {
  2132. // Honor parcel landing type and position.
  2133. ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
  2134. if (land != null)
  2135. {
  2136. if (land.landData.LandingType == (byte)1 && land.landData.UserLocation != Vector3.Zero)
  2137. {
  2138. agent.startpos = land.landData.UserLocation;
  2139. }
  2140. }
  2141. }
  2142. m_authenticateHandler.AddNewCircuit(agent.circuitcode, agent);
  2143. // rewrite session_id
  2144. CachedUserInfo userinfo = CommsManager.UserProfileCacheService.GetUserDetails(agent.AgentID);
  2145. if (userinfo != null)
  2146. {
  2147. userinfo.SessionID = agent.SessionID;
  2148. }
  2149. else
  2150. {
  2151. m_log.WarnFormat(
  2152. "[CONNECTION BEGIN]: We couldn't find a User Info record for {0}. This is usually an indication that the UUID we're looking up is invalid", agent.AgentID);
  2153. }
  2154. return true;
  2155. }
  2156. public virtual bool AuthenticateUser(AgentCircuitData agent, out string reason)
  2157. {
  2158. reason = String.Empty;
  2159. bool result = CommsManager.UserService.VerifySession(agent.AgentID, agent.SessionID);
  2160. m_log.Debug("[CONNECTION BEGIN]: User authentication returned " + result);
  2161. if (!result)
  2162. reason = String.Format("Failed to authenticate user {0} {1}, access denied.", agent.firstname, agent.lastname);
  2163. return result;
  2164. }
  2165. protected virtual bool AuthorizeUser(AgentCircuitData agent, out string reason)
  2166. {
  2167. reason = String.Empty;
  2168. if (!m_strictAccessControl) return true;
  2169. if (Permissions.IsGod(agent.AgentID)) return true;
  2170. if (m_regInfo.EstateSettings.IsBanned(agent.AgentID))
  2171. {
  2172. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist",
  2173. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  2174. reason = String.Format("Denied access to region {0}: You have been banned from that region.",
  2175. RegionInfo.RegionName);
  2176. return false;
  2177. }
  2178. if (!m_regInfo.EstateSettings.PublicAccess &&
  2179. !m_regInfo.EstateSettings.HasAccess(agent.AgentID))
  2180. {
  2181. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user does not have access to the estate",
  2182. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  2183. reason = String.Format("Denied access to private region {0}: You are not on the access list for that region.",
  2184. RegionInfo.RegionName);
  2185. return false;
  2186. }
  2187. // TODO: estate/region settings are not properly hooked up
  2188. // to ILandObject.isRestrictedFromLand()
  2189. // if (null != LandChannel)
  2190. // {
  2191. // // region seems to have local Id of 1
  2192. // ILandObject land = LandChannel.GetLandObject(1);
  2193. // if (null != land)
  2194. // {
  2195. // if (land.isBannedFromLand(agent.AgentID))
  2196. // {
  2197. // m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user has been banned from land",
  2198. // agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  2199. // reason = String.Format("Denied access to private region {0}: You are banned from that region.",
  2200. // RegionInfo.RegionName);
  2201. // return false;
  2202. // }
  2203. // if (land.isRestrictedFromLand(agent.AgentID))
  2204. // {
  2205. // m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user does not have access to the region",
  2206. // agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  2207. // reason = String.Format("Denied access to private region {0}: You are not on the access list for that region.",
  2208. // RegionInfo.RegionName);
  2209. // return false;
  2210. // }
  2211. // }
  2212. // }
  2213. return true;
  2214. }
  2215. public void UpdateCircuitData(AgentCircuitData data)
  2216. {
  2217. m_authenticateHandler.UpdateAgentData(data);
  2218. }
  2219. public bool ChangeCircuitCode(uint oldcc, uint newcc)
  2220. {
  2221. return m_authenticateHandler.TryChangeCiruitCode(oldcc, newcc);
  2222. }
  2223. public void HandleLogOffUserFromGrid(UUID AvatarID, UUID RegionSecret, string message)
  2224. {
  2225. ScenePresence loggingOffUser = null;
  2226. loggingOffUser = GetScenePresence(AvatarID);
  2227. if (loggingOffUser != null)
  2228. {
  2229. UUID localRegionSecret = UUID.Zero;
  2230. bool parsedsecret = UUID.TryParse(m_regInfo.regionSecret, out localRegionSecret);
  2231. // Region Secret is used here in case a new sessionid overwrites an old one on the user server.
  2232. // Will update the user server in a few revisions to use it.
  2233. if (RegionSecret == loggingOffUser.ControllingClient.SecureSessionId || (parsedsecret && RegionSecret == localRegionSecret))
  2234. {
  2235. m_sceneGridService.SendCloseChildAgentConnections(loggingOffUser.UUID, new List<ulong>(loggingOffUser.KnownRegions.Keys));
  2236. loggingOffUser.ControllingClient.Kick(message);
  2237. // Give them a second to receive the message!
  2238. Thread.Sleep(1000);
  2239. loggingOffUser.ControllingClient.Close(true);
  2240. }
  2241. else
  2242. {
  2243. m_log.Info("[USERLOGOFF]: System sending the LogOff user message failed to sucessfully authenticate");
  2244. }
  2245. }
  2246. else
  2247. {
  2248. m_log.InfoFormat("[USERLOGOFF]: Got a logoff request for {0} but the user isn't here. The user might already have been logged out", AvatarID.ToString());
  2249. }
  2250. }
  2251. /// <summary>
  2252. /// Triggered when an agent crosses into this sim. Also happens on initial login.
  2253. /// </summary>
  2254. /// <param name="agentID"></param>
  2255. /// <param name="position"></param>
  2256. /// <param name="isFlying"></param>
  2257. public virtual void AgentCrossing(UUID agentID, Vector3 position, bool isFlying)
  2258. {
  2259. ScenePresence presence;
  2260. lock (m_scenePresences)
  2261. {
  2262. m_scenePresences.TryGetValue(agentID, out presence);
  2263. }
  2264. if (presence != null)
  2265. {
  2266. try
  2267. {
  2268. presence.MakeRootAgent(position, isFlying);
  2269. }
  2270. catch (Exception e)
  2271. {
  2272. m_log.ErrorFormat("[SCENE]: Unable to do agent crossing, exception {0}", e);
  2273. }
  2274. }
  2275. else
  2276. {
  2277. m_log.ErrorFormat(
  2278. "[SCENE]: Could not find presence for agent {0} crossing into scene {1}",
  2279. agentID, RegionInfo.RegionName);
  2280. }
  2281. }
  2282. public virtual bool IncomingChildAgentDataUpdate(AgentData cAgentData)
  2283. {
  2284. // m_log.DebugFormat(
  2285. // "[SCENE]: Incoming child agent update for {0} in {1}", cAgentData.AgentID, RegionInfo.RegionName);
  2286. // We have to wait until the viewer contacts this region after receiving EAC.
  2287. // That calls AddNewClient, which finally creates the ScenePresence
  2288. ScenePresence childAgentUpdate = WaitGetScenePresence(cAgentData.AgentID);
  2289. if (childAgentUpdate != null)
  2290. {
  2291. childAgentUpdate.ChildAgentDataUpdate(cAgentData);
  2292. return true;
  2293. }
  2294. return false;
  2295. }
  2296. public virtual bool IncomingChildAgentDataUpdate(AgentPosition cAgentData)
  2297. {
  2298. //m_log.Debug(" XXX Scene IncomingChildAgentDataUpdate POSITION in " + RegionInfo.RegionName);
  2299. ScenePresence childAgentUpdate = GetScenePresence(cAgentData.AgentID);
  2300. if (childAgentUpdate != null)
  2301. {
  2302. // I can't imagine *yet* why we would get an update if the agent is a root agent..
  2303. // however to avoid a race condition crossing borders..
  2304. if (childAgentUpdate.IsChildAgent)
  2305. {
  2306. uint rRegionX = (uint)(cAgentData.RegionHandle >> 40);
  2307. uint rRegionY = (((uint)(cAgentData.RegionHandle)) >> 8);
  2308. uint tRegionX = RegionInfo.RegionLocX;
  2309. uint tRegionY = RegionInfo.RegionLocY;
  2310. //Send Data to ScenePresence
  2311. childAgentUpdate.ChildAgentDataUpdate(cAgentData, tRegionX, tRegionY, rRegionX, rRegionY);
  2312. // Not Implemented:
  2313. //TODO: Do we need to pass the message on to one of our neighbors?
  2314. }
  2315. return true;
  2316. }
  2317. return false;
  2318. }
  2319. protected virtual ScenePresence WaitGetScenePresence(UUID agentID)
  2320. {
  2321. int ntimes = 10;
  2322. ScenePresence childAgentUpdate = null;
  2323. while ((childAgentUpdate = GetScenePresence(agentID)) == null && (ntimes-- > 0))
  2324. Thread.Sleep(1000);
  2325. return childAgentUpdate;
  2326. }
  2327. public virtual bool IncomingRetrieveRootAgent(UUID id, out IAgentData agent)
  2328. {
  2329. agent = null;
  2330. ScenePresence sp = GetScenePresence(id);
  2331. if ((sp != null) && (!sp.IsChildAgent))
  2332. {
  2333. sp.IsChildAgent = true;
  2334. return sp.CopyAgent(out agent);
  2335. }
  2336. return false;
  2337. }
  2338. public virtual bool IncomingReleaseAgent(UUID id)
  2339. {
  2340. return m_sceneGridService.ReleaseAgent(id);
  2341. }
  2342. public void SendReleaseAgent(ulong regionHandle, UUID id, string uri)
  2343. {
  2344. m_interregionCommsOut.SendReleaseAgent(regionHandle, id, uri);
  2345. }
  2346. /// <summary>
  2347. /// Tell a single agent to disconnect from the region.
  2348. /// </summary>
  2349. /// <param name="regionHandle"></param>
  2350. /// <param name="agentID"></param>
  2351. public bool IncomingCloseAgent(UUID agentID)
  2352. {
  2353. //m_log.DebugFormat("[SCENE]: Processing incoming close agent for {0}", agentID);
  2354. ScenePresence presence = m_sceneGraph.GetScenePresence(agentID);
  2355. if (presence != null)
  2356. {
  2357. // Nothing is removed here, so down count it as such
  2358. if (presence.IsChildAgent)
  2359. {
  2360. m_sceneGraph.removeUserCount(false);
  2361. }
  2362. else
  2363. {
  2364. m_sceneGraph.removeUserCount(true);
  2365. }
  2366. // Don't do this to root agents on logout, it's not nice for the viewer
  2367. if (presence.IsChildAgent)
  2368. {
  2369. // Tell a single agent to disconnect from the region.
  2370. IEventQueue eq = RequestModuleInterface<IEventQueue>();
  2371. if (eq != null)
  2372. {
  2373. eq.DisableSimulator(RegionInfo.RegionHandle, agentID);
  2374. }
  2375. else
  2376. presence.ControllingClient.SendShutdownConnectionNotice();
  2377. }
  2378. presence.ControllingClient.Close(true);
  2379. return true;
  2380. }
  2381. // Agent not here
  2382. return false;
  2383. }
  2384. /// <summary>
  2385. /// Tell neighboring regions about this agent
  2386. /// When the regions respond with a true value,
  2387. /// tell the agents about the region.
  2388. ///
  2389. /// We have to tell the regions about the agents first otherwise it'll deny them access
  2390. ///
  2391. /// </summary>
  2392. /// <param name="presence"></param>
  2393. public void InformClientOfNeighbours(ScenePresence presence)
  2394. {
  2395. m_sceneGridService.EnableNeighbourChildAgents(presence, m_neighbours);
  2396. }
  2397. /// <summary>
  2398. /// Tell a neighboring region about this agent
  2399. /// </summary>
  2400. /// <param name="presence"></param>
  2401. /// <param name="region"></param>
  2402. public void InformClientOfNeighbor(ScenePresence presence, RegionInfo region)
  2403. {
  2404. m_sceneGridService.EnableNeighbourChildAgents(presence, m_neighbours);
  2405. }
  2406. /// <summary>
  2407. /// Requests information about this region from gridcomms
  2408. /// </summary>
  2409. /// <param name="regionHandle"></param>
  2410. /// <returns></returns>
  2411. public RegionInfo RequestNeighbouringRegionInfo(ulong regionHandle)
  2412. {
  2413. return m_sceneGridService.RequestNeighbouringRegionInfo(regionHandle);
  2414. }
  2415. /// <summary>
  2416. /// Requests textures for map from minimum region to maximum region in world cordinates
  2417. /// </summary>
  2418. /// <param name="remoteClient"></param>
  2419. /// <param name="minX"></param>
  2420. /// <param name="minY"></param>
  2421. /// <param name="maxX"></param>
  2422. /// <param name="maxY"></param>
  2423. public void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY)
  2424. {
  2425. m_log.DebugFormat("[MAPBLOCK]: {0}-{1}, {2}-{3}", minX, minY, maxX, maxY);
  2426. m_sceneGridService.RequestMapBlocks(remoteClient, minX, minY, maxX, maxY);
  2427. }
  2428. /// <summary>
  2429. /// Tries to teleport agent to other region.
  2430. /// </summary>
  2431. /// <param name="remoteClient"></param>
  2432. /// <param name="regionName"></param>
  2433. /// <param name="position"></param>
  2434. /// <param name="lookAt"></param>
  2435. /// <param name="teleportFlags"></param>
  2436. public void RequestTeleportLocation(IClientAPI remoteClient, string regionName, Vector3 position,
  2437. Vector3 lookat, uint teleportFlags)
  2438. {
  2439. RegionInfo regionInfo = m_sceneGridService.RequestClosestRegion(regionName);
  2440. if (regionInfo == null)
  2441. {
  2442. // can't find the region: Tell viewer and abort
  2443. remoteClient.SendTeleportFailed("The region '" + regionName + "' could not be found.");
  2444. return;
  2445. }
  2446. RequestTeleportLocation(remoteClient, regionInfo.RegionHandle, position, lookat, teleportFlags);
  2447. }
  2448. /// <summary>
  2449. /// Tries to teleport agent to other region.
  2450. /// </summary>
  2451. /// <param name="remoteClient"></param>
  2452. /// <param name="regionHandle"></param>
  2453. /// <param name="position"></param>
  2454. /// <param name="lookAt"></param>
  2455. /// <param name="teleportFlags"></param>
  2456. public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, Vector3 position,
  2457. Vector3 lookAt, uint teleportFlags)
  2458. {
  2459. ScenePresence sp = null;
  2460. lock (m_scenePresences)
  2461. {
  2462. if (m_scenePresences.ContainsKey(remoteClient.AgentId))
  2463. sp = m_scenePresences[remoteClient.AgentId];
  2464. }
  2465. if (sp != null)
  2466. {
  2467. if (m_teleportModule != null)
  2468. {
  2469. m_teleportModule.RequestTeleportToLocation(sp, regionHandle,
  2470. position, lookAt, teleportFlags);
  2471. }
  2472. else
  2473. {
  2474. m_sceneGridService.RequestTeleportToLocation(sp, regionHandle,
  2475. position, lookAt, teleportFlags);
  2476. }
  2477. }
  2478. }
  2479. /// <summary>
  2480. /// Tries to teleport agent to landmark.
  2481. /// </summary>
  2482. /// <param name="remoteClient"></param>
  2483. /// <param name="regionHandle"></param>
  2484. /// <param name="position"></param>
  2485. public void RequestTeleportLandmark(IClientAPI remoteClient, UUID regionID, Vector3 position)
  2486. {
  2487. RegionInfo info = CommsManager.GridService.RequestNeighbourInfo(regionID);
  2488. if (info == null)
  2489. {
  2490. // can't find the region: Tell viewer and abort
  2491. remoteClient.SendTeleportFailed("The teleport destination could not be found.");
  2492. return;
  2493. }
  2494. RequestTeleportLocation(remoteClient, info.RegionHandle, position, Vector3.Zero, (uint)(TPFlags.SetLastToTarget | TPFlags.ViaLandmark));
  2495. }
  2496. public void CrossAgentToNewRegion(ScenePresence agent, bool isFlying)
  2497. {
  2498. m_sceneGridService.CrossAgentToNewRegion(this, agent, isFlying);
  2499. }
  2500. public void SendOutChildAgentUpdates(AgentPosition cadu, ScenePresence presence)
  2501. {
  2502. m_sceneGridService.SendChildAgentDataUpdate(cadu, presence);
  2503. }
  2504. #endregion
  2505. #region Other Methods
  2506. public void SetObjectCapacity(int objects)
  2507. {
  2508. // Region specific config overrides global
  2509. //
  2510. if (RegionInfo.ObjectCapacity != 0)
  2511. objects = RegionInfo.ObjectCapacity;
  2512. if (StatsReporter != null)
  2513. {
  2514. StatsReporter.SetObjectCapacity(objects);
  2515. }
  2516. objectCapacity = objects;
  2517. }
  2518. public List<FriendListItem> GetFriendList(string id)
  2519. {
  2520. UUID avatarID;
  2521. if (!UUID.TryParse(id, out avatarID))
  2522. return new List<FriendListItem>();
  2523. return CommsManager.GetUserFriendList(avatarID);
  2524. }
  2525. public Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos(List<UUID> uuids)
  2526. {
  2527. return CommsManager.GetFriendRegionInfos(uuids);
  2528. }
  2529. public virtual void StoreAddFriendship(UUID ownerID, UUID friendID, uint perms)
  2530. {
  2531. m_sceneGridService.AddNewUserFriend(ownerID, friendID, perms);
  2532. }
  2533. public virtual void StoreUpdateFriendship(UUID ownerID, UUID friendID, uint perms)
  2534. {
  2535. m_sceneGridService.UpdateUserFriendPerms(ownerID, friendID, perms);
  2536. }
  2537. public virtual void StoreRemoveFriendship(UUID ownerID, UUID ExfriendID)
  2538. {
  2539. m_sceneGridService.RemoveUserFriend(ownerID, ExfriendID);
  2540. }
  2541. #endregion
  2542. public void HandleObjectPermissionsUpdate(IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set)
  2543. {
  2544. // Check for spoofing.. since this is permissions we're talking about here!
  2545. if ((controller.SessionId == sessionID) && (controller.AgentId == agentID))
  2546. {
  2547. // Tell the object to do permission update
  2548. if (localId != 0)
  2549. {
  2550. SceneObjectGroup chObjectGroup = GetGroupByPrim(localId);
  2551. if (chObjectGroup != null)
  2552. {
  2553. chObjectGroup.UpdatePermissions(agentID, field, localId, mask, set);
  2554. }
  2555. }
  2556. }
  2557. }
  2558. /// <summary>
  2559. /// Causes all clients to get a full object update on all of the objects in the scene.
  2560. /// </summary>
  2561. public void ForceClientUpdate()
  2562. {
  2563. List<EntityBase> EntityList = GetEntities();
  2564. foreach (EntityBase ent in EntityList)
  2565. {
  2566. if (ent is SceneObjectGroup)
  2567. {
  2568. ((SceneObjectGroup)ent).ScheduleGroupForFullUpdate();
  2569. }
  2570. }
  2571. }
  2572. /// <summary>
  2573. /// This is currently only used for scale (to scale to MegaPrim size)
  2574. /// There is a console command that calls this in OpenSimMain
  2575. /// </summary>
  2576. /// <param name="cmdparams"></param>
  2577. public void HandleEditCommand(string[] cmdparams)
  2578. {
  2579. m_log.Debug("Searching for Primitive: '" + cmdparams[2] + "'");
  2580. List<EntityBase> EntityList = GetEntities();
  2581. foreach (EntityBase ent in EntityList)
  2582. {
  2583. if (ent is SceneObjectGroup)
  2584. {
  2585. SceneObjectPart part = ((SceneObjectGroup)ent).GetChildPart(((SceneObjectGroup)ent).UUID);
  2586. if (part != null)
  2587. {
  2588. if (part.Name == cmdparams[2])
  2589. {
  2590. part.Resize(
  2591. new Vector3(Convert.ToSingle(cmdparams[3]), Convert.ToSingle(cmdparams[4]),
  2592. Convert.ToSingle(cmdparams[5])));
  2593. m_log.Debug("Edited scale of Primitive: " + part.Name);
  2594. }
  2595. }
  2596. }
  2597. }
  2598. }
  2599. public override void Show(string[] showParams)
  2600. {
  2601. base.Show(showParams);
  2602. switch (showParams[0])
  2603. {
  2604. case "users":
  2605. m_log.Error("Current Region: " + RegionInfo.RegionName);
  2606. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}{6,-16}", "Firstname", "Lastname",
  2607. "Agent ID", "Session ID", "Circuit", "IP", "World");
  2608. foreach (ScenePresence scenePresence in GetAvatars())
  2609. {
  2610. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}{6,-16}",
  2611. scenePresence.Firstname,
  2612. scenePresence.Lastname,
  2613. scenePresence.UUID,
  2614. scenePresence.ControllingClient.AgentId,
  2615. "Unknown",
  2616. "Unknown",
  2617. RegionInfo.RegionName);
  2618. }
  2619. break;
  2620. }
  2621. }
  2622. #region Script Handling Methods
  2623. /// <summary>
  2624. /// Console command handler to send script command to script engine.
  2625. /// </summary>
  2626. /// <param name="args"></param>
  2627. public void SendCommandToPlugins(string[] args)
  2628. {
  2629. m_eventManager.TriggerOnPluginConsole(args);
  2630. }
  2631. public LandData GetLandData(float x, float y)
  2632. {
  2633. return LandChannel.GetLandObject(x, y).landData;
  2634. }
  2635. public LandData GetLandData(uint x, uint y)
  2636. {
  2637. m_log.DebugFormat("[SCENE]: returning land for {0},{1}", x, y);
  2638. return LandChannel.GetLandObject((int)x, (int)y).landData;
  2639. }
  2640. public RegionInfo RequestClosestRegion(string name)
  2641. {
  2642. return m_sceneGridService.RequestClosestRegion(name);
  2643. }
  2644. #endregion
  2645. #region Script Engine
  2646. private List<ScriptEngineInterface> ScriptEngines = new List<ScriptEngineInterface>();
  2647. public bool DumpAssetsToFile;
  2648. /// <summary>
  2649. ///
  2650. /// </summary>
  2651. /// <param name="scriptEngine"></param>
  2652. public void AddScriptEngine(ScriptEngineInterface scriptEngine)
  2653. {
  2654. ScriptEngines.Add(scriptEngine);
  2655. scriptEngine.InitializeEngine(this);
  2656. }
  2657. private bool ScriptDanger(SceneObjectPart part,Vector3 pos)
  2658. {
  2659. ILandObject parcel = LandChannel.GetLandObject(pos.X, pos.Y);
  2660. if (part != null)
  2661. {
  2662. if (parcel != null)
  2663. {
  2664. if ((parcel.landData.Flags & (uint)ParcelFlags.AllowOtherScripts) != 0)
  2665. {
  2666. return true;
  2667. }
  2668. else if ((parcel.landData.Flags & (uint)ParcelFlags.AllowGroupScripts) != 0)
  2669. {
  2670. if (part.OwnerID == parcel.landData.OwnerID
  2671. || (parcel.landData.IsGroupOwned && part.GroupID == parcel.landData.GroupID)
  2672. || Permissions.IsGod(part.OwnerID))
  2673. {
  2674. return true;
  2675. }
  2676. else
  2677. {
  2678. return false;
  2679. }
  2680. }
  2681. else
  2682. {
  2683. if (part.OwnerID == parcel.landData.OwnerID)
  2684. {
  2685. return true;
  2686. }
  2687. else
  2688. {
  2689. return false;
  2690. }
  2691. }
  2692. }
  2693. else
  2694. {
  2695. if (pos.X > 0f && pos.X < Constants.RegionSize && pos.Y > 0f && pos.Y < Constants.RegionSize)
  2696. {
  2697. // The only time parcel != null when an object is inside a region is when
  2698. // there is nothing behind the landchannel. IE, no land plugin loaded.
  2699. return true;
  2700. }
  2701. else
  2702. {
  2703. // The object is outside of this region. Stop piping events to it.
  2704. return false;
  2705. }
  2706. }
  2707. }
  2708. else
  2709. {
  2710. return false;
  2711. }
  2712. }
  2713. public bool ScriptDanger(uint localID, Vector3 pos)
  2714. {
  2715. SceneObjectPart part = GetSceneObjectPart(localID);
  2716. if (part != null)
  2717. {
  2718. return ScriptDanger(part, pos);
  2719. }
  2720. else
  2721. {
  2722. return false;
  2723. }
  2724. }
  2725. public bool PipeEventsForScript(uint localID)
  2726. {
  2727. SceneObjectPart part = GetSceneObjectPart(localID);
  2728. if (part != null)
  2729. {
  2730. // Changed so that child prims of attachments return ScriptDanger for their parent, so that
  2731. // their scripts will actually run.
  2732. // -- Leaf, Tue Aug 12 14:17:05 EDT 2008
  2733. SceneObjectPart parent = part.ParentGroup.RootPart;
  2734. if (parent != null && parent.IsAttachment)
  2735. return ScriptDanger(parent, parent.GetWorldPosition());
  2736. else
  2737. return ScriptDanger(part, part.GetWorldPosition());
  2738. }
  2739. else
  2740. {
  2741. return false;
  2742. }
  2743. }
  2744. #endregion
  2745. #region SceneGraph wrapper methods
  2746. /// <summary>
  2747. ///
  2748. /// </summary>
  2749. /// <param name="localID"></param>
  2750. /// <returns></returns>
  2751. public UUID ConvertLocalIDToFullID(uint localID)
  2752. {
  2753. return m_sceneGraph.ConvertLocalIDToFullID(localID);
  2754. }
  2755. public void SwapRootAgentCount(bool rootChildChildRootTF)
  2756. {
  2757. m_sceneGraph.SwapRootChildAgent(rootChildChildRootTF);
  2758. }
  2759. public void AddPhysicalPrim(int num)
  2760. {
  2761. m_sceneGraph.AddPhysicalPrim(num);
  2762. }
  2763. public void RemovePhysicalPrim(int num)
  2764. {
  2765. m_sceneGraph.RemovePhysicalPrim(num);
  2766. }
  2767. //The idea is to have a group of method that return a list of avatars meeting some requirement
  2768. // ie it could be all m_scenePresences within a certain range of the calling prim/avatar.
  2769. /// <summary>
  2770. /// Return a list of all avatars in this region.
  2771. /// This list is a new object, so it can be iterated over without locking.
  2772. /// </summary>
  2773. /// <returns></returns>
  2774. public List<ScenePresence> GetAvatars()
  2775. {
  2776. return m_sceneGraph.GetAvatars();
  2777. }
  2778. /// <summary>
  2779. /// Return a list of all ScenePresences in this region. This returns child agents as well as root agents.
  2780. /// This list is a new object, so it can be iterated over without locking.
  2781. /// </summary>
  2782. /// <returns></returns>
  2783. public List<ScenePresence> GetScenePresences()
  2784. {
  2785. return m_sceneGraph.GetScenePresences();
  2786. }
  2787. /// <summary>
  2788. /// Request a filtered list of ScenePresences in this region.
  2789. /// This list is a new object, so it can be iterated over without locking.
  2790. /// </summary>
  2791. /// <param name="filter"></param>
  2792. /// <returns></returns>
  2793. public List<ScenePresence> GetScenePresences(FilterAvatarList filter)
  2794. {
  2795. return m_sceneGraph.GetScenePresences(filter);
  2796. }
  2797. /// <summary>
  2798. /// Request a scene presence by UUID
  2799. /// </summary>
  2800. /// <param name="avatarID"></param>
  2801. /// <returns></returns>
  2802. public ScenePresence GetScenePresence(UUID avatarID)
  2803. {
  2804. return m_sceneGraph.GetScenePresence(avatarID);
  2805. }
  2806. public override bool PresenceChildStatus(UUID avatarID)
  2807. {
  2808. ScenePresence cp = GetScenePresence(avatarID);
  2809. // FIXME: This is really crap - some logout code is relying on a NullReferenceException to halt its processing
  2810. // This needs to be fixed properly by cleaning up the logout code.
  2811. //if (cp != null)
  2812. // return cp.IsChildAgent;
  2813. //return false;
  2814. return cp.IsChildAgent;
  2815. }
  2816. /// <summary>
  2817. ///
  2818. /// </summary>
  2819. /// <param name="action"></param>
  2820. public void ForEachScenePresence(Action<ScenePresence> action)
  2821. {
  2822. // We don't want to try to send messages if there are no avatars.
  2823. if (m_scenePresences != null)
  2824. {
  2825. try
  2826. {
  2827. List<ScenePresence> presenceList = GetScenePresences();
  2828. foreach (ScenePresence presence in presenceList)
  2829. {
  2830. action(presence);
  2831. }
  2832. }
  2833. catch (Exception e)
  2834. {
  2835. m_log.Info("[BUG] in " + RegionInfo.RegionName + ": " + e.ToString());
  2836. m_log.Info("[BUG] Stack Trace: " + e.StackTrace);
  2837. }
  2838. }
  2839. }
  2840. /// <summary>
  2841. ///
  2842. /// </summary>
  2843. /// <param name="action"></param>
  2844. // public void ForEachObject(Action<SceneObjectGroup> action)
  2845. // {
  2846. // List<SceneObjectGroup> presenceList;
  2847. //
  2848. // lock (m_sceneObjects)
  2849. // {
  2850. // presenceList = new List<SceneObjectGroup>(m_sceneObjects.Values);
  2851. // }
  2852. //
  2853. // foreach (SceneObjectGroup presence in presenceList)
  2854. // {
  2855. // action(presence);
  2856. // }
  2857. // }
  2858. /// <summary>
  2859. /// Get a named prim contained in this scene (will return the first
  2860. /// found, if there are more than one prim with the same name)
  2861. /// </summary>
  2862. /// <param name="name"></param>
  2863. /// <returns></returns>
  2864. public SceneObjectPart GetSceneObjectPart(string name)
  2865. {
  2866. return m_sceneGraph.GetSceneObjectPart(name);
  2867. }
  2868. /// <summary>
  2869. /// Get a prim via its local id
  2870. /// </summary>
  2871. /// <param name="localID"></param>
  2872. /// <returns></returns>
  2873. public SceneObjectPart GetSceneObjectPart(uint localID)
  2874. {
  2875. return m_sceneGraph.GetSceneObjectPart(localID);
  2876. }
  2877. /// <summary>
  2878. /// Get a prim via its UUID
  2879. /// </summary>
  2880. /// <param name="fullID"></param>
  2881. /// <returns></returns>
  2882. public SceneObjectPart GetSceneObjectPart(UUID fullID)
  2883. {
  2884. return m_sceneGraph.GetSceneObjectPart(fullID);
  2885. }
  2886. public bool TryGetAvatar(UUID avatarId, out ScenePresence avatar)
  2887. {
  2888. return m_sceneGraph.TryGetAvatar(avatarId, out avatar);
  2889. }
  2890. public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
  2891. {
  2892. return m_sceneGraph.TryGetAvatarByName(avatarName, out avatar);
  2893. }
  2894. public void ForEachClient(Action<IClientAPI> action)
  2895. {
  2896. m_sceneGraph.ForEachClient(action);
  2897. }
  2898. /// <summary>
  2899. /// Returns a list of the entities in the scene. This is a new list so operations perform on the list itself
  2900. /// will not affect the original list of objects in the scene.
  2901. /// </summary>
  2902. /// <returns></returns>
  2903. public List<EntityBase> GetEntities()
  2904. {
  2905. return m_sceneGraph.GetEntities();
  2906. }
  2907. #endregion
  2908. #region Avatar Appearance Default
  2909. public static void GetDefaultAvatarAppearance(out AvatarWearable[] wearables, out byte[] visualParams)
  2910. {
  2911. visualParams = AvatarAppearance.GetDefaultVisualParams();
  2912. wearables = AvatarWearable.DefaultWearables;
  2913. }
  2914. #endregion
  2915. public void RegionHandleRequest(IClientAPI client, UUID regionID)
  2916. {
  2917. RegionInfo info;
  2918. if (regionID == RegionInfo.RegionID)
  2919. info = RegionInfo;
  2920. else
  2921. info = CommsManager.GridService.RequestNeighbourInfo(regionID);
  2922. if (info != null)
  2923. client.SendRegionHandle(regionID, info.RegionHandle);
  2924. }
  2925. public void TerrainUnAcked(IClientAPI client, int patchX, int patchY)
  2926. {
  2927. //m_log.Debug("Terrain packet unacked, resending patch: " + patchX + " , " + patchY);
  2928. client.SendLayerData(patchX, patchY, Heightmap.GetFloatsSerialised());
  2929. }
  2930. public void SetRootAgentScene(UUID agentID)
  2931. {
  2932. IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  2933. if (inv == null)
  2934. return;
  2935. inv.SetRootAgentScene(agentID, this);
  2936. EventManager.TriggerSetRootAgentScene(agentID, this);
  2937. }
  2938. public bool NeedSceneCacheClear(UUID agentID)
  2939. {
  2940. IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  2941. if (inv == null)
  2942. return true;
  2943. return inv.NeedSceneCacheClear(agentID, this);
  2944. }
  2945. public void ObjectSaleInfo(IClientAPI client, UUID agentID, UUID sessionID, uint localID, byte saleType, int salePrice)
  2946. {
  2947. SceneObjectPart part = GetSceneObjectPart(localID);
  2948. if (part == null || part.ParentGroup == null)
  2949. return;
  2950. if (part.ParentGroup.IsDeleted)
  2951. return;
  2952. part = part.ParentGroup.RootPart;
  2953. part.ObjectSaleType = saleType;
  2954. part.SalePrice = salePrice;
  2955. part.ParentGroup.HasGroupChanged = true;
  2956. part.GetProperties(client);
  2957. }
  2958. public bool PerformObjectBuy(IClientAPI remoteClient, UUID categoryID,
  2959. uint localID, byte saleType)
  2960. {
  2961. SceneObjectPart part = GetSceneObjectPart(localID);
  2962. if (part == null)
  2963. return false;
  2964. if (part.ParentGroup == null)
  2965. return false;
  2966. SceneObjectGroup group = part.ParentGroup;
  2967. switch (saleType)
  2968. {
  2969. case 1: // Sell as original (in-place sale)
  2970. uint effectivePerms=group.GetEffectivePermissions();
  2971. if ((effectivePerms & (uint)PermissionMask.Transfer) == 0)
  2972. {
  2973. m_dialogModule.SendAlertToUser(remoteClient, "This item doesn't appear to be for sale");
  2974. return false;
  2975. }
  2976. group.SetOwnerId(remoteClient.AgentId);
  2977. group.SetRootPartOwner(part, remoteClient.AgentId,
  2978. remoteClient.ActiveGroupId);
  2979. List<SceneObjectPart> partList =
  2980. new List<SceneObjectPart>(group.Children.Values);
  2981. if (Permissions.PropagatePermissions())
  2982. {
  2983. foreach (SceneObjectPart child in partList)
  2984. {
  2985. child.Inventory.ChangeInventoryOwner(remoteClient.AgentId);
  2986. child.ApplyNextOwnerPermissions();
  2987. }
  2988. }
  2989. part.ObjectSaleType = 0;
  2990. part.SalePrice = 10;
  2991. group.HasGroupChanged = true;
  2992. part.GetProperties(remoteClient);
  2993. part.ScheduleFullUpdate();
  2994. break;
  2995. case 2: // Sell a copy
  2996. string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(group);
  2997. CachedUserInfo userInfo =
  2998. CommsManager.UserProfileCacheService.GetUserDetails(remoteClient.AgentId);
  2999. if (userInfo != null)
  3000. {
  3001. uint perms=group.GetEffectivePermissions();
  3002. if ((perms & (uint)PermissionMask.Transfer) == 0)
  3003. {
  3004. m_dialogModule.SendAlertToUser(remoteClient, "This item doesn't appear to be for sale");
  3005. return false;
  3006. }
  3007. AssetBase asset = CreateAsset(
  3008. group.GetPartName(localID),
  3009. group.GetPartDescription(localID),
  3010. (sbyte)AssetType.Object,
  3011. Utils.StringToBytes(sceneObjectXml));
  3012. AssetService.Store(asset);
  3013. InventoryItemBase item = new InventoryItemBase();
  3014. item.CreatorId = part.CreatorID.ToString();
  3015. item.ID = UUID.Random();
  3016. item.Owner = remoteClient.AgentId;
  3017. item.AssetID = asset.FullID;
  3018. item.Description = asset.Description;
  3019. item.Name = asset.Name;
  3020. item.AssetType = asset.Type;
  3021. item.InvType = (int)InventoryType.Object;
  3022. item.Folder = categoryID;
  3023. uint nextPerms=(perms & 7) << 13;
  3024. if ((nextPerms & (uint)PermissionMask.Copy) == 0)
  3025. perms &= ~(uint)PermissionMask.Copy;
  3026. if ((nextPerms & (uint)PermissionMask.Transfer) == 0)
  3027. perms &= ~(uint)PermissionMask.Transfer;
  3028. if ((nextPerms & (uint)PermissionMask.Modify) == 0)
  3029. perms &= ~(uint)PermissionMask.Modify;
  3030. item.BasePermissions = perms & part.NextOwnerMask;
  3031. item.CurrentPermissions = perms & part.NextOwnerMask;
  3032. item.NextPermissions = part.NextOwnerMask;
  3033. item.EveryOnePermissions = part.EveryoneMask &
  3034. part.NextOwnerMask;
  3035. item.GroupPermissions = part.GroupMask &
  3036. part.NextOwnerMask;
  3037. item.CurrentPermissions |= 8; // Slam!
  3038. item.CreationDate = Util.UnixTimeSinceEpoch();
  3039. userInfo.AddItem(item);
  3040. remoteClient.SendInventoryItemCreateUpdate(item, 0);
  3041. }
  3042. else
  3043. {
  3044. m_dialogModule.SendAlertToUser(remoteClient, "Cannot buy now. Your inventory is unavailable");
  3045. return false;
  3046. }
  3047. break;
  3048. case 3: // Sell contents
  3049. List<UUID> invList = part.Inventory.GetInventoryList();
  3050. bool okToSell = true;
  3051. foreach (UUID invID in invList)
  3052. {
  3053. TaskInventoryItem item = part.Inventory.GetInventoryItem(invID);
  3054. if ((item.CurrentPermissions &
  3055. (uint)PermissionMask.Transfer) == 0)
  3056. {
  3057. okToSell = false;
  3058. break;
  3059. }
  3060. }
  3061. if (!okToSell)
  3062. {
  3063. m_dialogModule.SendAlertToUser(
  3064. remoteClient, "This item's inventory doesn't appear to be for sale");
  3065. return false;
  3066. }
  3067. if (invList.Count > 0)
  3068. MoveTaskInventoryItems(remoteClient.AgentId, part.Name,
  3069. part, invList);
  3070. break;
  3071. }
  3072. return true;
  3073. }
  3074. public void CleanTempObjects()
  3075. {
  3076. List<EntityBase> objs = GetEntities();
  3077. foreach (EntityBase obj in objs)
  3078. {
  3079. if (obj is SceneObjectGroup)
  3080. {
  3081. SceneObjectGroup grp = (SceneObjectGroup)obj;
  3082. if (!grp.IsDeleted)
  3083. {
  3084. if ((grp.RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
  3085. {
  3086. if (grp.RootPart.Expires <= DateTime.Now)
  3087. DeleteSceneObject(grp, false);
  3088. }
  3089. }
  3090. }
  3091. }
  3092. }
  3093. public void DeleteFromStorage(UUID uuid)
  3094. {
  3095. m_storageManager.DataStore.RemoveObject(uuid, m_regInfo.RegionID);
  3096. }
  3097. public int GetHealth()
  3098. {
  3099. // Returns:
  3100. // 1 = sim is up and accepting http requests. The heartbeat has
  3101. // stopped and the sim is probably locked up, but a remote
  3102. // admin restart may succeed
  3103. //
  3104. // 2 = Sim is up and the heartbeat is running. The sim is likely
  3105. // usable for people within and logins _may_ work
  3106. //
  3107. // 3 = We have seen a new user enter within the past 4 minutes
  3108. // which can be seen as positive confirmation of sim health
  3109. //
  3110. int health=1; // Start at 1, means we're up
  3111. if ((Environment.TickCount - m_lastUpdate) < 1000)
  3112. health+=1;
  3113. else
  3114. return health;
  3115. // A login in the last 4 mins? We can't be doing too badly
  3116. //
  3117. if ((Environment.TickCount - m_LastLogin) < 240000)
  3118. health++;
  3119. else
  3120. return health;
  3121. return health;
  3122. }
  3123. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  3124. // update non-physical objects like the joint proxy objects that represent the position
  3125. // of the joints in the scene.
  3126. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  3127. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  3128. // from within the OdePhysicsScene.
  3129. protected internal void jointMoved(PhysicsJoint joint)
  3130. {
  3131. // m_parentScene.PhysicsScene.DumpJointInfo(); // non-thread-locked version; we should already be in a lock (OdeLock) when this callback is invoked
  3132. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  3133. if (jointProxyObject == null)
  3134. {
  3135. jointErrorMessage(joint, "WARNING, joint proxy not found, name " + joint.ObjectNameInScene);
  3136. return;
  3137. }
  3138. // now update the joint proxy object in the scene to have the position of the joint as returned by the physics engine
  3139. SceneObjectPart trackedBody = GetSceneObjectPart(joint.TrackedBodyName); // FIXME: causes a sequential lookup
  3140. if (trackedBody == null) return; // the actor may have been deleted but the joint still lingers around a few frames waiting for deletion. during this time, trackedBody is NULL to prevent further motion of the joint proxy.
  3141. jointProxyObject.Velocity = trackedBody.Velocity;
  3142. jointProxyObject.RotationalVelocity = trackedBody.RotationalVelocity;
  3143. switch (joint.Type)
  3144. {
  3145. case PhysicsJointType.Ball:
  3146. {
  3147. PhysicsVector jointAnchor = PhysicsScene.GetJointAnchor(joint);
  3148. Vector3 proxyPos = new Vector3(jointAnchor.X, jointAnchor.Y, jointAnchor.Z);
  3149. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  3150. }
  3151. break;
  3152. case PhysicsJointType.Hinge:
  3153. {
  3154. PhysicsVector jointAnchor = PhysicsScene.GetJointAnchor(joint);
  3155. // Normally, we would just ask the physics scene to return the axis for the joint.
  3156. // Unfortunately, ODE sometimes returns <0,0,0> for the joint axis, which should
  3157. // never occur. Therefore we cannot rely on ODE to always return a correct joint axis.
  3158. // Therefore the following call does not always work:
  3159. //PhysicsVector phyJointAxis = _PhyScene.GetJointAxis(joint);
  3160. // instead we compute the joint orientation by saving the original joint orientation
  3161. // relative to one of the jointed bodies, and applying this transformation
  3162. // to the current position of the jointed bodies (the tracked body) to compute the
  3163. // current joint orientation.
  3164. if (joint.TrackedBodyName == null)
  3165. {
  3166. jointErrorMessage(joint, "joint.TrackedBodyName is null, joint " + joint.ObjectNameInScene);
  3167. }
  3168. Vector3 proxyPos = new Vector3(jointAnchor.X, jointAnchor.Y, jointAnchor.Z);
  3169. Quaternion q = trackedBody.RotationOffset * joint.LocalRotation;
  3170. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  3171. jointProxyObject.ParentGroup.UpdateGroupRotation(q); // schedules the entire group for a terse update
  3172. }
  3173. break;
  3174. }
  3175. }
  3176. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  3177. // update non-physical objects like the joint proxy objects that represent the position
  3178. // of the joints in the scene.
  3179. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  3180. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  3181. // from within the OdePhysicsScene.
  3182. protected internal void jointDeactivated(PhysicsJoint joint)
  3183. {
  3184. //m_log.Debug("[NINJA] SceneGraph.jointDeactivated, joint:" + joint.ObjectNameInScene);
  3185. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  3186. if (jointProxyObject == null)
  3187. {
  3188. jointErrorMessage(joint, "WARNING, trying to deactivate (stop interpolation of) joint proxy, but not found, name " + joint.ObjectNameInScene);
  3189. return;
  3190. }
  3191. // turn the proxy non-physical, which also stops its client-side interpolation
  3192. bool wasUsingPhysics = ((jointProxyObject.ObjectFlags & (uint)PrimFlags.Physics) != 0);
  3193. if (wasUsingPhysics)
  3194. {
  3195. jointProxyObject.UpdatePrimFlags(false, false, true, false); // FIXME: possible deadlock here; check to make sure all the scene alterations set into motion here won't deadlock
  3196. }
  3197. }
  3198. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  3199. // alert the user of errors by using the debug channel in the same way that scripts alert
  3200. // the user of compile errors.
  3201. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  3202. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  3203. // from within the OdePhysicsScene.
  3204. public void jointErrorMessage(PhysicsJoint joint, string message)
  3205. {
  3206. if (joint != null)
  3207. {
  3208. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  3209. return;
  3210. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  3211. if (jointProxyObject != null)
  3212. {
  3213. SimChat(Utils.StringToBytes("[NINJA]: " + message),
  3214. ChatTypeEnum.DebugChannel,
  3215. 2147483647,
  3216. jointProxyObject.AbsolutePosition,
  3217. jointProxyObject.Name,
  3218. jointProxyObject.UUID,
  3219. false);
  3220. joint.ErrorMessageCount++;
  3221. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  3222. {
  3223. SimChat(Utils.StringToBytes("[NINJA]: Too many messages for this joint, suppressing further messages."),
  3224. ChatTypeEnum.DebugChannel,
  3225. 2147483647,
  3226. jointProxyObject.AbsolutePosition,
  3227. jointProxyObject.Name,
  3228. jointProxyObject.UUID,
  3229. false);
  3230. }
  3231. }
  3232. else
  3233. {
  3234. // couldn't find the joint proxy object; the error message is silently suppressed
  3235. }
  3236. }
  3237. }
  3238. public Scene ConsoleScene()
  3239. {
  3240. if (MainConsole.Instance == null)
  3241. return null;
  3242. if (MainConsole.Instance.ConsoleScene is Scene)
  3243. return (Scene)MainConsole.Instance.ConsoleScene;
  3244. return null;
  3245. }
  3246. public float GetGroundHeight(float x, float y)
  3247. {
  3248. if (x < 0)
  3249. x = 0;
  3250. if (x >= Heightmap.Width)
  3251. x = Heightmap.Width - 1;
  3252. if (y < 0)
  3253. y = 0;
  3254. if (y >= Heightmap.Height)
  3255. y = Heightmap.Height - 1;
  3256. Vector3 p0 = new Vector3(x, y, (float)Heightmap[(int)x, (int)y]);
  3257. Vector3 p1 = new Vector3(p0);
  3258. Vector3 p2 = new Vector3(p0);
  3259. p1.X += 1.0f;
  3260. if (p1.X < Heightmap.Width)
  3261. p1.Z = (float)Heightmap[(int)p1.X, (int)p1.Y];
  3262. p2.Y += 1.0f;
  3263. if (p2.Y < Heightmap.Height)
  3264. p2.Z = (float)Heightmap[(int)p2.X, (int)p2.Y];
  3265. Vector3 v0 = new Vector3(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);
  3266. Vector3 v1 = new Vector3(p2.X - p0.X, p2.Y - p0.Y, p2.Z - p0.Z);
  3267. v0.Normalize();
  3268. v1.Normalize();
  3269. Vector3 vsn = new Vector3();
  3270. vsn.X = (v0.Y * v1.Z) - (v0.Z * v1.Y);
  3271. vsn.Y = (v0.Z * v1.X) - (v0.X * v1.Z);
  3272. vsn.Z = (v0.X * v1.Y) - (v0.Y * v1.X);
  3273. vsn.Normalize();
  3274. float xdiff = x - (float)((int)x);
  3275. float ydiff = y - (float)((int)y);
  3276. return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + p0.Z;
  3277. }
  3278. }
  3279. }