Scene.cs 246 KB

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