ScenePresence.cs 273 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073
  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)
  178. m_currentParcelHide = !land.LandData.SeeAVs;
  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. /*
  1889. InventoryFolderBase cof = m_scene.InventoryService.GetFolderForType(client.AgentId, (FolderType)46);
  1890. if (cof == null)
  1891. COF = UUID.Zero;
  1892. else
  1893. COF = cof.ID;
  1894. m_log.DebugFormat("[CompleteMovement]: Missing COF for {0} is {1}", client.AgentId, COF);
  1895. */
  1896. }
  1897. }
  1898. if (m_teleportFlags > 0)
  1899. m_gotCrossUpdate = false; // sanity check
  1900. if (!m_gotCrossUpdate)
  1901. RotateToLookAt(look);
  1902. m_previusParcelHide = false;
  1903. m_previusParcelUUID = UUID.Zero;
  1904. m_currentParcelHide = false;
  1905. m_currentParcelUUID = UUID.Zero;
  1906. ParcelDwellTickMS = Util.GetTimeStampMS();
  1907. m_inTransit = false;
  1908. // Tell the client that we're ready to send rest
  1909. if (!m_gotCrossUpdate)
  1910. {
  1911. m_gotRegionHandShake = false; // allow it if not a crossing
  1912. ControllingClient.SendRegionHandshake();
  1913. }
  1914. ControllingClient.MoveAgentIntoRegion(m_scene.RegionInfo, AbsolutePosition, look);
  1915. bool isHGTP = (m_teleportFlags & TeleportFlags.ViaHGLogin) != 0;
  1916. if(!IsNPC)
  1917. {
  1918. if( ParentPart != null && (m_crossingFlags & 0x08) != 0)
  1919. {
  1920. ParentPart.ParentGroup.SendFullAnimUpdateToClient(ControllingClient);
  1921. }
  1922. // verify baked textures and cache
  1923. if (m_scene.AvatarFactory != null && !isHGTP)
  1924. {
  1925. if (!m_scene.AvatarFactory.ValidateBakedTextureCache(this))
  1926. m_scene.AvatarFactory.QueueAppearanceSave(UUID);
  1927. }
  1928. }
  1929. if(isHGTP)
  1930. {
  1931. // ControllingClient.SendNameReply(m_uuid, Firstname, Lastname);
  1932. m_log.DebugFormat("[CompleteMovement] HG");
  1933. }
  1934. if (!IsNPC)
  1935. {
  1936. GodController.SyncViewerState();
  1937. // start sending terrain patchs
  1938. if (!m_gotCrossUpdate)
  1939. Scene.SendLayerData(ControllingClient);
  1940. // send initial land overlay and parcel
  1941. ILandChannel landch = m_scene.LandChannel;
  1942. if (landch != null)
  1943. landch.sendClientInitialLandInfo(client, !m_gotCrossUpdate);
  1944. }
  1945. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  1946. // send avatar object to all presences including us, so they cross it into region
  1947. // then hide if necessary
  1948. SendInitialAvatarDataToAllAgents(allpresences);
  1949. // send this look
  1950. if (!IsNPC)
  1951. SendAppearanceToAgent(this);
  1952. // send this animations
  1953. UUID[] animIDs = null;
  1954. int[] animseqs = null;
  1955. UUID[] animsobjs = null;
  1956. if (Animator != null)
  1957. Animator.GetArrays(out animIDs, out animseqs, out animsobjs);
  1958. bool haveAnims = (animIDs != null && animseqs != null && animsobjs != null);
  1959. if (!IsNPC && haveAnims)
  1960. SendAnimPackToAgent(this, animIDs, animseqs, animsobjs);
  1961. // send look and animations to others
  1962. // if not cached we send greys
  1963. // uncomented if will wait till avatar does baking
  1964. //if (cachedbaked)
  1965. {
  1966. foreach (ScenePresence p in allpresences)
  1967. {
  1968. if (p == this)
  1969. continue;
  1970. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  1971. continue;
  1972. SendAppearanceToAgentNF(p);
  1973. if (haveAnims)
  1974. SendAnimPackToAgentNF(p, animIDs, animseqs, animsobjs);
  1975. }
  1976. }
  1977. // attachments
  1978. if (IsNPC || IsRealLogin(m_teleportFlags))
  1979. {
  1980. if (Scene.AttachmentsModule != null)
  1981. {
  1982. if(IsNPC)
  1983. {
  1984. Util.FireAndForget(x =>
  1985. {
  1986. Scene.AttachmentsModule.RezAttachments(this);
  1987. });
  1988. }
  1989. else
  1990. Scene.AttachmentsModule.RezAttachments(this);
  1991. }
  1992. }
  1993. else
  1994. {
  1995. if (m_attachments.Count > 0)
  1996. {
  1997. foreach (SceneObjectGroup sog in m_attachments)
  1998. {
  1999. sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource());
  2000. sog.ResumeScripts();
  2001. }
  2002. foreach (ScenePresence p in allpresences)
  2003. {
  2004. if (p == this)
  2005. {
  2006. SendAttachmentsToAgentNF(this);
  2007. continue;
  2008. }
  2009. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  2010. continue;
  2011. SendAttachmentsToAgentNF(p);
  2012. }
  2013. }
  2014. }
  2015. if (!IsNPC)
  2016. {
  2017. if(m_gotCrossUpdate)
  2018. {
  2019. SendOtherAgentsAvatarFullToMe();
  2020. // Create child agents in neighbouring regions
  2021. IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
  2022. if (m_agentTransfer != null)
  2023. {
  2024. m_agentTransfer.EnableChildAgents(this);
  2025. }
  2026. m_lastChildUpdatesTime = Util.EnvironmentTickCount() + 10000;
  2027. m_lastChildAgentUpdatePosition = AbsolutePosition;
  2028. m_lastChildAgentCheckPosition = m_lastChildAgentUpdatePosition;
  2029. m_lastChildAgentUpdateDrawDistance = DrawDistance;
  2030. m_lastRegionsDrawDistance = RegionViewDistance;
  2031. m_lastChildAgentUpdateGodLevel = GodController.ViwerUIGodLevel;
  2032. m_childUpdatesBusy = false; // allow them
  2033. }
  2034. // send the rest of the world
  2035. //if (m_teleportFlags > 0 || m_currentParcelHide)
  2036. //SendInitialDataToMe();
  2037. //SendOtherAgentsAvatarFullToMe();
  2038. // priority uses avatar position only
  2039. // m_reprioritizationLastPosition = AbsolutePosition;
  2040. // m_reprioritizationLastDrawDistance = DrawDistance;
  2041. // m_reprioritizationLastTime = Util.EnvironmentTickCount() + 15000; // delay it
  2042. // m_reprioritizationBusy = false;
  2043. if (openChildAgents)
  2044. {
  2045. IFriendsModule friendsModule = m_scene.RequestModuleInterface<IFriendsModule>();
  2046. if (friendsModule != null)
  2047. {
  2048. if(m_gotCrossUpdate)
  2049. friendsModule.IsNowRoot(this);
  2050. else
  2051. friendsModule.SendFriendsOnlineIfNeeded(ControllingClient);
  2052. }
  2053. //m_log.DebugFormat("[CompleteMovement] friendsModule: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  2054. }
  2055. }
  2056. else
  2057. NeedInitialData = -1;
  2058. }
  2059. finally
  2060. {
  2061. m_haveGroupInformation = false;
  2062. m_gotCrossUpdate = false;
  2063. m_crossingFlags = 0;
  2064. m_inTransit = false;
  2065. }
  2066. m_scene.EventManager.OnRegionHeartbeatEnd += RegionHeartbeatEnd;
  2067. m_log.DebugFormat("[CompleteMovement] end: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  2068. }
  2069. /// <summary>
  2070. /// Callback for the Camera view block check. Gets called with the results of the camera view block test
  2071. /// hitYN is true when there's something in the way.
  2072. /// </summary>
  2073. /// <param name="hitYN"></param>
  2074. /// <param name="collisionPoint"></param>
  2075. /// <param name="localid"></param>
  2076. /// <param name="distance"></param>
  2077. ///
  2078. private void checkCameraCollision()
  2079. {
  2080. if(m_doingCamRayCast || !m_scene.PhysicsScene.SupportsRayCast())
  2081. return;
  2082. if(m_mouseLook || ParentID != 0)
  2083. {
  2084. if (CameraConstraintActive)
  2085. {
  2086. Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -10000f); // not right...
  2087. UpdateCameraCollisionPlane(plane);
  2088. CameraConstraintActive = false;
  2089. }
  2090. return;
  2091. }
  2092. Vector3 posAdjusted = AbsolutePosition;
  2093. posAdjusted.Z += 1.0f; // viewer current camera focus point
  2094. if(posAdjusted.ApproxEquals(m_lastCameraRayCastPos, 0.2f) &&
  2095. CameraPosition.ApproxEquals(m_lastCameraRayCastCam, 0.2f))
  2096. return;
  2097. m_lastCameraRayCastCam = CameraPosition;
  2098. m_lastCameraRayCastPos = posAdjusted;
  2099. Vector3 tocam = CameraPosition - posAdjusted;
  2100. float distTocamlen = tocam.LengthSquared();
  2101. if (distTocamlen > 0.01f && distTocamlen < 400)
  2102. {
  2103. distTocamlen = (float)Math.Sqrt(distTocamlen);
  2104. tocam *= (1.0f / distTocamlen);
  2105. m_doingCamRayCast = true;
  2106. m_scene.PhysicsScene.RaycastWorld(posAdjusted, tocam, distTocamlen + 1.0f, RayCastCameraCallback);
  2107. return;
  2108. }
  2109. if (CameraConstraintActive)
  2110. {
  2111. Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -10000f); // not right...
  2112. UpdateCameraCollisionPlane(plane);
  2113. CameraConstraintActive = false;
  2114. }
  2115. }
  2116. private void UpdateCameraCollisionPlane(Vector4 plane)
  2117. {
  2118. if (m_lastCameraCollisionPlane != plane)
  2119. {
  2120. m_lastCameraCollisionPlane = plane;
  2121. ControllingClient.SendCameraConstraint(plane);
  2122. }
  2123. }
  2124. public void RayCastCameraCallback(bool hitYN, Vector3 collisionPoint, uint localid, float distance, Vector3 pNormal)
  2125. {
  2126. if (hitYN && localid != LocalId)
  2127. {
  2128. if (localid != 0)
  2129. {
  2130. SceneObjectPart part = m_scene.GetSceneObjectPart(localid);
  2131. if (part != null && !part.VolumeDetectActive)
  2132. {
  2133. CameraConstraintActive = true;
  2134. pNormal.X = (float) Math.Round(pNormal.X, 2);
  2135. pNormal.Y = (float) Math.Round(pNormal.Y, 2);
  2136. pNormal.Z = (float) Math.Round(pNormal.Z, 2);
  2137. pNormal.Normalize();
  2138. collisionPoint.X = (float) Math.Round(collisionPoint.X, 1);
  2139. collisionPoint.Y = (float) Math.Round(collisionPoint.Y, 1);
  2140. collisionPoint.Z = (float) Math.Round(collisionPoint.Z, 1);
  2141. Vector4 plane = new Vector4(pNormal.X, pNormal.Y, pNormal.Z,
  2142. Vector3.Dot(collisionPoint, pNormal));
  2143. UpdateCameraCollisionPlane(plane);
  2144. }
  2145. }
  2146. else
  2147. {
  2148. CameraConstraintActive = true;
  2149. pNormal.X = (float) Math.Round(pNormal.X, 2);
  2150. pNormal.Y = (float) Math.Round(pNormal.Y, 2);
  2151. pNormal.Z = (float) Math.Round(pNormal.Z, 2);
  2152. pNormal.Normalize();
  2153. collisionPoint.X = (float) Math.Round(collisionPoint.X, 1);
  2154. collisionPoint.Y = (float) Math.Round(collisionPoint.Y, 1);
  2155. collisionPoint.Z = (float) Math.Round(collisionPoint.Z, 1);
  2156. Vector4 plane = new Vector4(pNormal.X, pNormal.Y, pNormal.Z,
  2157. Vector3.Dot(collisionPoint, pNormal));
  2158. UpdateCameraCollisionPlane(plane);
  2159. }
  2160. }
  2161. else if(CameraConstraintActive)
  2162. {
  2163. Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -9000f); // not right...
  2164. UpdateCameraCollisionPlane(plane);
  2165. CameraConstraintActive = false;
  2166. }
  2167. m_doingCamRayCast = false;
  2168. }
  2169. /// <summary>
  2170. /// This is the event handler for client movement. If a client is moving, this event is triggering.
  2171. /// </summary>
  2172. public void HandleAgentUpdate(IClientAPI remoteClient, AgentUpdateArgs agentData)
  2173. {
  2174. // m_log.DebugFormat(
  2175. // "[SCENE PRESENCE]: In {0} received agent update from {1}, flags {2}",
  2176. // Scene.Name, remoteClient.Name, (AgentManager.ControlFlags)agentData.ControlFlags);
  2177. if (IsChildAgent)
  2178. {
  2179. // m_log.DebugFormat("DEBUG: HandleAgentUpdate: child agent in {0}", Scene.Name);
  2180. return;
  2181. }
  2182. if (IsInTransit)
  2183. return;
  2184. #region Sanity Checking
  2185. // This is irritating. Really.
  2186. if (!AbsolutePosition.IsFinite())
  2187. {
  2188. bool isphysical = PhysicsActor != null;
  2189. if(isphysical)
  2190. RemoveFromPhysicalScene();
  2191. m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error #9999902");
  2192. m_pos = m_LastFinitePos;
  2193. if (!m_pos.IsFinite())
  2194. {
  2195. m_pos.X = 127f;
  2196. m_pos.Y = 127f;
  2197. m_pos.Z = 127f;
  2198. m_log.Error("[AVATAR]: NonFinite Avatar on lastFiniteposition also. Reset Position. Mantis this please. Error #9999903");
  2199. }
  2200. if(isphysical)
  2201. AddToPhysicalScene(false);
  2202. }
  2203. else
  2204. {
  2205. m_LastFinitePos = m_pos;
  2206. }
  2207. #endregion Sanity Checking
  2208. #region Inputs
  2209. AgentManager.ControlFlags flags = (AgentManager.ControlFlags)agentData.ControlFlags;
  2210. // The Agent's Draw distance setting
  2211. // When we get to the point of re-computing neighbors everytime this
  2212. // changes, then start using the agent's drawdistance rather than the
  2213. // region's draw distance.
  2214. DrawDistance = agentData.Far;
  2215. m_mouseLook = (flags & AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) != 0;
  2216. // FIXME: This does not work as intended because the viewer only sends the lbutton down when the button
  2217. // is first pressed, not whilst it is held down. If this is required in the future then need to look
  2218. // for an AGENT_CONTROL_LBUTTON_UP event and make sure to handle cases where an initial DOWN is not
  2219. // received (e.g. on holding LMB down on the avatar in a viewer).
  2220. m_leftButtonDown = (flags & AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0;
  2221. #endregion Inputs
  2222. // // Make anims work for client side autopilot
  2223. // if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0)
  2224. // m_updateCount = UPDATE_COUNT;
  2225. //
  2226. // // Make turning in place work
  2227. // if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0 ||
  2228. // (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  2229. // m_updateCount = UPDATE_COUNT;
  2230. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP) != 0)
  2231. {
  2232. StandUp();
  2233. }
  2234. // Raycast from the avatar's head to the camera to see if there's anything blocking the view
  2235. // this exclude checks may not be complete
  2236. if(agentData.NeedsCameraCollision) // condition parentID may be wrong
  2237. checkCameraCollision();
  2238. uint flagsForScripts = (uint)flags;
  2239. flags = RemoveIgnoredControls(flags, IgnoredControls);
  2240. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND) != 0)
  2241. HandleAgentSitOnGround();
  2242. // In the future, these values might need to go global.
  2243. // Here's where you get them.
  2244. m_AgentControlFlags = flags;
  2245. m_headrotation = agentData.HeadRotation;
  2246. byte oldState = State;
  2247. State = agentData.State;
  2248. // We need to send this back to the client in order to stop the edit beams
  2249. if ((oldState & (uint)AgentState.Editing) != 0 && State == (uint)AgentState.None)
  2250. SendAgentTerseUpdate(this);
  2251. PhysicsActor actor = PhysicsActor;
  2252. // This will be the case if the agent is sitting on the groudn or on an object.
  2253. if (actor == null)
  2254. {
  2255. SendControlsToScripts(flagsForScripts);
  2256. return;
  2257. }
  2258. if (AllowMovement && !SitGround)
  2259. {
  2260. // m_log.DebugFormat("[SCENE PRESENCE]: Initial body rotation {0} for {1}", agentData.BodyRotation, Name);
  2261. bool update_rotation = false;
  2262. if (!IsSatOnObject && agentData.BodyRotation != Rotation)
  2263. {
  2264. Rotation = agentData.BodyRotation;
  2265. update_rotation = true;
  2266. }
  2267. bool update_movementflag = false;
  2268. bool mvToTarget = m_movingToTarget;
  2269. if (agentData.UseClientAgentPosition)
  2270. {
  2271. m_movingToTarget = (agentData.ClientAgentPosition - AbsolutePosition).LengthSquared() > 0.04f;
  2272. m_moveToPositionTarget = agentData.ClientAgentPosition;
  2273. m_moveToSpeed = -1f;
  2274. }
  2275. int i = 0;
  2276. bool DCFlagKeyPressed = false;
  2277. Vector3 agent_control_v3 = Vector3.Zero;
  2278. bool newFlying = false;
  2279. if (ForceFly)
  2280. newFlying = true;
  2281. else if (FlyDisabled)
  2282. newFlying = false;
  2283. else if(mvToTarget)
  2284. newFlying = actor.Flying;
  2285. else
  2286. newFlying = ((flags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  2287. if (actor.Flying != newFlying)
  2288. {
  2289. // Note: ScenePresence.Flying is actually fetched from the physical actor
  2290. // so setting PhysActor.Flying here also sets the ScenePresence's value.
  2291. actor.Flying = newFlying;
  2292. update_movementflag = true;
  2293. }
  2294. if (ParentID == 0)
  2295. {
  2296. bool bAllowUpdateMoveToPosition = false;
  2297. Vector3[] dirVectors;
  2298. // use camera up angle when in mouselook and not flying or when holding the left mouse button down and not flying
  2299. // this prevents 'jumping' in inappropriate situations.
  2300. // if (!Flying && (m_mouseLook || m_leftButtonDown))
  2301. // dirVectors = GetWalkDirectionVectors();
  2302. // else
  2303. dirVectors = Dir_Vectors;
  2304. // A DIR_CONTROL_FLAG occurs when the user is trying to move in a particular direction.
  2305. foreach (Dir_ControlFlags DCF in DIR_CONTROL_FLAGS)
  2306. {
  2307. if (((uint)flags & (uint)DCF) != 0)
  2308. {
  2309. DCFlagKeyPressed = true;
  2310. try
  2311. {
  2312. agent_control_v3 += Dir_Vectors[i];
  2313. //m_log.DebugFormat("[Motion]: {0}, {1}",i, dirVectors[i]);
  2314. }
  2315. catch (IndexOutOfRangeException)
  2316. {
  2317. // Why did I get this?
  2318. }
  2319. if (((MovementFlag & (uint)DCF) == 0))
  2320. {
  2321. //m_log.DebugFormat("[SCENE PRESENCE]: Updating MovementFlag for {0} with {1}", Name, DCF);
  2322. MovementFlag |= (uint)DCF;
  2323. update_movementflag = true;
  2324. }
  2325. }
  2326. else
  2327. {
  2328. if ((MovementFlag & (uint)DCF) != 0)
  2329. {
  2330. //m_log.DebugFormat("[SCENE PRESENCE]: Updating MovementFlag for {0} with lack of {1}", Name, DCF);
  2331. MovementFlag &= (uint)~DCF;
  2332. update_movementflag = true;
  2333. /*
  2334. if ((DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD_NUDGE || DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_BACKWARD_NUDGE)
  2335. && ((MovementFlag & (byte)nudgehack) == nudgehack))
  2336. {
  2337. m_log.Debug("Removed Hack flag");
  2338. }
  2339. */
  2340. }
  2341. else
  2342. {
  2343. bAllowUpdateMoveToPosition = true;
  2344. }
  2345. }
  2346. i++;
  2347. }
  2348. // Detect AGENT_CONTROL_STOP state changes
  2349. if (AgentControlStopActive != ((flags & AgentManager.ControlFlags.AGENT_CONTROL_STOP) != 0))
  2350. {
  2351. AgentControlStopActive = !AgentControlStopActive;
  2352. update_movementflag = true;
  2353. }
  2354. if (m_movingToTarget)
  2355. {
  2356. // If the user has pressed a key then we want to cancel any move to target.
  2357. if (DCFlagKeyPressed)
  2358. {
  2359. ResetMoveToTarget();
  2360. update_movementflag = true;
  2361. }
  2362. else if (bAllowUpdateMoveToPosition)
  2363. {
  2364. // The UseClientAgentPosition is set if parcel ban is forcing the avatar to move to a
  2365. // certain position. It's only check for tolerance on returning to that position is 0.2
  2366. // rather than 1, at which point it removes its force target.
  2367. if (HandleMoveToTargetUpdate(agentData.UseClientAgentPosition ? 0.2f : 1f, ref agent_control_v3))
  2368. update_movementflag = true;
  2369. }
  2370. }
  2371. }
  2372. // Cause the avatar to stop flying if it's colliding
  2373. // with something with the down arrow pressed.
  2374. // Only do this if we're flying
  2375. if (Flying && !ForceFly)
  2376. {
  2377. // Need to stop in mid air if user holds down AGENT_CONTROL_STOP
  2378. // if (AgentControlStopActive)
  2379. // {
  2380. // agent_control_v3 = Vector3.Zero;
  2381. // }
  2382. // else
  2383. {
  2384. // Landing detection code
  2385. // Are the landing controls requirements filled?
  2386. bool controlland = (((flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) ||
  2387. ((flags & AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0));
  2388. //m_log.Debug("[CONTROL]: " +flags);
  2389. // Applies a satisfying roll effect to the avatar when flying.
  2390. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT) != 0 && (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0)
  2391. {
  2392. ApplyFlyingRoll(
  2393. FLY_ROLL_RADIANS_PER_UPDATE,
  2394. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0,
  2395. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0);
  2396. }
  2397. else if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT) != 0 &&
  2398. (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  2399. {
  2400. ApplyFlyingRoll(
  2401. -FLY_ROLL_RADIANS_PER_UPDATE,
  2402. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0,
  2403. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0);
  2404. }
  2405. else
  2406. {
  2407. if (m_AngularVelocity.Z != 0)
  2408. m_AngularVelocity.Z += CalculateFlyingRollResetToZero(FLY_ROLL_RESET_RADIANS_PER_UPDATE);
  2409. }
  2410. /*
  2411. if (Flying && IsColliding && controlland)
  2412. {
  2413. // nesting this check because LengthSquared() is expensive and we don't
  2414. // want to do it every step when flying.
  2415. if ((Velocity.LengthSquared() <= LAND_VELOCITYMAG_MAX))
  2416. StopFlying();
  2417. }
  2418. */
  2419. }
  2420. }
  2421. else if (IsColliding && agent_control_v3.Z < 0f)
  2422. agent_control_v3.Z = 0;
  2423. // else if(AgentControlStopActive %% Velocity.Z <0.01f)
  2424. // m_log.DebugFormat("[SCENE PRESENCE]: MovementFlag {0} for {1}", MovementFlag, Name);
  2425. // If the agent update does move the avatar, then calculate the force ready for the velocity update,
  2426. // which occurs later in the main scene loop
  2427. // We also need to update if the user rotates their avatar whilst it is slow walking/running (if they
  2428. // held down AGENT_CONTROL_STOP whilst normal walking/running). However, we do not want to update
  2429. // if the user rotated whilst holding down AGENT_CONTROL_STOP when already still (which locks the
  2430. // avatar location in place).
  2431. if (update_movementflag
  2432. || (update_rotation && DCFlagKeyPressed && (!AgentControlStopActive || MovementFlag != 0)))
  2433. {
  2434. if (AgentControlStopActive)
  2435. {
  2436. // if (MovementFlag == 0 && Animator.Falling)
  2437. if (MovementFlag == 0 && Animator.currentControlState == ScenePresenceAnimator.motionControlStates.falling)
  2438. {
  2439. AddNewMovement(agent_control_v3, AgentControlStopSlowVel, true);
  2440. }
  2441. else
  2442. AddNewMovement(agent_control_v3, AgentControlStopSlowVel);
  2443. }
  2444. else
  2445. {
  2446. if(m_movingToTarget ||
  2447. (Animator.currentControlState != ScenePresenceAnimator.motionControlStates.flying &&
  2448. Animator.currentControlState != ScenePresenceAnimator.motionControlStates.onsurface)
  2449. )
  2450. AddNewMovement(agent_control_v3);
  2451. else
  2452. {
  2453. if (MovementFlag != 0)
  2454. AddNewMovement(agent_control_v3);
  2455. else
  2456. m_delayedStop = Util.GetTimeStampMS() + 200.0;
  2457. }
  2458. }
  2459. }
  2460. /*
  2461. if (update_movementflag && ParentID == 0 && m_delayedStop < 0)
  2462. {
  2463. // m_log.DebugFormat("[SCENE PRESENCE]: Updating movement animations for {0}", Name);
  2464. Animator.UpdateMovementAnimations();
  2465. }
  2466. */
  2467. SendControlsToScripts(flagsForScripts);
  2468. }
  2469. // We need to send this back to the client in order to see the edit beams
  2470. if ((State & (uint)AgentState.Editing) != 0)
  2471. SendAgentTerseUpdate(this);
  2472. // m_scene.EventManager.TriggerOnClientMovement(this);
  2473. }
  2474. private void HandleAgentFOV(IClientAPI remoteClient, float _fov)
  2475. {
  2476. m_FOV = _fov;
  2477. }
  2478. /// <summary>
  2479. /// This is the event handler for client cameras. If a client is moving, or moving the camera, this event is triggering.
  2480. /// </summary>
  2481. private void HandleAgentCamerasUpdate(IClientAPI remoteClient, AgentUpdateArgs agentData)
  2482. {
  2483. //m_log.DebugFormat(
  2484. // "[SCENE PRESENCE]: In {0} received agent camera update from {1}, flags {2}",
  2485. // Scene.RegionInfo.RegionName, remoteClient.Name, (AgentManager.ControlFlags)agentData.ControlFlags);
  2486. if (IsChildAgent)
  2487. return;
  2488. if(IsInTransit)
  2489. return;
  2490. // AgentManager.ControlFlags flags = (AgentManager.ControlFlags)agentData.ControlFlags;
  2491. // Camera location in world. We'll need to raytrace
  2492. // from this location from time to time.
  2493. CameraPosition = agentData.CameraCenter;
  2494. // Use these three vectors to figure out what the agent is looking at
  2495. // Convert it to a Matrix and/or Quaternion
  2496. // this may need lock
  2497. CameraAtAxis = agentData.CameraAtAxis;
  2498. CameraLeftAxis = agentData.CameraLeftAxis;
  2499. CameraUpAxis = agentData.CameraUpAxis;
  2500. DrawDistance = agentData.Far;
  2501. CameraAtAxis.Normalize();
  2502. CameraLeftAxis.Normalize();
  2503. CameraUpAxis.Normalize();
  2504. Quaternion camRot = Util.Axes2Rot(CameraAtAxis, CameraLeftAxis, CameraUpAxis);
  2505. CameraRotation = camRot;
  2506. if(agentData.NeedsCameraCollision)
  2507. checkCameraCollision();
  2508. TriggerScenePresenceUpdated();
  2509. }
  2510. /// <summary>
  2511. /// Calculate an update to move the presence to the set target.
  2512. /// </summary>
  2513. /// <remarks>
  2514. /// This doesn't actually perform the movement. Instead, it adds its vector to agent_control_v3.
  2515. /// </remarks>
  2516. /// <param value="agent_control_v3">Cumulative agent movement that this method will update.</param>
  2517. /// <returns>True if movement has been updated in some way. False otherwise.</returns>
  2518. public bool HandleMoveToTargetUpdate(float tolerance, ref Vector3 agent_control_v3)
  2519. {
  2520. // m_log.DebugFormat("[SCENE PRESENCE]: Called HandleMoveToTargetUpdate() for {0}", Name);
  2521. bool updated = false;
  2522. Vector3 LocalVectorToTarget3D = m_moveToPositionTarget - AbsolutePosition;
  2523. // m_log.DebugFormat(
  2524. // "[SCENE PRESENCE]: bAllowUpdateMoveToPosition {0}, m_moveToPositionInProgress {1}, m_autopilotMoving {2}",
  2525. // allowUpdate, m_moveToPositionInProgress, m_autopilotMoving);
  2526. float distanceToTarget;
  2527. if(Flying && !LandAtTarget)
  2528. distanceToTarget = LocalVectorToTarget3D.LengthSquared();
  2529. else
  2530. distanceToTarget = (LocalVectorToTarget3D.X * LocalVectorToTarget3D.X) + (LocalVectorToTarget3D.Y * LocalVectorToTarget3D.Y);
  2531. // m_log.DebugFormat(
  2532. // "[SCENE PRESENCE]: Abs pos of {0} is {1}, target {2}, distance {3}",
  2533. // Name, AbsolutePosition, MoveToPositionTarget, distanceToTarget);
  2534. // Check the error term of the current position in relation to the target position
  2535. if (distanceToTarget <= tolerance * tolerance)
  2536. {
  2537. // We are close enough to the target
  2538. Velocity = Vector3.Zero;
  2539. AbsolutePosition = m_moveToPositionTarget;
  2540. if (Flying)
  2541. {
  2542. if (LandAtTarget)
  2543. Flying = false;
  2544. // A horrible hack to stop the avatar dead in its tracks rather than having them overshoot
  2545. // the target if flying.
  2546. // We really need to be more subtle (slow the avatar as it approaches the target) or at
  2547. // least be able to set collision status once, rather than 5 times to give it enough
  2548. // weighting so that that PhysicsActor thinks it really is colliding.
  2549. for (int i = 0; i < 5; i++)
  2550. IsColliding = true;
  2551. }
  2552. ResetMoveToTarget();
  2553. return false;
  2554. }
  2555. if (m_moveToSpeed > 0 &&
  2556. distanceToTarget <= m_moveToSpeed * m_moveToSpeed * Scene.FrameTime * Scene.FrameTime)
  2557. m_moveToSpeed = (float)Math.Sqrt(distanceToTarget) / Scene.FrameTime;
  2558. try
  2559. {
  2560. // move avatar in 3D towards target, in avatar coordinate frame.
  2561. // This movement vector gets added to the velocity through AddNewMovement().
  2562. // Theoretically we might need a more complex PID approach here if other
  2563. // unknown forces are acting on the avatar and we need to adaptively respond
  2564. // to such forces, but the following simple approach seems to works fine.
  2565. float angle = 0.5f * (float)Math.Atan2(LocalVectorToTarget3D.Y, LocalVectorToTarget3D.X);
  2566. Quaternion rot = new Quaternion(0,0, (float)Math.Sin(angle),(float)Math.Cos(angle));
  2567. Rotation = rot;
  2568. LocalVectorToTarget3D = LocalVectorToTarget3D * Quaternion.Inverse(rot); // change to avatar coords
  2569. LocalVectorToTarget3D.Normalize();
  2570. // update avatar movement flags. the avatar coordinate system is as follows:
  2571. //
  2572. // +X (forward)
  2573. //
  2574. // ^
  2575. // |
  2576. // |
  2577. // |
  2578. // |
  2579. // (left) +Y <--------o--------> -Y
  2580. // avatar
  2581. // |
  2582. // |
  2583. // |
  2584. // |
  2585. // v
  2586. // -X
  2587. //
  2588. // based on the above avatar coordinate system, classify the movement into
  2589. // one of left/right/back/forward.
  2590. const uint noMovFlagsMask = (uint)(~(Dir_ControlFlags.DIR_CONTROL_FLAG_BACK |
  2591. Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD | Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT |
  2592. Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT | Dir_ControlFlags.DIR_CONTROL_FLAG_UP |
  2593. Dir_ControlFlags.DIR_CONTROL_FLAG_DOWN));
  2594. MovementFlag &= noMovFlagsMask;
  2595. uint tmpAgentControlFlags = (uint)m_AgentControlFlags;
  2596. tmpAgentControlFlags &= noMovFlagsMask;
  2597. if (LocalVectorToTarget3D.X < 0) //MoveBack
  2598. {
  2599. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
  2600. tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
  2601. updated = true;
  2602. }
  2603. else if (LocalVectorToTarget3D.X > 0) //Move Forward
  2604. {
  2605. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
  2606. tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
  2607. updated = true;
  2608. }
  2609. if (LocalVectorToTarget3D.Y > 0) //MoveLeft
  2610. {
  2611. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
  2612. tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
  2613. updated = true;
  2614. }
  2615. else if (LocalVectorToTarget3D.Y < 0) //MoveRight
  2616. {
  2617. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
  2618. tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
  2619. updated = true;
  2620. }
  2621. if (LocalVectorToTarget3D.Z > 0) //Up
  2622. updated = true;
  2623. else if (LocalVectorToTarget3D.Z < 0) //Down
  2624. updated = true;
  2625. // m_log.DebugFormat(
  2626. // "[SCENE PRESENCE]: HandleMoveToTargetUpdate adding {0} to move vector {1} for {2}",
  2627. // LocalVectorToTarget3D, agent_control_v3, Name);
  2628. m_AgentControlFlags = (AgentManager.ControlFlags) tmpAgentControlFlags;
  2629. if(updated)
  2630. agent_control_v3 += LocalVectorToTarget3D;
  2631. }
  2632. catch (Exception e)
  2633. {
  2634. //Avoid system crash, can be slower but...
  2635. m_log.DebugFormat("Crash! {0}", e.ToString());
  2636. }
  2637. return updated;
  2638. // AddNewMovement(agent_control_v3);
  2639. }
  2640. public void MoveToTargetHandle(Vector3 pos, bool noFly, bool landAtTarget)
  2641. {
  2642. MoveToTarget(pos, noFly, landAtTarget);
  2643. }
  2644. /// <summary>
  2645. /// Move to the given target over time.
  2646. /// </summary>
  2647. /// <param name="pos"></param>
  2648. /// <param name="noFly">
  2649. /// If true, then don't allow the avatar to fly to the target, even if it's up in the air.
  2650. /// This is to allow movement to targets that are known to be on an elevated platform with a continuous path
  2651. /// from start to finish.
  2652. /// </param>
  2653. /// <param name="landAtTarget">
  2654. /// If true and the avatar starts flying during the move then land at the target.
  2655. /// </param>
  2656. public void MoveToTarget(Vector3 pos, bool noFly, bool landAtTarget, float tau = -1f)
  2657. {
  2658. m_delayedStop = -1;
  2659. if (SitGround || IsSatOnObject)
  2660. StandUp();
  2661. // m_log.DebugFormat(
  2662. // "[SCENE PRESENCE]: Avatar {0} received request to move to position {1} in {2}",
  2663. // Name, pos, m_scene.RegionInfo.RegionName);
  2664. // Allow move to another sub-region within a megaregion
  2665. Vector2 regionSize;
  2666. regionSize = new Vector2(m_scene.RegionInfo.RegionSizeX, m_scene.RegionInfo.RegionSizeY);
  2667. if (pos.X < 0.5f)
  2668. pos.X = 0.5f;
  2669. else if (pos.X > regionSize.X - 0.5f)
  2670. pos.X = regionSize.X - 0.5f;
  2671. if (pos.Y < 0.5f)
  2672. pos.Y = 0.5f;
  2673. else if (pos.Y > regionSize.Y - 0.5f)
  2674. pos.Y = regionSize.Y - 0.5f;
  2675. float terrainHeight;
  2676. Scene targetScene = m_scene;
  2677. terrainHeight = m_scene.GetGroundHeight(pos.X, pos.Y);
  2678. // dont try to land underground
  2679. terrainHeight += Appearance.AvatarHeight * 0.5f + 0.2f;
  2680. if(terrainHeight > pos.Z)
  2681. pos.Z = terrainHeight;
  2682. // m_log.DebugFormat(
  2683. // "[SCENE PRESENCE]: Avatar {0} set move to target {1} (terrain height {2}) in {3}",
  2684. // Name, pos, terrainHeight, m_scene.RegionInfo.RegionName);
  2685. terrainHeight += Appearance.AvatarHeight; // so 1.5 * AvatarHeight above ground at target
  2686. bool shouldfly = Flying;
  2687. if (noFly)
  2688. shouldfly = false;
  2689. else if (pos.Z > terrainHeight || Flying)
  2690. shouldfly = true;
  2691. Vector3 localVectorToTarget3D = pos - AbsolutePosition;
  2692. // m_log.DebugFormat("[SCENE PRESENCE]: Local vector to target is {0},[1}", localVectorToTarget3D.X,localVectorToTarget3D.Y);
  2693. m_movingToTarget = true;
  2694. LandAtTarget = landAtTarget;
  2695. m_moveToPositionTarget = pos;
  2696. if(tau > 0)
  2697. {
  2698. if(tau < Scene.FrameTime)
  2699. tau = Scene.FrameTime;
  2700. m_moveToSpeed = localVectorToTarget3D.Length() / tau;
  2701. if(m_moveToSpeed < 0.5f) //to tune
  2702. m_moveToSpeed = 0.5f;
  2703. else if(m_moveToSpeed > 50f)
  2704. m_moveToSpeed = 50f;
  2705. SetAlwaysRun = false;
  2706. }
  2707. else
  2708. m_moveToSpeed = 4.096f * m_speedModifier;
  2709. Flying = shouldfly;
  2710. Vector3 control = Vector3.Zero;
  2711. if(HandleMoveToTargetUpdate(1f, ref control))
  2712. AddNewMovement(control);
  2713. }
  2714. /// <summary>
  2715. /// Reset the move to target.
  2716. /// </summary>
  2717. public void ResetMoveToTarget()
  2718. {
  2719. // m_log.DebugFormat("[SCENE PRESENCE]: Resetting move to target for {0}", Name);
  2720. m_movingToTarget = false;
  2721. m_moveToSpeed = -1f;
  2722. // MoveToPositionTarget = Vector3.Zero;
  2723. // lock(m_forceToApplyLock)
  2724. // m_forceToApplyValid = false; // cancel possible last action
  2725. // We need to reset the control flag as the ScenePresenceAnimator uses this to determine the correct
  2726. // resting animation (e.g. hover or stand). NPCs don't have a client that will quickly reset this flag.
  2727. // However, the line is here rather than in the NPC module since it also appears necessary to stop a
  2728. // viewer that uses "go here" from juddering on all subsequent avatar movements.
  2729. AgentControlFlags = (uint)AgentManager.ControlFlags.NONE;
  2730. }
  2731. /// <summary>
  2732. /// Perform the logic necessary to stand the avatar up. This method also executes
  2733. /// the stand animation.
  2734. /// </summary>
  2735. public void StandUp()
  2736. {
  2737. // m_log.DebugFormat("[SCENE PRESENCE]: StandUp() for {0}", Name);
  2738. bool satOnObject = IsSatOnObject;
  2739. SceneObjectPart part = ParentPart;
  2740. SitGround = false;
  2741. if (satOnObject)
  2742. {
  2743. PrevSitOffset = m_pos; // Save sit offset
  2744. UnRegisterSeatControls(part.ParentGroup.UUID);
  2745. TaskInventoryDictionary taskIDict = part.TaskInventory;
  2746. if (taskIDict != null)
  2747. {
  2748. lock (taskIDict)
  2749. {
  2750. foreach (UUID taskID in taskIDict.Keys)
  2751. {
  2752. UnRegisterControlEventsToScript(LocalId, taskID);
  2753. taskIDict[taskID].PermsMask &= ~(
  2754. 2048 | //PERMISSION_CONTROL_CAMERA
  2755. 4); // PERMISSION_TAKE_CONTROLS
  2756. }
  2757. }
  2758. }
  2759. ControllingClient.SendClearFollowCamProperties(part.ParentUUID);
  2760. ParentID = 0;
  2761. ParentPart = null;
  2762. Quaternion standRotation = part.ParentGroup.RootPart.RotationOffset;
  2763. Vector3 sitWorldPosition = part.ParentGroup.AbsolutePosition + m_pos * standRotation;
  2764. standRotation = standRotation * m_bodyRot;
  2765. m_bodyRot = standRotation;
  2766. Quaternion standRotationZ;
  2767. Vector3 adjustmentForSitPose = part.StandOffset;
  2768. if (adjustmentForSitPose.X == 0 &&
  2769. adjustmentForSitPose.Y == 0 &&
  2770. adjustmentForSitPose.Z == 0)
  2771. {
  2772. standRotationZ = new Quaternion(0, 0, standRotation.Z, standRotation.W);
  2773. float t = standRotationZ.W * standRotationZ.W + standRotationZ.Z * standRotationZ.Z;
  2774. if (t > 0)
  2775. {
  2776. t = 1.0f / (float)Math.Sqrt(t);
  2777. standRotationZ.W *= t;
  2778. standRotationZ.Z *= t;
  2779. }
  2780. else
  2781. {
  2782. standRotationZ.W = 1.0f;
  2783. standRotationZ.Z = 0f;
  2784. }
  2785. adjustmentForSitPose = new Vector3(0.65f, 0, m_sitAvatarHeight * 0.5f + .1f) * standRotationZ;
  2786. }
  2787. else
  2788. {
  2789. sitWorldPosition = part.GetWorldPosition();
  2790. standRotation = part.GetWorldRotation();
  2791. standRotationZ = new Quaternion(0, 0, standRotation.Z, standRotation.W);
  2792. float t = standRotationZ.W * standRotationZ.W + standRotationZ.Z * standRotationZ.Z;
  2793. if (t > 0)
  2794. {
  2795. t = 1.0f / (float)Math.Sqrt(t);
  2796. standRotationZ.W *= t;
  2797. standRotationZ.Z *= t;
  2798. }
  2799. else
  2800. {
  2801. standRotationZ.W = 1.0f;
  2802. standRotationZ.Z = 0f;
  2803. }
  2804. adjustmentForSitPose *= standRotationZ;
  2805. if (Appearance != null && Appearance.AvatarHeight > 0)
  2806. adjustmentForSitPose.Z += 0.5f * Appearance.AvatarHeight + .1f;
  2807. else
  2808. adjustmentForSitPose.Z += .9f;
  2809. }
  2810. m_pos = sitWorldPosition + adjustmentForSitPose;
  2811. }
  2812. if (PhysicsActor == null)
  2813. AddToPhysicalScene(false);
  2814. if (satOnObject)
  2815. {
  2816. m_requestedSitTargetID = 0;
  2817. part.RemoveSittingAvatar(this);
  2818. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  2819. SendAvatarDataToAllAgents();
  2820. m_scene.EventManager.TriggerParcelPrimCountTainted(); // update select/ sat on
  2821. }
  2822. // reset to default sitAnimation
  2823. sitAnimation = "SIT";
  2824. Animator.SetMovementAnimations("STAND");
  2825. TriggerScenePresenceUpdated();
  2826. }
  2827. private SceneObjectPart FindNextAvailableSitTarget(UUID targetID)
  2828. {
  2829. SceneObjectPart targetPart = m_scene.GetSceneObjectPart(targetID);
  2830. if (targetPart == null)
  2831. return null;
  2832. // If the primitive the player clicked on has a sit target and that sit target is not full, that sit target is used.
  2833. // 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.
  2834. // Get our own copy of the part array, and sort into the order we want to test
  2835. SceneObjectPart[] partArray = targetPart.ParentGroup.Parts;
  2836. Array.Sort(partArray, delegate(SceneObjectPart p1, SceneObjectPart p2)
  2837. {
  2838. // we want the originally selected part first, then the rest in link order -- so make the selected part link num (-1)
  2839. int linkNum1 = p1==targetPart ? -1 : p1.LinkNum;
  2840. int linkNum2 = p2==targetPart ? -1 : p2.LinkNum;
  2841. return linkNum1 - linkNum2;
  2842. }
  2843. );
  2844. //look for prims with explicit sit targets that are available
  2845. foreach (SceneObjectPart part in partArray)
  2846. {
  2847. if (part.IsSitTargetSet && part.SitTargetAvatar == UUID.Zero && part.SitActiveRange >= 0)
  2848. {
  2849. //switch the target to this prim
  2850. return part;
  2851. }
  2852. }
  2853. // no explicit sit target found - use original target
  2854. return targetPart;
  2855. }
  2856. private void SendSitResponse(UUID targetID, Vector3 offset, Quaternion sitOrientation)
  2857. {
  2858. Vector3 cameraEyeOffset = Vector3.Zero;
  2859. Vector3 cameraAtOffset = Vector3.Zero;
  2860. bool forceMouselook = false;
  2861. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  2862. if (part == null)
  2863. return;
  2864. float range = part.SitActiveRange;
  2865. if (range < 0)
  2866. return;
  2867. Vector3 pos = part.AbsolutePosition + offset;
  2868. if (range > 1e-5f)
  2869. {
  2870. if (Vector3.DistanceSquared(AbsolutePosition, pos) > range * range)
  2871. return;
  2872. }
  2873. if (PhysicsActor != null)
  2874. m_sitAvatarHeight = PhysicsActor.Size.Z * 0.5f;
  2875. if (part.IsSitTargetSet && part.SitTargetAvatar == UUID.Zero)
  2876. {
  2877. offset = part.SitTargetPosition;
  2878. sitOrientation = part.SitTargetOrientation;
  2879. }
  2880. else
  2881. {
  2882. if (PhysicsSit(part,offset)) // physics engine
  2883. return;
  2884. if (Vector3.DistanceSquared(AbsolutePosition, pos) > 100f)
  2885. return;
  2886. AbsolutePosition = pos + new Vector3(0.0f, 0.0f, m_sitAvatarHeight);
  2887. }
  2888. if (PhysicsActor != null)
  2889. RemoveFromPhysicalScene();
  2890. if (m_movingToTarget)
  2891. ResetMoveToTarget();
  2892. Velocity = Vector3.Zero;
  2893. m_AngularVelocity = Vector3.Zero;
  2894. part.AddSittingAvatar(this);
  2895. cameraAtOffset = part.GetCameraAtOffset();
  2896. cameraEyeOffset = part.GetCameraEyeOffset();
  2897. forceMouselook = part.GetForceMouselook();
  2898. if (!part.IsRoot)
  2899. {
  2900. sitOrientation = part.RotationOffset * sitOrientation;
  2901. offset = offset * part.RotationOffset;
  2902. offset += part.OffsetPosition;
  2903. if (cameraAtOffset == Vector3.Zero && cameraEyeOffset == Vector3.Zero)
  2904. {
  2905. cameraAtOffset = part.ParentGroup.RootPart.GetCameraAtOffset();
  2906. cameraEyeOffset = part.ParentGroup.RootPart.GetCameraEyeOffset();
  2907. }
  2908. else
  2909. {
  2910. cameraAtOffset = cameraAtOffset * part.RotationOffset;
  2911. cameraAtOffset += part.OffsetPosition;
  2912. cameraEyeOffset = cameraEyeOffset * part.RotationOffset;
  2913. cameraEyeOffset += part.OffsetPosition;
  2914. }
  2915. }
  2916. sitOrientation = part.ParentGroup.RootPart.RotationOffset * sitOrientation;
  2917. ControllingClient.SendSitResponse(
  2918. part.ParentGroup.UUID, offset, sitOrientation,
  2919. true, cameraAtOffset, cameraEyeOffset, forceMouselook);
  2920. m_requestedSitTargetUUID = part.UUID;
  2921. HandleAgentSit(ControllingClient, UUID);
  2922. // Moved here to avoid a race with default sit anim
  2923. // The script event needs to be raised after the default sit anim is set.
  2924. //part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  2925. //m_scene.EventManager.TriggerParcelPrimCountTainted(); // update select/ sat on
  2926. }
  2927. public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset)
  2928. {
  2929. if (IsChildAgent)
  2930. return;
  2931. if (ParentID != 0)
  2932. {
  2933. if (ParentPart.UUID == targetID)
  2934. return; // already sitting here, ignore
  2935. StandUp();
  2936. }
  2937. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  2938. if (part != null)
  2939. {
  2940. m_requestedSitTargetID = part.LocalId;
  2941. m_requestedSitTargetUUID = part.UUID;
  2942. }
  2943. else
  2944. {
  2945. m_log.Warn("Sit requested on unknown object: " + targetID.ToString());
  2946. }
  2947. SendSitResponse(targetID, offset, Quaternion.Identity);
  2948. }
  2949. // returns false if does not suport so older sit can be tried
  2950. public bool PhysicsSit(SceneObjectPart part, Vector3 offset)
  2951. {
  2952. if (part == null || part.ParentGroup.IsAttachment)
  2953. return true;
  2954. if ( m_scene.PhysicsScene == null)
  2955. return false;
  2956. if (part.PhysActor == null)
  2957. {
  2958. // none physics shape
  2959. if (part.PhysicsShapeType == (byte)PhysicsShapeType.None)
  2960. ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
  2961. else
  2962. { // non physical phantom TODO
  2963. //ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
  2964. return false;
  2965. }
  2966. return true;
  2967. }
  2968. if (m_scene.PhysicsScene.SitAvatar(part.PhysActor, AbsolutePosition, CameraPosition, offset, new Vector3(0.35f, 0, 0.65f), PhysicsSitResponse) != 0)
  2969. {
  2970. return true;
  2971. }
  2972. return false;
  2973. }
  2974. private bool CanEnterLandPosition(Vector3 testPos)
  2975. {
  2976. ILandObject land = m_scene.LandChannel.GetLandObject(testPos.X, testPos.Y);
  2977. if (land == null || land.LandData.Name == "NO_LAND")
  2978. return true;
  2979. return land.CanBeOnThisLand(UUID,testPos.Z);
  2980. }
  2981. // status
  2982. // < 0 ignore
  2983. // 0 bad sit spot
  2984. public void PhysicsSitResponse(int status, uint partID, Vector3 offset, Quaternion Orientation)
  2985. {
  2986. if (status < 0)
  2987. return;
  2988. if (status == 0)
  2989. {
  2990. ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
  2991. return;
  2992. }
  2993. SceneObjectPart part = m_scene.GetSceneObjectPart(partID);
  2994. if (part == null)
  2995. return;
  2996. Vector3 targetPos = part.GetWorldPosition() + offset * part.GetWorldRotation();
  2997. if(!CanEnterLandPosition(targetPos))
  2998. {
  2999. ControllingClient.SendAlertMessage(" Sit position on restricted land, try another spot");
  3000. return;
  3001. }
  3002. RemoveFromPhysicalScene();
  3003. if (m_movingToTarget)
  3004. ResetMoveToTarget();
  3005. Velocity = Vector3.Zero;
  3006. m_AngularVelocity = Vector3.Zero;
  3007. m_requestedSitTargetID = 0;
  3008. part.AddSittingAvatar(this);
  3009. ParentPart = part;
  3010. ParentID = part.LocalId;
  3011. Vector3 cameraAtOffset = part.GetCameraAtOffset();
  3012. Vector3 cameraEyeOffset = part.GetCameraEyeOffset();
  3013. if (!part.IsRoot)
  3014. {
  3015. Orientation = part.RotationOffset * Orientation;
  3016. offset = offset * part.RotationOffset;
  3017. offset += part.OffsetPosition;
  3018. if (cameraAtOffset == Vector3.Zero && cameraEyeOffset == Vector3.Zero)
  3019. {
  3020. cameraAtOffset = part.ParentGroup.RootPart.GetCameraAtOffset();
  3021. cameraEyeOffset = part.ParentGroup.RootPart.GetCameraEyeOffset();
  3022. }
  3023. else
  3024. {
  3025. cameraAtOffset = cameraAtOffset * part.RotationOffset;
  3026. cameraAtOffset += part.OffsetPosition;
  3027. cameraEyeOffset = cameraEyeOffset * part.RotationOffset;
  3028. cameraEyeOffset += part.OffsetPosition;
  3029. }
  3030. }
  3031. m_bodyRot = Orientation;
  3032. m_pos = offset;
  3033. Orientation = part.ParentGroup.RootPart.RotationOffset * Orientation;
  3034. ControllingClient.SendSitResponse(
  3035. part.ParentGroup.UUID, offset, Orientation, true, cameraAtOffset, cameraEyeOffset, part.GetForceMouselook());
  3036. SendAvatarDataToAllAgents();
  3037. if (status == 3)
  3038. sitAnimation = "SIT_GROUND";
  3039. else
  3040. sitAnimation = "SIT";
  3041. Animator.SetMovementAnimations("SIT");
  3042. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  3043. m_scene.EventManager.TriggerParcelPrimCountTainted(); // update select/ sat on
  3044. }
  3045. public void HandleAgentSit(IClientAPI remoteClient, UUID agentID)
  3046. {
  3047. if (IsChildAgent)
  3048. return;
  3049. if(SitGround || IsSatOnObject)
  3050. return;
  3051. SceneObjectPart part = m_scene.GetSceneObjectPart(m_requestedSitTargetID);
  3052. if (part != null)
  3053. {
  3054. if (part.ParentGroup.IsAttachment)
  3055. {
  3056. m_log.WarnFormat(
  3057. "[SCENE PRESENCE]: Avatar {0} tried to sit on part {1} from object {2} in {3} but this is an attachment for avatar id {4}",
  3058. Name, part.Name, part.ParentGroup.Name, Scene.Name, part.ParentGroup.AttachedAvatar);
  3059. return;
  3060. }
  3061. RemoveFromPhysicalScene();
  3062. if (part.SitTargetAvatar == UUID)
  3063. {
  3064. Vector3 sitTargetPos = part.SitTargetPosition;
  3065. Quaternion sitTargetOrient = part.SitTargetOrientation;
  3066. // m_log.DebugFormat(
  3067. // "[SCENE PRESENCE]: Sitting {0} at sit target {1}, {2} on {3} {4}",
  3068. // Name, sitTargetPos, sitTargetOrient, part.Name, part.LocalId);
  3069. double x, y, z, m;
  3070. Vector3 sitOffset;
  3071. Quaternion r = sitTargetOrient;
  3072. Vector3 newPos;
  3073. Quaternion newRot;
  3074. if (LegacySitOffsets)
  3075. {
  3076. double m1,m2;
  3077. m1 = r.X * r.X + r.Y * r.Y;
  3078. m2 = r.Z * r.Z + r.W * r.W;
  3079. // Rotate the vector <0, 0, 1>
  3080. x = 2 * (r.X * r.Z + r.Y * r.W);
  3081. y = 2 * (-r.X * r.W + r.Y * r.Z);
  3082. z = m2 - m1;
  3083. // Set m to be the square of the norm of r.
  3084. m = m1 + m2;
  3085. // This constant is emperically determined to be what is used in SL.
  3086. // See also http://opensimulator.org/mantis/view.php?id=7096
  3087. double offset = 0.05;
  3088. // Normally m will be ~ 1, but if someone passed a handcrafted quaternion
  3089. // to llSitTarget with values so small that squaring them is rounded off
  3090. // to zero, then m could be zero. The result of this floating point
  3091. // round off error (causing us to skip this impossible normalization)
  3092. // is only 5 cm.
  3093. if (m > 0.000001)
  3094. {
  3095. offset /= m;
  3096. }
  3097. Vector3 up = new Vector3((float)x, (float)y, (float)z);
  3098. sitOffset = up * (float)offset;
  3099. newPos = sitTargetPos - sitOffset + SIT_TARGET_ADJUSTMENT;
  3100. }
  3101. else
  3102. {
  3103. m = r.X * r.X + r.Y * r.Y + r.Z * r.Z + r.W * r.W;
  3104. if (Math.Abs(1.0 - m) > 0.000001)
  3105. {
  3106. if(m != 0)
  3107. {
  3108. m = 1.0 / Math.Sqrt(m);
  3109. r.X *= (float)m;
  3110. r.Y *= (float)m;
  3111. r.Z *= (float)m;
  3112. r.W *= (float)m;
  3113. }
  3114. else
  3115. {
  3116. r.X = 0.0f;
  3117. r.Y = 0.0f;
  3118. r.Z = 0.0f;
  3119. r.W = 1.0f;
  3120. m = 1.0f;
  3121. }
  3122. }
  3123. x = 2 * (r.X * r.Z + r.Y * r.W);
  3124. y = 2 * (-r.X * r.W + r.Y * r.Z);
  3125. z = -r.X * r.X - r.Y * r.Y + r.Z * r.Z + r.W * r.W;
  3126. Vector3 up = new Vector3((float)x, (float)y, (float)z);
  3127. sitOffset = up * Appearance.AvatarHeight * 0.02638f;
  3128. newPos = sitTargetPos + sitOffset + SIT_TARGET_ADJUSTMENT;
  3129. }
  3130. if (part.IsRoot)
  3131. {
  3132. newRot = sitTargetOrient;
  3133. }
  3134. else
  3135. {
  3136. newPos = newPos * part.RotationOffset;
  3137. newRot = part.RotationOffset * sitTargetOrient;
  3138. }
  3139. newPos += part.OffsetPosition;
  3140. m_pos = newPos;
  3141. Rotation = newRot;
  3142. // ParentPosition = part.AbsolutePosition;
  3143. }
  3144. else
  3145. {
  3146. // An viewer expects to specify sit positions as offsets to the root prim, even if a child prim is
  3147. // being sat upon.
  3148. m_pos -= part.GroupPosition;
  3149. }
  3150. part.AddSittingAvatar(this);
  3151. ParentPart = part;
  3152. ParentID = m_requestedSitTargetID;
  3153. m_AngularVelocity = Vector3.Zero;
  3154. Velocity = Vector3.Zero;
  3155. m_requestedSitTargetID = 0;
  3156. SendAvatarDataToAllAgents();
  3157. if (String.IsNullOrEmpty(part.SitAnimation))
  3158. sitAnimation = "SIT";
  3159. else
  3160. sitAnimation = part.SitAnimation;
  3161. Animator.SetMovementAnimations("SIT");
  3162. // TriggerScenePresenceUpdated();
  3163. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  3164. m_scene.EventManager.TriggerParcelPrimCountTainted(); // update select/ sat on
  3165. }
  3166. }
  3167. public void HandleAgentSitOnGround()
  3168. {
  3169. if (IsChildAgent)
  3170. return;
  3171. sitAnimation = "SIT_GROUND_CONSTRAINED";
  3172. SitGround = true;
  3173. RemoveFromPhysicalScene();
  3174. m_AngularVelocity = Vector3.Zero;
  3175. Velocity = Vector3.Zero;
  3176. Animator.SetMovementAnimations("SITGROUND");
  3177. TriggerScenePresenceUpdated();
  3178. }
  3179. /// <summary>
  3180. /// Event handler for the 'Always run' setting on the client
  3181. /// Tells the physics plugin to increase speed of movement.
  3182. /// </summary>
  3183. public void HandleSetAlwaysRun(IClientAPI remoteClient, bool pSetAlwaysRun)
  3184. {
  3185. SetAlwaysRun = pSetAlwaysRun;
  3186. }
  3187. public void HandleStartAnim(IClientAPI remoteClient, UUID animID)
  3188. {
  3189. Animator.AddAnimation(animID, UUID.Zero);
  3190. TriggerScenePresenceUpdated();
  3191. }
  3192. public void HandleStopAnim(IClientAPI remoteClient, UUID animID)
  3193. {
  3194. Animator.RemoveAnimation(animID, false);
  3195. TriggerScenePresenceUpdated();
  3196. }
  3197. public void avnHandleChangeAnim(UUID animID, bool addRemove,bool sendPack)
  3198. {
  3199. Animator.avnChangeAnim(animID, addRemove, sendPack);
  3200. }
  3201. /// <summary>
  3202. /// Rotate the avatar to the given rotation and apply a movement in the given relative vector
  3203. /// </summary>
  3204. /// <param name="vec">The vector in which to move. This is relative to the rotation argument</param>
  3205. /// <param name="thisAddSpeedModifier">
  3206. /// Optional additional speed modifier for this particular add. Default is 1</param>
  3207. public void AddNewMovement(Vector3 vec, float thisAddSpeedModifier = 1, bool breaking = false)
  3208. {
  3209. // m_log.DebugFormat(
  3210. // "[SCENE PRESENCE]: Adding new movement {0} with rotation {1}, thisAddSpeedModifier {2} for {3}",
  3211. // vec, Rotation, thisAddSpeedModifier, Name);
  3212. m_delayedStop = -1;
  3213. // rotate from avatar coord space to world
  3214. Quaternion rot = Rotation;
  3215. if (!Flying && PresenceType != PresenceType.Npc)
  3216. {
  3217. // force rotation to be around Z only, if not flying
  3218. // needed for mouselook
  3219. rot.X = 0;
  3220. rot.Y = 0;
  3221. }
  3222. Vector3 direc = vec * rot;
  3223. direc.Normalize();
  3224. if ((vec.Z == 0f) && !Flying)
  3225. direc.Z = 0f; // Prevent camera WASD up.
  3226. bool notmvtrgt = !m_movingToTarget || m_moveToSpeed <= 0;
  3227. // odd rescalings
  3228. if(notmvtrgt)
  3229. direc *= 4.096f * SpeedModifier * thisAddSpeedModifier;
  3230. else
  3231. direc *= m_moveToSpeed;
  3232. // m_log.DebugFormat("[SCENE PRESENCE]: Force to apply before modification was {0} for {1}", direc, Name);
  3233. if (Animator.currentControlState == ScenePresenceAnimator.motionControlStates.falling
  3234. && (PhysicsActor == null || !PhysicsActor.PIDHoverActive))
  3235. {
  3236. if (breaking)
  3237. direc.Z = -9999f; //hack to tell physics to stop on Z
  3238. else
  3239. direc = Vector3.Zero;
  3240. }
  3241. else if (Flying)
  3242. {
  3243. if (IsColliding && direc.Z < 0)
  3244. // landing situation, prevent avatar moving or it may fail to land
  3245. // animator will handle this condition and do the land
  3246. direc = Vector3.Zero;
  3247. else if(notmvtrgt)
  3248. direc *= 4.0f;
  3249. }
  3250. else if (IsColliding)
  3251. {
  3252. if (direc.Z > 2.0f && notmvtrgt) // reinforce jumps
  3253. {
  3254. direc.Z *= 2.6f;
  3255. }
  3256. else if (direc.Z < 0) // on a surface moving down (pg down) only changes animation
  3257. direc.Z = 0;
  3258. }
  3259. TargetVelocity = direc;
  3260. Animator.UpdateMovementAnimations();
  3261. }
  3262. #endregion
  3263. #region Overridden Methods
  3264. const float ROTATION_TOLERANCE = 0.01f;
  3265. const float VELOCITY_TOLERANCE = 0.1f;
  3266. const float LOWVELOCITYSQ = 0.1f;
  3267. const float POSITION_LARGETOLERANCE = 5f;
  3268. const float POSITION_SMALLTOLERANCE = 0.05f;
  3269. public override void Update()
  3270. {
  3271. if (IsDeleted)
  3272. return;
  3273. if (NeedInitialData > 0)
  3274. {
  3275. SendInitialData();
  3276. return;
  3277. }
  3278. if (IsChildAgent || IsInTransit)
  3279. return;
  3280. CheckForBorderCrossing();
  3281. if (m_movingToTarget)
  3282. {
  3283. m_delayedStop = -1;
  3284. Vector3 control = Vector3.Zero;
  3285. if(HandleMoveToTargetUpdate(1f, ref control))
  3286. AddNewMovement(control);
  3287. }
  3288. else if(m_delayedStop > 0)
  3289. {
  3290. if(IsSatOnObject)
  3291. m_delayedStop = -1;
  3292. else
  3293. if(Util.GetTimeStampMS() > m_delayedStop)
  3294. AddNewMovement(Vector3.Zero);
  3295. }
  3296. if (Appearance.AvatarSize != m_lastSize)
  3297. SendAvatarDataToAllAgents();
  3298. // Send terse position update if not sitting and position, velocity, or rotation
  3299. // has changed significantly from last sent update
  3300. if (!IsSatOnObject)
  3301. {
  3302. // this does need to be more complex later
  3303. Vector3 vel = Velocity;
  3304. Vector3 dpos = m_pos - m_lastPosition;
  3305. if( State != m_lastState ||
  3306. !vel.ApproxEquals(m_lastVelocity) ||
  3307. !m_bodyRot.ApproxEquals(m_lastRotation) ||
  3308. (vel == Vector3.Zero && m_lastVelocity != Vector3.Zero) ||
  3309. Math.Abs(dpos.X) > POSITION_LARGETOLERANCE ||
  3310. Math.Abs(dpos.Y) > POSITION_LARGETOLERANCE ||
  3311. Math.Abs(dpos.Z) > POSITION_LARGETOLERANCE ||
  3312. ( (Math.Abs(dpos.X) > POSITION_SMALLTOLERANCE ||
  3313. Math.Abs(dpos.Y) > POSITION_SMALLTOLERANCE ||
  3314. Math.Abs(dpos.Z) > POSITION_SMALLTOLERANCE)
  3315. && vel.LengthSquared() < LOWVELOCITYSQ
  3316. ) ||
  3317. Math.Abs(CollisionPlane.X - m_lastCollisionPlane.X) > POSITION_SMALLTOLERANCE ||
  3318. Math.Abs(CollisionPlane.Y - m_lastCollisionPlane.Y) > POSITION_SMALLTOLERANCE ||
  3319. Math.Abs(CollisionPlane.W - m_lastCollisionPlane.W) > POSITION_SMALLTOLERANCE
  3320. )
  3321. {
  3322. SendTerseUpdateToAllClients();
  3323. }
  3324. }
  3325. CheckForSignificantMovement();
  3326. }
  3327. #endregion
  3328. #region Update Client(s)
  3329. public void SendUpdateToAgent(ScenePresence p)
  3330. {
  3331. IClientAPI remoteClient = p.ControllingClient;
  3332. if (remoteClient.IsActive)
  3333. {
  3334. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3335. remoteClient.SendEntityUpdate(this, PrimUpdateFlags.FullUpdate);
  3336. m_scene.StatsReporter.AddAgentUpdates(1);
  3337. }
  3338. }
  3339. public void SendFullUpdateToClient(IClientAPI remoteClient)
  3340. {
  3341. if (remoteClient.IsActive)
  3342. {
  3343. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3344. remoteClient.SendEntityUpdate(this, PrimUpdateFlags.FullUpdate);
  3345. m_scene.StatsReporter.AddAgentUpdates(1);
  3346. }
  3347. }
  3348. // this is diferente from SendTerseUpdateToClient
  3349. // this sends bypassing entities updates
  3350. public void SendAgentTerseUpdate(ISceneEntity p)
  3351. {
  3352. ControllingClient.SendAgentTerseUpdate(p);
  3353. }
  3354. /// <summary>
  3355. /// Sends a location update to the client connected to this scenePresence
  3356. /// via entity updates
  3357. /// </summary>
  3358. /// <param name="remoteClient"></param>
  3359. public void SendTerseUpdateToClient(IClientAPI remoteClient)
  3360. {
  3361. // If the client is inactive, it's getting its updates from another
  3362. // server.
  3363. if (remoteClient.IsActive)
  3364. {
  3365. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3366. remoteClient.SendEntityUpdate(
  3367. this,
  3368. PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  3369. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);
  3370. m_scene.StatsReporter.AddAgentUpdates(1);
  3371. }
  3372. }
  3373. public void SendTerseUpdateToAgent(ScenePresence p)
  3374. {
  3375. IClientAPI remoteClient = p.ControllingClient;
  3376. if (!remoteClient.IsActive)
  3377. return;
  3378. if (ParcelHideThisAvatar && p.currentParcelUUID != currentParcelUUID && !p.IsViewerUIGod)
  3379. return;
  3380. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3381. remoteClient.SendEntityUpdate(
  3382. this,
  3383. PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  3384. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);
  3385. m_scene.StatsReporter.AddAgentUpdates(1);
  3386. }
  3387. public void SendTerseUpdateToAgentNF(ScenePresence p)
  3388. {
  3389. IClientAPI remoteClient = p.ControllingClient;
  3390. if (remoteClient.IsActive)
  3391. {
  3392. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3393. remoteClient.SendEntityUpdate(this,
  3394. PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  3395. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);
  3396. m_scene.StatsReporter.AddAgentUpdates(1);
  3397. }
  3398. }
  3399. /// <summary>
  3400. /// Send a location/velocity/accelleration update to all agents in scene
  3401. /// </summary>
  3402. public void SendTerseUpdateToAllClients()
  3403. {
  3404. m_lastState = State;
  3405. m_lastPosition = m_pos;
  3406. m_lastRotation = m_bodyRot;
  3407. m_lastVelocity = Velocity;
  3408. m_lastCollisionPlane = CollisionPlane;
  3409. m_scene.ForEachScenePresence(SendTerseUpdateToAgent);
  3410. // Update the "last" values
  3411. TriggerScenePresenceUpdated();
  3412. }
  3413. public void SendCoarseLocations(List<Vector3> coarseLocations, List<UUID> avatarUUIDs)
  3414. {
  3415. SendCoarseLocationsMethod d = m_sendCoarseLocationsMethod;
  3416. if (d != null)
  3417. {
  3418. d.Invoke(m_scene.RegionInfo.originRegionID, this, coarseLocations, avatarUUIDs);
  3419. }
  3420. }
  3421. public void SetSendCoarseLocationMethod(SendCoarseLocationsMethod d)
  3422. {
  3423. if (d != null)
  3424. m_sendCoarseLocationsMethod = d;
  3425. }
  3426. public void SendCoarseLocationsDefault(UUID sceneId, ScenePresence p, List<Vector3> coarseLocations, List<UUID> avatarUUIDs)
  3427. {
  3428. ControllingClient.SendCoarseLocationUpdate(avatarUUIDs, coarseLocations);
  3429. }
  3430. public void RegionHandShakeReply (IClientAPI client)
  3431. {
  3432. if(IsNPC)
  3433. return;
  3434. lock (m_completeMovementLock)
  3435. {
  3436. if(m_gotRegionHandShake)
  3437. return;
  3438. m_gotRegionHandShake = true;
  3439. NeedInitialData = 2;
  3440. }
  3441. }
  3442. private void SendInitialData()
  3443. {
  3444. uint flags = ControllingClient.GetViewerCaps();
  3445. if ((flags & 0x1000) == 0) // wait for seeds sending
  3446. return;
  3447. if (NeedInitialData < 2)
  3448. return;
  3449. // give some extra time to make sure viewers did process seeds
  3450. if (++NeedInitialData < 6) // needs fix if update rate changes on heartbeat
  3451. return;
  3452. NeedInitialData = -1;
  3453. bool selfappearance = (flags & 4) != 0;
  3454. // this should enqueued on the client processing job to save threads
  3455. Util.FireAndForget(delegate
  3456. {
  3457. if(!IsChildAgent)
  3458. {
  3459. // close v1 sender region obsolete
  3460. if (!string.IsNullOrEmpty(m_callbackURI))
  3461. {
  3462. m_log.DebugFormat(
  3463. "[SCENE PRESENCE({0})]: Releasing {1} {2} with old callback to {3}",
  3464. Scene.RegionInfo.RegionName, Name, UUID, m_callbackURI);
  3465. UUID originID;
  3466. lock (m_originRegionIDAccessLock)
  3467. originID = m_originRegionID;
  3468. Scene.SimulationService.ReleaseAgent(originID, UUID, m_callbackURI);
  3469. m_callbackURI = null;
  3470. }
  3471. // v0.7 close HG sender region
  3472. else if (!string.IsNullOrEmpty(m_newCallbackURI))
  3473. {
  3474. m_log.DebugFormat(
  3475. "[SCENE PRESENCE({0})]: Releasing {1} {2} with callback to {3}",
  3476. Scene.RegionInfo.RegionName, Name, UUID, m_newCallbackURI);
  3477. UUID originID;
  3478. lock (m_originRegionIDAccessLock)
  3479. originID = m_originRegionID;
  3480. Scene.SimulationService.ReleaseAgent(originID, UUID, m_newCallbackURI);
  3481. m_newCallbackURI = null;
  3482. }
  3483. IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
  3484. if (m_agentTransfer != null)
  3485. {
  3486. m_agentTransfer.CloseOldChildAgents(this);
  3487. }
  3488. }
  3489. m_log.DebugFormat("[SCENE PRESENCE({0})]: SendInitialData for {1}", Scene.RegionInfo.RegionName, UUID);
  3490. if (m_teleportFlags <= 0)
  3491. {
  3492. Scene.SendLayerData(ControllingClient);
  3493. ILandChannel landch = m_scene.LandChannel;
  3494. if (landch != null)
  3495. landch.sendClientInitialLandInfo(ControllingClient, true);
  3496. }
  3497. SendOtherAgentsAvatarFullToMe();
  3498. if (m_scene.ObjectsCullingByDistance)
  3499. {
  3500. m_reprioritizationBusy = true;
  3501. m_reprioritizationLastPosition = AbsolutePosition;
  3502. m_reprioritizationLastDrawDistance = DrawDistance;
  3503. ControllingClient.ReprioritizeUpdates();
  3504. m_reprioritizationLastTime = Util.EnvironmentTickCount();
  3505. m_reprioritizationBusy = false;
  3506. }
  3507. else
  3508. {
  3509. //bool cacheCulling = (flags & 1) != 0;
  3510. bool cacheEmpty = (flags & 2) != 0;;
  3511. EntityBase[] entities = Scene.Entities.GetEntities();
  3512. if(cacheEmpty)
  3513. {
  3514. foreach (EntityBase e in entities)
  3515. {
  3516. if (e != null && e is SceneObjectGroup && !((SceneObjectGroup)e).IsAttachment)
  3517. ((SceneObjectGroup)e).SendFullAnimUpdateToClient(ControllingClient);
  3518. }
  3519. }
  3520. else
  3521. {
  3522. foreach (EntityBase e in entities)
  3523. {
  3524. if (e != null && e is SceneObjectGroup && !((SceneObjectGroup)e).IsAttachment)
  3525. {
  3526. SceneObjectGroup grp = e as SceneObjectGroup;
  3527. if(grp.IsViewerCachable)
  3528. grp.SendUpdateProbes(ControllingClient);
  3529. else
  3530. grp.SendFullAnimUpdateToClient(ControllingClient);
  3531. }
  3532. }
  3533. }
  3534. m_reprioritizationLastPosition = AbsolutePosition;
  3535. m_reprioritizationLastDrawDistance = DrawDistance;
  3536. m_reprioritizationLastTime = Util.EnvironmentTickCount() + 15000; // delay it
  3537. m_reprioritizationBusy = false;
  3538. }
  3539. if (!IsChildAgent)
  3540. {
  3541. // Create child agents in neighbouring regions
  3542. IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
  3543. if (m_agentTransfer != null)
  3544. {
  3545. m_agentTransfer.EnableChildAgents(this);
  3546. }
  3547. m_lastChildUpdatesTime = Util.EnvironmentTickCount() + 10000;
  3548. m_lastChildAgentUpdatePosition = AbsolutePosition;
  3549. m_lastChildAgentCheckPosition = m_lastChildAgentUpdatePosition;
  3550. m_lastChildAgentUpdateDrawDistance = DrawDistance;
  3551. m_lastRegionsDrawDistance = RegionViewDistance;
  3552. m_lastChildAgentUpdateGodLevel = GodController.ViwerUIGodLevel;
  3553. m_childUpdatesBusy = false; // allow them
  3554. }
  3555. });
  3556. }
  3557. /// <summary>
  3558. /// Send avatar full data appearance and animations for all other root agents to this agent, this agent
  3559. /// can be either a child or root
  3560. /// </summary>
  3561. public void SendOtherAgentsAvatarFullToMe()
  3562. {
  3563. int count = 0;
  3564. m_scene.ForEachRootScenePresence(delegate(ScenePresence p)
  3565. {
  3566. // only send information about other root agents
  3567. if (p.UUID == UUID)
  3568. return;
  3569. // get the avatar, then a kill if can't see it
  3570. p.SendInitialAvatarDataToAgent(this);
  3571. if (p.ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !IsViewerUIGod)
  3572. return;
  3573. p.SendAppearanceToAgentNF(this);
  3574. p.SendAnimPackToAgentNF(this);
  3575. p.SendAttachmentsToAgentNF(this);
  3576. count++;
  3577. });
  3578. m_scene.StatsReporter.AddAgentUpdates(count);
  3579. }
  3580. /// <summary>
  3581. /// Send this agent's avatar data to all other root and child agents in the scene
  3582. /// This agent must be root. This avatar will receive its own update.
  3583. /// </summary>
  3584. public void SendAvatarDataToAllAgents()
  3585. {
  3586. //m_log.DebugFormat("[SCENE PRESENCE] SendAvatarDataToAllAgents: {0} ({1})", Name, UUID);
  3587. // only send update from root agents to other clients; children are only "listening posts"
  3588. if (IsChildAgent)
  3589. {
  3590. m_log.WarnFormat(
  3591. "[SCENE PRESENCE]: Attempt to send avatar data from a child agent for {0} in {1}",
  3592. Name, Scene.RegionInfo.RegionName);
  3593. return;
  3594. }
  3595. m_lastSize = Appearance.AvatarSize;
  3596. int count = 0;
  3597. m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
  3598. {
  3599. SendAvatarDataToAgent(scenePresence);
  3600. count++;
  3601. });
  3602. m_scene.StatsReporter.AddAgentUpdates(count);
  3603. }
  3604. // sends avatar object to all clients so they cross it into region
  3605. // then sends kills to hide
  3606. public void SendInitialAvatarDataToAllAgents(List<ScenePresence> presences)
  3607. {
  3608. m_lastSize = Appearance.AvatarSize;
  3609. int count = 0;
  3610. SceneObjectPart sitroot = null;
  3611. if (ParentID != 0 && ParentPart != null) // we need to send the sitting root prim
  3612. {
  3613. sitroot = ParentPart.ParentGroup.RootPart;
  3614. }
  3615. foreach (ScenePresence p in presences)
  3616. {
  3617. if (sitroot != null) // we need to send the sitting root prim
  3618. {
  3619. p.ControllingClient.SendEntityFullUpdateImmediate(ParentPart.ParentGroup.RootPart);
  3620. }
  3621. p.ControllingClient.SendEntityFullUpdateImmediate(this);
  3622. if (p != this && ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3623. // either just kill the object
  3624. // p.ControllingClient.SendKillObject(new List<uint> {LocalId});
  3625. // or also attachments viewer may still know about
  3626. SendKillTo(p);
  3627. count++;
  3628. }
  3629. m_scene.StatsReporter.AddAgentUpdates(count);
  3630. }
  3631. public void SendInitialAvatarDataToAgent(ScenePresence p)
  3632. {
  3633. if(ParentID != 0 && ParentPart != null) // we need to send the sitting root prim
  3634. {
  3635. p.ControllingClient.SendEntityFullUpdateImmediate(ParentPart.ParentGroup.RootPart);
  3636. }
  3637. p.ControllingClient.SendEntityFullUpdateImmediate(this);
  3638. if (p != this && ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3639. // either just kill the object
  3640. // p.ControllingClient.SendKillObject(new List<uint> {LocalId});
  3641. // or also attachments viewer may still know about
  3642. SendKillTo(p);
  3643. }
  3644. /// <summary>
  3645. /// Send avatar data to an agent.
  3646. /// </summary>
  3647. /// <param name="avatar"></param>
  3648. public void SendAvatarDataToAgent(ScenePresence avatar)
  3649. {
  3650. //m_log.DebugFormat("[SCENE PRESENCE] SendAvatarDataToAgent from {0} ({1}) to {2} ({3})", Name, UUID, avatar.Name, avatar.UUID);
  3651. if (ParcelHideThisAvatar && currentParcelUUID != avatar.currentParcelUUID && !avatar.IsViewerUIGod)
  3652. return;
  3653. avatar.ControllingClient.SendEntityFullUpdateImmediate(this);
  3654. }
  3655. public void SendAvatarDataToAgentNF(ScenePresence avatar)
  3656. {
  3657. avatar.ControllingClient.SendEntityFullUpdateImmediate(this);
  3658. }
  3659. /// <summary>
  3660. /// Send this agent's appearance to all other root and child agents in the scene
  3661. /// This agent must be root.
  3662. /// </summary>
  3663. public void SendAppearanceToAllOtherAgents()
  3664. {
  3665. // m_log.DebugFormat("[SCENE PRESENCE] SendAppearanceToAllOtherAgents: {0} {1}", Name, UUID);
  3666. // only send update from root agents to other clients; children are only "listening posts"
  3667. if (IsChildAgent)
  3668. {
  3669. m_log.WarnFormat(
  3670. "[SCENE PRESENCE]: Attempt to send avatar data from a child agent for {0} in {1}",
  3671. Name, Scene.RegionInfo.RegionName);
  3672. return;
  3673. }
  3674. int count = 0;
  3675. m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
  3676. {
  3677. // only send information to other root agents
  3678. if (scenePresence.UUID == UUID)
  3679. return;
  3680. SendAppearanceToAgent(scenePresence);
  3681. count++;
  3682. });
  3683. m_scene.StatsReporter.AddAgentUpdates(count);
  3684. }
  3685. public void SendAppearanceToAgent(ScenePresence avatar)
  3686. {
  3687. // m_log.DebugFormat(
  3688. // "[SCENE PRESENCE]: Sending appearance data from {0} {1} to {2} {3}", Name, m_uuid, avatar.Name, avatar.UUID);
  3689. if (ParcelHideThisAvatar && currentParcelUUID != avatar.currentParcelUUID && !avatar.IsViewerUIGod)
  3690. return;
  3691. SendAppearanceToAgentNF(avatar);
  3692. }
  3693. public void SendAppearanceToAgentNF(ScenePresence avatar)
  3694. {
  3695. avatar.ControllingClient.SendAppearance(UUID, Appearance.VisualParams, Appearance.Texture.GetBakesBytes(), Appearance.AvatarPreferencesHoverZ);
  3696. }
  3697. public void SendAnimPackToAgent(ScenePresence p)
  3698. {
  3699. if (IsChildAgent || Animator == null)
  3700. return;
  3701. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3702. return;
  3703. Animator.SendAnimPackToClient(p.ControllingClient);
  3704. }
  3705. public void SendAnimPackToAgent(ScenePresence p, UUID[] animations, int[] seqs, UUID[] objectIDs)
  3706. {
  3707. if (IsChildAgent)
  3708. return;
  3709. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3710. return;
  3711. p.ControllingClient.SendAnimations(animations, seqs, ControllingClient.AgentId, objectIDs);
  3712. }
  3713. public void SendAnimPackToAgentNF(ScenePresence p)
  3714. {
  3715. if (IsChildAgent || Animator == null)
  3716. return;
  3717. Animator.SendAnimPackToClient(p.ControllingClient);
  3718. }
  3719. public void SendAnimPackToAgentNF(ScenePresence p, UUID[] animations, int[] seqs, UUID[] objectIDs)
  3720. {
  3721. p.ControllingClient.SendAnimations(animations, seqs, ControllingClient.AgentId, objectIDs);
  3722. }
  3723. public void SendAnimPack(UUID[] animations, int[] seqs, UUID[] objectIDs)
  3724. {
  3725. if (IsChildAgent)
  3726. return;
  3727. m_scene.ForEachScenePresence(delegate(ScenePresence p)
  3728. {
  3729. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3730. return;
  3731. p.ControllingClient.SendAnimations(animations, seqs, ControllingClient.AgentId, objectIDs);
  3732. });
  3733. }
  3734. #endregion
  3735. #region Significant Movement Method
  3736. private void checkRePrioritization()
  3737. {
  3738. if(IsDeleted || !ControllingClient.IsActive)
  3739. return;
  3740. if(m_reprioritizationBusy)
  3741. return;
  3742. float limit = Scene.ReprioritizationDistance;
  3743. bool byDrawdistance = Scene.ObjectsCullingByDistance;
  3744. if(byDrawdistance)
  3745. {
  3746. float minregionSize = Scene.RegionInfo.RegionSizeX;
  3747. if(minregionSize > Scene.RegionInfo.RegionSizeY)
  3748. minregionSize = Scene.RegionInfo.RegionSizeY;
  3749. minregionSize *= 0.5f;
  3750. if(DrawDistance > minregionSize && m_reprioritizationLastDrawDistance > minregionSize)
  3751. byDrawdistance = false;
  3752. else
  3753. byDrawdistance = (Math.Abs(DrawDistance - m_reprioritizationLastDrawDistance) > 0.5f * limit);
  3754. }
  3755. int tdiff = Util.EnvironmentTickCountSubtract(m_reprioritizationLastTime);
  3756. if(!byDrawdistance && tdiff < Scene.ReprioritizationInterval)
  3757. return;
  3758. // priority uses avatar position
  3759. Vector3 pos = AbsolutePosition;
  3760. Vector3 diff = pos - m_reprioritizationLastPosition;
  3761. limit *= limit;
  3762. if (!byDrawdistance && diff.LengthSquared() < limit)
  3763. return;
  3764. m_reprioritizationBusy = true;
  3765. m_reprioritizationLastPosition = pos;
  3766. m_reprioritizationLastDrawDistance = DrawDistance;
  3767. Util.FireAndForget(
  3768. o =>
  3769. {
  3770. ControllingClient.ReprioritizeUpdates();
  3771. m_reprioritizationLastTime = Util.EnvironmentTickCount();
  3772. m_reprioritizationBusy = false;
  3773. }, null, "ScenePresence.Reprioritization");
  3774. }
  3775. /// <summary>
  3776. /// This checks for a significant movement and sends a coarselocationchange update
  3777. /// </summary>
  3778. protected void CheckForSignificantMovement()
  3779. {
  3780. Vector3 pos = AbsolutePosition;
  3781. Vector3 diff = pos - posLastMove;
  3782. if (diff.LengthSquared() > MOVEMENT)
  3783. {
  3784. posLastMove = pos;
  3785. m_scene.EventManager.TriggerOnClientMovement(this);
  3786. }
  3787. diff = pos - posLastSignificantMove;
  3788. if (diff.LengthSquared() > SIGNIFICANT_MOVEMENT)
  3789. {
  3790. posLastSignificantMove = pos;
  3791. m_scene.EventManager.TriggerSignificantClientMovement(this);
  3792. }
  3793. if(IsNPC)
  3794. return;
  3795. // updates priority recalc
  3796. checkRePrioritization();
  3797. if(m_childUpdatesBusy || RegionViewDistance == 0)
  3798. return;
  3799. int tdiff = Util.EnvironmentTickCountSubtract(m_lastChildUpdatesTime);
  3800. if (tdiff < CHILDUPDATES_TIME)
  3801. return;
  3802. bool viewchanged = Math.Abs(RegionViewDistance - m_lastRegionsDrawDistance) > 32.0f;
  3803. IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
  3804. float dx = pos.X - m_lastChildAgentCheckPosition.X;
  3805. float dy = pos.Y - m_lastChildAgentCheckPosition.Y;
  3806. if ((m_agentTransfer != null) && (viewchanged || ((dx * dx + dy * dy) > CHILDAGENTSCHECK_MOVEMENT)))
  3807. {
  3808. m_childUpdatesBusy = true;
  3809. m_lastChildAgentCheckPosition = pos;
  3810. m_lastChildAgentUpdatePosition = pos;
  3811. m_lastChildAgentUpdateGodLevel = GodController.ViwerUIGodLevel;
  3812. m_lastChildAgentUpdateDrawDistance = DrawDistance;
  3813. m_lastRegionsDrawDistance = RegionViewDistance;
  3814. // m_lastChildAgentUpdateCamPosition = CameraPosition;
  3815. Util.FireAndForget(
  3816. o =>
  3817. {
  3818. m_agentTransfer.EnableChildAgents(this);
  3819. m_lastChildUpdatesTime = Util.EnvironmentTickCount();
  3820. m_childUpdatesBusy = false;
  3821. }, null, "ScenePresence.CheckChildAgents");
  3822. }
  3823. else
  3824. {
  3825. //possible KnownRegionHandles always contains current region and this check is not needed
  3826. int minhandles = KnownRegionHandles.Contains(RegionHandle) ? 1 : 0;
  3827. if(KnownRegionHandles.Count > minhandles)
  3828. {
  3829. bool doUpdate = false;
  3830. if (m_lastChildAgentUpdateGodLevel != GodController.ViwerUIGodLevel)
  3831. doUpdate = true;
  3832. if (Math.Abs(DrawDistance - m_lastChildAgentUpdateDrawDistance) > 32.0f)
  3833. doUpdate = true;
  3834. if(!doUpdate)
  3835. {
  3836. diff = pos - m_lastChildAgentUpdatePosition;
  3837. if (diff.LengthSquared() > CHILDUPDATES_MOVEMENT)
  3838. doUpdate = true;
  3839. }
  3840. if (doUpdate)
  3841. {
  3842. m_childUpdatesBusy = true;
  3843. m_lastChildAgentUpdatePosition = pos;
  3844. m_lastChildAgentUpdateGodLevel = GodController.ViwerUIGodLevel;
  3845. m_lastChildAgentUpdateDrawDistance = DrawDistance;
  3846. // m_lastChildAgentUpdateCamPosition = CameraPosition;
  3847. AgentPosition agentpos = new AgentPosition();
  3848. agentpos.AgentID = new UUID(UUID.Guid);
  3849. agentpos.SessionID = ControllingClient.SessionId;
  3850. agentpos.Size = Appearance.AvatarSize;
  3851. agentpos.Center = CameraPosition;
  3852. agentpos.Far = DrawDistance;
  3853. agentpos.Position = AbsolutePosition;
  3854. agentpos.Velocity = Velocity;
  3855. agentpos.RegionHandle = RegionHandle;
  3856. agentpos.GodData = GodController.State();
  3857. agentpos.Throttles = ControllingClient.GetThrottlesPacked(1);
  3858. // Let's get this out of the update loop
  3859. Util.FireAndForget(
  3860. o =>
  3861. {
  3862. m_scene.SendOutChildAgentUpdates(agentpos, this);
  3863. m_lastChildUpdatesTime = Util.EnvironmentTickCount();
  3864. m_childUpdatesBusy = false;
  3865. }, null, "ScenePresence.SendOutChildAgentUpdates");
  3866. }
  3867. }
  3868. }
  3869. }
  3870. #endregion
  3871. #region Border Crossing Methods
  3872. /// <summary>
  3873. /// Starts the process of moving an avatar into another region if they are crossing the border.
  3874. /// </summary>
  3875. /// <remarks>
  3876. /// Also removes the avatar from the physical scene if transit has started.
  3877. /// </remarks>
  3878. protected void CheckForBorderCrossing()
  3879. {
  3880. // Check that we we are not a child
  3881. if (IsChildAgent || IsInTransit)
  3882. return;
  3883. // If we don't have a PhysActor, we can't cross anyway
  3884. // Also don't do this while sat, sitting avatars cross with the
  3885. // object they sit on. ParentUUID denoted a pending sit, don't
  3886. // interfere with it.
  3887. if (ParentID != 0 || PhysicsActor == null || ParentUUID != UUID.Zero)
  3888. return;
  3889. Vector3 pos2 = AbsolutePosition;
  3890. Vector3 vel = Velocity;
  3891. float timeStep = 0.1f;
  3892. pos2.X += vel.X * timeStep;
  3893. pos2.Y += vel.Y * timeStep;
  3894. pos2.Z += vel.Z * timeStep;
  3895. // m_log.DebugFormat(
  3896. // "[SCENE PRESENCE]: Testing border check for projected position {0} of {1} in {2}",
  3897. // pos2, Name, Scene.Name);
  3898. if (Scene.PositionIsInCurrentRegion(pos2))
  3899. return;
  3900. if (!CrossToNewRegion() && m_requestedSitTargetUUID == UUID.Zero)
  3901. {
  3902. // we don't have entity transfer module
  3903. Vector3 pos = AbsolutePosition;
  3904. vel = Velocity;
  3905. float px = pos.X;
  3906. if (px < 0)
  3907. pos.X += vel.X * 2;
  3908. else if (px > m_scene.RegionInfo.RegionSizeX)
  3909. pos.X -= vel.X * 2;
  3910. float py = pos.Y;
  3911. if (py < 0)
  3912. pos.Y += vel.Y * 2;
  3913. else if (py > m_scene.RegionInfo.RegionSizeY)
  3914. pos.Y -= vel.Y * 2;
  3915. Velocity = Vector3.Zero;
  3916. m_AngularVelocity = Vector3.Zero;
  3917. AbsolutePosition = pos;
  3918. }
  3919. }
  3920. public void CrossToNewRegionFail()
  3921. {
  3922. if (m_requestedSitTargetUUID == UUID.Zero)
  3923. {
  3924. bool isFlying = Flying;
  3925. RemoveFromPhysicalScene();
  3926. Vector3 pos = AbsolutePosition;
  3927. Vector3 vel = Velocity;
  3928. float px = pos.X;
  3929. if (px < 0)
  3930. pos.X += vel.X * 2;
  3931. else if (px > m_scene.RegionInfo.RegionSizeX)
  3932. pos.X -= vel.X * 2;
  3933. float py = pos.Y;
  3934. if (py < 0)
  3935. pos.Y += vel.Y * 2;
  3936. else if (py > m_scene.RegionInfo.RegionSizeY)
  3937. pos.Y -= vel.Y * 2;
  3938. Velocity = Vector3.Zero;
  3939. m_AngularVelocity = Vector3.Zero;
  3940. AbsolutePosition = pos;
  3941. AddToPhysicalScene(isFlying);
  3942. }
  3943. }
  3944. /// <summary>
  3945. /// Moves the agent outside the region bounds
  3946. /// Tells neighbor region that we're crossing to it
  3947. /// If the neighbor accepts, remove the agent's viewable avatar from this scene
  3948. /// set them to a child agent.
  3949. /// </summary>
  3950. protected bool CrossToNewRegion()
  3951. {
  3952. bool result = false;
  3953. // parcelRegionCross(false);
  3954. try
  3955. {
  3956. result = m_scene.CrossAgentToNewRegion(this, Flying);
  3957. }
  3958. catch
  3959. {
  3960. // result = m_scene.CrossAgentToNewRegion(this, false);
  3961. return false;
  3962. }
  3963. // if(!result)
  3964. // parcelRegionCross(true);
  3965. return result;
  3966. }
  3967. /// <summary>
  3968. /// Computes which child agents to close when the scene presence moves to another region.
  3969. /// Removes those regions from m_knownRegions.
  3970. /// </summary>
  3971. /// <param name="newRegionHandle">The new region's handle</param>
  3972. /// <param name="newRegionSizeX">The new region's size x</param>
  3973. /// <param name="newRegionSizeY">The new region's size y</param>
  3974. /// <returns></returns>
  3975. public List<ulong> GetChildAgentsToClose(ulong newRegionHandle, int newRegionSizeX, int newRegionSizeY)
  3976. {
  3977. ulong curRegionHandle = m_scene.RegionInfo.RegionHandle;
  3978. List<ulong> byebyeRegions = new List<ulong>();
  3979. if(newRegionHandle == curRegionHandle) //??
  3980. return byebyeRegions;
  3981. uint newRegionX, newRegionY;
  3982. List<ulong> knownRegions = KnownRegionHandles;
  3983. m_log.DebugFormat(
  3984. "[SCENE PRESENCE]: Closing child agents. Checking {0} regions in {1}",
  3985. knownRegions.Count, Scene.RegionInfo.RegionName);
  3986. Util.RegionHandleToRegionLoc(newRegionHandle, out newRegionX, out newRegionY);
  3987. uint x, y;
  3988. spRegionSizeInfo regInfo;
  3989. foreach (ulong handle in knownRegions)
  3990. {
  3991. if(newRegionY == 0) // HG
  3992. byebyeRegions.Add(handle);
  3993. else if(handle == curRegionHandle)
  3994. {
  3995. continue;
  3996. /*
  3997. RegionInfo curreg = m_scene.RegionInfo;
  3998. if (Util.IsOutsideView(255, curreg.RegionLocX, newRegionX, curreg.RegionLocY, newRegionY,
  3999. (int)curreg.RegionSizeX, (int)curreg.RegionSizeX, newRegionSizeX, newRegionSizeY))
  4000. {
  4001. byebyeRegions.Add(handle);
  4002. }
  4003. */
  4004. }
  4005. else
  4006. {
  4007. Util.RegionHandleToRegionLoc(handle, out x, out y);
  4008. if (m_knownChildRegionsSizeInfo.TryGetValue(handle, out regInfo))
  4009. {
  4010. // if (Util.IsOutsideView(RegionViewDistance, x, newRegionX, y, newRegionY,
  4011. // for now need to close all but first order bc RegionViewDistance it the target value not ours
  4012. if (Util.IsOutsideView(255, x, newRegionX, y, newRegionY,
  4013. regInfo.sizeX, regInfo.sizeY, newRegionSizeX, newRegionSizeY))
  4014. {
  4015. byebyeRegions.Add(handle);
  4016. }
  4017. }
  4018. else
  4019. {
  4020. // if (Util.IsOutsideView(RegionViewDistance, x, newRegionX, y, newRegionY,
  4021. if (Util.IsOutsideView(255, x, newRegionX, y, newRegionY,
  4022. (int)Constants.RegionSize, (int)Constants.RegionSize, newRegionSizeX, newRegionSizeY))
  4023. {
  4024. byebyeRegions.Add(handle);
  4025. }
  4026. }
  4027. }
  4028. }
  4029. return byebyeRegions;
  4030. }
  4031. public void CloseChildAgents(List<ulong> byebyeRegions)
  4032. {
  4033. byebyeRegions.Remove(Scene.RegionInfo.RegionHandle);
  4034. if (byebyeRegions.Count > 0)
  4035. {
  4036. m_log.Debug("[SCENE PRESENCE]: Closing " + byebyeRegions.Count + " child agents");
  4037. AgentCircuitData acd = Scene.AuthenticateHandler.GetAgentCircuitData(UUID);
  4038. string auth = string.Empty;
  4039. if (acd != null)
  4040. auth = acd.SessionID.ToString();
  4041. m_scene.SceneGridService.SendCloseChildAgentConnections(ControllingClient.AgentId, auth, byebyeRegions);
  4042. }
  4043. foreach (ulong handle in byebyeRegions)
  4044. {
  4045. RemoveNeighbourRegion(handle);
  4046. Scene.CapsModule.DropChildSeed(UUID, handle);
  4047. }
  4048. }
  4049. public void closeAllChildAgents()
  4050. {
  4051. List<ulong> byebyeRegions = new List<ulong>();
  4052. List<ulong> knownRegions = KnownRegionHandles;
  4053. foreach (ulong handle in knownRegions)
  4054. {
  4055. if (handle != Scene.RegionInfo.RegionHandle)
  4056. {
  4057. byebyeRegions.Add(handle);
  4058. RemoveNeighbourRegion(handle);
  4059. Scene.CapsModule.DropChildSeed(UUID, handle);
  4060. }
  4061. }
  4062. if (byebyeRegions.Count > 0)
  4063. {
  4064. m_log.Debug("[SCENE PRESENCE]: Closing " + byebyeRegions.Count + " child agents");
  4065. AgentCircuitData acd = Scene.AuthenticateHandler.GetAgentCircuitData(UUID);
  4066. string auth = string.Empty;
  4067. if (acd != null)
  4068. auth = acd.SessionID.ToString();
  4069. m_scene.SceneGridService.SendCloseChildAgentConnections(ControllingClient.AgentId, auth, byebyeRegions);
  4070. }
  4071. }
  4072. #endregion
  4073. /// <summary>
  4074. /// handle god level requests.
  4075. /// </summary>
  4076. public void GrantGodlikePowers(UUID token, bool godStatus)
  4077. {
  4078. if (IsNPC)
  4079. return;
  4080. bool wasgod = IsViewerUIGod;
  4081. GodController.RequestGodMode(godStatus);
  4082. if (wasgod != IsViewerUIGod)
  4083. parcelGodCheck(m_currentParcelUUID);
  4084. }
  4085. #region Child Agent Updates
  4086. public void UpdateChildAgent(AgentData cAgentData)
  4087. {
  4088. // m_log.Debug(" >>> ChildAgentDataUpdate <<< " + Scene.RegionInfo.RegionName);
  4089. if (!IsChildAgent)
  4090. return;
  4091. CopyFrom(cAgentData);
  4092. m_updateAgentReceivedAfterTransferEvent.Set();
  4093. }
  4094. private static Vector3 marker = new Vector3(-1f, -1f, -1f);
  4095. private void RaiseUpdateThrottles()
  4096. {
  4097. if(m_capbandwidth > 0)
  4098. return;
  4099. m_bandwidth = 4 * ControllingClient.GetAgentThrottleSilent((int)ThrottleOutPacketType.Texture);
  4100. if(m_bandwidth < 50000)
  4101. m_bandwidth = 50000;
  4102. m_bandwidthBurst = m_bandwidth / 5;
  4103. }
  4104. /// <summary>
  4105. /// This updates important decision making data about a child agent
  4106. /// The main purpose is to figure out what objects to send to a child agent that's in a neighboring region
  4107. /// </summary>
  4108. public void UpdateChildAgent(AgentPosition cAgentData)
  4109. {
  4110. if (!IsChildAgent)
  4111. return;
  4112. GodController.SetState(cAgentData.GodData);
  4113. RegionHandle = cAgentData.RegionHandle;
  4114. uint rRegionX = (uint)(RegionHandle >> 40);
  4115. uint rRegionY = (((uint)RegionHandle) >> 8);
  4116. uint tRegionX = m_scene.RegionInfo.RegionLocX;
  4117. uint tRegionY = m_scene.RegionInfo.RegionLocY;
  4118. //m_log.Debug(" >>> ChildAgentPositionUpdate <<< " + rRegionX + "-" + rRegionY);
  4119. int shiftx = ((int)rRegionX - (int)tRegionX) * (int)Constants.RegionSize;
  4120. int shifty = ((int)rRegionY - (int)tRegionY) * (int)Constants.RegionSize;
  4121. Vector3 offset = new Vector3(shiftx, shifty, 0f);
  4122. DrawDistance = cAgentData.Far;
  4123. m_pos = cAgentData.Position + offset;
  4124. CameraPosition = cAgentData.Center + offset;
  4125. if (cAgentData.ChildrenCapSeeds != null && cAgentData.ChildrenCapSeeds.Count > 0)
  4126. {
  4127. if (Scene.CapsModule != null)
  4128. {
  4129. Scene.CapsModule.SetChildrenSeed(UUID, cAgentData.ChildrenCapSeeds);
  4130. }
  4131. KnownRegions = cAgentData.ChildrenCapSeeds;
  4132. }
  4133. if ((cAgentData.Throttles != null) && cAgentData.Throttles.Length > 0)
  4134. {
  4135. // some scaling factor
  4136. float x = m_pos.X;
  4137. if (x > m_scene.RegionInfo.RegionSizeX)
  4138. x -= m_scene.RegionInfo.RegionSizeX;
  4139. float y = m_pos.Y;
  4140. if (y > m_scene.RegionInfo.RegionSizeY)
  4141. y -= m_scene.RegionInfo.RegionSizeY;
  4142. x = x * x + y * y;
  4143. float factor = 1.0f - x * 0.3f / Constants.RegionSize / Constants.RegionSize;
  4144. if (factor < 0.2f)
  4145. factor = 0.2f;
  4146. ControllingClient.SetChildAgentThrottle(cAgentData.Throttles,factor);
  4147. }
  4148. //cAgentData.AVHeight;
  4149. //m_velocity = cAgentData.Velocity;
  4150. checkRePrioritization();
  4151. }
  4152. public void CopyTo(AgentData cAgent, bool isCrossUpdate)
  4153. {
  4154. cAgent.CallbackURI = m_callbackURI;
  4155. cAgent.NewCallbackURI = m_newCallbackURI;
  4156. cAgent.AgentID = UUID;
  4157. cAgent.RegionID = Scene.RegionInfo.RegionID;
  4158. cAgent.SessionID = ControllingClient.SessionId;
  4159. cAgent.Position = AbsolutePosition;
  4160. cAgent.Velocity = m_velocity;
  4161. cAgent.Center = CameraPosition;
  4162. cAgent.AtAxis = CameraAtAxis;
  4163. cAgent.LeftAxis = CameraLeftAxis;
  4164. cAgent.UpAxis = CameraUpAxis;
  4165. cAgent.Far = DrawDistance;
  4166. cAgent.GodData = GodController.State();
  4167. // Throttles
  4168. cAgent.Throttles = ControllingClient.GetThrottlesPacked(1);
  4169. cAgent.HeadRotation = m_headrotation;
  4170. cAgent.BodyRotation = Rotation;
  4171. cAgent.ControlFlags = (uint)m_AgentControlFlags;
  4172. cAgent.AlwaysRun = SetAlwaysRun;
  4173. // make clear we want the all thing
  4174. cAgent.Appearance = new AvatarAppearance(Appearance,true,true);
  4175. cAgent.ParentPart = ParentUUID;
  4176. cAgent.SitOffset = PrevSitOffset;
  4177. lock (scriptedcontrols)
  4178. {
  4179. ControllerData[] controls = new ControllerData[scriptedcontrols.Count];
  4180. int i = 0;
  4181. foreach (ScriptControllers c in scriptedcontrols.Values)
  4182. {
  4183. controls[i++] = new ControllerData(c.objectID, c.itemID, (uint)c.ignoreControls, (uint)c.eventControls);
  4184. }
  4185. cAgent.Controllers = controls;
  4186. }
  4187. // Animations
  4188. try
  4189. {
  4190. cAgent.Anims = Animator.Animations.ToArray();
  4191. }
  4192. catch { }
  4193. cAgent.DefaultAnim = Animator.Animations.DefaultAnimation;
  4194. cAgent.AnimState = Animator.Animations.ImplicitDefaultAnimation;
  4195. cAgent.MovementAnimationOverRides = Overrides.CloneAOPairs();
  4196. cAgent.MotionState = (byte)Animator.currentControlState;
  4197. if (Scene.AttachmentsModule != null)
  4198. Scene.AttachmentsModule.CopyAttachments(this, cAgent);
  4199. if(isCrossUpdate)
  4200. {
  4201. cAgent.CrossingFlags = m_crossingFlags;
  4202. cAgent.CrossingFlags |= 1;
  4203. cAgent.CrossExtraFlags = 0;
  4204. if((LastCommands & ScriptControlled.CONTROL_LBUTTON) != 0)
  4205. cAgent.CrossExtraFlags |= 1;
  4206. if((LastCommands & ScriptControlled.CONTROL_ML_LBUTTON) != 0)
  4207. cAgent.CrossExtraFlags |= 2;
  4208. }
  4209. else
  4210. cAgent.CrossingFlags = 0;
  4211. if(isCrossUpdate)
  4212. {
  4213. //cAgent.agentCOF = COF;
  4214. cAgent.ActiveGroupID = ControllingClient.ActiveGroupId;
  4215. cAgent.ActiveGroupName = ControllingClient.ActiveGroupName;
  4216. if(Grouptitle == null)
  4217. cAgent.ActiveGroupTitle = String.Empty;
  4218. else
  4219. cAgent.ActiveGroupTitle = Grouptitle;
  4220. }
  4221. }
  4222. private void CopyFrom(AgentData cAgent)
  4223. {
  4224. m_callbackURI = cAgent.CallbackURI;
  4225. m_newCallbackURI = cAgent.NewCallbackURI;
  4226. // m_log.DebugFormat(
  4227. // "[SCENE PRESENCE]: Set callback for {0} in {1} to {2} in CopyFrom()",
  4228. // Name, m_scene.RegionInfo.RegionName, m_callbackURI);
  4229. GodController.SetState(cAgent.GodData);
  4230. m_pos = cAgent.Position;
  4231. m_velocity = cAgent.Velocity;
  4232. CameraPosition = cAgent.Center;
  4233. CameraAtAxis = cAgent.AtAxis;
  4234. CameraLeftAxis = cAgent.LeftAxis;
  4235. CameraUpAxis = cAgent.UpAxis;
  4236. Quaternion camRot = Util.Axes2Rot(CameraAtAxis, CameraLeftAxis, CameraUpAxis);
  4237. CameraRotation = camRot;
  4238. ParentUUID = cAgent.ParentPart;
  4239. PrevSitOffset = cAgent.SitOffset;
  4240. // When we get to the point of re-computing neighbors everytime this
  4241. // changes, then start using the agent's drawdistance rather than the
  4242. // region's draw distance.
  4243. DrawDistance = cAgent.Far;
  4244. //DrawDistance = Scene.DefaultDrawDistance;
  4245. if (cAgent.ChildrenCapSeeds != null && cAgent.ChildrenCapSeeds.Count > 0)
  4246. {
  4247. if (Scene.CapsModule != null)
  4248. {
  4249. Scene.CapsModule.SetChildrenSeed(UUID, cAgent.ChildrenCapSeeds);
  4250. }
  4251. KnownRegions = cAgent.ChildrenCapSeeds;
  4252. }
  4253. if ((cAgent.Throttles != null) && cAgent.Throttles.Length > 0)
  4254. ControllingClient.SetChildAgentThrottle(cAgent.Throttles, 1.0f);
  4255. m_headrotation = cAgent.HeadRotation;
  4256. Rotation = cAgent.BodyRotation;
  4257. m_AgentControlFlags = (AgentManager.ControlFlags)cAgent.ControlFlags;
  4258. SetAlwaysRun = cAgent.AlwaysRun;
  4259. Appearance = new AvatarAppearance(cAgent.Appearance);
  4260. /*
  4261. bool isFlying = ((m_AgentControlFlags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  4262. if (PhysicsActor != null)
  4263. {
  4264. RemoveFromPhysicalScene();
  4265. AddToPhysicalScene(isFlying);
  4266. }
  4267. */
  4268. if (Scene.AttachmentsModule != null)
  4269. Scene.AttachmentsModule.CopyAttachments(cAgent, this);
  4270. try
  4271. {
  4272. lock (scriptedcontrols)
  4273. {
  4274. if (cAgent.Controllers != null)
  4275. {
  4276. scriptedcontrols.Clear();
  4277. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  4278. foreach (ControllerData c in cAgent.Controllers)
  4279. {
  4280. ScriptControllers sc = new ScriptControllers();
  4281. sc.objectID = c.ObjectID;
  4282. sc.itemID = c.ItemID;
  4283. sc.ignoreControls = (ScriptControlled)c.IgnoreControls;
  4284. sc.eventControls = (ScriptControlled)c.EventControls;
  4285. scriptedcontrols[sc.itemID] = sc;
  4286. IgnoredControls |= sc.ignoreControls; // this is not correct, aparently only last applied should count
  4287. }
  4288. }
  4289. }
  4290. }
  4291. catch { }
  4292. // we are losing animator somewhere
  4293. if (Animator == null)
  4294. Animator = new ScenePresenceAnimator(this);
  4295. else
  4296. Animator.ResetAnimations();
  4297. Overrides.CopyAOPairsFrom(cAgent.MovementAnimationOverRides);
  4298. int nanim = ControllingClient.NextAnimationSequenceNumber;
  4299. // FIXME: Why is this null check necessary? Where are the cases where we get a null Anims object?
  4300. if (cAgent.DefaultAnim != null)
  4301. {
  4302. if (cAgent.DefaultAnim.SequenceNum > nanim)
  4303. nanim = cAgent.DefaultAnim.SequenceNum;
  4304. Animator.Animations.SetDefaultAnimation(cAgent.DefaultAnim.AnimID, cAgent.DefaultAnim.SequenceNum, UUID.Zero);
  4305. }
  4306. if (cAgent.AnimState != null)
  4307. {
  4308. if (cAgent.AnimState.SequenceNum > nanim)
  4309. nanim = cAgent.AnimState.SequenceNum;
  4310. Animator.Animations.SetImplicitDefaultAnimation(cAgent.AnimState.AnimID, cAgent.AnimState.SequenceNum, UUID.Zero);
  4311. }
  4312. if (cAgent.Anims != null)
  4313. {
  4314. int canim = Animator.Animations.FromArray(cAgent.Anims);
  4315. if(canim > nanim)
  4316. nanim = canim;
  4317. }
  4318. ControllingClient.NextAnimationSequenceNumber = ++nanim;
  4319. if (cAgent.MotionState != 0)
  4320. Animator.currentControlState = (ScenePresenceAnimator.motionControlStates) cAgent.MotionState;
  4321. m_crossingFlags = cAgent.CrossingFlags;
  4322. m_gotCrossUpdate = (m_crossingFlags != 0);
  4323. if(m_gotCrossUpdate)
  4324. {
  4325. LastCommands &= ~(ScriptControlled.CONTROL_LBUTTON | ScriptControlled.CONTROL_ML_LBUTTON);
  4326. if((cAgent.CrossExtraFlags & 1) != 0)
  4327. LastCommands |= ScriptControlled.CONTROL_LBUTTON;
  4328. if((cAgent.CrossExtraFlags & 2) != 0)
  4329. LastCommands |= ScriptControlled.CONTROL_ML_LBUTTON;
  4330. MouseDown = (cAgent.CrossExtraFlags & 3) != 0;
  4331. }
  4332. m_haveGroupInformation = false;
  4333. // using this as protocol detection don't want to mess with the numbers for now
  4334. if(cAgent.ActiveGroupTitle != null)
  4335. {
  4336. m_haveGroupInformation = true;
  4337. //COF = cAgent.agentCOF;
  4338. if(ControllingClient.IsGroupMember(cAgent.ActiveGroupID))
  4339. {
  4340. ControllingClient.ActiveGroupId = cAgent.ActiveGroupID;
  4341. ControllingClient.ActiveGroupName = cAgent.ActiveGroupName;
  4342. Grouptitle = cAgent.ActiveGroupTitle;
  4343. ControllingClient.ActiveGroupPowers =
  4344. ControllingClient.GetGroupPowers(cAgent.ActiveGroupID);
  4345. }
  4346. else
  4347. {
  4348. // we got a unknown active group so get what groups thinks about us
  4349. IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  4350. if (gm != null)
  4351. gm.SendAgentGroupDataUpdate(ControllingClient);
  4352. }
  4353. }
  4354. lock (m_originRegionIDAccessLock)
  4355. m_originRegionID = cAgent.RegionID;
  4356. }
  4357. public bool CopyAgent(out IAgentData agent)
  4358. {
  4359. agent = new CompleteAgentData();
  4360. CopyTo((AgentData)agent, false);
  4361. return true;
  4362. }
  4363. #endregion Child Agent Updates
  4364. /// <summary>
  4365. /// Handles part of the PID controller function for moving an avatar.
  4366. /// </summary>
  4367. public void UpdateMovement()
  4368. {
  4369. /*
  4370. if (IsInTransit)
  4371. return;
  4372. lock(m_forceToApplyLock)
  4373. {
  4374. if (m_forceToApplyValid)
  4375. {
  4376. Velocity = m_forceToApply;
  4377. m_forceToApplyValid = false;
  4378. TriggerScenePresenceUpdated();
  4379. }
  4380. }
  4381. */
  4382. }
  4383. /// <summary>
  4384. /// Adds a physical representation of the avatar to the Physics plugin
  4385. /// </summary>
  4386. public void AddToPhysicalScene(bool isFlying)
  4387. {
  4388. // m_log.DebugFormat(
  4389. // "[SCENE PRESENCE]: Adding physics actor for {0}, ifFlying = {1} in {2}",
  4390. // Name, isFlying, Scene.RegionInfo.RegionName);
  4391. if (PhysicsActor != null)
  4392. {
  4393. m_log.ErrorFormat(
  4394. "[SCENE PRESENCE]: Adding physics actor for {0} to {1} but this scene presence already has a physics actor",
  4395. Name, Scene.RegionInfo.RegionName);
  4396. }
  4397. if (Appearance.AvatarHeight == 0)
  4398. // Appearance.SetHeight();
  4399. Appearance.SetSize(new Vector3(0.45f,0.6f,1.9f));
  4400. // lock(m_forceToApplyLock)
  4401. // m_forceToApplyValid = false;
  4402. PhysicsScene scene = m_scene.PhysicsScene;
  4403. Vector3 pVec = AbsolutePosition;
  4404. PhysicsActor pa = scene.AddAvatar(
  4405. LocalId, Firstname + "." + Lastname, pVec,
  4406. Appearance.AvatarBoxSize,Appearance.AvatarFeetOffset, isFlying);
  4407. pa.Orientation = m_bodyRot;
  4408. //PhysicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients;
  4409. pa.OnCollisionUpdate += PhysicsCollisionUpdate;
  4410. pa.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong
  4411. pa.SubscribeEvents(100);
  4412. pa.LocalID = LocalId;
  4413. pa.SetAlwaysRun = m_setAlwaysRun;
  4414. PhysicsActor = pa;
  4415. }
  4416. private void OutOfBoundsCall(Vector3 pos)
  4417. {
  4418. //bool flying = Flying;
  4419. //RemoveFromPhysicalScene();
  4420. //AddToPhysicalScene(flying);
  4421. if (ControllingClient != null)
  4422. ControllingClient.SendAgentAlertMessage("Physics is having a problem with your avatar. You may not be able to move until you relog.", true);
  4423. }
  4424. /// <summary>
  4425. /// Event called by the physics plugin to tell the avatar about a collision.
  4426. /// </summary>
  4427. /// <remarks>
  4428. /// This function is called continuously, even when there are no collisions. If the avatar is walking on the
  4429. /// ground or a prim then there will be collision information between the avatar and the surface.
  4430. ///
  4431. /// FIXME: However, we can't safely avoid calling this yet where there are no collisions without analyzing whether
  4432. /// any part of this method is relying on an every-frame call.
  4433. /// </remarks>
  4434. /// <param name="e"></param>
  4435. public void PhysicsCollisionUpdate(EventArgs e)
  4436. {
  4437. if (IsChildAgent)
  4438. return;
  4439. if(IsInTransit)
  4440. return;
  4441. //if ((Math.Abs(Velocity.X) > 0.1e-9f) || (Math.Abs(Velocity.Y) > 0.1e-9f))
  4442. // The Physics Scene will send updates every 500 ms grep: PhysicsActor.SubscribeEvents(
  4443. // as of this comment the interval is set in AddToPhysicalScene
  4444. // if (m_updateCount > 0)
  4445. // {
  4446. // if (Animator != null && Animator.UpdateMovementAnimations())
  4447. // TriggerScenePresenceUpdated();
  4448. // m_updateCount--;
  4449. // }
  4450. CollisionEventUpdate collisionData = (CollisionEventUpdate)e;
  4451. Dictionary<uint, ContactPoint> coldata = collisionData.m_objCollisionList;
  4452. // // No collisions at all means we may be flying. Update always
  4453. // // to make falling work
  4454. // if (m_lastColCount != coldata.Count || coldata.Count == 0)
  4455. // {
  4456. // m_updateCount = UPDATE_COUNT;
  4457. // m_lastColCount = coldata.Count;
  4458. // }
  4459. if (coldata.Count != 0)
  4460. {
  4461. ContactPoint lowest;
  4462. lowest.SurfaceNormal = Vector3.Zero;
  4463. lowest.Position = Vector3.Zero;
  4464. lowest.Position.Z = float.MaxValue;
  4465. foreach (ContactPoint contact in coldata.Values)
  4466. {
  4467. if (contact.CharacterFeet && contact.Position.Z < lowest.Position.Z)
  4468. lowest = contact;
  4469. }
  4470. if (lowest.Position.Z != float.MaxValue)
  4471. {
  4472. lowest.SurfaceNormal = -lowest.SurfaceNormal;
  4473. CollisionPlane = new Vector4(lowest.SurfaceNormal, Vector3.Dot(lowest.Position, lowest.SurfaceNormal));
  4474. }
  4475. else
  4476. CollisionPlane = Vector4.UnitW;
  4477. }
  4478. else
  4479. CollisionPlane = Vector4.UnitW;
  4480. RaiseCollisionScriptEvents(coldata);
  4481. // Gods do not take damage and Invulnerable is set depending on parcel/region flags
  4482. if (Invulnerable || IsViewerUIGod)
  4483. return;
  4484. // The following may be better in the ICombatModule
  4485. // probably tweaking of the values for ground and normal prim collisions will be needed
  4486. float startHealth = Health;
  4487. if(coldata.Count > 0)
  4488. {
  4489. uint killerObj = 0;
  4490. SceneObjectPart part = null;
  4491. float rvel; // relative velocity, negative on approch
  4492. foreach (uint localid in coldata.Keys)
  4493. {
  4494. if (localid == 0)
  4495. {
  4496. // 0 is the ground
  4497. rvel = coldata[0].RelativeSpeed;
  4498. if(rvel < -5.0f)
  4499. Health -= 0.01f * rvel * rvel;
  4500. }
  4501. else
  4502. {
  4503. part = Scene.GetSceneObjectPart(localid);
  4504. if(part != null && !part.ParentGroup.IsVolumeDetect)
  4505. {
  4506. if (part.ParentGroup.Damage > 0.0f)
  4507. {
  4508. // Something with damage...
  4509. Health -= part.ParentGroup.Damage;
  4510. part.ParentGroup.Scene.DeleteSceneObject(part.ParentGroup, false);
  4511. }
  4512. else
  4513. {
  4514. // An ordinary prim
  4515. rvel = coldata[localid].RelativeSpeed;
  4516. if(rvel < -5.0f)
  4517. {
  4518. Health -= 0.005f * rvel * rvel;
  4519. }
  4520. }
  4521. }
  4522. else
  4523. {
  4524. }
  4525. }
  4526. if (Health <= 0.0f)
  4527. {
  4528. if (localid != 0)
  4529. killerObj = localid;
  4530. }
  4531. }
  4532. if (Health <= 0)
  4533. {
  4534. ControllingClient.SendHealth(Health);
  4535. m_scene.EventManager.TriggerAvatarKill(killerObj, this);
  4536. return;
  4537. }
  4538. }
  4539. if(Math.Abs(Health - startHealth) > 1.0)
  4540. ControllingClient.SendHealth(Health);
  4541. }
  4542. public void setHealthWithUpdate(float health)
  4543. {
  4544. Health = health;
  4545. ControllingClient.SendHealth(Health);
  4546. }
  4547. protected internal void Close()
  4548. {
  4549. // Clear known regions
  4550. KnownRegions = new Dictionary<ulong, string>();
  4551. // I don't get it but mono crashes when you try to dispose of this timer,
  4552. // unsetting the elapsed callback should be enough to allow for cleanup however.
  4553. // m_reprioritizationTimer.Dispose();
  4554. RemoveFromPhysicalScene();
  4555. m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
  4556. RemoveClientEvents();
  4557. // if (Animator != null)
  4558. // Animator.Close();
  4559. Animator = null;
  4560. scriptedcontrols.Clear();
  4561. ControllingClient = null;
  4562. LifecycleState = ScenePresenceState.Removed;
  4563. IsDeleted = true;
  4564. m_updateAgentReceivedAfterTransferEvent.Dispose();
  4565. m_updateAgentReceivedAfterTransferEvent = null;
  4566. }
  4567. public void AddAttachment(SceneObjectGroup gobj)
  4568. {
  4569. lock (m_attachments)
  4570. {
  4571. // This may be true when the attachment comes back
  4572. // from serialization after login. Clear it.
  4573. gobj.IsDeleted = false;
  4574. m_attachments.Add(gobj);
  4575. }
  4576. IBakedTextureModule bakedModule = m_scene.RequestModuleInterface<IBakedTextureModule>();
  4577. if (bakedModule != null)
  4578. bakedModule.UpdateMeshAvatar(m_uuid);
  4579. }
  4580. public int GetAttachmentsCount()
  4581. {
  4582. return m_attachments.Count;
  4583. }
  4584. /// <summary>
  4585. /// Get all the presence's attachments.
  4586. /// </summary>
  4587. /// <returns>A copy of the list which contains the attachments.</returns>
  4588. public List<SceneObjectGroup> GetAttachments()
  4589. {
  4590. lock (m_attachments)
  4591. return new List<SceneObjectGroup>(m_attachments);
  4592. }
  4593. /// <summary>
  4594. /// Get the scene objects attached to the given point.
  4595. /// </summary>
  4596. /// <param name="attachmentPoint"></param>
  4597. /// <returns>Returns an empty list if there were no attachments at the point.</returns>
  4598. public List<SceneObjectGroup> GetAttachments(uint attachmentPoint)
  4599. {
  4600. List<SceneObjectGroup> attachments = new List<SceneObjectGroup>();
  4601. if (attachmentPoint >= 0)
  4602. {
  4603. lock (m_attachments)
  4604. {
  4605. foreach (SceneObjectGroup so in m_attachments)
  4606. {
  4607. if (attachmentPoint == so.AttachmentPoint)
  4608. attachments.Add(so);
  4609. }
  4610. }
  4611. }
  4612. return attachments;
  4613. }
  4614. public bool HasAttachments()
  4615. {
  4616. lock (m_attachments)
  4617. return m_attachments.Count > 0;
  4618. }
  4619. /// <summary>
  4620. /// Returns the total count of scripts in all parts inventories.
  4621. /// </summary>
  4622. public int ScriptCount()
  4623. {
  4624. int count = 0;
  4625. lock (m_attachments)
  4626. {
  4627. foreach (SceneObjectGroup gobj in m_attachments)
  4628. {
  4629. if (gobj != null)
  4630. {
  4631. count += gobj.ScriptCount();
  4632. }
  4633. }
  4634. }
  4635. return count;
  4636. }
  4637. /// <summary>
  4638. /// A float the value is a representative execution time in milliseconds of all scripts in all attachments.
  4639. /// </summary>
  4640. public float ScriptExecutionTime()
  4641. {
  4642. float time = 0.0f;
  4643. lock (m_attachments)
  4644. {
  4645. foreach (SceneObjectGroup gobj in m_attachments)
  4646. {
  4647. if (gobj != null)
  4648. {
  4649. time += gobj.ScriptExecutionTime();
  4650. }
  4651. }
  4652. }
  4653. return time;
  4654. }
  4655. /// <summary>
  4656. /// Returns the total count of running scripts in all parts.
  4657. /// </summary>
  4658. public int RunningScriptCount()
  4659. {
  4660. int count = 0;
  4661. lock (m_attachments)
  4662. {
  4663. foreach (SceneObjectGroup gobj in m_attachments)
  4664. {
  4665. if (gobj != null)
  4666. {
  4667. count += gobj.RunningScriptCount();
  4668. }
  4669. }
  4670. }
  4671. return count;
  4672. }
  4673. public bool HasScriptedAttachments()
  4674. {
  4675. lock (m_attachments)
  4676. {
  4677. foreach (SceneObjectGroup gobj in m_attachments)
  4678. {
  4679. if (gobj != null)
  4680. {
  4681. if (gobj.RootPart.Inventory.ContainsScripts())
  4682. return true;
  4683. }
  4684. }
  4685. }
  4686. return false;
  4687. }
  4688. public void RemoveAttachment(SceneObjectGroup gobj)
  4689. {
  4690. lock (m_attachments)
  4691. m_attachments.Remove(gobj);
  4692. }
  4693. /// <summary>
  4694. /// Clear all attachments
  4695. /// </summary>
  4696. public void ClearAttachments()
  4697. {
  4698. lock (m_attachments)
  4699. m_attachments.Clear();
  4700. }
  4701. /// <summary>
  4702. /// This is currently just being done for information.
  4703. /// </summary>
  4704. public bool ValidateAttachments()
  4705. {
  4706. bool validated = true;
  4707. lock (m_attachments)
  4708. {
  4709. // Validate
  4710. foreach (SceneObjectGroup gobj in m_attachments)
  4711. {
  4712. if (gobj == null)
  4713. {
  4714. m_log.WarnFormat(
  4715. "[SCENE PRESENCE]: Failed to validate an attachment for {0} since it was null. Continuing", Name);
  4716. validated = false;
  4717. }
  4718. else if (gobj.IsDeleted)
  4719. {
  4720. m_log.WarnFormat(
  4721. "[SCENE PRESENCE]: Failed to validate attachment {0} {1} for {2} since it had been deleted. Continuing",
  4722. gobj.Name, gobj.UUID, Name);
  4723. validated = false;
  4724. }
  4725. }
  4726. }
  4727. return validated;
  4728. }
  4729. /*
  4730. public void SendAttachmentsToAllAgents()
  4731. {
  4732. lock (m_attachments)
  4733. {
  4734. foreach (SceneObjectGroup sog in m_attachments)
  4735. {
  4736. m_scene.ForEachScenePresence(delegate(ScenePresence p)
  4737. {
  4738. if (p != this && sog.HasPrivateAttachmentPoint)
  4739. return;
  4740. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  4741. return;
  4742. SendTerseUpdateToAgentNF(p);
  4743. SendAttachmentFullUpdateToAgentNF(sog, p);
  4744. });
  4745. }
  4746. }
  4747. }
  4748. */
  4749. // send attachments to a client without filters except for huds
  4750. // for now they are checked in several places down the line...
  4751. public void SendAttachmentsToAgentNF(ScenePresence p)
  4752. {
  4753. SendTerseUpdateToAgentNF(p);
  4754. // SendAvatarDataToAgentNF(this);
  4755. lock (m_attachments)
  4756. {
  4757. foreach (SceneObjectGroup sog in m_attachments)
  4758. {
  4759. SendAttachmentFullUpdateToAgentNF(sog, p);
  4760. }
  4761. }
  4762. }
  4763. public void SendAttachmentFullUpdateToAgentNF(SceneObjectGroup sog, ScenePresence p)
  4764. {
  4765. if (p != this && sog.HasPrivateAttachmentPoint)
  4766. return;
  4767. SceneObjectPart[] parts = sog.Parts;
  4768. SceneObjectPart rootpart = sog.RootPart;
  4769. PrimUpdateFlags update = PrimUpdateFlags.FullUpdate;
  4770. if (rootpart.Shape.MeshFlagEntry)
  4771. update = PrimUpdateFlags.FullUpdatewithAnim;
  4772. p.ControllingClient.SendEntityUpdate(rootpart, update);
  4773. for (int i = 0; i < parts.Length; i++)
  4774. {
  4775. SceneObjectPart part = parts[i];
  4776. if (part == rootpart)
  4777. continue;
  4778. p.ControllingClient.SendEntityUpdate(part, update);
  4779. }
  4780. }
  4781. public void SendAttachmentScheduleUpdate(SceneObjectGroup sog)
  4782. {
  4783. if (IsChildAgent || IsInTransit)
  4784. return;
  4785. SceneObjectPart[] origparts = sog.Parts;
  4786. SceneObjectPart[] parts = new SceneObjectPart[origparts.Length];
  4787. PrimUpdateFlags[] flags = new PrimUpdateFlags[origparts.Length];
  4788. SceneObjectPart rootpart = sog.RootPart;
  4789. PrimUpdateFlags cur = sog.RootPart.GetAndClearUpdateFlag();
  4790. bool noanim = !rootpart.Shape.MeshFlagEntry;
  4791. int nparts = 0;
  4792. if (noanim || rootpart.Animations == null)
  4793. cur &= ~PrimUpdateFlags.Animations;
  4794. if (cur != PrimUpdateFlags.None)
  4795. {
  4796. flags[nparts] = cur;
  4797. parts[nparts] = rootpart;
  4798. ++nparts;
  4799. }
  4800. for (int i = 0; i < origparts.Length; i++)
  4801. {
  4802. if (origparts[i] == rootpart)
  4803. continue;
  4804. cur = origparts[i].GetAndClearUpdateFlag();
  4805. if (noanim || origparts[i].Animations == null)
  4806. cur &= ~PrimUpdateFlags.Animations;
  4807. if (cur == PrimUpdateFlags.None)
  4808. continue;
  4809. flags[nparts] = cur;
  4810. parts[nparts] = origparts[i];
  4811. ++nparts;
  4812. }
  4813. if (nparts == 0)
  4814. return;
  4815. for (int i = 0; i < nparts; i++)
  4816. ControllingClient.SendEntityUpdate(parts[i], flags[i]);
  4817. if (sog.HasPrivateAttachmentPoint)
  4818. return;
  4819. List<ScenePresence> allPresences = m_scene.GetScenePresences();
  4820. foreach (ScenePresence p in allPresences)
  4821. {
  4822. if (p == this)
  4823. continue;
  4824. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  4825. continue;
  4826. for (int i = 0; i < nparts; i++)
  4827. p.ControllingClient.SendEntityUpdate(parts[i], flags[i]);
  4828. }
  4829. }
  4830. public void SendAttachmentUpdate(SceneObjectGroup sog, PrimUpdateFlags update)
  4831. {
  4832. if (IsChildAgent || IsInTransit)
  4833. return;
  4834. SceneObjectPart[] origparts = sog.Parts;
  4835. SceneObjectPart[] parts = new SceneObjectPart[origparts.Length];
  4836. PrimUpdateFlags[] flags = new PrimUpdateFlags[origparts.Length];
  4837. SceneObjectPart rootpart = sog.RootPart;
  4838. bool noanim = !rootpart.Shape.MeshFlagEntry;
  4839. int nparts = 0;
  4840. PrimUpdateFlags cur = update;
  4841. if (noanim || rootpart.Animations == null)
  4842. cur &= ~PrimUpdateFlags.Animations;
  4843. if (cur != PrimUpdateFlags.None)
  4844. {
  4845. flags[nparts] = cur;
  4846. parts[nparts] = rootpart;
  4847. ++nparts;
  4848. }
  4849. for (int i = 0; i < origparts.Length; i++)
  4850. {
  4851. if (origparts[i] == rootpart)
  4852. continue;
  4853. cur = update;
  4854. if (noanim || origparts[i].Animations == null)
  4855. cur &= ~PrimUpdateFlags.Animations;
  4856. if (cur == PrimUpdateFlags.None)
  4857. continue;
  4858. flags[nparts] = cur;
  4859. parts[nparts] = origparts[i];
  4860. ++nparts;
  4861. }
  4862. if (nparts == 0)
  4863. return;
  4864. for(int i = 0; i < nparts; i++)
  4865. ControllingClient.SendEntityUpdate(parts[i], flags[i]);
  4866. if (sog.HasPrivateAttachmentPoint)
  4867. return;
  4868. List<ScenePresence> allPresences = m_scene.GetScenePresences();
  4869. foreach (ScenePresence p in allPresences)
  4870. {
  4871. if (p == this)
  4872. continue;
  4873. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  4874. continue;
  4875. p.ControllingClient.SendEntityUpdate(rootpart, update);
  4876. for (int i = 0; i < nparts; i++)
  4877. p.ControllingClient.SendEntityUpdate(parts[i], flags[i]);
  4878. }
  4879. }
  4880. public void SendAttachmentUpdate(SceneObjectPart part, PrimUpdateFlags update)
  4881. {
  4882. if (IsChildAgent || IsInTransit)
  4883. return;
  4884. if ((update & PrimUpdateFlags.Animations) != 0 && part.Animations == null)
  4885. {
  4886. update &= ~PrimUpdateFlags.Animations;
  4887. if (update == PrimUpdateFlags.None)
  4888. return;
  4889. }
  4890. ControllingClient.SendEntityUpdate(part, update);
  4891. if (part.ParentGroup.HasPrivateAttachmentPoint)
  4892. return;
  4893. List<ScenePresence> allPresences = m_scene.GetScenePresences();
  4894. foreach (ScenePresence p in allPresences)
  4895. {
  4896. if (p == this)
  4897. continue;
  4898. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  4899. continue;
  4900. p.ControllingClient.SendEntityUpdate(part, update);
  4901. }
  4902. }
  4903. /// <summary>
  4904. /// Send a script event to this scene presence's attachments
  4905. /// </summary>
  4906. /// <param name="eventName">The name of the event</param>
  4907. /// <param name="args">The arguments for the event</param>
  4908. public void SendScriptEventToAttachments(string eventName, Object[] args)
  4909. {
  4910. Util.FireAndForget(delegate(object x)
  4911. {
  4912. if (m_scriptEngines.Length == 0)
  4913. return;
  4914. lock (m_attachments)
  4915. {
  4916. foreach (SceneObjectGroup grp in m_attachments)
  4917. {
  4918. // 16384 is CHANGED_ANIMATION
  4919. //
  4920. // Send this to all attachment root prims
  4921. //
  4922. foreach (IScriptModule m in m_scriptEngines)
  4923. {
  4924. if (m == null) // No script engine loaded
  4925. continue;
  4926. m.PostObjectEvent(grp.RootPart.UUID, "changed", new Object[] { (int)Changed.ANIMATION });
  4927. }
  4928. }
  4929. }
  4930. }, null, "ScenePresence.SendScriptEventToAttachments");
  4931. }
  4932. /// <summary>
  4933. /// Gets the mass.
  4934. /// </summary>
  4935. /// <returns>
  4936. /// The mass.
  4937. /// </returns>
  4938. public float GetMass()
  4939. {
  4940. PhysicsActor pa = PhysicsActor;
  4941. if (pa != null)
  4942. return pa.Mass;
  4943. else
  4944. return 0;
  4945. }
  4946. internal void PushForce(Vector3 impulse)
  4947. {
  4948. if (PhysicsActor != null)
  4949. {
  4950. PhysicsActor.AddForce(impulse,true);
  4951. }
  4952. }
  4953. CameraData physActor_OnPhysicsRequestingCameraData()
  4954. {
  4955. return new CameraData
  4956. {
  4957. Valid = true,
  4958. MouseLook = this.m_mouseLook,
  4959. CameraRotation = this.CameraRotation,
  4960. CameraAtAxis = this.CameraAtAxis
  4961. };
  4962. }
  4963. public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID)
  4964. {
  4965. SceneObjectPart part = m_scene.GetSceneObjectPart(Obj_localID);
  4966. if (part == null)
  4967. return;
  4968. ControllingClient.SendTakeControls(controls, false, false);
  4969. ControllingClient.SendTakeControls(controls, true, false);
  4970. ScriptControllers obj = new ScriptControllers();
  4971. obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
  4972. obj.eventControls = ScriptControlled.CONTROL_ZERO;
  4973. obj.objectID = part.ParentGroup.UUID;
  4974. obj.itemID = Script_item_UUID;
  4975. if (pass_on == 0 && accept == 0)
  4976. {
  4977. IgnoredControls |= (ScriptControlled)controls;
  4978. obj.ignoreControls = (ScriptControlled)controls;
  4979. }
  4980. if (pass_on == 0 && accept == 1)
  4981. {
  4982. IgnoredControls |= (ScriptControlled)controls;
  4983. obj.ignoreControls = (ScriptControlled)controls;
  4984. obj.eventControls = (ScriptControlled)controls;
  4985. }
  4986. if (pass_on == 1 && accept == 1)
  4987. {
  4988. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  4989. obj.eventControls = (ScriptControlled)controls;
  4990. obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
  4991. }
  4992. lock (scriptedcontrols)
  4993. {
  4994. if (pass_on == 1 && accept == 0)
  4995. {
  4996. IgnoredControls &= ~(ScriptControlled)controls;
  4997. if (scriptedcontrols.ContainsKey(Script_item_UUID))
  4998. RemoveScriptFromControlNotifications(Script_item_UUID, part);
  4999. }
  5000. else
  5001. {
  5002. AddScriptToControlNotifications(Script_item_UUID, part, ref obj);
  5003. }
  5004. }
  5005. ControllingClient.SendTakeControls(controls, pass_on == 1 ? true : false, true);
  5006. }
  5007. private void AddScriptToControlNotifications(OpenMetaverse.UUID Script_item_UUID, SceneObjectPart part, ref ScriptControllers obj)
  5008. {
  5009. scriptedcontrols[Script_item_UUID] = obj;
  5010. PhysicsActor physActor = part.ParentGroup.RootPart.PhysActor;
  5011. if (physActor != null)
  5012. {
  5013. physActor.OnPhysicsRequestingCameraData -= physActor_OnPhysicsRequestingCameraData;
  5014. physActor.OnPhysicsRequestingCameraData += physActor_OnPhysicsRequestingCameraData;
  5015. }
  5016. }
  5017. private void RemoveScriptFromControlNotifications(OpenMetaverse.UUID Script_item_UUID, SceneObjectPart part)
  5018. {
  5019. scriptedcontrols.Remove(Script_item_UUID);
  5020. if (part != null)
  5021. {
  5022. PhysicsActor physActor = part.ParentGroup.RootPart.PhysActor;
  5023. if (physActor != null)
  5024. {
  5025. physActor.OnPhysicsRequestingCameraData -= physActor_OnPhysicsRequestingCameraData;
  5026. }
  5027. }
  5028. }
  5029. public void HandleForceReleaseControls(IClientAPI remoteClient, UUID agentID)
  5030. {
  5031. foreach (ScriptControllers c in scriptedcontrols.Values)
  5032. {
  5033. SceneObjectGroup sog = m_scene.GetSceneObjectGroup(c.objectID);
  5034. if(sog != null && !sog.IsDeleted && sog.RootPart.PhysActor != null)
  5035. sog.RootPart.PhysActor.OnPhysicsRequestingCameraData -= physActor_OnPhysicsRequestingCameraData;
  5036. }
  5037. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  5038. lock (scriptedcontrols)
  5039. {
  5040. scriptedcontrols.Clear();
  5041. }
  5042. ControllingClient.SendTakeControls(int.MaxValue, false, false);
  5043. }
  5044. public void HandleRevokePermissions(UUID objectID, uint permissions )
  5045. {
  5046. // still skeleton code
  5047. if((permissions & (16 | 0x8000 )) == 0) //PERMISSION_TRIGGER_ANIMATION | PERMISSION_OVERRIDE_ANIMATIONS
  5048. return;
  5049. if(objectID == m_scene.RegionInfo.RegionID) // for all objects
  5050. {
  5051. List<SceneObjectGroup> sogs = m_scene.GetSceneObjectGroups();
  5052. for(int i = 0; i < sogs.Count; ++i)
  5053. sogs[i].RemoveScriptsPermissions(this, (int)permissions);
  5054. }
  5055. else
  5056. {
  5057. SceneObjectPart part = m_scene.GetSceneObjectPart(objectID);
  5058. if(part != null)
  5059. {
  5060. part.Inventory.RemoveScriptsPermissions(this, (int)permissions);
  5061. }
  5062. }
  5063. }
  5064. public void ClearControls()
  5065. {
  5066. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  5067. lock (scriptedcontrols)
  5068. {
  5069. scriptedcontrols.Clear();
  5070. }
  5071. }
  5072. public void UnRegisterSeatControls(UUID obj)
  5073. {
  5074. List<UUID> takers = new List<UUID>();
  5075. foreach (ScriptControllers c in scriptedcontrols.Values)
  5076. {
  5077. if (c.objectID == obj)
  5078. takers.Add(c.itemID);
  5079. }
  5080. foreach (UUID t in takers)
  5081. {
  5082. UnRegisterControlEventsToScript(0, t);
  5083. }
  5084. }
  5085. public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID)
  5086. {
  5087. ScriptControllers takecontrols;
  5088. SceneObjectPart part = m_scene.GetSceneObjectPart(Obj_localID);
  5089. lock (scriptedcontrols)
  5090. {
  5091. if (scriptedcontrols.TryGetValue(Script_item_UUID, out takecontrols))
  5092. {
  5093. ScriptControlled sctc = takecontrols.eventControls;
  5094. ControllingClient.SendTakeControls((int)sctc, false, false);
  5095. ControllingClient.SendTakeControls((int)sctc, true, false);
  5096. RemoveScriptFromControlNotifications(Script_item_UUID, part);
  5097. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  5098. foreach (ScriptControllers scData in scriptedcontrols.Values)
  5099. {
  5100. IgnoredControls |= scData.ignoreControls;
  5101. }
  5102. }
  5103. }
  5104. }
  5105. private void SendControlsToScripts(uint flags)
  5106. {
  5107. // Notify the scripts only after calling UpdateMovementAnimations(), so that if a script
  5108. // (e.g., a walking script) checks which animation is active it will be the correct animation.
  5109. lock (scriptedcontrols)
  5110. {
  5111. if (scriptedcontrols.Count <= 0)
  5112. return;
  5113. ScriptControlled allflags;
  5114. // convert mouse from edge to level
  5115. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP) != 0 ||
  5116. (flags & unchecked((uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_UP)) != 0)
  5117. {
  5118. allflags = ScriptControlled.CONTROL_ZERO;
  5119. }
  5120. else // recover last state of mouse
  5121. allflags = LastCommands & (ScriptControlled.CONTROL_ML_LBUTTON | ScriptControlled.CONTROL_LBUTTON);
  5122. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN) != 0)
  5123. allflags |= ScriptControlled.CONTROL_ML_LBUTTON;
  5124. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0)
  5125. allflags |= ScriptControlled.CONTROL_LBUTTON;
  5126. // find all activated controls, whether the scripts are interested in them or not
  5127. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS) != 0)
  5128. {
  5129. allflags |= ScriptControlled.CONTROL_FWD;
  5130. }
  5131. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG) != 0)
  5132. {
  5133. allflags |= ScriptControlled.CONTROL_BACK;
  5134. }
  5135. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS) != 0)
  5136. {
  5137. allflags |= ScriptControlled.CONTROL_UP;
  5138. }
  5139. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0)
  5140. {
  5141. allflags |= ScriptControlled.CONTROL_DOWN;
  5142. }
  5143. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS) != 0)
  5144. {
  5145. allflags |= ScriptControlled.CONTROL_LEFT;
  5146. }
  5147. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG) != 0)
  5148. {
  5149. allflags |= ScriptControlled.CONTROL_RIGHT;
  5150. }
  5151. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  5152. {
  5153. allflags |= ScriptControlled.CONTROL_ROT_RIGHT;
  5154. }
  5155. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0)
  5156. {
  5157. allflags |= ScriptControlled.CONTROL_ROT_LEFT;
  5158. }
  5159. // optimization; we have to check per script, but if nothing is pressed and nothing changed, we can skip that
  5160. if (allflags != ScriptControlled.CONTROL_ZERO || allflags != LastCommands)
  5161. {
  5162. foreach (KeyValuePair<UUID, ScriptControllers> kvp in scriptedcontrols)
  5163. {
  5164. UUID scriptUUID = kvp.Key;
  5165. ScriptControllers scriptControlData = kvp.Value;
  5166. ScriptControlled localHeld = allflags & scriptControlData.eventControls; // the flags interesting for us
  5167. ScriptControlled localLast = LastCommands & scriptControlData.eventControls; // the activated controls in the last cycle
  5168. ScriptControlled localChange = localHeld ^ localLast; // the changed bits
  5169. if (localHeld != ScriptControlled.CONTROL_ZERO || localChange != ScriptControlled.CONTROL_ZERO)
  5170. {
  5171. // only send if still pressed or just changed
  5172. m_scene.EventManager.TriggerControlEvent(scriptUUID, UUID, (uint)localHeld, (uint)localChange);
  5173. }
  5174. }
  5175. }
  5176. LastCommands = allflags;
  5177. MouseDown = (allflags & (ScriptControlled.CONTROL_ML_LBUTTON | ScriptControlled.CONTROL_LBUTTON)) != 0;
  5178. }
  5179. }
  5180. internal static AgentManager.ControlFlags RemoveIgnoredControls(AgentManager.ControlFlags flags, ScriptControlled ignored)
  5181. {
  5182. if (ignored == ScriptControlled.CONTROL_ZERO)
  5183. return flags;
  5184. if ((ignored & ScriptControlled.CONTROL_BACK) != 0)
  5185. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG);
  5186. if ((ignored & ScriptControlled.CONTROL_FWD) != 0)
  5187. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS | AgentManager.ControlFlags.AGENT_CONTROL_AT_POS);
  5188. if ((ignored & ScriptControlled.CONTROL_DOWN) != 0)
  5189. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG);
  5190. if ((ignored & ScriptControlled.CONTROL_UP) != 0)
  5191. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS | AgentManager.ControlFlags.AGENT_CONTROL_UP_POS);
  5192. if ((ignored & ScriptControlled.CONTROL_LEFT) != 0)
  5193. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS);
  5194. if ((ignored & ScriptControlled.CONTROL_RIGHT) != 0)
  5195. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG | AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG);
  5196. if ((ignored & ScriptControlled.CONTROL_ROT_LEFT) != 0)
  5197. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG);
  5198. if ((ignored & ScriptControlled.CONTROL_ROT_RIGHT) != 0)
  5199. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS);
  5200. if ((ignored & ScriptControlled.CONTROL_ML_LBUTTON) != 0)
  5201. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN);
  5202. if ((ignored & ScriptControlled.CONTROL_LBUTTON) != 0)
  5203. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP | AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN);
  5204. //DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS,
  5205. //DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG,
  5206. //DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS,
  5207. //DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG,
  5208. //DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS,
  5209. //DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG,
  5210. //DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG
  5211. return flags;
  5212. }
  5213. // returns true it local teleport allowed and sets the destiny position into pos
  5214. public bool CheckLocalTPLandingPoint(ref Vector3 pos)
  5215. {
  5216. // Never constrain lures
  5217. if ((TeleportFlags & TeleportFlags.ViaLure) != 0)
  5218. return true;
  5219. if (m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
  5220. return true;
  5221. // do not constrain gods and estate managers
  5222. if(m_scene.Permissions.IsGod(m_uuid) ||
  5223. m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid))
  5224. return true;
  5225. // will teleport to a telehub spawn point or landpoint if that results in getting closer to target
  5226. // if not the local teleport fails.
  5227. float currDistanceSQ = Vector3.DistanceSquared(AbsolutePosition, pos);
  5228. // first check telehub
  5229. UUID TelehubObjectID = m_scene.RegionInfo.RegionSettings.TelehubObject;
  5230. if ( TelehubObjectID != UUID.Zero)
  5231. {
  5232. SceneObjectGroup telehubSOG = m_scene.GetSceneObjectGroup(TelehubObjectID);
  5233. if(telehubSOG != null)
  5234. {
  5235. Vector3 spawnPos;
  5236. float spawnDistSQ;
  5237. SpawnPoint[] spawnPoints = m_scene.RegionInfo.RegionSettings.SpawnPoints().ToArray();
  5238. if(spawnPoints.Length == 0)
  5239. {
  5240. spawnPos = new Vector3(128.0f, 128.0f, pos.Z);
  5241. spawnDistSQ = Vector3.DistanceSquared(spawnPos, pos);
  5242. }
  5243. else
  5244. {
  5245. Vector3 hubPos = telehubSOG.AbsolutePosition;
  5246. Quaternion hubRot = telehubSOG.GroupRotation;
  5247. spawnPos = spawnPoints[0].GetLocation(hubPos, hubRot);
  5248. spawnDistSQ = Vector3.DistanceSquared(spawnPos, pos);
  5249. float testDistSQ;
  5250. Vector3 testSpawnPos;
  5251. for(int i = 1; i< spawnPoints.Length; i++)
  5252. {
  5253. testSpawnPos = spawnPoints[i].GetLocation(hubPos, hubRot);
  5254. testDistSQ = Vector3.DistanceSquared(testSpawnPos, pos);
  5255. if(testDistSQ < spawnDistSQ)
  5256. {
  5257. spawnPos = testSpawnPos;
  5258. spawnDistSQ = testDistSQ;
  5259. }
  5260. }
  5261. }
  5262. if (currDistanceSQ < spawnDistSQ)
  5263. {
  5264. // we are already close
  5265. ControllingClient.SendAlertMessage("Can't teleport closer to destination");
  5266. return false;
  5267. }
  5268. else
  5269. {
  5270. pos = spawnPos;
  5271. return true;
  5272. }
  5273. }
  5274. }
  5275. ILandObject land = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
  5276. if (land.LandData.LandingType != (byte)LandingType.LandingPoint
  5277. || land.LandData.OwnerID == m_uuid)
  5278. return true;
  5279. Vector3 landLocation = land.LandData.UserLocation;
  5280. if(landLocation == Vector3.Zero)
  5281. return true;
  5282. if (currDistanceSQ < Vector3.DistanceSquared(landLocation, pos))
  5283. {
  5284. ControllingClient.SendAlertMessage("Can't teleport closer to destination");
  5285. return false;
  5286. }
  5287. pos = land.LandData.UserLocation;
  5288. return true;
  5289. }
  5290. const TeleportFlags TeleHubTPFlags = TeleportFlags.ViaLogin
  5291. | TeleportFlags.ViaHGLogin | TeleportFlags.ViaLocation;
  5292. private bool CheckAndAdjustTelehub(SceneObjectGroup telehub, ref Vector3 pos, ref bool positionChanged)
  5293. {
  5294. // forcing telehubs on any tp that reachs this
  5295. if ((m_teleportFlags & TeleHubTPFlags) != 0 ||
  5296. (m_scene.TelehubAllowLandmarks == true ? false : ((m_teleportFlags & TeleportFlags.ViaLandmark) != 0 )))
  5297. {
  5298. ILandObject land;
  5299. Vector3 teleHubPosition = telehub.AbsolutePosition;
  5300. SpawnPoint[] spawnPoints = m_scene.RegionInfo.RegionSettings.SpawnPoints().ToArray();
  5301. if(spawnPoints.Length == 0)
  5302. {
  5303. land = m_scene.LandChannel.GetLandObject(teleHubPosition.X,teleHubPosition.Y);
  5304. if(land != null)
  5305. {
  5306. pos = teleHubPosition;
  5307. if(land.IsEitherBannedOrRestricted(UUID))
  5308. return false;
  5309. positionChanged = true;
  5310. return true;
  5311. }
  5312. else
  5313. return false;
  5314. }
  5315. int index;
  5316. int tries;
  5317. bool selected = false;
  5318. bool validhub = false;
  5319. Vector3 spawnPosition;
  5320. Quaternion teleHubRotation = telehub.GroupRotation;
  5321. switch(m_scene.SpawnPointRouting)
  5322. {
  5323. case "random":
  5324. tries = spawnPoints.Length;
  5325. if(tries < 3) // no much sense in random with a few points when there same can have bans
  5326. goto case "sequence";
  5327. do
  5328. {
  5329. index = Util.RandomClass.Next(spawnPoints.Length - 1);
  5330. spawnPosition = spawnPoints[index].GetLocation(teleHubPosition, teleHubRotation);
  5331. land = m_scene.LandChannel.GetLandObject(spawnPosition.X,spawnPosition.Y);
  5332. if(land != null && !land.IsEitherBannedOrRestricted(UUID))
  5333. selected = true;
  5334. } while(selected == false && --tries > 0 );
  5335. if(tries <= 0)
  5336. goto case "sequence";
  5337. pos = spawnPosition;
  5338. return true;
  5339. case "sequence":
  5340. tries = spawnPoints.Length;
  5341. selected = false;
  5342. validhub = false;
  5343. do
  5344. {
  5345. index = m_scene.SpawnPoint();
  5346. spawnPosition = spawnPoints[index].GetLocation(teleHubPosition, teleHubRotation);
  5347. land = m_scene.LandChannel.GetLandObject(spawnPosition.X,spawnPosition.Y);
  5348. if(land != null)
  5349. {
  5350. validhub = true;
  5351. if(land.IsEitherBannedOrRestricted(UUID))
  5352. selected = false;
  5353. else
  5354. selected = true;
  5355. }
  5356. } while(selected == false && --tries > 0);
  5357. if(!validhub)
  5358. return false;
  5359. pos = spawnPosition;
  5360. if(!selected)
  5361. return false;
  5362. positionChanged = true;
  5363. return true;
  5364. default:
  5365. case "closest":
  5366. float distancesq = float.MaxValue;
  5367. int closest = -1;
  5368. validhub = false;
  5369. for(int i = 0; i < spawnPoints.Length; i++)
  5370. {
  5371. spawnPosition = spawnPoints[i].GetLocation(teleHubPosition, teleHubRotation);
  5372. Vector3 offset = spawnPosition - pos;
  5373. float dsq = offset.LengthSquared();
  5374. land = m_scene.LandChannel.GetLandObject(spawnPosition.X,spawnPosition.Y);
  5375. if(land == null)
  5376. continue;
  5377. validhub = true;
  5378. if(land.IsEitherBannedOrRestricted(UUID))
  5379. continue;
  5380. if(dsq >= distancesq)
  5381. continue;
  5382. distancesq = dsq;
  5383. closest = i;
  5384. }
  5385. if(!validhub)
  5386. return false;
  5387. if(closest < 0)
  5388. {
  5389. pos = spawnPoints[0].GetLocation(teleHubPosition, teleHubRotation);
  5390. positionChanged = true;
  5391. return false;
  5392. }
  5393. pos = spawnPoints[closest].GetLocation(teleHubPosition, teleHubRotation);
  5394. positionChanged = true;
  5395. return true;
  5396. }
  5397. }
  5398. return false;
  5399. }
  5400. const TeleportFlags adicionalLandPointFlags = TeleportFlags.ViaLandmark |
  5401. TeleportFlags.ViaLocation | TeleportFlags.ViaHGLogin;
  5402. // Modify landing point based on possible banning, telehubs or parcel restrictions.
  5403. // This is the behavior in OpenSim for a very long time, different from SL
  5404. private bool CheckAndAdjustLandingPoint_OS(ref Vector3 pos, ref Vector3 lookat, ref bool positionChanged)
  5405. {
  5406. string reason;
  5407. // Honor bans
  5408. if (!m_scene.TestLandRestrictions(UUID, out reason, ref pos.X, ref pos.Y))
  5409. return false;
  5410. SceneObjectGroup telehub = null;
  5411. if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null)
  5412. {
  5413. if (!m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
  5414. {
  5415. CheckAndAdjustTelehub(telehub, ref pos, ref positionChanged);
  5416. return true;
  5417. }
  5418. }
  5419. ILandObject land = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
  5420. if (land != null)
  5421. {
  5422. if (Scene.DebugTeleporting)
  5423. TeleportFlagsDebug();
  5424. // If we come in via login, landmark or map, we want to
  5425. // honor landing points. If we come in via Lure, we want
  5426. // to ignore them.
  5427. if ((m_teleportFlags & (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)) ==
  5428. (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID) ||
  5429. (m_teleportFlags & adicionalLandPointFlags) != 0)
  5430. {
  5431. // Don't restrict gods, estate managers, or land owners to
  5432. // the TP point. This behaviour mimics agni.
  5433. if (land.LandData.LandingType == (byte)LandingType.LandingPoint &&
  5434. land.LandData.UserLocation != Vector3.Zero &&
  5435. !IsViewerUIGod &&
  5436. ((land.LandData.OwnerID != m_uuid &&
  5437. !m_scene.Permissions.IsGod(m_uuid) &&
  5438. !m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid)) ||
  5439. (m_teleportFlags & TeleportFlags.ViaLocation) != 0 ||
  5440. (m_teleportFlags & Constants.TeleportFlags.ViaHGLogin) != 0))
  5441. {
  5442. pos = land.LandData.UserLocation;
  5443. positionChanged = true;
  5444. }
  5445. }
  5446. land.SendLandUpdateToClient(ControllingClient);
  5447. }
  5448. return true;
  5449. }
  5450. // Modify landing point based on telehubs or parcel restrictions.
  5451. // This is a behavior coming from AVN, somewhat mimicking SL
  5452. private bool CheckAndAdjustLandingPoint_SL(ref Vector3 pos, ref Vector3 lookat, ref bool positionChanged)
  5453. {
  5454. string reason;
  5455. // dont mess with gods
  5456. if(IsGod)
  5457. return true;
  5458. // respect region owner and managers
  5459. // if(m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid))
  5460. // return true;
  5461. if (!m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
  5462. {
  5463. SceneObjectGroup telehub = null;
  5464. if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null)
  5465. {
  5466. if(CheckAndAdjustTelehub(telehub, ref pos, ref positionChanged))
  5467. return true;
  5468. }
  5469. }
  5470. // Honor bans, actually we don't honour them
  5471. if (!m_scene.TestLandRestrictions(UUID, out reason, ref pos.X, ref pos.Y))
  5472. return false;
  5473. ILandObject land = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
  5474. if (land != null)
  5475. {
  5476. if (Scene.DebugTeleporting)
  5477. TeleportFlagsDebug();
  5478. // If we come in via login, landmark or map, we want to
  5479. // honor landing points. If we come in via Lure, we want
  5480. // to ignore them.
  5481. if ((m_teleportFlags & (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)) ==
  5482. (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)
  5483. || (m_teleportFlags & adicionalLandPointFlags) != 0)
  5484. {
  5485. if (land.LandData.LandingType == (byte)LandingType.LandingPoint &&
  5486. land.LandData.UserLocation != Vector3.Zero )
  5487. // &&
  5488. // land.LandData.OwnerID != m_uuid )
  5489. {
  5490. pos = land.LandData.UserLocation;
  5491. if(land.LandData.UserLookAt != Vector3.Zero)
  5492. lookat = land.LandData.UserLookAt;
  5493. positionChanged = true;
  5494. }
  5495. }
  5496. }
  5497. return true;
  5498. }
  5499. private DetectedObject CreateDetObject(SceneObjectPart obj)
  5500. {
  5501. DetectedObject detobj = new DetectedObject();
  5502. detobj.keyUUID = obj.UUID;
  5503. detobj.nameStr = obj.Name;
  5504. detobj.ownerUUID = obj.OwnerID;
  5505. detobj.posVector = obj.AbsolutePosition;
  5506. detobj.rotQuat = obj.GetWorldRotation();
  5507. detobj.velVector = obj.Velocity;
  5508. detobj.colliderType = 0;
  5509. detobj.groupUUID = obj.GroupID;
  5510. detobj.linkNumber = 0;
  5511. return detobj;
  5512. }
  5513. private DetectedObject CreateDetObject(ScenePresence av)
  5514. {
  5515. DetectedObject detobj = new DetectedObject();
  5516. detobj.keyUUID = av.UUID;
  5517. detobj.nameStr = av.ControllingClient.Name;
  5518. detobj.ownerUUID = av.UUID;
  5519. detobj.posVector = av.AbsolutePosition;
  5520. detobj.rotQuat = av.Rotation;
  5521. detobj.velVector = av.Velocity;
  5522. detobj.colliderType = av.IsNPC ? 0x20 : 0x1; // OpenSim\Region\ScriptEngine\Shared\Helpers.cs
  5523. if(av.IsSatOnObject)
  5524. detobj.colliderType |= 0x4; //passive
  5525. else if(detobj.velVector != Vector3.Zero)
  5526. detobj.colliderType |= 0x2; //active
  5527. detobj.groupUUID = av.ControllingClient.ActiveGroupId;
  5528. detobj.linkNumber = 0;
  5529. return detobj;
  5530. }
  5531. private DetectedObject CreateDetObjectForGround()
  5532. {
  5533. DetectedObject detobj = new DetectedObject();
  5534. detobj.keyUUID = UUID.Zero;
  5535. detobj.nameStr = "";
  5536. detobj.ownerUUID = UUID.Zero;
  5537. detobj.posVector = AbsolutePosition;
  5538. detobj.rotQuat = Quaternion.Identity;
  5539. detobj.velVector = Vector3.Zero;
  5540. detobj.colliderType = 0;
  5541. detobj.groupUUID = UUID.Zero;
  5542. detobj.linkNumber = 0;
  5543. return detobj;
  5544. }
  5545. private ColliderArgs CreateColliderArgs(SceneObjectPart dest, List<uint> colliders)
  5546. {
  5547. ColliderArgs colliderArgs = new ColliderArgs();
  5548. List<DetectedObject> colliding = new List<DetectedObject>();
  5549. foreach (uint localId in colliders)
  5550. {
  5551. if (localId == 0)
  5552. continue;
  5553. SceneObjectPart obj = m_scene.GetSceneObjectPart(localId);
  5554. if (obj != null)
  5555. {
  5556. if (!dest.CollisionFilteredOut(obj.UUID, obj.Name))
  5557. colliding.Add(CreateDetObject(obj));
  5558. }
  5559. else
  5560. {
  5561. ScenePresence av = m_scene.GetScenePresence(localId);
  5562. if (av != null && (!av.IsChildAgent))
  5563. {
  5564. if (!dest.CollisionFilteredOut(av.UUID, av.Name))
  5565. colliding.Add(CreateDetObject(av));
  5566. }
  5567. }
  5568. }
  5569. colliderArgs.Colliders = colliding;
  5570. return colliderArgs;
  5571. }
  5572. private delegate void ScriptCollidingNotification(uint localID, ColliderArgs message);
  5573. private void SendCollisionEvent(SceneObjectGroup dest, scriptEvents ev, List<uint> colliders, ScriptCollidingNotification notify)
  5574. {
  5575. ColliderArgs CollidingMessage;
  5576. if (colliders.Count > 0)
  5577. {
  5578. if ((dest.RootPart.ScriptEvents & ev) != 0)
  5579. {
  5580. CollidingMessage = CreateColliderArgs(dest.RootPart, colliders);
  5581. if (CollidingMessage.Colliders.Count > 0)
  5582. notify(dest.RootPart.LocalId, CollidingMessage);
  5583. }
  5584. }
  5585. }
  5586. private void SendLandCollisionEvent(SceneObjectGroup dest, scriptEvents ev, ScriptCollidingNotification notify)
  5587. {
  5588. if ((dest.RootPart.ScriptEvents & ev) != 0)
  5589. {
  5590. ColliderArgs LandCollidingMessage = new ColliderArgs();
  5591. List<DetectedObject> colliding = new List<DetectedObject>();
  5592. colliding.Add(CreateDetObjectForGround());
  5593. LandCollidingMessage.Colliders = colliding;
  5594. notify(dest.RootPart.LocalId, LandCollidingMessage);
  5595. }
  5596. }
  5597. private void RaiseCollisionScriptEvents(Dictionary<uint, ContactPoint> coldata)
  5598. {
  5599. try
  5600. {
  5601. List<uint> thisHitColliders = new List<uint>();
  5602. List<uint> endedColliders = new List<uint>();
  5603. List<uint> startedColliders = new List<uint>();
  5604. if (coldata.Count == 0)
  5605. {
  5606. if (m_lastColliders.Count == 0)
  5607. return; // nothing to do
  5608. for(int i = 0; i < m_lastColliders.Count; ++i)
  5609. endedColliders.Add(m_lastColliders[i]);
  5610. m_lastColliders.Clear();
  5611. }
  5612. else
  5613. {
  5614. List<CollisionForSoundInfo> soundinfolist = new List<CollisionForSoundInfo>();
  5615. if(ParcelAllowThisAvatarSounds)
  5616. {
  5617. CollisionForSoundInfo soundinfo;
  5618. ContactPoint curcontact;
  5619. foreach (uint id in coldata.Keys)
  5620. {
  5621. thisHitColliders.Add(id);
  5622. if (!m_lastColliders.Contains(id))
  5623. {
  5624. startedColliders.Add(id);
  5625. curcontact = coldata[id];
  5626. if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
  5627. {
  5628. soundinfo = new CollisionForSoundInfo();
  5629. soundinfo.colliderID = id;
  5630. soundinfo.position = curcontact.Position;
  5631. soundinfo.relativeVel = curcontact.RelativeSpeed;
  5632. soundinfolist.Add(soundinfo);
  5633. }
  5634. }
  5635. }
  5636. }
  5637. else
  5638. {
  5639. foreach (uint id in coldata.Keys)
  5640. {
  5641. thisHitColliders.Add(id);
  5642. if (!m_lastColliders.Contains(id))
  5643. startedColliders.Add(id);
  5644. }
  5645. }
  5646. // calculate things that ended colliding
  5647. foreach (uint localID in m_lastColliders)
  5648. {
  5649. if (!thisHitColliders.Contains(localID))
  5650. {
  5651. endedColliders.Add(localID);
  5652. }
  5653. }
  5654. //add the items that started colliding this time to the last colliders list.
  5655. foreach (uint localID in startedColliders)
  5656. {
  5657. m_lastColliders.Add(localID);
  5658. }
  5659. // remove things that ended colliding from the last colliders list
  5660. foreach (uint localID in endedColliders)
  5661. {
  5662. m_lastColliders.Remove(localID);
  5663. }
  5664. if (soundinfolist.Count > 0)
  5665. CollisionSounds.AvatarCollisionSound(this, soundinfolist);
  5666. }
  5667. List<SceneObjectGroup> attachements = GetAttachments();
  5668. for (int i = 0; i< attachements.Count; ++i)
  5669. {
  5670. SceneObjectGroup att = attachements[i];
  5671. SendCollisionEvent(att, scriptEvents.collision_start, startedColliders, m_scene.EventManager.TriggerScriptCollidingStart);
  5672. SendCollisionEvent(att, scriptEvents.collision , m_lastColliders , m_scene.EventManager.TriggerScriptColliding);
  5673. SendCollisionEvent(att, scriptEvents.collision_end , endedColliders , m_scene.EventManager.TriggerScriptCollidingEnd);
  5674. if (startedColliders.Contains(0))
  5675. SendLandCollisionEvent(att, scriptEvents.land_collision_start, m_scene.EventManager.TriggerScriptLandCollidingStart);
  5676. if (m_lastColliders.Contains(0))
  5677. SendLandCollisionEvent(att, scriptEvents.land_collision, m_scene.EventManager.TriggerScriptLandColliding);
  5678. if (endedColliders.Contains(0))
  5679. SendLandCollisionEvent(att, scriptEvents.land_collision_end, m_scene.EventManager.TriggerScriptLandCollidingEnd);
  5680. }
  5681. }
  5682. catch { }
  5683. // finally
  5684. // {
  5685. // m_collisionEventFlag = false;
  5686. // }
  5687. }
  5688. private void TeleportFlagsDebug() {
  5689. // Some temporary debugging help to show all the TeleportFlags we have...
  5690. bool HG = false;
  5691. if((m_teleportFlags & TeleportFlags.ViaHGLogin) == TeleportFlags.ViaHGLogin)
  5692. HG = true;
  5693. m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
  5694. uint i = 0u;
  5695. for (int x = 0; x <= 30 ; x++, i = 1u << x)
  5696. {
  5697. i = 1u << x;
  5698. if((m_teleportFlags & (TeleportFlags)i) == (TeleportFlags)i)
  5699. if (HG == false)
  5700. m_log.InfoFormat("[SCENE PRESENCE]: Teleport Flags include {0}", ((TeleportFlags) i).ToString());
  5701. else
  5702. m_log.InfoFormat("[SCENE PRESENCE]: HG Teleport Flags include {0}", ((TeleportFlags)i).ToString());
  5703. }
  5704. m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
  5705. }
  5706. private void parcelGodCheck(UUID currentParcelID)
  5707. {
  5708. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  5709. foreach (ScenePresence p in allpresences)
  5710. {
  5711. if (p.IsDeleted || p.IsChildAgent || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5712. continue;
  5713. if (p.ParcelHideThisAvatar && p.currentParcelUUID != currentParcelID)
  5714. {
  5715. if (IsViewerUIGod)
  5716. p.SendViewTo(this);
  5717. else
  5718. p.SendKillTo(this);
  5719. }
  5720. }
  5721. }
  5722. private void ParcelCrossCheck(UUID currentParcelID,UUID previusParcelID,
  5723. bool currentParcelHide, bool previusParcelHide, bool oldhide, bool check)
  5724. {
  5725. List<ScenePresence> killsToSendto = new List<ScenePresence>();
  5726. List<ScenePresence> killsToSendme = new List<ScenePresence>();
  5727. List<ScenePresence> viewsToSendto = new List<ScenePresence>();
  5728. List<ScenePresence> viewsToSendme = new List<ScenePresence>();
  5729. List<ScenePresence> allpresences = null;
  5730. if (IsInTransit || IsChildAgent)
  5731. return;
  5732. if (check)
  5733. {
  5734. // check is relative to current parcel only
  5735. if (oldhide == currentParcelHide)
  5736. return;
  5737. allpresences = m_scene.GetScenePresences();
  5738. if (oldhide)
  5739. { // where private
  5740. foreach (ScenePresence p in allpresences)
  5741. {
  5742. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5743. continue;
  5744. // those on not on parcel see me
  5745. if (currentParcelID != p.currentParcelUUID)
  5746. {
  5747. viewsToSendto.Add(p); // they see me
  5748. }
  5749. }
  5750. } // where private end
  5751. else
  5752. { // where public
  5753. foreach (ScenePresence p in allpresences)
  5754. {
  5755. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5756. continue;
  5757. // those not on parcel dont see me
  5758. if (currentParcelID != p.currentParcelUUID && !p.IsViewerUIGod)
  5759. {
  5760. killsToSendto.Add(p); // they dont see me
  5761. }
  5762. }
  5763. } // where public end
  5764. allpresences.Clear();
  5765. }
  5766. else
  5767. {
  5768. if (currentParcelHide)
  5769. {
  5770. // now on a private parcel
  5771. allpresences = m_scene.GetScenePresences();
  5772. if (previusParcelHide && previusParcelID != UUID.Zero)
  5773. {
  5774. foreach (ScenePresence p in allpresences)
  5775. {
  5776. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5777. continue;
  5778. // only those on previous parcel need receive kills
  5779. if (previusParcelID == p.currentParcelUUID)
  5780. {
  5781. if(!p.IsViewerUIGod)
  5782. killsToSendto.Add(p); // they dont see me
  5783. if(!IsViewerUIGod)
  5784. killsToSendme.Add(p); // i dont see them
  5785. }
  5786. // only those on new parcel need see
  5787. if (currentParcelID == p.currentParcelUUID)
  5788. {
  5789. viewsToSendto.Add(p); // they see me
  5790. viewsToSendme.Add(p); // i see them
  5791. }
  5792. }
  5793. }
  5794. else
  5795. {
  5796. //was on a public area
  5797. allpresences = m_scene.GetScenePresences();
  5798. foreach (ScenePresence p in allpresences)
  5799. {
  5800. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5801. continue;
  5802. // those not on new parcel dont see me
  5803. if (currentParcelID != p.currentParcelUUID && !p.IsViewerUIGod)
  5804. {
  5805. killsToSendto.Add(p); // they dont see me
  5806. }
  5807. else
  5808. {
  5809. viewsToSendme.Add(p); // i see those on it
  5810. }
  5811. }
  5812. }
  5813. allpresences.Clear();
  5814. } // now on a private parcel end
  5815. else
  5816. {
  5817. // now on public parcel
  5818. if (previusParcelHide && previusParcelID != UUID.Zero)
  5819. {
  5820. // was on private area
  5821. allpresences = m_scene.GetScenePresences();
  5822. foreach (ScenePresence p in allpresences)
  5823. {
  5824. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5825. continue;
  5826. // only those old parcel need kills
  5827. if (previusParcelID == p.currentParcelUUID && !IsViewerUIGod)
  5828. {
  5829. killsToSendme.Add(p); // i dont see them
  5830. }
  5831. else
  5832. {
  5833. viewsToSendto.Add(p); // they see me
  5834. }
  5835. }
  5836. }
  5837. else
  5838. return; // was on a public area also
  5839. } // now on public parcel end
  5840. }
  5841. // send the things
  5842. if (killsToSendto.Count > 0)
  5843. {
  5844. foreach (ScenePresence p in killsToSendto)
  5845. {
  5846. // m_log.Debug("[AVATAR]: killTo: " + Lastname + " " + p.Lastname);
  5847. SendKillTo(p);
  5848. }
  5849. }
  5850. if (killsToSendme.Count > 0)
  5851. {
  5852. foreach (ScenePresence p in killsToSendme)
  5853. {
  5854. // m_log.Debug("[AVATAR]: killToMe: " + Lastname + " " + p.Lastname);
  5855. p.SendKillTo(this);
  5856. }
  5857. }
  5858. if (viewsToSendto.Count > 0)
  5859. {
  5860. foreach (ScenePresence p in viewsToSendto)
  5861. {
  5862. SendViewTo(p);
  5863. }
  5864. }
  5865. if (viewsToSendme.Count > 0 )
  5866. {
  5867. foreach (ScenePresence p in viewsToSendme)
  5868. {
  5869. if (p.IsChildAgent)
  5870. continue;
  5871. // m_log.Debug("[AVATAR]: viewMe: " + Lastname + "<-" + p.Lastname);
  5872. p.SendViewTo(this);
  5873. }
  5874. }
  5875. }
  5876. public void HasMovedAway(bool nearRegion)
  5877. {
  5878. if (nearRegion)
  5879. {
  5880. if (Scene.AttachmentsModule != null)
  5881. Scene.AttachmentsModule.DeleteAttachmentsFromScene(this, true);
  5882. if (!ParcelHideThisAvatar || IsViewerUIGod)
  5883. return;
  5884. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  5885. foreach (ScenePresence p in allpresences)
  5886. {
  5887. if (p.IsDeleted || p == this || p.IsChildAgent || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5888. continue;
  5889. if (p.currentParcelUUID == m_currentParcelUUID)
  5890. {
  5891. p.SendKillTo(this);
  5892. }
  5893. }
  5894. }
  5895. else
  5896. {
  5897. lock (m_completeMovementLock)
  5898. {
  5899. GodController.HasMovedAway();
  5900. NeedInitialData = -1;
  5901. m_gotRegionHandShake = false;
  5902. }
  5903. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  5904. foreach (ScenePresence p in allpresences)
  5905. {
  5906. if (p == this)
  5907. continue;
  5908. SendKillTo(p);
  5909. if (!p.IsChildAgent)
  5910. p.SendKillTo(this);
  5911. }
  5912. if (Scene.AttachmentsModule != null)
  5913. Scene.AttachmentsModule.DeleteAttachmentsFromScene(this, true);
  5914. }
  5915. }
  5916. // kill with attachs root kills
  5917. public void SendKillTo(ScenePresence p)
  5918. {
  5919. List<uint> ids = new List<uint>(m_attachments.Count + 1);
  5920. foreach (SceneObjectGroup sog in m_attachments)
  5921. {
  5922. ids.Add(sog.RootPart.LocalId);
  5923. }
  5924. ids.Add(LocalId);
  5925. p.ControllingClient.SendKillObject(ids);
  5926. }
  5927. /*
  5928. // kill with hack
  5929. public void SendKillTo(ScenePresence p)
  5930. {
  5931. foreach (SceneObjectGroup sog in m_attachments)
  5932. p.ControllingClient.SendPartFullUpdate(sog.RootPart, LocalId + 1);
  5933. p.ControllingClient.SendKillObject(new List<uint> { LocalId });
  5934. }
  5935. */
  5936. public void SendViewTo(ScenePresence p)
  5937. {
  5938. SendAvatarDataToAgentNF(p);
  5939. SendAppearanceToAgent(p);
  5940. if (Animator != null)
  5941. Animator.SendAnimPackToClient(p.ControllingClient);
  5942. SendAttachmentsToAgentNF(p);
  5943. }
  5944. public void SetAnimationOverride(string animState, UUID animID)
  5945. {
  5946. Overrides.SetOverride(animState, animID);
  5947. // Animator.SendAnimPack();
  5948. Animator.ForceUpdateMovementAnimations();
  5949. }
  5950. public UUID GetAnimationOverride(string animState)
  5951. {
  5952. return Overrides.GetOverriddenAnimation(animState);
  5953. }
  5954. // http caps assets bandwidth control
  5955. private int m_capbandwidth = -1;
  5956. private int m_bandwidth = 100000;
  5957. private int m_bandwidthBurst = 20000;
  5958. private int m_bytesControl;
  5959. private double m_lastBandwithTime;
  5960. private object m_throttleLock = new object();
  5961. public bool CapCanSendAsset(int type, int size)
  5962. {
  5963. if(size == 0)
  5964. return true;
  5965. lock (m_throttleLock)
  5966. {
  5967. if (type > 1)
  5968. {
  5969. // not texture or mesh
  5970. m_bytesControl -= size;
  5971. return true;
  5972. }
  5973. double currenttime = Util.GetTimeStamp();
  5974. double timeElapsed = currenttime - m_lastBandwithTime;
  5975. if (timeElapsed > .02)
  5976. {
  5977. m_lastBandwithTime = currenttime;
  5978. int add = (int)(m_bandwidth * timeElapsed);
  5979. m_bytesControl += add;
  5980. if (m_bytesControl > m_bandwidthBurst)
  5981. m_bytesControl = m_bandwidthBurst;
  5982. }
  5983. if (m_bytesControl > 0 )
  5984. {
  5985. m_bytesControl -= size;
  5986. return true;
  5987. }
  5988. }
  5989. return false;
  5990. }
  5991. }
  5992. }