ScenePresence.cs 195 KB

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