ScenePresence.cs 272 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052
  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.Framework.Monitoring;
  40. using OpenSim.Region.Framework.Interfaces;
  41. using OpenSim.Region.Framework.Scenes.Animation;
  42. using OpenSim.Region.Framework.Scenes.Types;
  43. using OpenSim.Region.PhysicsModules.SharedBase;
  44. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  45. using OpenSim.Services.Interfaces;
  46. using TeleportFlags = OpenSim.Framework.Constants.TeleportFlags;
  47. namespace OpenSim.Region.Framework.Scenes
  48. {
  49. [Flags]
  50. enum ScriptControlled : uint
  51. {
  52. CONTROL_ZERO = 0,
  53. CONTROL_FWD = 1,
  54. CONTROL_BACK = 2,
  55. CONTROL_LEFT = 4,
  56. CONTROL_RIGHT = 8,
  57. CONTROL_UP = 16,
  58. CONTROL_DOWN = 32,
  59. CONTROL_ROT_LEFT = 256,
  60. CONTROL_ROT_RIGHT = 512,
  61. CONTROL_LBUTTON = 268435456,
  62. CONTROL_ML_LBUTTON = 1073741824
  63. }
  64. struct ScriptControllers
  65. {
  66. public UUID objectID;
  67. public UUID itemID;
  68. public ScriptControlled ignoreControls;
  69. public ScriptControlled eventControls;
  70. }
  71. public delegate void SendCoarseLocationsMethod(UUID scene, ScenePresence presence, List<Vector3> coarseLocations, List<UUID> avatarUUIDs);
  72. public class ScenePresence : EntityBase, IScenePresence
  73. {
  74. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  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 bool IsNPC { get; private set; }
  85. // simple yes or no isGOD from god level >= 200
  86. // should only be set by GodController
  87. // we have two to suport legacy behaviour
  88. // IsViewerUIGod was controlled by viewer in older versions
  89. // IsGod may now be also controled by viewer acording to options
  90. public bool IsViewerUIGod { get; set; }
  91. public bool IsGod { get; set; }
  92. private bool m_gotRegionHandShake = false;
  93. private PresenceType m_presenceType;
  94. public PresenceType PresenceType
  95. {
  96. get {return m_presenceType;}
  97. private set
  98. {
  99. m_presenceType = value;
  100. IsNPC = (m_presenceType == PresenceType.Npc);
  101. }
  102. }
  103. private ScenePresenceStateMachine m_stateMachine;
  104. /// <summary>
  105. /// The current state of this presence. Governs only the existence lifecycle. See ScenePresenceStateMachine
  106. /// for more details.
  107. /// </summary>
  108. public ScenePresenceState LifecycleState
  109. {
  110. get
  111. {
  112. return m_stateMachine.GetState();
  113. }
  114. set
  115. {
  116. m_stateMachine.SetState(value);
  117. }
  118. }
  119. /// <summary>
  120. /// This exists to prevent race conditions between two CompleteMovement threads if the simulator is slow and
  121. /// the viewer fires these in quick succession.
  122. /// </summary>
  123. /// <remarks>
  124. /// TODO: The child -> agent transition should be folded into LifecycleState and the CompleteMovement
  125. /// regulation done there.
  126. /// </remarks>
  127. private object m_completeMovementLock = new object();
  128. // private static readonly byte[] DEFAULT_TEXTURE = AvatarAppearance.GetDefaultTexture().GetBytes();
  129. private static readonly Array DIR_CONTROL_FLAGS = Enum.GetValues(typeof(Dir_ControlFlags));
  130. private static readonly Vector3 HEAD_ADJUSTMENT = new Vector3(0f, 0f, 0.3f);
  131. /// <summary>
  132. /// Experimentally determined "fudge factor" to make sit-target positions
  133. /// the same as in SecondLife. Fudge factor was tested for 36 different
  134. /// test cases including prims of type box, sphere, cylinder, and torus,
  135. /// with varying parameters for sit target location, prim size, prim
  136. /// rotation, prim cut, prim twist, prim taper, and prim shear. See mantis
  137. /// issue #1716
  138. /// </summary>
  139. public static readonly Vector3 SIT_TARGET_ADJUSTMENT = new Vector3(0.0f, 0.0f, 0.4f);
  140. public bool LegacySitOffsets = true;
  141. /// <summary>
  142. /// Movement updates for agents in neighboring regions are sent directly to clients.
  143. /// This value only affects how often agent positions are sent to neighbor regions
  144. /// for things such as distance-based update prioritization
  145. /// this are the square of real distances
  146. /// </summary>
  147. public static readonly float MOVEMENT = .25f;
  148. public static readonly float SIGNIFICANT_MOVEMENT = 16.0f;
  149. public static readonly float CHILDUPDATES_MOVEMENT = 100.0f;
  150. public static readonly float CHILDAGENTSCHECK_MOVEMENT = 1024f; // 32m
  151. public static readonly float CHILDUPDATES_TIME = 2000f; // min time between child updates (ms)
  152. private UUID m_previusParcelUUID = UUID.Zero;
  153. private UUID m_currentParcelUUID = UUID.Zero;
  154. private bool m_previusParcelHide = false;
  155. private bool m_currentParcelHide = false;
  156. private object parcelLock = new Object();
  157. public double ParcelDwellTickMS;
  158. public UUID currentParcelUUID
  159. {
  160. get { return m_currentParcelUUID; }
  161. set
  162. {
  163. lock (parcelLock)
  164. {
  165. bool oldhide = m_currentParcelHide;
  166. bool checksame = true;
  167. if (value != m_currentParcelUUID)
  168. {
  169. ParcelDwellTickMS = Util.GetTimeStampMS();
  170. m_previusParcelHide = m_currentParcelHide;
  171. m_previusParcelUUID = m_currentParcelUUID;
  172. checksame = false;
  173. }
  174. m_currentParcelUUID = value;
  175. m_currentParcelHide = false;
  176. ILandObject land = m_scene.LandChannel.GetLandObject(AbsolutePosition.X, AbsolutePosition.Y);
  177. if (land != null && !land.LandData.SeeAVs)
  178. m_currentParcelHide = true;
  179. if (m_previusParcelUUID != UUID.Zero || checksame)
  180. ParcelCrossCheck(m_currentParcelUUID, m_previusParcelUUID, m_currentParcelHide, m_previusParcelHide, oldhide,checksame);
  181. }
  182. }
  183. }
  184. public void sitSOGmoved()
  185. {
  186. /*
  187. if (IsDeleted || !IsSatOnObject)
  188. //what me? nahh
  189. return;
  190. if (IsInTransit)
  191. return;
  192. ILandObject land = m_scene.LandChannel.GetLandObject(AbsolutePosition.X, AbsolutePosition.Y);
  193. if (land == null)
  194. return; //??
  195. UUID parcelID = land.LandData.GlobalID;
  196. if (m_currentParcelUUID != parcelID)
  197. currentParcelUUID = parcelID;
  198. */
  199. }
  200. public bool ParcelAllowThisAvatarSounds
  201. {
  202. get
  203. {
  204. try
  205. {
  206. lock (parcelLock)
  207. {
  208. ILandObject land = m_scene.LandChannel.GetLandObject(AbsolutePosition.X, AbsolutePosition.Y);
  209. if (land == null)
  210. return true;
  211. if (land.LandData.AnyAVSounds)
  212. return true;
  213. if (!land.LandData.GroupAVSounds)
  214. return false;
  215. return ControllingClient.IsGroupMember(land.LandData.GroupID);
  216. }
  217. }
  218. catch
  219. {
  220. return true;
  221. }
  222. }
  223. }
  224. public bool ParcelHideThisAvatar
  225. {
  226. get
  227. {
  228. return m_currentParcelHide;
  229. }
  230. }
  231. /// <value>
  232. /// The animator for this avatar
  233. /// </value>
  234. public ScenePresenceAnimator Animator { get; private set; }
  235. /// <value>
  236. /// Server Side Animation Override
  237. /// </value>
  238. public MovementAnimationOverrides Overrides { get; private set; }
  239. public String sitAnimation = "SIT";
  240. /// <summary>
  241. /// Attachments recorded on this avatar.
  242. /// </summary>
  243. /// <remarks>
  244. /// TODO: For some reason, we effectively have a list both here and in Appearance. Need to work out if this is
  245. /// necessary.
  246. /// </remarks>
  247. private List<SceneObjectGroup> m_attachments = new List<SceneObjectGroup>();
  248. public Object AttachmentsSyncLock { get; private set; }
  249. private Dictionary<UUID, ScriptControllers> scriptedcontrols = new Dictionary<UUID, ScriptControllers>();
  250. private ScriptControlled IgnoredControls = ScriptControlled.CONTROL_ZERO;
  251. private ScriptControlled LastCommands = ScriptControlled.CONTROL_ZERO;
  252. private bool MouseDown = false;
  253. public Vector3 lastKnownAllowedPosition;
  254. public bool sentMessageAboutRestrictedParcelFlyingDown;
  255. public Vector4 CollisionPlane = Vector4.UnitW;
  256. public Vector4 m_lastCollisionPlane = Vector4.UnitW;
  257. private byte m_lastState;
  258. private Vector3 m_lastPosition;
  259. private Quaternion m_lastRotation;
  260. private Vector3 m_lastVelocity;
  261. private Vector3 m_lastSize = new Vector3(0.45f,0.6f,1.9f);
  262. private int NeedInitialData = -1;
  263. private int m_userFlags;
  264. public int UserFlags
  265. {
  266. get { return m_userFlags; }
  267. }
  268. // Flying
  269. public bool Flying
  270. {
  271. get { return PhysicsActor != null && PhysicsActor.Flying; }
  272. set
  273. {
  274. if(PhysicsActor != null)
  275. PhysicsActor.Flying = value;
  276. }
  277. }
  278. public bool IsColliding
  279. {
  280. get { return PhysicsActor != null && PhysicsActor.IsColliding; }
  281. // We would expect setting IsColliding to be private but it's used by a hack in Scene
  282. set { PhysicsActor.IsColliding = value; }
  283. }
  284. private List<uint> m_lastColliders = new List<uint>();
  285. private TeleportFlags m_teleportFlags;
  286. public TeleportFlags TeleportFlags
  287. {
  288. get { return m_teleportFlags; }
  289. set { m_teleportFlags = value; }
  290. }
  291. private uint m_requestedSitTargetID;
  292. private UUID m_requestedSitTargetUUID;
  293. /// <summary>
  294. /// Are we sitting on the ground?
  295. /// </summary>
  296. public bool SitGround { get; private set; }
  297. private SendCoarseLocationsMethod m_sendCoarseLocationsMethod;
  298. //private Vector3 m_requestedSitOffset = new Vector3();
  299. private Vector3 m_LastFinitePos;
  300. private float m_sitAvatarHeight = 2.0f;
  301. private bool m_childUpdatesBusy = false;
  302. private int m_lastChildUpdatesTime;
  303. private int m_lastChildAgentUpdateGodLevel;
  304. private float m_lastChildAgentUpdateDrawDistance;
  305. private float m_lastRegionsDrawDistance;
  306. private Vector3 m_lastChildAgentUpdatePosition;
  307. private Vector3 m_lastChildAgentCheckPosition;
  308. // private Vector3 m_lastChildAgentUpdateCamPosition;
  309. private Vector3 m_lastCameraRayCastCam;
  310. private Vector3 m_lastCameraRayCastPos;
  311. private float m_FOV = 1.04f;
  312. private const int LAND_VELOCITYMAG_MAX = 12;
  313. private const float FLY_ROLL_MAX_RADIANS = 1.1f;
  314. private const float FLY_ROLL_RADIANS_PER_UPDATE = 0.06f;
  315. private const float FLY_ROLL_RESET_RADIANS_PER_UPDATE = 0.02f;
  316. private float m_health = 100f;
  317. private float m_healRate = 1f;
  318. private float m_healRatePerFrame = 0.05f;
  319. private readonly Vector3[] Dir_Vectors = new Vector3[12];
  320. protected int m_reprioritizationLastTime;
  321. protected bool m_reprioritizationBusy;
  322. protected Vector3 m_reprioritizationLastPosition;
  323. protected float m_reprioritizationLastDrawDistance;
  324. private Quaternion m_headrotation = Quaternion.Identity;
  325. //PauPaw:Proper PID Controler for autopilot************
  326. private bool m_movingToTarget;
  327. public bool MovingToTarget
  328. {
  329. get {return m_movingToTarget;}
  330. private set {m_movingToTarget = value; }
  331. }
  332. private Vector3 m_moveToPositionTarget;
  333. public Vector3 MoveToPositionTarget
  334. {
  335. get {return m_moveToPositionTarget;}
  336. private set {m_moveToPositionTarget = value; }
  337. }
  338. private float m_moveToSpeed;
  339. public float MoveToSpeed
  340. {
  341. get {return m_moveToSpeed;}
  342. private set {m_moveToSpeed = value; }
  343. }
  344. private double m_delayedStop = -1.0;
  345. /// <summary>
  346. /// Controls whether an avatar automatically moving to a target will land when it gets there (if flying).
  347. /// </summary>
  348. public bool LandAtTarget { get; private set; }
  349. private bool CameraConstraintActive;
  350. private object m_collisionEventLock = new Object();
  351. private int m_movementAnimationUpdateCounter = 0;
  352. public Vector3 PrevSitOffset { get; set; }
  353. protected AvatarAppearance m_appearance;
  354. public AvatarAppearance Appearance
  355. {
  356. get { return m_appearance; }
  357. set
  358. {
  359. m_appearance = value;
  360. // m_log.DebugFormat("[SCENE PRESENCE]: Set appearance for {0} to {1}", Name, value);
  361. }
  362. }
  363. /// <summary>
  364. /// Copy of the script states while the agent is in transit. This state may
  365. /// need to be placed back in case of transfer fail.
  366. /// </summary>
  367. public List<string> InTransitScriptStates
  368. {
  369. get { return m_InTransitScriptStates; }
  370. private set { m_InTransitScriptStates = value; }
  371. }
  372. private List<string> m_InTransitScriptStates = new List<string>();
  373. /// <summary>
  374. /// Implemented Control Flags
  375. /// </summary>
  376. private enum Dir_ControlFlags:uint
  377. {
  378. DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS,
  379. DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG,
  380. DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS,
  381. DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG,
  382. DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS,
  383. DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG,
  384. DIR_CONTROL_FLAG_FORWARD_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS,
  385. DIR_CONTROL_FLAG_BACKWARD_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG,
  386. DIR_CONTROL_FLAG_LEFT_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS,
  387. DIR_CONTROL_FLAG_RIGHT_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG,
  388. DIR_CONTROL_FLAG_UP_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS,
  389. DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG
  390. }
  391. /// <summary>
  392. /// Position at which a significant movement was made
  393. /// </summary>
  394. private Vector3 posLastSignificantMove;
  395. private Vector3 posLastMove;
  396. #region For teleports and crossings callbacks
  397. /// <summary>
  398. /// the destination simulator sends ReleaseAgent to this address, for very long range tps, HG.
  399. /// </summary>
  400. private string m_callbackURI; // to remove with v1 support
  401. private string m_newCallbackURI;
  402. /// <summary>
  403. /// Records the region from which this presence originated, if not from login.
  404. /// </summary>
  405. /// <remarks>
  406. /// Also acts as a signal in the teleport V2 process to release UpdateAgent after a viewer has triggered
  407. /// CompleteMovement and made the previous child agent a root agent.
  408. /// </remarks>
  409. private UUID m_originRegionID;
  410. /// <summary>
  411. /// This object is used as a lock before accessing m_originRegionID to make sure that every thread is seeing
  412. /// the very latest value and not using some cached version. Cannot make m_originRegionID itself volatite as
  413. /// it is a value type.
  414. /// </summary>
  415. private object m_originRegionIDAccessLock = new object();
  416. private AutoResetEvent m_updateAgentReceivedAfterTransferEvent = new AutoResetEvent(false);
  417. /// <summary>
  418. /// Used by the entity transfer module to signal when the presence should not be closed because a subsequent
  419. /// teleport is reusing the connection.
  420. /// </summary>
  421. /// <remarks>May be refactored or move somewhere else soon.</remarks>
  422. public bool DoNotCloseAfterTeleport { get; set; }
  423. #endregion
  424. /// <value>
  425. /// Script engines present in the scene
  426. /// </value>
  427. private IScriptModule[] m_scriptEngines;
  428. private enum LandingPointBehavior
  429. {
  430. OS = 1,
  431. SL = 2
  432. }
  433. private LandingPointBehavior m_LandingPointBehavior = LandingPointBehavior.OS;
  434. #region Properties
  435. /// <summary>
  436. /// Physical scene representation of this Avatar.
  437. /// </summary>
  438. PhysicsActor m_physActor;
  439. public PhysicsActor PhysicsActor
  440. {
  441. get
  442. {
  443. return m_physActor;
  444. }
  445. private set
  446. {
  447. m_physActor = value;
  448. }
  449. }
  450. /// <summary>
  451. /// Record user movement inputs.
  452. /// </summary>
  453. public uint MovementFlag { get; private set; }
  454. /// <summary>
  455. /// Is the agent stop control flag currently active?
  456. /// </summary>
  457. public bool AgentControlStopActive { get; private set; }
  458. private bool m_invulnerable = true;
  459. public bool Invulnerable
  460. {
  461. set
  462. {
  463. m_invulnerable = value;
  464. if(value && Health != 100.0f)
  465. Health = 100.0f;
  466. }
  467. get { return m_invulnerable; }
  468. }
  469. public GodController GodController { get; private set; }
  470. private ulong m_rootRegionHandle;
  471. private Vector3 m_rootRegionPosition = new Vector3();
  472. public ulong RegionHandle
  473. {
  474. get { return m_rootRegionHandle; }
  475. private set
  476. {
  477. m_rootRegionHandle = value;
  478. // position rounded to lower multiple of 256m
  479. m_rootRegionPosition.X = (float)((m_rootRegionHandle >> 32) & 0xffffff00);
  480. m_rootRegionPosition.Y = (float)(m_rootRegionHandle & 0xffffff00);
  481. }
  482. }
  483. #region Client Camera
  484. /// <summary>
  485. /// Position of agent's camera in world (region cordinates)
  486. /// </summary>
  487. // protected Vector3 m_lastCameraPosition;
  488. private Vector4 m_lastCameraCollisionPlane = new Vector4(0f, 0f, 0f, 1);
  489. private bool m_doingCamRayCast = false;
  490. public Vector3 CameraPosition { get; set; }
  491. public Quaternion CameraRotation { get; private set; }
  492. // Use these three vectors to figure out what the agent is looking at
  493. // Convert it to a Matrix and/or Quaternion
  494. //
  495. public Vector3 CameraAtAxis { get; set; }
  496. public Vector3 CameraLeftAxis { get; set; }
  497. public Vector3 CameraUpAxis { get; set; }
  498. public Vector3 Lookat
  499. {
  500. get
  501. {
  502. Vector3 a = new Vector3(CameraAtAxis.X, CameraAtAxis.Y, 0);
  503. a.Normalize();
  504. return a;
  505. }
  506. }
  507. #endregion
  508. public string Firstname { get; private set; }
  509. public string Lastname { get; private set; }
  510. public bool m_haveGroupInformation;
  511. public bool m_gotCrossUpdate;
  512. public byte m_crossingFlags;
  513. public string Grouptitle
  514. {
  515. get { return m_groupTitle; }
  516. set { m_groupTitle = value; }
  517. }
  518. private string m_groupTitle;
  519. // Agent's Draw distance.
  520. private float m_drawDistance = 255f;
  521. public float DrawDistance
  522. {
  523. get
  524. {
  525. return m_drawDistance;
  526. }
  527. set
  528. {
  529. m_drawDistance = Util.Clamp(value, 32f, m_scene.MaxDrawDistance);
  530. }
  531. }
  532. public float RegionViewDistance
  533. {
  534. get
  535. {
  536. return Util.Clamp(m_drawDistance + 64f, m_scene.MinRegionViewDistance, m_scene.MaxRegionViewDistance);
  537. }
  538. }
  539. public bool AllowMovement { get; set; }
  540. private bool m_setAlwaysRun;
  541. public bool SetAlwaysRun
  542. {
  543. get
  544. {
  545. if (PhysicsActor != null)
  546. {
  547. return PhysicsActor.SetAlwaysRun;
  548. }
  549. else
  550. {
  551. return m_setAlwaysRun;
  552. }
  553. }
  554. set
  555. {
  556. m_setAlwaysRun = value;
  557. if (PhysicsActor != null)
  558. {
  559. PhysicsActor.SetAlwaysRun = value;
  560. }
  561. }
  562. }
  563. public byte State { get; set; }
  564. private AgentManager.ControlFlags m_AgentControlFlags;
  565. public uint AgentControlFlags
  566. {
  567. get { return (uint)m_AgentControlFlags; }
  568. set { m_AgentControlFlags = (AgentManager.ControlFlags)value; }
  569. }
  570. public IClientAPI ControllingClient { get; set; }
  571. public IClientCore ClientView
  572. {
  573. get { return (IClientCore)ControllingClient; }
  574. }
  575. public UUID COF { get; set; }
  576. // public Vector3 ParentPosition { get; set; }
  577. /// <summary>
  578. /// Position of this avatar relative to the region the avatar is in
  579. /// </summary>
  580. public override Vector3 AbsolutePosition
  581. {
  582. get
  583. {
  584. if (PhysicsActor != null)
  585. {
  586. m_pos = PhysicsActor.Position;
  587. // m_log.DebugFormat(
  588. // "[SCENE PRESENCE]: Set position of {0} in {1} to {2} via getting AbsolutePosition!",
  589. // Name, Scene.Name, m_pos);
  590. }
  591. else
  592. {
  593. // m_log.DebugFormat("[SCENE PRESENCE]: Fetching abs pos where PhysicsActor == null and parent part {0} for {1}", Name, Scene.Name);
  594. // Obtain the correct position of a seated avatar.
  595. // In addition to providing the correct position while
  596. // the avatar is seated, this value will also
  597. // be used as the location to unsit to.
  598. //
  599. // If ParentID is not 0, assume we are a seated avatar
  600. // and we should return the position based on the sittarget
  601. // offset and rotation of the prim we are seated on.
  602. //
  603. // Generally, m_pos will contain the position of the avatar
  604. // in the sim unless the avatar is on a sit target. While
  605. // on a sit target, m_pos will contain the desired offset
  606. // without the parent rotation applied.
  607. if (ParentPart != null)
  608. {
  609. SceneObjectPart rootPart = ParentPart.ParentGroup.RootPart;
  610. // if (sitPart != null)
  611. // return sitPart.AbsolutePosition + (m_pos * sitPart.GetWorldRotation());
  612. if (rootPart != null)
  613. return rootPart.AbsolutePosition + (m_pos * rootPart.GetWorldRotation());
  614. }
  615. }
  616. return m_pos;
  617. }
  618. set
  619. {
  620. // m_log.DebugFormat("[SCENE PRESENCE]: Setting position of {0} to {1} in {2}", Name, value, Scene.Name);
  621. // Util.PrintCallStack();
  622. if (PhysicsActor != null)
  623. {
  624. try
  625. {
  626. PhysicsActor.Position = value;
  627. }
  628. catch (Exception e)
  629. {
  630. m_log.Error("[SCENE PRESENCE]: ABSOLUTE POSITION " + e.Message);
  631. }
  632. }
  633. // Don't update while sitting. The PhysicsActor above is null whilst sitting.
  634. if (ParentID == 0)
  635. m_pos = value;
  636. //m_log.DebugFormat(
  637. // "[ENTITY BASE]: In {0} set AbsolutePosition of {1} to {2}",
  638. // Scene.RegionInfo.RegionName, Name, m_pos);
  639. TriggerScenePresenceUpdated();
  640. }
  641. }
  642. /// <summary>
  643. /// If sitting, returns the offset position from the prim the avatar is sitting on.
  644. /// Otherwise, returns absolute position in the scene.
  645. /// </summary>
  646. public Vector3 OffsetPosition
  647. {
  648. get { return m_pos; }
  649. // Don't remove setter. It's not currently used in core but
  650. // upcoming Avination code needs it.
  651. set
  652. {
  653. // There is no offset position when not seated
  654. if (ParentID == 0)
  655. return;
  656. m_pos = value;
  657. TriggerScenePresenceUpdated();
  658. }
  659. }
  660. /// <summary>
  661. /// Current velocity of the avatar.
  662. /// </summary>
  663. public override Vector3 Velocity
  664. {
  665. get
  666. {
  667. if (PhysicsActor != null)
  668. {
  669. m_velocity = PhysicsActor.Velocity;
  670. // m_log.DebugFormat(
  671. // "[SCENE PRESENCE]: Set velocity {0} for {1} in {2} via getting Velocity!",
  672. // m_velocity, Name, Scene.RegionInfo.RegionName);
  673. }
  674. return m_velocity;
  675. }
  676. set
  677. {
  678. if (PhysicsActor != null)
  679. {
  680. try
  681. {
  682. PhysicsActor.TargetVelocity = value;
  683. }
  684. catch (Exception e)
  685. {
  686. m_log.Error("[SCENE PRESENCE]: VELOCITY " + e.Message);
  687. }
  688. }
  689. m_velocity = value;
  690. // m_log.DebugFormat(
  691. // "[SCENE PRESENCE]: In {0} set velocity of {1} to {2}",
  692. // Scene.RegionInfo.RegionName, Name, m_velocity);
  693. }
  694. }
  695. // requested Velocity for physics engines avatar motors
  696. // only makes sense if there is a physical rep
  697. public Vector3 TargetVelocity
  698. {
  699. get
  700. {
  701. if (PhysicsActor != null)
  702. return PhysicsActor.TargetVelocity;
  703. else
  704. return Vector3.Zero;
  705. }
  706. set
  707. {
  708. if (PhysicsActor != null)
  709. {
  710. try
  711. {
  712. PhysicsActor.TargetVelocity = value;
  713. }
  714. catch (Exception e)
  715. {
  716. m_log.Error("[SCENE PRESENCE]: TARGETVELOCITY " + e.Message);
  717. }
  718. }
  719. }
  720. }
  721. private Quaternion m_bodyRot = Quaternion.Identity;
  722. /// <summary>
  723. /// The rotation of the avatar.
  724. /// </summary>
  725. /// <remarks>
  726. /// If the avatar is not sitting, this is with respect to the world
  727. /// If the avatar is sitting, this is a with respect to the part that it's sitting upon (a local rotation).
  728. /// If you always want the world rotation, use GetWorldRotation()
  729. /// </remarks>
  730. public Quaternion Rotation
  731. {
  732. get
  733. {
  734. return m_bodyRot;
  735. }
  736. set
  737. {
  738. m_bodyRot = value;
  739. if (PhysicsActor != null)
  740. {
  741. try
  742. {
  743. PhysicsActor.Orientation = m_bodyRot;
  744. }
  745. catch (Exception e)
  746. {
  747. m_log.Error("[SCENE PRESENCE]: Orientation " + e.Message);
  748. }
  749. }
  750. // m_log.DebugFormat("[SCENE PRESENCE]: Body rot for {0} set to {1}", Name, m_bodyRot);
  751. }
  752. }
  753. // Used for limited viewer 'fake' user rotations.
  754. private Vector3 m_AngularVelocity = Vector3.Zero;
  755. public Vector3 AngularVelocity
  756. {
  757. get { return m_AngularVelocity; }
  758. }
  759. public bool IsChildAgent { get; set; }
  760. /// <summary>
  761. /// If the avatar is sitting, the local ID of the prim that it's sitting on. If not sitting then zero.
  762. /// </summary>
  763. public uint ParentID { get; set; }
  764. public UUID ParentUUID
  765. {
  766. get { return m_parentUUID; }
  767. set { m_parentUUID = value; }
  768. }
  769. private UUID m_parentUUID = UUID.Zero;
  770. /// <summary>
  771. /// Are we sitting on an object?
  772. /// </summary>
  773. /// <remarks>A more readable way of testing presence sit status than ParentID == 0</remarks>
  774. public bool IsSatOnObject { get { return ParentID != 0; } }
  775. /// <summary>
  776. /// If the avatar is sitting, the prim that it's sitting on. If not sitting then null.
  777. /// </summary>
  778. /// <remarks>
  779. /// If you use this property then you must take a reference since another thread could set it to null.
  780. /// </remarks>
  781. public SceneObjectPart ParentPart { get; set; }
  782. public float Health
  783. {
  784. get { return m_health; }
  785. set { m_health = value; }
  786. }
  787. public float HealRate
  788. {
  789. get { return m_healRate; }
  790. set
  791. {
  792. if(value > 100.0f)
  793. m_healRate = 100.0f;
  794. else if (value <= 0.0)
  795. m_healRate = 0.0f;
  796. else
  797. m_healRate = value;
  798. if(Scene != null)
  799. m_healRatePerFrame = m_healRate * Scene.FrameTime;
  800. else
  801. m_healRatePerFrame = 0.05f;
  802. }
  803. }
  804. /// <summary>
  805. /// Gets the world rotation of this presence.
  806. /// </summary>
  807. /// <remarks>
  808. /// Unlike Rotation, this returns the world rotation no matter whether the avatar is sitting on a prim or not.
  809. /// </remarks>
  810. /// <returns></returns>
  811. public Quaternion GetWorldRotation()
  812. {
  813. if (IsSatOnObject)
  814. {
  815. SceneObjectPart sitPart = ParentPart;
  816. if (sitPart != null)
  817. return sitPart.GetWorldRotation() * Rotation;
  818. }
  819. return Rotation;
  820. }
  821. /// <summary>
  822. /// Get velocity relative to the world.
  823. /// </summary>
  824. public Vector3 GetWorldVelocity()
  825. {
  826. SceneObjectPart sitPart = ParentPart;
  827. if (sitPart != null)
  828. return sitPart.ParentGroup.Velocity;
  829. return Velocity;
  830. }
  831. public void AdjustKnownSeeds()
  832. {
  833. Dictionary<ulong, string> seeds;
  834. if (Scene.CapsModule != null)
  835. seeds = Scene.CapsModule.GetChildrenSeeds(UUID);
  836. else
  837. seeds = new Dictionary<ulong, string>();
  838. KnownRegions = seeds;
  839. }
  840. public void DumpKnownRegions()
  841. {
  842. m_log.Info("================ KnownRegions "+Scene.RegionInfo.RegionName+" ================");
  843. foreach (KeyValuePair<ulong, string> kvp in KnownRegions)
  844. {
  845. uint x, y;
  846. Util.RegionHandleToRegionLoc(kvp.Key, out x, out y);
  847. m_log.Info(" >> "+x+", "+y+": "+kvp.Value);
  848. }
  849. }
  850. private bool m_mouseLook;
  851. private bool m_leftButtonDown;
  852. private bool m_inTransit;
  853. /// <summary>
  854. /// This signals whether the presence is in transit between neighbouring regions.
  855. /// </summary>
  856. /// <remarks>
  857. /// It is not set when the presence is teleporting or logging in/out directly to a region.
  858. /// </remarks>
  859. public bool IsInTransit
  860. {
  861. get { return m_inTransit; }
  862. set {
  863. if(value)
  864. {
  865. if (Flying)
  866. m_AgentControlFlags |= AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  867. else
  868. m_AgentControlFlags &= ~AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  869. }
  870. m_inTransit = value;
  871. }
  872. }
  873. // this is is only valid if IsInTransit is true
  874. // only false on HG tps
  875. // used work arounf viewers asking source region about destination user
  876. public bool IsInLocalTransit {get; set; }
  877. /// <summary>
  878. /// Modifier for agent movement if we get an AGENT_CONTROL_STOP whilst walking or running
  879. /// </summary>
  880. /// <remarks>
  881. /// AGENT_CONTRL_STOP comes about if user holds down space key on viewers.
  882. /// </remarks>
  883. private const float AgentControlStopSlowVel = 0.2f;
  884. // velocities
  885. public const float AgentControlNudgeVel = 1.0f; // setting this diferent from normal as no effect currently
  886. public const float AgentControlNormalVel = 1.0f;
  887. // old normal speed was tuned to match sl normal plus Fast modifiers
  888. // so we need to rescale it
  889. private float m_speedModifier = 1.0f;
  890. public float SpeedModifier
  891. {
  892. get { return m_speedModifier; }
  893. set { m_speedModifier = value; }
  894. }
  895. private bool m_forceFly;
  896. public bool ForceFly
  897. {
  898. get { return m_forceFly; }
  899. set { m_forceFly = value; }
  900. }
  901. private bool m_flyDisabled;
  902. public bool FlyDisabled
  903. {
  904. get { return m_flyDisabled; }
  905. set { m_flyDisabled = value; }
  906. }
  907. public string Viewer
  908. {
  909. get { return Util.GetViewerName(m_scene.AuthenticateHandler.GetAgentCircuitData(ControllingClient.CircuitCode)); }
  910. }
  911. #endregion
  912. #region Constructor(s)
  913. public ScenePresence(
  914. IClientAPI client, Scene world, AvatarAppearance appearance, PresenceType type)
  915. {
  916. m_scene = world;
  917. AttachmentsSyncLock = new Object();
  918. AllowMovement = true;
  919. IsChildAgent = true;
  920. m_sendCoarseLocationsMethod = SendCoarseLocationsDefault;
  921. Animator = new ScenePresenceAnimator(this);
  922. Overrides = new MovementAnimationOverrides();
  923. PresenceType = type;
  924. m_drawDistance = client.StartFar;
  925. if(m_drawDistance > 32)
  926. {
  927. if(m_drawDistance > world.MaxDrawDistance)
  928. m_drawDistance = world.MaxDrawDistance;
  929. }
  930. else
  931. m_drawDistance = world.DefaultDrawDistance;
  932. RegionHandle = world.RegionInfo.RegionHandle;
  933. ControllingClient = client;
  934. Firstname = ControllingClient.FirstName;
  935. Lastname = ControllingClient.LastName;
  936. m_name = String.Format("{0} {1}", Firstname, Lastname);
  937. m_uuid = client.AgentId;
  938. LocalId = m_scene.AllocateLocalId();
  939. LegacySitOffsets = m_scene.LegacySitOffsets;
  940. IsInLocalTransit = true;
  941. UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, m_uuid);
  942. if (account != null)
  943. m_userFlags = account.UserFlags;
  944. else
  945. m_userFlags = 0;
  946. int userlevel = 0;
  947. if (account != null)
  948. userlevel = account.UserLevel;
  949. GodController = new GodController(world, this, userlevel);
  950. // IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  951. // if (gm != null)
  952. // Grouptitle = gm.GetGroupTitle(m_uuid);
  953. m_scriptEngines = m_scene.RequestModuleInterfaces<IScriptModule>();
  954. AbsolutePosition = posLastMove = posLastSignificantMove = CameraPosition =
  955. m_reprioritizationLastPosition = ControllingClient.StartPos;
  956. m_reprioritizationLastDrawDistance = -1000;
  957. // disable updates workjobs for now
  958. m_childUpdatesBusy = true;
  959. m_reprioritizationBusy = true;
  960. AdjustKnownSeeds();
  961. RegisterToClientEvents();
  962. SetDirectionVectors();
  963. Appearance = appearance;
  964. m_stateMachine = new ScenePresenceStateMachine(this);
  965. HealRate = 0.5f;
  966. IConfig sconfig = m_scene.Config.Configs["EntityTransfer"];
  967. if (sconfig != null)
  968. {
  969. string lpb = sconfig.GetString("LandingPointBehavior", "LandingPointBehavior_OS");
  970. if (lpb == "LandingPointBehavior_SL")
  971. m_LandingPointBehavior = LandingPointBehavior.SL;
  972. }
  973. m_bandwidth = 100000;
  974. m_lastBandwithTime = Util.GetTimeStamp() + 0.1;
  975. IConfig cconfig = m_scene.Config.Configs["ClientStack.LindenCaps"];
  976. if (cconfig != null)
  977. {
  978. m_capbandwidth = cconfig.GetInt("Cap_AssetThrottle", m_capbandwidth);
  979. if(m_capbandwidth > 0)
  980. {
  981. m_bandwidth = m_capbandwidth;
  982. if(m_bandwidth < 50000)
  983. m_bandwidth = 50000;
  984. }
  985. }
  986. m_bandwidthBurst = m_bandwidth / 5;
  987. ControllingClient.RefreshGroupMembership();
  988. }
  989. private float lastHealthSent = 0;
  990. private void RegionHeartbeatEnd(Scene scene)
  991. {
  992. if (IsChildAgent)
  993. return;
  994. m_movementAnimationUpdateCounter ++;
  995. if (m_movementAnimationUpdateCounter >= 2)
  996. {
  997. m_movementAnimationUpdateCounter = 0;
  998. if (Animator != null)
  999. {
  1000. // If the parentID == 0 we are not sitting
  1001. // if !SitGournd then we are not sitting on the ground
  1002. // Fairly straightforward, now here comes the twist
  1003. // if ParentUUID is NOT UUID.Zero, we are looking to
  1004. // be sat on an object that isn't there yet. Should
  1005. // be treated as if sat.
  1006. if(ParentID == 0 && !SitGround && ParentUUID == UUID.Zero) // skip it if sitting
  1007. Animator.UpdateMovementAnimations();
  1008. }
  1009. else
  1010. {
  1011. // m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
  1012. }
  1013. }
  1014. if(m_healRatePerFrame != 0f && Health != 100.0f)
  1015. {
  1016. float last = Health;
  1017. Health += m_healRatePerFrame;
  1018. if(Health > 100.0f)
  1019. {
  1020. Health = 100.0f;
  1021. lastHealthSent = Health;
  1022. ControllingClient.SendHealth(Health);
  1023. }
  1024. else if(Math.Abs(Health - lastHealthSent) > 1.0)
  1025. {
  1026. lastHealthSent = Health;
  1027. ControllingClient.SendHealth(Health);
  1028. }
  1029. }
  1030. }
  1031. public void RegisterToClientEvents()
  1032. {
  1033. ControllingClient.OnCompleteMovementToRegion += CompleteMovement;
  1034. ControllingClient.OnAgentUpdate += HandleAgentUpdate;
  1035. ControllingClient.OnAgentCameraUpdate += HandleAgentCamerasUpdate;
  1036. ControllingClient.OnAgentRequestSit += HandleAgentRequestSit;
  1037. ControllingClient.OnAgentSit += HandleAgentSit;
  1038. ControllingClient.OnSetAlwaysRun += HandleSetAlwaysRun;
  1039. ControllingClient.OnStartAnim += HandleStartAnim;
  1040. ControllingClient.OnStopAnim += HandleStopAnim;
  1041. ControllingClient.OnChangeAnim += avnHandleChangeAnim;
  1042. ControllingClient.OnForceReleaseControls += HandleForceReleaseControls;
  1043. ControllingClient.OnAutoPilotGo += MoveToTargetHandle;
  1044. ControllingClient.OnUpdateThrottles += RaiseUpdateThrottles;
  1045. ControllingClient.OnRegionHandShakeReply += RegionHandShakeReply;
  1046. // ControllingClient.OnAgentFOV += HandleAgentFOV;
  1047. // ControllingClient.OnChildAgentStatus += new StatusChange(this.ChildStatusChange);
  1048. // ControllingClient.OnStopMovement += new GenericCall2(this.StopMovement);
  1049. }
  1050. public void RemoveClientEvents()
  1051. {
  1052. ControllingClient.OnCompleteMovementToRegion -= CompleteMovement;
  1053. ControllingClient.OnAgentUpdate -= HandleAgentUpdate;
  1054. ControllingClient.OnAgentCameraUpdate -= HandleAgentCamerasUpdate;
  1055. ControllingClient.OnAgentRequestSit -= HandleAgentRequestSit;
  1056. ControllingClient.OnAgentSit -= HandleAgentSit;
  1057. ControllingClient.OnSetAlwaysRun -= HandleSetAlwaysRun;
  1058. ControllingClient.OnStartAnim -= HandleStartAnim;
  1059. ControllingClient.OnStopAnim -= HandleStopAnim;
  1060. ControllingClient.OnChangeAnim -= avnHandleChangeAnim;
  1061. ControllingClient.OnForceReleaseControls -= HandleForceReleaseControls;
  1062. ControllingClient.OnAutoPilotGo -= MoveToTargetHandle;
  1063. ControllingClient.OnUpdateThrottles -= RaiseUpdateThrottles;
  1064. ControllingClient.OnRegionHandShakeReply -= RegionHandShakeReply;
  1065. // ControllingClient.OnAgentFOV += HandleAgentFOV;
  1066. }
  1067. private void SetDirectionVectors()
  1068. {
  1069. Dir_Vectors[0] = new Vector3(AgentControlNormalVel,0,0); //FORWARD
  1070. Dir_Vectors[1] = new Vector3(-AgentControlNormalVel,0,0);; //BACK
  1071. Dir_Vectors[2] = new Vector3(0,AgentControlNormalVel,0); //LEFT
  1072. Dir_Vectors[3] = new Vector3(0,-AgentControlNormalVel,0); //RIGHT
  1073. Dir_Vectors[4] = new Vector3(0,0,AgentControlNormalVel); //UP
  1074. Dir_Vectors[5] = new Vector3(0,0,-AgentControlNormalVel); //DOWN
  1075. Dir_Vectors[6] = new Vector3(AgentControlNudgeVel, 0f, 0f); //FORWARD_NUDGE
  1076. Dir_Vectors[7] = new Vector3(-AgentControlNudgeVel, 0f, 0f); //BACK_NUDGE
  1077. Dir_Vectors[8] = new Vector3(0f, AgentControlNudgeVel, 0f); //LEFT_NUDGE
  1078. Dir_Vectors[9] = new Vector3(0f, -AgentControlNudgeVel, 0f); //RIGHT_NUDGE
  1079. Dir_Vectors[10] = new Vector3(0f, 0f, AgentControlNudgeVel); //UP_Nudge
  1080. Dir_Vectors[11] = new Vector3(0f, 0f, -AgentControlNudgeVel); //DOWN_Nudge
  1081. }
  1082. #endregion
  1083. #region Status Methods
  1084. /// <summary>
  1085. /// Turns a child agent into a root agent.
  1086. /// </summary>
  1087. /// <remarks>
  1088. /// Child agents are logged into neighbouring sims largely to observe changes. Root agents exist when the
  1089. /// avatar is actual in the sim. They can perform all actions.
  1090. /// This change is made whenever an avatar enters a region, whether by crossing over from a neighbouring sim,
  1091. /// teleporting in or on initial login.
  1092. ///
  1093. /// This method is on the critical path for transferring an avatar from one region to another. Delay here
  1094. /// delays that crossing.
  1095. /// </remarks>
  1096. // constants for physics position search
  1097. const float PhysSearchHeight = 300f;
  1098. const float PhysMinSkipGap = 20f;
  1099. const float PhysSkipGapDelta = 30f;
  1100. const int PhysNumberCollisions = 30;
  1101. // only in use as part of completemovement
  1102. // other uses need fix
  1103. private bool MakeRootAgent(Vector3 pos, bool isFlying, ref Vector3 lookat)
  1104. {
  1105. //int ts = Util.EnvironmentTickCount();
  1106. lock (m_completeMovementLock)
  1107. {
  1108. if (!IsChildAgent)
  1109. return false;
  1110. //m_log.DebugFormat("[MakeRootAgent] enter lock: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1111. //m_log.DebugFormat("[SCENE]: known regions in {0}: {1}", Scene.RegionInfo.RegionName, KnownChildRegionHandles.Count);
  1112. // m_log.InfoFormat(
  1113. // "[SCENE]: Upgrading child to root agent for {0} in {1}",
  1114. // Name, m_scene.RegionInfo.RegionName);
  1115. if (ParentUUID != UUID.Zero)
  1116. {
  1117. m_log.DebugFormat("[SCENE PRESENCE]: Sitting avatar back on prim {0}", ParentUUID);
  1118. SceneObjectPart part = m_scene.GetSceneObjectPart(ParentUUID);
  1119. if (part == null)
  1120. {
  1121. m_log.ErrorFormat("[SCENE PRESENCE]: Can't find prim {0} to sit on", ParentUUID);
  1122. ParentID = 0;
  1123. ParentPart = null;
  1124. PrevSitOffset = Vector3.Zero;
  1125. HandleForceReleaseControls(ControllingClient, UUID); // needs testing
  1126. }
  1127. else
  1128. {
  1129. part.AddSittingAvatar(this);
  1130. // if not actually on the target invalidate it
  1131. if(m_gotCrossUpdate && (m_crossingFlags & 0x04) == 0)
  1132. part.SitTargetAvatar = UUID.Zero;
  1133. ParentID = part.LocalId;
  1134. ParentPart = part;
  1135. m_pos = PrevSitOffset;
  1136. pos = part.GetWorldPosition();
  1137. PhysicsActor partPhysActor = part.PhysActor;
  1138. if(partPhysActor != null)
  1139. {
  1140. partPhysActor.OnPhysicsRequestingCameraData -=
  1141. physActor_OnPhysicsRequestingCameraData;
  1142. partPhysActor.OnPhysicsRequestingCameraData +=
  1143. physActor_OnPhysicsRequestingCameraData;
  1144. }
  1145. }
  1146. ParentUUID = UUID.Zero;
  1147. }
  1148. IsChildAgent = false;
  1149. }
  1150. //m_log.DebugFormat("[MakeRootAgent] out lock: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1151. // Must reset this here so that a teleport to a region next to an existing region does not keep the flag
  1152. // set and prevent the close of the connection on a subsequent re-teleport.
  1153. // Should not be needed if we are not trying to tell this region to close
  1154. // DoNotCloseAfterTeleport = false;
  1155. RegionHandle = m_scene.RegionInfo.RegionHandle;
  1156. m_scene.EventManager.TriggerSetRootAgentScene(m_uuid, m_scene);
  1157. //m_log.DebugFormat("[MakeRootAgent] TriggerSetRootAgentScene: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1158. if (ParentID == 0)
  1159. {
  1160. bool positionChanged = false;
  1161. bool success = true;
  1162. if (m_LandingPointBehavior == LandingPointBehavior.OS)
  1163. success = CheckAndAdjustLandingPoint_OS(ref pos, ref lookat, ref positionChanged);
  1164. else
  1165. success = CheckAndAdjustLandingPoint_SL(ref pos, ref lookat, ref positionChanged);
  1166. if (!success)
  1167. m_log.DebugFormat("[SCENE PRESENCE MakeRootAgent]: houston we have a problem.. {0} ({1} got banned)", Name, UUID);
  1168. if (pos.X < 0f || pos.Y < 0f
  1169. || pos.X >= m_scene.RegionInfo.RegionSizeX
  1170. || pos.Y >= m_scene.RegionInfo.RegionSizeY)
  1171. {
  1172. m_log.WarnFormat(
  1173. "[SCENE PRESENCE]: MakeRootAgent() was given an illegal position of {0} for avatar {1}, {2}. Clamping",
  1174. pos, Name, UUID);
  1175. if (pos.X < 0f)
  1176. pos.X = 0.5f;
  1177. else if(pos.X >= m_scene.RegionInfo.RegionSizeX)
  1178. pos.X = m_scene.RegionInfo.RegionSizeX - 0.5f;
  1179. if (pos.Y < 0f)
  1180. pos.Y = 0.5f;
  1181. else if(pos.Y >= m_scene.RegionInfo.RegionSizeY)
  1182. pos.Y = m_scene.RegionInfo.RegionSizeY - 0.5f;
  1183. }
  1184. float groundHeight = m_scene.GetGroundHeight(pos.X, pos.Y) + .01f;
  1185. float physTestHeight;
  1186. if(PhysSearchHeight < groundHeight + 100f)
  1187. physTestHeight = groundHeight + 100f;
  1188. else
  1189. physTestHeight = PhysSearchHeight;
  1190. float localAVHalfHeight = 0.8f;
  1191. if (Appearance != null && Appearance.AvatarHeight > 0)
  1192. localAVHalfHeight = 0.5f * Appearance.AvatarHeight;
  1193. groundHeight += localAVHalfHeight;
  1194. if (groundHeight > pos.Z)
  1195. pos.Z = groundHeight;
  1196. bool checkPhysics = !positionChanged &&
  1197. m_scene.SupportsRayCastFiltered() &&
  1198. pos.Z < physTestHeight &&
  1199. ((m_teleportFlags & (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)) ==
  1200. (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)
  1201. || (m_teleportFlags & TeleportFlags.ViaLocation) != 0
  1202. || (m_teleportFlags & TeleportFlags.ViaHGLogin) != 0);
  1203. if(checkPhysics)
  1204. {
  1205. // land check was done above
  1206. RayFilterFlags rayfilter = RayFilterFlags.BackFaceCull;
  1207. rayfilter |= RayFilterFlags.PrimsNonPhantomAgents;
  1208. int physcount = PhysNumberCollisions;
  1209. float dist = physTestHeight - groundHeight + localAVHalfHeight;
  1210. Vector3 direction = new Vector3(0f, 0f, -1f);
  1211. Vector3 RayStart = pos;
  1212. RayStart.Z = physTestHeight;
  1213. List<ContactResult> physresults =
  1214. (List<ContactResult>)m_scene.RayCastFiltered(RayStart, direction, dist, physcount, rayfilter);
  1215. while (physresults != null && physresults.Count > 0)
  1216. {
  1217. float dest = physresults[0].Pos.Z;
  1218. if (dest - groundHeight > PhysMinSkipGap + PhysSkipGapDelta)
  1219. break;
  1220. if (physresults.Count > 1)
  1221. {
  1222. physresults.Sort(delegate(ContactResult a, ContactResult b)
  1223. {
  1224. return a.Depth.CompareTo(b.Depth);
  1225. });
  1226. int sel = 0;
  1227. int count = physresults.Count;
  1228. float curd = physresults[0].Depth;
  1229. float nextd = curd + PhysMinSkipGap;
  1230. float maxDepth = dist - pos.Z;
  1231. for(int i = 1; i < count; i++)
  1232. {
  1233. curd = physresults[i].Depth;
  1234. if(curd >= nextd)
  1235. {
  1236. sel = i;
  1237. if(curd >= maxDepth || curd >= nextd + PhysSkipGapDelta)
  1238. break;
  1239. }
  1240. nextd = curd + PhysMinSkipGap;
  1241. }
  1242. dest = physresults[sel].Pos.Z;
  1243. }
  1244. dest += localAVHalfHeight;
  1245. if(dest > pos.Z)
  1246. pos.Z = dest;
  1247. break;
  1248. }
  1249. }
  1250. AbsolutePosition = pos;
  1251. // m_log.DebugFormat(
  1252. // "Set pos {0}, vel {1} in {1} to {2} from input position of {3} on MakeRootAgent",
  1253. // Name, Scene.Name, AbsolutePosition, pos);
  1254. //
  1255. if (m_teleportFlags == TeleportFlags.Default)
  1256. {
  1257. Vector3 vel = Velocity;
  1258. AddToPhysicalScene(isFlying);
  1259. if (PhysicsActor != null)
  1260. PhysicsActor.SetMomentum(vel);
  1261. }
  1262. else
  1263. {
  1264. AddToPhysicalScene(isFlying);
  1265. // reset camera to avatar pos
  1266. CameraPosition = pos;
  1267. }
  1268. if (ForceFly)
  1269. {
  1270. Flying = true;
  1271. }
  1272. else if (FlyDisabled)
  1273. {
  1274. Flying = false;
  1275. }
  1276. }
  1277. //m_log.DebugFormat("[MakeRootAgent] position and physical: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1278. m_scene.SwapRootAgentCount(false);
  1279. // If we don't reset the movement flag here, an avatar that crosses to a neighbouring sim and returns will
  1280. // stall on the border crossing since the existing child agent will still have the last movement
  1281. // recorded, which stops the input from being processed.
  1282. MovementFlag = 0;
  1283. m_scene.EventManager.TriggerOnMakeRootAgent(this);
  1284. //m_log.DebugFormat("[MakeRootAgent] TriggerOnMakeRootAgent and done: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1285. return true;
  1286. }
  1287. private void RestartAttachmentScripts()
  1288. {
  1289. // We need to restart scripts here so that they receive the correct changed events (CHANGED_TELEPORT
  1290. // and CHANGED_REGION) when the attachments have been rezzed in the new region. This cannot currently
  1291. // be done in AttachmentsModule.CopyAttachments(AgentData ad, IScenePresence sp) itself since we are
  1292. // not transporting the required data.
  1293. //
  1294. // We must take a copy of the attachments list here (rather than locking) to avoid a deadlock where a script in one of
  1295. // the attachments may start processing an event (which locks ScriptInstance.m_Script) that then calls a method here
  1296. // which needs to lock m_attachments. ResumeScripts() needs to take a ScriptInstance.m_Script lock to try to unset the Suspend status.
  1297. //
  1298. // FIXME: In theory, this deadlock should not arise since scripts should not be processing events until ResumeScripts().
  1299. // But XEngine starts all scripts unsuspended. Starting them suspended will not currently work because script rezzing
  1300. // is placed in an asynchronous queue in XEngine and so the ResumeScripts() call will almost certainly execute before the
  1301. // script is rezzed. This means the ResumeScripts() does absolutely nothing when using XEngine.
  1302. List<SceneObjectGroup> attachments = GetAttachments();
  1303. m_log.DebugFormat(
  1304. "[SCENE PRESENCE]: Restarting scripts in {0} attachments for {1} in {2}", attachments.Count, Name, Scene.Name);
  1305. // Resume scripts
  1306. foreach (SceneObjectGroup sog in attachments)
  1307. {
  1308. sog.ScheduleGroupForFullUpdate();
  1309. sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource());
  1310. sog.ResumeScripts();
  1311. }
  1312. }
  1313. private static bool IsRealLogin(TeleportFlags teleportFlags)
  1314. {
  1315. return ((teleportFlags & TeleportFlags.ViaLogin) != 0) && ((teleportFlags & TeleportFlags.ViaHGLogin) == 0);
  1316. }
  1317. /// <summary>
  1318. /// Force viewers to show the avatar's current name.
  1319. /// </summary>
  1320. /// <remarks>
  1321. /// The avatar name that is shown above the avatar in the viewers is sent in ObjectUpdate packets,
  1322. /// and they get the name from the ScenePresence. Unfortunately, viewers have a bug (as of April 2014)
  1323. /// where they ignore changes to the avatar name. However, tey don't ignore changes to the avatar's
  1324. /// Group Title. So the following trick makes viewers update the avatar's name by briefly changing
  1325. /// the group title (to "(Loading)"), and then restoring it.
  1326. /// </remarks>
  1327. /*
  1328. public void ForceViewersUpdateName()
  1329. {
  1330. m_log.DebugFormat("[SCENE PRESENCE]: Forcing viewers to update the avatar name for " + Name);
  1331. UseFakeGroupTitle = true;
  1332. Util.FireAndForget(o =>
  1333. {
  1334. // Viewers only update the avatar name when idle. Therefore, we must wait long
  1335. // enough for the viewer to show the fake name that we had set above, and only
  1336. // then switch back to the true name. This delay was chosen because it has a high
  1337. // chance of succeeding (we don't want to choose a value that's too low).
  1338. Thread.Sleep(5000);
  1339. UseFakeGroupTitle = false;
  1340. SendAvatarDataToAllClients(false);
  1341. }, null, "Scenepresence.ForceViewersUpdateName");
  1342. }
  1343. */
  1344. public int GetStateSource()
  1345. {
  1346. /*
  1347. AgentCircuitData aCircuit = m_scene.AuthenticateHandler.GetAgentCircuitData(UUID);
  1348. if (aCircuit != null && (aCircuit.teleportFlags != (uint)TeleportFlags.Default))
  1349. {
  1350. // This will get your attention
  1351. //m_log.Error("[XXX] Triggering CHANGED_TELEPORT");
  1352. return 5; // StateSource.Teleporting
  1353. }
  1354. return 2; // StateSource.PrimCrossing
  1355. */
  1356. return m_teleportFlags == TeleportFlags.Default ? 2 : 5;
  1357. }
  1358. /// <summary>
  1359. /// This turns a root agent into a child agent
  1360. /// </summary>
  1361. /// <remarks>
  1362. /// when an agent departs this region for a neighbor, this gets called.
  1363. ///
  1364. /// It doesn't get called for a teleport. Reason being, an agent that
  1365. /// teleports out may not end up anywhere near this region
  1366. /// </remarks>
  1367. public void MakeChildAgent(ulong newRegionHandle)
  1368. {
  1369. m_updateAgentReceivedAfterTransferEvent.Reset();
  1370. m_haveGroupInformation = false;
  1371. m_gotCrossUpdate = false;
  1372. m_crossingFlags = 0;
  1373. m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
  1374. RegionHandle = newRegionHandle;
  1375. m_log.DebugFormat("[SCENE PRESENCE]: Making {0} a child agent in {1} from root region {2}",
  1376. Name, Scene.RegionInfo.RegionName, newRegionHandle);
  1377. // Reset the m_originRegionID as it has dual use as a flag to signal that the UpdateAgent() call orignating
  1378. // from the source simulator has completed on a V2 teleport.
  1379. lock (m_originRegionIDAccessLock)
  1380. m_originRegionID = UUID.Zero;
  1381. // Reset these so that teleporting in and walking out isn't seen
  1382. // as teleporting back
  1383. TeleportFlags = TeleportFlags.Default;
  1384. MovementFlag = 0;
  1385. // It looks like Animator is set to null somewhere, and MakeChild
  1386. // is called after that. Probably in aborted teleports.
  1387. if (Animator == null)
  1388. Animator = new ScenePresenceAnimator(this);
  1389. else
  1390. Animator.ResetAnimations();
  1391. // m_log.DebugFormat(
  1392. // "[SCENE PRESENCE]: Downgrading root agent {0}, {1} to a child agent in {2}",
  1393. // Name, UUID, m_scene.RegionInfo.RegionName);
  1394. // Don't zero out the velocity since this can cause problems when an avatar is making a region crossing,
  1395. // depending on the exact timing. This shouldn't matter anyway since child agent positions are not updated.
  1396. //Velocity = new Vector3(0, 0, 0);
  1397. IsChildAgent = true;
  1398. m_scene.SwapRootAgentCount(true);
  1399. RemoveFromPhysicalScene();
  1400. ParentID = 0; // Child agents can't be sitting
  1401. // we dont have land information for child
  1402. m_previusParcelHide = false;
  1403. m_previusParcelUUID = UUID.Zero;
  1404. m_currentParcelHide = false;
  1405. m_currentParcelUUID = UUID.Zero;
  1406. CollisionPlane = Vector4.UnitW;
  1407. // we need to kill this on agents that do not see the new region
  1408. m_scene.ForEachRootScenePresence(delegate(ScenePresence p)
  1409. {
  1410. if (!p.knowsNeighbourRegion(newRegionHandle))
  1411. {
  1412. SendKillTo(p);
  1413. }
  1414. });
  1415. m_scene.EventManager.TriggerOnMakeChildAgent(this);
  1416. }
  1417. /// <summary>
  1418. /// Removes physics plugin scene representation of this agent if it exists.
  1419. /// </summary>
  1420. public void RemoveFromPhysicalScene()
  1421. {
  1422. PhysicsActor pa = Interlocked.Exchange(ref m_physActor, null);
  1423. if (pa != null)
  1424. {
  1425. // PhysicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients;
  1426. pa.OnOutOfBounds -= OutOfBoundsCall;
  1427. pa.OnCollisionUpdate -= PhysicsCollisionUpdate;
  1428. pa.UnSubscribeEvents();
  1429. m_scene.PhysicsScene.RemoveAvatar(pa);
  1430. }
  1431. // else
  1432. // {
  1433. // m_log.ErrorFormat(
  1434. // "[SCENE PRESENCE]: Attempt to remove physics actor for {0} on {1} but this scene presence has no physics actor",
  1435. // Name, Scene.RegionInfo.RegionName);
  1436. // }
  1437. }
  1438. public void Teleport(Vector3 pos)
  1439. {
  1440. TeleportWithMomentum(pos, Vector3.Zero);
  1441. }
  1442. public void TeleportWithMomentum(Vector3 pos, Vector3? v)
  1443. {
  1444. if(!CheckLocalTPLandingPoint(ref pos))
  1445. return;
  1446. if (ParentID != (uint)0)
  1447. StandUp();
  1448. bool isFlying = Flying;
  1449. Vector3 vel = Velocity;
  1450. RemoveFromPhysicalScene();
  1451. AbsolutePosition = pos;
  1452. AddToPhysicalScene(isFlying);
  1453. if (PhysicsActor != null)
  1454. {
  1455. if (v.HasValue)
  1456. PhysicsActor.SetMomentum((Vector3)v);
  1457. else
  1458. PhysicsActor.SetMomentum(vel);
  1459. }
  1460. SendTerseUpdateToAllClients();
  1461. }
  1462. public void TeleportOnEject(Vector3 pos)
  1463. {
  1464. if (ParentID != (uint)0)
  1465. StandUp();
  1466. bool isFlying = Flying;
  1467. RemoveFromPhysicalScene();
  1468. AbsolutePosition = pos;
  1469. AddToPhysicalScene(isFlying);
  1470. SendTerseUpdateToAllClients();
  1471. }
  1472. public void LocalTeleport(Vector3 newpos, Vector3 newvel, Vector3 newlookat, int flags)
  1473. {
  1474. if (newpos.X <= 0)
  1475. {
  1476. newpos.X = 0.1f;
  1477. if (newvel.X < 0)
  1478. newvel.X = 0;
  1479. }
  1480. else if (newpos.X >= Scene.RegionInfo.RegionSizeX)
  1481. {
  1482. newpos.X = Scene.RegionInfo.RegionSizeX - 0.1f;
  1483. if (newvel.X > 0)
  1484. newvel.X = 0;
  1485. }
  1486. if (newpos.Y <= 0)
  1487. {
  1488. newpos.Y = 0.1f;
  1489. if (newvel.Y < 0)
  1490. newvel.Y = 0;
  1491. }
  1492. else if (newpos.Y >= Scene.RegionInfo.RegionSizeY)
  1493. {
  1494. newpos.Y = Scene.RegionInfo.RegionSizeY - 0.1f;
  1495. if (newvel.Y > 0)
  1496. newvel.Y = 0;
  1497. }
  1498. string reason;
  1499. if (!m_scene.TestLandRestrictions(UUID, out reason, ref newpos.X, ref newpos.Y))
  1500. return ;
  1501. if (IsSatOnObject)
  1502. StandUp();
  1503. float localHalfAVHeight = 0.8f;
  1504. if (Appearance != null)
  1505. localHalfAVHeight = Appearance.AvatarHeight * 0.5f;
  1506. float posZLimit = (float)Scene.Heightmap[(int)newpos.X, (int)newpos.Y];
  1507. posZLimit += localHalfAVHeight + 0.1f;
  1508. if (newpos.Z < posZLimit)
  1509. newpos.Z = posZLimit;
  1510. if((flags & 0x1e) != 0)
  1511. {
  1512. if ((flags & 8) != 0)
  1513. Flying = true;
  1514. else if ((flags & 16) != 0)
  1515. Flying = false;
  1516. uint tpflags = (uint)TeleportFlags.ViaLocation;
  1517. if(Flying)
  1518. tpflags |= (uint)TeleportFlags.IsFlying;
  1519. Vector3 lookat = Lookat;
  1520. if ((flags & 2) != 0)
  1521. {
  1522. newlookat.Z = 0;
  1523. newlookat.Normalize();
  1524. if (Math.Abs(newlookat.X) > 0.001 || Math.Abs(newlookat.Y) > 0.001)
  1525. lookat = newlookat;
  1526. }
  1527. else if((flags & 4) != 0)
  1528. {
  1529. if((flags & 1) != 0)
  1530. newlookat = newvel;
  1531. else
  1532. newlookat = m_velocity;
  1533. newlookat.Z = 0;
  1534. newlookat.Normalize();
  1535. if (Math.Abs(newlookat.X) > 0.001 || Math.Abs(newlookat.Y) > 0.001)
  1536. lookat = newlookat;
  1537. }
  1538. AbsolutePosition = newpos;
  1539. ControllingClient.SendLocalTeleport(newpos, lookat, tpflags);
  1540. }
  1541. else
  1542. AbsolutePosition = newpos;
  1543. if ((flags & 1) != 0)
  1544. {
  1545. if (PhysicsActor != null)
  1546. PhysicsActor.SetMomentum(newvel);
  1547. m_velocity = newvel;
  1548. }
  1549. SendTerseUpdateToAllClients();
  1550. }
  1551. public void StopFlying()
  1552. {
  1553. if (IsInTransit)
  1554. return;
  1555. Vector3 pos = AbsolutePosition;
  1556. if (Appearance.AvatarHeight != 127.0f)
  1557. pos += new Vector3(0f, 0f, (Appearance.AvatarHeight / 6f));
  1558. else
  1559. pos += new Vector3(0f, 0f, (1.56f / 6f));
  1560. AbsolutePosition = pos;
  1561. // attach a suitable collision plane regardless of the actual situation to force the LLClient to land.
  1562. // Collision plane below the avatar's position a 6th of the avatar's height is suitable.
  1563. // Mind you, that this method doesn't get called if the avatar's velocity magnitude is greater then a
  1564. // certain amount.. because the LLClient wouldn't land in that situation anyway.
  1565. // why are we still testing for this really old height value default???
  1566. if (Appearance.AvatarHeight != 127.0f)
  1567. CollisionPlane = new Vector4(0, 0, 0, pos.Z - Appearance.AvatarHeight / 6f);
  1568. else
  1569. CollisionPlane = new Vector4(0, 0, 0, pos.Z - (1.56f / 6f));
  1570. SendAgentTerseUpdate(this);
  1571. }
  1572. /// <summary>
  1573. /// Applies a roll accumulator to the avatar's angular velocity for the avatar fly roll effect.
  1574. /// </summary>
  1575. /// <param name="amount">Postive or negative roll amount in radians</param>
  1576. private void ApplyFlyingRoll(float amount, bool PressingUp, bool PressingDown)
  1577. {
  1578. float rollAmount = Util.Clamp(m_AngularVelocity.Z + amount, -FLY_ROLL_MAX_RADIANS, FLY_ROLL_MAX_RADIANS);
  1579. m_AngularVelocity.Z = rollAmount;
  1580. // APPLY EXTRA consideration for flying up and flying down during this time.
  1581. // if we're turning left
  1582. if (amount > 0)
  1583. {
  1584. // If we're at the max roll and pressing up, we want to swing BACK a bit
  1585. // Automatically adds noise
  1586. if (PressingUp)
  1587. {
  1588. if (m_AngularVelocity.Z >= FLY_ROLL_MAX_RADIANS - 0.04f)
  1589. m_AngularVelocity.Z -= 0.9f;
  1590. }
  1591. // If we're at the max roll and pressing down, we want to swing MORE a bit
  1592. if (PressingDown)
  1593. {
  1594. if (m_AngularVelocity.Z >= FLY_ROLL_MAX_RADIANS && m_AngularVelocity.Z < FLY_ROLL_MAX_RADIANS + 0.6f)
  1595. m_AngularVelocity.Z += 0.6f;
  1596. }
  1597. }
  1598. else // we're turning right.
  1599. {
  1600. // If we're at the max roll and pressing up, we want to swing BACK a bit
  1601. // Automatically adds noise
  1602. if (PressingUp)
  1603. {
  1604. if (m_AngularVelocity.Z <= (-FLY_ROLL_MAX_RADIANS))
  1605. m_AngularVelocity.Z += 0.6f;
  1606. }
  1607. // If we're at the max roll and pressing down, we want to swing MORE a bit
  1608. if (PressingDown)
  1609. {
  1610. if (m_AngularVelocity.Z >= -FLY_ROLL_MAX_RADIANS - 0.6f)
  1611. m_AngularVelocity.Z -= 0.6f;
  1612. }
  1613. }
  1614. }
  1615. /// <summary>
  1616. /// incrementally sets roll amount to zero
  1617. /// </summary>
  1618. /// <param name="amount">Positive roll amount in radians</param>
  1619. /// <returns></returns>
  1620. private float CalculateFlyingRollResetToZero(float amount)
  1621. {
  1622. const float rollMinRadians = 0f;
  1623. if (m_AngularVelocity.Z > 0)
  1624. {
  1625. float leftOverToMin = m_AngularVelocity.Z - rollMinRadians;
  1626. if (amount > leftOverToMin)
  1627. return -leftOverToMin;
  1628. else
  1629. return -amount;
  1630. }
  1631. else
  1632. {
  1633. float leftOverToMin = -m_AngularVelocity.Z - rollMinRadians;
  1634. if (amount > leftOverToMin)
  1635. return leftOverToMin;
  1636. else
  1637. return amount;
  1638. }
  1639. }
  1640. // neighbouring regions we have enabled a child agent in
  1641. // holds the seed cap for the child agent in that region
  1642. private Dictionary<ulong, string> m_knownChildRegions = new Dictionary<ulong, string>();
  1643. struct spRegionSizeInfo
  1644. {
  1645. public int sizeX;
  1646. public int sizeY;
  1647. }
  1648. private Dictionary<ulong, spRegionSizeInfo> m_knownChildRegionsSizeInfo = new Dictionary<ulong, spRegionSizeInfo>();
  1649. public void AddNeighbourRegion(GridRegion region, string capsPath)
  1650. {
  1651. lock (m_knownChildRegions)
  1652. {
  1653. ulong regionHandle = region.RegionHandle;
  1654. m_knownChildRegions.Add(regionHandle,capsPath);
  1655. spRegionSizeInfo sizeInfo = new spRegionSizeInfo();
  1656. sizeInfo.sizeX = region.RegionSizeX;
  1657. sizeInfo.sizeY = region.RegionSizeY;
  1658. m_knownChildRegionsSizeInfo[regionHandle] = sizeInfo;
  1659. }
  1660. }
  1661. public void AddNeighbourRegionSizeInfo(GridRegion region)
  1662. {
  1663. lock (m_knownChildRegions)
  1664. {
  1665. spRegionSizeInfo sizeInfo = new spRegionSizeInfo();
  1666. sizeInfo.sizeX = region.RegionSizeX;
  1667. sizeInfo.sizeY = region.RegionSizeY;
  1668. ulong regionHandle = region.RegionHandle;
  1669. if (!m_knownChildRegionsSizeInfo.ContainsKey(regionHandle))
  1670. {
  1671. m_knownChildRegionsSizeInfo.Add(regionHandle, sizeInfo);
  1672. }
  1673. else
  1674. m_knownChildRegionsSizeInfo[regionHandle] = sizeInfo;
  1675. }
  1676. }
  1677. public void SetNeighbourRegionSizeInfo(List<GridRegion> regionsList)
  1678. {
  1679. lock (m_knownChildRegions)
  1680. {
  1681. m_knownChildRegionsSizeInfo.Clear();
  1682. foreach (GridRegion region in regionsList)
  1683. {
  1684. spRegionSizeInfo sizeInfo = new spRegionSizeInfo();
  1685. sizeInfo.sizeX = region.RegionSizeX;
  1686. sizeInfo.sizeY = region.RegionSizeY;
  1687. ulong regionHandle = region.RegionHandle;
  1688. m_knownChildRegionsSizeInfo.Add(regionHandle, sizeInfo);
  1689. }
  1690. }
  1691. }
  1692. public void RemoveNeighbourRegion(ulong regionHandle)
  1693. {
  1694. lock (m_knownChildRegions)
  1695. {
  1696. // Checking ContainsKey is redundant as Remove works either way and returns a bool
  1697. // This is here to allow the Debug output to be conditional on removal
  1698. //if (m_knownChildRegions.ContainsKey(regionHandle))
  1699. // m_log.DebugFormat(" !!! removing known region {0} in {1}. Count = {2}", regionHandle, Scene.RegionInfo.RegionName, m_knownChildRegions.Count);
  1700. m_knownChildRegions.Remove(regionHandle);
  1701. m_knownChildRegionsSizeInfo.Remove(regionHandle);
  1702. }
  1703. }
  1704. public bool knowsNeighbourRegion(ulong regionHandle)
  1705. {
  1706. lock (m_knownChildRegions)
  1707. return m_knownChildRegions.ContainsKey(regionHandle);
  1708. }
  1709. public void DropOldNeighbours(List<ulong> oldRegions)
  1710. {
  1711. foreach (ulong handle in oldRegions)
  1712. {
  1713. RemoveNeighbourRegion(handle);
  1714. Scene.CapsModule.DropChildSeed(UUID, handle);
  1715. }
  1716. }
  1717. public void DropThisRootRegionFromNeighbours()
  1718. {
  1719. ulong handle = m_scene.RegionInfo.RegionHandle;
  1720. RemoveNeighbourRegion(handle);
  1721. Scene.CapsModule.DropChildSeed(UUID, handle);
  1722. }
  1723. public Dictionary<ulong, string> KnownRegions
  1724. {
  1725. get
  1726. {
  1727. lock (m_knownChildRegions)
  1728. return new Dictionary<ulong, string>(m_knownChildRegions);
  1729. }
  1730. set
  1731. {
  1732. // Replacing the reference is atomic but we still need to lock on
  1733. // the original dictionary object which may be in use elsewhere
  1734. lock (m_knownChildRegions)
  1735. m_knownChildRegions = value;
  1736. }
  1737. }
  1738. public List<ulong> KnownRegionHandles
  1739. {
  1740. get
  1741. {
  1742. lock (m_knownChildRegions)
  1743. return new List<ulong>(m_knownChildRegions.Keys);
  1744. }
  1745. }
  1746. public int KnownRegionCount
  1747. {
  1748. get
  1749. {
  1750. lock (m_knownChildRegions)
  1751. return m_knownChildRegions.Count;
  1752. }
  1753. }
  1754. #endregion
  1755. #region Event Handlers
  1756. /// <summary>
  1757. /// Sets avatar height in the physics plugin
  1758. /// </summary>
  1759. /// <param name="height">New height of avatar</param>
  1760. public void SetHeight(float height)
  1761. {
  1762. if (PhysicsActor != null && !IsChildAgent)
  1763. PhysicsActor.Size = new Vector3(0.45f, 0.6f, height);
  1764. }
  1765. public void SetSize(Vector3 size, float feetoffset)
  1766. {
  1767. if (PhysicsActor != null && !IsChildAgent)
  1768. PhysicsActor.setAvatarSize(size, feetoffset);
  1769. }
  1770. private bool WaitForUpdateAgent(IClientAPI client)
  1771. {
  1772. // Before the source region executes UpdateAgent
  1773. // (which triggers Scene.IncomingUpdateChildAgent(AgentData cAgentData) here in the destination,
  1774. // m_originRegionID is UUID.Zero; after, it's non-Zero. The CompleteMovement sequence initiated from the
  1775. // viewer (in turn triggered by the source region sending it a TeleportFinish event) waits until it's non-zero
  1776. try
  1777. {
  1778. if(m_updateAgentReceivedAfterTransferEvent.WaitOne(10000))
  1779. {
  1780. UUID originID = UUID.Zero;
  1781. lock (m_originRegionIDAccessLock)
  1782. originID = m_originRegionID;
  1783. if (originID.Equals(UUID.Zero))
  1784. {
  1785. // Movement into region will fail
  1786. m_log.WarnFormat("[SCENE PRESENCE]: Update agent {0} at {1} got invalid origin region id ", client.Name, Scene.Name);
  1787. return false;
  1788. }
  1789. return true;
  1790. }
  1791. else
  1792. {
  1793. m_log.WarnFormat("[SCENE PRESENCE]: Update agent {0} at {1} did not receive agent update ", client.Name, Scene.Name);
  1794. return false;
  1795. }
  1796. }
  1797. catch { }
  1798. finally
  1799. {
  1800. m_updateAgentReceivedAfterTransferEvent.Reset();
  1801. }
  1802. return false;
  1803. }
  1804. public void RotateToLookAt(Vector3 lookAt)
  1805. {
  1806. if(ParentID == 0)
  1807. {
  1808. float n = lookAt.X * lookAt.X + lookAt.Y * lookAt.Y;
  1809. if(n < 0.0001f)
  1810. {
  1811. Rotation = Quaternion.Identity;
  1812. return;
  1813. }
  1814. n = lookAt.X/(float)Math.Sqrt(n);
  1815. float angle = (float)Math.Acos(n);
  1816. angle *= 0.5f;
  1817. float s = (float)Math.Sin(angle);
  1818. if(lookAt.Y < 0)
  1819. s = -s;
  1820. Rotation = new Quaternion(
  1821. 0f,
  1822. 0f,
  1823. s,
  1824. (float)Math.Cos(angle)
  1825. );
  1826. }
  1827. }
  1828. /// <summary>
  1829. /// Complete Avatar's movement into the region.
  1830. /// </summary>
  1831. /// <param name="client"></param>
  1832. /// <param name="openChildAgents">
  1833. /// If true, send notification to neighbour regions to expect
  1834. /// a child agent from the client. These neighbours can be some distance away, depending right now on the
  1835. /// configuration of DefaultDrawDistance in the [Startup] section of config
  1836. /// </param>
  1837. public void CompleteMovement(IClientAPI client, bool openChildAgents)
  1838. {
  1839. int ts = Util.EnvironmentTickCount();
  1840. m_log.InfoFormat(
  1841. "[SCENE PRESENCE]: Completing movement of {0} into region {1} in position {2}",
  1842. client.Name, Scene.Name, AbsolutePosition);
  1843. m_inTransit = true;
  1844. try
  1845. {
  1846. // Make sure it's not a login agent. We don't want to wait for updates during login
  1847. if (!IsNPC && !IsRealLogin(m_teleportFlags))
  1848. {
  1849. // Let's wait until UpdateAgent (called by departing region) is done
  1850. if (!WaitForUpdateAgent(client))
  1851. // The sending region never sent the UpdateAgent data, we have to refuse
  1852. return;
  1853. }
  1854. //m_log.DebugFormat("[CompleteMovement] WaitForUpdateAgent: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1855. bool flying = ((m_AgentControlFlags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  1856. Vector3 look = Lookat;
  1857. look.Z = 0f;
  1858. if ((Math.Abs(look.X) < 0.01) && (Math.Abs(look.Y) < 0.01))
  1859. {
  1860. look = Velocity;
  1861. look.Normalize();
  1862. if ((Math.Abs(look.X) < 0.01) && (Math.Abs(look.Y) < 0.01) )
  1863. look = new Vector3(0.99f, 0.042f, 0);
  1864. }
  1865. // Check Default Location (Also See EntityTransferModule.TeleportAgentWithinRegion)
  1866. if (AbsolutePosition.X == 128f && AbsolutePosition.Y == 128f && AbsolutePosition.Z == 22.5f)
  1867. AbsolutePosition = Scene.RegionInfo.DefaultLandingPoint;
  1868. if (!MakeRootAgent(AbsolutePosition, flying, ref look))
  1869. {
  1870. m_log.DebugFormat(
  1871. "[SCENE PRESENCE]: Aborting CompleteMovement call for {0} in {1} as they are already root",
  1872. Name, Scene.Name);
  1873. return;
  1874. }
  1875. if(IsChildAgent)
  1876. {
  1877. return; // how?
  1878. }
  1879. //m_log.DebugFormat("[CompleteMovement] MakeRootAgent: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1880. if (!IsNPC)
  1881. {
  1882. if (!m_haveGroupInformation)
  1883. {
  1884. IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  1885. if (gm != null)
  1886. Grouptitle = gm.GetGroupTitle(m_uuid);
  1887. //m_log.DebugFormat("[CompleteMovement] Missing Grouptitle: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1888. InventoryFolderBase cof = m_scene.InventoryService.GetFolderForType(client.AgentId, (FolderType)46);
  1889. if (cof == null)
  1890. COF = UUID.Zero;
  1891. else
  1892. COF = cof.ID;
  1893. m_log.DebugFormat("[CompleteMovement]: Missing COF for {0} is {1}", client.AgentId, COF);
  1894. }
  1895. }
  1896. if (m_teleportFlags > 0)
  1897. m_gotCrossUpdate = false; // sanity check
  1898. if (!m_gotCrossUpdate)
  1899. RotateToLookAt(look);
  1900. m_previusParcelHide = false;
  1901. m_previusParcelUUID = UUID.Zero;
  1902. m_currentParcelHide = false;
  1903. m_currentParcelUUID = UUID.Zero;
  1904. ParcelDwellTickMS = Util.GetTimeStampMS();
  1905. m_inTransit = false;
  1906. // Tell the client that we're ready to send rest
  1907. if (!m_gotCrossUpdate)
  1908. {
  1909. m_gotRegionHandShake = false; // allow it if not a crossing
  1910. ControllingClient.SendRegionHandshake();
  1911. }
  1912. ControllingClient.MoveAgentIntoRegion(m_scene.RegionInfo, AbsolutePosition, look);
  1913. bool isHGTP = (m_teleportFlags & TeleportFlags.ViaHGLogin) != 0;
  1914. if(!IsNPC)
  1915. {
  1916. if( ParentPart != null && (m_crossingFlags & 0x08) != 0)
  1917. {
  1918. ParentPart.ParentGroup.SendFullAnimUpdateToClient(ControllingClient);
  1919. }
  1920. // verify baked textures and cache
  1921. if (m_scene.AvatarFactory != null && !isHGTP)
  1922. {
  1923. if (!m_scene.AvatarFactory.ValidateBakedTextureCache(this))
  1924. m_scene.AvatarFactory.QueueAppearanceSave(UUID);
  1925. }
  1926. }
  1927. if(isHGTP)
  1928. {
  1929. // ControllingClient.SendNameReply(m_uuid, Firstname, Lastname);
  1930. m_log.DebugFormat("[CompleteMovement] HG");
  1931. }
  1932. if (!IsNPC)
  1933. {
  1934. GodController.SyncViewerState();
  1935. // start sending terrain patchs
  1936. if (!m_gotCrossUpdate)
  1937. Scene.SendLayerData(ControllingClient);
  1938. // send initial land overlay and parcel
  1939. ILandChannel landch = m_scene.LandChannel;
  1940. if (landch != null)
  1941. landch.sendClientInitialLandInfo(client, !m_gotCrossUpdate);
  1942. }
  1943. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  1944. // send avatar object to all presences including us, so they cross it into region
  1945. // then hide if necessary
  1946. SendInitialAvatarDataToAllAgents(allpresences);
  1947. // send this look
  1948. if (!IsNPC)
  1949. SendAppearanceToAgent(this);
  1950. // send this animations
  1951. UUID[] animIDs = null;
  1952. int[] animseqs = null;
  1953. UUID[] animsobjs = null;
  1954. if (Animator != null)
  1955. Animator.GetArrays(out animIDs, out animseqs, out animsobjs);
  1956. bool haveAnims = (animIDs != null && animseqs != null && animsobjs != null);
  1957. if (!IsNPC && haveAnims)
  1958. SendAnimPackToAgent(this, animIDs, animseqs, animsobjs);
  1959. // send look and animations to others
  1960. // if not cached we send greys
  1961. // uncomented if will wait till avatar does baking
  1962. //if (cachedbaked)
  1963. {
  1964. foreach (ScenePresence p in allpresences)
  1965. {
  1966. if (p == this)
  1967. continue;
  1968. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  1969. continue;
  1970. SendAppearanceToAgentNF(p);
  1971. if (haveAnims)
  1972. SendAnimPackToAgentNF(p, animIDs, animseqs, animsobjs);
  1973. }
  1974. }
  1975. // attachments
  1976. if (IsNPC || IsRealLogin(m_teleportFlags))
  1977. {
  1978. if (Scene.AttachmentsModule != null)
  1979. {
  1980. if(IsNPC)
  1981. {
  1982. Util.FireAndForget(x =>
  1983. {
  1984. Scene.AttachmentsModule.RezAttachments(this);
  1985. });
  1986. }
  1987. else
  1988. Scene.AttachmentsModule.RezAttachments(this);
  1989. }
  1990. }
  1991. else
  1992. {
  1993. if (m_attachments.Count > 0)
  1994. {
  1995. foreach (SceneObjectGroup sog in m_attachments)
  1996. {
  1997. sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource());
  1998. sog.ResumeScripts();
  1999. }
  2000. foreach (ScenePresence p in allpresences)
  2001. {
  2002. if (p == this)
  2003. {
  2004. SendAttachmentsToAgentNF(this);
  2005. continue;
  2006. }
  2007. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  2008. continue;
  2009. SendAttachmentsToAgentNF(p);
  2010. }
  2011. }
  2012. }
  2013. if (!IsNPC)
  2014. {
  2015. if(m_gotCrossUpdate)
  2016. {
  2017. SendOtherAgentsAvatarFullToMe();
  2018. // Create child agents in neighbouring regions
  2019. IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
  2020. if (m_agentTransfer != null)
  2021. {
  2022. m_agentTransfer.EnableChildAgents(this);
  2023. }
  2024. m_lastChildUpdatesTime = Util.EnvironmentTickCount() + 10000;
  2025. m_lastChildAgentUpdatePosition = AbsolutePosition;
  2026. m_lastChildAgentCheckPosition = m_lastChildAgentUpdatePosition;
  2027. m_lastChildAgentUpdateDrawDistance = DrawDistance;
  2028. m_lastRegionsDrawDistance = RegionViewDistance;
  2029. m_lastChildAgentUpdateGodLevel = GodController.ViwerUIGodLevel;
  2030. m_childUpdatesBusy = false; // allow them
  2031. }
  2032. // send the rest of the world
  2033. //if (m_teleportFlags > 0 || m_currentParcelHide)
  2034. //SendInitialDataToMe();
  2035. //SendOtherAgentsAvatarFullToMe();
  2036. // priority uses avatar position only
  2037. // m_reprioritizationLastPosition = AbsolutePosition;
  2038. // m_reprioritizationLastDrawDistance = DrawDistance;
  2039. // m_reprioritizationLastTime = Util.EnvironmentTickCount() + 15000; // delay it
  2040. // m_reprioritizationBusy = false;
  2041. if (openChildAgents)
  2042. {
  2043. IFriendsModule friendsModule = m_scene.RequestModuleInterface<IFriendsModule>();
  2044. if (friendsModule != null)
  2045. {
  2046. if(m_gotCrossUpdate)
  2047. friendsModule.IsNowRoot(this);
  2048. else
  2049. friendsModule.SendFriendsOnlineIfNeeded(ControllingClient);
  2050. }
  2051. //m_log.DebugFormat("[CompleteMovement] friendsModule: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  2052. }
  2053. }
  2054. }
  2055. finally
  2056. {
  2057. m_haveGroupInformation = false;
  2058. m_gotCrossUpdate = false;
  2059. m_crossingFlags = 0;
  2060. m_inTransit = false;
  2061. }
  2062. m_scene.EventManager.OnRegionHeartbeatEnd += RegionHeartbeatEnd;
  2063. m_log.DebugFormat("[CompleteMovement] end: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  2064. }
  2065. /// <summary>
  2066. /// Callback for the Camera view block check. Gets called with the results of the camera view block test
  2067. /// hitYN is true when there's something in the way.
  2068. /// </summary>
  2069. /// <param name="hitYN"></param>
  2070. /// <param name="collisionPoint"></param>
  2071. /// <param name="localid"></param>
  2072. /// <param name="distance"></param>
  2073. ///
  2074. private void checkCameraCollision()
  2075. {
  2076. if(m_doingCamRayCast || !m_scene.PhysicsScene.SupportsRayCast())
  2077. return;
  2078. if(m_mouseLook || ParentID != 0)
  2079. {
  2080. if (CameraConstraintActive)
  2081. {
  2082. Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -10000f); // not right...
  2083. UpdateCameraCollisionPlane(plane);
  2084. CameraConstraintActive = false;
  2085. }
  2086. return;
  2087. }
  2088. Vector3 posAdjusted = AbsolutePosition;
  2089. posAdjusted.Z += 1.0f; // viewer current camera focus point
  2090. if(posAdjusted.ApproxEquals(m_lastCameraRayCastPos, 0.2f) &&
  2091. CameraPosition.ApproxEquals(m_lastCameraRayCastCam, 0.2f))
  2092. return;
  2093. m_lastCameraRayCastCam = CameraPosition;
  2094. m_lastCameraRayCastPos = posAdjusted;
  2095. Vector3 tocam = CameraPosition - posAdjusted;
  2096. float distTocamlen = tocam.LengthSquared();
  2097. if (distTocamlen > 0.01f && distTocamlen < 400)
  2098. {
  2099. distTocamlen = (float)Math.Sqrt(distTocamlen);
  2100. tocam *= (1.0f / distTocamlen);
  2101. m_doingCamRayCast = true;
  2102. m_scene.PhysicsScene.RaycastWorld(posAdjusted, tocam, distTocamlen + 1.0f, RayCastCameraCallback);
  2103. return;
  2104. }
  2105. if (CameraConstraintActive)
  2106. {
  2107. Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -10000f); // not right...
  2108. UpdateCameraCollisionPlane(plane);
  2109. CameraConstraintActive = false;
  2110. }
  2111. }
  2112. private void UpdateCameraCollisionPlane(Vector4 plane)
  2113. {
  2114. if (m_lastCameraCollisionPlane != plane)
  2115. {
  2116. m_lastCameraCollisionPlane = plane;
  2117. ControllingClient.SendCameraConstraint(plane);
  2118. }
  2119. }
  2120. public void RayCastCameraCallback(bool hitYN, Vector3 collisionPoint, uint localid, float distance, Vector3 pNormal)
  2121. {
  2122. if (hitYN && localid != LocalId)
  2123. {
  2124. if (localid != 0)
  2125. {
  2126. SceneObjectPart part = m_scene.GetSceneObjectPart(localid);
  2127. if (part != null && !part.VolumeDetectActive)
  2128. {
  2129. CameraConstraintActive = true;
  2130. pNormal.X = (float) Math.Round(pNormal.X, 2);
  2131. pNormal.Y = (float) Math.Round(pNormal.Y, 2);
  2132. pNormal.Z = (float) Math.Round(pNormal.Z, 2);
  2133. pNormal.Normalize();
  2134. collisionPoint.X = (float) Math.Round(collisionPoint.X, 1);
  2135. collisionPoint.Y = (float) Math.Round(collisionPoint.Y, 1);
  2136. collisionPoint.Z = (float) Math.Round(collisionPoint.Z, 1);
  2137. Vector4 plane = new Vector4(pNormal.X, pNormal.Y, pNormal.Z,
  2138. Vector3.Dot(collisionPoint, pNormal));
  2139. UpdateCameraCollisionPlane(plane);
  2140. }
  2141. }
  2142. else
  2143. {
  2144. CameraConstraintActive = true;
  2145. pNormal.X = (float) Math.Round(pNormal.X, 2);
  2146. pNormal.Y = (float) Math.Round(pNormal.Y, 2);
  2147. pNormal.Z = (float) Math.Round(pNormal.Z, 2);
  2148. pNormal.Normalize();
  2149. collisionPoint.X = (float) Math.Round(collisionPoint.X, 1);
  2150. collisionPoint.Y = (float) Math.Round(collisionPoint.Y, 1);
  2151. collisionPoint.Z = (float) Math.Round(collisionPoint.Z, 1);
  2152. Vector4 plane = new Vector4(pNormal.X, pNormal.Y, pNormal.Z,
  2153. Vector3.Dot(collisionPoint, pNormal));
  2154. UpdateCameraCollisionPlane(plane);
  2155. }
  2156. }
  2157. else if(CameraConstraintActive)
  2158. {
  2159. Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -9000f); // not right...
  2160. UpdateCameraCollisionPlane(plane);
  2161. CameraConstraintActive = false;
  2162. }
  2163. m_doingCamRayCast = false;
  2164. }
  2165. /// <summary>
  2166. /// This is the event handler for client movement. If a client is moving, this event is triggering.
  2167. /// </summary>
  2168. public void HandleAgentUpdate(IClientAPI remoteClient, AgentUpdateArgs agentData)
  2169. {
  2170. // m_log.DebugFormat(
  2171. // "[SCENE PRESENCE]: In {0} received agent update from {1}, flags {2}",
  2172. // Scene.Name, remoteClient.Name, (AgentManager.ControlFlags)agentData.ControlFlags);
  2173. if (IsChildAgent)
  2174. {
  2175. // m_log.DebugFormat("DEBUG: HandleAgentUpdate: child agent in {0}", Scene.Name);
  2176. return;
  2177. }
  2178. if (IsInTransit)
  2179. return;
  2180. #region Sanity Checking
  2181. // This is irritating. Really.
  2182. if (!AbsolutePosition.IsFinite())
  2183. {
  2184. bool isphysical = PhysicsActor != null;
  2185. if(isphysical)
  2186. RemoveFromPhysicalScene();
  2187. m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error #9999902");
  2188. m_pos = m_LastFinitePos;
  2189. if (!m_pos.IsFinite())
  2190. {
  2191. m_pos.X = 127f;
  2192. m_pos.Y = 127f;
  2193. m_pos.Z = 127f;
  2194. m_log.Error("[AVATAR]: NonFinite Avatar on lastFiniteposition also. Reset Position. Mantis this please. Error #9999903");
  2195. }
  2196. if(isphysical)
  2197. AddToPhysicalScene(false);
  2198. }
  2199. else
  2200. {
  2201. m_LastFinitePos = m_pos;
  2202. }
  2203. #endregion Sanity Checking
  2204. #region Inputs
  2205. AgentManager.ControlFlags flags = (AgentManager.ControlFlags)agentData.ControlFlags;
  2206. // The Agent's Draw distance setting
  2207. // When we get to the point of re-computing neighbors everytime this
  2208. // changes, then start using the agent's drawdistance rather than the
  2209. // region's draw distance.
  2210. DrawDistance = agentData.Far;
  2211. m_mouseLook = (flags & AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) != 0;
  2212. // FIXME: This does not work as intended because the viewer only sends the lbutton down when the button
  2213. // is first pressed, not whilst it is held down. If this is required in the future then need to look
  2214. // for an AGENT_CONTROL_LBUTTON_UP event and make sure to handle cases where an initial DOWN is not
  2215. // received (e.g. on holding LMB down on the avatar in a viewer).
  2216. m_leftButtonDown = (flags & AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0;
  2217. #endregion Inputs
  2218. // // Make anims work for client side autopilot
  2219. // if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0)
  2220. // m_updateCount = UPDATE_COUNT;
  2221. //
  2222. // // Make turning in place work
  2223. // if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0 ||
  2224. // (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  2225. // m_updateCount = UPDATE_COUNT;
  2226. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP) != 0)
  2227. {
  2228. StandUp();
  2229. }
  2230. // Raycast from the avatar's head to the camera to see if there's anything blocking the view
  2231. // this exclude checks may not be complete
  2232. if(agentData.NeedsCameraCollision) // condition parentID may be wrong
  2233. checkCameraCollision();
  2234. uint flagsForScripts = (uint)flags;
  2235. flags = RemoveIgnoredControls(flags, IgnoredControls);
  2236. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND) != 0)
  2237. HandleAgentSitOnGround();
  2238. // In the future, these values might need to go global.
  2239. // Here's where you get them.
  2240. m_AgentControlFlags = flags;
  2241. m_headrotation = agentData.HeadRotation;
  2242. byte oldState = State;
  2243. State = agentData.State;
  2244. // We need to send this back to the client in order to stop the edit beams
  2245. if ((oldState & (uint)AgentState.Editing) != 0 && State == (uint)AgentState.None)
  2246. SendAgentTerseUpdate(this);
  2247. PhysicsActor actor = PhysicsActor;
  2248. // This will be the case if the agent is sitting on the groudn or on an object.
  2249. if (actor == null)
  2250. {
  2251. SendControlsToScripts(flagsForScripts);
  2252. return;
  2253. }
  2254. if (AllowMovement && !SitGround)
  2255. {
  2256. // m_log.DebugFormat("[SCENE PRESENCE]: Initial body rotation {0} for {1}", agentData.BodyRotation, Name);
  2257. bool update_rotation = false;
  2258. if (agentData.BodyRotation != Rotation)
  2259. {
  2260. Rotation = agentData.BodyRotation;
  2261. update_rotation = true;
  2262. }
  2263. bool update_movementflag = false;
  2264. bool mvToTarget = m_movingToTarget;
  2265. if (agentData.UseClientAgentPosition)
  2266. {
  2267. m_movingToTarget = (agentData.ClientAgentPosition - AbsolutePosition).LengthSquared() > 0.04f;
  2268. m_moveToPositionTarget = agentData.ClientAgentPosition;
  2269. m_moveToSpeed = -1f;
  2270. }
  2271. int i = 0;
  2272. bool DCFlagKeyPressed = false;
  2273. Vector3 agent_control_v3 = Vector3.Zero;
  2274. bool newFlying = false;
  2275. if (ForceFly)
  2276. newFlying = true;
  2277. else if (FlyDisabled)
  2278. newFlying = false;
  2279. else if(mvToTarget)
  2280. newFlying = actor.Flying;
  2281. else
  2282. newFlying = ((flags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  2283. if (actor.Flying != newFlying)
  2284. {
  2285. // Note: ScenePresence.Flying is actually fetched from the physical actor
  2286. // so setting PhysActor.Flying here also sets the ScenePresence's value.
  2287. actor.Flying = newFlying;
  2288. update_movementflag = true;
  2289. }
  2290. if (ParentID == 0)
  2291. {
  2292. bool bAllowUpdateMoveToPosition = false;
  2293. Vector3[] dirVectors;
  2294. // use camera up angle when in mouselook and not flying or when holding the left mouse button down and not flying
  2295. // this prevents 'jumping' in inappropriate situations.
  2296. // if (!Flying && (m_mouseLook || m_leftButtonDown))
  2297. // dirVectors = GetWalkDirectionVectors();
  2298. // else
  2299. dirVectors = Dir_Vectors;
  2300. // A DIR_CONTROL_FLAG occurs when the user is trying to move in a particular direction.
  2301. foreach (Dir_ControlFlags DCF in DIR_CONTROL_FLAGS)
  2302. {
  2303. if (((uint)flags & (uint)DCF) != 0)
  2304. {
  2305. DCFlagKeyPressed = true;
  2306. try
  2307. {
  2308. agent_control_v3 += Dir_Vectors[i];
  2309. //m_log.DebugFormat("[Motion]: {0}, {1}",i, dirVectors[i]);
  2310. }
  2311. catch (IndexOutOfRangeException)
  2312. {
  2313. // Why did I get this?
  2314. }
  2315. if (((MovementFlag & (uint)DCF) == 0))
  2316. {
  2317. //m_log.DebugFormat("[SCENE PRESENCE]: Updating MovementFlag for {0} with {1}", Name, DCF);
  2318. MovementFlag |= (uint)DCF;
  2319. update_movementflag = true;
  2320. }
  2321. }
  2322. else
  2323. {
  2324. if ((MovementFlag & (uint)DCF) != 0)
  2325. {
  2326. //m_log.DebugFormat("[SCENE PRESENCE]: Updating MovementFlag for {0} with lack of {1}", Name, DCF);
  2327. MovementFlag &= (uint)~DCF;
  2328. update_movementflag = true;
  2329. /*
  2330. if ((DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD_NUDGE || DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_BACKWARD_NUDGE)
  2331. && ((MovementFlag & (byte)nudgehack) == nudgehack))
  2332. {
  2333. m_log.Debug("Removed Hack flag");
  2334. }
  2335. */
  2336. }
  2337. else
  2338. {
  2339. bAllowUpdateMoveToPosition = true;
  2340. }
  2341. }
  2342. i++;
  2343. }
  2344. // Detect AGENT_CONTROL_STOP state changes
  2345. if (AgentControlStopActive != ((flags & AgentManager.ControlFlags.AGENT_CONTROL_STOP) != 0))
  2346. {
  2347. AgentControlStopActive = !AgentControlStopActive;
  2348. update_movementflag = true;
  2349. }
  2350. if (m_movingToTarget)
  2351. {
  2352. // If the user has pressed a key then we want to cancel any move to target.
  2353. if (DCFlagKeyPressed)
  2354. {
  2355. ResetMoveToTarget();
  2356. update_movementflag = true;
  2357. }
  2358. else if (bAllowUpdateMoveToPosition)
  2359. {
  2360. // The UseClientAgentPosition is set if parcel ban is forcing the avatar to move to a
  2361. // certain position. It's only check for tolerance on returning to that position is 0.2
  2362. // rather than 1, at which point it removes its force target.
  2363. if (HandleMoveToTargetUpdate(agentData.UseClientAgentPosition ? 0.2f : 1f, ref agent_control_v3))
  2364. update_movementflag = true;
  2365. }
  2366. }
  2367. }
  2368. // Cause the avatar to stop flying if it's colliding
  2369. // with something with the down arrow pressed.
  2370. // Only do this if we're flying
  2371. if (Flying && !ForceFly)
  2372. {
  2373. // Need to stop in mid air if user holds down AGENT_CONTROL_STOP
  2374. // if (AgentControlStopActive)
  2375. // {
  2376. // agent_control_v3 = Vector3.Zero;
  2377. // }
  2378. // else
  2379. {
  2380. // Landing detection code
  2381. // Are the landing controls requirements filled?
  2382. bool controlland = (((flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) ||
  2383. ((flags & AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0));
  2384. //m_log.Debug("[CONTROL]: " +flags);
  2385. // Applies a satisfying roll effect to the avatar when flying.
  2386. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT) != 0 && (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0)
  2387. {
  2388. ApplyFlyingRoll(
  2389. FLY_ROLL_RADIANS_PER_UPDATE,
  2390. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0,
  2391. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0);
  2392. }
  2393. else if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT) != 0 &&
  2394. (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  2395. {
  2396. ApplyFlyingRoll(
  2397. -FLY_ROLL_RADIANS_PER_UPDATE,
  2398. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0,
  2399. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0);
  2400. }
  2401. else
  2402. {
  2403. if (m_AngularVelocity.Z != 0)
  2404. m_AngularVelocity.Z += CalculateFlyingRollResetToZero(FLY_ROLL_RESET_RADIANS_PER_UPDATE);
  2405. }
  2406. /*
  2407. if (Flying && IsColliding && controlland)
  2408. {
  2409. // nesting this check because LengthSquared() is expensive and we don't
  2410. // want to do it every step when flying.
  2411. if ((Velocity.LengthSquared() <= LAND_VELOCITYMAG_MAX))
  2412. StopFlying();
  2413. }
  2414. */
  2415. }
  2416. }
  2417. else if (IsColliding && agent_control_v3.Z < 0f)
  2418. agent_control_v3.Z = 0;
  2419. // else if(AgentControlStopActive %% Velocity.Z <0.01f)
  2420. // m_log.DebugFormat("[SCENE PRESENCE]: MovementFlag {0} for {1}", MovementFlag, Name);
  2421. // If the agent update does move the avatar, then calculate the force ready for the velocity update,
  2422. // which occurs later in the main scene loop
  2423. // We also need to update if the user rotates their avatar whilst it is slow walking/running (if they
  2424. // held down AGENT_CONTROL_STOP whilst normal walking/running). However, we do not want to update
  2425. // if the user rotated whilst holding down AGENT_CONTROL_STOP when already still (which locks the
  2426. // avatar location in place).
  2427. if (update_movementflag
  2428. || (update_rotation && DCFlagKeyPressed && (!AgentControlStopActive || MovementFlag != 0)))
  2429. {
  2430. if (AgentControlStopActive)
  2431. {
  2432. // if (MovementFlag == 0 && Animator.Falling)
  2433. if (MovementFlag == 0 && Animator.currentControlState == ScenePresenceAnimator.motionControlStates.falling)
  2434. {
  2435. AddNewMovement(agent_control_v3, AgentControlStopSlowVel, true);
  2436. }
  2437. else
  2438. AddNewMovement(agent_control_v3, AgentControlStopSlowVel);
  2439. }
  2440. else
  2441. {
  2442. if(m_movingToTarget ||
  2443. (Animator.currentControlState != ScenePresenceAnimator.motionControlStates.flying &&
  2444. Animator.currentControlState != ScenePresenceAnimator.motionControlStates.onsurface)
  2445. )
  2446. AddNewMovement(agent_control_v3);
  2447. else
  2448. {
  2449. if (MovementFlag != 0)
  2450. AddNewMovement(agent_control_v3);
  2451. else
  2452. m_delayedStop = Util.GetTimeStampMS() + 200.0;
  2453. }
  2454. }
  2455. }
  2456. /*
  2457. if (update_movementflag && ParentID == 0 && m_delayedStop < 0)
  2458. {
  2459. // m_log.DebugFormat("[SCENE PRESENCE]: Updating movement animations for {0}", Name);
  2460. Animator.UpdateMovementAnimations();
  2461. }
  2462. */
  2463. SendControlsToScripts(flagsForScripts);
  2464. }
  2465. // We need to send this back to the client in order to see the edit beams
  2466. if ((State & (uint)AgentState.Editing) != 0)
  2467. SendAgentTerseUpdate(this);
  2468. // m_scene.EventManager.TriggerOnClientMovement(this);
  2469. }
  2470. private void HandleAgentFOV(IClientAPI remoteClient, float _fov)
  2471. {
  2472. m_FOV = _fov;
  2473. }
  2474. /// <summary>
  2475. /// This is the event handler for client cameras. If a client is moving, or moving the camera, this event is triggering.
  2476. /// </summary>
  2477. private void HandleAgentCamerasUpdate(IClientAPI remoteClient, AgentUpdateArgs agentData)
  2478. {
  2479. //m_log.DebugFormat(
  2480. // "[SCENE PRESENCE]: In {0} received agent camera update from {1}, flags {2}",
  2481. // Scene.RegionInfo.RegionName, remoteClient.Name, (AgentManager.ControlFlags)agentData.ControlFlags);
  2482. if (IsChildAgent)
  2483. return;
  2484. if(IsInTransit)
  2485. return;
  2486. // AgentManager.ControlFlags flags = (AgentManager.ControlFlags)agentData.ControlFlags;
  2487. // Camera location in world. We'll need to raytrace
  2488. // from this location from time to time.
  2489. CameraPosition = agentData.CameraCenter;
  2490. // Use these three vectors to figure out what the agent is looking at
  2491. // Convert it to a Matrix and/or Quaternion
  2492. // this may need lock
  2493. CameraAtAxis = agentData.CameraAtAxis;
  2494. CameraLeftAxis = agentData.CameraLeftAxis;
  2495. CameraUpAxis = agentData.CameraUpAxis;
  2496. DrawDistance = agentData.Far;
  2497. CameraAtAxis.Normalize();
  2498. CameraLeftAxis.Normalize();
  2499. CameraUpAxis.Normalize();
  2500. Quaternion camRot = Util.Axes2Rot(CameraAtAxis, CameraLeftAxis, CameraUpAxis);
  2501. CameraRotation = camRot;
  2502. if(agentData.NeedsCameraCollision)
  2503. checkCameraCollision();
  2504. TriggerScenePresenceUpdated();
  2505. }
  2506. /// <summary>
  2507. /// Calculate an update to move the presence to the set target.
  2508. /// </summary>
  2509. /// <remarks>
  2510. /// This doesn't actually perform the movement. Instead, it adds its vector to agent_control_v3.
  2511. /// </remarks>
  2512. /// <param value="agent_control_v3">Cumulative agent movement that this method will update.</param>
  2513. /// <returns>True if movement has been updated in some way. False otherwise.</returns>
  2514. public bool HandleMoveToTargetUpdate(float tolerance, ref Vector3 agent_control_v3)
  2515. {
  2516. // m_log.DebugFormat("[SCENE PRESENCE]: Called HandleMoveToTargetUpdate() for {0}", Name);
  2517. bool updated = false;
  2518. Vector3 LocalVectorToTarget3D = m_moveToPositionTarget - AbsolutePosition;
  2519. // m_log.DebugFormat(
  2520. // "[SCENE PRESENCE]: bAllowUpdateMoveToPosition {0}, m_moveToPositionInProgress {1}, m_autopilotMoving {2}",
  2521. // allowUpdate, m_moveToPositionInProgress, m_autopilotMoving);
  2522. float distanceToTarget;
  2523. if(Flying && !LandAtTarget)
  2524. distanceToTarget = LocalVectorToTarget3D.LengthSquared();
  2525. else
  2526. distanceToTarget = (LocalVectorToTarget3D.X * LocalVectorToTarget3D.X) + (LocalVectorToTarget3D.Y * LocalVectorToTarget3D.Y);
  2527. // m_log.DebugFormat(
  2528. // "[SCENE PRESENCE]: Abs pos of {0} is {1}, target {2}, distance {3}",
  2529. // Name, AbsolutePosition, MoveToPositionTarget, distanceToTarget);
  2530. // Check the error term of the current position in relation to the target position
  2531. if (distanceToTarget <= tolerance * tolerance)
  2532. {
  2533. // We are close enough to the target
  2534. Velocity = Vector3.Zero;
  2535. AbsolutePosition = m_moveToPositionTarget;
  2536. if (Flying)
  2537. {
  2538. if (LandAtTarget)
  2539. Flying = false;
  2540. // A horrible hack to stop the avatar dead in its tracks rather than having them overshoot
  2541. // the target if flying.
  2542. // We really need to be more subtle (slow the avatar as it approaches the target) or at
  2543. // least be able to set collision status once, rather than 5 times to give it enough
  2544. // weighting so that that PhysicsActor thinks it really is colliding.
  2545. for (int i = 0; i < 5; i++)
  2546. IsColliding = true;
  2547. }
  2548. ResetMoveToTarget();
  2549. return false;
  2550. }
  2551. if (m_moveToSpeed > 0 &&
  2552. distanceToTarget <= m_moveToSpeed * m_moveToSpeed * Scene.FrameTime * Scene.FrameTime)
  2553. m_moveToSpeed = (float)Math.Sqrt(distanceToTarget) / Scene.FrameTime;
  2554. try
  2555. {
  2556. // move avatar in 3D towards target, in avatar coordinate frame.
  2557. // This movement vector gets added to the velocity through AddNewMovement().
  2558. // Theoretically we might need a more complex PID approach here if other
  2559. // unknown forces are acting on the avatar and we need to adaptively respond
  2560. // to such forces, but the following simple approach seems to works fine.
  2561. float angle = 0.5f * (float)Math.Atan2(LocalVectorToTarget3D.Y, LocalVectorToTarget3D.X);
  2562. Quaternion rot = new Quaternion(0,0, (float)Math.Sin(angle),(float)Math.Cos(angle));
  2563. Rotation = rot;
  2564. LocalVectorToTarget3D = LocalVectorToTarget3D * Quaternion.Inverse(rot); // change to avatar coords
  2565. LocalVectorToTarget3D.Normalize();
  2566. // update avatar movement flags. the avatar coordinate system is as follows:
  2567. //
  2568. // +X (forward)
  2569. //
  2570. // ^
  2571. // |
  2572. // |
  2573. // |
  2574. // |
  2575. // (left) +Y <--------o--------> -Y
  2576. // avatar
  2577. // |
  2578. // |
  2579. // |
  2580. // |
  2581. // v
  2582. // -X
  2583. //
  2584. // based on the above avatar coordinate system, classify the movement into
  2585. // one of left/right/back/forward.
  2586. const uint noMovFlagsMask = (uint)(~(Dir_ControlFlags.DIR_CONTROL_FLAG_BACK |
  2587. Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD | Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT |
  2588. Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT | Dir_ControlFlags.DIR_CONTROL_FLAG_UP |
  2589. Dir_ControlFlags.DIR_CONTROL_FLAG_DOWN));
  2590. MovementFlag &= noMovFlagsMask;
  2591. uint tmpAgentControlFlags = (uint)m_AgentControlFlags;
  2592. tmpAgentControlFlags &= noMovFlagsMask;
  2593. if (LocalVectorToTarget3D.X < 0) //MoveBack
  2594. {
  2595. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
  2596. tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
  2597. updated = true;
  2598. }
  2599. else if (LocalVectorToTarget3D.X > 0) //Move Forward
  2600. {
  2601. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
  2602. tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
  2603. updated = true;
  2604. }
  2605. if (LocalVectorToTarget3D.Y > 0) //MoveLeft
  2606. {
  2607. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
  2608. tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
  2609. updated = true;
  2610. }
  2611. else if (LocalVectorToTarget3D.Y < 0) //MoveRight
  2612. {
  2613. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
  2614. tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
  2615. updated = true;
  2616. }
  2617. if (LocalVectorToTarget3D.Z > 0) //Up
  2618. updated = true;
  2619. else if (LocalVectorToTarget3D.Z < 0) //Down
  2620. updated = true;
  2621. // m_log.DebugFormat(
  2622. // "[SCENE PRESENCE]: HandleMoveToTargetUpdate adding {0} to move vector {1} for {2}",
  2623. // LocalVectorToTarget3D, agent_control_v3, Name);
  2624. m_AgentControlFlags = (AgentManager.ControlFlags) tmpAgentControlFlags;
  2625. if(updated)
  2626. agent_control_v3 += LocalVectorToTarget3D;
  2627. }
  2628. catch (Exception e)
  2629. {
  2630. //Avoid system crash, can be slower but...
  2631. m_log.DebugFormat("Crash! {0}", e.ToString());
  2632. }
  2633. return updated;
  2634. // AddNewMovement(agent_control_v3);
  2635. }
  2636. public void MoveToTargetHandle(Vector3 pos, bool noFly, bool landAtTarget)
  2637. {
  2638. MoveToTarget(pos, noFly, landAtTarget);
  2639. }
  2640. /// <summary>
  2641. /// Move to the given target over time.
  2642. /// </summary>
  2643. /// <param name="pos"></param>
  2644. /// <param name="noFly">
  2645. /// If true, then don't allow the avatar to fly to the target, even if it's up in the air.
  2646. /// This is to allow movement to targets that are known to be on an elevated platform with a continuous path
  2647. /// from start to finish.
  2648. /// </param>
  2649. /// <param name="landAtTarget">
  2650. /// If true and the avatar starts flying during the move then land at the target.
  2651. /// </param>
  2652. public void MoveToTarget(Vector3 pos, bool noFly, bool landAtTarget, float tau = -1f)
  2653. {
  2654. m_delayedStop = -1;
  2655. if (SitGround || IsSatOnObject)
  2656. StandUp();
  2657. // m_log.DebugFormat(
  2658. // "[SCENE PRESENCE]: Avatar {0} received request to move to position {1} in {2}",
  2659. // Name, pos, m_scene.RegionInfo.RegionName);
  2660. // Allow move to another sub-region within a megaregion
  2661. Vector2 regionSize;
  2662. regionSize = new Vector2(m_scene.RegionInfo.RegionSizeX, m_scene.RegionInfo.RegionSizeY);
  2663. if (pos.X < 0.5f)
  2664. pos.X = 0.5f;
  2665. else if (pos.X > regionSize.X - 0.5f)
  2666. pos.X = regionSize.X - 0.5f;
  2667. if (pos.Y < 0.5f)
  2668. pos.Y = 0.5f;
  2669. else if (pos.Y > regionSize.Y - 0.5f)
  2670. pos.Y = regionSize.Y - 0.5f;
  2671. float terrainHeight;
  2672. Scene targetScene = m_scene;
  2673. terrainHeight = m_scene.GetGroundHeight(pos.X, pos.Y);
  2674. // dont try to land underground
  2675. terrainHeight += Appearance.AvatarHeight * 0.5f + 0.2f;
  2676. if(terrainHeight > pos.Z)
  2677. pos.Z = terrainHeight;
  2678. // m_log.DebugFormat(
  2679. // "[SCENE PRESENCE]: Avatar {0} set move to target {1} (terrain height {2}) in {3}",
  2680. // Name, pos, terrainHeight, m_scene.RegionInfo.RegionName);
  2681. terrainHeight += Appearance.AvatarHeight; // so 1.5 * AvatarHeight above ground at target
  2682. bool shouldfly = Flying;
  2683. if (noFly)
  2684. shouldfly = false;
  2685. else if (pos.Z > terrainHeight || Flying)
  2686. shouldfly = true;
  2687. Vector3 localVectorToTarget3D = pos - AbsolutePosition;
  2688. // m_log.DebugFormat("[SCENE PRESENCE]: Local vector to target is {0},[1}", localVectorToTarget3D.X,localVectorToTarget3D.Y);
  2689. m_movingToTarget = true;
  2690. LandAtTarget = landAtTarget;
  2691. m_moveToPositionTarget = pos;
  2692. if(tau > 0)
  2693. {
  2694. if(tau < Scene.FrameTime)
  2695. tau = Scene.FrameTime;
  2696. m_moveToSpeed = localVectorToTarget3D.Length() / tau;
  2697. if(m_moveToSpeed < 0.5f) //to tune
  2698. m_moveToSpeed = 0.5f;
  2699. else if(m_moveToSpeed > 50f)
  2700. m_moveToSpeed = 50f;
  2701. SetAlwaysRun = false;
  2702. }
  2703. else
  2704. m_moveToSpeed = 4.096f * m_speedModifier;
  2705. Flying = shouldfly;
  2706. Vector3 control = Vector3.Zero;
  2707. if(HandleMoveToTargetUpdate(1f, ref control))
  2708. AddNewMovement(control);
  2709. }
  2710. /// <summary>
  2711. /// Reset the move to target.
  2712. /// </summary>
  2713. public void ResetMoveToTarget()
  2714. {
  2715. // m_log.DebugFormat("[SCENE PRESENCE]: Resetting move to target for {0}", Name);
  2716. m_movingToTarget = false;
  2717. m_moveToSpeed = -1f;
  2718. // MoveToPositionTarget = Vector3.Zero;
  2719. // lock(m_forceToApplyLock)
  2720. // m_forceToApplyValid = false; // cancel possible last action
  2721. // We need to reset the control flag as the ScenePresenceAnimator uses this to determine the correct
  2722. // resting animation (e.g. hover or stand). NPCs don't have a client that will quickly reset this flag.
  2723. // However, the line is here rather than in the NPC module since it also appears necessary to stop a
  2724. // viewer that uses "go here" from juddering on all subsequent avatar movements.
  2725. AgentControlFlags = (uint)AgentManager.ControlFlags.NONE;
  2726. }
  2727. /// <summary>
  2728. /// Perform the logic necessary to stand the avatar up. This method also executes
  2729. /// the stand animation.
  2730. /// </summary>
  2731. public void StandUp()
  2732. {
  2733. // m_log.DebugFormat("[SCENE PRESENCE]: StandUp() for {0}", Name);
  2734. bool satOnObject = IsSatOnObject;
  2735. SceneObjectPart part = ParentPart;
  2736. SitGround = false;
  2737. if (satOnObject)
  2738. {
  2739. PrevSitOffset = m_pos; // Save sit offset
  2740. UnRegisterSeatControls(part.ParentGroup.UUID);
  2741. TaskInventoryDictionary taskIDict = part.TaskInventory;
  2742. if (taskIDict != null)
  2743. {
  2744. lock (taskIDict)
  2745. {
  2746. foreach (UUID taskID in taskIDict.Keys)
  2747. {
  2748. UnRegisterControlEventsToScript(LocalId, taskID);
  2749. taskIDict[taskID].PermsMask &= ~(
  2750. 2048 | //PERMISSION_CONTROL_CAMERA
  2751. 4); // PERMISSION_TAKE_CONTROLS
  2752. }
  2753. }
  2754. }
  2755. // part.ParentGroup.DeleteAvatar(UUID);
  2756. Quaternion standRotation = part.ParentGroup.RootPart.RotationOffset;
  2757. Vector3 sitPartWorldPosition = part.ParentGroup.AbsolutePosition + m_pos * standRotation;
  2758. ControllingClient.SendClearFollowCamProperties(part.ParentUUID);
  2759. ParentID = 0;
  2760. ParentPart = null;
  2761. if (part.SitTargetAvatar == UUID)
  2762. standRotation = standRotation * part.SitTargetOrientation;
  2763. else
  2764. standRotation = standRotation * m_bodyRot;
  2765. m_bodyRot = standRotation;
  2766. Quaternion standRotationZ = new Quaternion(0,0,standRotation.Z,standRotation.W);
  2767. float t = standRotationZ.W * standRotationZ.W + standRotationZ.Z * standRotationZ.Z;
  2768. if (t > 0)
  2769. {
  2770. t = 1.0f / (float)Math.Sqrt(t);
  2771. standRotationZ.W *= t;
  2772. standRotationZ.Z *= t;
  2773. }
  2774. else
  2775. {
  2776. standRotationZ.W = 1.0f;
  2777. standRotationZ.Z = 0f;
  2778. }
  2779. Vector3 adjustmentForSitPose = new Vector3(0.75f, 0, m_sitAvatarHeight + .3f) * standRotationZ;
  2780. Vector3 standPos = sitPartWorldPosition + adjustmentForSitPose;
  2781. m_pos = standPos;
  2782. }
  2783. // We need to wait until we have calculated proper stand positions before sitting up the physical
  2784. // avatar to avoid race conditions.
  2785. if (PhysicsActor == null)
  2786. AddToPhysicalScene(false);
  2787. if (satOnObject)
  2788. {
  2789. m_requestedSitTargetID = 0;
  2790. part.RemoveSittingAvatar(this);
  2791. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  2792. SendAvatarDataToAllAgents();
  2793. m_scene.EventManager.TriggerParcelPrimCountTainted(); // update select/ sat on
  2794. }
  2795. // reset to default sitAnimation
  2796. sitAnimation = "SIT";
  2797. // Animator.TrySetMovementAnimation("STAND");
  2798. Animator.SetMovementAnimations("STAND");
  2799. TriggerScenePresenceUpdated();
  2800. }
  2801. private SceneObjectPart FindNextAvailableSitTarget(UUID targetID)
  2802. {
  2803. SceneObjectPart targetPart = m_scene.GetSceneObjectPart(targetID);
  2804. if (targetPart == null)
  2805. return null;
  2806. // If the primitive the player clicked on has a sit target and that sit target is not full, that sit target is used.
  2807. // 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.
  2808. // Get our own copy of the part array, and sort into the order we want to test
  2809. SceneObjectPart[] partArray = targetPart.ParentGroup.Parts;
  2810. Array.Sort(partArray, delegate(SceneObjectPart p1, SceneObjectPart p2)
  2811. {
  2812. // we want the originally selected part first, then the rest in link order -- so make the selected part link num (-1)
  2813. int linkNum1 = p1==targetPart ? -1 : p1.LinkNum;
  2814. int linkNum2 = p2==targetPart ? -1 : p2.LinkNum;
  2815. return linkNum1 - linkNum2;
  2816. }
  2817. );
  2818. //look for prims with explicit sit targets that are available
  2819. foreach (SceneObjectPart part in partArray)
  2820. {
  2821. if (part.IsSitTargetSet && part.SitTargetAvatar == UUID.Zero)
  2822. {
  2823. //switch the target to this prim
  2824. return part;
  2825. }
  2826. }
  2827. // no explicit sit target found - use original target
  2828. return targetPart;
  2829. }
  2830. private void SendSitResponse(UUID targetID, Vector3 offset, Quaternion sitOrientation)
  2831. {
  2832. Vector3 cameraEyeOffset = Vector3.Zero;
  2833. Vector3 cameraAtOffset = Vector3.Zero;
  2834. bool forceMouselook = false;
  2835. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  2836. if (part == null)
  2837. return;
  2838. if (PhysicsActor != null)
  2839. m_sitAvatarHeight = PhysicsActor.Size.Z * 0.5f;
  2840. bool canSit = false;
  2841. if (part.IsSitTargetSet && part.SitTargetAvatar == UUID.Zero)
  2842. {
  2843. offset = part.SitTargetPosition;
  2844. sitOrientation = part.SitTargetOrientation;
  2845. canSit = true;
  2846. }
  2847. else
  2848. {
  2849. if (PhysicsSit(part,offset)) // physics engine
  2850. return;
  2851. Vector3 pos = part.AbsolutePosition + offset;
  2852. if (Util.GetDistanceTo(AbsolutePosition, pos) <= 10)
  2853. {
  2854. AbsolutePosition = pos + new Vector3(0.0f, 0.0f, m_sitAvatarHeight);
  2855. canSit = true;
  2856. }
  2857. }
  2858. if (canSit)
  2859. {
  2860. if (PhysicsActor != null)
  2861. {
  2862. // We can remove the physicsActor until they stand up.
  2863. RemoveFromPhysicalScene();
  2864. }
  2865. if (m_movingToTarget)
  2866. ResetMoveToTarget();
  2867. Velocity = Vector3.Zero;
  2868. m_AngularVelocity = Vector3.Zero;
  2869. part.AddSittingAvatar(this);
  2870. cameraAtOffset = part.GetCameraAtOffset();
  2871. cameraEyeOffset = part.GetCameraEyeOffset();
  2872. forceMouselook = part.GetForceMouselook();
  2873. if (!part.IsRoot)
  2874. {
  2875. sitOrientation = part.RotationOffset * sitOrientation;
  2876. offset = offset * part.RotationOffset;
  2877. offset += part.OffsetPosition;
  2878. if (cameraAtOffset == Vector3.Zero && cameraEyeOffset == Vector3.Zero)
  2879. {
  2880. cameraAtOffset = part.ParentGroup.RootPart.GetCameraAtOffset();
  2881. cameraEyeOffset = part.ParentGroup.RootPart.GetCameraEyeOffset();
  2882. }
  2883. else
  2884. {
  2885. cameraAtOffset = cameraAtOffset * part.RotationOffset;
  2886. cameraAtOffset += part.OffsetPosition;
  2887. cameraEyeOffset = cameraEyeOffset * part.RotationOffset;
  2888. cameraEyeOffset += part.OffsetPosition;
  2889. }
  2890. }
  2891. ControllingClient.SendSitResponse(
  2892. part.ParentGroup.UUID, offset, sitOrientation, false, cameraAtOffset, cameraEyeOffset, forceMouselook);
  2893. m_requestedSitTargetUUID = part.UUID;
  2894. HandleAgentSit(ControllingClient, UUID);
  2895. // Moved here to avoid a race with default sit anim
  2896. // The script event needs to be raised after the default sit anim is set.
  2897. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  2898. m_scene.EventManager.TriggerParcelPrimCountTainted(); // update select/ sat on
  2899. }
  2900. }
  2901. public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset)
  2902. {
  2903. if (IsChildAgent)
  2904. return;
  2905. if (ParentID != 0)
  2906. {
  2907. if (ParentPart.UUID == targetID)
  2908. return; // already sitting here, ignore
  2909. StandUp();
  2910. }
  2911. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  2912. if (part != null)
  2913. {
  2914. m_requestedSitTargetID = part.LocalId;
  2915. m_requestedSitTargetUUID = part.UUID;
  2916. }
  2917. else
  2918. {
  2919. m_log.Warn("Sit requested on unknown object: " + targetID.ToString());
  2920. }
  2921. SendSitResponse(targetID, offset, Quaternion.Identity);
  2922. }
  2923. // returns false if does not suport so older sit can be tried
  2924. public bool PhysicsSit(SceneObjectPart part, Vector3 offset)
  2925. {
  2926. if (part == null || part.ParentGroup.IsAttachment)
  2927. return true;
  2928. if ( m_scene.PhysicsScene == null)
  2929. return false;
  2930. if (part.PhysActor == null)
  2931. {
  2932. // none physcis shape
  2933. if (part.PhysicsShapeType == (byte)PhysicsShapeType.None)
  2934. ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
  2935. else
  2936. { // non physical phantom TODO
  2937. // ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
  2938. return false;
  2939. }
  2940. return true;
  2941. }
  2942. if (m_scene.PhysicsScene.SitAvatar(part.PhysActor, AbsolutePosition, CameraPosition, offset, new Vector3(0.35f, 0, 0.65f), PhysicsSitResponse) != 0)
  2943. {
  2944. return true;
  2945. }
  2946. return false;
  2947. }
  2948. private bool CanEnterLandPosition(Vector3 testPos)
  2949. {
  2950. ILandObject land = m_scene.LandChannel.GetLandObject(testPos.X, testPos.Y);
  2951. if (land == null || land.LandData.Name == "NO_LAND")
  2952. return true;
  2953. return land.CanBeOnThisLand(UUID,testPos.Z);
  2954. }
  2955. // status
  2956. // < 0 ignore
  2957. // 0 bad sit spot
  2958. public void PhysicsSitResponse(int status, uint partID, Vector3 offset, Quaternion Orientation)
  2959. {
  2960. if (status < 0)
  2961. return;
  2962. if (status == 0)
  2963. {
  2964. ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
  2965. return;
  2966. }
  2967. SceneObjectPart part = m_scene.GetSceneObjectPart(partID);
  2968. if (part == null)
  2969. return;
  2970. Vector3 targetPos = part.GetWorldPosition() + offset * part.GetWorldRotation();
  2971. if(!CanEnterLandPosition(targetPos))
  2972. {
  2973. ControllingClient.SendAlertMessage(" Sit position on restricted land, try another spot");
  2974. return;
  2975. }
  2976. RemoveFromPhysicalScene();
  2977. if (m_movingToTarget)
  2978. ResetMoveToTarget();
  2979. Velocity = Vector3.Zero;
  2980. m_AngularVelocity = Vector3.Zero;
  2981. m_requestedSitTargetID = 0;
  2982. part.AddSittingAvatar(this);
  2983. ParentPart = part;
  2984. ParentID = part.LocalId;
  2985. Vector3 cameraAtOffset = part.GetCameraAtOffset();
  2986. Vector3 cameraEyeOffset = part.GetCameraEyeOffset();
  2987. bool forceMouselook = part.GetForceMouselook();
  2988. if (!part.IsRoot)
  2989. {
  2990. Orientation = part.RotationOffset * Orientation;
  2991. offset = offset * part.RotationOffset;
  2992. offset += part.OffsetPosition;
  2993. if (cameraAtOffset == Vector3.Zero && cameraEyeOffset == Vector3.Zero)
  2994. {
  2995. cameraAtOffset = part.ParentGroup.RootPart.GetCameraAtOffset();
  2996. cameraEyeOffset = part.ParentGroup.RootPart.GetCameraEyeOffset();
  2997. }
  2998. else
  2999. {
  3000. cameraAtOffset = cameraAtOffset * part.RotationOffset;
  3001. cameraAtOffset += part.OffsetPosition;
  3002. cameraEyeOffset = cameraEyeOffset * part.RotationOffset;
  3003. cameraEyeOffset += part.OffsetPosition;
  3004. }
  3005. }
  3006. m_bodyRot = Orientation;
  3007. m_pos = offset;
  3008. ControllingClient.SendSitResponse(
  3009. part.ParentGroup.UUID, offset, Orientation, true, cameraAtOffset, cameraEyeOffset, forceMouselook);
  3010. SendAvatarDataToAllAgents();
  3011. if (status == 3)
  3012. sitAnimation = "SIT_GROUND";
  3013. else
  3014. sitAnimation = "SIT";
  3015. Animator.SetMovementAnimations("SIT");
  3016. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  3017. m_scene.EventManager.TriggerParcelPrimCountTainted(); // update select/ sat on
  3018. }
  3019. public void HandleAgentSit(IClientAPI remoteClient, UUID agentID)
  3020. {
  3021. if (IsChildAgent)
  3022. return;
  3023. SceneObjectPart part = m_scene.GetSceneObjectPart(m_requestedSitTargetID);
  3024. if (part != null)
  3025. {
  3026. if (part.ParentGroup.IsAttachment)
  3027. {
  3028. m_log.WarnFormat(
  3029. "[SCENE PRESENCE]: Avatar {0} tried to sit on part {1} from object {2} in {3} but this is an attachment for avatar id {4}",
  3030. Name, part.Name, part.ParentGroup.Name, Scene.Name, part.ParentGroup.AttachedAvatar);
  3031. return;
  3032. }
  3033. if (part.SitTargetAvatar == UUID)
  3034. {
  3035. Vector3 sitTargetPos = part.SitTargetPosition;
  3036. Quaternion sitTargetOrient = part.SitTargetOrientation;
  3037. // m_log.DebugFormat(
  3038. // "[SCENE PRESENCE]: Sitting {0} at sit target {1}, {2} on {3} {4}",
  3039. // Name, sitTargetPos, sitTargetOrient, part.Name, part.LocalId);
  3040. double x, y, z, m;
  3041. Vector3 sitOffset;
  3042. Quaternion r = sitTargetOrient;
  3043. Vector3 newPos;
  3044. if (LegacySitOffsets)
  3045. {
  3046. double m1,m2;
  3047. m1 = r.X * r.X + r.Y * r.Y;
  3048. m2 = r.Z * r.Z + r.W * r.W;
  3049. // Rotate the vector <0, 0, 1>
  3050. x = 2 * (r.X * r.Z + r.Y * r.W);
  3051. y = 2 * (-r.X * r.W + r.Y * r.Z);
  3052. z = m2 - m1;
  3053. // Set m to be the square of the norm of r.
  3054. m = m1 + m2;
  3055. // This constant is emperically determined to be what is used in SL.
  3056. // See also http://opensimulator.org/mantis/view.php?id=7096
  3057. double offset = 0.05;
  3058. // Normally m will be ~ 1, but if someone passed a handcrafted quaternion
  3059. // to llSitTarget with values so small that squaring them is rounded off
  3060. // to zero, then m could be zero. The result of this floating point
  3061. // round off error (causing us to skip this impossible normalization)
  3062. // is only 5 cm.
  3063. if (m > 0.000001)
  3064. {
  3065. offset /= m;
  3066. }
  3067. Vector3 up = new Vector3((float)x, (float)y, (float)z);
  3068. sitOffset = up * (float)offset;
  3069. newPos = sitTargetPos - sitOffset + SIT_TARGET_ADJUSTMENT;
  3070. }
  3071. else
  3072. {
  3073. m = r.X * r.X + r.Y * r.Y + r.Z * r.Z + r.W * r.W;
  3074. if (Math.Abs(1.0 - m) > 0.000001)
  3075. {
  3076. if(m != 0)
  3077. {
  3078. m = 1.0 / Math.Sqrt(m);
  3079. r.X *= (float)m;
  3080. r.Y *= (float)m;
  3081. r.Z *= (float)m;
  3082. r.W *= (float)m;
  3083. }
  3084. else
  3085. {
  3086. r.X = 0.0f;
  3087. r.Y = 0.0f;
  3088. r.Z = 0.0f;
  3089. r.W = 1.0f;
  3090. m = 1.0f;
  3091. }
  3092. }
  3093. x = 2 * (r.X * r.Z + r.Y * r.W);
  3094. y = 2 * (-r.X * r.W + r.Y * r.Z);
  3095. z = -r.X * r.X - r.Y * r.Y + r.Z * r.Z + r.W * r.W;
  3096. Vector3 up = new Vector3((float)x, (float)y, (float)z);
  3097. sitOffset = up * Appearance.AvatarHeight * 0.02638f;
  3098. newPos = sitTargetPos + sitOffset + SIT_TARGET_ADJUSTMENT;
  3099. }
  3100. Quaternion newRot;
  3101. if (part.IsRoot)
  3102. {
  3103. newRot = sitTargetOrient;
  3104. }
  3105. else
  3106. {
  3107. newPos = newPos * part.RotationOffset;
  3108. newRot = part.RotationOffset * sitTargetOrient;
  3109. }
  3110. newPos += part.OffsetPosition;
  3111. m_pos = newPos;
  3112. Rotation = newRot;
  3113. // ParentPosition = part.AbsolutePosition;
  3114. }
  3115. else
  3116. {
  3117. // An viewer expects to specify sit positions as offsets to the root prim, even if a child prim is
  3118. // being sat upon.
  3119. m_pos -= part.GroupPosition;
  3120. // ParentPosition = part.AbsolutePosition;
  3121. // m_log.DebugFormat(
  3122. // "[SCENE PRESENCE]: Sitting {0} at position {1} ({2} + {3}) on part {4} {5} without sit target",
  3123. // Name, part.AbsolutePosition, m_pos, ParentPosition, part.Name, part.LocalId);
  3124. }
  3125. part.AddSittingAvatar(this);
  3126. ParentPart = part;
  3127. ParentID = m_requestedSitTargetID;
  3128. RemoveFromPhysicalScene();
  3129. m_AngularVelocity = Vector3.Zero;
  3130. Velocity = Vector3.Zero;
  3131. m_requestedSitTargetID = 0;
  3132. SendAvatarDataToAllAgents();
  3133. sitAnimation = "SIT";
  3134. if (!String.IsNullOrEmpty(part.SitAnimation))
  3135. {
  3136. sitAnimation = part.SitAnimation;
  3137. }
  3138. // Animator.TrySetMovementAnimation(sitAnimation);
  3139. Animator.SetMovementAnimations("SIT");
  3140. TriggerScenePresenceUpdated();
  3141. }
  3142. }
  3143. public void HandleAgentSitOnGround()
  3144. {
  3145. if (IsChildAgent)
  3146. return;
  3147. sitAnimation = "SIT_GROUND_CONSTRAINED";
  3148. SitGround = true;
  3149. RemoveFromPhysicalScene();
  3150. m_AngularVelocity = Vector3.Zero;
  3151. Velocity = Vector3.Zero;
  3152. Animator.SetMovementAnimations("SITGROUND");
  3153. TriggerScenePresenceUpdated();
  3154. }
  3155. /// <summary>
  3156. /// Event handler for the 'Always run' setting on the client
  3157. /// Tells the physics plugin to increase speed of movement.
  3158. /// </summary>
  3159. public void HandleSetAlwaysRun(IClientAPI remoteClient, bool pSetAlwaysRun)
  3160. {
  3161. SetAlwaysRun = pSetAlwaysRun;
  3162. }
  3163. public void HandleStartAnim(IClientAPI remoteClient, UUID animID)
  3164. {
  3165. Animator.AddAnimation(animID, UUID.Zero);
  3166. TriggerScenePresenceUpdated();
  3167. }
  3168. public void HandleStopAnim(IClientAPI remoteClient, UUID animID)
  3169. {
  3170. Animator.RemoveAnimation(animID, false);
  3171. TriggerScenePresenceUpdated();
  3172. }
  3173. public void avnHandleChangeAnim(UUID animID, bool addRemove,bool sendPack)
  3174. {
  3175. Animator.avnChangeAnim(animID, addRemove, sendPack);
  3176. }
  3177. /// <summary>
  3178. /// Rotate the avatar to the given rotation and apply a movement in the given relative vector
  3179. /// </summary>
  3180. /// <param name="vec">The vector in which to move. This is relative to the rotation argument</param>
  3181. /// <param name="thisAddSpeedModifier">
  3182. /// Optional additional speed modifier for this particular add. Default is 1</param>
  3183. public void AddNewMovement(Vector3 vec, float thisAddSpeedModifier = 1, bool breaking = false)
  3184. {
  3185. // m_log.DebugFormat(
  3186. // "[SCENE PRESENCE]: Adding new movement {0} with rotation {1}, thisAddSpeedModifier {2} for {3}",
  3187. // vec, Rotation, thisAddSpeedModifier, Name);
  3188. m_delayedStop = -1;
  3189. // rotate from avatar coord space to world
  3190. Quaternion rot = Rotation;
  3191. if (!Flying && PresenceType != PresenceType.Npc)
  3192. {
  3193. // force rotation to be around Z only, if not flying
  3194. // needed for mouselook
  3195. rot.X = 0;
  3196. rot.Y = 0;
  3197. }
  3198. Vector3 direc = vec * rot;
  3199. direc.Normalize();
  3200. if ((vec.Z == 0f) && !Flying)
  3201. direc.Z = 0f; // Prevent camera WASD up.
  3202. bool notmvtrgt = !m_movingToTarget || m_moveToSpeed <= 0;
  3203. // odd rescalings
  3204. if(notmvtrgt)
  3205. direc *= 4.096f * SpeedModifier * thisAddSpeedModifier;
  3206. else
  3207. direc *= m_moveToSpeed;
  3208. // m_log.DebugFormat("[SCENE PRESENCE]: Force to apply before modification was {0} for {1}", direc, Name);
  3209. if (Animator.currentControlState == ScenePresenceAnimator.motionControlStates.falling
  3210. && (PhysicsActor == null || !PhysicsActor.PIDHoverActive))
  3211. {
  3212. if (breaking)
  3213. direc.Z = -9999f; //hack to tell physics to stop on Z
  3214. else
  3215. direc = Vector3.Zero;
  3216. }
  3217. else if (Flying)
  3218. {
  3219. if (IsColliding && direc.Z < 0)
  3220. // landing situation, prevent avatar moving or it may fail to land
  3221. // animator will handle this condition and do the land
  3222. direc = Vector3.Zero;
  3223. else if(notmvtrgt)
  3224. direc *= 4.0f;
  3225. }
  3226. else if (IsColliding)
  3227. {
  3228. if (direc.Z > 2.0f && notmvtrgt) // reinforce jumps
  3229. {
  3230. direc.Z *= 2.6f;
  3231. }
  3232. else if (direc.Z < 0) // on a surface moving down (pg down) only changes animation
  3233. direc.Z = 0;
  3234. }
  3235. TargetVelocity = direc;
  3236. Animator.UpdateMovementAnimations();
  3237. }
  3238. #endregion
  3239. #region Overridden Methods
  3240. const float ROTATION_TOLERANCE = 0.01f;
  3241. const float VELOCITY_TOLERANCE = 0.1f;
  3242. const float LOWVELOCITYSQ = 0.1f;
  3243. const float POSITION_LARGETOLERANCE = 5f;
  3244. const float POSITION_SMALLTOLERANCE = 0.05f;
  3245. public override void Update()
  3246. {
  3247. if (IsDeleted)
  3248. return;
  3249. if (NeedInitialData > 0)
  3250. {
  3251. SendInitialData();
  3252. return;
  3253. }
  3254. if (IsChildAgent || IsInTransit)
  3255. return;
  3256. CheckForBorderCrossing();
  3257. if (m_movingToTarget)
  3258. {
  3259. m_delayedStop = -1;
  3260. Vector3 control = Vector3.Zero;
  3261. if(HandleMoveToTargetUpdate(1f, ref control))
  3262. AddNewMovement(control);
  3263. }
  3264. else if(m_delayedStop > 0)
  3265. {
  3266. if(IsSatOnObject)
  3267. m_delayedStop = -1;
  3268. else
  3269. if(Util.GetTimeStampMS() > m_delayedStop)
  3270. AddNewMovement(Vector3.Zero);
  3271. }
  3272. if (Appearance.AvatarSize != m_lastSize)
  3273. SendAvatarDataToAllAgents();
  3274. // Send terse position update if not sitting and position, velocity, or rotation
  3275. // has changed significantly from last sent update
  3276. if (!IsSatOnObject)
  3277. {
  3278. // this does need to be more complex later
  3279. Vector3 vel = Velocity;
  3280. Vector3 dpos = m_pos - m_lastPosition;
  3281. if( State != m_lastState ||
  3282. !vel.ApproxEquals(m_lastVelocity) ||
  3283. !m_bodyRot.ApproxEquals(m_lastRotation) ||
  3284. (vel == Vector3.Zero && m_lastVelocity != Vector3.Zero) ||
  3285. Math.Abs(dpos.X) > POSITION_LARGETOLERANCE ||
  3286. Math.Abs(dpos.Y) > POSITION_LARGETOLERANCE ||
  3287. Math.Abs(dpos.Z) > POSITION_LARGETOLERANCE ||
  3288. ( (Math.Abs(dpos.X) > POSITION_SMALLTOLERANCE ||
  3289. Math.Abs(dpos.Y) > POSITION_SMALLTOLERANCE ||
  3290. Math.Abs(dpos.Z) > POSITION_SMALLTOLERANCE)
  3291. && vel.LengthSquared() < LOWVELOCITYSQ
  3292. ) ||
  3293. Math.Abs(CollisionPlane.X - m_lastCollisionPlane.X) > POSITION_SMALLTOLERANCE ||
  3294. Math.Abs(CollisionPlane.Y - m_lastCollisionPlane.Y) > POSITION_SMALLTOLERANCE ||
  3295. Math.Abs(CollisionPlane.W - m_lastCollisionPlane.W) > POSITION_SMALLTOLERANCE
  3296. )
  3297. {
  3298. SendTerseUpdateToAllClients();
  3299. }
  3300. }
  3301. CheckForSignificantMovement();
  3302. }
  3303. #endregion
  3304. #region Update Client(s)
  3305. public void SendUpdateToAgent(ScenePresence p)
  3306. {
  3307. IClientAPI remoteClient = p.ControllingClient;
  3308. if (remoteClient.IsActive)
  3309. {
  3310. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3311. remoteClient.SendEntityUpdate(this, PrimUpdateFlags.FullUpdate);
  3312. m_scene.StatsReporter.AddAgentUpdates(1);
  3313. }
  3314. }
  3315. public void SendFullUpdateToClient(IClientAPI remoteClient)
  3316. {
  3317. if (remoteClient.IsActive)
  3318. {
  3319. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3320. remoteClient.SendEntityUpdate(this, PrimUpdateFlags.FullUpdate);
  3321. m_scene.StatsReporter.AddAgentUpdates(1);
  3322. }
  3323. }
  3324. // this is diferente from SendTerseUpdateToClient
  3325. // this sends bypassing entities updates
  3326. public void SendAgentTerseUpdate(ISceneEntity p)
  3327. {
  3328. ControllingClient.SendAgentTerseUpdate(p);
  3329. }
  3330. /// <summary>
  3331. /// Sends a location update to the client connected to this scenePresence
  3332. /// via entity updates
  3333. /// </summary>
  3334. /// <param name="remoteClient"></param>
  3335. public void SendTerseUpdateToClient(IClientAPI remoteClient)
  3336. {
  3337. // If the client is inactive, it's getting its updates from another
  3338. // server.
  3339. if (remoteClient.IsActive)
  3340. {
  3341. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3342. remoteClient.SendEntityUpdate(
  3343. this,
  3344. PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  3345. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);
  3346. m_scene.StatsReporter.AddAgentUpdates(1);
  3347. }
  3348. }
  3349. public void SendTerseUpdateToAgent(ScenePresence p)
  3350. {
  3351. IClientAPI remoteClient = p.ControllingClient;
  3352. if (!remoteClient.IsActive)
  3353. return;
  3354. if (ParcelHideThisAvatar && p.currentParcelUUID != currentParcelUUID && !p.IsViewerUIGod)
  3355. return;
  3356. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3357. remoteClient.SendEntityUpdate(
  3358. this,
  3359. PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  3360. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);
  3361. m_scene.StatsReporter.AddAgentUpdates(1);
  3362. }
  3363. public void SendTerseUpdateToAgentNF(ScenePresence p)
  3364. {
  3365. IClientAPI remoteClient = p.ControllingClient;
  3366. if (remoteClient.IsActive)
  3367. {
  3368. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3369. remoteClient.SendEntityUpdate(this,
  3370. PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  3371. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);
  3372. m_scene.StatsReporter.AddAgentUpdates(1);
  3373. }
  3374. }
  3375. /// <summary>
  3376. /// Send a location/velocity/accelleration update to all agents in scene
  3377. /// </summary>
  3378. public void SendTerseUpdateToAllClients()
  3379. {
  3380. m_lastState = State;
  3381. m_lastPosition = m_pos;
  3382. m_lastRotation = m_bodyRot;
  3383. m_lastVelocity = Velocity;
  3384. m_lastCollisionPlane = CollisionPlane;
  3385. m_scene.ForEachScenePresence(SendTerseUpdateToAgent);
  3386. // Update the "last" values
  3387. TriggerScenePresenceUpdated();
  3388. }
  3389. public void SendCoarseLocations(List<Vector3> coarseLocations, List<UUID> avatarUUIDs)
  3390. {
  3391. SendCoarseLocationsMethod d = m_sendCoarseLocationsMethod;
  3392. if (d != null)
  3393. {
  3394. d.Invoke(m_scene.RegionInfo.originRegionID, this, coarseLocations, avatarUUIDs);
  3395. }
  3396. }
  3397. public void SetSendCoarseLocationMethod(SendCoarseLocationsMethod d)
  3398. {
  3399. if (d != null)
  3400. m_sendCoarseLocationsMethod = d;
  3401. }
  3402. public void SendCoarseLocationsDefault(UUID sceneId, ScenePresence p, List<Vector3> coarseLocations, List<UUID> avatarUUIDs)
  3403. {
  3404. ControllingClient.SendCoarseLocationUpdate(avatarUUIDs, coarseLocations);
  3405. }
  3406. public void RegionHandShakeReply (IClientAPI client)
  3407. {
  3408. if(IsNPC)
  3409. return;
  3410. lock (m_completeMovementLock)
  3411. {
  3412. if(m_gotRegionHandShake)
  3413. return;
  3414. m_gotRegionHandShake = true;
  3415. NeedInitialData = 1;
  3416. }
  3417. }
  3418. private void SendInitialData()
  3419. {
  3420. uint flags = ControllingClient.GetViewerCaps();
  3421. if((flags & 0x1000) == 0) // wait for seeds sending
  3422. return;
  3423. // lock (m_completeMovementLock)
  3424. {
  3425. if(NeedInitialData < 0)
  3426. return;
  3427. // give some extra time to make sure viewers did process seeds
  3428. if(++NeedInitialData < 4) // needs fix if update rate changes on heartbeat
  3429. return;
  3430. }
  3431. NeedInitialData = -1;
  3432. bool selfappearance = (flags & 4) != 0;
  3433. // this should enqueued on the client processing job to save threads
  3434. Util.FireAndForget(delegate
  3435. {
  3436. if(!IsChildAgent)
  3437. {
  3438. // close v1 sender region obsolete
  3439. if (!string.IsNullOrEmpty(m_callbackURI))
  3440. {
  3441. m_log.DebugFormat(
  3442. "[SCENE PRESENCE({0})]: Releasing {1} {2} with old callback to {3}",
  3443. Scene.RegionInfo.RegionName, Name, UUID, m_callbackURI);
  3444. UUID originID;
  3445. lock (m_originRegionIDAccessLock)
  3446. originID = m_originRegionID;
  3447. Scene.SimulationService.ReleaseAgent(originID, UUID, m_callbackURI);
  3448. m_callbackURI = null;
  3449. }
  3450. // v0.7 close HG sender region
  3451. else if (!string.IsNullOrEmpty(m_newCallbackURI))
  3452. {
  3453. m_log.DebugFormat(
  3454. "[SCENE PRESENCE({0})]: Releasing {1} {2} with callback to {3}",
  3455. Scene.RegionInfo.RegionName, Name, UUID, m_newCallbackURI);
  3456. UUID originID;
  3457. lock (m_originRegionIDAccessLock)
  3458. originID = m_originRegionID;
  3459. Scene.SimulationService.ReleaseAgent(originID, UUID, m_newCallbackURI);
  3460. m_newCallbackURI = null;
  3461. }
  3462. IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
  3463. if (m_agentTransfer != null)
  3464. {
  3465. m_agentTransfer.CloseOldChildAgents(this);
  3466. }
  3467. }
  3468. m_log.DebugFormat("[SCENE PRESENCE({0})]: SendInitialData for {1}", Scene.RegionInfo.RegionName, UUID);
  3469. if (m_teleportFlags <= 0)
  3470. {
  3471. Scene.SendLayerData(ControllingClient);
  3472. ILandChannel landch = m_scene.LandChannel;
  3473. if (landch != null)
  3474. landch.sendClientInitialLandInfo(ControllingClient, true);
  3475. }
  3476. SendOtherAgentsAvatarFullToMe();
  3477. if (m_scene.ObjectsCullingByDistance)
  3478. {
  3479. m_reprioritizationBusy = true;
  3480. m_reprioritizationLastPosition = AbsolutePosition;
  3481. m_reprioritizationLastDrawDistance = DrawDistance;
  3482. ControllingClient.ReprioritizeUpdates();
  3483. m_reprioritizationLastTime = Util.EnvironmentTickCount();
  3484. m_reprioritizationBusy = false;
  3485. }
  3486. else
  3487. {
  3488. //bool cacheCulling = (flags & 1) != 0;
  3489. bool cacheEmpty = (flags & 2) != 0;;
  3490. EntityBase[] entities = Scene.Entities.GetEntities();
  3491. if(cacheEmpty)
  3492. {
  3493. foreach (EntityBase e in entities)
  3494. {
  3495. if (e != null && e is SceneObjectGroup && !((SceneObjectGroup)e).IsAttachment)
  3496. ((SceneObjectGroup)e).SendFullAnimUpdateToClient(ControllingClient);
  3497. }
  3498. }
  3499. else
  3500. {
  3501. foreach (EntityBase e in entities)
  3502. {
  3503. if (e != null && e is SceneObjectGroup && !((SceneObjectGroup)e).IsAttachment)
  3504. {
  3505. SceneObjectGroup grp = e as SceneObjectGroup;
  3506. if(grp.IsViewerCachable)
  3507. grp.SendUpdateProbes(ControllingClient);
  3508. else
  3509. grp.SendFullAnimUpdateToClient(ControllingClient);
  3510. }
  3511. }
  3512. }
  3513. m_reprioritizationLastPosition = AbsolutePosition;
  3514. m_reprioritizationLastDrawDistance = DrawDistance;
  3515. m_reprioritizationLastTime = Util.EnvironmentTickCount() + 15000; // delay it
  3516. m_reprioritizationBusy = false;
  3517. }
  3518. if (!IsChildAgent)
  3519. {
  3520. // Create child agents in neighbouring regions
  3521. IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
  3522. if (m_agentTransfer != null)
  3523. {
  3524. m_agentTransfer.EnableChildAgents(this);
  3525. }
  3526. m_lastChildUpdatesTime = Util.EnvironmentTickCount() + 10000;
  3527. m_lastChildAgentUpdatePosition = AbsolutePosition;
  3528. m_lastChildAgentCheckPosition = m_lastChildAgentUpdatePosition;
  3529. m_lastChildAgentUpdateDrawDistance = DrawDistance;
  3530. m_lastRegionsDrawDistance = RegionViewDistance;
  3531. m_lastChildAgentUpdateGodLevel = GodController.ViwerUIGodLevel;
  3532. m_childUpdatesBusy = false; // allow them
  3533. }
  3534. });
  3535. }
  3536. /// <summary>
  3537. /// Send avatar full data appearance and animations for all other root agents to this agent, this agent
  3538. /// can be either a child or root
  3539. /// </summary>
  3540. public void SendOtherAgentsAvatarFullToMe()
  3541. {
  3542. int count = 0;
  3543. m_scene.ForEachRootScenePresence(delegate(ScenePresence p)
  3544. {
  3545. // only send information about other root agents
  3546. if (p.UUID == UUID)
  3547. return;
  3548. // get the avatar, then a kill if can't see it
  3549. p.SendInitialAvatarDataToAgent(this);
  3550. if (p.ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !IsViewerUIGod)
  3551. return;
  3552. p.SendAppearanceToAgentNF(this);
  3553. p.SendAnimPackToAgentNF(this);
  3554. p.SendAttachmentsToAgentNF(this);
  3555. count++;
  3556. });
  3557. m_scene.StatsReporter.AddAgentUpdates(count);
  3558. }
  3559. /// <summary>
  3560. /// Send this agent's avatar data to all other root and child agents in the scene
  3561. /// This agent must be root. This avatar will receive its own update.
  3562. /// </summary>
  3563. public void SendAvatarDataToAllAgents()
  3564. {
  3565. //m_log.DebugFormat("[SCENE PRESENCE] SendAvatarDataToAllAgents: {0} ({1})", Name, UUID);
  3566. // only send update from root agents to other clients; children are only "listening posts"
  3567. if (IsChildAgent)
  3568. {
  3569. m_log.WarnFormat(
  3570. "[SCENE PRESENCE]: Attempt to send avatar data from a child agent for {0} in {1}",
  3571. Name, Scene.RegionInfo.RegionName);
  3572. return;
  3573. }
  3574. m_lastSize = Appearance.AvatarSize;
  3575. int count = 0;
  3576. m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
  3577. {
  3578. SendAvatarDataToAgent(scenePresence);
  3579. count++;
  3580. });
  3581. m_scene.StatsReporter.AddAgentUpdates(count);
  3582. }
  3583. // sends avatar object to all clients so they cross it into region
  3584. // then sends kills to hide
  3585. public void SendInitialAvatarDataToAllAgents(List<ScenePresence> presences)
  3586. {
  3587. m_lastSize = Appearance.AvatarSize;
  3588. int count = 0;
  3589. SceneObjectPart sitroot = null;
  3590. if (ParentID != 0 && ParentPart != null) // we need to send the sitting root prim
  3591. {
  3592. sitroot = ParentPart.ParentGroup.RootPart;
  3593. }
  3594. foreach (ScenePresence p in presences)
  3595. {
  3596. if (sitroot != null) // we need to send the sitting root prim
  3597. {
  3598. p.ControllingClient.SendEntityFullUpdateImmediate(ParentPart.ParentGroup.RootPart);
  3599. }
  3600. p.ControllingClient.SendEntityFullUpdateImmediate(this);
  3601. if (p != this && ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3602. // either just kill the object
  3603. // p.ControllingClient.SendKillObject(new List<uint> {LocalId});
  3604. // or also attachments viewer may still know about
  3605. SendKillTo(p);
  3606. count++;
  3607. }
  3608. m_scene.StatsReporter.AddAgentUpdates(count);
  3609. }
  3610. public void SendInitialAvatarDataToAgent(ScenePresence p)
  3611. {
  3612. if(ParentID != 0 && ParentPart != null) // we need to send the sitting root prim
  3613. {
  3614. p.ControllingClient.SendEntityFullUpdateImmediate(ParentPart.ParentGroup.RootPart);
  3615. }
  3616. p.ControllingClient.SendEntityFullUpdateImmediate(this);
  3617. if (p != this && ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3618. // either just kill the object
  3619. // p.ControllingClient.SendKillObject(new List<uint> {LocalId});
  3620. // or also attachments viewer may still know about
  3621. SendKillTo(p);
  3622. }
  3623. /// <summary>
  3624. /// Send avatar data to an agent.
  3625. /// </summary>
  3626. /// <param name="avatar"></param>
  3627. public void SendAvatarDataToAgent(ScenePresence avatar)
  3628. {
  3629. //m_log.DebugFormat("[SCENE PRESENCE] SendAvatarDataToAgent from {0} ({1}) to {2} ({3})", Name, UUID, avatar.Name, avatar.UUID);
  3630. if (ParcelHideThisAvatar && currentParcelUUID != avatar.currentParcelUUID && !avatar.IsViewerUIGod)
  3631. return;
  3632. avatar.ControllingClient.SendEntityFullUpdateImmediate(this);
  3633. }
  3634. public void SendAvatarDataToAgentNF(ScenePresence avatar)
  3635. {
  3636. avatar.ControllingClient.SendEntityFullUpdateImmediate(this);
  3637. }
  3638. /// <summary>
  3639. /// Send this agent's appearance to all other root and child agents in the scene
  3640. /// This agent must be root.
  3641. /// </summary>
  3642. public void SendAppearanceToAllOtherAgents()
  3643. {
  3644. // m_log.DebugFormat("[SCENE PRESENCE] SendAppearanceToAllOtherAgents: {0} {1}", Name, UUID);
  3645. // only send update from root agents to other clients; children are only "listening posts"
  3646. if (IsChildAgent)
  3647. {
  3648. m_log.WarnFormat(
  3649. "[SCENE PRESENCE]: Attempt to send avatar data from a child agent for {0} in {1}",
  3650. Name, Scene.RegionInfo.RegionName);
  3651. return;
  3652. }
  3653. int count = 0;
  3654. m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
  3655. {
  3656. // only send information to other root agents
  3657. if (scenePresence.UUID == UUID)
  3658. return;
  3659. SendAppearanceToAgent(scenePresence);
  3660. count++;
  3661. });
  3662. m_scene.StatsReporter.AddAgentUpdates(count);
  3663. }
  3664. public void SendAppearanceToAgent(ScenePresence avatar)
  3665. {
  3666. // m_log.DebugFormat(
  3667. // "[SCENE PRESENCE]: Sending appearance data from {0} {1} to {2} {3}", Name, m_uuid, avatar.Name, avatar.UUID);
  3668. if (ParcelHideThisAvatar && currentParcelUUID != avatar.currentParcelUUID && !avatar.IsViewerUIGod)
  3669. return;
  3670. SendAppearanceToAgentNF(avatar);
  3671. }
  3672. public void SendAppearanceToAgentNF(ScenePresence avatar)
  3673. {
  3674. avatar.ControllingClient.SendAppearance(UUID, Appearance.VisualParams, Appearance.Texture.GetBakesBytes(), Appearance.AvatarPreferencesHoverZ);
  3675. }
  3676. public void SendAnimPackToAgent(ScenePresence p)
  3677. {
  3678. if (IsChildAgent || Animator == null)
  3679. return;
  3680. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3681. return;
  3682. Animator.SendAnimPackToClient(p.ControllingClient);
  3683. }
  3684. public void SendAnimPackToAgent(ScenePresence p, UUID[] animations, int[] seqs, UUID[] objectIDs)
  3685. {
  3686. if (IsChildAgent)
  3687. return;
  3688. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3689. return;
  3690. p.ControllingClient.SendAnimations(animations, seqs, ControllingClient.AgentId, objectIDs);
  3691. }
  3692. public void SendAnimPackToAgentNF(ScenePresence p)
  3693. {
  3694. if (IsChildAgent || Animator == null)
  3695. return;
  3696. Animator.SendAnimPackToClient(p.ControllingClient);
  3697. }
  3698. public void SendAnimPackToAgentNF(ScenePresence p, UUID[] animations, int[] seqs, UUID[] objectIDs)
  3699. {
  3700. p.ControllingClient.SendAnimations(animations, seqs, ControllingClient.AgentId, objectIDs);
  3701. }
  3702. public void SendAnimPack(UUID[] animations, int[] seqs, UUID[] objectIDs)
  3703. {
  3704. if (IsChildAgent)
  3705. return;
  3706. m_scene.ForEachScenePresence(delegate(ScenePresence p)
  3707. {
  3708. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3709. return;
  3710. p.ControllingClient.SendAnimations(animations, seqs, ControllingClient.AgentId, objectIDs);
  3711. });
  3712. }
  3713. #endregion
  3714. #region Significant Movement Method
  3715. private void checkRePrioritization()
  3716. {
  3717. if(IsDeleted || !ControllingClient.IsActive)
  3718. return;
  3719. if(m_reprioritizationBusy)
  3720. return;
  3721. float limit = Scene.ReprioritizationDistance;
  3722. bool byDrawdistance = Scene.ObjectsCullingByDistance;
  3723. if(byDrawdistance)
  3724. {
  3725. float minregionSize = Scene.RegionInfo.RegionSizeX;
  3726. if(minregionSize > Scene.RegionInfo.RegionSizeY)
  3727. minregionSize = Scene.RegionInfo.RegionSizeY;
  3728. minregionSize *= 0.5f;
  3729. if(DrawDistance > minregionSize && m_reprioritizationLastDrawDistance > minregionSize)
  3730. byDrawdistance = false;
  3731. else
  3732. byDrawdistance = (Math.Abs(DrawDistance - m_reprioritizationLastDrawDistance) > 0.5f * limit);
  3733. }
  3734. int tdiff = Util.EnvironmentTickCountSubtract(m_reprioritizationLastTime);
  3735. if(!byDrawdistance && tdiff < Scene.ReprioritizationInterval)
  3736. return;
  3737. // priority uses avatar position
  3738. Vector3 pos = AbsolutePosition;
  3739. Vector3 diff = pos - m_reprioritizationLastPosition;
  3740. limit *= limit;
  3741. if (!byDrawdistance && diff.LengthSquared() < limit)
  3742. return;
  3743. m_reprioritizationBusy = true;
  3744. m_reprioritizationLastPosition = pos;
  3745. m_reprioritizationLastDrawDistance = DrawDistance;
  3746. Util.FireAndForget(
  3747. o =>
  3748. {
  3749. ControllingClient.ReprioritizeUpdates();
  3750. m_reprioritizationLastTime = Util.EnvironmentTickCount();
  3751. m_reprioritizationBusy = false;
  3752. }, null, "ScenePresence.Reprioritization");
  3753. }
  3754. /// <summary>
  3755. /// This checks for a significant movement and sends a coarselocationchange update
  3756. /// </summary>
  3757. protected void CheckForSignificantMovement()
  3758. {
  3759. Vector3 pos = AbsolutePosition;
  3760. Vector3 diff = pos - posLastMove;
  3761. if (diff.LengthSquared() > MOVEMENT)
  3762. {
  3763. posLastMove = pos;
  3764. m_scene.EventManager.TriggerOnClientMovement(this);
  3765. }
  3766. diff = pos - posLastSignificantMove;
  3767. if (diff.LengthSquared() > SIGNIFICANT_MOVEMENT)
  3768. {
  3769. posLastSignificantMove = pos;
  3770. m_scene.EventManager.TriggerSignificantClientMovement(this);
  3771. }
  3772. if(IsNPC)
  3773. return;
  3774. // updates priority recalc
  3775. checkRePrioritization();
  3776. if(m_childUpdatesBusy || RegionViewDistance == 0)
  3777. return;
  3778. int tdiff = Util.EnvironmentTickCountSubtract(m_lastChildUpdatesTime);
  3779. if (tdiff < CHILDUPDATES_TIME)
  3780. return;
  3781. bool viewchanged = Math.Abs(RegionViewDistance - m_lastRegionsDrawDistance) > 32.0f;
  3782. IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
  3783. float dx = pos.X - m_lastChildAgentCheckPosition.X;
  3784. float dy = pos.Y - m_lastChildAgentCheckPosition.Y;
  3785. if ((m_agentTransfer != null) && (viewchanged || ((dx * dx + dy * dy) > CHILDAGENTSCHECK_MOVEMENT)))
  3786. {
  3787. m_childUpdatesBusy = true;
  3788. m_lastChildAgentCheckPosition = pos;
  3789. m_lastChildAgentUpdatePosition = pos;
  3790. m_lastChildAgentUpdateGodLevel = GodController.ViwerUIGodLevel;
  3791. m_lastChildAgentUpdateDrawDistance = DrawDistance;
  3792. m_lastRegionsDrawDistance = RegionViewDistance;
  3793. // m_lastChildAgentUpdateCamPosition = CameraPosition;
  3794. Util.FireAndForget(
  3795. o =>
  3796. {
  3797. m_agentTransfer.EnableChildAgents(this);
  3798. m_lastChildUpdatesTime = Util.EnvironmentTickCount();
  3799. m_childUpdatesBusy = false;
  3800. }, null, "ScenePresence.CheckChildAgents");
  3801. }
  3802. else
  3803. {
  3804. //possible KnownRegionHandles always contains current region and this check is not needed
  3805. int minhandles = KnownRegionHandles.Contains(RegionHandle) ? 1 : 0;
  3806. if(KnownRegionHandles.Count > minhandles)
  3807. {
  3808. bool doUpdate = false;
  3809. if (m_lastChildAgentUpdateGodLevel != GodController.ViwerUIGodLevel)
  3810. doUpdate = true;
  3811. if (Math.Abs(DrawDistance - m_lastChildAgentUpdateDrawDistance) > 32.0f)
  3812. doUpdate = true;
  3813. if(!doUpdate)
  3814. {
  3815. diff = pos - m_lastChildAgentUpdatePosition;
  3816. if (diff.LengthSquared() > CHILDUPDATES_MOVEMENT)
  3817. doUpdate = true;
  3818. }
  3819. if (doUpdate)
  3820. {
  3821. m_childUpdatesBusy = true;
  3822. m_lastChildAgentUpdatePosition = pos;
  3823. m_lastChildAgentUpdateGodLevel = GodController.ViwerUIGodLevel;
  3824. m_lastChildAgentUpdateDrawDistance = DrawDistance;
  3825. // m_lastChildAgentUpdateCamPosition = CameraPosition;
  3826. AgentPosition agentpos = new AgentPosition();
  3827. agentpos.AgentID = new UUID(UUID.Guid);
  3828. agentpos.SessionID = ControllingClient.SessionId;
  3829. agentpos.Size = Appearance.AvatarSize;
  3830. agentpos.Center = CameraPosition;
  3831. agentpos.Far = DrawDistance;
  3832. agentpos.Position = AbsolutePosition;
  3833. agentpos.Velocity = Velocity;
  3834. agentpos.RegionHandle = RegionHandle;
  3835. agentpos.GodData = GodController.State();
  3836. agentpos.Throttles = ControllingClient.GetThrottlesPacked(1);
  3837. // Let's get this out of the update loop
  3838. Util.FireAndForget(
  3839. o =>
  3840. {
  3841. m_scene.SendOutChildAgentUpdates(agentpos, this);
  3842. m_lastChildUpdatesTime = Util.EnvironmentTickCount();
  3843. m_childUpdatesBusy = false;
  3844. }, null, "ScenePresence.SendOutChildAgentUpdates");
  3845. }
  3846. }
  3847. }
  3848. }
  3849. #endregion
  3850. #region Border Crossing Methods
  3851. /// <summary>
  3852. /// Starts the process of moving an avatar into another region if they are crossing the border.
  3853. /// </summary>
  3854. /// <remarks>
  3855. /// Also removes the avatar from the physical scene if transit has started.
  3856. /// </remarks>
  3857. protected void CheckForBorderCrossing()
  3858. {
  3859. // Check that we we are not a child
  3860. if (IsChildAgent || IsInTransit)
  3861. return;
  3862. // If we don't have a PhysActor, we can't cross anyway
  3863. // Also don't do this while sat, sitting avatars cross with the
  3864. // object they sit on. ParentUUID denoted a pending sit, don't
  3865. // interfere with it.
  3866. if (ParentID != 0 || PhysicsActor == null || ParentUUID != UUID.Zero)
  3867. return;
  3868. Vector3 pos2 = AbsolutePosition;
  3869. Vector3 vel = Velocity;
  3870. float timeStep = 0.1f;
  3871. pos2.X += vel.X * timeStep;
  3872. pos2.Y += vel.Y * timeStep;
  3873. pos2.Z += vel.Z * timeStep;
  3874. // m_log.DebugFormat(
  3875. // "[SCENE PRESENCE]: Testing border check for projected position {0} of {1} in {2}",
  3876. // pos2, Name, Scene.Name);
  3877. if (Scene.PositionIsInCurrentRegion(pos2))
  3878. return;
  3879. if (!CrossToNewRegion() && m_requestedSitTargetUUID == UUID.Zero)
  3880. {
  3881. // we don't have entity transfer module
  3882. Vector3 pos = AbsolutePosition;
  3883. vel = Velocity;
  3884. float px = pos.X;
  3885. if (px < 0)
  3886. pos.X += vel.X * 2;
  3887. else if (px > m_scene.RegionInfo.RegionSizeX)
  3888. pos.X -= vel.X * 2;
  3889. float py = pos.Y;
  3890. if (py < 0)
  3891. pos.Y += vel.Y * 2;
  3892. else if (py > m_scene.RegionInfo.RegionSizeY)
  3893. pos.Y -= vel.Y * 2;
  3894. Velocity = Vector3.Zero;
  3895. m_AngularVelocity = Vector3.Zero;
  3896. AbsolutePosition = pos;
  3897. }
  3898. }
  3899. public void CrossToNewRegionFail()
  3900. {
  3901. if (m_requestedSitTargetUUID == UUID.Zero)
  3902. {
  3903. bool isFlying = Flying;
  3904. RemoveFromPhysicalScene();
  3905. Vector3 pos = AbsolutePosition;
  3906. Vector3 vel = Velocity;
  3907. float px = pos.X;
  3908. if (px < 0)
  3909. pos.X += vel.X * 2;
  3910. else if (px > m_scene.RegionInfo.RegionSizeX)
  3911. pos.X -= vel.X * 2;
  3912. float py = pos.Y;
  3913. if (py < 0)
  3914. pos.Y += vel.Y * 2;
  3915. else if (py > m_scene.RegionInfo.RegionSizeY)
  3916. pos.Y -= vel.Y * 2;
  3917. Velocity = Vector3.Zero;
  3918. m_AngularVelocity = Vector3.Zero;
  3919. AbsolutePosition = pos;
  3920. AddToPhysicalScene(isFlying);
  3921. }
  3922. }
  3923. /// <summary>
  3924. /// Moves the agent outside the region bounds
  3925. /// Tells neighbor region that we're crossing to it
  3926. /// If the neighbor accepts, remove the agent's viewable avatar from this scene
  3927. /// set them to a child agent.
  3928. /// </summary>
  3929. protected bool CrossToNewRegion()
  3930. {
  3931. bool result = false;
  3932. // parcelRegionCross(false);
  3933. try
  3934. {
  3935. result = m_scene.CrossAgentToNewRegion(this, Flying);
  3936. }
  3937. catch
  3938. {
  3939. // result = m_scene.CrossAgentToNewRegion(this, false);
  3940. return false;
  3941. }
  3942. // if(!result)
  3943. // parcelRegionCross(true);
  3944. return result;
  3945. }
  3946. /// <summary>
  3947. /// Computes which child agents to close when the scene presence moves to another region.
  3948. /// Removes those regions from m_knownRegions.
  3949. /// </summary>
  3950. /// <param name="newRegionHandle">The new region's handle</param>
  3951. /// <param name="newRegionSizeX">The new region's size x</param>
  3952. /// <param name="newRegionSizeY">The new region's size y</param>
  3953. /// <returns></returns>
  3954. public List<ulong> GetChildAgentsToClose(ulong newRegionHandle, int newRegionSizeX, int newRegionSizeY)
  3955. {
  3956. ulong curRegionHandle = m_scene.RegionInfo.RegionHandle;
  3957. List<ulong> byebyeRegions = new List<ulong>();
  3958. if(newRegionHandle == curRegionHandle) //??
  3959. return byebyeRegions;
  3960. uint newRegionX, newRegionY;
  3961. List<ulong> knownRegions = KnownRegionHandles;
  3962. m_log.DebugFormat(
  3963. "[SCENE PRESENCE]: Closing child agents. Checking {0} regions in {1}",
  3964. knownRegions.Count, Scene.RegionInfo.RegionName);
  3965. Util.RegionHandleToRegionLoc(newRegionHandle, out newRegionX, out newRegionY);
  3966. uint x, y;
  3967. spRegionSizeInfo regInfo;
  3968. foreach (ulong handle in knownRegions)
  3969. {
  3970. if(newRegionY == 0) // HG
  3971. byebyeRegions.Add(handle);
  3972. else if(handle == curRegionHandle)
  3973. {
  3974. continue;
  3975. /*
  3976. RegionInfo curreg = m_scene.RegionInfo;
  3977. if (Util.IsOutsideView(255, curreg.RegionLocX, newRegionX, curreg.RegionLocY, newRegionY,
  3978. (int)curreg.RegionSizeX, (int)curreg.RegionSizeX, newRegionSizeX, newRegionSizeY))
  3979. {
  3980. byebyeRegions.Add(handle);
  3981. }
  3982. */
  3983. }
  3984. else
  3985. {
  3986. Util.RegionHandleToRegionLoc(handle, out x, out y);
  3987. if (m_knownChildRegionsSizeInfo.TryGetValue(handle, out regInfo))
  3988. {
  3989. // if (Util.IsOutsideView(RegionViewDistance, x, newRegionX, y, newRegionY,
  3990. // for now need to close all but first order bc RegionViewDistance it the target value not ours
  3991. if (Util.IsOutsideView(255, x, newRegionX, y, newRegionY,
  3992. regInfo.sizeX, regInfo.sizeY, newRegionSizeX, newRegionSizeY))
  3993. {
  3994. byebyeRegions.Add(handle);
  3995. }
  3996. }
  3997. else
  3998. {
  3999. // if (Util.IsOutsideView(RegionViewDistance, x, newRegionX, y, newRegionY,
  4000. if (Util.IsOutsideView(255, x, newRegionX, y, newRegionY,
  4001. (int)Constants.RegionSize, (int)Constants.RegionSize, newRegionSizeX, newRegionSizeY))
  4002. {
  4003. byebyeRegions.Add(handle);
  4004. }
  4005. }
  4006. }
  4007. }
  4008. return byebyeRegions;
  4009. }
  4010. public void CloseChildAgents(List<ulong> byebyeRegions)
  4011. {
  4012. byebyeRegions.Remove(Scene.RegionInfo.RegionHandle);
  4013. if (byebyeRegions.Count > 0)
  4014. {
  4015. m_log.Debug("[SCENE PRESENCE]: Closing " + byebyeRegions.Count + " child agents");
  4016. AgentCircuitData acd = Scene.AuthenticateHandler.GetAgentCircuitData(UUID);
  4017. string auth = string.Empty;
  4018. if (acd != null)
  4019. auth = acd.SessionID.ToString();
  4020. m_scene.SceneGridService.SendCloseChildAgentConnections(ControllingClient.AgentId, auth, byebyeRegions);
  4021. }
  4022. foreach (ulong handle in byebyeRegions)
  4023. {
  4024. RemoveNeighbourRegion(handle);
  4025. Scene.CapsModule.DropChildSeed(UUID, handle);
  4026. }
  4027. }
  4028. public void closeAllChildAgents()
  4029. {
  4030. List<ulong> byebyeRegions = new List<ulong>();
  4031. List<ulong> knownRegions = KnownRegionHandles;
  4032. foreach (ulong handle in knownRegions)
  4033. {
  4034. if (handle != Scene.RegionInfo.RegionHandle)
  4035. {
  4036. byebyeRegions.Add(handle);
  4037. RemoveNeighbourRegion(handle);
  4038. Scene.CapsModule.DropChildSeed(UUID, handle);
  4039. }
  4040. }
  4041. if (byebyeRegions.Count > 0)
  4042. {
  4043. m_log.Debug("[SCENE PRESENCE]: Closing " + byebyeRegions.Count + " child agents");
  4044. AgentCircuitData acd = Scene.AuthenticateHandler.GetAgentCircuitData(UUID);
  4045. string auth = string.Empty;
  4046. if (acd != null)
  4047. auth = acd.SessionID.ToString();
  4048. m_scene.SceneGridService.SendCloseChildAgentConnections(ControllingClient.AgentId, auth, byebyeRegions);
  4049. }
  4050. }
  4051. #endregion
  4052. /// <summary>
  4053. /// handle god level requests.
  4054. /// </summary>
  4055. public void GrantGodlikePowers(UUID token, bool godStatus)
  4056. {
  4057. if (IsNPC)
  4058. return;
  4059. bool wasgod = IsViewerUIGod;
  4060. GodController.RequestGodMode(godStatus);
  4061. if (wasgod != IsViewerUIGod)
  4062. parcelGodCheck(m_currentParcelUUID);
  4063. }
  4064. #region Child Agent Updates
  4065. public void UpdateChildAgent(AgentData cAgentData)
  4066. {
  4067. // m_log.Debug(" >>> ChildAgentDataUpdate <<< " + Scene.RegionInfo.RegionName);
  4068. if (!IsChildAgent)
  4069. return;
  4070. CopyFrom(cAgentData);
  4071. m_updateAgentReceivedAfterTransferEvent.Set();
  4072. }
  4073. private static Vector3 marker = new Vector3(-1f, -1f, -1f);
  4074. private void RaiseUpdateThrottles()
  4075. {
  4076. if(m_capbandwidth > 0)
  4077. return;
  4078. m_bandwidth = 4 * ControllingClient.GetAgentThrottleSilent((int)ThrottleOutPacketType.Texture);
  4079. if(m_bandwidth < 50000)
  4080. m_bandwidth = 50000;
  4081. m_bandwidthBurst = m_bandwidth / 5;
  4082. }
  4083. /// <summary>
  4084. /// This updates important decision making data about a child agent
  4085. /// The main purpose is to figure out what objects to send to a child agent that's in a neighboring region
  4086. /// </summary>
  4087. public void UpdateChildAgent(AgentPosition cAgentData, uint tRegionX, uint tRegionY, uint rRegionX, uint rRegionY)
  4088. {
  4089. if (!IsChildAgent)
  4090. return;
  4091. GodController.SetState(cAgentData.GodData);
  4092. RegionHandle = cAgentData.RegionHandle;
  4093. //m_log.Debug(" >>> ChildAgentPositionUpdate <<< " + rRegionX + "-" + rRegionY);
  4094. int shiftx = ((int)rRegionX - (int)tRegionX) * (int)Constants.RegionSize;
  4095. int shifty = ((int)rRegionY - (int)tRegionY) * (int)Constants.RegionSize;
  4096. Vector3 offset = new Vector3(shiftx, shifty, 0f);
  4097. DrawDistance = cAgentData.Far;
  4098. if (cAgentData.Position != marker) // UGH!!
  4099. m_pos = cAgentData.Position + offset;
  4100. CameraPosition = cAgentData.Center + offset;
  4101. if ((cAgentData.Throttles != null) && cAgentData.Throttles.Length > 0)
  4102. {
  4103. // some scaling factor
  4104. float x = m_pos.X;
  4105. if (x > m_scene.RegionInfo.RegionSizeX)
  4106. x -= m_scene.RegionInfo.RegionSizeX;
  4107. float y = m_pos.Y;
  4108. if (y > m_scene.RegionInfo.RegionSizeY)
  4109. y -= m_scene.RegionInfo.RegionSizeY;
  4110. x = x * x + y * y;
  4111. const float distScale = 0.4f / Constants.RegionSize / Constants.RegionSize;
  4112. float factor = 1.0f - distScale * x;
  4113. if (factor < 0.2f)
  4114. factor = 0.2f;
  4115. ControllingClient.SetChildAgentThrottle(cAgentData.Throttles,factor);
  4116. }
  4117. if(cAgentData.ChildrenCapSeeds != null && cAgentData.ChildrenCapSeeds.Count >0)
  4118. {
  4119. if (Scene.CapsModule != null)
  4120. {
  4121. Scene.CapsModule.SetChildrenSeed(UUID, cAgentData.ChildrenCapSeeds);
  4122. }
  4123. KnownRegions = cAgentData.ChildrenCapSeeds;
  4124. }
  4125. //cAgentData.AVHeight;
  4126. //m_velocity = cAgentData.Velocity;
  4127. checkRePrioritization();
  4128. }
  4129. public void CopyTo(AgentData cAgent, bool isCrossUpdate)
  4130. {
  4131. cAgent.CallbackURI = m_callbackURI;
  4132. cAgent.NewCallbackURI = m_newCallbackURI;
  4133. cAgent.AgentID = UUID;
  4134. cAgent.RegionID = Scene.RegionInfo.RegionID;
  4135. cAgent.SessionID = ControllingClient.SessionId;
  4136. cAgent.Position = AbsolutePosition;
  4137. cAgent.Velocity = m_velocity;
  4138. cAgent.Center = CameraPosition;
  4139. cAgent.AtAxis = CameraAtAxis;
  4140. cAgent.LeftAxis = CameraLeftAxis;
  4141. cAgent.UpAxis = CameraUpAxis;
  4142. cAgent.Far = DrawDistance;
  4143. cAgent.GodData = GodController.State();
  4144. // Throttles
  4145. cAgent.Throttles = ControllingClient.GetThrottlesPacked(1);
  4146. cAgent.HeadRotation = m_headrotation;
  4147. cAgent.BodyRotation = Rotation;
  4148. cAgent.ControlFlags = (uint)m_AgentControlFlags;
  4149. cAgent.AlwaysRun = SetAlwaysRun;
  4150. // make clear we want the all thing
  4151. cAgent.Appearance = new AvatarAppearance(Appearance,true,true);
  4152. cAgent.ParentPart = ParentUUID;
  4153. cAgent.SitOffset = PrevSitOffset;
  4154. lock (scriptedcontrols)
  4155. {
  4156. ControllerData[] controls = new ControllerData[scriptedcontrols.Count];
  4157. int i = 0;
  4158. foreach (ScriptControllers c in scriptedcontrols.Values)
  4159. {
  4160. controls[i++] = new ControllerData(c.objectID, c.itemID, (uint)c.ignoreControls, (uint)c.eventControls);
  4161. }
  4162. cAgent.Controllers = controls;
  4163. }
  4164. // Animations
  4165. try
  4166. {
  4167. cAgent.Anims = Animator.Animations.ToArray();
  4168. }
  4169. catch { }
  4170. cAgent.DefaultAnim = Animator.Animations.DefaultAnimation;
  4171. cAgent.AnimState = Animator.Animations.ImplicitDefaultAnimation;
  4172. cAgent.MovementAnimationOverRides = Overrides.CloneAOPairs();
  4173. cAgent.MotionState = (byte)Animator.currentControlState;
  4174. if (Scene.AttachmentsModule != null)
  4175. Scene.AttachmentsModule.CopyAttachments(this, cAgent);
  4176. if(isCrossUpdate)
  4177. {
  4178. cAgent.CrossingFlags = m_crossingFlags;
  4179. cAgent.CrossingFlags |= 1;
  4180. cAgent.CrossExtraFlags = 0;
  4181. if((LastCommands & ScriptControlled.CONTROL_LBUTTON) != 0)
  4182. cAgent.CrossExtraFlags |= 1;
  4183. if((LastCommands & ScriptControlled.CONTROL_ML_LBUTTON) != 0)
  4184. cAgent.CrossExtraFlags |= 2;
  4185. }
  4186. else
  4187. cAgent.CrossingFlags = 0;
  4188. if(isCrossUpdate)
  4189. {
  4190. cAgent.agentCOF = COF;
  4191. cAgent.ActiveGroupID = ControllingClient.ActiveGroupId;
  4192. cAgent.ActiveGroupName = ControllingClient.ActiveGroupName;
  4193. if(Grouptitle == null)
  4194. cAgent.ActiveGroupTitle = String.Empty;
  4195. else
  4196. cAgent.ActiveGroupTitle = Grouptitle;
  4197. }
  4198. }
  4199. private void CopyFrom(AgentData cAgent)
  4200. {
  4201. m_callbackURI = cAgent.CallbackURI;
  4202. m_newCallbackURI = cAgent.NewCallbackURI;
  4203. // m_log.DebugFormat(
  4204. // "[SCENE PRESENCE]: Set callback for {0} in {1} to {2} in CopyFrom()",
  4205. // Name, m_scene.RegionInfo.RegionName, m_callbackURI);
  4206. GodController.SetState(cAgent.GodData);
  4207. m_pos = cAgent.Position;
  4208. m_velocity = cAgent.Velocity;
  4209. CameraPosition = cAgent.Center;
  4210. CameraAtAxis = cAgent.AtAxis;
  4211. CameraLeftAxis = cAgent.LeftAxis;
  4212. CameraUpAxis = cAgent.UpAxis;
  4213. Quaternion camRot = Util.Axes2Rot(CameraAtAxis, CameraLeftAxis, CameraUpAxis);
  4214. CameraRotation = camRot;
  4215. ParentUUID = cAgent.ParentPart;
  4216. PrevSitOffset = cAgent.SitOffset;
  4217. // When we get to the point of re-computing neighbors everytime this
  4218. // changes, then start using the agent's drawdistance rather than the
  4219. // region's draw distance.
  4220. DrawDistance = cAgent.Far;
  4221. //DrawDistance = Scene.DefaultDrawDistance;
  4222. if (cAgent.ChildrenCapSeeds != null && cAgent.ChildrenCapSeeds.Count > 0)
  4223. {
  4224. if (Scene.CapsModule != null)
  4225. {
  4226. Scene.CapsModule.SetChildrenSeed(UUID, cAgent.ChildrenCapSeeds);
  4227. }
  4228. KnownRegions = cAgent.ChildrenCapSeeds;
  4229. }
  4230. if ((cAgent.Throttles != null) && cAgent.Throttles.Length > 0)
  4231. ControllingClient.SetChildAgentThrottle(cAgent.Throttles);
  4232. m_headrotation = cAgent.HeadRotation;
  4233. Rotation = cAgent.BodyRotation;
  4234. m_AgentControlFlags = (AgentManager.ControlFlags)cAgent.ControlFlags;
  4235. SetAlwaysRun = cAgent.AlwaysRun;
  4236. Appearance = new AvatarAppearance(cAgent.Appearance);
  4237. /*
  4238. bool isFlying = ((m_AgentControlFlags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  4239. if (PhysicsActor != null)
  4240. {
  4241. RemoveFromPhysicalScene();
  4242. AddToPhysicalScene(isFlying);
  4243. }
  4244. */
  4245. if (Scene.AttachmentsModule != null)
  4246. Scene.AttachmentsModule.CopyAttachments(cAgent, this);
  4247. try
  4248. {
  4249. lock (scriptedcontrols)
  4250. {
  4251. if (cAgent.Controllers != null)
  4252. {
  4253. scriptedcontrols.Clear();
  4254. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  4255. foreach (ControllerData c in cAgent.Controllers)
  4256. {
  4257. ScriptControllers sc = new ScriptControllers();
  4258. sc.objectID = c.ObjectID;
  4259. sc.itemID = c.ItemID;
  4260. sc.ignoreControls = (ScriptControlled)c.IgnoreControls;
  4261. sc.eventControls = (ScriptControlled)c.EventControls;
  4262. scriptedcontrols[sc.itemID] = sc;
  4263. IgnoredControls |= sc.ignoreControls; // this is not correct, aparently only last applied should count
  4264. }
  4265. }
  4266. }
  4267. }
  4268. catch { }
  4269. // we are losing animator somewhere
  4270. if (Animator == null)
  4271. Animator = new ScenePresenceAnimator(this);
  4272. else
  4273. Animator.ResetAnimations();
  4274. Overrides.CopyAOPairsFrom(cAgent.MovementAnimationOverRides);
  4275. int nanim = ControllingClient.NextAnimationSequenceNumber;
  4276. // FIXME: Why is this null check necessary? Where are the cases where we get a null Anims object?
  4277. if (cAgent.DefaultAnim != null)
  4278. {
  4279. if (cAgent.DefaultAnim.SequenceNum > nanim)
  4280. nanim = cAgent.DefaultAnim.SequenceNum;
  4281. Animator.Animations.SetDefaultAnimation(cAgent.DefaultAnim.AnimID, cAgent.DefaultAnim.SequenceNum, UUID.Zero);
  4282. }
  4283. if (cAgent.AnimState != null)
  4284. {
  4285. if (cAgent.AnimState.SequenceNum > nanim)
  4286. nanim = cAgent.AnimState.SequenceNum;
  4287. Animator.Animations.SetImplicitDefaultAnimation(cAgent.AnimState.AnimID, cAgent.AnimState.SequenceNum, UUID.Zero);
  4288. }
  4289. if (cAgent.Anims != null)
  4290. {
  4291. int canim = Animator.Animations.FromArray(cAgent.Anims);
  4292. if(canim > nanim)
  4293. nanim = canim;
  4294. }
  4295. ControllingClient.NextAnimationSequenceNumber = ++nanim;
  4296. if (cAgent.MotionState != 0)
  4297. Animator.currentControlState = (ScenePresenceAnimator.motionControlStates) cAgent.MotionState;
  4298. m_crossingFlags = cAgent.CrossingFlags;
  4299. m_gotCrossUpdate = (m_crossingFlags != 0);
  4300. if(m_gotCrossUpdate)
  4301. {
  4302. LastCommands &= ~(ScriptControlled.CONTROL_LBUTTON | ScriptControlled.CONTROL_ML_LBUTTON);
  4303. if((cAgent.CrossExtraFlags & 1) != 0)
  4304. LastCommands |= ScriptControlled.CONTROL_LBUTTON;
  4305. if((cAgent.CrossExtraFlags & 2) != 0)
  4306. LastCommands |= ScriptControlled.CONTROL_ML_LBUTTON;
  4307. MouseDown = (cAgent.CrossExtraFlags & 3) != 0;
  4308. }
  4309. m_haveGroupInformation = false;
  4310. // using this as protocol detection don't want to mess with the numbers for now
  4311. if(cAgent.ActiveGroupTitle != null)
  4312. {
  4313. m_haveGroupInformation = true;
  4314. COF = cAgent.agentCOF;
  4315. if(ControllingClient.IsGroupMember(cAgent.ActiveGroupID))
  4316. {
  4317. ControllingClient.ActiveGroupId = cAgent.ActiveGroupID;
  4318. ControllingClient.ActiveGroupName = cAgent.ActiveGroupName;
  4319. Grouptitle = cAgent.ActiveGroupTitle;
  4320. ControllingClient.ActiveGroupPowers =
  4321. ControllingClient.GetGroupPowers(cAgent.ActiveGroupID);
  4322. }
  4323. else
  4324. {
  4325. // we got a unknown active group so get what groups thinks about us
  4326. IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  4327. if (gm != null)
  4328. gm.SendAgentGroupDataUpdate(ControllingClient);
  4329. }
  4330. }
  4331. lock (m_originRegionIDAccessLock)
  4332. m_originRegionID = cAgent.RegionID;
  4333. }
  4334. public bool CopyAgent(out IAgentData agent)
  4335. {
  4336. agent = new CompleteAgentData();
  4337. CopyTo((AgentData)agent, false);
  4338. return true;
  4339. }
  4340. #endregion Child Agent Updates
  4341. /// <summary>
  4342. /// Handles part of the PID controller function for moving an avatar.
  4343. /// </summary>
  4344. public void UpdateMovement()
  4345. {
  4346. /*
  4347. if (IsInTransit)
  4348. return;
  4349. lock(m_forceToApplyLock)
  4350. {
  4351. if (m_forceToApplyValid)
  4352. {
  4353. Velocity = m_forceToApply;
  4354. m_forceToApplyValid = false;
  4355. TriggerScenePresenceUpdated();
  4356. }
  4357. }
  4358. */
  4359. }
  4360. /// <summary>
  4361. /// Adds a physical representation of the avatar to the Physics plugin
  4362. /// </summary>
  4363. public void AddToPhysicalScene(bool isFlying)
  4364. {
  4365. // m_log.DebugFormat(
  4366. // "[SCENE PRESENCE]: Adding physics actor for {0}, ifFlying = {1} in {2}",
  4367. // Name, isFlying, Scene.RegionInfo.RegionName);
  4368. if (PhysicsActor != null)
  4369. {
  4370. m_log.ErrorFormat(
  4371. "[SCENE PRESENCE]: Adding physics actor for {0} to {1} but this scene presence already has a physics actor",
  4372. Name, Scene.RegionInfo.RegionName);
  4373. }
  4374. if (Appearance.AvatarHeight == 0)
  4375. // Appearance.SetHeight();
  4376. Appearance.SetSize(new Vector3(0.45f,0.6f,1.9f));
  4377. // lock(m_forceToApplyLock)
  4378. // m_forceToApplyValid = false;
  4379. PhysicsScene scene = m_scene.PhysicsScene;
  4380. Vector3 pVec = AbsolutePosition;
  4381. PhysicsActor pa = scene.AddAvatar(
  4382. LocalId, Firstname + "." + Lastname, pVec,
  4383. Appearance.AvatarBoxSize,Appearance.AvatarFeetOffset, isFlying);
  4384. pa.Orientation = m_bodyRot;
  4385. //PhysicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients;
  4386. pa.OnCollisionUpdate += PhysicsCollisionUpdate;
  4387. pa.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong
  4388. pa.SubscribeEvents(100);
  4389. pa.LocalID = LocalId;
  4390. pa.SetAlwaysRun = m_setAlwaysRun;
  4391. PhysicsActor = pa;
  4392. }
  4393. private void OutOfBoundsCall(Vector3 pos)
  4394. {
  4395. //bool flying = Flying;
  4396. //RemoveFromPhysicalScene();
  4397. //AddToPhysicalScene(flying);
  4398. if (ControllingClient != null)
  4399. ControllingClient.SendAgentAlertMessage("Physics is having a problem with your avatar. You may not be able to move until you relog.", true);
  4400. }
  4401. /// <summary>
  4402. /// Event called by the physics plugin to tell the avatar about a collision.
  4403. /// </summary>
  4404. /// <remarks>
  4405. /// This function is called continuously, even when there are no collisions. If the avatar is walking on the
  4406. /// ground or a prim then there will be collision information between the avatar and the surface.
  4407. ///
  4408. /// FIXME: However, we can't safely avoid calling this yet where there are no collisions without analyzing whether
  4409. /// any part of this method is relying on an every-frame call.
  4410. /// </remarks>
  4411. /// <param name="e"></param>
  4412. public void PhysicsCollisionUpdate(EventArgs e)
  4413. {
  4414. if (IsChildAgent)
  4415. return;
  4416. if(IsInTransit)
  4417. return;
  4418. //if ((Math.Abs(Velocity.X) > 0.1e-9f) || (Math.Abs(Velocity.Y) > 0.1e-9f))
  4419. // The Physics Scene will send updates every 500 ms grep: PhysicsActor.SubscribeEvents(
  4420. // as of this comment the interval is set in AddToPhysicalScene
  4421. // if (m_updateCount > 0)
  4422. // {
  4423. // if (Animator != null && Animator.UpdateMovementAnimations())
  4424. // TriggerScenePresenceUpdated();
  4425. // m_updateCount--;
  4426. // }
  4427. CollisionEventUpdate collisionData = (CollisionEventUpdate)e;
  4428. Dictionary<uint, ContactPoint> coldata = collisionData.m_objCollisionList;
  4429. // // No collisions at all means we may be flying. Update always
  4430. // // to make falling work
  4431. // if (m_lastColCount != coldata.Count || coldata.Count == 0)
  4432. // {
  4433. // m_updateCount = UPDATE_COUNT;
  4434. // m_lastColCount = coldata.Count;
  4435. // }
  4436. if (coldata.Count != 0)
  4437. {
  4438. ContactPoint lowest;
  4439. lowest.SurfaceNormal = Vector3.Zero;
  4440. lowest.Position = Vector3.Zero;
  4441. lowest.Position.Z = float.MaxValue;
  4442. foreach (ContactPoint contact in coldata.Values)
  4443. {
  4444. if (contact.CharacterFeet && contact.Position.Z < lowest.Position.Z)
  4445. lowest = contact;
  4446. }
  4447. if (lowest.Position.Z != float.MaxValue)
  4448. {
  4449. lowest.SurfaceNormal = -lowest.SurfaceNormal;
  4450. CollisionPlane = new Vector4(lowest.SurfaceNormal, Vector3.Dot(lowest.Position, lowest.SurfaceNormal));
  4451. }
  4452. else
  4453. CollisionPlane = Vector4.UnitW;
  4454. }
  4455. else
  4456. CollisionPlane = Vector4.UnitW;
  4457. RaiseCollisionScriptEvents(coldata);
  4458. // Gods do not take damage and Invulnerable is set depending on parcel/region flags
  4459. if (Invulnerable || IsViewerUIGod)
  4460. return;
  4461. // The following may be better in the ICombatModule
  4462. // probably tweaking of the values for ground and normal prim collisions will be needed
  4463. float startHealth = Health;
  4464. if(coldata.Count > 0)
  4465. {
  4466. uint killerObj = 0;
  4467. SceneObjectPart part = null;
  4468. float rvel; // relative velocity, negative on approch
  4469. foreach (uint localid in coldata.Keys)
  4470. {
  4471. if (localid == 0)
  4472. {
  4473. // 0 is the ground
  4474. rvel = coldata[0].RelativeSpeed;
  4475. if(rvel < -5.0f)
  4476. Health -= 0.01f * rvel * rvel;
  4477. }
  4478. else
  4479. {
  4480. part = Scene.GetSceneObjectPart(localid);
  4481. if(part != null && !part.ParentGroup.IsVolumeDetect)
  4482. {
  4483. if (part.ParentGroup.Damage > 0.0f)
  4484. {
  4485. // Something with damage...
  4486. Health -= part.ParentGroup.Damage;
  4487. part.ParentGroup.Scene.DeleteSceneObject(part.ParentGroup, false);
  4488. }
  4489. else
  4490. {
  4491. // An ordinary prim
  4492. rvel = coldata[localid].RelativeSpeed;
  4493. if(rvel < -5.0f)
  4494. {
  4495. Health -= 0.005f * rvel * rvel;
  4496. }
  4497. }
  4498. }
  4499. else
  4500. {
  4501. }
  4502. }
  4503. if (Health <= 0.0f)
  4504. {
  4505. if (localid != 0)
  4506. killerObj = localid;
  4507. }
  4508. }
  4509. if (Health <= 0)
  4510. {
  4511. ControllingClient.SendHealth(Health);
  4512. m_scene.EventManager.TriggerAvatarKill(killerObj, this);
  4513. return;
  4514. }
  4515. }
  4516. if(Math.Abs(Health - startHealth) > 1.0)
  4517. ControllingClient.SendHealth(Health);
  4518. }
  4519. public void setHealthWithUpdate(float health)
  4520. {
  4521. Health = health;
  4522. ControllingClient.SendHealth(Health);
  4523. }
  4524. protected internal void Close()
  4525. {
  4526. // Clear known regions
  4527. KnownRegions = new Dictionary<ulong, string>();
  4528. // I don't get it but mono crashes when you try to dispose of this timer,
  4529. // unsetting the elapsed callback should be enough to allow for cleanup however.
  4530. // m_reprioritizationTimer.Dispose();
  4531. RemoveFromPhysicalScene();
  4532. m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
  4533. RemoveClientEvents();
  4534. // if (Animator != null)
  4535. // Animator.Close();
  4536. Animator = null;
  4537. scriptedcontrols.Clear();
  4538. ControllingClient = null;
  4539. LifecycleState = ScenePresenceState.Removed;
  4540. IsDeleted = true;
  4541. m_updateAgentReceivedAfterTransferEvent.Dispose();
  4542. m_updateAgentReceivedAfterTransferEvent = null;
  4543. }
  4544. public void AddAttachment(SceneObjectGroup gobj)
  4545. {
  4546. lock (m_attachments)
  4547. {
  4548. // This may be true when the attachment comes back
  4549. // from serialization after login. Clear it.
  4550. gobj.IsDeleted = false;
  4551. m_attachments.Add(gobj);
  4552. }
  4553. IBakedTextureModule bakedModule = m_scene.RequestModuleInterface<IBakedTextureModule>();
  4554. if (bakedModule != null)
  4555. bakedModule.UpdateMeshAvatar(m_uuid);
  4556. }
  4557. public int GetAttachmentsCount()
  4558. {
  4559. return m_attachments.Count;
  4560. }
  4561. /// <summary>
  4562. /// Get all the presence's attachments.
  4563. /// </summary>
  4564. /// <returns>A copy of the list which contains the attachments.</returns>
  4565. public List<SceneObjectGroup> GetAttachments()
  4566. {
  4567. lock (m_attachments)
  4568. return new List<SceneObjectGroup>(m_attachments);
  4569. }
  4570. /// <summary>
  4571. /// Get the scene objects attached to the given point.
  4572. /// </summary>
  4573. /// <param name="attachmentPoint"></param>
  4574. /// <returns>Returns an empty list if there were no attachments at the point.</returns>
  4575. public List<SceneObjectGroup> GetAttachments(uint attachmentPoint)
  4576. {
  4577. List<SceneObjectGroup> attachments = new List<SceneObjectGroup>();
  4578. if (attachmentPoint >= 0)
  4579. {
  4580. lock (m_attachments)
  4581. {
  4582. foreach (SceneObjectGroup so in m_attachments)
  4583. {
  4584. if (attachmentPoint == so.AttachmentPoint)
  4585. attachments.Add(so);
  4586. }
  4587. }
  4588. }
  4589. return attachments;
  4590. }
  4591. public bool HasAttachments()
  4592. {
  4593. lock (m_attachments)
  4594. return m_attachments.Count > 0;
  4595. }
  4596. /// <summary>
  4597. /// Returns the total count of scripts in all parts inventories.
  4598. /// </summary>
  4599. public int ScriptCount()
  4600. {
  4601. int count = 0;
  4602. lock (m_attachments)
  4603. {
  4604. foreach (SceneObjectGroup gobj in m_attachments)
  4605. {
  4606. if (gobj != null)
  4607. {
  4608. count += gobj.ScriptCount();
  4609. }
  4610. }
  4611. }
  4612. return count;
  4613. }
  4614. /// <summary>
  4615. /// A float the value is a representative execution time in milliseconds of all scripts in all attachments.
  4616. /// </summary>
  4617. public float ScriptExecutionTime()
  4618. {
  4619. float time = 0.0f;
  4620. lock (m_attachments)
  4621. {
  4622. foreach (SceneObjectGroup gobj in m_attachments)
  4623. {
  4624. if (gobj != null)
  4625. {
  4626. time += gobj.ScriptExecutionTime();
  4627. }
  4628. }
  4629. }
  4630. return time;
  4631. }
  4632. /// <summary>
  4633. /// Returns the total count of running scripts in all parts.
  4634. /// </summary>
  4635. public int RunningScriptCount()
  4636. {
  4637. int count = 0;
  4638. lock (m_attachments)
  4639. {
  4640. foreach (SceneObjectGroup gobj in m_attachments)
  4641. {
  4642. if (gobj != null)
  4643. {
  4644. count += gobj.RunningScriptCount();
  4645. }
  4646. }
  4647. }
  4648. return count;
  4649. }
  4650. public bool HasScriptedAttachments()
  4651. {
  4652. lock (m_attachments)
  4653. {
  4654. foreach (SceneObjectGroup gobj in m_attachments)
  4655. {
  4656. if (gobj != null)
  4657. {
  4658. if (gobj.RootPart.Inventory.ContainsScripts())
  4659. return true;
  4660. }
  4661. }
  4662. }
  4663. return false;
  4664. }
  4665. public void RemoveAttachment(SceneObjectGroup gobj)
  4666. {
  4667. lock (m_attachments)
  4668. m_attachments.Remove(gobj);
  4669. }
  4670. /// <summary>
  4671. /// Clear all attachments
  4672. /// </summary>
  4673. public void ClearAttachments()
  4674. {
  4675. lock (m_attachments)
  4676. m_attachments.Clear();
  4677. }
  4678. /// <summary>
  4679. /// This is currently just being done for information.
  4680. /// </summary>
  4681. public bool ValidateAttachments()
  4682. {
  4683. bool validated = true;
  4684. lock (m_attachments)
  4685. {
  4686. // Validate
  4687. foreach (SceneObjectGroup gobj in m_attachments)
  4688. {
  4689. if (gobj == null)
  4690. {
  4691. m_log.WarnFormat(
  4692. "[SCENE PRESENCE]: Failed to validate an attachment for {0} since it was null. Continuing", Name);
  4693. validated = false;
  4694. }
  4695. else if (gobj.IsDeleted)
  4696. {
  4697. m_log.WarnFormat(
  4698. "[SCENE PRESENCE]: Failed to validate attachment {0} {1} for {2} since it had been deleted. Continuing",
  4699. gobj.Name, gobj.UUID, Name);
  4700. validated = false;
  4701. }
  4702. }
  4703. }
  4704. return validated;
  4705. }
  4706. /*
  4707. public void SendAttachmentsToAllAgents()
  4708. {
  4709. lock (m_attachments)
  4710. {
  4711. foreach (SceneObjectGroup sog in m_attachments)
  4712. {
  4713. m_scene.ForEachScenePresence(delegate(ScenePresence p)
  4714. {
  4715. if (p != this && sog.HasPrivateAttachmentPoint)
  4716. return;
  4717. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  4718. return;
  4719. SendTerseUpdateToAgentNF(p);
  4720. SendAttachmentFullUpdateToAgentNF(sog, p);
  4721. });
  4722. }
  4723. }
  4724. }
  4725. */
  4726. // send attachments to a client without filters except for huds
  4727. // for now they are checked in several places down the line...
  4728. public void SendAttachmentsToAgentNF(ScenePresence p)
  4729. {
  4730. SendTerseUpdateToAgentNF(p);
  4731. // SendAvatarDataToAgentNF(this);
  4732. lock (m_attachments)
  4733. {
  4734. foreach (SceneObjectGroup sog in m_attachments)
  4735. {
  4736. SendAttachmentFullUpdateToAgentNF(sog, p);
  4737. }
  4738. }
  4739. }
  4740. public void SendAttachmentFullUpdateToAgentNF(SceneObjectGroup sog, ScenePresence p)
  4741. {
  4742. if (p != this && sog.HasPrivateAttachmentPoint)
  4743. return;
  4744. SceneObjectPart[] parts = sog.Parts;
  4745. SceneObjectPart rootpart = sog.RootPart;
  4746. PrimUpdateFlags update = PrimUpdateFlags.FullUpdate;
  4747. if (rootpart.Shape.MeshFlagEntry)
  4748. update = PrimUpdateFlags.FullUpdatewithAnim;
  4749. p.ControllingClient.SendEntityUpdate(rootpart, update);
  4750. for (int i = 0; i < parts.Length; i++)
  4751. {
  4752. SceneObjectPart part = parts[i];
  4753. if (part == rootpart)
  4754. continue;
  4755. p.ControllingClient.SendEntityUpdate(part, update);
  4756. }
  4757. }
  4758. public void SendAttachmentScheduleUpdate(SceneObjectGroup sog)
  4759. {
  4760. if (IsChildAgent || IsInTransit)
  4761. return;
  4762. SceneObjectPart[] origparts = sog.Parts;
  4763. SceneObjectPart[] parts = new SceneObjectPart[origparts.Length];
  4764. PrimUpdateFlags[] flags = new PrimUpdateFlags[origparts.Length];
  4765. SceneObjectPart rootpart = sog.RootPart;
  4766. PrimUpdateFlags cur = sog.RootPart.GetAndClearUpdateFlag();
  4767. bool noanim = !rootpart.Shape.MeshFlagEntry;
  4768. int nparts = 0;
  4769. if (noanim || rootpart.Animations == null)
  4770. cur &= ~PrimUpdateFlags.Animations;
  4771. if (cur != PrimUpdateFlags.None)
  4772. {
  4773. flags[nparts] = cur;
  4774. parts[nparts] = rootpart;
  4775. ++nparts;
  4776. }
  4777. for (int i = 0; i < origparts.Length; i++)
  4778. {
  4779. if (origparts[i] == rootpart)
  4780. continue;
  4781. cur = origparts[i].GetAndClearUpdateFlag();
  4782. if (noanim || origparts[i].Animations == null)
  4783. cur &= ~PrimUpdateFlags.Animations;
  4784. if (cur == PrimUpdateFlags.None)
  4785. continue;
  4786. flags[nparts] = cur;
  4787. parts[nparts] = origparts[i];
  4788. ++nparts;
  4789. }
  4790. if (nparts == 0)
  4791. return;
  4792. for (int i = 0; i < nparts; i++)
  4793. ControllingClient.SendEntityUpdate(parts[i], flags[i]);
  4794. if (sog.HasPrivateAttachmentPoint)
  4795. return;
  4796. List<ScenePresence> allPresences = m_scene.GetScenePresences();
  4797. foreach (ScenePresence p in allPresences)
  4798. {
  4799. if (p == this)
  4800. continue;
  4801. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  4802. continue;
  4803. for (int i = 0; i < nparts; i++)
  4804. p.ControllingClient.SendEntityUpdate(parts[i], flags[i]);
  4805. }
  4806. }
  4807. public void SendAttachmentUpdate(SceneObjectGroup sog, PrimUpdateFlags update)
  4808. {
  4809. if (IsChildAgent || IsInTransit)
  4810. return;
  4811. SceneObjectPart[] origparts = sog.Parts;
  4812. SceneObjectPart[] parts = new SceneObjectPart[origparts.Length];
  4813. PrimUpdateFlags[] flags = new PrimUpdateFlags[origparts.Length];
  4814. SceneObjectPart rootpart = sog.RootPart;
  4815. bool noanim = !rootpart.Shape.MeshFlagEntry;
  4816. int nparts = 0;
  4817. PrimUpdateFlags cur = update;
  4818. if (noanim || rootpart.Animations == null)
  4819. cur &= ~PrimUpdateFlags.Animations;
  4820. if (cur != PrimUpdateFlags.None)
  4821. {
  4822. flags[nparts] = cur;
  4823. parts[nparts] = rootpart;
  4824. ++nparts;
  4825. }
  4826. for (int i = 0; i < origparts.Length; i++)
  4827. {
  4828. if (origparts[i] == rootpart)
  4829. continue;
  4830. cur = update;
  4831. if (noanim || origparts[i].Animations == null)
  4832. cur &= ~PrimUpdateFlags.Animations;
  4833. if (cur == PrimUpdateFlags.None)
  4834. continue;
  4835. flags[nparts] = cur;
  4836. parts[nparts] = origparts[i];
  4837. ++nparts;
  4838. }
  4839. if (nparts == 0)
  4840. return;
  4841. for(int i = 0; i < nparts; i++)
  4842. ControllingClient.SendEntityUpdate(parts[i], flags[i]);
  4843. if (sog.HasPrivateAttachmentPoint)
  4844. return;
  4845. List<ScenePresence> allPresences = m_scene.GetScenePresences();
  4846. foreach (ScenePresence p in allPresences)
  4847. {
  4848. if (p == this)
  4849. continue;
  4850. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  4851. continue;
  4852. p.ControllingClient.SendEntityUpdate(rootpart, update);
  4853. for (int i = 0; i < nparts; i++)
  4854. p.ControllingClient.SendEntityUpdate(parts[i], flags[i]);
  4855. }
  4856. }
  4857. public void SendAttachmentUpdate(SceneObjectPart part, PrimUpdateFlags update)
  4858. {
  4859. if (IsChildAgent || IsInTransit)
  4860. return;
  4861. if ((update & PrimUpdateFlags.Animations) != 0 && part.Animations == null)
  4862. {
  4863. update &= ~PrimUpdateFlags.Animations;
  4864. if (update == PrimUpdateFlags.None)
  4865. return;
  4866. }
  4867. ControllingClient.SendEntityUpdate(part, update);
  4868. if (part.ParentGroup.HasPrivateAttachmentPoint)
  4869. return;
  4870. List<ScenePresence> allPresences = m_scene.GetScenePresences();
  4871. foreach (ScenePresence p in allPresences)
  4872. {
  4873. if (p == this)
  4874. continue;
  4875. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  4876. continue;
  4877. p.ControllingClient.SendEntityUpdate(part, update);
  4878. }
  4879. }
  4880. /// <summary>
  4881. /// Send a script event to this scene presence's attachments
  4882. /// </summary>
  4883. /// <param name="eventName">The name of the event</param>
  4884. /// <param name="args">The arguments for the event</param>
  4885. public void SendScriptEventToAttachments(string eventName, Object[] args)
  4886. {
  4887. Util.FireAndForget(delegate(object x)
  4888. {
  4889. if (m_scriptEngines.Length == 0)
  4890. return;
  4891. lock (m_attachments)
  4892. {
  4893. foreach (SceneObjectGroup grp in m_attachments)
  4894. {
  4895. // 16384 is CHANGED_ANIMATION
  4896. //
  4897. // Send this to all attachment root prims
  4898. //
  4899. foreach (IScriptModule m in m_scriptEngines)
  4900. {
  4901. if (m == null) // No script engine loaded
  4902. continue;
  4903. m.PostObjectEvent(grp.RootPart.UUID, "changed", new Object[] { (int)Changed.ANIMATION });
  4904. }
  4905. }
  4906. }
  4907. }, null, "ScenePresence.SendScriptEventToAttachments");
  4908. }
  4909. /// <summary>
  4910. /// Gets the mass.
  4911. /// </summary>
  4912. /// <returns>
  4913. /// The mass.
  4914. /// </returns>
  4915. public float GetMass()
  4916. {
  4917. PhysicsActor pa = PhysicsActor;
  4918. if (pa != null)
  4919. return pa.Mass;
  4920. else
  4921. return 0;
  4922. }
  4923. internal void PushForce(Vector3 impulse)
  4924. {
  4925. if (PhysicsActor != null)
  4926. {
  4927. PhysicsActor.AddForce(impulse,true);
  4928. }
  4929. }
  4930. CameraData physActor_OnPhysicsRequestingCameraData()
  4931. {
  4932. return new CameraData
  4933. {
  4934. Valid = true,
  4935. MouseLook = this.m_mouseLook,
  4936. CameraRotation = this.CameraRotation,
  4937. CameraAtAxis = this.CameraAtAxis
  4938. };
  4939. }
  4940. public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID)
  4941. {
  4942. SceneObjectPart part = m_scene.GetSceneObjectPart(Obj_localID);
  4943. if (part == null)
  4944. return;
  4945. ControllingClient.SendTakeControls(controls, false, false);
  4946. ControllingClient.SendTakeControls(controls, true, false);
  4947. ScriptControllers obj = new ScriptControllers();
  4948. obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
  4949. obj.eventControls = ScriptControlled.CONTROL_ZERO;
  4950. obj.objectID = part.ParentGroup.UUID;
  4951. obj.itemID = Script_item_UUID;
  4952. if (pass_on == 0 && accept == 0)
  4953. {
  4954. IgnoredControls |= (ScriptControlled)controls;
  4955. obj.ignoreControls = (ScriptControlled)controls;
  4956. }
  4957. if (pass_on == 0 && accept == 1)
  4958. {
  4959. IgnoredControls |= (ScriptControlled)controls;
  4960. obj.ignoreControls = (ScriptControlled)controls;
  4961. obj.eventControls = (ScriptControlled)controls;
  4962. }
  4963. if (pass_on == 1 && accept == 1)
  4964. {
  4965. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  4966. obj.eventControls = (ScriptControlled)controls;
  4967. obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
  4968. }
  4969. lock (scriptedcontrols)
  4970. {
  4971. if (pass_on == 1 && accept == 0)
  4972. {
  4973. IgnoredControls &= ~(ScriptControlled)controls;
  4974. if (scriptedcontrols.ContainsKey(Script_item_UUID))
  4975. RemoveScriptFromControlNotifications(Script_item_UUID, part);
  4976. }
  4977. else
  4978. {
  4979. AddScriptToControlNotifications(Script_item_UUID, part, ref obj);
  4980. }
  4981. }
  4982. ControllingClient.SendTakeControls(controls, pass_on == 1 ? true : false, true);
  4983. }
  4984. private void AddScriptToControlNotifications(OpenMetaverse.UUID Script_item_UUID, SceneObjectPart part, ref ScriptControllers obj)
  4985. {
  4986. scriptedcontrols[Script_item_UUID] = obj;
  4987. PhysicsActor physActor = part.ParentGroup.RootPart.PhysActor;
  4988. if (physActor != null)
  4989. {
  4990. physActor.OnPhysicsRequestingCameraData -= physActor_OnPhysicsRequestingCameraData;
  4991. physActor.OnPhysicsRequestingCameraData += physActor_OnPhysicsRequestingCameraData;
  4992. }
  4993. }
  4994. private void RemoveScriptFromControlNotifications(OpenMetaverse.UUID Script_item_UUID, SceneObjectPart part)
  4995. {
  4996. scriptedcontrols.Remove(Script_item_UUID);
  4997. if (part != null)
  4998. {
  4999. PhysicsActor physActor = part.ParentGroup.RootPart.PhysActor;
  5000. if (physActor != null)
  5001. {
  5002. physActor.OnPhysicsRequestingCameraData -= physActor_OnPhysicsRequestingCameraData;
  5003. }
  5004. }
  5005. }
  5006. public void HandleForceReleaseControls(IClientAPI remoteClient, UUID agentID)
  5007. {
  5008. foreach (ScriptControllers c in scriptedcontrols.Values)
  5009. {
  5010. SceneObjectGroup sog = m_scene.GetSceneObjectGroup(c.objectID);
  5011. if(sog != null && !sog.IsDeleted && sog.RootPart.PhysActor != null)
  5012. sog.RootPart.PhysActor.OnPhysicsRequestingCameraData -= physActor_OnPhysicsRequestingCameraData;
  5013. }
  5014. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  5015. lock (scriptedcontrols)
  5016. {
  5017. scriptedcontrols.Clear();
  5018. }
  5019. ControllingClient.SendTakeControls(int.MaxValue, false, false);
  5020. }
  5021. public void HandleRevokePermissions(UUID objectID, uint permissions )
  5022. {
  5023. // still skeleton code
  5024. if((permissions & (16 | 0x8000 )) == 0) //PERMISSION_TRIGGER_ANIMATION | PERMISSION_OVERRIDE_ANIMATIONS
  5025. return;
  5026. if(objectID == m_scene.RegionInfo.RegionID) // for all objects
  5027. {
  5028. }
  5029. else
  5030. {
  5031. SceneObjectPart part = m_scene.GetSceneObjectPart(objectID);
  5032. if(part != null)
  5033. {
  5034. }
  5035. }
  5036. }
  5037. public void ClearControls()
  5038. {
  5039. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  5040. lock (scriptedcontrols)
  5041. {
  5042. scriptedcontrols.Clear();
  5043. }
  5044. }
  5045. public void UnRegisterSeatControls(UUID obj)
  5046. {
  5047. List<UUID> takers = new List<UUID>();
  5048. foreach (ScriptControllers c in scriptedcontrols.Values)
  5049. {
  5050. if (c.objectID == obj)
  5051. takers.Add(c.itemID);
  5052. }
  5053. foreach (UUID t in takers)
  5054. {
  5055. UnRegisterControlEventsToScript(0, t);
  5056. }
  5057. }
  5058. public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID)
  5059. {
  5060. ScriptControllers takecontrols;
  5061. SceneObjectPart part = m_scene.GetSceneObjectPart(Obj_localID);
  5062. lock (scriptedcontrols)
  5063. {
  5064. if (scriptedcontrols.TryGetValue(Script_item_UUID, out takecontrols))
  5065. {
  5066. ScriptControlled sctc = takecontrols.eventControls;
  5067. ControllingClient.SendTakeControls((int)sctc, false, false);
  5068. ControllingClient.SendTakeControls((int)sctc, true, false);
  5069. RemoveScriptFromControlNotifications(Script_item_UUID, part);
  5070. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  5071. foreach (ScriptControllers scData in scriptedcontrols.Values)
  5072. {
  5073. IgnoredControls |= scData.ignoreControls;
  5074. }
  5075. }
  5076. }
  5077. }
  5078. private void SendControlsToScripts(uint flags)
  5079. {
  5080. // Notify the scripts only after calling UpdateMovementAnimations(), so that if a script
  5081. // (e.g., a walking script) checks which animation is active it will be the correct animation.
  5082. lock (scriptedcontrols)
  5083. {
  5084. if (scriptedcontrols.Count <= 0)
  5085. return;
  5086. ScriptControlled allflags;
  5087. // convert mouse from edge to level
  5088. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP) != 0 ||
  5089. (flags & unchecked((uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_UP)) != 0)
  5090. {
  5091. allflags = ScriptControlled.CONTROL_ZERO;
  5092. }
  5093. else // recover last state of mouse
  5094. allflags = LastCommands & (ScriptControlled.CONTROL_ML_LBUTTON | ScriptControlled.CONTROL_LBUTTON);
  5095. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN) != 0)
  5096. allflags |= ScriptControlled.CONTROL_ML_LBUTTON;
  5097. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0)
  5098. allflags |= ScriptControlled.CONTROL_LBUTTON;
  5099. // find all activated controls, whether the scripts are interested in them or not
  5100. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS) != 0)
  5101. {
  5102. allflags |= ScriptControlled.CONTROL_FWD;
  5103. }
  5104. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG) != 0)
  5105. {
  5106. allflags |= ScriptControlled.CONTROL_BACK;
  5107. }
  5108. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS) != 0)
  5109. {
  5110. allflags |= ScriptControlled.CONTROL_UP;
  5111. }
  5112. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0)
  5113. {
  5114. allflags |= ScriptControlled.CONTROL_DOWN;
  5115. }
  5116. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS) != 0)
  5117. {
  5118. allflags |= ScriptControlled.CONTROL_LEFT;
  5119. }
  5120. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG) != 0)
  5121. {
  5122. allflags |= ScriptControlled.CONTROL_RIGHT;
  5123. }
  5124. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  5125. {
  5126. allflags |= ScriptControlled.CONTROL_ROT_RIGHT;
  5127. }
  5128. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0)
  5129. {
  5130. allflags |= ScriptControlled.CONTROL_ROT_LEFT;
  5131. }
  5132. // optimization; we have to check per script, but if nothing is pressed and nothing changed, we can skip that
  5133. if (allflags != ScriptControlled.CONTROL_ZERO || allflags != LastCommands)
  5134. {
  5135. foreach (KeyValuePair<UUID, ScriptControllers> kvp in scriptedcontrols)
  5136. {
  5137. UUID scriptUUID = kvp.Key;
  5138. ScriptControllers scriptControlData = kvp.Value;
  5139. ScriptControlled localHeld = allflags & scriptControlData.eventControls; // the flags interesting for us
  5140. ScriptControlled localLast = LastCommands & scriptControlData.eventControls; // the activated controls in the last cycle
  5141. ScriptControlled localChange = localHeld ^ localLast; // the changed bits
  5142. if (localHeld != ScriptControlled.CONTROL_ZERO || localChange != ScriptControlled.CONTROL_ZERO)
  5143. {
  5144. // only send if still pressed or just changed
  5145. m_scene.EventManager.TriggerControlEvent(scriptUUID, UUID, (uint)localHeld, (uint)localChange);
  5146. }
  5147. }
  5148. }
  5149. LastCommands = allflags;
  5150. MouseDown = (allflags & (ScriptControlled.CONTROL_ML_LBUTTON | ScriptControlled.CONTROL_LBUTTON)) != 0;
  5151. }
  5152. }
  5153. internal static AgentManager.ControlFlags RemoveIgnoredControls(AgentManager.ControlFlags flags, ScriptControlled ignored)
  5154. {
  5155. if (ignored == ScriptControlled.CONTROL_ZERO)
  5156. return flags;
  5157. if ((ignored & ScriptControlled.CONTROL_BACK) != 0)
  5158. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG);
  5159. if ((ignored & ScriptControlled.CONTROL_FWD) != 0)
  5160. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS | AgentManager.ControlFlags.AGENT_CONTROL_AT_POS);
  5161. if ((ignored & ScriptControlled.CONTROL_DOWN) != 0)
  5162. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG);
  5163. if ((ignored & ScriptControlled.CONTROL_UP) != 0)
  5164. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS | AgentManager.ControlFlags.AGENT_CONTROL_UP_POS);
  5165. if ((ignored & ScriptControlled.CONTROL_LEFT) != 0)
  5166. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS);
  5167. if ((ignored & ScriptControlled.CONTROL_RIGHT) != 0)
  5168. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG | AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG);
  5169. if ((ignored & ScriptControlled.CONTROL_ROT_LEFT) != 0)
  5170. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG);
  5171. if ((ignored & ScriptControlled.CONTROL_ROT_RIGHT) != 0)
  5172. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS);
  5173. if ((ignored & ScriptControlled.CONTROL_ML_LBUTTON) != 0)
  5174. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN);
  5175. if ((ignored & ScriptControlled.CONTROL_LBUTTON) != 0)
  5176. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP | AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN);
  5177. //DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS,
  5178. //DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG,
  5179. //DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS,
  5180. //DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG,
  5181. //DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS,
  5182. //DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG,
  5183. //DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG
  5184. return flags;
  5185. }
  5186. // returns true it local teleport allowed and sets the destiny position into pos
  5187. public bool CheckLocalTPLandingPoint(ref Vector3 pos)
  5188. {
  5189. // Never constrain lures
  5190. if ((TeleportFlags & TeleportFlags.ViaLure) != 0)
  5191. return true;
  5192. if (m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
  5193. return true;
  5194. // do not constrain gods and estate managers
  5195. if(m_scene.Permissions.IsGod(m_uuid) ||
  5196. m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid))
  5197. return true;
  5198. // will teleport to a telehub spawn point or landpoint if that results in getting closer to target
  5199. // if not the local teleport fails.
  5200. float currDistanceSQ = Vector3.DistanceSquared(AbsolutePosition, pos);
  5201. // first check telehub
  5202. UUID TelehubObjectID = m_scene.RegionInfo.RegionSettings.TelehubObject;
  5203. if ( TelehubObjectID != UUID.Zero)
  5204. {
  5205. SceneObjectGroup telehubSOG = m_scene.GetSceneObjectGroup(TelehubObjectID);
  5206. if(telehubSOG != null)
  5207. {
  5208. Vector3 spawnPos;
  5209. float spawnDistSQ;
  5210. SpawnPoint[] spawnPoints = m_scene.RegionInfo.RegionSettings.SpawnPoints().ToArray();
  5211. if(spawnPoints.Length == 0)
  5212. {
  5213. spawnPos = new Vector3(128.0f, 128.0f, pos.Z);
  5214. spawnDistSQ = Vector3.DistanceSquared(spawnPos, pos);
  5215. }
  5216. else
  5217. {
  5218. Vector3 hubPos = telehubSOG.AbsolutePosition;
  5219. Quaternion hubRot = telehubSOG.GroupRotation;
  5220. spawnPos = spawnPoints[0].GetLocation(hubPos, hubRot);
  5221. spawnDistSQ = Vector3.DistanceSquared(spawnPos, pos);
  5222. float testDistSQ;
  5223. Vector3 testSpawnPos;
  5224. for(int i = 1; i< spawnPoints.Length; i++)
  5225. {
  5226. testSpawnPos = spawnPoints[i].GetLocation(hubPos, hubRot);
  5227. testDistSQ = Vector3.DistanceSquared(testSpawnPos, pos);
  5228. if(testDistSQ < spawnDistSQ)
  5229. {
  5230. spawnPos = testSpawnPos;
  5231. spawnDistSQ = testDistSQ;
  5232. }
  5233. }
  5234. }
  5235. if (currDistanceSQ < spawnDistSQ)
  5236. {
  5237. // we are already close
  5238. ControllingClient.SendAlertMessage("Can't teleport closer to destination");
  5239. return false;
  5240. }
  5241. else
  5242. {
  5243. pos = spawnPos;
  5244. return true;
  5245. }
  5246. }
  5247. }
  5248. ILandObject land = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
  5249. if (land.LandData.LandingType != (byte)LandingType.LandingPoint
  5250. || land.LandData.OwnerID == m_uuid)
  5251. return true;
  5252. Vector3 landLocation = land.LandData.UserLocation;
  5253. if(landLocation == Vector3.Zero)
  5254. return true;
  5255. if (currDistanceSQ < Vector3.DistanceSquared(landLocation, pos))
  5256. {
  5257. ControllingClient.SendAlertMessage("Can't teleport closer to destination");
  5258. return false;
  5259. }
  5260. pos = land.LandData.UserLocation;
  5261. return true;
  5262. }
  5263. const TeleportFlags TeleHubTPFlags = TeleportFlags.ViaLogin
  5264. | TeleportFlags.ViaHGLogin | TeleportFlags.ViaLocation;
  5265. private bool CheckAndAdjustTelehub(SceneObjectGroup telehub, ref Vector3 pos, ref bool positionChanged)
  5266. {
  5267. // forcing telehubs on any tp that reachs this
  5268. if ((m_teleportFlags & TeleHubTPFlags) != 0 ||
  5269. (m_scene.TelehubAllowLandmarks == true ? false : ((m_teleportFlags & TeleportFlags.ViaLandmark) != 0 )))
  5270. {
  5271. ILandObject land;
  5272. Vector3 teleHubPosition = telehub.AbsolutePosition;
  5273. SpawnPoint[] spawnPoints = m_scene.RegionInfo.RegionSettings.SpawnPoints().ToArray();
  5274. if(spawnPoints.Length == 0)
  5275. {
  5276. land = m_scene.LandChannel.GetLandObject(teleHubPosition.X,teleHubPosition.Y);
  5277. if(land != null)
  5278. {
  5279. pos = teleHubPosition;
  5280. if(land.IsEitherBannedOrRestricted(UUID))
  5281. return false;
  5282. positionChanged = true;
  5283. return true;
  5284. }
  5285. else
  5286. return false;
  5287. }
  5288. int index;
  5289. int tries;
  5290. bool selected = false;
  5291. bool validhub = false;
  5292. Vector3 spawnPosition;
  5293. Quaternion teleHubRotation = telehub.GroupRotation;
  5294. switch(m_scene.SpawnPointRouting)
  5295. {
  5296. case "random":
  5297. tries = spawnPoints.Length;
  5298. if(tries < 3) // no much sense in random with a few points when there same can have bans
  5299. goto case "sequence";
  5300. do
  5301. {
  5302. index = Util.RandomClass.Next(spawnPoints.Length - 1);
  5303. spawnPosition = spawnPoints[index].GetLocation(teleHubPosition, teleHubRotation);
  5304. land = m_scene.LandChannel.GetLandObject(spawnPosition.X,spawnPosition.Y);
  5305. if(land != null && !land.IsEitherBannedOrRestricted(UUID))
  5306. selected = true;
  5307. } while(selected == false && --tries > 0 );
  5308. if(tries <= 0)
  5309. goto case "sequence";
  5310. pos = spawnPosition;
  5311. return true;
  5312. case "sequence":
  5313. tries = spawnPoints.Length;
  5314. selected = false;
  5315. validhub = false;
  5316. do
  5317. {
  5318. index = m_scene.SpawnPoint();
  5319. spawnPosition = spawnPoints[index].GetLocation(teleHubPosition, teleHubRotation);
  5320. land = m_scene.LandChannel.GetLandObject(spawnPosition.X,spawnPosition.Y);
  5321. if(land != null)
  5322. {
  5323. validhub = true;
  5324. if(land.IsEitherBannedOrRestricted(UUID))
  5325. selected = false;
  5326. else
  5327. selected = true;
  5328. }
  5329. } while(selected == false && --tries > 0);
  5330. if(!validhub)
  5331. return false;
  5332. pos = spawnPosition;
  5333. if(!selected)
  5334. return false;
  5335. positionChanged = true;
  5336. return true;
  5337. default:
  5338. case "closest":
  5339. float distancesq = float.MaxValue;
  5340. int closest = -1;
  5341. validhub = false;
  5342. for(int i = 0; i < spawnPoints.Length; i++)
  5343. {
  5344. spawnPosition = spawnPoints[i].GetLocation(teleHubPosition, teleHubRotation);
  5345. Vector3 offset = spawnPosition - pos;
  5346. float dsq = offset.LengthSquared();
  5347. land = m_scene.LandChannel.GetLandObject(spawnPosition.X,spawnPosition.Y);
  5348. if(land == null)
  5349. continue;
  5350. validhub = true;
  5351. if(land.IsEitherBannedOrRestricted(UUID))
  5352. continue;
  5353. if(dsq >= distancesq)
  5354. continue;
  5355. distancesq = dsq;
  5356. closest = i;
  5357. }
  5358. if(!validhub)
  5359. return false;
  5360. if(closest < 0)
  5361. {
  5362. pos = spawnPoints[0].GetLocation(teleHubPosition, teleHubRotation);
  5363. positionChanged = true;
  5364. return false;
  5365. }
  5366. pos = spawnPoints[closest].GetLocation(teleHubPosition, teleHubRotation);
  5367. positionChanged = true;
  5368. return true;
  5369. }
  5370. }
  5371. return false;
  5372. }
  5373. const TeleportFlags adicionalLandPointFlags = TeleportFlags.ViaLandmark |
  5374. TeleportFlags.ViaLocation | TeleportFlags.ViaHGLogin;
  5375. // Modify landing point based on possible banning, telehubs or parcel restrictions.
  5376. // This is the behavior in OpenSim for a very long time, different from SL
  5377. private bool CheckAndAdjustLandingPoint_OS(ref Vector3 pos, ref Vector3 lookat, ref bool positionChanged)
  5378. {
  5379. string reason;
  5380. // Honor bans
  5381. if (!m_scene.TestLandRestrictions(UUID, out reason, ref pos.X, ref pos.Y))
  5382. return false;
  5383. SceneObjectGroup telehub = null;
  5384. if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null)
  5385. {
  5386. if (!m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
  5387. {
  5388. CheckAndAdjustTelehub(telehub, ref pos, ref positionChanged);
  5389. return true;
  5390. }
  5391. }
  5392. ILandObject land = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
  5393. if (land != null)
  5394. {
  5395. if (Scene.DebugTeleporting)
  5396. TeleportFlagsDebug();
  5397. // If we come in via login, landmark or map, we want to
  5398. // honor landing points. If we come in via Lure, we want
  5399. // to ignore them.
  5400. if ((m_teleportFlags & (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)) ==
  5401. (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID) ||
  5402. (m_teleportFlags & adicionalLandPointFlags) != 0)
  5403. {
  5404. // Don't restrict gods, estate managers, or land owners to
  5405. // the TP point. This behaviour mimics agni.
  5406. if (land.LandData.LandingType == (byte)LandingType.LandingPoint &&
  5407. land.LandData.UserLocation != Vector3.Zero &&
  5408. !IsViewerUIGod &&
  5409. ((land.LandData.OwnerID != m_uuid &&
  5410. !m_scene.Permissions.IsGod(m_uuid) &&
  5411. !m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid)) ||
  5412. (m_teleportFlags & TeleportFlags.ViaLocation) != 0 ||
  5413. (m_teleportFlags & Constants.TeleportFlags.ViaHGLogin) != 0))
  5414. {
  5415. pos = land.LandData.UserLocation;
  5416. positionChanged = true;
  5417. }
  5418. }
  5419. land.SendLandUpdateToClient(ControllingClient);
  5420. }
  5421. return true;
  5422. }
  5423. // Modify landing point based on telehubs or parcel restrictions.
  5424. // This is a behavior coming from AVN, somewhat mimicking SL
  5425. private bool CheckAndAdjustLandingPoint_SL(ref Vector3 pos, ref Vector3 lookat, ref bool positionChanged)
  5426. {
  5427. string reason;
  5428. // dont mess with gods
  5429. if(IsGod)
  5430. return true;
  5431. // respect region owner and managers
  5432. // if(m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid))
  5433. // return true;
  5434. if (!m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
  5435. {
  5436. SceneObjectGroup telehub = null;
  5437. if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null)
  5438. {
  5439. if(CheckAndAdjustTelehub(telehub, ref pos, ref positionChanged))
  5440. return true;
  5441. }
  5442. }
  5443. // Honor bans, actually we don't honour them
  5444. if (!m_scene.TestLandRestrictions(UUID, out reason, ref pos.X, ref pos.Y))
  5445. return false;
  5446. ILandObject land = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
  5447. if (land != null)
  5448. {
  5449. if (Scene.DebugTeleporting)
  5450. TeleportFlagsDebug();
  5451. // If we come in via login, landmark or map, we want to
  5452. // honor landing points. If we come in via Lure, we want
  5453. // to ignore them.
  5454. if ((m_teleportFlags & (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)) ==
  5455. (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)
  5456. || (m_teleportFlags & adicionalLandPointFlags) != 0)
  5457. {
  5458. if (land.LandData.LandingType == (byte)LandingType.LandingPoint &&
  5459. land.LandData.UserLocation != Vector3.Zero )
  5460. // &&
  5461. // land.LandData.OwnerID != m_uuid )
  5462. {
  5463. pos = land.LandData.UserLocation;
  5464. if(land.LandData.UserLookAt != Vector3.Zero)
  5465. lookat = land.LandData.UserLookAt;
  5466. positionChanged = true;
  5467. }
  5468. }
  5469. }
  5470. return true;
  5471. }
  5472. private DetectedObject CreateDetObject(SceneObjectPart obj)
  5473. {
  5474. DetectedObject detobj = new DetectedObject();
  5475. detobj.keyUUID = obj.UUID;
  5476. detobj.nameStr = obj.Name;
  5477. detobj.ownerUUID = obj.OwnerID;
  5478. detobj.posVector = obj.AbsolutePosition;
  5479. detobj.rotQuat = obj.GetWorldRotation();
  5480. detobj.velVector = obj.Velocity;
  5481. detobj.colliderType = 0;
  5482. detobj.groupUUID = obj.GroupID;
  5483. detobj.linkNumber = 0;
  5484. return detobj;
  5485. }
  5486. private DetectedObject CreateDetObject(ScenePresence av)
  5487. {
  5488. DetectedObject detobj = new DetectedObject();
  5489. detobj.keyUUID = av.UUID;
  5490. detobj.nameStr = av.ControllingClient.Name;
  5491. detobj.ownerUUID = av.UUID;
  5492. detobj.posVector = av.AbsolutePosition;
  5493. detobj.rotQuat = av.Rotation;
  5494. detobj.velVector = av.Velocity;
  5495. detobj.colliderType = av.IsNPC ? 0x20 : 0x1; // OpenSim\Region\ScriptEngine\Shared\Helpers.cs
  5496. if(av.IsSatOnObject)
  5497. detobj.colliderType |= 0x4; //passive
  5498. else if(detobj.velVector != Vector3.Zero)
  5499. detobj.colliderType |= 0x2; //active
  5500. detobj.groupUUID = av.ControllingClient.ActiveGroupId;
  5501. detobj.linkNumber = 0;
  5502. return detobj;
  5503. }
  5504. private DetectedObject CreateDetObjectForGround()
  5505. {
  5506. DetectedObject detobj = new DetectedObject();
  5507. detobj.keyUUID = UUID.Zero;
  5508. detobj.nameStr = "";
  5509. detobj.ownerUUID = UUID.Zero;
  5510. detobj.posVector = AbsolutePosition;
  5511. detobj.rotQuat = Quaternion.Identity;
  5512. detobj.velVector = Vector3.Zero;
  5513. detobj.colliderType = 0;
  5514. detobj.groupUUID = UUID.Zero;
  5515. detobj.linkNumber = 0;
  5516. return detobj;
  5517. }
  5518. private ColliderArgs CreateColliderArgs(SceneObjectPart dest, List<uint> colliders)
  5519. {
  5520. ColliderArgs colliderArgs = new ColliderArgs();
  5521. List<DetectedObject> colliding = new List<DetectedObject>();
  5522. foreach (uint localId in colliders)
  5523. {
  5524. if (localId == 0)
  5525. continue;
  5526. SceneObjectPart obj = m_scene.GetSceneObjectPart(localId);
  5527. if (obj != null)
  5528. {
  5529. if (!dest.CollisionFilteredOut(obj.UUID, obj.Name))
  5530. colliding.Add(CreateDetObject(obj));
  5531. }
  5532. else
  5533. {
  5534. ScenePresence av = m_scene.GetScenePresence(localId);
  5535. if (av != null && (!av.IsChildAgent))
  5536. {
  5537. if (!dest.CollisionFilteredOut(av.UUID, av.Name))
  5538. colliding.Add(CreateDetObject(av));
  5539. }
  5540. }
  5541. }
  5542. colliderArgs.Colliders = colliding;
  5543. return colliderArgs;
  5544. }
  5545. private delegate void ScriptCollidingNotification(uint localID, ColliderArgs message);
  5546. private void SendCollisionEvent(SceneObjectGroup dest, scriptEvents ev, List<uint> colliders, ScriptCollidingNotification notify)
  5547. {
  5548. ColliderArgs CollidingMessage;
  5549. if (colliders.Count > 0)
  5550. {
  5551. if ((dest.RootPart.ScriptEvents & ev) != 0)
  5552. {
  5553. CollidingMessage = CreateColliderArgs(dest.RootPart, colliders);
  5554. if (CollidingMessage.Colliders.Count > 0)
  5555. notify(dest.RootPart.LocalId, CollidingMessage);
  5556. }
  5557. }
  5558. }
  5559. private void SendLandCollisionEvent(SceneObjectGroup dest, scriptEvents ev, ScriptCollidingNotification notify)
  5560. {
  5561. if ((dest.RootPart.ScriptEvents & ev) != 0)
  5562. {
  5563. ColliderArgs LandCollidingMessage = new ColliderArgs();
  5564. List<DetectedObject> colliding = new List<DetectedObject>();
  5565. colliding.Add(CreateDetObjectForGround());
  5566. LandCollidingMessage.Colliders = colliding;
  5567. notify(dest.RootPart.LocalId, LandCollidingMessage);
  5568. }
  5569. }
  5570. private void RaiseCollisionScriptEvents(Dictionary<uint, ContactPoint> coldata)
  5571. {
  5572. try
  5573. {
  5574. List<uint> thisHitColliders = new List<uint>();
  5575. List<uint> endedColliders = new List<uint>();
  5576. List<uint> startedColliders = new List<uint>();
  5577. if (coldata.Count == 0)
  5578. {
  5579. if (m_lastColliders.Count == 0)
  5580. return; // nothing to do
  5581. for(int i = 0; i < m_lastColliders.Count; ++i)
  5582. endedColliders.Add(m_lastColliders[i]);
  5583. m_lastColliders.Clear();
  5584. }
  5585. else
  5586. {
  5587. List<CollisionForSoundInfo> soundinfolist = new List<CollisionForSoundInfo>();
  5588. if(ParcelAllowThisAvatarSounds)
  5589. {
  5590. CollisionForSoundInfo soundinfo;
  5591. ContactPoint curcontact;
  5592. foreach (uint id in coldata.Keys)
  5593. {
  5594. thisHitColliders.Add(id);
  5595. if (!m_lastColliders.Contains(id))
  5596. {
  5597. startedColliders.Add(id);
  5598. curcontact = coldata[id];
  5599. if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
  5600. {
  5601. soundinfo = new CollisionForSoundInfo();
  5602. soundinfo.colliderID = id;
  5603. soundinfo.position = curcontact.Position;
  5604. soundinfo.relativeVel = curcontact.RelativeSpeed;
  5605. soundinfolist.Add(soundinfo);
  5606. }
  5607. }
  5608. }
  5609. }
  5610. else
  5611. {
  5612. foreach (uint id in coldata.Keys)
  5613. {
  5614. thisHitColliders.Add(id);
  5615. if (!m_lastColliders.Contains(id))
  5616. startedColliders.Add(id);
  5617. }
  5618. }
  5619. // calculate things that ended colliding
  5620. foreach (uint localID in m_lastColliders)
  5621. {
  5622. if (!thisHitColliders.Contains(localID))
  5623. {
  5624. endedColliders.Add(localID);
  5625. }
  5626. }
  5627. //add the items that started colliding this time to the last colliders list.
  5628. foreach (uint localID in startedColliders)
  5629. {
  5630. m_lastColliders.Add(localID);
  5631. }
  5632. // remove things that ended colliding from the last colliders list
  5633. foreach (uint localID in endedColliders)
  5634. {
  5635. m_lastColliders.Remove(localID);
  5636. }
  5637. if (soundinfolist.Count > 0)
  5638. CollisionSounds.AvatarCollisionSound(this, soundinfolist);
  5639. }
  5640. List<SceneObjectGroup> attachements = GetAttachments();
  5641. for (int i = 0; i< attachements.Count; ++i)
  5642. {
  5643. SceneObjectGroup att = attachements[i];
  5644. SendCollisionEvent(att, scriptEvents.collision_start, startedColliders, m_scene.EventManager.TriggerScriptCollidingStart);
  5645. SendCollisionEvent(att, scriptEvents.collision , m_lastColliders , m_scene.EventManager.TriggerScriptColliding);
  5646. SendCollisionEvent(att, scriptEvents.collision_end , endedColliders , m_scene.EventManager.TriggerScriptCollidingEnd);
  5647. if (startedColliders.Contains(0))
  5648. SendLandCollisionEvent(att, scriptEvents.land_collision_start, m_scene.EventManager.TriggerScriptLandCollidingStart);
  5649. if (m_lastColliders.Contains(0))
  5650. SendLandCollisionEvent(att, scriptEvents.land_collision, m_scene.EventManager.TriggerScriptLandColliding);
  5651. if (endedColliders.Contains(0))
  5652. SendLandCollisionEvent(att, scriptEvents.land_collision_end, m_scene.EventManager.TriggerScriptLandCollidingEnd);
  5653. }
  5654. }
  5655. catch { }
  5656. // finally
  5657. // {
  5658. // m_collisionEventFlag = false;
  5659. // }
  5660. }
  5661. private void TeleportFlagsDebug() {
  5662. // Some temporary debugging help to show all the TeleportFlags we have...
  5663. bool HG = false;
  5664. if((m_teleportFlags & TeleportFlags.ViaHGLogin) == TeleportFlags.ViaHGLogin)
  5665. HG = true;
  5666. m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
  5667. uint i = 0u;
  5668. for (int x = 0; x <= 30 ; x++, i = 1u << x)
  5669. {
  5670. i = 1u << x;
  5671. if((m_teleportFlags & (TeleportFlags)i) == (TeleportFlags)i)
  5672. if (HG == false)
  5673. m_log.InfoFormat("[SCENE PRESENCE]: Teleport Flags include {0}", ((TeleportFlags) i).ToString());
  5674. else
  5675. m_log.InfoFormat("[SCENE PRESENCE]: HG Teleport Flags include {0}", ((TeleportFlags)i).ToString());
  5676. }
  5677. m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
  5678. }
  5679. private void parcelGodCheck(UUID currentParcelID)
  5680. {
  5681. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  5682. foreach (ScenePresence p in allpresences)
  5683. {
  5684. if (p.IsDeleted || p.IsChildAgent || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5685. continue;
  5686. if (p.ParcelHideThisAvatar && p.currentParcelUUID != currentParcelID)
  5687. {
  5688. if (IsViewerUIGod)
  5689. p.SendViewTo(this);
  5690. else
  5691. p.SendKillTo(this);
  5692. }
  5693. }
  5694. }
  5695. private void ParcelCrossCheck(UUID currentParcelID,UUID previusParcelID,
  5696. bool currentParcelHide, bool previusParcelHide, bool oldhide, bool check)
  5697. {
  5698. List<ScenePresence> killsToSendto = new List<ScenePresence>();
  5699. List<ScenePresence> killsToSendme = new List<ScenePresence>();
  5700. List<ScenePresence> viewsToSendto = new List<ScenePresence>();
  5701. List<ScenePresence> viewsToSendme = new List<ScenePresence>();
  5702. List<ScenePresence> allpresences = null;
  5703. if (IsInTransit || IsChildAgent)
  5704. return;
  5705. if (check)
  5706. {
  5707. // check is relative to current parcel only
  5708. if (oldhide == currentParcelHide)
  5709. return;
  5710. allpresences = m_scene.GetScenePresences();
  5711. if (oldhide)
  5712. { // where private
  5713. foreach (ScenePresence p in allpresences)
  5714. {
  5715. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5716. continue;
  5717. // those on not on parcel see me
  5718. if (currentParcelID != p.currentParcelUUID)
  5719. {
  5720. viewsToSendto.Add(p); // they see me
  5721. }
  5722. }
  5723. } // where private end
  5724. else
  5725. { // where public
  5726. foreach (ScenePresence p in allpresences)
  5727. {
  5728. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5729. continue;
  5730. // those not on parcel dont see me
  5731. if (currentParcelID != p.currentParcelUUID && !p.IsViewerUIGod)
  5732. {
  5733. killsToSendto.Add(p); // they dont see me
  5734. }
  5735. }
  5736. } // where public end
  5737. allpresences.Clear();
  5738. }
  5739. else
  5740. {
  5741. if (currentParcelHide)
  5742. {
  5743. // now on a private parcel
  5744. allpresences = m_scene.GetScenePresences();
  5745. if (previusParcelHide && previusParcelID != UUID.Zero)
  5746. {
  5747. foreach (ScenePresence p in allpresences)
  5748. {
  5749. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5750. continue;
  5751. // only those on previous parcel need receive kills
  5752. if (previusParcelID == p.currentParcelUUID)
  5753. {
  5754. if(!p.IsViewerUIGod)
  5755. killsToSendto.Add(p); // they dont see me
  5756. if(!IsViewerUIGod)
  5757. killsToSendme.Add(p); // i dont see them
  5758. }
  5759. // only those on new parcel need see
  5760. if (currentParcelID == p.currentParcelUUID)
  5761. {
  5762. viewsToSendto.Add(p); // they see me
  5763. viewsToSendme.Add(p); // i see them
  5764. }
  5765. }
  5766. }
  5767. else
  5768. {
  5769. //was on a public area
  5770. allpresences = m_scene.GetScenePresences();
  5771. foreach (ScenePresence p in allpresences)
  5772. {
  5773. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5774. continue;
  5775. // those not on new parcel dont see me
  5776. if (currentParcelID != p.currentParcelUUID && !p.IsViewerUIGod)
  5777. {
  5778. killsToSendto.Add(p); // they dont see me
  5779. }
  5780. else
  5781. {
  5782. viewsToSendme.Add(p); // i see those on it
  5783. }
  5784. }
  5785. }
  5786. allpresences.Clear();
  5787. } // now on a private parcel end
  5788. else
  5789. {
  5790. // now on public parcel
  5791. if (previusParcelHide && previusParcelID != UUID.Zero)
  5792. {
  5793. // was on private area
  5794. allpresences = m_scene.GetScenePresences();
  5795. foreach (ScenePresence p in allpresences)
  5796. {
  5797. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5798. continue;
  5799. // only those old parcel need kills
  5800. if (previusParcelID == p.currentParcelUUID && !IsViewerUIGod)
  5801. {
  5802. killsToSendme.Add(p); // i dont see them
  5803. }
  5804. else
  5805. {
  5806. viewsToSendto.Add(p); // they see me
  5807. }
  5808. }
  5809. }
  5810. else
  5811. return; // was on a public area also
  5812. } // now on public parcel end
  5813. }
  5814. // send the things
  5815. if (killsToSendto.Count > 0)
  5816. {
  5817. foreach (ScenePresence p in killsToSendto)
  5818. {
  5819. // m_log.Debug("[AVATAR]: killTo: " + Lastname + " " + p.Lastname);
  5820. SendKillTo(p);
  5821. }
  5822. }
  5823. if (killsToSendme.Count > 0)
  5824. {
  5825. foreach (ScenePresence p in killsToSendme)
  5826. {
  5827. // m_log.Debug("[AVATAR]: killToMe: " + Lastname + " " + p.Lastname);
  5828. p.SendKillTo(this);
  5829. }
  5830. }
  5831. if (viewsToSendto.Count > 0)
  5832. {
  5833. foreach (ScenePresence p in viewsToSendto)
  5834. {
  5835. SendViewTo(p);
  5836. }
  5837. }
  5838. if (viewsToSendme.Count > 0 )
  5839. {
  5840. foreach (ScenePresence p in viewsToSendme)
  5841. {
  5842. if (p.IsChildAgent)
  5843. continue;
  5844. // m_log.Debug("[AVATAR]: viewMe: " + Lastname + "<-" + p.Lastname);
  5845. p.SendViewTo(this);
  5846. }
  5847. }
  5848. }
  5849. public void HasMovedAway(bool nearRegion)
  5850. {
  5851. if (nearRegion)
  5852. {
  5853. if (Scene.AttachmentsModule != null)
  5854. Scene.AttachmentsModule.DeleteAttachmentsFromScene(this, true);
  5855. if (!ParcelHideThisAvatar || IsViewerUIGod)
  5856. return;
  5857. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  5858. foreach (ScenePresence p in allpresences)
  5859. {
  5860. if (p.IsDeleted || p == this || p.IsChildAgent || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5861. continue;
  5862. if (p.currentParcelUUID == m_currentParcelUUID)
  5863. {
  5864. p.SendKillTo(this);
  5865. }
  5866. }
  5867. }
  5868. else
  5869. {
  5870. lock (m_completeMovementLock)
  5871. {
  5872. GodController.HasMovedAway();
  5873. NeedInitialData = -1;
  5874. m_gotRegionHandShake = false;
  5875. }
  5876. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  5877. foreach (ScenePresence p in allpresences)
  5878. {
  5879. if (p == this)
  5880. continue;
  5881. SendKillTo(p);
  5882. if (!p.IsChildAgent)
  5883. p.SendKillTo(this);
  5884. }
  5885. if (Scene.AttachmentsModule != null)
  5886. Scene.AttachmentsModule.DeleteAttachmentsFromScene(this, true);
  5887. }
  5888. }
  5889. // kill with attachs root kills
  5890. public void SendKillTo(ScenePresence p)
  5891. {
  5892. List<uint> ids = new List<uint>(m_attachments.Count + 1);
  5893. foreach (SceneObjectGroup sog in m_attachments)
  5894. {
  5895. ids.Add(sog.RootPart.LocalId);
  5896. }
  5897. ids.Add(LocalId);
  5898. p.ControllingClient.SendKillObject(ids);
  5899. }
  5900. /*
  5901. // kill with hack
  5902. public void SendKillTo(ScenePresence p)
  5903. {
  5904. foreach (SceneObjectGroup sog in m_attachments)
  5905. p.ControllingClient.SendPartFullUpdate(sog.RootPart, LocalId + 1);
  5906. p.ControllingClient.SendKillObject(new List<uint> { LocalId });
  5907. }
  5908. */
  5909. public void SendViewTo(ScenePresence p)
  5910. {
  5911. SendAvatarDataToAgentNF(p);
  5912. SendAppearanceToAgent(p);
  5913. if (Animator != null)
  5914. Animator.SendAnimPackToClient(p.ControllingClient);
  5915. SendAttachmentsToAgentNF(p);
  5916. }
  5917. public void SetAnimationOverride(string animState, UUID animID)
  5918. {
  5919. Overrides.SetOverride(animState, animID);
  5920. // Animator.SendAnimPack();
  5921. Animator.ForceUpdateMovementAnimations();
  5922. }
  5923. public UUID GetAnimationOverride(string animState)
  5924. {
  5925. return Overrides.GetOverriddenAnimation(animState);
  5926. }
  5927. // http caps assets bandwidth control
  5928. private int m_capbandwidth = -1;
  5929. private int m_bandwidth = 100000;
  5930. private int m_bandwidthBurst = 20000;
  5931. private int m_bytesControl;
  5932. private double m_lastBandwithTime;
  5933. private object m_throttleLock = new object();
  5934. public bool CapCanSendAsset(int type, int size)
  5935. {
  5936. if(size == 0)
  5937. return true;
  5938. lock (m_throttleLock)
  5939. {
  5940. if (type > 1)
  5941. {
  5942. // not texture or mesh
  5943. m_bytesControl -= size;
  5944. return true;
  5945. }
  5946. double currenttime = Util.GetTimeStamp();
  5947. double timeElapsed = currenttime - m_lastBandwithTime;
  5948. if (timeElapsed > .02)
  5949. {
  5950. m_lastBandwithTime = currenttime;
  5951. int add = (int)(m_bandwidth * timeElapsed);
  5952. m_bytesControl += add;
  5953. if (m_bytesControl > m_bandwidthBurst)
  5954. m_bytesControl = m_bandwidthBurst;
  5955. }
  5956. if (m_bytesControl > 0 )
  5957. {
  5958. m_bytesControl -= size;
  5959. return true;
  5960. }
  5961. }
  5962. return false;
  5963. }
  5964. }
  5965. }