ScenePresence.cs 196 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the 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.Xml;
  29. using System.Collections.Generic;
  30. using System.Reflection;
  31. using System.Threading;
  32. using System.Timers;
  33. using Timer = System.Timers.Timer;
  34. using OpenMetaverse;
  35. using log4net;
  36. using Nini.Config;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Client;
  39. using OpenSim.Region.Framework.Interfaces;
  40. using OpenSim.Region.Framework.Scenes.Animation;
  41. using OpenSim.Region.Framework.Scenes.Types;
  42. using OpenSim.Region.Physics.Manager;
  43. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  44. using OpenSim.Services.Interfaces;
  45. using TeleportFlags = OpenSim.Framework.Constants.TeleportFlags;
  46. namespace OpenSim.Region.Framework.Scenes
  47. {
  48. [Flags]
  49. enum ScriptControlled : uint
  50. {
  51. CONTROL_ZERO = 0,
  52. CONTROL_FWD = 1,
  53. CONTROL_BACK = 2,
  54. CONTROL_LEFT = 4,
  55. CONTROL_RIGHT = 8,
  56. CONTROL_UP = 16,
  57. CONTROL_DOWN = 32,
  58. CONTROL_ROT_LEFT = 256,
  59. CONTROL_ROT_RIGHT = 512,
  60. CONTROL_LBUTTON = 268435456,
  61. CONTROL_ML_LBUTTON = 1073741824
  62. }
  63. struct ScriptControllers
  64. {
  65. public UUID objectID;
  66. public UUID itemID;
  67. public ScriptControlled ignoreControls;
  68. public ScriptControlled eventControls;
  69. }
  70. public delegate void SendCoarseLocationsMethod(UUID scene, ScenePresence presence, List<Vector3> coarseLocations, List<UUID> avatarUUIDs);
  71. public class ScenePresence : EntityBase, IScenePresence
  72. {
  73. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  74. private static readonly String LogHeader = "[SCENE PRESENCE]";
  75. // ~ScenePresence()
  76. // {
  77. // m_log.DebugFormat("[SCENE PRESENCE]: Destructor called on {0}", Name);
  78. // }
  79. public void TriggerScenePresenceUpdated()
  80. {
  81. if (m_scene != null)
  82. m_scene.EventManager.TriggerScenePresenceUpdated(this);
  83. }
  84. public PresenceType PresenceType { get; private set; }
  85. private ScenePresenceStateMachine m_stateMachine;
  86. /// <summary>
  87. /// The current state of this presence. Governs only the existence lifecycle. See ScenePresenceStateMachine
  88. /// for more details.
  89. /// </summary>
  90. public ScenePresenceState LifecycleState
  91. {
  92. get
  93. {
  94. return m_stateMachine.GetState();
  95. }
  96. set
  97. {
  98. m_stateMachine.SetState(value);
  99. }
  100. }
  101. /// <summary>
  102. /// This exists to prevent race conditions between two CompleteMovement threads if the simulator is slow and
  103. /// the viewer fires these in quick succession.
  104. /// </summary>
  105. /// <remarks>
  106. /// TODO: The child -> agent transition should be folded into LifecycleState and the CompleteMovement
  107. /// regulation done there.
  108. /// </remarks>
  109. private object m_completeMovementLock = new object();
  110. // private static readonly byte[] DEFAULT_TEXTURE = AvatarAppearance.GetDefaultTexture().GetBytes();
  111. private static readonly Array DIR_CONTROL_FLAGS = Enum.GetValues(typeof(Dir_ControlFlags));
  112. private static readonly Vector3 HEAD_ADJUSTMENT = new Vector3(0f, 0f, 0.3f);
  113. /// <summary>
  114. /// Experimentally determined "fudge factor" to make sit-target positions
  115. /// the same as in SecondLife. Fudge factor was tested for 36 different
  116. /// test cases including prims of type box, sphere, cylinder, and torus,
  117. /// with varying parameters for sit target location, prim size, prim
  118. /// rotation, prim cut, prim twist, prim taper, and prim shear. See mantis
  119. /// issue #1716
  120. /// </summary>
  121. public static readonly Vector3 SIT_TARGET_ADJUSTMENT = new Vector3(0.0f, 0.0f, 0.4f);
  122. /// <summary>
  123. /// Movement updates for agents in neighboring regions are sent directly to clients.
  124. /// This value only affects how often agent positions are sent to neighbor regions
  125. /// for things such as distance-based update prioritization
  126. /// </summary>
  127. public static readonly float SIGNIFICANT_MOVEMENT = 2.0f;
  128. public UUID currentParcelUUID = UUID.Zero;
  129. /// <value>
  130. /// The animator for this avatar
  131. /// </value>
  132. public ScenePresenceAnimator Animator { get; private set; }
  133. /// <summary>
  134. /// Attachments recorded on this avatar.
  135. /// </summary>
  136. /// <remarks>
  137. /// TODO: For some reason, we effectively have a list both here and in Appearance. Need to work out if this is
  138. /// necessary.
  139. /// </remarks>
  140. private List<SceneObjectGroup> m_attachments = new List<SceneObjectGroup>();
  141. public Object AttachmentsSyncLock { get; private set; }
  142. private Dictionary<UUID, ScriptControllers> scriptedcontrols = new Dictionary<UUID, ScriptControllers>();
  143. private ScriptControlled IgnoredControls = ScriptControlled.CONTROL_ZERO;
  144. private ScriptControlled LastCommands = ScriptControlled.CONTROL_ZERO;
  145. private bool MouseDown = false;
  146. // private SceneObjectGroup proxyObjectGroup;
  147. //private SceneObjectPart proxyObjectPart = null;
  148. public Vector3 lastKnownAllowedPosition;
  149. public bool sentMessageAboutRestrictedParcelFlyingDown;
  150. public Vector4 CollisionPlane = Vector4.UnitW;
  151. private Vector3 m_lastPosition;
  152. private Quaternion m_lastRotation;
  153. private Vector3 m_lastVelocity;
  154. private Vector3 m_lastSize = new Vector3(0.45f,0.6f,1.9f);
  155. private bool m_followCamAuto = false;
  156. private Vector3? m_forceToApply;
  157. private int m_userFlags;
  158. public int UserFlags
  159. {
  160. get { return m_userFlags; }
  161. }
  162. // Flying
  163. public bool Flying
  164. {
  165. get { return PhysicsActor != null && PhysicsActor.Flying; }
  166. set { PhysicsActor.Flying = value; }
  167. }
  168. // add for fly velocity control
  169. private bool FlyingOld {get; set;}
  170. public bool WasFlying
  171. {
  172. get; private set;
  173. }
  174. public bool IsColliding
  175. {
  176. get { return PhysicsActor != null && PhysicsActor.IsColliding; }
  177. // We would expect setting IsColliding to be private but it's used by a hack in Scene
  178. set { PhysicsActor.IsColliding = value; }
  179. }
  180. // private int m_lastColCount = -1; //KF: Look for Collision chnages
  181. // private int m_updateCount = 0; //KF: Update Anims for a while
  182. // private static readonly int UPDATE_COUNT = 10; // how many frames to update for
  183. private List<uint> m_lastColliders = new List<uint>();
  184. private TeleportFlags m_teleportFlags;
  185. public TeleportFlags TeleportFlags
  186. {
  187. get { return m_teleportFlags; }
  188. set { m_teleportFlags = value; }
  189. }
  190. private uint m_requestedSitTargetID;
  191. private UUID m_requestedSitTargetUUID;
  192. /// <summary>
  193. /// Are we sitting on the ground?
  194. /// </summary>
  195. public bool SitGround { get; private set; }
  196. private SendCoarseLocationsMethod m_sendCoarseLocationsMethod;
  197. //private Vector3 m_requestedSitOffset = new Vector3();
  198. private Vector3 m_LastFinitePos;
  199. private float m_sitAvatarHeight = 2.0f;
  200. private Vector3 m_lastChildAgentUpdatePosition;
  201. // private Vector3 m_lastChildAgentUpdateCamPosition;
  202. private const int LAND_VELOCITYMAG_MAX = 12;
  203. private const float FLY_ROLL_MAX_RADIANS = 1.1f;
  204. private const float FLY_ROLL_RADIANS_PER_UPDATE = 0.06f;
  205. private const float FLY_ROLL_RESET_RADIANS_PER_UPDATE = 0.02f;
  206. private float m_health = 100f;
  207. protected ulong crossingFromRegion;
  208. private readonly Vector3[] Dir_Vectors = new Vector3[11];
  209. protected Timer m_reprioritization_timer;
  210. protected bool m_reprioritizing;
  211. protected bool m_reprioritization_called;
  212. private Quaternion m_headrotation = Quaternion.Identity;
  213. //PauPaw:Proper PID Controler for autopilot************
  214. public bool MovingToTarget { get; private set; }
  215. public Vector3 MoveToPositionTarget { get; private set; }
  216. /// <summary>
  217. /// Controls whether an avatar automatically moving to a target will land when it gets there (if flying).
  218. /// </summary>
  219. public bool LandAtTarget { get; private set; }
  220. private int m_movementUpdateCount;
  221. private const int NumMovementsBetweenRayCast = 5;
  222. private bool CameraConstraintActive;
  223. //private int m_moveToPositionStateStatus;
  224. //*****************************************************
  225. private bool m_collisionEventFlag = false;
  226. private object m_collisionEventLock = new Object();
  227. private int m_movementAnimationUpdateCounter = 0;
  228. public Vector3 PrevSitOffset { get; set; }
  229. protected AvatarAppearance m_appearance;
  230. public AvatarAppearance Appearance
  231. {
  232. get { return m_appearance; }
  233. set
  234. {
  235. m_appearance = value;
  236. // m_log.DebugFormat("[SCENE PRESENCE]: Set appearance for {0} to {1}", Name, value);
  237. }
  238. }
  239. /// <summary>
  240. /// Copy of the script states while the agent is in transit. This state may
  241. /// need to be placed back in case of transfer fail.
  242. /// </summary>
  243. public List<string> InTransitScriptStates
  244. {
  245. get { return m_InTransitScriptStates; }
  246. private set { m_InTransitScriptStates = value; }
  247. }
  248. private List<string> m_InTransitScriptStates = new List<string>();
  249. /// <summary>
  250. /// Implemented Control Flags
  251. /// </summary>
  252. private enum Dir_ControlFlags
  253. {
  254. DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS,
  255. DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG,
  256. DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS,
  257. DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG,
  258. DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS,
  259. DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG,
  260. DIR_CONTROL_FLAG_FORWARD_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS,
  261. DIR_CONTROL_FLAG_BACKWARD_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG,
  262. DIR_CONTROL_FLAG_LEFT_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS,
  263. DIR_CONTROL_FLAG_RIGHT_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG,
  264. DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG
  265. }
  266. /// <summary>
  267. /// Position at which a significant movement was made
  268. /// </summary>
  269. private Vector3 posLastSignificantMove;
  270. #region For teleports and crossings callbacks
  271. /// <summary>
  272. /// In the V1 teleport protocol, the destination simulator sends ReleaseAgent to this address.
  273. /// </summary>
  274. private string m_callbackURI;
  275. /// <summary>
  276. /// Records the region from which this presence originated, if not from login.
  277. /// </summary>
  278. /// <remarks>
  279. /// Also acts as a signal in the teleport V2 process to release UpdateAgent after a viewer has triggered
  280. /// CompleteMovement and made the previous child agent a root agent.
  281. /// </remarks>
  282. private UUID m_originRegionID;
  283. /// <summary>
  284. /// This object is used as a lock before accessing m_originRegionID to make sure that every thread is seeing
  285. /// the very latest value and not using some cached version. Cannot make m_originRegionID itself volatite as
  286. /// it is a value type.
  287. /// </summary>
  288. private object m_originRegionIDAccessLock = new object();
  289. /// <summary>
  290. /// Used by the entity transfer module to signal when the presence should not be closed because a subsequent
  291. /// teleport is reusing the connection.
  292. /// </summary>
  293. /// <remarks>May be refactored or move somewhere else soon.</remarks>
  294. public bool DoNotCloseAfterTeleport { get; set; }
  295. #endregion
  296. /// <value>
  297. /// Script engines present in the scene
  298. /// </value>
  299. private IScriptModule[] m_scriptEngines;
  300. #region Properties
  301. /// <summary>
  302. /// Physical scene representation of this Avatar.
  303. /// </summary>
  304. public PhysicsActor PhysicsActor { get; private set; }
  305. /// <summary>
  306. /// Record user movement inputs.
  307. /// </summary>
  308. public uint MovementFlag { get; private set; }
  309. /// <summary>
  310. /// Is the agent stop control flag currently active?
  311. /// </summary>
  312. public bool AgentControlStopActive { get; private set; }
  313. private bool m_invulnerable = true;
  314. public bool Invulnerable
  315. {
  316. set { m_invulnerable = value; }
  317. get { return m_invulnerable; }
  318. }
  319. private int m_userLevel;
  320. public int UserLevel
  321. {
  322. get { return m_userLevel; }
  323. private set { m_userLevel = value; }
  324. }
  325. private int m_godLevel;
  326. public int GodLevel
  327. {
  328. get { return m_godLevel; }
  329. private set { m_godLevel = value; }
  330. }
  331. private ulong m_rootRegionHandle;
  332. public ulong RegionHandle
  333. {
  334. get { return m_rootRegionHandle; }
  335. private set { m_rootRegionHandle = value; }
  336. }
  337. #region Client Camera
  338. /// <summary>
  339. /// Position of agent's camera in world (region cordinates)
  340. /// </summary>
  341. protected Vector3 m_lastCameraPosition;
  342. private Vector4 m_lastCameraCollisionPlane = new Vector4(0f, 0f, 0f, 1);
  343. private bool m_doingCamRayCast = false;
  344. public Vector3 CameraPosition { get; set; }
  345. public Quaternion CameraRotation
  346. {
  347. get { return Util.Axes2Rot(CameraAtAxis, CameraLeftAxis, CameraUpAxis); }
  348. }
  349. // Use these three vectors to figure out what the agent is looking at
  350. // Convert it to a Matrix and/or Quaternion
  351. //
  352. public Vector3 CameraAtAxis { get; set; }
  353. public Vector3 CameraLeftAxis { get; set; }
  354. public Vector3 CameraUpAxis { get; set; }
  355. public Vector3 Lookat
  356. {
  357. get
  358. {
  359. Vector3 a = new Vector3(CameraAtAxis.X, CameraAtAxis.Y, 0);
  360. if (a == Vector3.Zero)
  361. return a;
  362. return Util.GetNormalizedVector(a);
  363. }
  364. }
  365. #endregion
  366. public string Firstname { get; private set; }
  367. public string Lastname { get; private set; }
  368. public string Grouptitle { get; set; }
  369. // Agent's Draw distance.
  370. public float DrawDistance { get; set; }
  371. public bool AllowMovement { get; set; }
  372. private bool m_setAlwaysRun;
  373. public bool SetAlwaysRun
  374. {
  375. get
  376. {
  377. if (PhysicsActor != null)
  378. {
  379. return PhysicsActor.SetAlwaysRun;
  380. }
  381. else
  382. {
  383. return m_setAlwaysRun;
  384. }
  385. }
  386. set
  387. {
  388. m_setAlwaysRun = value;
  389. if (PhysicsActor != null)
  390. {
  391. PhysicsActor.SetAlwaysRun = value;
  392. }
  393. }
  394. }
  395. public byte State { get; set; }
  396. private AgentManager.ControlFlags m_AgentControlFlags;
  397. public uint AgentControlFlags
  398. {
  399. get { return (uint)m_AgentControlFlags; }
  400. set { m_AgentControlFlags = (AgentManager.ControlFlags)value; }
  401. }
  402. public IClientAPI ControllingClient { get; set; }
  403. public IClientCore ClientView
  404. {
  405. get { return (IClientCore)ControllingClient; }
  406. }
  407. public UUID COF { get; set; }
  408. // public Vector3 ParentPosition { get; set; }
  409. /// <summary>
  410. /// Position of this avatar relative to the region the avatar is in
  411. /// </summary>
  412. public override Vector3 AbsolutePosition
  413. {
  414. get
  415. {
  416. if (PhysicsActor != null)
  417. {
  418. m_pos = PhysicsActor.Position;
  419. // m_log.DebugFormat(
  420. // "[SCENE PRESENCE]: Set position of {0} in {1} to {2} via getting AbsolutePosition!",
  421. // Name, Scene.Name, m_pos);
  422. }
  423. else
  424. {
  425. // m_log.DebugFormat("[SCENE PRESENCE]: Fetching abs pos where PhysicsActor == null and parent part {0} for {1}", Name, Scene.Name);
  426. // Obtain the correct position of a seated avatar.
  427. // In addition to providing the correct position while
  428. // the avatar is seated, this value will also
  429. // be used as the location to unsit to.
  430. //
  431. // If ParentID is not 0, assume we are a seated avatar
  432. // and we should return the position based on the sittarget
  433. // offset and rotation of the prim we are seated on.
  434. //
  435. // Generally, m_pos will contain the position of the avatar
  436. // in the sim unless the avatar is on a sit target. While
  437. // on a sit target, m_pos will contain the desired offset
  438. // without the parent rotation applied.
  439. SceneObjectPart sitPart = ParentPart;
  440. if (sitPart != null)
  441. return sitPart.AbsolutePosition + (m_pos * sitPart.GetWorldRotation());
  442. }
  443. return m_pos;
  444. }
  445. set
  446. {
  447. // m_log.DebugFormat("[SCENE PRESENCE]: Setting position of {0} to {1} in {2}", Name, value, Scene.Name);
  448. // Util.PrintCallStack();
  449. if (PhysicsActor != null)
  450. {
  451. try
  452. {
  453. PhysicsActor.Position = value;
  454. }
  455. catch (Exception e)
  456. {
  457. m_log.Error("[SCENE PRESENCE]: ABSOLUTE POSITION " + e.Message);
  458. }
  459. }
  460. // Don't update while sitting. The PhysicsActor above is null whilst sitting.
  461. if (ParentID == 0)
  462. m_pos = value;
  463. //m_log.DebugFormat(
  464. // "[ENTITY BASE]: In {0} set AbsolutePosition of {1} to {2}",
  465. // Scene.RegionInfo.RegionName, Name, m_pos);
  466. TriggerScenePresenceUpdated();
  467. }
  468. }
  469. /// <summary>
  470. /// If sitting, returns the offset position from the prim the avatar is sitting on.
  471. /// Otherwise, returns absolute position in the scene.
  472. /// </summary>
  473. public Vector3 OffsetPosition
  474. {
  475. get { return m_pos; }
  476. // Don't remove setter. It's not currently used in core but
  477. // upcoming Avination code needs it.
  478. set
  479. {
  480. // There is no offset position when not seated
  481. if (ParentID == 0)
  482. return;
  483. m_pos = value;
  484. TriggerScenePresenceUpdated();
  485. }
  486. }
  487. /// <summary>
  488. /// Current velocity of the avatar.
  489. /// </summary>
  490. public override Vector3 Velocity
  491. {
  492. get
  493. {
  494. if (PhysicsActor != null)
  495. {
  496. m_velocity = PhysicsActor.Velocity;
  497. // m_log.DebugFormat(
  498. // "[SCENE PRESENCE]: Set velocity {0} for {1} in {2} via getting Velocity!",
  499. // m_velocity, Name, Scene.RegionInfo.RegionName);
  500. }
  501. return m_velocity;
  502. }
  503. set
  504. {
  505. if (PhysicsActor != null)
  506. {
  507. try
  508. {
  509. PhysicsActor.TargetVelocity = value;
  510. }
  511. catch (Exception e)
  512. {
  513. m_log.Error("[SCENE PRESENCE]: VELOCITY " + e.Message);
  514. }
  515. }
  516. m_velocity = value;
  517. // m_log.DebugFormat(
  518. // "[SCENE PRESENCE]: In {0} set velocity of {1} to {2}",
  519. // Scene.RegionInfo.RegionName, Name, m_velocity);
  520. }
  521. }
  522. /*
  523. public override Vector3 AngularVelocity
  524. {
  525. get
  526. {
  527. if (PhysicsActor != null)
  528. {
  529. m_rotationalvelocity = PhysicsActor.RotationalVelocity;
  530. // m_log.DebugFormat(
  531. // "[SCENE PRESENCE]: Set velocity {0} for {1} in {2} via getting Velocity!",
  532. // m_velocity, Name, Scene.RegionInfo.RegionName);
  533. }
  534. return m_rotationalvelocity;
  535. }
  536. }
  537. */
  538. private Quaternion m_bodyRot = Quaternion.Identity;
  539. /// <summary>
  540. /// The rotation of the avatar.
  541. /// </summary>
  542. /// <remarks>
  543. /// If the avatar is not sitting, this is with respect to the world
  544. /// If the avatar is sitting, this is a with respect to the part that it's sitting upon (a local rotation).
  545. /// If you always want the world rotation, use GetWorldRotation()
  546. /// </remarks>
  547. public Quaternion Rotation
  548. {
  549. get
  550. {
  551. return m_bodyRot;
  552. }
  553. set
  554. {
  555. m_bodyRot = value;
  556. if (PhysicsActor != null)
  557. {
  558. try
  559. {
  560. PhysicsActor.Orientation = m_bodyRot;
  561. }
  562. catch (Exception e)
  563. {
  564. m_log.Error("[SCENE PRESENCE]: Orientation " + e.Message);
  565. }
  566. }
  567. // m_log.DebugFormat("[SCENE PRESENCE]: Body rot for {0} set to {1}", Name, m_bodyRot);
  568. }
  569. }
  570. // Used for limited viewer 'fake' user rotations.
  571. private Vector3 m_AngularVelocity = Vector3.Zero;
  572. public Vector3 AngularVelocity
  573. {
  574. get { return m_AngularVelocity; }
  575. }
  576. public bool IsChildAgent { get; set; }
  577. public bool IsLoggingIn { get; set; }
  578. /// <summary>
  579. /// If the avatar is sitting, the local ID of the prim that it's sitting on. If not sitting then zero.
  580. /// </summary>
  581. public uint ParentID { get; set; }
  582. public UUID ParentUUID
  583. {
  584. get { return m_parentUUID; }
  585. set { m_parentUUID = value; }
  586. }
  587. private UUID m_parentUUID = UUID.Zero;
  588. /// <summary>
  589. /// Are we sitting on an object?
  590. /// </summary>
  591. /// <remarks>A more readable way of testing presence sit status than ParentID == 0</remarks>
  592. public bool IsSatOnObject { get { return ParentID != 0; } }
  593. /// <summary>
  594. /// If the avatar is sitting, the prim that it's sitting on. If not sitting then null.
  595. /// </summary>
  596. /// <remarks>
  597. /// If you use this property then you must take a reference since another thread could set it to null.
  598. /// </remarks>
  599. public SceneObjectPart ParentPart { get; set; }
  600. public float Health
  601. {
  602. get { return m_health; }
  603. set { m_health = value; }
  604. }
  605. /// <summary>
  606. /// Gets the world rotation of this presence.
  607. /// </summary>
  608. /// <remarks>
  609. /// Unlike Rotation, this returns the world rotation no matter whether the avatar is sitting on a prim or not.
  610. /// </remarks>
  611. /// <returns></returns>
  612. public Quaternion GetWorldRotation()
  613. {
  614. if (IsSatOnObject)
  615. {
  616. SceneObjectPart sitPart = ParentPart;
  617. if (sitPart != null)
  618. return sitPart.GetWorldRotation() * Rotation;
  619. }
  620. return Rotation;
  621. }
  622. public void AdjustKnownSeeds()
  623. {
  624. Dictionary<ulong, string> seeds;
  625. if (Scene.CapsModule != null)
  626. seeds = Scene.CapsModule.GetChildrenSeeds(UUID);
  627. else
  628. seeds = new Dictionary<ulong, string>();
  629. List<ulong> old = new List<ulong>();
  630. foreach (ulong handle in seeds.Keys)
  631. {
  632. uint x, y;
  633. Util.RegionHandleToRegionLoc(handle, out x, out y);
  634. if (Util.IsOutsideView(DrawDistance, x, Scene.RegionInfo.RegionLocX, y, Scene.RegionInfo.RegionLocY))
  635. {
  636. old.Add(handle);
  637. }
  638. }
  639. DropOldNeighbours(old);
  640. if (Scene.CapsModule != null)
  641. Scene.CapsModule.SetChildrenSeed(UUID, seeds);
  642. KnownRegions = seeds;
  643. //m_log.Debug(" ++++++++++AFTER+++++++++++++ ");
  644. //DumpKnownRegions();
  645. }
  646. public void DumpKnownRegions()
  647. {
  648. m_log.Info("================ KnownRegions "+Scene.RegionInfo.RegionName+" ================");
  649. foreach (KeyValuePair<ulong, string> kvp in KnownRegions)
  650. {
  651. uint x, y;
  652. Util.RegionHandleToRegionLoc(kvp.Key, out x, out y);
  653. m_log.Info(" >> "+x+", "+y+": "+kvp.Value);
  654. }
  655. }
  656. private bool m_mouseLook;
  657. private bool m_leftButtonDown;
  658. private bool m_inTransit;
  659. /// <summary>
  660. /// This signals whether the presence is in transit between neighbouring regions.
  661. /// </summary>
  662. /// <remarks>
  663. /// It is not set when the presence is teleporting or logging in/out directly to a region.
  664. /// </remarks>
  665. public bool IsInTransit
  666. {
  667. get { return m_inTransit; }
  668. set {
  669. if(value)
  670. {
  671. if (Flying)
  672. m_AgentControlFlags |= AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  673. else
  674. m_AgentControlFlags &= ~AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  675. }
  676. m_inTransit = value;
  677. }
  678. }
  679. private float m_speedModifier = 1.0f;
  680. public float SpeedModifier
  681. {
  682. get { return m_speedModifier; }
  683. set { m_speedModifier = value; }
  684. }
  685. /// <summary>
  686. /// Modifier for agent movement if we get an AGENT_CONTROL_STOP whilst walking or running
  687. /// </summary>
  688. /// <remarks>
  689. /// AGENT_CONTRL_STOP comes about if user holds down space key on viewers.
  690. /// </remarks>
  691. private float AgentControlStopSlowWhilstMoving = 0.5f;
  692. private bool m_forceFly;
  693. public bool ForceFly
  694. {
  695. get { return m_forceFly; }
  696. set { m_forceFly = value; }
  697. }
  698. private bool m_flyDisabled;
  699. public bool FlyDisabled
  700. {
  701. get { return m_flyDisabled; }
  702. set { m_flyDisabled = value; }
  703. }
  704. public string Viewer
  705. {
  706. get { return Util.GetViewerName(m_scene.AuthenticateHandler.GetAgentCircuitData(ControllingClient.CircuitCode)); }
  707. }
  708. #endregion
  709. #region Constructor(s)
  710. public ScenePresence(
  711. IClientAPI client, Scene world, AvatarAppearance appearance, PresenceType type)
  712. {
  713. AttachmentsSyncLock = new Object();
  714. AllowMovement = true;
  715. IsChildAgent = true;
  716. IsLoggingIn = false;
  717. m_sendCoarseLocationsMethod = SendCoarseLocationsDefault;
  718. Animator = new ScenePresenceAnimator(this);
  719. PresenceType = type;
  720. DrawDistance = world.DefaultDrawDistance;
  721. RegionHandle = world.RegionInfo.RegionHandle;
  722. ControllingClient = client;
  723. Firstname = ControllingClient.FirstName;
  724. Lastname = ControllingClient.LastName;
  725. m_name = String.Format("{0} {1}", Firstname, Lastname);
  726. m_scene = world;
  727. m_uuid = client.AgentId;
  728. LocalId = m_scene.AllocateLocalId();
  729. UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, m_uuid);
  730. if (account != null)
  731. m_userFlags = account.UserFlags;
  732. else
  733. m_userFlags = 0;
  734. if (account != null)
  735. UserLevel = account.UserLevel;
  736. IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  737. if (gm != null)
  738. Grouptitle = gm.GetGroupTitle(m_uuid);
  739. m_scriptEngines = m_scene.RequestModuleInterfaces<IScriptModule>();
  740. AbsolutePosition = posLastSignificantMove = CameraPosition =
  741. m_lastCameraPosition = ControllingClient.StartPos;
  742. m_reprioritization_timer = new Timer(world.ReprioritizationInterval);
  743. m_reprioritization_timer.Elapsed += new ElapsedEventHandler(Reprioritize);
  744. m_reprioritization_timer.AutoReset = false;
  745. AdjustKnownSeeds();
  746. RegisterToEvents();
  747. SetDirectionVectors();
  748. Appearance = appearance;
  749. m_stateMachine = new ScenePresenceStateMachine(this);
  750. }
  751. private void RegionHeartbeatEnd(Scene scene)
  752. {
  753. if (IsChildAgent)
  754. return;
  755. m_movementAnimationUpdateCounter ++;
  756. if (m_movementAnimationUpdateCounter >= 2)
  757. {
  758. m_movementAnimationUpdateCounter = 0;
  759. if (Animator != null)
  760. {
  761. // If the parentID == 0 we are not sitting
  762. // if !SitGournd then we are not sitting on the ground
  763. // Fairly straightforward, now here comes the twist
  764. // if ParentUUID is NOT UUID.Zero, we are looking to
  765. // be sat on an object that isn't there yet. Should
  766. // be treated as if sat.
  767. if(ParentID == 0 && !SitGround && ParentUUID == UUID.Zero) // skip it if sitting
  768. Animator.UpdateMovementAnimations();
  769. }
  770. else
  771. {
  772. m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
  773. }
  774. }
  775. }
  776. public void RegisterToEvents()
  777. {
  778. ControllingClient.OnCompleteMovementToRegion += CompleteMovement;
  779. ControllingClient.OnAgentUpdate += HandleAgentUpdate;
  780. ControllingClient.OnAgentCameraUpdate += HandleAgentCamerasUpdate;
  781. ControllingClient.OnAgentRequestSit += HandleAgentRequestSit;
  782. ControllingClient.OnAgentSit += HandleAgentSit;
  783. ControllingClient.OnSetAlwaysRun += HandleSetAlwaysRun;
  784. ControllingClient.OnStartAnim += HandleStartAnim;
  785. ControllingClient.OnStopAnim += HandleStopAnim;
  786. ControllingClient.OnForceReleaseControls += HandleForceReleaseControls;
  787. ControllingClient.OnAutoPilotGo += MoveToTarget;
  788. // ControllingClient.OnChildAgentStatus += new StatusChange(this.ChildStatusChange);
  789. // ControllingClient.OnStopMovement += new GenericCall2(this.StopMovement);
  790. }
  791. private void SetDirectionVectors()
  792. {
  793. Dir_Vectors[0] = Vector3.UnitX; //FORWARD
  794. Dir_Vectors[1] = -Vector3.UnitX; //BACK
  795. Dir_Vectors[2] = Vector3.UnitY; //LEFT
  796. Dir_Vectors[3] = -Vector3.UnitY; //RIGHT
  797. Dir_Vectors[4] = Vector3.UnitZ; //UP
  798. Dir_Vectors[5] = -Vector3.UnitZ; //DOWN
  799. Dir_Vectors[6] = new Vector3(0.5f, 0f, 0f); //FORWARD_NUDGE
  800. Dir_Vectors[7] = new Vector3(-0.5f, 0f, 0f); //BACK_NUDGE
  801. Dir_Vectors[8] = new Vector3(0f, 0.5f, 0f); //LEFT_NUDGE
  802. Dir_Vectors[9] = new Vector3(0f, -0.5f, 0f); //RIGHT_NUDGE
  803. Dir_Vectors[10] = new Vector3(0f, 0f, -0.5f); //DOWN_Nudge
  804. }
  805. private Vector3[] GetWalkDirectionVectors()
  806. {
  807. Vector3[] vector = new Vector3[11];
  808. vector[0] = new Vector3(CameraUpAxis.Z, 0f, -CameraAtAxis.Z); //FORWARD
  809. vector[1] = new Vector3(-CameraUpAxis.Z, 0f, CameraAtAxis.Z); //BACK
  810. vector[2] = Vector3.UnitY; //LEFT
  811. vector[3] = -Vector3.UnitY; //RIGHT
  812. vector[4] = new Vector3(CameraAtAxis.Z, 0f, CameraUpAxis.Z); //UP
  813. vector[5] = new Vector3(-CameraAtAxis.Z, 0f, -CameraUpAxis.Z); //DOWN
  814. vector[6] = new Vector3(CameraUpAxis.Z, 0f, -CameraAtAxis.Z); //FORWARD_NUDGE
  815. vector[7] = new Vector3(-CameraUpAxis.Z, 0f, CameraAtAxis.Z); //BACK_NUDGE
  816. vector[8] = Vector3.UnitY; //LEFT_NUDGE
  817. vector[9] = -Vector3.UnitY; //RIGHT_NUDGE
  818. vector[10] = new Vector3(-CameraAtAxis.Z, 0f, -CameraUpAxis.Z); //DOWN_NUDGE
  819. return vector;
  820. }
  821. #endregion
  822. #region Status Methods
  823. /// <summary>
  824. /// Turns a child agent into a root agent.
  825. /// </summary>
  826. /// <remarks>
  827. /// Child agents are logged into neighbouring sims largely to observe changes. Root agents exist when the
  828. /// avatar is actual in the sim. They can perform all actions.
  829. /// This change is made whenever an avatar enters a region, whether by crossing over from a neighbouring sim,
  830. /// teleporting in or on initial login.
  831. ///
  832. /// This method is on the critical path for transferring an avatar from one region to another. Delay here
  833. /// delays that crossing.
  834. /// </remarks>
  835. private bool MakeRootAgent(Vector3 pos, bool isFlying)
  836. {
  837. lock (m_completeMovementLock)
  838. {
  839. if (!IsChildAgent)
  840. return false;
  841. //m_log.DebugFormat("[SCENE]: known regions in {0}: {1}", Scene.RegionInfo.RegionName, KnownChildRegionHandles.Count);
  842. // m_log.InfoFormat(
  843. // "[SCENE]: Upgrading child to root agent for {0} in {1}",
  844. // Name, m_scene.RegionInfo.RegionName);
  845. if (ParentUUID != UUID.Zero)
  846. {
  847. m_log.DebugFormat("[SCENE PRESENCE]: Sitting avatar back on prim {0}", ParentUUID);
  848. SceneObjectPart part = m_scene.GetSceneObjectPart(ParentUUID);
  849. if (part == null)
  850. {
  851. m_log.ErrorFormat("[SCENE PRESENCE]: Can't find prim {0} to sit on", ParentUUID);
  852. }
  853. else
  854. {
  855. part.ParentGroup.AddAvatar(UUID);
  856. if (part.SitTargetPosition != Vector3.Zero)
  857. part.SitTargetAvatar = UUID;
  858. // ParentPosition = part.GetWorldPosition();
  859. ParentID = part.LocalId;
  860. ParentPart = part;
  861. m_pos = PrevSitOffset;
  862. // pos = ParentPosition;
  863. pos = part.GetWorldPosition();
  864. }
  865. ParentUUID = UUID.Zero;
  866. // Animator.TrySetMovementAnimation("SIT");
  867. }
  868. else
  869. {
  870. IsLoggingIn = false;
  871. }
  872. IsChildAgent = false;
  873. }
  874. // Must reset this here so that a teleport to a region next to an existing region does not keep the flag
  875. // set and prevent the close of the connection on a subsequent re-teleport.
  876. // Should not be needed if we are not trying to tell this region to close
  877. // DoNotCloseAfterTeleport = false;
  878. IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  879. if (gm != null)
  880. Grouptitle = gm.GetGroupTitle(m_uuid);
  881. RegionHandle = m_scene.RegionInfo.RegionHandle;
  882. m_scene.EventManager.TriggerSetRootAgentScene(m_uuid, m_scene);
  883. UUID groupUUID = ControllingClient.ActiveGroupId;
  884. string groupName = string.Empty;
  885. ulong groupPowers = 0;
  886. // ----------------------------------
  887. // Previous Agent Difference - AGNI sends an unsolicited AgentDataUpdate upon root agent status
  888. try
  889. {
  890. if (groupUUID != UUID.Zero && gm != null)
  891. {
  892. GroupRecord record = gm.GetGroupRecord(groupUUID);
  893. if (record != null)
  894. groupName = record.GroupName;
  895. GroupMembershipData groupMembershipData = gm.GetMembershipData(groupUUID, m_uuid);
  896. if (groupMembershipData != null)
  897. groupPowers = groupMembershipData.GroupPowers;
  898. }
  899. ControllingClient.SendAgentDataUpdate(
  900. m_uuid, groupUUID, Firstname, Lastname, groupPowers, groupName, Grouptitle);
  901. }
  902. catch (Exception e)
  903. {
  904. m_log.Error("[AGENTUPDATE]: Error ", e);
  905. }
  906. // ------------------------------------
  907. if (ParentID == 0)
  908. {
  909. // Moved this from SendInitialData to ensure that Appearance is initialized
  910. // before the inventory is processed in MakeRootAgent. This fixes a race condition
  911. // related to the handling of attachments
  912. //m_scene.GetAvatarAppearance(ControllingClient, out Appearance);
  913. /* RA 20140111: Commented out these TestBorderCross's.
  914. * Not sure why this code is here. It is not checking all the borders
  915. * and 'in region' sanity checking is done in CheckAndAdjustLandingPoint and below.
  916. if (m_scene.TestBorderCross(pos, Cardinals.E))
  917. {
  918. Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.E);
  919. pos.X = crossedBorder.BorderLine.Z - 1;
  920. }
  921. if (m_scene.TestBorderCross(pos, Cardinals.N))
  922. {
  923. Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.N);
  924. pos.Y = crossedBorder.BorderLine.Z - 1;
  925. }
  926. */
  927. CheckAndAdjustLandingPoint(ref pos);
  928. if (pos.X < 0f || pos.Y < 0f || pos.Z < 0f)
  929. {
  930. m_log.WarnFormat(
  931. "[SCENE PRESENCE]: MakeRootAgent() was given an illegal position of {0} for avatar {1}, {2}. Clamping",
  932. pos, Name, UUID);
  933. if (pos.X < 0f) pos.X = 0f;
  934. if (pos.Y < 0f) pos.Y = 0f;
  935. if (pos.Z < 0f) pos.Z = 0f;
  936. }
  937. float localAVHeight = 1.56f;
  938. if (Appearance.AvatarHeight > 0)
  939. localAVHeight = Appearance.AvatarHeight;
  940. float posZLimit = 0;
  941. if (pos.X < m_scene.RegionInfo.RegionSizeX && pos.Y < m_scene.RegionInfo.RegionSizeY)
  942. posZLimit = (float)m_scene.Heightmap[(int)pos.X, (int)pos.Y];
  943. float newPosZ = posZLimit + localAVHeight / 2;
  944. if (posZLimit >= (pos.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
  945. {
  946. pos.Z = newPosZ;
  947. }
  948. AbsolutePosition = pos;
  949. if (m_teleportFlags == TeleportFlags.Default)
  950. {
  951. Vector3 vel = Velocity;
  952. AddToPhysicalScene(isFlying);
  953. if (PhysicsActor != null)
  954. PhysicsActor.SetMomentum(vel);
  955. }
  956. else
  957. AddToPhysicalScene(isFlying);
  958. // XXX: This is to trigger any secondary teleport needed for a megaregion when the user has teleported to a
  959. // location outside the 'root region' (the south-west 256x256 corner). This is the earlist we can do it
  960. // since it requires a physics actor to be present. If it is left any later, then physics appears to reset
  961. // the value to a negative position which does not trigger the border cross.
  962. // This may not be the best location for this.
  963. CheckForBorderCrossing();
  964. if (ForceFly)
  965. {
  966. Flying = true;
  967. }
  968. else if (FlyDisabled)
  969. {
  970. Flying = false;
  971. }
  972. }
  973. // Don't send an animation pack here, since on a region crossing this will sometimes cause a flying
  974. // avatar to return to the standing position in mid-air. On login it looks like this is being sent
  975. // elsewhere anyway
  976. // Animator.SendAnimPack();
  977. m_scene.SwapRootAgentCount(false);
  978. // The initial login scene presence is already root when it gets here
  979. // and it has already rezzed the attachments and started their scripts.
  980. // We do the following only for non-login agents, because their scripts
  981. // haven't started yet.
  982. if (PresenceType == PresenceType.Npc || (TeleportFlags & TeleportFlags.ViaLogin) != 0)
  983. {
  984. // Viewers which have a current outfit folder will actually rez their own attachments. However,
  985. // viewers without (e.g. v1 viewers) will not, so we still need to make this call.
  986. if (Scene.AttachmentsModule != null)
  987. Util.FireAndForget(
  988. o =>
  989. {
  990. // if (PresenceType != PresenceType.Npc && Util.FireAndForgetMethod != FireAndForgetMethod.None)
  991. // System.Threading.Thread.Sleep(7000);
  992. Scene.AttachmentsModule.RezAttachments(this);
  993. });
  994. }
  995. else
  996. {
  997. // We need to restart scripts here so that they receive the correct changed events (CHANGED_TELEPORT
  998. // and CHANGED_REGION) when the attachments have been rezzed in the new region. This cannot currently
  999. // be done in AttachmentsModule.CopyAttachments(AgentData ad, IScenePresence sp) itself since we are
  1000. // not transporting the required data.
  1001. //
  1002. // We need to restart scripts here so that they receive the correct changed events (CHANGED_TELEPORT
  1003. // and CHANGED_REGION) when the attachments have been rezzed in the new region. This cannot currently
  1004. // be done in AttachmentsModule.CopyAttachments(AgentData ad, IScenePresence sp) itself since we are
  1005. // not transporting the required data.
  1006. //
  1007. // We must take a copy of the attachments list here (rather than locking) to avoid a deadlock where a script in one of
  1008. // the attachments may start processing an event (which locks ScriptInstance.m_Script) that then calls a method here
  1009. // which needs to lock m_attachments. ResumeScripts() needs to take a ScriptInstance.m_Script lock to try to unset the Suspend status.
  1010. //
  1011. // FIXME: In theory, this deadlock should not arise since scripts should not be processing events until ResumeScripts().
  1012. // But XEngine starts all scripts unsuspended. Starting them suspended will not currently work because script rezzing
  1013. // is placed in an asynchronous queue in XEngine and so the ResumeScripts() call will almost certainly execute before the
  1014. // script is rezzed. This means the ResumeScripts() does absolutely nothing when using XEngine.
  1015. //
  1016. // One cannot simply iterate over attachments in a fire and forget thread because this would no longer
  1017. // be locked, allowing race conditions if other code changes the attachments list.
  1018. List<SceneObjectGroup> attachments = GetAttachments();
  1019. if (attachments.Count > 0)
  1020. {
  1021. m_log.DebugFormat(
  1022. "[SCENE PRESENCE]: Restarting scripts in attachments for {0} in {1}", Name, Scene.Name);
  1023. // Resume scripts
  1024. foreach (SceneObjectGroup sog in attachments)
  1025. {
  1026. sog.ScheduleGroupForFullUpdate();
  1027. sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource());
  1028. sog.ResumeScripts();
  1029. }
  1030. }
  1031. }
  1032. SendAvatarDataToAllAgents();
  1033. // send the animations of the other presences to me
  1034. m_scene.ForEachRootScenePresence(delegate(ScenePresence presence)
  1035. {
  1036. if (presence != this)
  1037. presence.Animator.SendAnimPackToClient(ControllingClient);
  1038. });
  1039. // If we don't reset the movement flag here, an avatar that crosses to a neighbouring sim and returns will
  1040. // stall on the border crossing since the existing child agent will still have the last movement
  1041. // recorded, which stops the input from being processed.
  1042. MovementFlag = 0;
  1043. m_scene.EventManager.TriggerOnMakeRootAgent(this);
  1044. return true;
  1045. }
  1046. public int GetStateSource()
  1047. {
  1048. AgentCircuitData aCircuit = m_scene.AuthenticateHandler.GetAgentCircuitData(UUID);
  1049. if (aCircuit != null && (aCircuit.teleportFlags != (uint)TeleportFlags.Default))
  1050. {
  1051. // This will get your attention
  1052. //m_log.Error("[XXX] Triggering CHANGED_TELEPORT");
  1053. return 5; // StateSource.Teleporting
  1054. }
  1055. return 2; // StateSource.PrimCrossing
  1056. }
  1057. /// <summary>
  1058. /// This turns a root agent into a child agent
  1059. /// </summary>
  1060. /// <remarks>
  1061. /// when an agent departs this region for a neighbor, this gets called.
  1062. ///
  1063. /// It doesn't get called for a teleport. Reason being, an agent that
  1064. /// teleports out may not end up anywhere near this region
  1065. /// </remarks>
  1066. public void MakeChildAgent()
  1067. {
  1068. m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
  1069. m_log.DebugFormat("[SCENE PRESENCE]: Making {0} a child agent in {1}", Name, Scene.RegionInfo.RegionName);
  1070. // Reset these so that teleporting in and walking out isn't seen
  1071. // as teleporting back
  1072. TeleportFlags = TeleportFlags.Default;
  1073. MovementFlag = 0;
  1074. // It looks like Animator is set to null somewhere, and MakeChild
  1075. // is called after that. Probably in aborted teleports.
  1076. if (Animator == null)
  1077. Animator = new ScenePresenceAnimator(this);
  1078. else
  1079. Animator.ResetAnimations();
  1080. // m_log.DebugFormat(
  1081. // "[SCENE PRESENCE]: Downgrading root agent {0}, {1} to a child agent in {2}",
  1082. // Name, UUID, m_scene.RegionInfo.RegionName);
  1083. // Don't zero out the velocity since this can cause problems when an avatar is making a region crossing,
  1084. // depending on the exact timing. This shouldn't matter anyway since child agent positions are not updated.
  1085. //Velocity = new Vector3(0, 0, 0);
  1086. IsChildAgent = true;
  1087. m_scene.SwapRootAgentCount(true);
  1088. RemoveFromPhysicalScene();
  1089. ParentID = 0; // Child agents can't be sitting
  1090. // FIXME: Set RegionHandle to the region handle of the scene this agent is moving into
  1091. m_scene.EventManager.TriggerOnMakeChildAgent(this);
  1092. }
  1093. /// <summary>
  1094. /// Removes physics plugin scene representation of this agent if it exists.
  1095. /// </summary>
  1096. public void RemoveFromPhysicalScene()
  1097. {
  1098. if (PhysicsActor != null)
  1099. {
  1100. // PhysicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients;
  1101. PhysicsActor.OnOutOfBounds -= OutOfBoundsCall;
  1102. PhysicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate;
  1103. PhysicsActor.UnSubscribeEvents();
  1104. m_scene.PhysicsScene.RemoveAvatar(PhysicsActor);
  1105. PhysicsActor = null;
  1106. }
  1107. // else
  1108. // {
  1109. // m_log.ErrorFormat(
  1110. // "[SCENE PRESENCE]: Attempt to remove physics actor for {0} on {1} but this scene presence has no physics actor",
  1111. // Name, Scene.RegionInfo.RegionName);
  1112. // }
  1113. }
  1114. /// <summary>
  1115. /// Do not call this directly. Call Scene.RequestTeleportLocation() instead.
  1116. /// </summary>
  1117. /// <param name="pos"></param>
  1118. public void Teleport(Vector3 pos)
  1119. {
  1120. TeleportWithMomentum(pos, Vector3.Zero);
  1121. }
  1122. public void TeleportWithMomentum(Vector3 pos, Vector3? v)
  1123. {
  1124. if (ParentID != (uint)0)
  1125. StandUp();
  1126. bool isFlying = Flying;
  1127. Vector3 vel = Velocity;
  1128. RemoveFromPhysicalScene();
  1129. CheckLandingPoint(ref pos);
  1130. AbsolutePosition = pos;
  1131. AddToPhysicalScene(isFlying);
  1132. if (PhysicsActor != null)
  1133. {
  1134. if (v.HasValue)
  1135. PhysicsActor.SetMomentum((Vector3)v);
  1136. else
  1137. PhysicsActor.SetMomentum(vel);
  1138. }
  1139. }
  1140. public void avnLocalTeleport(Vector3 newpos, Vector3? newvel, bool rotateToVelXY)
  1141. {
  1142. CheckLandingPoint(ref newpos);
  1143. AbsolutePosition = newpos;
  1144. if (newvel.HasValue)
  1145. {
  1146. if ((Vector3)newvel == Vector3.Zero)
  1147. {
  1148. if (PhysicsActor != null)
  1149. PhysicsActor.SetMomentum(Vector3.Zero);
  1150. m_velocity = Vector3.Zero;
  1151. }
  1152. else
  1153. {
  1154. if (PhysicsActor != null)
  1155. PhysicsActor.SetMomentum((Vector3)newvel);
  1156. m_velocity = (Vector3)newvel;
  1157. if (rotateToVelXY)
  1158. {
  1159. Vector3 lookAt = (Vector3)newvel;
  1160. lookAt.Z = 0;
  1161. lookAt.Normalize();
  1162. ControllingClient.SendLocalTeleport(newpos, lookAt, (uint)TeleportFlags.ViaLocation);
  1163. return;
  1164. }
  1165. }
  1166. }
  1167. }
  1168. public void StopFlying()
  1169. {
  1170. Vector3 pos = AbsolutePosition;
  1171. if (Appearance.AvatarHeight != 127.0f)
  1172. pos += new Vector3(0f, 0f, (Appearance.AvatarHeight / 6f));
  1173. else
  1174. pos += new Vector3(0f, 0f, (1.56f / 6f));
  1175. AbsolutePosition = pos;
  1176. // attach a suitable collision plane regardless of the actual situation to force the LLClient to land.
  1177. // Collision plane below the avatar's position a 6th of the avatar's height is suitable.
  1178. // Mind you, that this method doesn't get called if the avatar's velocity magnitude is greater then a
  1179. // certain amount.. because the LLClient wouldn't land in that situation anyway.
  1180. // why are we still testing for this really old height value default???
  1181. if (Appearance.AvatarHeight != 127.0f)
  1182. CollisionPlane = new Vector4(0, 0, 0, pos.Z - Appearance.AvatarHeight / 6f);
  1183. else
  1184. CollisionPlane = new Vector4(0, 0, 0, pos.Z - (1.56f / 6f));
  1185. ControllingClient.SendAgentTerseUpdate(this);
  1186. }
  1187. /// <summary>
  1188. /// Applies a roll accumulator to the avatar's angular velocity for the avatar fly roll effect.
  1189. /// </summary>
  1190. /// <param name="amount">Postive or negative roll amount in radians</param>
  1191. private void ApplyFlyingRoll(float amount, bool PressingUp, bool PressingDown)
  1192. {
  1193. float rollAmount = Util.Clamp(m_AngularVelocity.Z + amount, -FLY_ROLL_MAX_RADIANS, FLY_ROLL_MAX_RADIANS);
  1194. m_AngularVelocity.Z = rollAmount;
  1195. // APPLY EXTRA consideration for flying up and flying down during this time.
  1196. // if we're turning left
  1197. if (amount > 0)
  1198. {
  1199. // If we're at the max roll and pressing up, we want to swing BACK a bit
  1200. // Automatically adds noise
  1201. if (PressingUp)
  1202. {
  1203. if (m_AngularVelocity.Z >= FLY_ROLL_MAX_RADIANS - 0.04f)
  1204. m_AngularVelocity.Z -= 0.9f;
  1205. }
  1206. // If we're at the max roll and pressing down, we want to swing MORE a bit
  1207. if (PressingDown)
  1208. {
  1209. if (m_AngularVelocity.Z >= FLY_ROLL_MAX_RADIANS && m_AngularVelocity.Z < FLY_ROLL_MAX_RADIANS + 0.6f)
  1210. m_AngularVelocity.Z += 0.6f;
  1211. }
  1212. }
  1213. else // we're turning right.
  1214. {
  1215. // If we're at the max roll and pressing up, we want to swing BACK a bit
  1216. // Automatically adds noise
  1217. if (PressingUp)
  1218. {
  1219. if (m_AngularVelocity.Z <= (-FLY_ROLL_MAX_RADIANS))
  1220. m_AngularVelocity.Z += 0.6f;
  1221. }
  1222. // If we're at the max roll and pressing down, we want to swing MORE a bit
  1223. if (PressingDown)
  1224. {
  1225. if (m_AngularVelocity.Z >= -FLY_ROLL_MAX_RADIANS - 0.6f)
  1226. m_AngularVelocity.Z -= 0.6f;
  1227. }
  1228. }
  1229. }
  1230. /// <summary>
  1231. /// incrementally sets roll amount to zero
  1232. /// </summary>
  1233. /// <param name="amount">Positive roll amount in radians</param>
  1234. /// <returns></returns>
  1235. private float CalculateFlyingRollResetToZero(float amount)
  1236. {
  1237. const float rollMinRadians = 0f;
  1238. if (m_AngularVelocity.Z > 0)
  1239. {
  1240. float leftOverToMin = m_AngularVelocity.Z - rollMinRadians;
  1241. if (amount > leftOverToMin)
  1242. return -leftOverToMin;
  1243. else
  1244. return -amount;
  1245. }
  1246. else
  1247. {
  1248. float leftOverToMin = -m_AngularVelocity.Z - rollMinRadians;
  1249. if (amount > leftOverToMin)
  1250. return leftOverToMin;
  1251. else
  1252. return amount;
  1253. }
  1254. }
  1255. // neighbouring regions we have enabled a child agent in
  1256. // holds the seed cap for the child agent in that region
  1257. private Dictionary<ulong, string> m_knownChildRegions = new Dictionary<ulong, string>();
  1258. public void AddNeighbourRegion(ulong regionHandle, string cap)
  1259. {
  1260. lock (m_knownChildRegions)
  1261. {
  1262. if (!m_knownChildRegions.ContainsKey(regionHandle))
  1263. {
  1264. uint x, y;
  1265. Utils.LongToUInts(regionHandle, out x, out y);
  1266. m_knownChildRegions.Add(regionHandle, cap);
  1267. }
  1268. }
  1269. }
  1270. public void RemoveNeighbourRegion(ulong regionHandle)
  1271. {
  1272. lock (m_knownChildRegions)
  1273. {
  1274. // Checking ContainsKey is redundant as Remove works either way and returns a bool
  1275. // This is here to allow the Debug output to be conditional on removal
  1276. //if (m_knownChildRegions.ContainsKey(regionHandle))
  1277. // m_log.DebugFormat(" !!! removing known region {0} in {1}. Count = {2}", regionHandle, Scene.RegionInfo.RegionName, m_knownChildRegions.Count);
  1278. m_knownChildRegions.Remove(regionHandle);
  1279. }
  1280. }
  1281. public void DropOldNeighbours(List<ulong> oldRegions)
  1282. {
  1283. foreach (ulong handle in oldRegions)
  1284. {
  1285. RemoveNeighbourRegion(handle);
  1286. Scene.CapsModule.DropChildSeed(UUID, handle);
  1287. }
  1288. }
  1289. public Dictionary<ulong, string> KnownRegions
  1290. {
  1291. get
  1292. {
  1293. lock (m_knownChildRegions)
  1294. return new Dictionary<ulong, string>(m_knownChildRegions);
  1295. }
  1296. set
  1297. {
  1298. // Replacing the reference is atomic but we still need to lock on
  1299. // the original dictionary object which may be in use elsewhere
  1300. lock (m_knownChildRegions)
  1301. m_knownChildRegions = value;
  1302. }
  1303. }
  1304. public List<ulong> KnownRegionHandles
  1305. {
  1306. get
  1307. {
  1308. return new List<ulong>(KnownRegions.Keys);
  1309. }
  1310. }
  1311. public int KnownRegionCount
  1312. {
  1313. get
  1314. {
  1315. lock (m_knownChildRegions)
  1316. return m_knownChildRegions.Count;
  1317. }
  1318. }
  1319. #endregion
  1320. #region Event Handlers
  1321. /// <summary>
  1322. /// Sets avatar height in the physics plugin
  1323. /// </summary>
  1324. /// <param name="height">New height of avatar</param>
  1325. public void SetHeight(float height)
  1326. {
  1327. if (PhysicsActor != null && !IsChildAgent)
  1328. PhysicsActor.Size = new Vector3(0.45f, 0.6f, height);
  1329. }
  1330. public void SetSize(Vector3 size, float feetoffset)
  1331. {
  1332. // TODO: Merge the physics bits
  1333. // if (PhysicsActor != null && !IsChildAgent)
  1334. // PhysicsActor.setAvatarSize(size, feetoffset);
  1335. }
  1336. private bool WaitForUpdateAgent(IClientAPI client)
  1337. {
  1338. // Before the source region executes UpdateAgent
  1339. // (which triggers Scene.IncomingUpdateChildAgent(AgentData cAgentData) here in the destination,
  1340. // m_originRegionID is UUID.Zero; after, it's non-Zero. The CompleteMovement sequence initiated from the
  1341. // viewer (in turn triggered by the source region sending it a TeleportFinish event) waits until it's non-zero
  1342. int count = 50;
  1343. UUID originID;
  1344. lock (m_originRegionIDAccessLock)
  1345. originID = m_originRegionID;
  1346. while (originID.Equals(UUID.Zero) && count-- > 0)
  1347. {
  1348. lock (m_originRegionIDAccessLock)
  1349. originID = m_originRegionID;
  1350. m_log.DebugFormat("[SCENE PRESENCE]: Agent {0} waiting for update in {1}", client.Name, Scene.Name);
  1351. Thread.Sleep(200);
  1352. }
  1353. if (originID.Equals(UUID.Zero))
  1354. {
  1355. // Movement into region will fail
  1356. m_log.WarnFormat("[SCENE PRESENCE]: Update agent {0} never arrived in {1}", client.Name, Scene.Name);
  1357. return false;
  1358. }
  1359. return true;
  1360. }
  1361. /// <summary>
  1362. /// Complete Avatar's movement into the region.
  1363. /// </summary>
  1364. /// <param name="client"></param>
  1365. /// <param name="openChildAgents">
  1366. /// If true, send notification to neighbour regions to expect
  1367. /// a child agent from the client. These neighbours can be some distance away, depending right now on the
  1368. /// configuration of DefaultDrawDistance in the [Startup] section of config
  1369. /// </param>
  1370. public void CompleteMovement(IClientAPI client, bool openChildAgents)
  1371. {
  1372. // DateTime startTime = DateTime.Now;
  1373. m_log.InfoFormat(
  1374. "[SCENE PRESENCE]: Completing movement of {0} into region {1} in position {2}",
  1375. client.Name, Scene.Name, AbsolutePosition);
  1376. // Make sure it's not a login agent. We don't want to wait for updates during login
  1377. if (PresenceType != PresenceType.Npc && (m_teleportFlags & TeleportFlags.ViaLogin) == 0)
  1378. {
  1379. // Let's wait until UpdateAgent (called by departing region) is done
  1380. if (!WaitForUpdateAgent(client))
  1381. // The sending region never sent the UpdateAgent data, we have to refuse
  1382. return;
  1383. }
  1384. Vector3 look = Velocity;
  1385. // if ((look.X == 0) && (look.Y == 0) && (look.Z == 0))
  1386. if ((Math.Abs(look.X) < 0.1) && (Math.Abs(look.Y) < 0.1) && (Math.Abs(look.Z) < 0.1))
  1387. {
  1388. look = new Vector3(0.99f, 0.042f, 0);
  1389. }
  1390. // Prevent teleporting to an underground location
  1391. // (may crash client otherwise)
  1392. //
  1393. Vector3 pos = AbsolutePosition;
  1394. float ground = m_scene.GetGroundHeight(pos.X, pos.Y);
  1395. if (pos.Z < ground + 1.5f)
  1396. {
  1397. pos.Z = ground + 1.5f;
  1398. AbsolutePosition = pos;
  1399. }
  1400. bool flying = ((m_AgentControlFlags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  1401. if (!MakeRootAgent(AbsolutePosition, flying))
  1402. {
  1403. m_log.DebugFormat(
  1404. "[SCENE PRESENCE]: Aborting CompleteMovement call for {0} in {1} as they are already root",
  1405. Name, Scene.Name);
  1406. return;
  1407. }
  1408. // Tell the client that we're totally ready
  1409. ControllingClient.MoveAgentIntoRegion(m_scene.RegionInfo, AbsolutePosition, look);
  1410. // Remember in HandleUseCircuitCode, we delayed this to here
  1411. if (m_teleportFlags > 0)
  1412. SendInitialDataToMe();
  1413. // m_log.DebugFormat("[SCENE PRESENCE] Completed movement");
  1414. if (!string.IsNullOrEmpty(m_callbackURI))
  1415. {
  1416. // We cannot sleep here since this would hold up the inbound packet processing thread, as
  1417. // CompleteMovement() is executed synchronously. However, it might be better to delay the release
  1418. // here until we know for sure that the agent is active in this region. Sending AgentMovementComplete
  1419. // is not enough for Imprudence clients - there appears to be a small delay (<200ms, <500ms) until they regard this
  1420. // region as the current region, meaning that a close sent before then will fail the teleport.
  1421. // System.Threading.Thread.Sleep(2000);
  1422. m_log.DebugFormat(
  1423. "[SCENE PRESENCE]: Releasing {0} {1} with callback to {2}",
  1424. client.Name, client.AgentId, m_callbackURI);
  1425. UUID originID;
  1426. lock (m_originRegionIDAccessLock)
  1427. originID = m_originRegionID;
  1428. Scene.SimulationService.ReleaseAgent(originID, UUID, m_callbackURI);
  1429. m_callbackURI = null;
  1430. }
  1431. // else
  1432. // {
  1433. // m_log.DebugFormat(
  1434. // "[SCENE PRESENCE]: No callback provided on CompleteMovement of {0} {1} to {2}",
  1435. // client.Name, client.AgentId, m_scene.RegionInfo.RegionName);
  1436. // }
  1437. ValidateAndSendAppearanceAndAgentData();
  1438. // Create child agents in neighbouring regions
  1439. if (openChildAgents && !IsChildAgent)
  1440. {
  1441. IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
  1442. if (m_agentTransfer != null)
  1443. m_agentTransfer.EnableChildAgents(this);
  1444. IFriendsModule friendsModule = m_scene.RequestModuleInterface<IFriendsModule>();
  1445. if (friendsModule != null)
  1446. friendsModule.SendFriendsOnlineIfNeeded(ControllingClient);
  1447. }
  1448. // XXX: If we force an update here, then multiple attachments do appear correctly on a destination region
  1449. // If we do it a little bit earlier (e.g. when converting the child to a root agent) then this does not work.
  1450. // This may be due to viewer code or it may be something we're not doing properly simulator side.
  1451. lock (m_attachments)
  1452. {
  1453. foreach (SceneObjectGroup sog in m_attachments)
  1454. sog.ScheduleGroupForFullUpdate();
  1455. }
  1456. // m_log.DebugFormat(
  1457. // "[SCENE PRESENCE]: Completing movement of {0} into region {1} took {2}ms",
  1458. // client.Name, Scene.RegionInfo.RegionName, (DateTime.Now - startTime).Milliseconds);
  1459. }
  1460. /// <summary>
  1461. /// Callback for the Camera view block check. Gets called with the results of the camera view block test
  1462. /// hitYN is true when there's something in the way.
  1463. /// </summary>
  1464. /// <param name="hitYN"></param>
  1465. /// <param name="collisionPoint"></param>
  1466. /// <param name="localid"></param>
  1467. /// <param name="distance"></param>
  1468. ///
  1469. private void UpdateCameraCollisionPlane(Vector4 plane)
  1470. {
  1471. if (m_lastCameraCollisionPlane != plane)
  1472. {
  1473. m_lastCameraCollisionPlane = plane;
  1474. ControllingClient.SendCameraConstraint(plane);
  1475. }
  1476. }
  1477. public void RayCastCameraCallback(bool hitYN, Vector3 collisionPoint, uint localid, float distance, Vector3 pNormal)
  1478. {
  1479. const float POSITION_TOLERANCE = 0.02f;
  1480. const float ROTATION_TOLERANCE = 0.02f;
  1481. m_doingCamRayCast = false;
  1482. if (hitYN && localid != LocalId)
  1483. {
  1484. SceneObjectGroup group = m_scene.GetGroupByPrim(localid);
  1485. bool IsPrim = group != null;
  1486. if (IsPrim)
  1487. {
  1488. SceneObjectPart part = group.GetPart(localid);
  1489. if (part != null && !part.VolumeDetectActive)
  1490. {
  1491. CameraConstraintActive = true;
  1492. pNormal.X = (float) Math.Round(pNormal.X, 2);
  1493. pNormal.Y = (float) Math.Round(pNormal.Y, 2);
  1494. pNormal.Z = (float) Math.Round(pNormal.Z, 2);
  1495. pNormal.Normalize();
  1496. collisionPoint.X = (float) Math.Round(collisionPoint.X, 1);
  1497. collisionPoint.Y = (float) Math.Round(collisionPoint.Y, 1);
  1498. collisionPoint.Z = (float) Math.Round(collisionPoint.Z, 1);
  1499. Vector4 plane = new Vector4(pNormal.X, pNormal.Y, pNormal.Z,
  1500. Vector3.Dot(collisionPoint, pNormal));
  1501. UpdateCameraCollisionPlane(plane);
  1502. }
  1503. }
  1504. else
  1505. {
  1506. CameraConstraintActive = true;
  1507. pNormal.X = (float) Math.Round(pNormal.X, 2);
  1508. pNormal.Y = (float) Math.Round(pNormal.Y, 2);
  1509. pNormal.Z = (float) Math.Round(pNormal.Z, 2);
  1510. pNormal.Normalize();
  1511. collisionPoint.X = (float) Math.Round(collisionPoint.X, 1);
  1512. collisionPoint.Y = (float) Math.Round(collisionPoint.Y, 1);
  1513. collisionPoint.Z = (float) Math.Round(collisionPoint.Z, 1);
  1514. Vector4 plane = new Vector4(pNormal.X, pNormal.Y, pNormal.Z,
  1515. Vector3.Dot(collisionPoint, pNormal));
  1516. UpdateCameraCollisionPlane(plane);
  1517. }
  1518. }
  1519. else if (!m_pos.ApproxEquals(m_lastPosition, POSITION_TOLERANCE) ||
  1520. !Rotation.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE))
  1521. {
  1522. Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -9000f); // not right...
  1523. UpdateCameraCollisionPlane(plane);
  1524. CameraConstraintActive = false;
  1525. }
  1526. }
  1527. /// <summary>
  1528. /// This is the event handler for client movement. If a client is moving, this event is triggering.
  1529. /// </summary>
  1530. public void HandleAgentUpdate(IClientAPI remoteClient, AgentUpdateArgs agentData)
  1531. {
  1532. //m_log.DebugFormat(
  1533. // "[SCENE PRESENCE]: In {0} received agent update from {1}, flags {2}",
  1534. // Scene.RegionInfo.RegionName, remoteClient.Name, (AgentManager.ControlFlags)agentData.ControlFlags);
  1535. if (IsChildAgent)
  1536. {
  1537. // // m_log.Debug("DEBUG: HandleAgentUpdate: child agent");
  1538. return;
  1539. }
  1540. #region Sanity Checking
  1541. // This is irritating. Really.
  1542. if (!AbsolutePosition.IsFinite())
  1543. {
  1544. RemoveFromPhysicalScene();
  1545. m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error #9999902");
  1546. m_pos = m_LastFinitePos;
  1547. if (!m_pos.IsFinite())
  1548. {
  1549. m_pos.X = 127f;
  1550. m_pos.Y = 127f;
  1551. m_pos.Z = 127f;
  1552. m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error #9999903");
  1553. }
  1554. AddToPhysicalScene(false);
  1555. }
  1556. else
  1557. {
  1558. m_LastFinitePos = m_pos;
  1559. }
  1560. #endregion Sanity Checking
  1561. #region Inputs
  1562. AgentManager.ControlFlags flags = (AgentManager.ControlFlags)agentData.ControlFlags;
  1563. // The Agent's Draw distance setting
  1564. // When we get to the point of re-computing neighbors everytime this
  1565. // changes, then start using the agent's drawdistance rather than the
  1566. // region's draw distance.
  1567. // DrawDistance = agentData.Far;
  1568. DrawDistance = Scene.DefaultDrawDistance;
  1569. m_mouseLook = (flags & AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) != 0;
  1570. m_leftButtonDown = (flags & AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0;
  1571. #endregion Inputs
  1572. // // Make anims work for client side autopilot
  1573. // if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0)
  1574. // m_updateCount = UPDATE_COUNT;
  1575. //
  1576. // // Make turning in place work
  1577. // if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0 ||
  1578. // (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  1579. // m_updateCount = UPDATE_COUNT;
  1580. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP) != 0)
  1581. {
  1582. StandUp();
  1583. }
  1584. // Raycast from the avatar's head to the camera to see if there's anything blocking the view
  1585. // this exclude checks may not be complete
  1586. if (m_movementUpdateCount % NumMovementsBetweenRayCast == 0 && m_scene.PhysicsScene.SupportsRayCast())
  1587. {
  1588. if (!m_doingCamRayCast && !m_mouseLook && ParentID == 0)
  1589. {
  1590. Vector3 posAdjusted = AbsolutePosition;
  1591. // posAdjusted.Z += 0.5f * Appearance.AvatarSize.Z - 0.5f;
  1592. posAdjusted.Z += 1.0f; // viewer current camera focus point
  1593. Vector3 tocam = CameraPosition - posAdjusted;
  1594. tocam.X = (float)Math.Round(tocam.X, 1);
  1595. tocam.Y = (float)Math.Round(tocam.Y, 1);
  1596. tocam.Z = (float)Math.Round(tocam.Z, 1);
  1597. float distTocamlen = tocam.Length();
  1598. if (distTocamlen > 0.3f)
  1599. {
  1600. tocam *= (1.0f / distTocamlen);
  1601. posAdjusted.X = (float)Math.Round(posAdjusted.X, 1);
  1602. posAdjusted.Y = (float)Math.Round(posAdjusted.Y, 1);
  1603. posAdjusted.Z = (float)Math.Round(posAdjusted.Z, 1);
  1604. m_doingCamRayCast = true;
  1605. m_scene.PhysicsScene.RaycastWorld(posAdjusted, tocam, distTocamlen + 1.0f, RayCastCameraCallback);
  1606. }
  1607. }
  1608. else if (CameraConstraintActive && (m_mouseLook || ParentID != 0))
  1609. {
  1610. Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -10000f); // not right...
  1611. UpdateCameraCollisionPlane(plane);
  1612. CameraConstraintActive = false;
  1613. }
  1614. }
  1615. uint flagsForScripts = (uint)flags;
  1616. flags = RemoveIgnoredControls(flags, IgnoredControls);
  1617. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND) != 0)
  1618. HandleAgentSitOnGround();
  1619. // In the future, these values might need to go global.
  1620. // Here's where you get them.
  1621. m_AgentControlFlags = flags;
  1622. m_headrotation = agentData.HeadRotation;
  1623. byte oldState = State;
  1624. State = agentData.State;
  1625. // We need to send this back to the client in order to stop the edit beams
  1626. if ((oldState & (uint)AgentState.Editing) != 0 && State == (uint)AgentState.None)
  1627. ControllingClient.SendAgentTerseUpdate(this);
  1628. PhysicsActor actor = PhysicsActor;
  1629. // This will be the case if the agent is sitting on the groudn or on an object.
  1630. if (actor == null)
  1631. {
  1632. SendControlsToScripts(flagsForScripts);
  1633. return;
  1634. }
  1635. if (AllowMovement && !SitGround)
  1636. {
  1637. // m_log.DebugFormat("[SCENE PRESENCE]: Initial body rotation {0} for {1}", agentData.BodyRotation, Name);
  1638. bool update_rotation = false;
  1639. if (agentData.BodyRotation != Rotation)
  1640. {
  1641. Rotation = agentData.BodyRotation;
  1642. update_rotation = true;
  1643. }
  1644. bool update_movementflag = false;
  1645. if (agentData.UseClientAgentPosition)
  1646. {
  1647. MovingToTarget = (agentData.ClientAgentPosition - AbsolutePosition).Length() > 0.2f;
  1648. MoveToPositionTarget = agentData.ClientAgentPosition;
  1649. }
  1650. int i = 0;
  1651. bool DCFlagKeyPressed = false;
  1652. Vector3 agent_control_v3 = Vector3.Zero;
  1653. bool newFlying = actor.Flying;
  1654. if (ForceFly)
  1655. newFlying = true;
  1656. else if (FlyDisabled)
  1657. newFlying = false;
  1658. else
  1659. newFlying = ((flags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  1660. if (actor.Flying != newFlying)
  1661. {
  1662. // Note: ScenePresence.Flying is actually fetched from the physical actor
  1663. // so setting PhysActor.Flying here also sets the ScenePresence's value.
  1664. actor.Flying = newFlying;
  1665. update_movementflag = true;
  1666. }
  1667. if (ParentID == 0)
  1668. {
  1669. bool bAllowUpdateMoveToPosition = false;
  1670. Vector3[] dirVectors;
  1671. // use camera up angle when in mouselook and not flying or when holding the left mouse button down and not flying
  1672. // this prevents 'jumping' in inappropriate situations.
  1673. if (!Flying && (m_mouseLook || m_leftButtonDown))
  1674. dirVectors = GetWalkDirectionVectors();
  1675. else
  1676. dirVectors = Dir_Vectors;
  1677. // A DIR_CONTROL_FLAG occurs when the user is trying to move in a particular direction.
  1678. foreach (Dir_ControlFlags DCF in DIR_CONTROL_FLAGS)
  1679. {
  1680. if (((uint)flags & (uint)DCF) != 0)
  1681. {
  1682. DCFlagKeyPressed = true;
  1683. try
  1684. {
  1685. agent_control_v3 += dirVectors[i];
  1686. //m_log.DebugFormat("[Motion]: {0}, {1}",i, dirVectors[i]);
  1687. }
  1688. catch (IndexOutOfRangeException)
  1689. {
  1690. // Why did I get this?
  1691. }
  1692. if (((MovementFlag & (uint)DCF) == 0) & !AgentControlStopActive)
  1693. {
  1694. //m_log.DebugFormat("[SCENE PRESENCE]: Updating MovementFlag for {0} with {1}", Name, DCF);
  1695. MovementFlag += (uint)DCF;
  1696. update_movementflag = true;
  1697. }
  1698. }
  1699. else
  1700. {
  1701. if ((MovementFlag & (uint)DCF) != 0)
  1702. {
  1703. //m_log.DebugFormat("[SCENE PRESENCE]: Updating MovementFlag for {0} with lack of {1}", Name, DCF);
  1704. MovementFlag -= (uint)DCF;
  1705. update_movementflag = true;
  1706. /*
  1707. if ((DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD_NUDGE || DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_BACKWARD_NUDGE)
  1708. && ((MovementFlag & (byte)nudgehack) == nudgehack))
  1709. {
  1710. m_log.Debug("Removed Hack flag");
  1711. }
  1712. */
  1713. }
  1714. else
  1715. {
  1716. bAllowUpdateMoveToPosition = true;
  1717. }
  1718. }
  1719. i++;
  1720. }
  1721. // Detect AGENT_CONTROL_STOP state changes
  1722. if (AgentControlStopActive != ((flags & AgentManager.ControlFlags.AGENT_CONTROL_STOP) != 0))
  1723. {
  1724. AgentControlStopActive = !AgentControlStopActive;
  1725. update_movementflag = true;
  1726. }
  1727. if (MovingToTarget)
  1728. {
  1729. // If the user has pressed a key then we want to cancel any move to target.
  1730. if (DCFlagKeyPressed)
  1731. {
  1732. ResetMoveToTarget();
  1733. update_movementflag = true;
  1734. }
  1735. else if (bAllowUpdateMoveToPosition)
  1736. {
  1737. // The UseClientAgentPosition is set if parcel ban is forcing the avatar to move to a
  1738. // certain position. It's only check for tolerance on returning to that position is 0.2
  1739. // rather than 1, at which point it removes its force target.
  1740. if (HandleMoveToTargetUpdate(agentData.UseClientAgentPosition ? 0.2 : 1, ref agent_control_v3))
  1741. update_movementflag = true;
  1742. }
  1743. }
  1744. }
  1745. // Cause the avatar to stop flying if it's colliding
  1746. // with something with the down arrow pressed.
  1747. // Only do this if we're flying
  1748. if (Flying && !ForceFly)
  1749. {
  1750. // Need to stop in mid air if user holds down AGENT_CONTROL_STOP
  1751. if (AgentControlStopActive)
  1752. {
  1753. agent_control_v3 = Vector3.Zero;
  1754. }
  1755. else
  1756. {
  1757. // Landing detection code
  1758. // Are the landing controls requirements filled?
  1759. bool controlland = (((flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) ||
  1760. ((flags & AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0));
  1761. //m_log.Debug("[CONTROL]: " +flags);
  1762. // Applies a satisfying roll effect to the avatar when flying.
  1763. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT) != 0 && (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0)
  1764. {
  1765. ApplyFlyingRoll(
  1766. FLY_ROLL_RADIANS_PER_UPDATE,
  1767. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0,
  1768. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0);
  1769. }
  1770. else if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT) != 0 &&
  1771. (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  1772. {
  1773. ApplyFlyingRoll(
  1774. -FLY_ROLL_RADIANS_PER_UPDATE,
  1775. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0,
  1776. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0);
  1777. }
  1778. else
  1779. {
  1780. if (m_AngularVelocity.Z != 0)
  1781. m_AngularVelocity.Z += CalculateFlyingRollResetToZero(FLY_ROLL_RESET_RADIANS_PER_UPDATE);
  1782. }
  1783. if (Flying && IsColliding && controlland)
  1784. {
  1785. // nesting this check because LengthSquared() is expensive and we don't
  1786. // want to do it every step when flying.
  1787. if ((Velocity.LengthSquared() <= LAND_VELOCITYMAG_MAX))
  1788. StopFlying();
  1789. }
  1790. }
  1791. }
  1792. // m_log.DebugFormat("[SCENE PRESENCE]: MovementFlag {0} for {1}", MovementFlag, Name);
  1793. // If the agent update does move the avatar, then calculate the force ready for the velocity update,
  1794. // which occurs later in the main scene loop
  1795. // We also need to update if the user rotates their avatar whilst it is slow walking/running (if they
  1796. // held down AGENT_CONTROL_STOP whilst normal walking/running). However, we do not want to update
  1797. // if the user rotated whilst holding down AGENT_CONTROL_STOP when already still (which locks the
  1798. // avatar location in place).
  1799. if (update_movementflag
  1800. || (update_rotation && DCFlagKeyPressed && (!AgentControlStopActive || MovementFlag != 0)))
  1801. {
  1802. // if (update_movementflag || !AgentControlStopActive || MovementFlag != 0)
  1803. // {
  1804. // m_log.DebugFormat(
  1805. // "[SCENE PRESENCE]: In {0} adding velocity of {1} to {2}, umf = {3}, mf = {4}, ur = {5}",
  1806. // m_scene.RegionInfo.RegionName, agent_control_v3, Name,
  1807. // update_movementflag, MovementFlag, update_rotation);
  1808. float speedModifier;
  1809. if (AgentControlStopActive)
  1810. speedModifier = AgentControlStopSlowWhilstMoving;
  1811. else
  1812. speedModifier = 1;
  1813. AddNewMovement(agent_control_v3, speedModifier);
  1814. // }
  1815. }
  1816. // else
  1817. // {
  1818. // if (!update_movementflag)
  1819. // {
  1820. // m_log.DebugFormat(
  1821. // "[SCENE PRESENCE]: In {0} ignoring requested update of {1} for {2} as update_movementflag = false",
  1822. // m_scene.RegionInfo.RegionName, agent_control_v3, Name);
  1823. // }
  1824. // }
  1825. if (update_movementflag && ParentID == 0)
  1826. {
  1827. // m_log.DebugFormat("[SCENE PRESENCE]: Updating movement animations for {0}", Name);
  1828. Animator.UpdateMovementAnimations();
  1829. }
  1830. SendControlsToScripts(flagsForScripts);
  1831. }
  1832. // We need to send this back to the client in order to see the edit beams
  1833. if ((State & (uint)AgentState.Editing) != 0)
  1834. ControllingClient.SendAgentTerseUpdate(this);
  1835. m_scene.EventManager.TriggerOnClientMovement(this);
  1836. }
  1837. /// <summary>
  1838. /// This is the event handler for client cameras. If a client is moving, or moving the camera, this event is triggering.
  1839. /// </summary>
  1840. private void HandleAgentCamerasUpdate(IClientAPI remoteClient, AgentUpdateArgs agentData)
  1841. {
  1842. //m_log.DebugFormat(
  1843. // "[SCENE PRESENCE]: In {0} received agent camera update from {1}, flags {2}",
  1844. // Scene.RegionInfo.RegionName, remoteClient.Name, (AgentManager.ControlFlags)agentData.ControlFlags);
  1845. if (IsChildAgent)
  1846. {
  1847. // // m_log.Debug("DEBUG: HandleAgentUpdate: child agent");
  1848. return;
  1849. }
  1850. ++m_movementUpdateCount;
  1851. if (m_movementUpdateCount < 1)
  1852. m_movementUpdateCount = 1;
  1853. // AgentManager.ControlFlags flags = (AgentManager.ControlFlags)agentData.ControlFlags;
  1854. // Camera location in world. We'll need to raytrace
  1855. // from this location from time to time.
  1856. CameraPosition = agentData.CameraCenter;
  1857. if (Vector3.Distance(m_lastCameraPosition, CameraPosition) >= Scene.RootReprioritizationDistance)
  1858. {
  1859. ReprioritizeUpdates();
  1860. m_lastCameraPosition = CameraPosition;
  1861. }
  1862. // Use these three vectors to figure out what the agent is looking at
  1863. // Convert it to a Matrix and/or Quaternion
  1864. CameraAtAxis = agentData.CameraAtAxis;
  1865. CameraLeftAxis = agentData.CameraLeftAxis;
  1866. CameraUpAxis = agentData.CameraUpAxis;
  1867. // The Agent's Draw distance setting
  1868. // When we get to the point of re-computing neighbors everytime this
  1869. // changes, then start using the agent's drawdistance rather than the
  1870. // region's draw distance.
  1871. // DrawDistance = agentData.Far;
  1872. DrawDistance = Scene.DefaultDrawDistance;
  1873. // Check if Client has camera in 'follow cam' or 'build' mode.
  1874. Vector3 camdif = (Vector3.One * Rotation - Vector3.One * CameraRotation);
  1875. m_followCamAuto = ((CameraUpAxis.Z > 0.959f && CameraUpAxis.Z < 0.98f)
  1876. && (Math.Abs(camdif.X) < 0.4f && Math.Abs(camdif.Y) < 0.4f)) ? true : false;
  1877. //m_log.DebugFormat("[FollowCam]: {0}", m_followCamAuto);
  1878. // Raycast from the avatar's head to the camera to see if there's anything blocking the view
  1879. if ((m_movementUpdateCount % NumMovementsBetweenRayCast) == 0 && m_scene.PhysicsScene.SupportsRayCast())
  1880. {
  1881. if (m_followCamAuto)
  1882. {
  1883. Vector3 posAdjusted = m_pos + HEAD_ADJUSTMENT;
  1884. m_scene.PhysicsScene.RaycastWorld(m_pos, Vector3.Normalize(CameraPosition - posAdjusted), Vector3.Distance(CameraPosition, posAdjusted) + 0.3f, RayCastCameraCallback);
  1885. }
  1886. }
  1887. TriggerScenePresenceUpdated();
  1888. }
  1889. /// <summary>
  1890. /// Calculate an update to move the presence to the set target.
  1891. /// </summary>
  1892. /// <remarks>
  1893. /// This doesn't actually perform the movement. Instead, it adds its vector to agent_control_v3.
  1894. /// </remarks>
  1895. /// <param value="agent_control_v3">Cumulative agent movement that this method will update.</param>
  1896. /// <returns>True if movement has been updated in some way. False otherwise.</returns>
  1897. public bool HandleMoveToTargetUpdate(double tolerance, ref Vector3 agent_control_v3)
  1898. {
  1899. // m_log.DebugFormat("[SCENE PRESENCE]: Called HandleMoveToTargetUpdate() for {0}", Name);
  1900. bool updated = false;
  1901. // m_log.DebugFormat(
  1902. // "[SCENE PRESENCE]: bAllowUpdateMoveToPosition {0}, m_moveToPositionInProgress {1}, m_autopilotMoving {2}",
  1903. // allowUpdate, m_moveToPositionInProgress, m_autopilotMoving);
  1904. double distanceToTarget = Util.GetDistanceTo(AbsolutePosition, MoveToPositionTarget);
  1905. // m_log.DebugFormat(
  1906. // "[SCENE PRESENCE]: Abs pos of {0} is {1}, target {2}, distance {3}",
  1907. // Name, AbsolutePosition, MoveToPositionTarget, distanceToTarget);
  1908. // Check the error term of the current position in relation to the target position
  1909. if (distanceToTarget <= tolerance)
  1910. {
  1911. // We are close enough to the target
  1912. AbsolutePosition = MoveToPositionTarget;
  1913. ResetMoveToTarget();
  1914. updated = true;
  1915. }
  1916. else
  1917. {
  1918. try
  1919. {
  1920. // move avatar in 3D at one meter/second towards target, in avatar coordinate frame.
  1921. // This movement vector gets added to the velocity through AddNewMovement().
  1922. // Theoretically we might need a more complex PID approach here if other
  1923. // unknown forces are acting on the avatar and we need to adaptively respond
  1924. // to such forces, but the following simple approach seems to works fine.
  1925. Vector3 LocalVectorToTarget3D =
  1926. (MoveToPositionTarget - AbsolutePosition) // vector from cur. pos to target in global coords
  1927. * Matrix4.CreateFromQuaternion(Quaternion.Inverse(Rotation)); // change to avatar coords
  1928. // Ignore z component of vector
  1929. // Vector3 LocalVectorToTarget2D = new Vector3((float)(LocalVectorToTarget3D.X), (float)(LocalVectorToTarget3D.Y), 0f);
  1930. LocalVectorToTarget3D.Normalize();
  1931. // update avatar movement flags. the avatar coordinate system is as follows:
  1932. //
  1933. // +X (forward)
  1934. //
  1935. // ^
  1936. // |
  1937. // |
  1938. // |
  1939. // |
  1940. // (left) +Y <--------o--------> -Y
  1941. // avatar
  1942. // |
  1943. // |
  1944. // |
  1945. // |
  1946. // v
  1947. // -X
  1948. //
  1949. // based on the above avatar coordinate system, classify the movement into
  1950. // one of left/right/back/forward.
  1951. if (LocalVectorToTarget3D.X < 0) //MoveBack
  1952. {
  1953. MovementFlag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
  1954. AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
  1955. updated = true;
  1956. }
  1957. else if (LocalVectorToTarget3D.X > 0) //Move Forward
  1958. {
  1959. MovementFlag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
  1960. AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
  1961. updated = true;
  1962. }
  1963. if (LocalVectorToTarget3D.Y > 0) //MoveLeft
  1964. {
  1965. MovementFlag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
  1966. AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
  1967. updated = true;
  1968. }
  1969. else if (LocalVectorToTarget3D.Y < 0) //MoveRight
  1970. {
  1971. MovementFlag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
  1972. AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
  1973. updated = true;
  1974. }
  1975. if (LocalVectorToTarget3D.Z > 0) //Up
  1976. {
  1977. // Don't set these flags for up or down - doing so will make the avatar crouch or
  1978. // keep trying to jump even if walking along level ground
  1979. //MovementFlag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_UP;
  1980. //AgentControlFlags
  1981. //AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_UP;
  1982. updated = true;
  1983. }
  1984. else if (LocalVectorToTarget3D.Z < 0) //Down
  1985. {
  1986. //MovementFlag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_DOWN;
  1987. //AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_DOWN;
  1988. updated = true;
  1989. }
  1990. // m_log.DebugFormat(
  1991. // "[SCENE PRESENCE]: HandleMoveToTargetUpdate adding {0} to move vector {1} for {2}",
  1992. // LocalVectorToTarget3D, agent_control_v3, Name);
  1993. agent_control_v3 += LocalVectorToTarget3D;
  1994. }
  1995. catch (Exception e)
  1996. {
  1997. //Avoid system crash, can be slower but...
  1998. m_log.DebugFormat("Crash! {0}", e.ToString());
  1999. }
  2000. }
  2001. return updated;
  2002. }
  2003. /// <summary>
  2004. /// Move to the given target over time.
  2005. /// </summary>
  2006. /// <param name="pos"></param>
  2007. /// <param name="noFly">
  2008. /// If true, then don't allow the avatar to fly to the target, even if it's up in the air.
  2009. /// This is to allow movement to targets that are known to be on an elevated platform with a continuous path
  2010. /// from start to finish.
  2011. /// </param>
  2012. /// <param name="landAtTarget">
  2013. /// If true and the avatar starts flying during the move then land at the target.
  2014. /// </param>
  2015. public void MoveToTarget(Vector3 pos, bool noFly, bool landAtTarget)
  2016. {
  2017. if (SitGround)
  2018. StandUp();
  2019. // m_log.DebugFormat(
  2020. // "[SCENE PRESENCE]: Avatar {0} received request to move to position {1} in {2}",
  2021. // Name, pos, m_scene.RegionInfo.RegionName);
  2022. // Allow move to another sub-region within a megaregion
  2023. Vector2 regionSize;
  2024. IRegionCombinerModule regionCombinerModule = m_scene.RequestModuleInterface<IRegionCombinerModule>();
  2025. if (regionCombinerModule != null)
  2026. regionSize = regionCombinerModule.GetSizeOfMegaregion(m_scene.RegionInfo.RegionID);
  2027. else
  2028. regionSize = new Vector2(m_scene.RegionInfo.RegionSizeX, m_scene.RegionInfo.RegionSizeY);
  2029. if (pos.X < 0 || pos.X >= regionSize.X
  2030. || pos.Y < 0 || pos.Y >= regionSize.Y
  2031. || pos.Z < 0)
  2032. return;
  2033. // Vector3 heightAdjust = new Vector3(0, 0, Appearance.AvatarHeight / 2);
  2034. // pos += heightAdjust;
  2035. //
  2036. // // Anti duck-walking measure
  2037. // if (Math.Abs(pos.Z - AbsolutePosition.Z) < 0.2f)
  2038. // {
  2039. //// m_log.DebugFormat("[SCENE PRESENCE]: Adjusting MoveToPosition from {0} to {1}", pos, AbsolutePosition);
  2040. // pos.Z = AbsolutePosition.Z;
  2041. // }
  2042. // Get terrain height for sub-region in a megaregion if necessary
  2043. int X = (int)((m_scene.RegionInfo.WorldLocX) + pos.X);
  2044. int Y = (int)((m_scene.RegionInfo.WorldLocY) + pos.Y);
  2045. GridRegion target_region = m_scene.GridService.GetRegionByPosition(m_scene.RegionInfo.ScopeID, X, Y);
  2046. // If X and Y is NaN, target_region will be null
  2047. if (target_region == null)
  2048. return;
  2049. UUID target_regionID = target_region.RegionID;
  2050. Scene targetScene = m_scene;
  2051. if (!SceneManager.Instance.TryGetScene(target_regionID, out targetScene))
  2052. targetScene = m_scene;
  2053. float terrainHeight = (float)targetScene.Heightmap[(int)(pos.X % regionSize.X), (int)(pos.Y % regionSize.Y)];
  2054. pos.Z = Math.Max(terrainHeight, pos.Z);
  2055. // Fudge factor. It appears that if one clicks "go here" on a piece of ground, the go here request is
  2056. // always slightly higher than the actual terrain height.
  2057. // FIXME: This constrains NPC movements as well, so should be somewhere else.
  2058. if (pos.Z - terrainHeight < 0.2)
  2059. pos.Z = terrainHeight;
  2060. // m_log.DebugFormat(
  2061. // "[SCENE PRESENCE]: Avatar {0} set move to target {1} (terrain height {2}) in {3}",
  2062. // Name, pos, terrainHeight, m_scene.RegionInfo.RegionName);
  2063. if (noFly)
  2064. Flying = false;
  2065. else if (pos.Z > terrainHeight)
  2066. Flying = true;
  2067. LandAtTarget = landAtTarget;
  2068. MovingToTarget = true;
  2069. MoveToPositionTarget = pos;
  2070. // Rotate presence around the z-axis to point in same direction as movement.
  2071. // Ignore z component of vector
  2072. Vector3 localVectorToTarget3D = pos - AbsolutePosition;
  2073. Vector3 localVectorToTarget2D = new Vector3((float)(localVectorToTarget3D.X), (float)(localVectorToTarget3D.Y), 0f);
  2074. // m_log.DebugFormat("[SCENE PRESENCE]: Local vector to target is {0}", localVectorToTarget2D);
  2075. // Calculate the yaw.
  2076. Vector3 angle = new Vector3(0, 0, (float)(Math.Atan2(localVectorToTarget2D.Y, localVectorToTarget2D.X)));
  2077. // m_log.DebugFormat("[SCENE PRESENCE]: Angle is {0}", angle);
  2078. Rotation = Quaternion.CreateFromEulers(angle);
  2079. // m_log.DebugFormat("[SCENE PRESENCE]: Body rot for {0} set to {1}", Name, Rotation);
  2080. Vector3 agent_control_v3 = new Vector3();
  2081. HandleMoveToTargetUpdate(1, ref agent_control_v3);
  2082. AddNewMovement(agent_control_v3);
  2083. }
  2084. /// <summary>
  2085. /// Reset the move to target.
  2086. /// </summary>
  2087. public void ResetMoveToTarget()
  2088. {
  2089. // m_log.DebugFormat("[SCENE PRESENCE]: Resetting move to target for {0}", Name);
  2090. MovingToTarget = false;
  2091. // MoveToPositionTarget = Vector3.Zero;
  2092. m_forceToApply = null; // cancel possible last action
  2093. // We need to reset the control flag as the ScenePresenceAnimator uses this to determine the correct
  2094. // resting animation (e.g. hover or stand). NPCs don't have a client that will quickly reset this flag.
  2095. // However, the line is here rather than in the NPC module since it also appears necessary to stop a
  2096. // viewer that uses "go here" from juddering on all subsequent avatar movements.
  2097. AgentControlFlags = (uint)AgentManager.ControlFlags.NONE;
  2098. }
  2099. /// <summary>
  2100. /// Perform the logic necessary to stand the avatar up. This method also executes
  2101. /// the stand animation.
  2102. /// </summary>
  2103. public void StandUp()
  2104. {
  2105. // m_log.DebugFormat("[SCENE PRESENCE]: StandUp() for {0}", Name);
  2106. bool satOnObject = IsSatOnObject;
  2107. SceneObjectPart part = ParentPart;
  2108. SitGround = false;
  2109. if (satOnObject)
  2110. {
  2111. PrevSitOffset = m_pos; // Save sit offset
  2112. UnRegisterSeatControls(part.ParentGroup.UUID);
  2113. TaskInventoryDictionary taskIDict = part.TaskInventory;
  2114. if (taskIDict != null)
  2115. {
  2116. lock (taskIDict)
  2117. {
  2118. foreach (UUID taskID in taskIDict.Keys)
  2119. {
  2120. UnRegisterControlEventsToScript(LocalId, taskID);
  2121. taskIDict[taskID].PermsMask &= ~(
  2122. 2048 | //PERMISSION_CONTROL_CAMERA
  2123. 4); // PERMISSION_TAKE_CONTROLS
  2124. }
  2125. }
  2126. }
  2127. part.ParentGroup.DeleteAvatar(UUID);
  2128. Vector3 sitPartWorldPosition = part.GetWorldPosition();
  2129. ControllingClient.SendClearFollowCamProperties(part.ParentUUID);
  2130. ParentID = 0;
  2131. ParentPart = null;
  2132. Quaternion standRotation;
  2133. if (part.SitTargetAvatar == UUID)
  2134. {
  2135. standRotation = part.GetWorldRotation();
  2136. if (!part.IsRoot)
  2137. standRotation = standRotation * part.SitTargetOrientation;
  2138. // standRotation = part.RotationOffset * part.SitTargetOrientation;
  2139. // else
  2140. // standRotation = part.SitTargetOrientation;
  2141. }
  2142. else
  2143. {
  2144. standRotation = Rotation;
  2145. }
  2146. //Vector3 standPos = ParentPosition + new Vector3(0.0f, 0.0f, 2.0f * m_sitAvatarHeight);
  2147. //Vector3 standPos = ParentPosition;
  2148. // Vector3 standPositionAdjustment
  2149. // = part.SitTargetPosition + new Vector3(0.5f, 0f, m_sitAvatarHeight / 2f);
  2150. Vector3 adjustmentForSitPosition = part.SitTargetPosition * part.GetWorldRotation();
  2151. // XXX: This is based on the physics capsule sizes. Need to find a better way to read this rather than
  2152. // hardcoding here.
  2153. Vector3 adjustmentForSitPose = new Vector3(0.74f, 0f, 0f) * standRotation;
  2154. Vector3 standPos = sitPartWorldPosition + adjustmentForSitPosition + adjustmentForSitPose;
  2155. // m_log.DebugFormat(
  2156. // "[SCENE PRESENCE]: Setting stand to pos {0}, (adjustmentForSitPosition {1}, adjustmentForSitPose {2}) rotation {3} for {4} in {5}",
  2157. // standPos, adjustmentForSitPosition, adjustmentForSitPose, standRotation, Name, Scene.Name);
  2158. Rotation = standRotation;
  2159. AbsolutePosition = standPos;
  2160. }
  2161. // We need to wait until we have calculated proper stand positions before sitting up the physical
  2162. // avatar to avoid race conditions.
  2163. if (PhysicsActor == null)
  2164. AddToPhysicalScene(false);
  2165. if (satOnObject)
  2166. {
  2167. SendAvatarDataToAllAgents();
  2168. m_requestedSitTargetID = 0;
  2169. part.RemoveSittingAvatar(UUID);
  2170. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  2171. }
  2172. else if (PhysicsActor == null)
  2173. AddToPhysicalScene(false);
  2174. Animator.TrySetMovementAnimation("STAND");
  2175. TriggerScenePresenceUpdated();
  2176. }
  2177. private SceneObjectPart FindNextAvailableSitTarget(UUID targetID)
  2178. {
  2179. SceneObjectPart targetPart = m_scene.GetSceneObjectPart(targetID);
  2180. if (targetPart == null)
  2181. return null;
  2182. // If the primitive the player clicked on has a sit target and that sit target is not full, that sit target is used.
  2183. // If the primitive the player clicked on has no sit target, and one or more other linked objects have sit targets that are not full, the sit target of the object with the lowest link number will be used.
  2184. // Get our own copy of the part array, and sort into the order we want to test
  2185. SceneObjectPart[] partArray = targetPart.ParentGroup.Parts;
  2186. Array.Sort(partArray, delegate(SceneObjectPart p1, SceneObjectPart p2)
  2187. {
  2188. // we want the originally selected part first, then the rest in link order -- so make the selected part link num (-1)
  2189. int linkNum1 = p1==targetPart ? -1 : p1.LinkNum;
  2190. int linkNum2 = p2==targetPart ? -1 : p2.LinkNum;
  2191. return linkNum1 - linkNum2;
  2192. }
  2193. );
  2194. //look for prims with explicit sit targets that are available
  2195. foreach (SceneObjectPart part in partArray)
  2196. {
  2197. if (part.IsSitTargetSet && part.SitTargetAvatar == UUID.Zero)
  2198. {
  2199. //switch the target to this prim
  2200. return part;
  2201. }
  2202. }
  2203. // no explicit sit target found - use original target
  2204. return targetPart;
  2205. }
  2206. private void SendSitResponse(UUID targetID, Vector3 offset, Quaternion sitOrientation)
  2207. {
  2208. Vector3 cameraEyeOffset = Vector3.Zero;
  2209. Vector3 cameraAtOffset = Vector3.Zero;
  2210. bool forceMouselook = false;
  2211. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  2212. if (part == null)
  2213. return;
  2214. if (PhysicsActor != null)
  2215. m_sitAvatarHeight = PhysicsActor.Size.Z * 0.5f;
  2216. bool canSit = false;
  2217. if (part.IsSitTargetSet && part.SitTargetAvatar == UUID.Zero)
  2218. {
  2219. // m_log.DebugFormat(
  2220. // "[SCENE PRESENCE]: Sitting {0} on {1} {2} because sit target is set and unoccupied",
  2221. // Name, part.Name, part.LocalId);
  2222. offset = part.SitTargetPosition;
  2223. sitOrientation = part.SitTargetOrientation;
  2224. if (!part.IsRoot)
  2225. {
  2226. // m_log.DebugFormat("Old sit orient {0}", sitOrientation);
  2227. sitOrientation = part.RotationOffset * sitOrientation;
  2228. // m_log.DebugFormat("New sit orient {0}", sitOrientation);
  2229. // m_log.DebugFormat("Old sit offset {0}", offset);
  2230. offset = offset * part.RotationOffset;
  2231. // m_log.DebugFormat("New sit offset {0}", offset);
  2232. }
  2233. canSit = true;
  2234. }
  2235. else
  2236. {
  2237. if (PhysicsSit(part,offset)) // physics engine
  2238. return;
  2239. Vector3 pos = part.AbsolutePosition + offset;
  2240. if (Util.GetDistanceTo(AbsolutePosition, pos) <= 10)
  2241. {
  2242. AbsolutePosition = pos + new Vector3(0.0f, 0.0f, m_sitAvatarHeight);
  2243. canSit = true;
  2244. }
  2245. }
  2246. if (canSit)
  2247. {
  2248. if (PhysicsActor != null)
  2249. {
  2250. // We can remove the physicsActor until they stand up.
  2251. RemoveFromPhysicalScene();
  2252. }
  2253. if (MovingToTarget)
  2254. ResetMoveToTarget();
  2255. Velocity = Vector3.Zero;
  2256. part.AddSittingAvatar(UUID);
  2257. cameraAtOffset = part.GetCameraAtOffset();
  2258. cameraEyeOffset = part.GetCameraEyeOffset();
  2259. forceMouselook = part.GetForceMouselook();
  2260. // An viewer expects to specify sit positions as offsets to the root prim, even if a child prim is
  2261. // being sat upon.
  2262. offset += part.OffsetPosition;
  2263. ControllingClient.SendSitResponse(
  2264. part.ParentGroup.UUID, offset, sitOrientation, false, cameraAtOffset, cameraEyeOffset, forceMouselook);
  2265. m_requestedSitTargetUUID = part.UUID;
  2266. HandleAgentSit(ControllingClient, UUID);
  2267. // Moved here to avoid a race with default sit anim
  2268. // The script event needs to be raised after the default sit anim is set.
  2269. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  2270. }
  2271. }
  2272. public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset)
  2273. {
  2274. if (IsChildAgent)
  2275. return;
  2276. if (ParentID != 0)
  2277. {
  2278. if (ParentPart.UUID == targetID)
  2279. return; // already sitting here, ignore
  2280. StandUp();
  2281. }
  2282. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  2283. if (part != null)
  2284. {
  2285. m_requestedSitTargetID = part.LocalId;
  2286. m_requestedSitTargetUUID = part.UUID;
  2287. }
  2288. else
  2289. {
  2290. m_log.Warn("Sit requested on unknown object: " + targetID.ToString());
  2291. }
  2292. SendSitResponse(targetID, offset, Quaternion.Identity);
  2293. }
  2294. // returns false if does not suport so older sit can be tried
  2295. public bool PhysicsSit(SceneObjectPart part, Vector3 offset)
  2296. {
  2297. // TODO: Pull in these bits
  2298. return false;
  2299. /*
  2300. if (part == null || part.ParentGroup.IsAttachment)
  2301. {
  2302. return true;
  2303. }
  2304. if ( m_scene.PhysicsScene == null)
  2305. return false;
  2306. if (part.PhysActor == null)
  2307. {
  2308. // none physcis shape
  2309. if (part.PhysicsShapeType == (byte)PhysicsShapeType.None)
  2310. ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
  2311. else
  2312. { // non physical phantom TODO
  2313. ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
  2314. return false;
  2315. }
  2316. return true;
  2317. }
  2318. // not doing autopilot
  2319. m_requestedSitTargetID = 0;
  2320. if (m_scene.PhysicsScene.SitAvatar(part.PhysActor, AbsolutePosition, CameraPosition, offset, new Vector3(0.35f, 0, 0.65f), PhysicsSitResponse) != 0)
  2321. return true;
  2322. return false;
  2323. */
  2324. }
  2325. private bool CanEnterLandPosition(Vector3 testPos)
  2326. {
  2327. ILandObject land = m_scene.LandChannel.GetLandObject(testPos.X, testPos.Y);
  2328. if (land == null || land.LandData.Name == "NO_LAND")
  2329. return true;
  2330. return land.CanBeOnThisLand(UUID,testPos.Z);
  2331. }
  2332. // status
  2333. // < 0 ignore
  2334. // 0 bad sit spot
  2335. public void PhysicsSitResponse(int status, uint partID, Vector3 offset, Quaternion Orientation)
  2336. {
  2337. if (status < 0)
  2338. return;
  2339. if (status == 0)
  2340. {
  2341. ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
  2342. return;
  2343. }
  2344. SceneObjectPart part = m_scene.GetSceneObjectPart(partID);
  2345. if (part == null)
  2346. return;
  2347. Vector3 targetPos = part.GetWorldPosition() + offset * part.GetWorldRotation();
  2348. if(!CanEnterLandPosition(targetPos))
  2349. {
  2350. ControllingClient.SendAlertMessage(" Sit position on restricted land, try another spot");
  2351. return;
  2352. }
  2353. RemoveFromPhysicalScene();
  2354. if (MovingToTarget)
  2355. ResetMoveToTarget();
  2356. Velocity = Vector3.Zero;
  2357. part.AddSittingAvatar(UUID);
  2358. Vector3 cameraAtOffset = part.GetCameraAtOffset();
  2359. Vector3 cameraEyeOffset = part.GetCameraEyeOffset();
  2360. bool forceMouselook = part.GetForceMouselook();
  2361. ControllingClient.SendSitResponse(
  2362. part.UUID, offset, Orientation, false, cameraAtOffset, cameraEyeOffset, forceMouselook);
  2363. // not using autopilot
  2364. Rotation = Orientation;
  2365. m_pos = offset;
  2366. m_requestedSitTargetID = 0;
  2367. part.ParentGroup.AddAvatar(UUID);
  2368. ParentPart = part;
  2369. ParentID = part.LocalId;
  2370. if(status == 3)
  2371. Animator.TrySetMovementAnimation("SIT_GROUND");
  2372. else
  2373. Animator.TrySetMovementAnimation("SIT");
  2374. SendAvatarDataToAllAgents();
  2375. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  2376. }
  2377. public void HandleAgentSit(IClientAPI remoteClient, UUID agentID)
  2378. {
  2379. if (IsChildAgent)
  2380. return;
  2381. SceneObjectPart part = m_scene.GetSceneObjectPart(m_requestedSitTargetID);
  2382. if (part != null)
  2383. {
  2384. if (part.ParentGroup.IsAttachment)
  2385. {
  2386. m_log.WarnFormat(
  2387. "[SCENE PRESENCE]: Avatar {0} tried to sit on part {1} from object {2} in {3} but this is an attachment for avatar id {4}",
  2388. Name, part.Name, part.ParentGroup.Name, Scene.Name, part.ParentGroup.AttachedAvatar);
  2389. return;
  2390. }
  2391. if (part.SitTargetAvatar == UUID)
  2392. {
  2393. Vector3 sitTargetPos = part.SitTargetPosition;
  2394. Quaternion sitTargetOrient = part.SitTargetOrientation;
  2395. // m_log.DebugFormat(
  2396. // "[SCENE PRESENCE]: Sitting {0} at sit target {1}, {2} on {3} {4}",
  2397. // Name, sitTargetPos, sitTargetOrient, part.Name, part.LocalId);
  2398. //Quaternion vq = new Quaternion(sitTargetPos.X, sitTargetPos.Y+0.2f, sitTargetPos.Z+0.2f, 0);
  2399. //Quaternion nq = new Quaternion(-sitTargetOrient.X, -sitTargetOrient.Y, -sitTargetOrient.Z, sitTargetOrient.w);
  2400. //Quaternion result = (sitTargetOrient * vq) * nq;
  2401. double x, y, z, m;
  2402. Quaternion r = sitTargetOrient;
  2403. m = r.X * r.X + r.Y * r.Y + r.Z * r.Z + r.W * r.W;
  2404. if (Math.Abs(1.0 - m) > 0.000001)
  2405. {
  2406. m = 1.0 / Math.Sqrt(m);
  2407. r.X *= (float)m;
  2408. r.Y *= (float)m;
  2409. r.Z *= (float)m;
  2410. r.W *= (float)m;
  2411. }
  2412. x = 2 * (r.X * r.Z + r.Y * r.W);
  2413. y = 2 * (-r.X * r.W + r.Y * r.Z);
  2414. z = -r.X * r.X - r.Y * r.Y + r.Z * r.Z + r.W * r.W;
  2415. Vector3 up = new Vector3((float)x, (float)y, (float)z);
  2416. Vector3 sitOffset = up * Appearance.AvatarHeight * 0.02638f;
  2417. Vector3 newPos = sitTargetPos + sitOffset + SIT_TARGET_ADJUSTMENT;
  2418. Quaternion newRot;
  2419. if (part.IsRoot)
  2420. {
  2421. newRot = sitTargetOrient;
  2422. }
  2423. else
  2424. {
  2425. newPos = newPos * part.RotationOffset;
  2426. newRot = part.RotationOffset * sitTargetOrient;
  2427. }
  2428. newPos += part.OffsetPosition;
  2429. m_pos = newPos;
  2430. Rotation = newRot;
  2431. // ParentPosition = part.AbsolutePosition;
  2432. }
  2433. else
  2434. {
  2435. // An viewer expects to specify sit positions as offsets to the root prim, even if a child prim is
  2436. // being sat upon.
  2437. m_pos -= part.GroupPosition;
  2438. // ParentPosition = part.AbsolutePosition;
  2439. // m_log.DebugFormat(
  2440. // "[SCENE PRESENCE]: Sitting {0} at position {1} ({2} + {3}) on part {4} {5} without sit target",
  2441. // Name, part.AbsolutePosition, m_pos, ParentPosition, part.Name, part.LocalId);
  2442. }
  2443. part.ParentGroup.AddAvatar(UUID);
  2444. ParentPart = m_scene.GetSceneObjectPart(m_requestedSitTargetID);
  2445. ParentID = m_requestedSitTargetID;
  2446. m_AngularVelocity = Vector3.Zero;
  2447. Velocity = Vector3.Zero;
  2448. RemoveFromPhysicalScene();
  2449. String sitAnimation = "SIT";
  2450. if (!String.IsNullOrEmpty(part.SitAnimation))
  2451. {
  2452. sitAnimation = part.SitAnimation;
  2453. }
  2454. Animator.TrySetMovementAnimation(sitAnimation);
  2455. SendAvatarDataToAllAgents();
  2456. TriggerScenePresenceUpdated();
  2457. }
  2458. }
  2459. public void HandleAgentSitOnGround()
  2460. {
  2461. if (IsChildAgent)
  2462. return;
  2463. // m_updateCount = 0; // Kill animation update burst so that the SIT_G.. will stick..
  2464. m_AngularVelocity = Vector3.Zero;
  2465. Animator.TrySetMovementAnimation("SIT_GROUND_CONSTRAINED");
  2466. TriggerScenePresenceUpdated();
  2467. SitGround = true;
  2468. RemoveFromPhysicalScene();
  2469. }
  2470. /// <summary>
  2471. /// Event handler for the 'Always run' setting on the client
  2472. /// Tells the physics plugin to increase speed of movement.
  2473. /// </summary>
  2474. public void HandleSetAlwaysRun(IClientAPI remoteClient, bool pSetAlwaysRun)
  2475. {
  2476. SetAlwaysRun = pSetAlwaysRun;
  2477. }
  2478. public void HandleStartAnim(IClientAPI remoteClient, UUID animID)
  2479. {
  2480. Animator.AddAnimation(animID, UUID.Zero);
  2481. TriggerScenePresenceUpdated();
  2482. }
  2483. public void HandleStopAnim(IClientAPI remoteClient, UUID animID)
  2484. {
  2485. Animator.RemoveAnimation(animID, false);
  2486. TriggerScenePresenceUpdated();
  2487. }
  2488. /// <summary>
  2489. /// Rotate the avatar to the given rotation and apply a movement in the given relative vector
  2490. /// </summary>
  2491. /// <param name="vec">The vector in which to move. This is relative to the rotation argument</param>
  2492. /// <param name="thisAddSpeedModifier">
  2493. /// Optional additional speed modifier for this particular add. Default is 1</param>
  2494. public void AddNewMovement(Vector3 vec, float thisAddSpeedModifier = 1)
  2495. {
  2496. // m_log.DebugFormat(
  2497. // "[SCENE PRESENCE]: Adding new movement {0} with rotation {1}, thisAddSpeedModifier {2} for {3}",
  2498. // vec, Rotation, thisAddSpeedModifier, Name);
  2499. Vector3 direc = vec * Rotation;
  2500. direc.Normalize();
  2501. if (Flying != FlyingOld) // add for fly velocity control
  2502. {
  2503. FlyingOld = Flying; // add for fly velocity control
  2504. if (!Flying)
  2505. WasFlying = true; // add for fly velocity control
  2506. }
  2507. if (IsColliding)
  2508. WasFlying = false; // add for fly velocity control
  2509. if ((vec.Z == 0f) && !Flying)
  2510. direc.Z = 0f; // Prevent camera WASD up.
  2511. direc *= 0.03f * 128f * SpeedModifier * thisAddSpeedModifier;
  2512. // m_log.DebugFormat("[SCENE PRESENCE]: Force to apply before modification was {0} for {1}", direc, Name);
  2513. if (PhysicsActor != null)
  2514. {
  2515. if (Flying)
  2516. {
  2517. direc *= 4.0f;
  2518. //bool controlland = (((m_AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) || ((m_AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0));
  2519. //if (controlland)
  2520. // m_log.Info("[AGENT]: landCommand");
  2521. //if (IsColliding)
  2522. // m_log.Info("[AGENT]: colliding");
  2523. //if (Flying && IsColliding && controlland)
  2524. //{
  2525. // StopFlying();
  2526. // m_log.Info("[AGENT]: Stop Flying");
  2527. //}
  2528. }
  2529. if (Animator.Falling && WasFlying) // if falling from flying, disable motion add
  2530. {
  2531. direc *= 0.0f;
  2532. }
  2533. else if (!Flying && IsColliding)
  2534. {
  2535. if (direc.Z > 2.0f)
  2536. {
  2537. direc.Z *= 2.6f;
  2538. // TODO: PreJump and jump happen too quickly. Many times prejump gets ignored.
  2539. // Animator.TrySetMovementAnimation("PREJUMP");
  2540. // Animator.TrySetMovementAnimation("JUMP");
  2541. }
  2542. }
  2543. }
  2544. // m_log.DebugFormat("[SCENE PRESENCE]: Setting force to apply to {0} for {1}", direc, Name);
  2545. // TODO: Add the force instead of only setting it to support multiple forces per frame?
  2546. m_forceToApply = direc;
  2547. Animator.UpdateMovementAnimations();
  2548. }
  2549. #endregion
  2550. #region Overridden Methods
  2551. public override void Update()
  2552. {
  2553. const float ROTATION_TOLERANCE = 0.01f;
  2554. const float VELOCITY_TOLERANCE = 0.001f;
  2555. const float POSITION_TOLERANCE = 0.05f;
  2556. if (IsChildAgent == false)
  2557. {
  2558. // NOTE: Velocity is not the same as m_velocity. Velocity will attempt to
  2559. // grab the latest PhysicsActor velocity, whereas m_velocity is often
  2560. // storing a requested force instead of an actual traveling velocity
  2561. if (Appearance.AvatarSize != m_lastSize && !IsLoggingIn)
  2562. SendAvatarDataToAllAgents();
  2563. // Allow any updates for sitting avatars to that llSetPrimitiveLinkParams() can work for very
  2564. // small increments (e.g. sit position adjusters). An alternative may be to eliminate the tolerance
  2565. // checks on all updates but the ramifications of this would need careful consideration.
  2566. bool updateClients
  2567. = IsSatOnObject && (Rotation != m_lastRotation || Velocity != m_lastVelocity || m_pos != m_lastPosition);
  2568. if (!updateClients)
  2569. updateClients
  2570. = !Rotation.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE)
  2571. || !Velocity.ApproxEquals(m_lastVelocity, VELOCITY_TOLERANCE)
  2572. || !m_pos.ApproxEquals(m_lastPosition, POSITION_TOLERANCE);
  2573. if (updateClients)
  2574. {
  2575. SendTerseUpdateToAllClients();
  2576. // Update the "last" values
  2577. m_lastPosition = m_pos;
  2578. m_lastRotation = Rotation;
  2579. m_lastVelocity = Velocity;
  2580. }
  2581. CheckForBorderCrossing();
  2582. CheckForSignificantMovement(); // sends update to the modules.
  2583. }
  2584. }
  2585. #endregion
  2586. #region Update Client(s)
  2587. /// <summary>
  2588. /// Sends a location update to the client connected to this scenePresence
  2589. /// </summary>
  2590. /// <param name="remoteClient"></param>
  2591. public void SendTerseUpdateToClient(IClientAPI remoteClient)
  2592. {
  2593. // If the client is inactive, it's getting its updates from another
  2594. // server.
  2595. if (remoteClient.IsActive)
  2596. {
  2597. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  2598. remoteClient.SendEntityUpdate(
  2599. this,
  2600. PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  2601. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);
  2602. m_scene.StatsReporter.AddAgentUpdates(1);
  2603. }
  2604. }
  2605. // vars to support reduced update frequency when velocity is unchanged
  2606. private Vector3 lastVelocitySentToAllClients = Vector3.Zero;
  2607. private Vector3 lastPositionSentToAllClients = Vector3.Zero;
  2608. private int lastTerseUpdateToAllClientsTick = Util.EnvironmentTickCount();
  2609. /// <summary>
  2610. /// Send a location/velocity/accelleration update to all agents in scene
  2611. /// </summary>
  2612. public void SendTerseUpdateToAllClients()
  2613. {
  2614. int currentTick = Util.EnvironmentTickCount();
  2615. // Decrease update frequency when avatar is moving but velocity is
  2616. // not changing.
  2617. // If there is a mismatch between distance travelled and expected
  2618. // distance based on last velocity sent and velocity hasnt changed,
  2619. // then send a new terse update
  2620. float timeSinceLastUpdate = (currentTick - lastTerseUpdateToAllClientsTick) * 0.001f;
  2621. Vector3 expectedPosition = lastPositionSentToAllClients + lastVelocitySentToAllClients * timeSinceLastUpdate;
  2622. float distanceError = Vector3.Distance(OffsetPosition, expectedPosition);
  2623. float speed = Velocity.Length();
  2624. float velocidyDiff = Vector3.Distance(lastVelocitySentToAllClients, Velocity);
  2625. // assuming 5 ms. worst case precision for timer, use 2x that
  2626. // for distance error threshold
  2627. float distanceErrorThreshold = speed * 0.01f;
  2628. if (speed < 0.01f // allow rotation updates if avatar position is unchanged
  2629. || Math.Abs(distanceError) > distanceErrorThreshold
  2630. || velocidyDiff > 0.01f) // did velocity change from last update?
  2631. {
  2632. lastVelocitySentToAllClients = Velocity;
  2633. lastTerseUpdateToAllClientsTick = currentTick;
  2634. lastPositionSentToAllClients = OffsetPosition;
  2635. // Console.WriteLine("Scheduled update for {0} in {1}", Name, Scene.Name);
  2636. m_scene.ForEachClient(SendTerseUpdateToClient);
  2637. }
  2638. TriggerScenePresenceUpdated();
  2639. }
  2640. public void SendCoarseLocations(List<Vector3> coarseLocations, List<UUID> avatarUUIDs)
  2641. {
  2642. SendCoarseLocationsMethod d = m_sendCoarseLocationsMethod;
  2643. if (d != null)
  2644. {
  2645. d.Invoke(m_scene.RegionInfo.originRegionID, this, coarseLocations, avatarUUIDs);
  2646. }
  2647. }
  2648. public void SetSendCoarseLocationMethod(SendCoarseLocationsMethod d)
  2649. {
  2650. if (d != null)
  2651. m_sendCoarseLocationsMethod = d;
  2652. }
  2653. public void SendCoarseLocationsDefault(UUID sceneId, ScenePresence p, List<Vector3> coarseLocations, List<UUID> avatarUUIDs)
  2654. {
  2655. ControllingClient.SendCoarseLocationUpdate(avatarUUIDs, coarseLocations);
  2656. }
  2657. public void SendInitialDataToMe()
  2658. {
  2659. // Send all scene object to the new client
  2660. Util.RunThreadNoTimeout(delegate
  2661. {
  2662. // we created a new ScenePresence (a new child agent) in a fresh region.
  2663. // Request info about all the (root) agents in this region
  2664. // Note: This won't send data *to* other clients in that region (children don't send)
  2665. SendOtherAgentsAvatarDataToMe();
  2666. SendOtherAgentsAppearanceToMe();
  2667. EntityBase[] entities = Scene.Entities.GetEntities();
  2668. foreach (EntityBase e in entities)
  2669. {
  2670. if (e != null && e is SceneObjectGroup)
  2671. ((SceneObjectGroup)e).SendFullUpdateToClient(ControllingClient);
  2672. }
  2673. }, "SendInitialDataToMe", null);
  2674. }
  2675. /// <summary>
  2676. /// Do everything required once a client completes its movement into a region and becomes
  2677. /// a root agent.
  2678. /// </summary>
  2679. private void ValidateAndSendAppearanceAndAgentData()
  2680. {
  2681. //m_log.DebugFormat("[SCENE PRESENCE] SendInitialData: {0} ({1})", Name, UUID);
  2682. // Moved this into CompleteMovement to ensure that Appearance is initialized before
  2683. // the inventory arrives
  2684. // m_scene.GetAvatarAppearance(ControllingClient, out Appearance);
  2685. bool cachedappearance = false;
  2686. // We have an appearance but we may not have the baked textures. Check the asset cache
  2687. // to see if all the baked textures are already here.
  2688. if (m_scene.AvatarFactory != null)
  2689. cachedappearance = m_scene.AvatarFactory.ValidateBakedTextureCache(this);
  2690. // If we aren't using a cached appearance, then clear out the baked textures
  2691. if (!cachedappearance)
  2692. {
  2693. Appearance.ResetAppearance();
  2694. if (m_scene.AvatarFactory != null)
  2695. m_scene.AvatarFactory.QueueAppearanceSave(UUID);
  2696. }
  2697. // This agent just became root. We are going to tell everyone about it. The process of
  2698. // getting other avatars information was initiated elsewhere immediately after the child circuit connected... don't do it
  2699. // again here... this comes after the cached appearance check because the avatars
  2700. // appearance goes into the avatar update packet
  2701. SendAvatarDataToAllAgents();
  2702. // This invocation always shows up in the viewer logs as an error. Is it needed?
  2703. SendAppearanceToAgent(this);
  2704. // If we are using the the cached appearance then send it out to everyone
  2705. if (cachedappearance)
  2706. {
  2707. m_log.DebugFormat("[SCENE PRESENCE]: Baked textures are in the cache for {0} in {1}", Name, m_scene.Name);
  2708. // If the avatars baked textures are all in the cache, then we have a
  2709. // complete appearance... send it out, if not, then we'll send it when
  2710. // the avatar finishes updating its appearance
  2711. SendAppearanceToAllOtherAgents();
  2712. }
  2713. }
  2714. /// <summary>
  2715. /// Send this agent's avatar data to all other root and child agents in the scene
  2716. /// This agent must be root. This avatar will receive its own update.
  2717. /// </summary>
  2718. public void SendAvatarDataToAllAgents()
  2719. {
  2720. //m_log.DebugFormat("[SCENE PRESENCE] SendAvatarDataToAllAgents: {0} ({1})", Name, UUID);
  2721. // only send update from root agents to other clients; children are only "listening posts"
  2722. if (IsChildAgent)
  2723. {
  2724. m_log.WarnFormat(
  2725. "[SCENE PRESENCE]: Attempt to send avatar data from a child agent for {0} in {1}",
  2726. Name, Scene.RegionInfo.RegionName);
  2727. return;
  2728. }
  2729. m_lastSize = Appearance.AvatarSize;
  2730. int count = 0;
  2731. m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
  2732. {
  2733. SendAvatarDataToAgent(scenePresence);
  2734. count++;
  2735. });
  2736. m_scene.StatsReporter.AddAgentUpdates(count);
  2737. }
  2738. /// <summary>
  2739. /// Send avatar data for all other root agents to this agent, this agent
  2740. /// can be either a child or root
  2741. /// </summary>
  2742. public void SendOtherAgentsAvatarDataToMe()
  2743. {
  2744. int count = 0;
  2745. m_scene.ForEachRootScenePresence(delegate(ScenePresence scenePresence)
  2746. {
  2747. // only send information about other root agents
  2748. if (scenePresence.UUID == UUID)
  2749. return;
  2750. scenePresence.SendAvatarDataToAgent(this);
  2751. count++;
  2752. });
  2753. m_scene.StatsReporter.AddAgentUpdates(count);
  2754. }
  2755. /// <summary>
  2756. /// Send avatar data to an agent.
  2757. /// </summary>
  2758. /// <param name="avatar"></param>
  2759. public void SendAvatarDataToAgent(ScenePresence avatar)
  2760. {
  2761. //m_log.DebugFormat("[SCENE PRESENCE] SendAvatarDataToAgent from {0} ({1}) to {2} ({3})", Name, UUID, avatar.Name, avatar.UUID);
  2762. avatar.ControllingClient.SendAvatarDataImmediate(this);
  2763. Animator.SendAnimPackToClient(avatar.ControllingClient);
  2764. }
  2765. /// <summary>
  2766. /// Send this agent's appearance to all other root and child agents in the scene
  2767. /// This agent must be root.
  2768. /// </summary>
  2769. public void SendAppearanceToAllOtherAgents()
  2770. {
  2771. // m_log.DebugFormat("[SCENE PRESENCE] SendAppearanceToAllOtherAgents: {0} {1}", Name, UUID);
  2772. // only send update from root agents to other clients; children are only "listening posts"
  2773. if (IsChildAgent)
  2774. {
  2775. m_log.WarnFormat(
  2776. "[SCENE PRESENCE]: Attempt to send avatar data from a child agent for {0} in {1}",
  2777. Name, Scene.RegionInfo.RegionName);
  2778. return;
  2779. }
  2780. int count = 0;
  2781. m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
  2782. {
  2783. // only send information to other root agents
  2784. if (scenePresence.UUID == UUID)
  2785. return;
  2786. SendAppearanceToAgent(scenePresence);
  2787. count++;
  2788. });
  2789. m_scene.StatsReporter.AddAgentUpdates(count);
  2790. }
  2791. /// <summary>
  2792. /// Send appearance from all other root agents to this agent. this agent
  2793. /// can be either root or child
  2794. /// </summary>
  2795. public void SendOtherAgentsAppearanceToMe()
  2796. {
  2797. // m_log.DebugFormat("[SCENE PRESENCE] SendOtherAgentsAppearanceToMe: {0} {1}", Name, UUID);
  2798. int count = 0;
  2799. m_scene.ForEachRootScenePresence(delegate(ScenePresence scenePresence)
  2800. {
  2801. // only send information about other root agents
  2802. if (scenePresence.UUID == UUID)
  2803. return;
  2804. scenePresence.SendAppearanceToAgent(this);
  2805. count++;
  2806. });
  2807. m_scene.StatsReporter.AddAgentUpdates(count);
  2808. }
  2809. /// <summary>
  2810. /// Send appearance data to an agent.
  2811. /// </summary>
  2812. /// <param name="avatar"></param>
  2813. public void SendAppearanceToAgent(ScenePresence avatar)
  2814. {
  2815. // m_log.DebugFormat(
  2816. // "[SCENE PRESENCE]: Sending appearance data from {0} {1} to {2} {3}", Name, m_uuid, avatar.Name, avatar.UUID);
  2817. avatar.ControllingClient.SendAppearance(
  2818. UUID, Appearance.VisualParams, Appearance.Texture.GetBytes());
  2819. }
  2820. #endregion
  2821. #region Significant Movement Method
  2822. /// <summary>
  2823. /// This checks for a significant movement and sends a coarselocationchange update
  2824. /// </summary>
  2825. protected void CheckForSignificantMovement()
  2826. {
  2827. if (Util.GetDistanceTo(AbsolutePosition, posLastSignificantMove) > SIGNIFICANT_MOVEMENT)
  2828. {
  2829. posLastSignificantMove = AbsolutePosition;
  2830. m_scene.EventManager.TriggerSignificantClientMovement(this);
  2831. }
  2832. // Minimum Draw distance is 64 meters, the Radius of the draw distance sphere is 32m
  2833. if (Util.GetDistanceTo(AbsolutePosition, m_lastChildAgentUpdatePosition) >= Scene.ChildReprioritizationDistance)
  2834. {
  2835. m_lastChildAgentUpdatePosition = AbsolutePosition;
  2836. // m_lastChildAgentUpdateCamPosition = CameraPosition;
  2837. ChildAgentDataUpdate cadu = new ChildAgentDataUpdate();
  2838. cadu.ActiveGroupID = UUID.Zero.Guid;
  2839. cadu.AgentID = UUID.Guid;
  2840. cadu.alwaysrun = SetAlwaysRun;
  2841. cadu.AVHeight = Appearance.AvatarHeight;
  2842. cadu.cameraPosition = CameraPosition;
  2843. cadu.drawdistance = DrawDistance;
  2844. cadu.GroupAccess = 0;
  2845. cadu.Position = AbsolutePosition;
  2846. cadu.regionHandle = RegionHandle;
  2847. // Throttles
  2848. float multiplier = 1;
  2849. int childRegions = KnownRegionCount;
  2850. if (childRegions != 0)
  2851. multiplier = 1f / childRegions;
  2852. // Minimum throttle for a child region is 1/4 of the root region throttle
  2853. if (multiplier <= 0.25f)
  2854. multiplier = 0.25f;
  2855. cadu.throttles = ControllingClient.GetThrottlesPacked(multiplier);
  2856. cadu.Velocity = Velocity;
  2857. AgentPosition agentpos = new AgentPosition();
  2858. agentpos.CopyFrom(cadu, ControllingClient.SessionId);
  2859. // Let's get this out of the update loop
  2860. Util.FireAndForget(delegate { m_scene.SendOutChildAgentUpdates(agentpos, this); });
  2861. }
  2862. }
  2863. #endregion
  2864. #region Border Crossing Methods
  2865. /// <summary>
  2866. /// Starts the process of moving an avatar into another region if they are crossing the border.
  2867. /// </summary>
  2868. /// <remarks>
  2869. /// Also removes the avatar from the physical scene if transit has started.
  2870. /// </remarks>
  2871. protected void CheckForBorderCrossing()
  2872. {
  2873. // Check that we we are not a child
  2874. if (IsChildAgent)
  2875. return;
  2876. // If we don't have a PhysActor, we can't cross anyway
  2877. // Also don't do this while sat, sitting avatars cross with the
  2878. // object they sit on. ParentUUID denoted a pending sit, don't
  2879. // interfere with it.
  2880. if (ParentID != 0 || PhysicsActor == null || ParentUUID != UUID.Zero)
  2881. return;
  2882. if (!IsInTransit)
  2883. {
  2884. Vector3 pos2 = AbsolutePosition;
  2885. Vector3 origPosition = pos2;
  2886. Vector3 vel = Velocity;
  2887. // Compute the avatar position in the next physics tick.
  2888. // If the avatar will be crossing, we force the crossing to happen now
  2889. // in the hope that this will make the avatar movement smoother when crossing.
  2890. float timeStep = 0.1f;
  2891. pos2.X = pos2.X + (vel.X * timeStep);
  2892. pos2.Y = pos2.Y + (vel.Y * timeStep);
  2893. pos2.Z = pos2.Z + (vel.Z * timeStep);
  2894. if (!IsInTransit)
  2895. {
  2896. if (!m_scene.PositionIsInCurrentRegion(pos2))
  2897. {
  2898. m_log.DebugFormat("{0} CheckForBorderCrossing: position outside region. {1} in {2} at pos {3}",
  2899. LogHeader, Name, Scene.Name, pos2);
  2900. // Disconnect from the current region
  2901. bool isFlying = Flying;
  2902. RemoveFromPhysicalScene();
  2903. // pos2 is the forcasted position so make that the 'current' position so the crossing
  2904. // code will move us into the newly addressed region.
  2905. m_pos = pos2;
  2906. if (CrossToNewRegion())
  2907. {
  2908. AddToPhysicalScene(isFlying);
  2909. }
  2910. else
  2911. {
  2912. // Tried to make crossing happen but it failed.
  2913. if (m_requestedSitTargetUUID == UUID.Zero)
  2914. {
  2915. m_log.DebugFormat("{0} CheckForBorderCrossing: Crossing failed. Restoring old position.", LogHeader);
  2916. Velocity = Vector3.Zero;
  2917. AbsolutePosition = EnforceSanityOnPosition(origPosition);
  2918. AddToPhysicalScene(isFlying);
  2919. }
  2920. }
  2921. }
  2922. }
  2923. else
  2924. {
  2925. // This constant has been inferred from experimentation
  2926. // I'm not sure what this value should be, so I tried a few values.
  2927. timeStep = 0.04f;
  2928. pos2 = AbsolutePosition;
  2929. pos2.X = pos2.X + (vel.X * timeStep);
  2930. pos2.Y = pos2.Y + (vel.Y * timeStep);
  2931. // Don't touch the Z
  2932. m_pos = pos2;
  2933. m_log.DebugFormat("[SCENE PRESENCE]: In transit m_pos={0}", m_pos);
  2934. }
  2935. }
  2936. }
  2937. // Given a position, make sure it is within the current region.
  2938. // If just outside some border, the returned position will be just inside the border on that side.
  2939. private Vector3 EnforceSanityOnPosition(Vector3 origPosition)
  2940. {
  2941. const float borderFudge = 0.1f;
  2942. Vector3 ret = origPosition;
  2943. // Sanity checking on the position to make sure it is in the region we couldn't cross from
  2944. float extentX = (float)m_scene.RegionInfo.RegionSizeX;
  2945. float extentY = (float)m_scene.RegionInfo.RegionSizeY;
  2946. IRegionCombinerModule combiner = m_scene.RequestModuleInterface<IRegionCombinerModule>();
  2947. if (combiner != null)
  2948. {
  2949. // If a mega-region, the size could be much bigger
  2950. Vector2 megaExtent = combiner.GetSizeOfMegaregion(m_scene.RegionInfo.RegionID);
  2951. extentX = megaExtent.X;
  2952. extentY = megaExtent.Y;
  2953. }
  2954. if (ret.X < 0)
  2955. ret.X = borderFudge;
  2956. else if (ret.X >= extentX)
  2957. ret.X = extentX - borderFudge;
  2958. if (ret.Y < 0)
  2959. ret.Y = borderFudge;
  2960. else if (ret.Y >= extentY)
  2961. ret.Y = extentY - borderFudge;
  2962. return ret;
  2963. }
  2964. /// <summary>
  2965. /// Moves the agent outside the region bounds
  2966. /// Tells neighbor region that we're crossing to it
  2967. /// If the neighbor accepts, remove the agent's viewable avatar from this scene
  2968. /// set them to a child agent.
  2969. /// </summary>
  2970. protected bool CrossToNewRegion()
  2971. {
  2972. try
  2973. {
  2974. return m_scene.CrossAgentToNewRegion(this, Flying);
  2975. }
  2976. catch
  2977. {
  2978. return m_scene.CrossAgentToNewRegion(this, false);
  2979. }
  2980. }
  2981. public void Reset()
  2982. {
  2983. // m_log.DebugFormat("[SCENE PRESENCE]: Resetting {0} in {1}", Name, Scene.RegionInfo.RegionName);
  2984. // Put the child agent back at the center
  2985. AbsolutePosition
  2986. = new Vector3(((float)m_scene.RegionInfo.RegionSizeX * 0.5f), ((float)m_scene.RegionInfo.RegionSizeY * 0.5f), 70);
  2987. Animator.ResetAnimations();
  2988. }
  2989. /// <summary>
  2990. /// Computes which child agents to close when the scene presence moves to another region.
  2991. /// Removes those regions from m_knownRegions.
  2992. /// </summary>
  2993. /// <param name="newRegionX">The new region's x on the map</param>
  2994. /// <param name="newRegionY">The new region's y on the map</param>
  2995. /// <returns></returns>
  2996. public void CloseChildAgents(uint newRegionX, uint newRegionY)
  2997. {
  2998. List<ulong> byebyeRegions = new List<ulong>();
  2999. List<ulong> knownRegions = KnownRegionHandles;
  3000. m_log.DebugFormat(
  3001. "[SCENE PRESENCE]: Closing child agents. Checking {0} regions in {1}",
  3002. knownRegions.Count, Scene.RegionInfo.RegionName);
  3003. //DumpKnownRegions();
  3004. foreach (ulong handle in knownRegions)
  3005. {
  3006. // Don't close the agent on this region yet
  3007. if (handle != Scene.RegionInfo.RegionHandle)
  3008. {
  3009. uint x, y;
  3010. Util.RegionHandleToRegionLoc(handle, out x, out y);
  3011. // m_log.Debug("---> x: " + x + "; newx:" + newRegionX + "; Abs:" + (int)Math.Abs((int)(x - newRegionX)));
  3012. // m_log.Debug("---> y: " + y + "; newy:" + newRegionY + "; Abs:" + (int)Math.Abs((int)(y - newRegionY)));
  3013. if (Util.IsOutsideView(DrawDistance, x, newRegionX, y, newRegionY))
  3014. {
  3015. byebyeRegions.Add(handle);
  3016. }
  3017. }
  3018. }
  3019. if (byebyeRegions.Count > 0)
  3020. {
  3021. m_log.Debug("[SCENE PRESENCE]: Closing " + byebyeRegions.Count + " child agents");
  3022. AgentCircuitData acd = Scene.AuthenticateHandler.GetAgentCircuitData(UUID);
  3023. string auth = string.Empty;
  3024. if (acd != null)
  3025. auth = acd.SessionID.ToString();
  3026. m_scene.SceneGridService.SendCloseChildAgentConnections(ControllingClient.AgentId, auth, byebyeRegions);
  3027. }
  3028. foreach (ulong handle in byebyeRegions)
  3029. {
  3030. RemoveNeighbourRegion(handle);
  3031. }
  3032. }
  3033. #endregion
  3034. /// <summary>
  3035. /// This allows the Sim owner the abiility to kick users from their sim currently.
  3036. /// It tells the client that the agent has permission to do so.
  3037. /// </summary>
  3038. public void GrantGodlikePowers(UUID agentID, UUID sessionID, UUID token, bool godStatus)
  3039. {
  3040. if (godStatus)
  3041. {
  3042. // For now, assign god level 200 to anyone
  3043. // who is granted god powers, but has no god level set.
  3044. //
  3045. UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, agentID);
  3046. if (account != null)
  3047. {
  3048. if (account.UserLevel > 0)
  3049. GodLevel = account.UserLevel;
  3050. else
  3051. GodLevel = 200;
  3052. }
  3053. }
  3054. else
  3055. {
  3056. GodLevel = 0;
  3057. }
  3058. ControllingClient.SendAdminResponse(token, (uint)GodLevel);
  3059. }
  3060. #region Child Agent Updates
  3061. public void UpdateChildAgent(AgentData cAgentData)
  3062. {
  3063. // m_log.Debug(" >>> ChildAgentDataUpdate <<< " + Scene.RegionInfo.RegionName);
  3064. if (!IsChildAgent)
  3065. return;
  3066. CopyFrom(cAgentData);
  3067. }
  3068. private static Vector3 marker = new Vector3(-1f, -1f, -1f);
  3069. /// <summary>
  3070. /// This updates important decision making data about a child agent
  3071. /// The main purpose is to figure out what objects to send to a child agent that's in a neighboring region
  3072. /// </summary>
  3073. public void UpdateChildAgent(AgentPosition cAgentData, uint tRegionX, uint tRegionY, uint rRegionX, uint rRegionY)
  3074. {
  3075. if (!IsChildAgent)
  3076. return;
  3077. //m_log.Debug(" >>> ChildAgentPositionUpdate <<< " + rRegionX + "-" + rRegionY);
  3078. // Find the distance (in meters) between the two regions
  3079. uint shiftx = Util.RegionToWorldLoc(rRegionX - tRegionX);
  3080. uint shifty = Util.RegionToWorldLoc(rRegionY - tRegionY);
  3081. Vector3 offset = new Vector3(shiftx, shifty, 0f);
  3082. // When we get to the point of re-computing neighbors everytime this
  3083. // changes, then start using the agent's drawdistance rather than the
  3084. // region's draw distance.
  3085. // DrawDistance = cAgentData.Far;
  3086. DrawDistance = Scene.DefaultDrawDistance;
  3087. if (cAgentData.Position != marker) // UGH!!
  3088. m_pos = cAgentData.Position + offset;
  3089. if (Vector3.Distance(AbsolutePosition, posLastSignificantMove) >= Scene.ChildReprioritizationDistance)
  3090. {
  3091. posLastSignificantMove = AbsolutePosition;
  3092. ReprioritizeUpdates();
  3093. }
  3094. CameraPosition = cAgentData.Center + offset;
  3095. if ((cAgentData.Throttles != null) && cAgentData.Throttles.Length > 0)
  3096. ControllingClient.SetChildAgentThrottle(cAgentData.Throttles);
  3097. //cAgentData.AVHeight;
  3098. RegionHandle = cAgentData.RegionHandle;
  3099. //m_velocity = cAgentData.Velocity;
  3100. }
  3101. public void CopyTo(AgentData cAgent)
  3102. {
  3103. cAgent.CallbackURI = m_callbackURI;
  3104. cAgent.AgentID = UUID;
  3105. cAgent.RegionID = Scene.RegionInfo.RegionID;
  3106. cAgent.SessionID = ControllingClient.SessionId;
  3107. cAgent.Position = AbsolutePosition;
  3108. cAgent.Velocity = m_velocity;
  3109. cAgent.Center = CameraPosition;
  3110. cAgent.AtAxis = CameraAtAxis;
  3111. cAgent.LeftAxis = CameraLeftAxis;
  3112. cAgent.UpAxis = CameraUpAxis;
  3113. cAgent.Far = DrawDistance;
  3114. // Throttles
  3115. float multiplier = 1;
  3116. int childRegions = KnownRegionCount;
  3117. if (childRegions != 0)
  3118. multiplier = 1f / childRegions;
  3119. // Minimum throttle for a child region is 1/4 of the root region throttle
  3120. if (multiplier <= 0.25f)
  3121. multiplier = 0.25f;
  3122. cAgent.Throttles = ControllingClient.GetThrottlesPacked(multiplier);
  3123. cAgent.HeadRotation = m_headrotation;
  3124. cAgent.BodyRotation = Rotation;
  3125. cAgent.ControlFlags = (uint)m_AgentControlFlags;
  3126. if (m_scene.Permissions.IsGod(new UUID(cAgent.AgentID)))
  3127. cAgent.GodLevel = (byte)GodLevel;
  3128. else
  3129. cAgent.GodLevel = (byte) 0;
  3130. cAgent.AlwaysRun = SetAlwaysRun;
  3131. cAgent.Appearance = new AvatarAppearance(Appearance);
  3132. cAgent.ParentPart = ParentUUID;
  3133. cAgent.SitOffset = PrevSitOffset;
  3134. lock (scriptedcontrols)
  3135. {
  3136. ControllerData[] controls = new ControllerData[scriptedcontrols.Count];
  3137. int i = 0;
  3138. foreach (ScriptControllers c in scriptedcontrols.Values)
  3139. {
  3140. controls[i++] = new ControllerData(c.objectID, c.itemID, (uint)c.ignoreControls, (uint)c.eventControls);
  3141. }
  3142. cAgent.Controllers = controls;
  3143. }
  3144. // Animations
  3145. try
  3146. {
  3147. cAgent.Anims = Animator.Animations.ToArray();
  3148. }
  3149. catch { }
  3150. cAgent.DefaultAnim = Animator.Animations.DefaultAnimation;
  3151. cAgent.AnimState = Animator.Animations.ImplicitDefaultAnimation;
  3152. if (Scene.AttachmentsModule != null)
  3153. Scene.AttachmentsModule.CopyAttachments(this, cAgent);
  3154. }
  3155. private void CopyFrom(AgentData cAgent)
  3156. {
  3157. lock (m_originRegionIDAccessLock)
  3158. m_originRegionID = cAgent.RegionID;
  3159. m_callbackURI = cAgent.CallbackURI;
  3160. // m_log.DebugFormat(
  3161. // "[SCENE PRESENCE]: Set callback for {0} in {1} to {2} in CopyFrom()",
  3162. // Name, m_scene.RegionInfo.RegionName, m_callbackURI);
  3163. m_pos = cAgent.Position;
  3164. m_velocity = cAgent.Velocity;
  3165. CameraPosition = cAgent.Center;
  3166. CameraAtAxis = cAgent.AtAxis;
  3167. CameraLeftAxis = cAgent.LeftAxis;
  3168. CameraUpAxis = cAgent.UpAxis;
  3169. ParentUUID = cAgent.ParentPart;
  3170. PrevSitOffset = cAgent.SitOffset;
  3171. // When we get to the point of re-computing neighbors everytime this
  3172. // changes, then start using the agent's drawdistance rather than the
  3173. // region's draw distance.
  3174. // DrawDistance = cAgent.Far;
  3175. DrawDistance = Scene.DefaultDrawDistance;
  3176. if ((cAgent.Throttles != null) && cAgent.Throttles.Length > 0)
  3177. ControllingClient.SetChildAgentThrottle(cAgent.Throttles);
  3178. m_headrotation = cAgent.HeadRotation;
  3179. Rotation = cAgent.BodyRotation;
  3180. m_AgentControlFlags = (AgentManager.ControlFlags)cAgent.ControlFlags;
  3181. if (m_scene.Permissions.IsGod(new UUID(cAgent.AgentID)))
  3182. GodLevel = cAgent.GodLevel;
  3183. SetAlwaysRun = cAgent.AlwaysRun;
  3184. Appearance = new AvatarAppearance(cAgent.Appearance);
  3185. if (PhysicsActor != null)
  3186. {
  3187. bool isFlying = Flying;
  3188. RemoveFromPhysicalScene();
  3189. AddToPhysicalScene(isFlying);
  3190. }
  3191. try
  3192. {
  3193. lock (scriptedcontrols)
  3194. {
  3195. if (cAgent.Controllers != null)
  3196. {
  3197. scriptedcontrols.Clear();
  3198. foreach (ControllerData c in cAgent.Controllers)
  3199. {
  3200. ScriptControllers sc = new ScriptControllers();
  3201. sc.objectID = c.ObjectID;
  3202. sc.itemID = c.ItemID;
  3203. sc.ignoreControls = (ScriptControlled)c.IgnoreControls;
  3204. sc.eventControls = (ScriptControlled)c.EventControls;
  3205. scriptedcontrols[sc.itemID] = sc;
  3206. }
  3207. }
  3208. }
  3209. }
  3210. catch { }
  3211. // FIXME: Why is this null check necessary? Where are the cases where we get a null Anims object?
  3212. if (cAgent.Anims != null)
  3213. Animator.Animations.FromArray(cAgent.Anims);
  3214. if (cAgent.DefaultAnim != null)
  3215. Animator.Animations.SetDefaultAnimation(cAgent.DefaultAnim.AnimID, cAgent.DefaultAnim.SequenceNum, UUID.Zero);
  3216. if (cAgent.AnimState != null)
  3217. Animator.Animations.SetImplicitDefaultAnimation(cAgent.AnimState.AnimID, cAgent.AnimState.SequenceNum, UUID.Zero);
  3218. if (Scene.AttachmentsModule != null)
  3219. Scene.AttachmentsModule.CopyAttachments(cAgent, this);
  3220. }
  3221. public bool CopyAgent(out IAgentData agent)
  3222. {
  3223. agent = new CompleteAgentData();
  3224. CopyTo((AgentData)agent);
  3225. return true;
  3226. }
  3227. #endregion Child Agent Updates
  3228. /// <summary>
  3229. /// Handles part of the PID controller function for moving an avatar.
  3230. /// </summary>
  3231. public void UpdateMovement()
  3232. {
  3233. if (m_forceToApply.HasValue)
  3234. {
  3235. Vector3 force = m_forceToApply.Value;
  3236. Velocity = force;
  3237. m_forceToApply = null;
  3238. TriggerScenePresenceUpdated();
  3239. }
  3240. }
  3241. /// <summary>
  3242. /// Adds a physical representation of the avatar to the Physics plugin
  3243. /// </summary>
  3244. public void AddToPhysicalScene(bool isFlying)
  3245. {
  3246. // m_log.DebugFormat(
  3247. // "[SCENE PRESENCE]: Adding physics actor for {0}, ifFlying = {1} in {2}",
  3248. // Name, isFlying, Scene.RegionInfo.RegionName);
  3249. if (PhysicsActor != null)
  3250. {
  3251. m_log.ErrorFormat(
  3252. "[SCENE PRESENCE]: Adding physics actor for {0} to {1} but this scene presence already has a physics actor",
  3253. Name, Scene.RegionInfo.RegionName);
  3254. }
  3255. if (Appearance.AvatarHeight == 0)
  3256. // Appearance.SetHeight();
  3257. Appearance.SetSize(new Vector3(0.45f,0.6f,1.9f));
  3258. PhysicsScene scene = m_scene.PhysicsScene;
  3259. Vector3 pVec = AbsolutePosition;
  3260. /*
  3261. PhysicsActor = scene.AddAvatar(
  3262. LocalId, Firstname + "." + Lastname, pVec,
  3263. new Vector3(0.45f, 0.6f, Appearance.AvatarHeight), isFlying);
  3264. */
  3265. PhysicsActor = scene.AddAvatar(
  3266. LocalId, Firstname + "." + Lastname, pVec,
  3267. Appearance.AvatarBoxSize, isFlying);
  3268. //PhysicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients;
  3269. PhysicsActor.OnCollisionUpdate += PhysicsCollisionUpdate;
  3270. PhysicsActor.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong
  3271. PhysicsActor.SubscribeEvents(100);
  3272. PhysicsActor.LocalID = LocalId;
  3273. }
  3274. private void OutOfBoundsCall(Vector3 pos)
  3275. {
  3276. //bool flying = Flying;
  3277. //RemoveFromPhysicalScene();
  3278. //AddToPhysicalScene(flying);
  3279. if (ControllingClient != null)
  3280. ControllingClient.SendAgentAlertMessage("Physics is having a problem with your avatar. You may not be able to move until you relog.", true);
  3281. }
  3282. /// <summary>
  3283. /// Event called by the physics plugin to tell the avatar about a collision.
  3284. /// </summary>
  3285. /// <remarks>
  3286. /// This function is called continuously, even when there are no collisions. If the avatar is walking on the
  3287. /// ground or a prim then there will be collision information between the avatar and the surface.
  3288. ///
  3289. /// FIXME: However, we can't safely avoid calling this yet where there are no collisions without analyzing whether
  3290. /// any part of this method is relying on an every-frame call.
  3291. /// </remarks>
  3292. /// <param name="e"></param>
  3293. public void PhysicsCollisionUpdate(EventArgs e)
  3294. {
  3295. if (IsChildAgent || Animator == null)
  3296. return;
  3297. //if ((Math.Abs(Velocity.X) > 0.1e-9f) || (Math.Abs(Velocity.Y) > 0.1e-9f))
  3298. // The Physics Scene will send updates every 500 ms grep: PhysicsActor.SubscribeEvents(
  3299. // as of this comment the interval is set in AddToPhysicalScene
  3300. // if (m_updateCount > 0)
  3301. // {
  3302. if (Animator.UpdateMovementAnimations())
  3303. TriggerScenePresenceUpdated();
  3304. // m_updateCount--;
  3305. // }
  3306. CollisionEventUpdate collisionData = (CollisionEventUpdate)e;
  3307. Dictionary<uint, ContactPoint> coldata = collisionData.m_objCollisionList;
  3308. // // No collisions at all means we may be flying. Update always
  3309. // // to make falling work
  3310. // if (m_lastColCount != coldata.Count || coldata.Count == 0)
  3311. // {
  3312. // m_updateCount = UPDATE_COUNT;
  3313. // m_lastColCount = coldata.Count;
  3314. // }
  3315. CollisionPlane = Vector4.UnitW;
  3316. // Gods do not take damage and Invulnerable is set depending on parcel/region flags
  3317. if (Invulnerable || GodLevel > 0)
  3318. return;
  3319. // The following may be better in the ICombatModule
  3320. // probably tweaking of the values for ground and normal prim collisions will be needed
  3321. float starthealth = Health;
  3322. uint killerObj = 0;
  3323. SceneObjectPart part = null;
  3324. foreach (uint localid in coldata.Keys)
  3325. {
  3326. if (localid == 0)
  3327. {
  3328. part = null;
  3329. }
  3330. else
  3331. {
  3332. part = Scene.GetSceneObjectPart(localid);
  3333. }
  3334. if (part != null)
  3335. {
  3336. // Ignore if it has been deleted or volume detect
  3337. if (!part.ParentGroup.IsDeleted && !part.ParentGroup.IsVolumeDetect)
  3338. {
  3339. if (part.ParentGroup.Damage > 0.0f)
  3340. {
  3341. // Something with damage...
  3342. Health -= part.ParentGroup.Damage;
  3343. part.ParentGroup.Scene.DeleteSceneObject(part.ParentGroup, false);
  3344. }
  3345. else
  3346. {
  3347. // An ordinary prim
  3348. if (coldata[localid].PenetrationDepth >= 0.10f)
  3349. Health -= coldata[localid].PenetrationDepth * 5.0f;
  3350. }
  3351. }
  3352. }
  3353. else
  3354. {
  3355. // 0 is the ground
  3356. // what about collisions with other avatars?
  3357. if (localid == 0 && coldata[localid].PenetrationDepth >= 0.10f)
  3358. Health -= coldata[localid].PenetrationDepth * 5.0f;
  3359. }
  3360. if (Health <= 0.0f)
  3361. {
  3362. if (localid != 0)
  3363. killerObj = localid;
  3364. }
  3365. //m_log.Debug("[AVATAR]: Collision with localid: " + localid.ToString() + " at depth: " + coldata[localid].ToString());
  3366. }
  3367. //Health = 100;
  3368. if (!Invulnerable)
  3369. {
  3370. if (starthealth != Health)
  3371. {
  3372. ControllingClient.SendHealth(Health);
  3373. }
  3374. if (Health <= 0)
  3375. {
  3376. m_scene.EventManager.TriggerAvatarKill(killerObj, this);
  3377. }
  3378. if (starthealth == Health && Health < 100.0f)
  3379. {
  3380. Health += 0.03f;
  3381. if (Health > 100.0f)
  3382. Health = 100.0f;
  3383. ControllingClient.SendHealth(Health);
  3384. }
  3385. }
  3386. }
  3387. public void setHealthWithUpdate(float health)
  3388. {
  3389. Health = health;
  3390. ControllingClient.SendHealth(Health);
  3391. }
  3392. protected internal void Close()
  3393. {
  3394. // Clear known regions
  3395. KnownRegions = new Dictionary<ulong, string>();
  3396. lock (m_reprioritization_timer)
  3397. {
  3398. m_reprioritization_timer.Enabled = false;
  3399. m_reprioritization_timer.Elapsed -= new ElapsedEventHandler(Reprioritize);
  3400. }
  3401. // I don't get it but mono crashes when you try to dispose of this timer,
  3402. // unsetting the elapsed callback should be enough to allow for cleanup however.
  3403. // m_reprioritizationTimer.Dispose();
  3404. RemoveFromPhysicalScene();
  3405. m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
  3406. // if (Animator != null)
  3407. // Animator.Close();
  3408. Animator = null;
  3409. LifecycleState = ScenePresenceState.Removed;
  3410. }
  3411. public void AddAttachment(SceneObjectGroup gobj)
  3412. {
  3413. lock (m_attachments)
  3414. {
  3415. // This may be true when the attachment comes back
  3416. // from serialization after login. Clear it.
  3417. gobj.IsDeleted = false;
  3418. m_attachments.Add(gobj);
  3419. }
  3420. }
  3421. /// <summary>
  3422. /// Get all the presence's attachments.
  3423. /// </summary>
  3424. /// <returns>A copy of the list which contains the attachments.</returns>
  3425. public List<SceneObjectGroup> GetAttachments()
  3426. {
  3427. lock (m_attachments)
  3428. return new List<SceneObjectGroup>(m_attachments);
  3429. }
  3430. /// <summary>
  3431. /// Get the scene objects attached to the given point.
  3432. /// </summary>
  3433. /// <param name="attachmentPoint"></param>
  3434. /// <returns>Returns an empty list if there were no attachments at the point.</returns>
  3435. public List<SceneObjectGroup> GetAttachments(uint attachmentPoint)
  3436. {
  3437. List<SceneObjectGroup> attachments = new List<SceneObjectGroup>();
  3438. if (attachmentPoint >= 0)
  3439. {
  3440. lock (m_attachments)
  3441. {
  3442. foreach (SceneObjectGroup so in m_attachments)
  3443. {
  3444. if (attachmentPoint == so.AttachmentPoint)
  3445. attachments.Add(so);
  3446. }
  3447. }
  3448. }
  3449. return attachments;
  3450. }
  3451. public bool HasAttachments()
  3452. {
  3453. lock (m_attachments)
  3454. return m_attachments.Count > 0;
  3455. }
  3456. /// <summary>
  3457. /// Returns the total count of scripts in all parts inventories.
  3458. /// </summary>
  3459. public int ScriptCount()
  3460. {
  3461. int count = 0;
  3462. lock (m_attachments)
  3463. {
  3464. foreach (SceneObjectGroup gobj in m_attachments)
  3465. {
  3466. if (gobj != null)
  3467. {
  3468. count += gobj.ScriptCount();
  3469. }
  3470. }
  3471. }
  3472. return count;
  3473. }
  3474. /// <summary>
  3475. /// A float the value is a representative execution time in milliseconds of all scripts in all attachments.
  3476. /// </summary>
  3477. public float ScriptExecutionTime()
  3478. {
  3479. float time = 0.0f;
  3480. lock (m_attachments)
  3481. {
  3482. foreach (SceneObjectGroup gobj in m_attachments)
  3483. {
  3484. if (gobj != null)
  3485. {
  3486. time += gobj.ScriptExecutionTime();
  3487. }
  3488. }
  3489. }
  3490. return time;
  3491. }
  3492. /// <summary>
  3493. /// Returns the total count of running scripts in all parts.
  3494. /// </summary>
  3495. public int RunningScriptCount()
  3496. {
  3497. int count = 0;
  3498. lock (m_attachments)
  3499. {
  3500. foreach (SceneObjectGroup gobj in m_attachments)
  3501. {
  3502. if (gobj != null)
  3503. {
  3504. count += gobj.RunningScriptCount();
  3505. }
  3506. }
  3507. }
  3508. return count;
  3509. }
  3510. public bool HasScriptedAttachments()
  3511. {
  3512. lock (m_attachments)
  3513. {
  3514. foreach (SceneObjectGroup gobj in m_attachments)
  3515. {
  3516. if (gobj != null)
  3517. {
  3518. if (gobj.RootPart.Inventory.ContainsScripts())
  3519. return true;
  3520. }
  3521. }
  3522. }
  3523. return false;
  3524. }
  3525. public void RemoveAttachment(SceneObjectGroup gobj)
  3526. {
  3527. lock (m_attachments)
  3528. m_attachments.Remove(gobj);
  3529. }
  3530. /// <summary>
  3531. /// Clear all attachments
  3532. /// </summary>
  3533. public void ClearAttachments()
  3534. {
  3535. lock (m_attachments)
  3536. m_attachments.Clear();
  3537. }
  3538. /// <summary>
  3539. /// This is currently just being done for information.
  3540. /// </summary>
  3541. public bool ValidateAttachments()
  3542. {
  3543. bool validated = true;
  3544. lock (m_attachments)
  3545. {
  3546. // Validate
  3547. foreach (SceneObjectGroup gobj in m_attachments)
  3548. {
  3549. if (gobj == null)
  3550. {
  3551. m_log.WarnFormat(
  3552. "[SCENE PRESENCE]: Failed to validate an attachment for {0} since it was null. Continuing", Name);
  3553. validated = false;
  3554. }
  3555. else if (gobj.IsDeleted)
  3556. {
  3557. m_log.WarnFormat(
  3558. "[SCENE PRESENCE]: Failed to validate attachment {0} {1} for {2} since it had been deleted. Continuing",
  3559. gobj.Name, gobj.UUID, Name);
  3560. validated = false;
  3561. }
  3562. }
  3563. }
  3564. return validated;
  3565. }
  3566. /// <summary>
  3567. /// Send a script event to this scene presence's attachments
  3568. /// </summary>
  3569. /// <param name="eventName">The name of the event</param>
  3570. /// <param name="args">The arguments for the event</param>
  3571. public void SendScriptEventToAttachments(string eventName, Object[] args)
  3572. {
  3573. Util.FireAndForget(delegate(object x)
  3574. {
  3575. if (m_scriptEngines.Length == 0)
  3576. return;
  3577. lock (m_attachments)
  3578. {
  3579. foreach (SceneObjectGroup grp in m_attachments)
  3580. {
  3581. // 16384 is CHANGED_ANIMATION
  3582. //
  3583. // Send this to all attachment root prims
  3584. //
  3585. foreach (IScriptModule m in m_scriptEngines)
  3586. {
  3587. if (m == null) // No script engine loaded
  3588. continue;
  3589. m.PostObjectEvent(grp.RootPart.UUID, "changed", new Object[] { (int)Changed.ANIMATION });
  3590. }
  3591. }
  3592. }
  3593. });
  3594. }
  3595. /// <summary>
  3596. /// Gets the mass.
  3597. /// </summary>
  3598. /// <returns>
  3599. /// The mass.
  3600. /// </returns>
  3601. public float GetMass()
  3602. {
  3603. PhysicsActor pa = PhysicsActor;
  3604. if (pa != null)
  3605. return pa.Mass;
  3606. else
  3607. return 0;
  3608. }
  3609. internal void PushForce(Vector3 impulse)
  3610. {
  3611. if (PhysicsActor != null)
  3612. {
  3613. PhysicsActor.AddForce(impulse,true);
  3614. }
  3615. }
  3616. public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID)
  3617. {
  3618. SceneObjectPart p = m_scene.GetSceneObjectPart(Obj_localID);
  3619. if (p == null)
  3620. return;
  3621. ControllingClient.SendTakeControls(controls, false, false);
  3622. ControllingClient.SendTakeControls(controls, true, false);
  3623. ScriptControllers obj = new ScriptControllers();
  3624. obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
  3625. obj.eventControls = ScriptControlled.CONTROL_ZERO;
  3626. obj.objectID = p.ParentGroup.UUID;
  3627. obj.itemID = Script_item_UUID;
  3628. if (pass_on == 0 && accept == 0)
  3629. {
  3630. IgnoredControls |= (ScriptControlled)controls;
  3631. obj.ignoreControls = (ScriptControlled)controls;
  3632. }
  3633. if (pass_on == 0 && accept == 1)
  3634. {
  3635. IgnoredControls |= (ScriptControlled)controls;
  3636. obj.ignoreControls = (ScriptControlled)controls;
  3637. obj.eventControls = (ScriptControlled)controls;
  3638. }
  3639. if (pass_on == 1 && accept == 1)
  3640. {
  3641. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  3642. obj.eventControls = (ScriptControlled)controls;
  3643. obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
  3644. }
  3645. lock (scriptedcontrols)
  3646. {
  3647. if (pass_on == 1 && accept == 0)
  3648. {
  3649. IgnoredControls &= ~(ScriptControlled)controls;
  3650. if (scriptedcontrols.ContainsKey(Script_item_UUID))
  3651. scriptedcontrols.Remove(Script_item_UUID);
  3652. }
  3653. else
  3654. {
  3655. scriptedcontrols[Script_item_UUID] = obj;
  3656. }
  3657. }
  3658. ControllingClient.SendTakeControls(controls, pass_on == 1 ? true : false, true);
  3659. }
  3660. public void HandleForceReleaseControls(IClientAPI remoteClient, UUID agentID)
  3661. {
  3662. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  3663. lock (scriptedcontrols)
  3664. {
  3665. scriptedcontrols.Clear();
  3666. }
  3667. ControllingClient.SendTakeControls(int.MaxValue, false, false);
  3668. }
  3669. private void UnRegisterSeatControls(UUID obj)
  3670. {
  3671. List<UUID> takers = new List<UUID>();
  3672. foreach (ScriptControllers c in scriptedcontrols.Values)
  3673. {
  3674. if (c.objectID == obj)
  3675. takers.Add(c.itemID);
  3676. }
  3677. foreach (UUID t in takers)
  3678. {
  3679. UnRegisterControlEventsToScript(0, t);
  3680. }
  3681. }
  3682. public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID)
  3683. {
  3684. ScriptControllers takecontrols;
  3685. lock (scriptedcontrols)
  3686. {
  3687. if (scriptedcontrols.TryGetValue(Script_item_UUID, out takecontrols))
  3688. {
  3689. ScriptControlled sctc = takecontrols.eventControls;
  3690. ControllingClient.SendTakeControls((int)sctc, false, false);
  3691. ControllingClient.SendTakeControls((int)sctc, true, false);
  3692. scriptedcontrols.Remove(Script_item_UUID);
  3693. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  3694. foreach (ScriptControllers scData in scriptedcontrols.Values)
  3695. {
  3696. IgnoredControls |= scData.ignoreControls;
  3697. }
  3698. }
  3699. }
  3700. }
  3701. private void SendControlsToScripts(uint flags)
  3702. {
  3703. // Notify the scripts only after calling UpdateMovementAnimations(), so that if a script
  3704. // (e.g., a walking script) checks which animation is active it will be the correct animation.
  3705. lock (scriptedcontrols)
  3706. {
  3707. if (scriptedcontrols.Count <= 0)
  3708. return;
  3709. ScriptControlled allflags = ScriptControlled.CONTROL_ZERO;
  3710. if (MouseDown)
  3711. {
  3712. allflags = LastCommands & (ScriptControlled.CONTROL_ML_LBUTTON | ScriptControlled.CONTROL_LBUTTON);
  3713. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP) != 0 || (flags & unchecked((uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_UP)) != 0)
  3714. {
  3715. allflags = ScriptControlled.CONTROL_ZERO;
  3716. MouseDown = true;
  3717. }
  3718. }
  3719. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN) != 0)
  3720. {
  3721. allflags |= ScriptControlled.CONTROL_ML_LBUTTON;
  3722. MouseDown = true;
  3723. }
  3724. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0)
  3725. {
  3726. allflags |= ScriptControlled.CONTROL_LBUTTON;
  3727. MouseDown = true;
  3728. }
  3729. // find all activated controls, whether the scripts are interested in them or not
  3730. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS) != 0)
  3731. {
  3732. allflags |= ScriptControlled.CONTROL_FWD;
  3733. }
  3734. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG) != 0)
  3735. {
  3736. allflags |= ScriptControlled.CONTROL_BACK;
  3737. }
  3738. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS) != 0)
  3739. {
  3740. allflags |= ScriptControlled.CONTROL_UP;
  3741. }
  3742. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0)
  3743. {
  3744. allflags |= ScriptControlled.CONTROL_DOWN;
  3745. }
  3746. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS) != 0)
  3747. {
  3748. allflags |= ScriptControlled.CONTROL_LEFT;
  3749. }
  3750. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG) != 0)
  3751. {
  3752. allflags |= ScriptControlled.CONTROL_RIGHT;
  3753. }
  3754. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  3755. {
  3756. allflags |= ScriptControlled.CONTROL_ROT_RIGHT;
  3757. }
  3758. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0)
  3759. {
  3760. allflags |= ScriptControlled.CONTROL_ROT_LEFT;
  3761. }
  3762. // optimization; we have to check per script, but if nothing is pressed and nothing changed, we can skip that
  3763. if (allflags != ScriptControlled.CONTROL_ZERO || allflags != LastCommands)
  3764. {
  3765. foreach (KeyValuePair<UUID, ScriptControllers> kvp in scriptedcontrols)
  3766. {
  3767. UUID scriptUUID = kvp.Key;
  3768. ScriptControllers scriptControlData = kvp.Value;
  3769. ScriptControlled localHeld = allflags & scriptControlData.eventControls; // the flags interesting for us
  3770. ScriptControlled localLast = LastCommands & scriptControlData.eventControls; // the activated controls in the last cycle
  3771. ScriptControlled localChange = localHeld ^ localLast; // the changed bits
  3772. if (localHeld != ScriptControlled.CONTROL_ZERO || localChange != ScriptControlled.CONTROL_ZERO)
  3773. {
  3774. // only send if still pressed or just changed
  3775. m_scene.EventManager.TriggerControlEvent(scriptUUID, UUID, (uint)localHeld, (uint)localChange);
  3776. }
  3777. }
  3778. }
  3779. LastCommands = allflags;
  3780. }
  3781. }
  3782. internal static AgentManager.ControlFlags RemoveIgnoredControls(AgentManager.ControlFlags flags, ScriptControlled ignored)
  3783. {
  3784. if (ignored == ScriptControlled.CONTROL_ZERO)
  3785. return flags;
  3786. if ((ignored & ScriptControlled.CONTROL_BACK) != 0)
  3787. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG);
  3788. if ((ignored & ScriptControlled.CONTROL_FWD) != 0)
  3789. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS | AgentManager.ControlFlags.AGENT_CONTROL_AT_POS);
  3790. if ((ignored & ScriptControlled.CONTROL_DOWN) != 0)
  3791. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG);
  3792. if ((ignored & ScriptControlled.CONTROL_UP) != 0)
  3793. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS | AgentManager.ControlFlags.AGENT_CONTROL_UP_POS);
  3794. if ((ignored & ScriptControlled.CONTROL_LEFT) != 0)
  3795. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS);
  3796. if ((ignored & ScriptControlled.CONTROL_RIGHT) != 0)
  3797. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG | AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG);
  3798. if ((ignored & ScriptControlled.CONTROL_ROT_LEFT) != 0)
  3799. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG);
  3800. if ((ignored & ScriptControlled.CONTROL_ROT_RIGHT) != 0)
  3801. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS);
  3802. if ((ignored & ScriptControlled.CONTROL_ML_LBUTTON) != 0)
  3803. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN);
  3804. if ((ignored & ScriptControlled.CONTROL_LBUTTON) != 0)
  3805. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP | AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN);
  3806. //DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS,
  3807. //DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG,
  3808. //DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS,
  3809. //DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG,
  3810. //DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS,
  3811. //DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG,
  3812. //DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG
  3813. return flags;
  3814. }
  3815. private void ReprioritizeUpdates()
  3816. {
  3817. if (Scene.IsReprioritizationEnabled && Scene.UpdatePrioritizationScheme != UpdatePrioritizationSchemes.Time)
  3818. {
  3819. lock (m_reprioritization_timer)
  3820. {
  3821. if (!m_reprioritizing)
  3822. m_reprioritization_timer.Enabled = m_reprioritizing = true;
  3823. else
  3824. m_reprioritization_called = true;
  3825. }
  3826. }
  3827. }
  3828. private void Reprioritize(object sender, ElapsedEventArgs e)
  3829. {
  3830. ControllingClient.ReprioritizeUpdates();
  3831. lock (m_reprioritization_timer)
  3832. {
  3833. m_reprioritization_timer.Enabled = m_reprioritizing = m_reprioritization_called;
  3834. m_reprioritization_called = false;
  3835. }
  3836. }
  3837. private void CheckLandingPoint(ref Vector3 pos)
  3838. {
  3839. // Never constrain lures
  3840. if ((TeleportFlags & TeleportFlags.ViaLure) != 0)
  3841. return;
  3842. if (m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
  3843. return;
  3844. ILandObject land = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
  3845. if (land.LandData.LandingType == (byte)LandingType.LandingPoint &&
  3846. land.LandData.UserLocation != Vector3.Zero &&
  3847. land.LandData.OwnerID != m_uuid &&
  3848. (!m_scene.Permissions.IsGod(m_uuid)) &&
  3849. (!m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid)))
  3850. {
  3851. float curr = Vector3.Distance(AbsolutePosition, pos);
  3852. if (Vector3.Distance(land.LandData.UserLocation, pos) < curr)
  3853. pos = land.LandData.UserLocation;
  3854. else
  3855. ControllingClient.SendAlertMessage("Can't teleport closer to destination");
  3856. }
  3857. }
  3858. private void CheckAndAdjustTelehub(SceneObjectGroup telehub, ref Vector3 pos)
  3859. {
  3860. if ((m_teleportFlags & (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)) ==
  3861. (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID) ||
  3862. (m_scene.TelehubAllowLandmarks == true ? false : ((m_teleportFlags & TeleportFlags.ViaLandmark) != 0 )) ||
  3863. (m_teleportFlags & TeleportFlags.ViaLocation) != 0 ||
  3864. (m_teleportFlags & Constants.TeleportFlags.ViaHGLogin) != 0)
  3865. {
  3866. if (GodLevel < 200 &&
  3867. ((!m_scene.Permissions.IsGod(m_uuid) &&
  3868. !m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid)) ||
  3869. (m_teleportFlags & TeleportFlags.ViaLocation) != 0 ||
  3870. (m_teleportFlags & Constants.TeleportFlags.ViaHGLogin) != 0))
  3871. {
  3872. SpawnPoint[] spawnPoints = m_scene.RegionInfo.RegionSettings.SpawnPoints().ToArray();
  3873. if (spawnPoints.Length == 0)
  3874. {
  3875. if(m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid))
  3876. {
  3877. pos.X = 128.0f;
  3878. pos.Y = 128.0f;
  3879. }
  3880. return;
  3881. }
  3882. int index;
  3883. bool selected = false;
  3884. switch (m_scene.SpawnPointRouting)
  3885. {
  3886. case "random":
  3887. if (spawnPoints.Length == 0)
  3888. return;
  3889. do
  3890. {
  3891. index = Util.RandomClass.Next(spawnPoints.Length - 1);
  3892. Vector3 spawnPosition = spawnPoints[index].GetLocation(
  3893. telehub.AbsolutePosition,
  3894. telehub.GroupRotation
  3895. );
  3896. // SpawnPoint sp = spawnPoints[index];
  3897. ILandObject land = m_scene.LandChannel.GetLandObject(spawnPosition.X, spawnPosition.Y);
  3898. if (land == null || land.IsEitherBannedOrRestricted(UUID))
  3899. selected = false;
  3900. else
  3901. selected = true;
  3902. } while ( selected == false);
  3903. pos = spawnPoints[index].GetLocation(
  3904. telehub.AbsolutePosition,
  3905. telehub.GroupRotation
  3906. );
  3907. return;
  3908. case "sequence":
  3909. do
  3910. {
  3911. index = m_scene.SpawnPoint();
  3912. Vector3 spawnPosition = spawnPoints[index].GetLocation(
  3913. telehub.AbsolutePosition,
  3914. telehub.GroupRotation
  3915. );
  3916. // SpawnPoint sp = spawnPoints[index];
  3917. ILandObject land = m_scene.LandChannel.GetLandObject(spawnPosition.X, spawnPosition.Y);
  3918. if (land == null || land.IsEitherBannedOrRestricted(UUID))
  3919. selected = false;
  3920. else
  3921. selected = true;
  3922. } while (selected == false);
  3923. pos = spawnPoints[index].GetLocation(telehub.AbsolutePosition, telehub.GroupRotation);
  3924. ;
  3925. return;
  3926. default:
  3927. case "closest":
  3928. float distance = 9999;
  3929. int closest = -1;
  3930. for (int i = 0; i < spawnPoints.Length; i++)
  3931. {
  3932. Vector3 spawnPosition = spawnPoints[i].GetLocation(
  3933. telehub.AbsolutePosition,
  3934. telehub.GroupRotation
  3935. );
  3936. Vector3 offset = spawnPosition - pos;
  3937. float d = Vector3.Mag(offset);
  3938. if (d >= distance)
  3939. continue;
  3940. ILandObject land = m_scene.LandChannel.GetLandObject(spawnPosition.X, spawnPosition.Y);
  3941. if (land == null)
  3942. continue;
  3943. if (land.IsEitherBannedOrRestricted(UUID))
  3944. continue;
  3945. distance = d;
  3946. closest = i;
  3947. }
  3948. if (closest == -1)
  3949. return;
  3950. pos = spawnPoints[closest].GetLocation(telehub.AbsolutePosition, telehub.GroupRotation);
  3951. return;
  3952. }
  3953. }
  3954. }
  3955. }
  3956. // Modify landing point based on possible banning, telehubs or parcel restrictions.
  3957. private void CheckAndAdjustLandingPoint(ref Vector3 pos)
  3958. {
  3959. string reason;
  3960. // Honor bans
  3961. if (!m_scene.TestLandRestrictions(UUID, out reason, ref pos.X, ref pos.Y))
  3962. return;
  3963. SceneObjectGroup telehub = null;
  3964. if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null)
  3965. {
  3966. if (!m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
  3967. {
  3968. CheckAndAdjustTelehub(telehub, ref pos);
  3969. return;
  3970. }
  3971. }
  3972. ILandObject land = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
  3973. if (land != null)
  3974. {
  3975. if (Scene.DebugTeleporting)
  3976. TeleportFlagsDebug();
  3977. // If we come in via login, landmark or map, we want to
  3978. // honor landing points. If we come in via Lure, we want
  3979. // to ignore them.
  3980. if ((m_teleportFlags & (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)) ==
  3981. (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID) ||
  3982. (m_teleportFlags & TeleportFlags.ViaLandmark) != 0 ||
  3983. (m_teleportFlags & TeleportFlags.ViaLocation) != 0 ||
  3984. (m_teleportFlags & Constants.TeleportFlags.ViaHGLogin) != 0)
  3985. {
  3986. // Don't restrict gods, estate managers, or land owners to
  3987. // the TP point. This behaviour mimics agni.
  3988. if (land.LandData.LandingType == (byte)LandingType.LandingPoint &&
  3989. land.LandData.UserLocation != Vector3.Zero &&
  3990. GodLevel < 200 &&
  3991. ((land.LandData.OwnerID != m_uuid &&
  3992. !m_scene.Permissions.IsGod(m_uuid) &&
  3993. !m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid)) ||
  3994. (m_teleportFlags & TeleportFlags.ViaLocation) != 0 ||
  3995. (m_teleportFlags & Constants.TeleportFlags.ViaHGLogin) != 0))
  3996. {
  3997. pos = land.LandData.UserLocation;
  3998. }
  3999. }
  4000. land.SendLandUpdateToClient(ControllingClient);
  4001. }
  4002. }
  4003. private DetectedObject CreateDetObject(SceneObjectPart obj)
  4004. {
  4005. DetectedObject detobj = new DetectedObject();
  4006. detobj.keyUUID = obj.UUID;
  4007. detobj.nameStr = obj.Name;
  4008. detobj.ownerUUID = obj.OwnerID;
  4009. detobj.posVector = obj.AbsolutePosition;
  4010. detobj.rotQuat = obj.GetWorldRotation();
  4011. detobj.velVector = obj.Velocity;
  4012. detobj.colliderType = 0;
  4013. detobj.groupUUID = obj.GroupID;
  4014. return detobj;
  4015. }
  4016. private DetectedObject CreateDetObject(ScenePresence av)
  4017. {
  4018. DetectedObject detobj = new DetectedObject();
  4019. detobj.keyUUID = av.UUID;
  4020. detobj.nameStr = av.ControllingClient.Name;
  4021. detobj.ownerUUID = av.UUID;
  4022. detobj.posVector = av.AbsolutePosition;
  4023. detobj.rotQuat = av.Rotation;
  4024. detobj.velVector = av.Velocity;
  4025. detobj.colliderType = 0;
  4026. detobj.groupUUID = av.ControllingClient.ActiveGroupId;
  4027. return detobj;
  4028. }
  4029. private DetectedObject CreateDetObjectForGround()
  4030. {
  4031. DetectedObject detobj = new DetectedObject();
  4032. detobj.keyUUID = UUID.Zero;
  4033. detobj.nameStr = "";
  4034. detobj.ownerUUID = UUID.Zero;
  4035. detobj.posVector = AbsolutePosition;
  4036. detobj.rotQuat = Quaternion.Identity;
  4037. detobj.velVector = Vector3.Zero;
  4038. detobj.colliderType = 0;
  4039. detobj.groupUUID = UUID.Zero;
  4040. return detobj;
  4041. }
  4042. private ColliderArgs CreateColliderArgs(SceneObjectPart dest, List<uint> colliders)
  4043. {
  4044. ColliderArgs colliderArgs = new ColliderArgs();
  4045. List<DetectedObject> colliding = new List<DetectedObject>();
  4046. foreach (uint localId in colliders)
  4047. {
  4048. if (localId == 0)
  4049. continue;
  4050. SceneObjectPart obj = m_scene.GetSceneObjectPart(localId);
  4051. if (obj != null)
  4052. {
  4053. if (!dest.CollisionFilteredOut(obj.UUID, obj.Name))
  4054. colliding.Add(CreateDetObject(obj));
  4055. }
  4056. else
  4057. {
  4058. ScenePresence av = m_scene.GetScenePresence(localId);
  4059. if (av != null && (!av.IsChildAgent))
  4060. {
  4061. if (!dest.CollisionFilteredOut(av.UUID, av.Name))
  4062. colliding.Add(CreateDetObject(av));
  4063. }
  4064. }
  4065. }
  4066. colliderArgs.Colliders = colliding;
  4067. return colliderArgs;
  4068. }
  4069. private delegate void ScriptCollidingNotification(uint localID, ColliderArgs message);
  4070. private void SendCollisionEvent(SceneObjectGroup dest, scriptEvents ev, List<uint> colliders, ScriptCollidingNotification notify)
  4071. {
  4072. ColliderArgs CollidingMessage;
  4073. if (colliders.Count > 0)
  4074. {
  4075. if ((dest.RootPart.ScriptEvents & ev) != 0)
  4076. {
  4077. CollidingMessage = CreateColliderArgs(dest.RootPart, colliders);
  4078. if (CollidingMessage.Colliders.Count > 0)
  4079. notify(dest.RootPart.LocalId, CollidingMessage);
  4080. }
  4081. }
  4082. }
  4083. private void SendLandCollisionEvent(SceneObjectGroup dest, scriptEvents ev, ScriptCollidingNotification notify)
  4084. {
  4085. if ((dest.RootPart.ScriptEvents & ev) != 0)
  4086. {
  4087. ColliderArgs LandCollidingMessage = new ColliderArgs();
  4088. List<DetectedObject> colliding = new List<DetectedObject>();
  4089. colliding.Add(CreateDetObjectForGround());
  4090. LandCollidingMessage.Colliders = colliding;
  4091. notify(dest.RootPart.LocalId, LandCollidingMessage);
  4092. }
  4093. }
  4094. private void TeleportFlagsDebug() {
  4095. // Some temporary debugging help to show all the TeleportFlags we have...
  4096. bool HG = false;
  4097. if((m_teleportFlags & TeleportFlags.ViaHGLogin) == TeleportFlags.ViaHGLogin)
  4098. HG = true;
  4099. m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
  4100. uint i = 0u;
  4101. for (int x = 0; x <= 30 ; x++, i = 1u << x)
  4102. {
  4103. i = 1u << x;
  4104. if((m_teleportFlags & (TeleportFlags)i) == (TeleportFlags)i)
  4105. if (HG == false)
  4106. m_log.InfoFormat("[SCENE PRESENCE]: Teleport Flags include {0}", ((TeleportFlags) i).ToString());
  4107. else
  4108. m_log.InfoFormat("[SCENE PRESENCE]: HG Teleport Flags include {0}", ((TeleportFlags)i).ToString());
  4109. }
  4110. m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
  4111. }
  4112. }
  4113. }