Scene.cs 204 KB

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