Scene.cs 243 KB

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