OSSL_Api.cs 239 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650
  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 log4net;
  28. using Nini.Config;
  29. using OpenMetaverse;
  30. using OpenMetaverse.StructuredData;
  31. using OpenSim.Framework;
  32. using OpenSim.Region.Framework.Interfaces;
  33. using OpenSim.Region.Framework.Scenes;
  34. using OpenSim.Region.Framework.Scenes.Scripting;
  35. using OpenSim.Region.ScriptEngine.Interfaces;
  36. using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces;
  37. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  38. using OpenSim.Services.Connectors.Hypergrid;
  39. using OpenSim.Services.Interfaces;
  40. using System;
  41. using System.Collections;
  42. using System.Collections.Concurrent;
  43. using System.Collections.Generic;
  44. using System.Reflection;
  45. using System.Text;
  46. using System.Text.RegularExpressions;
  47. using System.Threading;
  48. using System.Security.Cryptography;
  49. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  50. using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
  51. using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
  52. using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  53. using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
  54. using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
  55. using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
  56. using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
  57. using PermissionMask = OpenSim.Framework.PermissionMask;
  58. using TPFlags = OpenSim.Framework.Constants.TeleportFlags;
  59. #pragma warning disable IDE1006
  60. namespace OpenSim.Region.ScriptEngine.Shared.Api
  61. {
  62. //////////////////////////////////////////////////////////////
  63. //
  64. // Level description
  65. //
  66. // None - Function is no threat at all. It doesn't constitute
  67. // an threat to either users or the system and has no
  68. // known side effects
  69. //
  70. // Nuisance - Abuse of this command can cause a nuisance to the
  71. // region operator, such as log message spew
  72. //
  73. // VeryLow - Extreme levels ob abuse of this function can cause
  74. // impaired functioning of the region, or very gullible
  75. // users can be tricked into experiencing harmless effects
  76. //
  77. // Low - Intentional abuse can cause crashes or malfunction
  78. // under certain circumstances, which can easily be rectified,
  79. // or certain users can be tricked into certain situations
  80. // in an avoidable manner.
  81. //
  82. // Moderate - Intentional abuse can cause denial of service and crashes
  83. // with potential of data or state loss, or trusting users
  84. // can be tricked into embarrassing or uncomfortable
  85. // situationsa.
  86. //
  87. // High - Casual abuse can cause impaired functionality or temporary
  88. // denial of service conditions. Intentional abuse can easily
  89. // cause crashes with potential data loss, or can be used to
  90. // trick experienced and cautious users into unwanted situations,
  91. // or changes global data permanently and without undo ability
  92. // Malicious scripting can allow theft of content
  93. //
  94. // VeryHigh - Even normal use may, depending on the number of instances,
  95. // or frequency of use, result in severe service impairment
  96. // or crash with loss of data, or can be used to cause
  97. // unwanted or harmful effects on users without giving the
  98. // user a means to avoid it.
  99. //
  100. // Severe - Even casual use is a danger to region stability, or function
  101. // allows console or OS command execution, or function allows
  102. // taking money without consent, or allows deletion or
  103. // modification of user data, or allows the compromise of
  104. // sensitive data by design.
  105. // flags functions threat control
  106. public enum AllowedControlFlags : int
  107. {
  108. NONE = 0,
  109. PARCEL_OWNER = 1,
  110. PARCEL_GROUP_MEMBER = 1 << 1,
  111. ESTATE_MANAGER = 1 << 2,
  112. ESTATE_OWNER = 1 << 3,
  113. ACTIVE_GOD = 1 << 4,
  114. GOD = 1 << 5,
  115. GRID_GOD = 1 << 6,
  116. // internal
  117. THREATLEVEL = 1 << 28,
  118. OWNERUUID = 1 << 29,
  119. CREATORUUID = 1 << 30,
  120. //int thingie = 1 << 31,
  121. ALL = 0x0FFFFFFF
  122. }
  123. class FunctionPerms
  124. {
  125. public List<UUID> AllowedCreators;
  126. public List<UUID> AllowedOwners;
  127. public AllowedControlFlags AllowedControl = AllowedControlFlags.NONE;
  128. }
  129. [Serializable]
  130. public class OSSL_Api : IOSSL_Api, IScriptApi
  131. {
  132. public const string GridInfoServiceConfigSectionName = "GridInfoService";
  133. // shared things
  134. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  135. private static readonly object m_OSSLLock = new();
  136. private static bool m_doneSharedInit = false;
  137. internal static bool m_OSFunctionsEnabled = false;
  138. internal static TimeZoneInfo PSTTimeZone = null;
  139. internal static bool m_PermissionErrortoOwner = false;
  140. internal static ThreatLevel m_MaxThreatLevel = ThreatLevel.VeryLow;
  141. internal static float m_ScriptDelayFactor = 1.0f;
  142. internal static float m_ScriptDistanceFactor = 1.0f;
  143. internal static IConfig m_osslconfig;
  144. internal static ConcurrentDictionary<string, FunctionPerms> m_FunctionPerms = new();
  145. internal IScriptEngine m_ScriptEngine;
  146. internal LSL_Api m_LSL_Api = null; // get a reference to the LSL API so we can call methods housed there
  147. internal SceneObjectPart m_host;
  148. internal TaskInventoryItem m_item;
  149. protected IUrlModule m_UrlModule = null;
  150. protected ISoundModule m_SoundModule = null;
  151. protected IEnvironmentModule m_envModule = null;
  152. protected IGroupsModule m_groupsModule = null;
  153. protected IMessageTransferModule m_TransferModule = null;
  154. public Scene World;
  155. public void Initialize(IScriptEngine scriptEngine, SceneObjectPart host, TaskInventoryItem item)
  156. {
  157. //private init
  158. m_ScriptEngine = scriptEngine;
  159. World = scriptEngine.World;
  160. m_host = host;
  161. m_item = item;
  162. m_UrlModule = m_ScriptEngine.World.RequestModuleInterface<IUrlModule>();
  163. m_SoundModule = m_ScriptEngine.World.RequestModuleInterface<ISoundModule>();
  164. m_envModule = m_ScriptEngine.World.RequestModuleInterface<IEnvironmentModule>();
  165. m_groupsModule = m_ScriptEngine.World.RequestModuleInterface<IGroupsModule>();
  166. m_TransferModule = m_ScriptEngine.World.RequestModuleInterface<IMessageTransferModule>();
  167. //private init
  168. lock (m_OSSLLock)
  169. {
  170. if(m_doneSharedInit)
  171. return;
  172. m_osslconfig = m_ScriptEngine.ConfigSource.Configs["OSSL"];
  173. m_osslconfig ??= m_ScriptEngine.Config;
  174. if (m_osslconfig.GetBoolean("AllowOSFunctions", true))
  175. {
  176. m_OSFunctionsEnabled = true;
  177. // m_log.Warn("[OSSL] OSSL FUNCTIONS ENABLED");
  178. }
  179. m_PermissionErrortoOwner = m_osslconfig.GetBoolean("PermissionErrorToOwner", m_PermissionErrortoOwner);
  180. m_ScriptDelayFactor = m_ScriptEngine.Config.GetFloat("ScriptDelayFactor", 1.0f);
  181. m_ScriptDistanceFactor = m_ScriptEngine.Config.GetFloat("ScriptDistanceLimitFactor", 1.0f);
  182. string risk = m_osslconfig.GetString("OSFunctionThreatLevel", "VeryLow");
  183. switch (risk)
  184. {
  185. case "NoAccess":
  186. m_MaxThreatLevel = ThreatLevel.NoAccess;
  187. break;
  188. case "None":
  189. m_MaxThreatLevel = ThreatLevel.None;
  190. break;
  191. case "VeryLow":
  192. m_MaxThreatLevel = ThreatLevel.VeryLow;
  193. break;
  194. case "Low":
  195. m_MaxThreatLevel = ThreatLevel.Low;
  196. break;
  197. case "Moderate":
  198. m_MaxThreatLevel = ThreatLevel.Moderate;
  199. break;
  200. case "High":
  201. m_MaxThreatLevel = ThreatLevel.High;
  202. break;
  203. case "VeryHigh":
  204. m_MaxThreatLevel = ThreatLevel.VeryHigh;
  205. break;
  206. case "Severe":
  207. m_MaxThreatLevel = ThreatLevel.Severe;
  208. break;
  209. default:
  210. break;
  211. }
  212. try
  213. {
  214. PSTTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
  215. }
  216. catch
  217. {
  218. PSTTimeZone = null;
  219. }
  220. if(PSTTimeZone == null)
  221. {
  222. try
  223. {
  224. PSTTimeZone = TimeZoneInfo.FindSystemTimeZoneById("America/Los_Angeles");
  225. }
  226. catch
  227. {
  228. PSTTimeZone = null;
  229. }
  230. }
  231. m_doneSharedInit = true;
  232. }
  233. }
  234. internal static void OSSLError(string msg)
  235. {
  236. throw new ScriptException("OSSL Runtime Error: " + msg);
  237. }
  238. /// <summary>
  239. /// Initialize the LSL interface.
  240. /// </summary>
  241. /// <remarks>
  242. /// FIXME: This is an abomination. We should be able to set this up earlier but currently we have no
  243. /// guarantee the interface is present on Initialize(). There needs to be another post initialize call from
  244. /// ScriptInstance.
  245. /// </remarks>
  246. private void InitLSL()
  247. {
  248. if (m_LSL_Api == null)
  249. {
  250. m_LSL_Api = (LSL_Api)m_ScriptEngine.GetApi(m_item.ItemID, "LSL");
  251. if (m_LSL_Api == null)
  252. throw new Exception("OSSL failed to load LSL API");
  253. }
  254. }
  255. //
  256. //Dumps an error message on the debug console.
  257. //
  258. internal void OSSLShoutError(string message)
  259. {
  260. if (message.Length > 1023)
  261. message = message[..1023];
  262. World.SimChat(Utils.StringToBytes(message),
  263. ChatTypeEnum.Shout, ScriptBaseClass.DEBUG_CHANNEL, m_host.ParentGroup.RootPart.AbsolutePosition, m_host.Name, m_host.UUID, false);
  264. IWorldComm wComm = m_ScriptEngine.World.RequestModuleInterface<IWorldComm>();
  265. wComm?.DeliverMessage(ChatTypeEnum.Shout, ScriptBaseClass.DEBUG_CHANNEL, m_host.Name, m_host.UUID, message);
  266. if (m_item is not null)
  267. m_ScriptEngine.SleepScript(m_item.ItemID, 1000);
  268. //else
  269. // Thread.Sleep(1000);
  270. }
  271. // Returns if OSSL is enabled. Throws a script exception if OSSL is not allowed..
  272. // for safe funtions always active
  273. public static void CheckThreatLevel()
  274. {
  275. if (!m_OSFunctionsEnabled)
  276. OSSLError("permission denied. All unsafe OSSL funtions disabled"); // throws
  277. }
  278. // Returns if the function is allowed. Throws a script exception if not allowed.
  279. public void CheckThreatLevel(ThreatLevel level, string function)
  280. {
  281. if (!m_OSFunctionsEnabled)
  282. {
  283. if (m_PermissionErrortoOwner)
  284. throw new ScriptException("(OWNER)OSSL Permission Error: All unsafe OSSL funtions disabled");
  285. else
  286. throw new ScriptException("OSSL Permission Error: All unsafe OSSL funtions disabled");
  287. }
  288. string reasonWhyNot = CheckThreatLevelTest(level, function);
  289. if (!string.IsNullOrEmpty(reasonWhyNot))
  290. {
  291. if (m_PermissionErrortoOwner)
  292. throw new ScriptException("(OWNER)OSSL Permission Error: " + reasonWhyNot);
  293. else
  294. throw new ScriptException("OSSL Permission Error: " + reasonWhyNot);
  295. }
  296. }
  297. // Check to see if function is allowed. Returns an empty string if function permitted
  298. // or a string explaining why this function can't be used.
  299. private string CheckThreatLevelTest(ThreatLevel level, string function)
  300. {
  301. if (!m_FunctionPerms.TryGetValue(function, out FunctionPerms perms))
  302. {
  303. perms = new FunctionPerms();
  304. string ownerPerm = m_osslconfig.GetString("Allow_" + function, "");
  305. string creatorPerm = m_osslconfig.GetString("Creators_" + function, "");
  306. if (string.IsNullOrWhiteSpace(ownerPerm) && string.IsNullOrWhiteSpace(creatorPerm))
  307. {
  308. // Default Threat level check
  309. perms.AllowedControl = AllowedControlFlags.THREATLEVEL;
  310. }
  311. else
  312. {
  313. if (bool.TryParse(ownerPerm, out bool allowed))
  314. {
  315. // Boolean given
  316. if (allowed)
  317. {
  318. // Allow globally
  319. perms.AllowedControl = AllowedControlFlags.ALL;
  320. }
  321. // false is fallback
  322. }
  323. else
  324. {
  325. string[] ids;
  326. bool error = false;
  327. if (!string.IsNullOrWhiteSpace(ownerPerm))
  328. {
  329. ids = ownerPerm.Split(Util.SplitCommaArray);
  330. foreach (string id in ids)
  331. {
  332. string current = id.Trim();
  333. current = current.ToUpper();
  334. switch(current)
  335. {
  336. case "":
  337. break;
  338. case "PARCEL_OWNER":
  339. perms.AllowedControl |= AllowedControlFlags.PARCEL_OWNER;
  340. break;
  341. case "PARCEL_GROUP_MEMBER":
  342. perms.AllowedControl |= AllowedControlFlags.PARCEL_GROUP_MEMBER;
  343. break;
  344. case "ESTATE_MANAGER":
  345. perms.AllowedControl |= AllowedControlFlags.ESTATE_MANAGER;
  346. break;
  347. case "ESTATE_OWNER":
  348. perms.AllowedControl |= AllowedControlFlags.ESTATE_OWNER;
  349. break;
  350. case "ACTIVE_GOD":
  351. perms.AllowedControl |= AllowedControlFlags.ACTIVE_GOD;
  352. break;
  353. case "GOD":
  354. perms.AllowedControl |= AllowedControlFlags.GOD;
  355. break;
  356. case "GRID_GOD":
  357. perms.AllowedControl |= AllowedControlFlags.GRID_GOD;
  358. break;
  359. default:
  360. {
  361. if (UUID.TryParse(current, out UUID uuid))
  362. {
  363. if (uuid.IsNotZero())
  364. {
  365. perms.AllowedOwners ??= new List<UUID>();
  366. perms.AllowedControl |= AllowedControlFlags.OWNERUUID;
  367. perms.AllowedOwners.Add(uuid);
  368. }
  369. }
  370. else
  371. {
  372. error = true;
  373. }
  374. break;
  375. }
  376. }
  377. }
  378. if (error)
  379. m_log.WarnFormat("[OSSLENABLE]: error parsing line Allow_{0} = {1}", function, ownerPerm);
  380. }
  381. error = false;
  382. if (!string.IsNullOrWhiteSpace(creatorPerm))
  383. {
  384. ids = creatorPerm.Split(Util.SplitCommaArray);
  385. foreach (string id in ids)
  386. {
  387. string current = id.Trim();
  388. if (UUID.TryParse(current, out UUID uuid))
  389. {
  390. if (!uuid.IsZero())
  391. {
  392. perms.AllowedCreators ??= new List<UUID>();
  393. perms.AllowedControl |= AllowedControlFlags.CREATORUUID;
  394. perms.AllowedCreators.Add(uuid);
  395. }
  396. }
  397. else
  398. {
  399. error = true;
  400. }
  401. }
  402. if (error)
  403. m_log.WarnFormat("[OSSLENABLE]: error parsing line Creators_{0} = {1}", function, creatorPerm);
  404. }
  405. // both empty fallback as disabled
  406. }
  407. }
  408. m_FunctionPerms.TryAdd(function,perms);
  409. }
  410. AllowedControlFlags functionControl = perms.AllowedControl;
  411. if (functionControl == AllowedControlFlags.THREATLEVEL)
  412. {
  413. // Allow / disallow by threat level
  414. if (level <= m_MaxThreatLevel)
  415. return string.Empty;
  416. return $"{function} permission denied. Allowed threat level is {m_MaxThreatLevel} but function threat level is {level}";
  417. }
  418. if (functionControl == 0)
  419. return $"{function} disabled in region configuration";
  420. if (functionControl == AllowedControlFlags.ALL)
  421. return string.Empty;
  422. if (((functionControl & AllowedControlFlags.OWNERUUID) != 0) && perms.AllowedOwners.Contains(m_host.OwnerID))
  423. {
  424. // prim owner is in the list of allowed owners
  425. return string.Empty;
  426. }
  427. if ((functionControl & AllowedControlFlags.PARCEL_OWNER) != 0)
  428. {
  429. ILandObject land = World.LandChannel.GetLandObject(m_host.AbsolutePosition);
  430. if (land.LandData.OwnerID.Equals(m_item.OwnerID))
  431. return string.Empty;
  432. }
  433. //OSSL only may be used if object is in the same group as the parcel
  434. if ((functionControl & AllowedControlFlags.PARCEL_GROUP_MEMBER) != 0)
  435. {
  436. ILandObject land = World.LandChannel.GetLandObject(m_host.AbsolutePosition);
  437. if (land.LandData.GroupID.Equals(m_item.GroupID) && !land.LandData.GroupID.IsZero())
  438. return string.Empty;
  439. }
  440. //Only regionowners may use the function
  441. if ((functionControl & AllowedControlFlags.ESTATE_OWNER) != 0)
  442. {
  443. if (World.RegionInfo.EstateSettings.EstateOwner.Equals(m_item.OwnerID))
  444. return string.Empty;
  445. }
  446. //Only Estate Managers may use the function
  447. if ((functionControl & AllowedControlFlags.ESTATE_MANAGER) != 0)
  448. {
  449. //Only Estate Managers may use the function
  450. if (World.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_item.OwnerID))
  451. return string.Empty;
  452. }
  453. //Only grid gods may use the function
  454. if ((functionControl & AllowedControlFlags.GRID_GOD) != 0)
  455. {
  456. if (World.Permissions.IsGridGod(m_item.OwnerID))
  457. return string.Empty;
  458. }
  459. //Any god may use the function
  460. if ((functionControl & AllowedControlFlags.GOD) != 0)
  461. {
  462. if (World.Permissions.IsAdministrator(m_item.OwnerID))
  463. return string.Empty;
  464. }
  465. //Only active gods may use the function
  466. if ((functionControl & AllowedControlFlags.ACTIVE_GOD) != 0)
  467. {
  468. ScenePresence sp = World.GetScenePresence(m_item.OwnerID);
  469. if (sp is not null && !sp.IsDeleted && sp.IsGod)
  470. return string.Empty;
  471. }
  472. // else if no creators its denied
  473. if((functionControl & AllowedControlFlags.CREATORUUID) == 0)
  474. return $"{function} permission denied";
  475. if (!perms.AllowedCreators.Contains(m_item.CreatorID))
  476. return($"{function} permission denied. Script creator is not in the list of users allowed to execute this function and prim owner also has no permission");
  477. if (m_item.CreatorID.NotEqual(m_item.OwnerID))
  478. {
  479. if ((m_item.CurrentPermissions & (uint)PermissionMask.Modify) != 0)
  480. return $"{function} permission denied. Script creator is not prim owner";
  481. }
  482. return string.Empty;
  483. }
  484. internal void OSSLDeprecated(string function, string replacement)
  485. {
  486. OSSLShoutError($"Use of function {function} is deprecated. Use {replacement} instead.");
  487. }
  488. protected void ScriptSleep(int delay)
  489. {
  490. delay = (int)(delay * m_ScriptDelayFactor);
  491. if (delay < 10)
  492. return;
  493. if(m_item is not null)
  494. m_ScriptEngine.SleepScript(m_item.ItemID, delay);
  495. }
  496. public LSL_Integer osSetTerrainHeight(int x, int y, double val)
  497. {
  498. CheckThreatLevel(ThreatLevel.High, "osSetTerrainHeight");
  499. return SetTerrainHeight(x, y, val);
  500. }
  501. public LSL_Integer osTerrainSetHeight(int x, int y, double val)
  502. {
  503. CheckThreatLevel(ThreatLevel.High, "osTerrainSetHeight");
  504. OSSLDeprecated("osTerrainSetHeight", "osSetTerrainHeight");
  505. return SetTerrainHeight(x, y, val);
  506. }
  507. private LSL_Integer SetTerrainHeight(int x, int y, double val)
  508. {
  509. if (x > (World.RegionInfo.RegionSizeX - 1) || x < 0 || y > (World.RegionInfo.RegionSizeY - 1) || y < 0)
  510. OSSLError("osSetTerrainHeight: Coordinate out of bounds");
  511. if (World.Permissions.CanTerraformLand(m_host.OwnerID, new Vector3(x, y, 0)))
  512. {
  513. World.Heightmap[x, y] = (float)val;
  514. return 1;
  515. }
  516. return 0;
  517. }
  518. public LSL_Float osGetTerrainHeight(int x, int y)
  519. {
  520. CheckThreatLevel();
  521. return GetTerrainHeight(x, y);
  522. }
  523. public LSL_Float osTerrainGetHeight(int x, int y)
  524. {
  525. CheckThreatLevel();
  526. OSSLDeprecated("osTerrainGetHeight", "osGetTerrainHeight");
  527. return GetTerrainHeight(x, y);
  528. }
  529. private LSL_Float GetTerrainHeight(int x, int y)
  530. {
  531. if (x > (World.RegionInfo.RegionSizeX - 1) || x < 0 || y > (World.RegionInfo.RegionSizeY - 1) || y < 0)
  532. OSSLError("osGetTerrainHeight: Coordinate out of bounds");
  533. return World.Heightmap[x, y];
  534. }
  535. double m_lastosTerrainFlush = 0;
  536. public void osTerrainFlush()
  537. {
  538. double now = Util.GetTimeStamp();
  539. if(now - m_lastosTerrainFlush < 60)
  540. return;
  541. m_lastosTerrainFlush = now;
  542. CheckThreatLevel(ThreatLevel.VeryLow, "osTerrainFlush");
  543. ITerrainModule terrainModule = World.RequestModuleInterface<ITerrainModule>();
  544. terrainModule?.TaintTerrain();
  545. }
  546. public int osRegionRestart(double seconds)
  547. {
  548. // This is High here because region restart is not reliable
  549. // it may result in the region staying down or becoming
  550. // unstable. This should be changed to Low or VeryLow once
  551. // The underlying functionality is fixed, since the security
  552. // as such is sound
  553. //
  554. CheckThreatLevel(ThreatLevel.High, "osRegionRestart");
  555. IRestartModule restartModule = World.RequestModuleInterface<IRestartModule>();
  556. if (World.Permissions.CanIssueEstateCommand(m_host.OwnerID, false) && (restartModule != null))
  557. {
  558. if (seconds < 15)
  559. {
  560. restartModule.AbortRestart("Region restart has been aborted\n");
  561. return 1;
  562. }
  563. RegionRestart(seconds, string.Empty);
  564. return 1;
  565. }
  566. return 0;
  567. }
  568. public int osRegionRestart(double seconds, string msg)
  569. {
  570. CheckThreatLevel(ThreatLevel.High, "osRegionRestart");
  571. IRestartModule restartModule = World.RequestModuleInterface<IRestartModule>();
  572. if (World.Permissions.CanIssueEstateCommand(m_host.OwnerID, false) && (restartModule != null))
  573. {
  574. if (seconds < 15)
  575. {
  576. restartModule.AbortRestart("Region restart has been aborted\n");
  577. return 1;
  578. }
  579. RegionRestart(seconds, msg);
  580. return 1;
  581. }
  582. return 0;
  583. }
  584. private void RegionRestart(double seconds, string msg)
  585. {
  586. IRestartModule restartModule = World.RequestModuleInterface<IRestartModule>();
  587. List<int> times = new();
  588. while (seconds > 0)
  589. {
  590. times.Add((int)seconds);
  591. if (seconds > 300)
  592. seconds -= 120;
  593. else if (seconds > 120)
  594. seconds -= 60;
  595. else if (seconds > 60)
  596. seconds -= 30;
  597. else
  598. seconds -= 15;
  599. }
  600. if (msg.Length == 0)
  601. restartModule.ScheduleRestart(UUID.Zero, "Region: " + World.RegionInfo.RegionName + " is about to restart.\n\nIf you stay here you will be logged out.\n\n\nTime remaining: {0}.\n", times.ToArray(), true);
  602. else
  603. restartModule.ScheduleRestart(UUID.Zero, msg + "\n\nTime remaining: {0}.\n", times.ToArray(), true);
  604. }
  605. public void osRegionNotice(string msg)
  606. {
  607. CheckThreatLevel(ThreatLevel.High, "osRegionNotice");
  608. IDialogModule dm = World.RequestModuleInterface<IDialogModule>();
  609. if (dm == null)
  610. return;
  611. if (!World.Permissions.CanIssueEstateCommand(m_host.OwnerID, false))
  612. return;
  613. dm.SendGeneralAlert(msg + "\n");
  614. }
  615. public void osRegionNotice(LSL_Key agentID, string msg)
  616. {
  617. CheckThreatLevel(ThreatLevel.High, "osRegionNotice");
  618. if (!World.Permissions.CanIssueEstateCommand(m_host.OwnerID, false))
  619. return;
  620. IDialogModule dm = World.RequestModuleInterface<IDialogModule>();
  621. if (dm is null)
  622. return;
  623. if (!UUID.TryParse(agentID, out UUID avatarID))
  624. return;
  625. if (!World.TryGetScenePresence(avatarID, out ScenePresence sp))
  626. return;
  627. if (sp is null || sp.IsChildAgent || sp.IsDeleted || sp.IsInTransit || sp.IsNPC)
  628. return;
  629. dm.SendAlertToUser(sp.ControllingClient, msg + "\n", false);
  630. }
  631. public void osSetRot(UUID target, Quaternion rotation)
  632. {
  633. // if enabled It can be used to destroy
  634. // arbitrary builds the user would normally have no rights to
  635. //
  636. CheckThreatLevel(ThreatLevel.VeryHigh, "osSetRot");
  637. if (World.Entities.TryGetValue(target, out EntityBase entity))
  638. {
  639. if (entity is SceneObjectGroup sog)
  640. sog.UpdateGroupRotationR(rotation);
  641. else if (entity is ScenePresence sop)
  642. sop.Rotation = rotation;
  643. }
  644. else
  645. {
  646. OSSLError("osSetRot: Invalid target");
  647. }
  648. }
  649. public string osSetDynamicTextureURL(string dynamicID, string contentType, string url, string extraParams,
  650. int timer)
  651. {
  652. CheckThreatLevel(ThreatLevel.VeryHigh, "osSetDynamicTextureURL");
  653. if (dynamicID.Length == 0)
  654. {
  655. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  656. UUID createdTexture =
  657. textureManager.AddDynamicTextureURL(World.RegionInfo.RegionID, m_host.UUID, contentType, url,
  658. extraParams);
  659. return createdTexture.ToString();
  660. }
  661. else
  662. {
  663. //TODO update existing dynamic textures
  664. }
  665. return ScriptBaseClass.NULL_KEY;
  666. }
  667. public string osSetDynamicTextureURLBlend(string dynamicID, string contentType, string url, string extraParams,
  668. int timer, int alpha)
  669. {
  670. CheckThreatLevel(ThreatLevel.VeryHigh, "osSetDynamicTextureURLBlend");
  671. if (dynamicID.Length == 0)
  672. {
  673. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  674. UUID createdTexture =
  675. textureManager.AddDynamicTextureURL(World.RegionInfo.RegionID, m_host.UUID, contentType, url,
  676. extraParams, true, (byte) alpha);
  677. return createdTexture.ToString();
  678. }
  679. else
  680. {
  681. //TODO update existing dynamic textures
  682. }
  683. return ScriptBaseClass.NULL_KEY;
  684. }
  685. public string osSetDynamicTextureURLBlendFace(string dynamicID, string contentType, string url, string extraParams,
  686. bool blend, int disp, int timer, int alpha, int face)
  687. {
  688. CheckThreatLevel(ThreatLevel.VeryHigh, "osSetDynamicTextureURLBlendFace");
  689. if (dynamicID.Length == 0)
  690. {
  691. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  692. UUID createdTexture =
  693. textureManager.AddDynamicTextureURL(World.RegionInfo.RegionID, m_host.UUID, contentType, url,
  694. extraParams, blend, disp, (byte) alpha, face);
  695. return createdTexture.ToString();
  696. }
  697. else
  698. {
  699. //TODO update existing dynamic textures
  700. }
  701. return ScriptBaseClass.NULL_KEY;
  702. }
  703. public string osSetDynamicTextureData(string dynamicID, string contentType, string data, string extraParams,
  704. int timer)
  705. {
  706. return osSetDynamicTextureDataFace(dynamicID, contentType, data, extraParams, timer, -1);
  707. }
  708. public string osSetDynamicTextureDataFace(string dynamicID, string contentType, string data, string extraParams,
  709. int timer, int face)
  710. {
  711. CheckThreatLevel(ThreatLevel.VeryLow, "osSetDynamicTextureData");
  712. if (dynamicID.Length == 0)
  713. {
  714. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  715. if (textureManager is not null)
  716. {
  717. if (extraParams.Length == 0)
  718. {
  719. extraParams = "256";
  720. }
  721. UUID createdTexture =
  722. textureManager.AddDynamicTextureData(World.RegionInfo.RegionID, m_host.UUID, contentType, data,
  723. extraParams, false, 3, 255, face);
  724. return createdTexture.ToString();
  725. }
  726. }
  727. else
  728. {
  729. //TODO update existing dynamic textures
  730. }
  731. return ScriptBaseClass.NULL_KEY;
  732. }
  733. public string osSetDynamicTextureDataBlend(string dynamicID, string contentType, string data, string extraParams,
  734. int timer, int alpha)
  735. {
  736. CheckThreatLevel(ThreatLevel.VeryLow, "osSetDynamicTextureDataBlend");
  737. if (dynamicID.Length == 0)
  738. {
  739. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  740. if (textureManager is not null)
  741. {
  742. if (extraParams.Length == 0)
  743. {
  744. extraParams = "256";
  745. }
  746. UUID createdTexture =
  747. textureManager.AddDynamicTextureData(World.RegionInfo.RegionID, m_host.UUID, contentType, data,
  748. extraParams, true, (byte) alpha);
  749. return createdTexture.ToString();
  750. }
  751. }
  752. else
  753. {
  754. //TODO update existing dynamic textures
  755. }
  756. return ScriptBaseClass.NULL_KEY;
  757. }
  758. public string osSetDynamicTextureDataBlendFace(string dynamicID, string contentType, string data, string extraParams,
  759. bool blend, int disp, int timer, int alpha, int face)
  760. {
  761. CheckThreatLevel(ThreatLevel.VeryLow , "osSetDynamicTextureDataBlendFace");
  762. if (dynamicID.Length == 0)
  763. {
  764. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  765. if (textureManager is not null)
  766. {
  767. if (extraParams.Length == 0)
  768. {
  769. extraParams = "256";
  770. }
  771. UUID createdTexture =
  772. textureManager.AddDynamicTextureData(World.RegionInfo.RegionID, m_host.UUID, contentType, data,
  773. extraParams, blend, disp, (byte) alpha, face);
  774. return createdTexture.ToString();
  775. }
  776. }
  777. else
  778. {
  779. //TODO update existing dynamic textures
  780. }
  781. return ScriptBaseClass.NULL_KEY;
  782. }
  783. public bool osConsoleCommand(string command)
  784. {
  785. CheckThreatLevel(ThreatLevel.Severe, "osConsoleCommand");
  786. // For safety, we add another permission check here, and don't rely only on the standard OSSL permissions
  787. if (World.Permissions.CanRunConsoleCommand(m_host.OwnerID))
  788. {
  789. MainConsole.Instance.RunCommand(command);
  790. return true;
  791. }
  792. return false;
  793. }
  794. public void osSetPrimFloatOnWater(int floatYN)
  795. {
  796. CheckThreatLevel(ThreatLevel.VeryLow, "osSetPrimFloatOnWater");
  797. m_host.ParentGroup.RootPart.SetFloatOnWater(floatYN);
  798. }
  799. private bool checkAllowAgentTPbyLandOwner(UUID agentId, Vector3 pos)
  800. {
  801. if(m_host.OwnerID.Equals(agentId))
  802. return true;
  803. if (m_item.PermsGranter.Equals(agentId))
  804. {
  805. if ((m_item.PermsMask & ScriptBaseClass.PERMISSION_TELEPORT) != 0)
  806. return true;
  807. }
  808. ILandObject land = World.LandChannel.GetLandObject(pos);
  809. if(land is null)
  810. return true;
  811. LandData landdata = land.LandData;
  812. if(landdata is null)
  813. return true;
  814. if(landdata.OwnerID.Equals(m_host.OwnerID))
  815. return true;
  816. EstateSettings es = World.RegionInfo.EstateSettings;
  817. if(es is not null && es.IsEstateManagerOrOwner(m_host.OwnerID))
  818. return true;
  819. if(!landdata.IsGroupOwned)
  820. return false;
  821. UUID landGroup = landdata.GroupID;
  822. if(landGroup.IsZero())
  823. return false;
  824. if(landGroup.Equals(m_host.GroupID))
  825. return true;
  826. return false;
  827. }
  828. // Teleport functions
  829. public void osLocalTeleportAgent(LSL_Key agent, LSL_Types.Vector3 position, LSL_Types.Vector3 velocity, LSL_Types.Vector3 lookat, LSL_Integer flags)
  830. {
  831. if (!UUID.TryParse(agent, out UUID agentId))
  832. return;
  833. ScenePresence presence = World.GetScenePresence(agentId);
  834. if (presence is null || presence.IsDeleted || presence.IsInTransit)
  835. return;
  836. Vector3 pos = presence.AbsolutePosition;
  837. if (!checkAllowAgentTPbyLandOwner(agentId, pos))
  838. return;
  839. World.RequestLocalTeleport(presence, position, velocity, lookat, flags);
  840. }
  841. public void osTeleportAgent(string agent, string regionName, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat)
  842. {
  843. // High because there is no security check. High griefer potential
  844. //
  845. CheckThreatLevel(ThreatLevel.Severe, "osTeleportAgent");
  846. TeleportAgent(agent, regionName, position, lookat);
  847. }
  848. private void TeleportAgent(string agent, string regionName, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat)
  849. {
  850. if (UUID.TryParse(agent, out UUID agentId))
  851. {
  852. ScenePresence presence = World.GetScenePresence(agentId);
  853. if (presence is null || presence.IsDeleted || presence.IsChildAgent || presence.IsInTransit)
  854. return;
  855. Vector3 pos = presence.AbsolutePosition;
  856. if (!checkAllowAgentTPbyLandOwner(agentId, pos))
  857. {
  858. ScriptSleep(500);
  859. return;
  860. }
  861. if (string.IsNullOrEmpty(regionName) || regionName.Equals(World.RegionInfo.RegionName, StringComparison.InvariantCultureIgnoreCase))
  862. {
  863. World.RequestTeleportLocation(presence.ControllingClient, World.RegionInfo.RegionName, position,
  864. lookat, (uint)TPFlags.ViaLocation);
  865. ScriptSleep(500);
  866. }
  867. else
  868. {
  869. // We will launch the teleport on a new thread so that when the script threads are terminated
  870. // before teleport in ScriptInstance.GetXMLState(), we don't end up aborting the one doing the teleporting.
  871. Util.FireAndForget(
  872. o => World.RequestTeleportLocation(
  873. presence.ControllingClient, regionName, position,
  874. lookat, (uint)TPFlags.ViaLocation),
  875. null, "OSSL_Api.TeleportAgentByRegionCoords");
  876. ScriptSleep(5000);
  877. }
  878. }
  879. }
  880. public void osTeleportAgent(string agent, int regionGridX, int regionGridY, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat)
  881. {
  882. // High because there is no security check. High griefer potential
  883. //
  884. CheckThreatLevel(ThreatLevel.Severe, "osTeleportAgent");
  885. TeleportAgent(agent, regionGridX, regionGridY, position, lookat);
  886. }
  887. private void TeleportAgent(string agent, int regionGridX, int regionGridY,
  888. LSL_Types.Vector3 position, LSL_Types.Vector3 lookat)
  889. {
  890. if (UUID.TryParse(agent, out UUID agentId))
  891. {
  892. ScenePresence presence = World.GetScenePresence(agentId);
  893. if (presence is null || presence.IsDeleted || presence.IsChildAgent || presence.IsInTransit)
  894. return;
  895. Vector3 pos = presence.AbsolutePosition;
  896. if (!checkAllowAgentTPbyLandOwner(agentId, pos))
  897. {
  898. ScriptSleep(500);
  899. return;
  900. }
  901. ulong regionHandle = Util.RegionGridLocToHandle((uint)regionGridX, (uint)regionGridY);
  902. Util.FireAndForget(
  903. o => World.RequestTeleportLocation(
  904. presence.ControllingClient, regionHandle,
  905. position, lookat, (uint)TPFlags.ViaLocation),
  906. null, "OSSL_Api.TeleportAgentByRegionName");
  907. ScriptSleep(5000);
  908. }
  909. }
  910. public void osTeleportAgent(string agent, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat)
  911. {
  912. if (UUID.TryParse(agent, out UUID agentId))
  913. {
  914. ScenePresence presence = World.GetScenePresence(agentId);
  915. if (presence == null || presence.IsDeleted || presence.IsChildAgent || presence.IsInTransit)
  916. return;
  917. Vector3 pos = presence.AbsolutePosition;
  918. if (!checkAllowAgentTPbyLandOwner(agentId, pos))
  919. {
  920. ScriptSleep(500);
  921. return;
  922. }
  923. RegionInfo ri = World.RegionInfo;
  924. double px = position.x;
  925. double py = position.y;
  926. if (px >= 0 && px < ri.RegionSizeX && py >= 0 && py < ri.RegionSizeY)
  927. {
  928. World.RequestTeleportLocation(presence.ControllingClient, ri.RegionName, position,
  929. lookat, (uint)TPFlags.ViaLocation);
  930. ScriptSleep(500);
  931. return;
  932. }
  933. // not in region. lets use global position then.
  934. px += ri.WorldLocX;
  935. py += ri.WorldLocY;
  936. int gx = (int)px / 256;
  937. int gy = (int)py / 256;
  938. px -= 256 * gx;
  939. py -= 256 * gy;
  940. ulong regionHandle = Util.RegionGridLocToHandle((uint)gx, (uint)gy);
  941. Util.FireAndForget(
  942. o => World.RequestTeleportLocation(
  943. presence.ControllingClient, regionHandle,
  944. new Vector3((float)px, (float)py, (float)position.z), lookat, (uint)TPFlags.ViaLocation),
  945. null, "OSSL_Api.TeleportAgentByFarPos");
  946. ScriptSleep(5000);
  947. }
  948. }
  949. public void osTeleportOwner(string regionName, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat)
  950. {
  951. // Threat level None because this is what can already be done with the World Map in the viewer
  952. CheckThreatLevel(ThreatLevel.None, "osTeleportOwner");
  953. TeleportAgent(m_host.OwnerID.ToString(), regionName, position, lookat);
  954. }
  955. public void osTeleportOwner(int regionGridX, int regionGridY, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat)
  956. {
  957. CheckThreatLevel(ThreatLevel.None, "osTeleportOwner");
  958. TeleportAgent(m_host.OwnerID.ToString(), regionGridX, regionGridY, position, lookat);
  959. }
  960. public void osTeleportOwner(LSL_Types.Vector3 position, LSL_Types.Vector3 lookat)
  961. {
  962. CheckThreatLevel(ThreatLevel.None, "osTeleportOwner");
  963. osTeleportAgent(m_host.OwnerID.ToString(), position, lookat);
  964. }
  965. ///<summary>
  966. /// Allows a script IN the target prim to force an avatar to sit on it using normal methods
  967. /// as if called by the client.
  968. /// Silent fail if agent (or target if overloaded) not found.
  969. /// Does work if passed key (or keys if overloaded).
  970. /// </summary>
  971. /// <param name="avatar"></param>
  972. public void osForceOtherSit(string avatar)
  973. {
  974. CheckThreatLevel(ThreatLevel.VeryHigh, "osForceOtherSit");
  975. ForceSit(avatar, m_host.UUID);
  976. }
  977. /// <summary>
  978. /// Overload method of osForceOtherSit(string avatar) to allow a script NOT in the target prim to force
  979. /// an avatar to sit on the target prim using normal methods as if called by the client.
  980. /// </summary>
  981. /// <param name="avatar"></param>
  982. /// <param name="target"></param>
  983. public void osForceOtherSit(string avatar, string target)
  984. {
  985. CheckThreatLevel(ThreatLevel.VeryHigh, "osForceOtherSit");
  986. if(UUID.TryParse( target, out UUID targetID))
  987. ForceSit(avatar, targetID);
  988. }
  989. public void ForceSit(string avatar, UUID targetID)
  990. {
  991. if (!UUID.TryParse(avatar, out UUID agentID))
  992. return;
  993. ScenePresence presence = World.GetScenePresence(agentID);
  994. if(presence is null)
  995. return;
  996. SceneObjectPart part = World.GetSceneObjectPart(targetID);
  997. if (part is not null && part.SitTargetAvatar.IsZero())
  998. presence.HandleAgentRequestSit(presence.ControllingClient,
  999. agentID, targetID,
  1000. part.SitTargetPosition);
  1001. }
  1002. // Get a list of all the avatars/agents in the region
  1003. public LSL_List osGetAgents()
  1004. {
  1005. // threat level is None as we could get this information with an
  1006. // in-world script as well, just not as efficient
  1007. CheckThreatLevel(ThreatLevel.None, "osGetAgents");
  1008. LSL_List result = new();
  1009. World.ForEachRootScenePresence(delegate(ScenePresence sp)
  1010. {
  1011. result.Add(new LSL_String(sp.Name));
  1012. });
  1013. return result;
  1014. }
  1015. public string osGetAgentIP(string agent)
  1016. {
  1017. CheckThreatLevel(ThreatLevel.Severe, "osGetAgentIP");
  1018. if(!(World.Permissions.IsGod(m_host.OwnerID))) // user god always needed
  1019. return string.Empty;
  1020. if(!UUID.TryParse(agent, out UUID avatarID))
  1021. return string.Empty;
  1022. ScenePresence target = World.GetScenePresence(avatarID);
  1023. if (target is not null)
  1024. {
  1025. return target.ControllingClient.RemoteEndPoint.Address.ToString();
  1026. }
  1027. return string.Empty;
  1028. }
  1029. // Adam's super super custom animation functions
  1030. public void osAvatarPlayAnimation(LSL_Key avatar, string animation)
  1031. {
  1032. CheckThreatLevel(ThreatLevel.VeryHigh, "osAvatarPlayAnimation");
  1033. if (!UUID.TryParse(avatar, out UUID avatarID))
  1034. return;
  1035. ScenePresence target = World.GetScenePresence(avatarID);
  1036. if (target is null)
  1037. return;
  1038. UUID animID = UUID.Zero;
  1039. m_host.TaskInventory.LockItemsForRead(true);
  1040. foreach (KeyValuePair<UUID, TaskInventoryItem> inv in m_host.TaskInventory)
  1041. {
  1042. if (inv.Value.Type == (int)AssetType.Animation)
  1043. {
  1044. if (inv.Value.Name == animation)
  1045. {
  1046. animID = inv.Value.AssetID;
  1047. break;
  1048. }
  1049. }
  1050. }
  1051. m_host.TaskInventory.LockItemsForRead(false);
  1052. if (animID.IsZero())
  1053. target.Animator.AddAnimation(animation, m_host.UUID);
  1054. else
  1055. target.Animator.AddAnimation(animID, m_host.UUID);
  1056. }
  1057. public void osAvatarStopAnimation(LSL_Key avatar, string animation)
  1058. {
  1059. CheckThreatLevel(ThreatLevel.VeryHigh, "osAvatarStopAnimation");
  1060. if (!UUID.TryParse(avatar, out UUID avatarID))
  1061. return;
  1062. ScenePresence target = World.GetScenePresence(avatarID);
  1063. if (target is null)
  1064. return;
  1065. if (!UUID.TryParse(animation, out UUID animID))
  1066. {
  1067. TaskInventoryItem item = m_host.Inventory.GetInventoryItem(animation);
  1068. if (item != null && item.Type == (int)AssetType.Animation)
  1069. animID = item.AssetID;
  1070. else
  1071. animID = UUID.Zero;
  1072. }
  1073. if (animID.IsZero())
  1074. target.Animator.RemoveAnimation(animation);
  1075. else
  1076. target.Animator.RemoveAnimation(animID, true);
  1077. }
  1078. //Texture draw functions
  1079. public string osDrawResetTransform(string drawList)
  1080. {
  1081. CheckThreatLevel();
  1082. drawList += "ResetTransf;";
  1083. return drawList;
  1084. }
  1085. public string osDrawRotationTransform(string drawList, LSL_Float x)
  1086. {
  1087. CheckThreatLevel();
  1088. drawList += "RotTransf " + x + ";";
  1089. return drawList;
  1090. }
  1091. public string osDrawScaleTransform(string drawList, LSL_Float x, LSL_Float y)
  1092. {
  1093. CheckThreatLevel();
  1094. drawList += "ScaleTransf " + x + "," + y + ";";
  1095. return drawList;
  1096. }
  1097. public string osDrawTranslationTransform(string drawList, LSL_Float x, LSL_Float y)
  1098. {
  1099. CheckThreatLevel();
  1100. drawList += "TransTransf " + x + "," + y + ";";
  1101. return drawList;
  1102. }
  1103. public string osMovePen(string drawList, int x, int y)
  1104. {
  1105. CheckThreatLevel();
  1106. drawList += "MoveTo " + x + "," + y + ";";
  1107. return drawList;
  1108. }
  1109. public string osDrawLine(string drawList, int startX, int startY, int endX, int endY)
  1110. {
  1111. CheckThreatLevel();
  1112. drawList += "MoveTo "+ startX+","+ startY +"; LineTo "+endX +","+endY +"; ";
  1113. return drawList;
  1114. }
  1115. public string osDrawLine(string drawList, int endX, int endY)
  1116. {
  1117. CheckThreatLevel();
  1118. drawList += "LineTo " + endX + "," + endY + "; ";
  1119. return drawList;
  1120. }
  1121. public string osDrawText(string drawList, string text)
  1122. {
  1123. CheckThreatLevel();
  1124. drawList += "Text " + text + "; ";
  1125. return drawList;
  1126. }
  1127. public string osDrawEllipse(string drawList, int width, int height)
  1128. {
  1129. CheckThreatLevel();
  1130. drawList += "Ellipse " + width + "," + height + "; ";
  1131. return drawList;
  1132. }
  1133. public string osDrawFilledEllipse(string drawList, int width, int height)
  1134. {
  1135. CheckThreatLevel();
  1136. drawList += "FillEllipse " + width + "," + height + "; ";
  1137. return drawList;
  1138. }
  1139. public string osDrawRectangle(string drawList, int width, int height)
  1140. {
  1141. CheckThreatLevel();
  1142. drawList += "Rectangle " + width + "," + height + "; ";
  1143. return drawList;
  1144. }
  1145. public string osDrawFilledRectangle(string drawList, int width, int height)
  1146. {
  1147. CheckThreatLevel();
  1148. drawList += "FillRectangle " + width + "," + height + "; ";
  1149. return drawList;
  1150. }
  1151. public string osDrawFilledPolygon(string drawList, LSL_List x, LSL_List y)
  1152. {
  1153. CheckThreatLevel();
  1154. if (x.Length != y.Length || x.Length < 3)
  1155. {
  1156. return "";
  1157. }
  1158. drawList += "FillPolygon " + x.GetStringItem(0) + "," + y.GetStringItem(0);
  1159. for (int i = 1; i < x.Length; i++)
  1160. {
  1161. drawList += "," + x.GetStringItem(i) + "," + y.GetStringItem(i);
  1162. }
  1163. drawList += "; ";
  1164. return drawList;
  1165. }
  1166. public string osDrawPolygon(string drawList, LSL_List x, LSL_List y)
  1167. {
  1168. CheckThreatLevel();
  1169. if (x.Length != y.Length || x.Length < 3)
  1170. {
  1171. return "";
  1172. }
  1173. drawList += "Polygon " + x.GetStringItem(0) + "," + y.GetStringItem(0);
  1174. for (int i = 1; i < x.Length; i++)
  1175. {
  1176. drawList += "," + x.GetStringItem(i) + "," + y.GetStringItem(i);
  1177. }
  1178. drawList += "; ";
  1179. return drawList;
  1180. }
  1181. public string osSetFontSize(string drawList, int fontSize)
  1182. {
  1183. CheckThreatLevel();
  1184. drawList += "FontSize "+ fontSize +"; ";
  1185. return drawList;
  1186. }
  1187. public string osSetFontName(string drawList, string fontName)
  1188. {
  1189. CheckThreatLevel();
  1190. drawList += "FontName "+ fontName +"; ";
  1191. return drawList;
  1192. }
  1193. public string osSetPenSize(string drawList, int penSize)
  1194. {
  1195. CheckThreatLevel();
  1196. drawList += "PenSize " + penSize + "; ";
  1197. return drawList;
  1198. }
  1199. public string osSetPenColor(string drawList, string color)
  1200. {
  1201. CheckThreatLevel();
  1202. drawList += "PenColor " + color + "; ";
  1203. return drawList;
  1204. }
  1205. public string osSetPenColor(string drawList, LSL_Types.Vector3 color)
  1206. {
  1207. CheckThreatLevel();
  1208. byte argbR = Utils.FloatZeroOneToByte((float)color.x);
  1209. byte argbG = Utils.FloatZeroOneToByte((float)color.y);
  1210. byte argbB = Utils.FloatZeroOneToByte((float)color.z);
  1211. StringBuilder sb = new(19);
  1212. sb.Append("PenColor FF");
  1213. sb.Append(Utils.charHighNibbleToHexChar(argbR));
  1214. sb.Append(Utils.charLowNibbleToHexChar(argbR));
  1215. sb.Append(Utils.charHighNibbleToHexChar(argbG));
  1216. sb.Append(Utils.charLowNibbleToHexChar(argbG));
  1217. sb.Append(Utils.charHighNibbleToHexChar(argbB));
  1218. sb.Append(Utils.charLowNibbleToHexChar(argbB));
  1219. sb.Append("; ");
  1220. drawList += sb.ToString();
  1221. return drawList;
  1222. }
  1223. public string osSetPenColor(string drawList, LSL_Types.Vector3 color, LSL_Float alpha)
  1224. {
  1225. CheckThreatLevel();
  1226. byte argbA = Utils.FloatZeroOneToByte((float)alpha);
  1227. byte argbR = Utils.FloatZeroOneToByte((float)color.x);
  1228. byte argbG = Utils.FloatZeroOneToByte((float)color.y);
  1229. byte argbB = Utils.FloatZeroOneToByte((float)color.z);
  1230. StringBuilder sb = new(19);
  1231. sb.Append("PenColor ");
  1232. sb.Append(Utils.charHighNibbleToHexChar(argbA));
  1233. sb.Append(Utils.charLowNibbleToHexChar(argbA));
  1234. sb.Append(Utils.charHighNibbleToHexChar(argbR));
  1235. sb.Append(Utils.charLowNibbleToHexChar(argbR));
  1236. sb.Append(Utils.charHighNibbleToHexChar(argbG));
  1237. sb.Append(Utils.charLowNibbleToHexChar(argbG));
  1238. sb.Append(Utils.charHighNibbleToHexChar(argbB));
  1239. sb.Append(Utils.charLowNibbleToHexChar(argbB));
  1240. sb.Append(';');
  1241. sb.Append(' ');
  1242. drawList += sb.ToString();
  1243. return drawList;
  1244. }
  1245. // Deprecated
  1246. public string osSetPenColour(string drawList, string colour)
  1247. {
  1248. CheckThreatLevel();
  1249. OSSLDeprecated("osSetPenColour", "osSetPenColor");
  1250. drawList += "PenColour " + colour + "; ";
  1251. return drawList;
  1252. }
  1253. public string osSetPenCap(string drawList, string direction, string type)
  1254. {
  1255. CheckThreatLevel();
  1256. drawList += "PenCap " + direction + "," + type + "; ";
  1257. return drawList;
  1258. }
  1259. public string osDrawImage(string drawList, int width, int height, string imageUrl)
  1260. {
  1261. CheckThreatLevel();
  1262. drawList +="Image " +width + "," + height+ ","+ imageUrl +"; " ;
  1263. return drawList;
  1264. }
  1265. public LSL_Vector osGetDrawStringSize(string contentType, string text, string fontName, int fontSize)
  1266. {
  1267. CheckThreatLevel();
  1268. IDynamicTextureManager textureManager = World.RequestModuleInterface<IDynamicTextureManager>();
  1269. if (textureManager is not null)
  1270. {
  1271. textureManager.GetDrawStringSize(contentType, text, fontName, fontSize,
  1272. out double xSize, out double ySize);
  1273. return new LSL_Vector(xSize, ySize, 0);
  1274. }
  1275. return LSL_Vector.Zero;
  1276. }
  1277. public void osSetRegionWaterHeight(double height)
  1278. {
  1279. CheckThreatLevel(ThreatLevel.High, "osSetRegionWaterHeight");
  1280. World.EventManager.TriggerRequestChangeWaterHeight((float)height);
  1281. }
  1282. /// <summary>
  1283. /// Changes the Region Sun Settings, then Triggers a Sun Update
  1284. /// </summary>
  1285. /// <param name="useEstateSun">True to use Estate Sun instead of Region Sun</param>
  1286. /// <param name="sunFixed">True to keep the sun stationary</param>
  1287. /// <param name="sunHour">The "Sun Hour" that is desired, 0...24, with 0 just after SunRise</param>
  1288. public void osSetRegionSunSettings(bool useEstateSun, bool sunFixed, double sunHour)
  1289. {
  1290. CheckThreatLevel(ThreatLevel.High, "osSetRegionSunSettings");
  1291. while (sunHour > 24.0)
  1292. sunHour -= 24.0;
  1293. while (sunHour < 0)
  1294. sunHour += 24.0;
  1295. World.RegionInfo.RegionSettings.UseEstateSun = useEstateSun;
  1296. World.RegionInfo.RegionSettings.SunPosition = sunHour + 6; // LL Region Sun Hour is 6 to 30
  1297. World.RegionInfo.RegionSettings.FixedSun = sunFixed;
  1298. World.RegionInfo.RegionSettings.Save();
  1299. World.EventManager.TriggerEstateToolsSunUpdate(World.RegionInfo.RegionHandle);
  1300. }
  1301. /// <summary>
  1302. /// Changes the Estate Sun Settings, then Triggers a Sun Update
  1303. /// </summary>
  1304. /// <param name="sunFixed">True to keep the sun stationary, false to use global time</param>
  1305. /// <param name="sunHour">The "Sun Hour" that is desired, 0...24, with 0 just after SunRise</param>
  1306. public void osSetEstateSunSettings(bool sunFixed, double sunHour)
  1307. {
  1308. /*
  1309. CheckThreatLevel(ThreatLevel.High, "osSetEstateSunSettings");
  1310. while (sunHour > 24.0)
  1311. sunHour -= 24.0;
  1312. while (sunHour < 0)
  1313. sunHour += 24.0;
  1314. World.RegionInfo.EstateSettings.UseGlobalTime = !sunFixed;
  1315. World.RegionInfo.EstateSettings.SunPosition = sunHour;
  1316. World.RegionInfo.EstateSettings.FixedSun = sunFixed;
  1317. World.EstateDataService.StoreEstateSettings(World.RegionInfo.EstateSettings);
  1318. World.EventManager.TriggerEstateToolsSunUpdate(World.RegionInfo.RegionHandle);
  1319. */
  1320. }
  1321. /// <summary>
  1322. /// Return the current Sun Hour 0...24, with 0 being roughly sun-rise
  1323. /// </summary>
  1324. /// <returns></returns>
  1325. public LSL_Float osGetCurrentSunHour()
  1326. {
  1327. CheckThreatLevel();
  1328. if (m_envModule is null)
  1329. return 0;
  1330. float frac = m_envModule.GetRegionDayFractionTime();
  1331. return 24 * frac;
  1332. }
  1333. public LSL_Float osGetApparentTime()
  1334. {
  1335. CheckThreatLevel();
  1336. if (m_envModule is null)
  1337. return 0;
  1338. float frac = m_envModule.GetRegionDayFractionTime();
  1339. return 86400 * frac;
  1340. }
  1341. private static string timeToString(float frac, bool format24)
  1342. {
  1343. int h = (int)frac;
  1344. frac -= h;
  1345. frac *= 60;
  1346. int m = (int)frac;
  1347. frac -= m;
  1348. frac *= 60;
  1349. int s = (int)frac;
  1350. if (format24)
  1351. {
  1352. return string.Format("{0:00}:{1:00}:{2:00}", h, m, s);
  1353. }
  1354. if (h > 12)
  1355. return string.Format("{0}:{1:00}:{2:00} PM", h - 12, m, s);
  1356. if (h == 12)
  1357. return string.Format("{0}:{1:00}:{2:00} PM", h, m, s);
  1358. return string.Format("{0}:{1:00}:{2:00} AM", h, m, s);
  1359. }
  1360. public LSL_String osGetApparentTimeString(LSL_Integer format24)
  1361. {
  1362. CheckThreatLevel();
  1363. if (m_envModule is null)
  1364. return format24 != 0 ? "00:00:00" : "0:00:00 AM";
  1365. float frac = 24 * m_envModule.GetRegionDayFractionTime();
  1366. return timeToString(frac, format24 != 0);
  1367. }
  1368. public LSL_Float osGetApparentRegionTime()
  1369. {
  1370. CheckThreatLevel();
  1371. if (m_envModule is null)
  1372. return 0;
  1373. float frac = m_envModule.GetRegionDayFractionTime();
  1374. return 86400 * frac;
  1375. }
  1376. public LSL_String osGetApparentRegionTimeString(LSL_Integer format24)
  1377. {
  1378. CheckThreatLevel();
  1379. if (m_envModule is null)
  1380. return format24 != 0 ? "00:00:00" : "0:00:00 AM";
  1381. float frac = 24 * m_envModule.GetRegionDayFractionTime();
  1382. return timeToString(frac, format24 != 0);
  1383. }
  1384. public double osSunGetParam(string param)
  1385. {
  1386. CheckThreatLevel(ThreatLevel.None, "osSunGetParam");
  1387. OSSLDeprecated("osSunGetParam", "osGetSunParam");
  1388. return GetSunParam(param);
  1389. }
  1390. public LSL_Float osGetSunParam(LSL_String param)
  1391. {
  1392. CheckThreatLevel();
  1393. return GetSunParam(param);
  1394. }
  1395. private double GetSunParam(string param)
  1396. {
  1397. param = param.ToLower();
  1398. switch(param)
  1399. {
  1400. case "day_length":
  1401. return m_envModule is null ? 14400 : m_envModule.GetDayLength(m_host.AbsolutePosition);
  1402. case "year_length":
  1403. return 365;
  1404. case "day_night_offset":
  1405. return 0;
  1406. case "update_interval":
  1407. return 0.1;
  1408. case "day_time_sun_hour_scale":
  1409. return 1;
  1410. default:
  1411. break;
  1412. }
  1413. return 0;
  1414. }
  1415. public void osSunSetParam(string param, double value)
  1416. {
  1417. CheckThreatLevel(ThreatLevel.None, "osSunSetParam");
  1418. OSSLDeprecated("osSunSetParam", "osSetSunParam");
  1419. SetSunParam(param, value);
  1420. }
  1421. public void osSetSunParam(string param, double value)
  1422. {
  1423. CheckThreatLevel(ThreatLevel.None, "osSetSunParam");
  1424. SetSunParam(param, value);
  1425. }
  1426. private void SetSunParam(string param, double value)
  1427. {
  1428. ISunModule module = World.RequestModuleInterface<ISunModule>();
  1429. module?.SetSunParameter(param, value);
  1430. }
  1431. public string osWindActiveModelPluginName()
  1432. {
  1433. CheckThreatLevel(ThreatLevel.None, "osWindActiveModelPluginName");
  1434. IWindModule module = World.RequestModuleInterface<IWindModule>();
  1435. if (module is not null)
  1436. {
  1437. return module.WindActiveModelPluginName;
  1438. }
  1439. return string.Empty;
  1440. }
  1441. public void osSetWindParam(string plugin, string param, LSL_Float value)
  1442. {
  1443. CheckThreatLevel(ThreatLevel.VeryLow, "osSetWindParam");
  1444. IWindModule module = World.RequestModuleInterface<IWindModule>();
  1445. if (module is not null)
  1446. {
  1447. try
  1448. {
  1449. module.WindParamSet(plugin, param, (float)value);
  1450. }
  1451. catch (Exception) { }
  1452. }
  1453. }
  1454. public LSL_Float osGetWindParam(string plugin, string param)
  1455. {
  1456. CheckThreatLevel(ThreatLevel.VeryLow, "osGetWindParam");
  1457. IWindModule module = World.RequestModuleInterface<IWindModule>();
  1458. if (module is not null)
  1459. {
  1460. return module.WindParamGet(plugin, param);
  1461. }
  1462. return 0.0f;
  1463. }
  1464. public LSL_Integer osGetParcelDwell(LSL_Vector pos)
  1465. {
  1466. LandData land = World.GetLandData(pos);
  1467. if (land is not null)
  1468. {
  1469. return (int)land.Dwell;
  1470. }
  1471. return 0;
  1472. }
  1473. // Routines for creating and managing parcels programmatically
  1474. public void osParcelJoin(LSL_Vector pos1, LSL_Vector pos2)
  1475. {
  1476. CheckThreatLevel(ThreatLevel.High, "osParcelJoin");
  1477. int startx = (int)(pos1.x < pos2.x ? pos1.x : pos2.x);
  1478. int starty = (int)(pos1.y < pos2.y ? pos1.y : pos2.y);
  1479. int endx = (int)(pos1.x > pos2.x ? pos1.x : pos2.x);
  1480. int endy = (int)(pos1.y > pos2.y ? pos1.y : pos2.y);
  1481. World.LandChannel.Join(startx,starty,endx,endy,m_host.OwnerID);
  1482. }
  1483. public void osParcelSubdivide(LSL_Vector pos1, LSL_Vector pos2)
  1484. {
  1485. CheckThreatLevel(ThreatLevel.High, "osParcelSubdivide");
  1486. int startx = (int)(pos1.x < pos2.x ? pos1.x : pos2.x);
  1487. int starty = (int)(pos1.y < pos2.y ? pos1.y : pos2.y);
  1488. int endx = (int)(pos1.x > pos2.x ? pos1.x : pos2.x);
  1489. int endy = (int)(pos1.y > pos2.y ? pos1.y : pos2.y);
  1490. World.LandChannel.Subdivide(startx,starty,endx,endy,m_host.OwnerID);
  1491. }
  1492. public void osParcelSetDetails(LSL_Vector pos, LSL_List rules)
  1493. {
  1494. const string functionName = "osParcelSetDetails";
  1495. CheckThreatLevel(ThreatLevel.High, functionName);
  1496. OSSLDeprecated(functionName, "osSetParcelDetails");
  1497. SetParcelDetails(pos, rules, functionName);
  1498. }
  1499. public void osSetParcelDetails(LSL_Vector pos, LSL_List rules)
  1500. {
  1501. const string functionName = "osSetParcelDetails";
  1502. CheckThreatLevel(ThreatLevel.High, functionName);
  1503. SetParcelDetails(pos, rules, functionName);
  1504. }
  1505. private void SetParcelDetails(LSL_Vector pos, LSL_List rules, string functionName)
  1506. {
  1507. // Get a reference to the land data and make sure the owner of the script
  1508. // can modify it
  1509. ILandObject startLandObject = World.LandChannel.GetLandObject((int)pos.x, (int)pos.y);
  1510. if (startLandObject is null)
  1511. {
  1512. OSSLShoutError("There is no land at that location");
  1513. return;
  1514. }
  1515. if (!World.Permissions.CanEditParcelProperties(m_host.OwnerID, startLandObject, GroupPowers.LandOptions, false))
  1516. {
  1517. OSSLShoutError("script owner does not have permission to modify the parcel");
  1518. return;
  1519. }
  1520. // Create a new land data object we can modify
  1521. LandData newLand = startLandObject.LandData.Copy();
  1522. UUID uuid;
  1523. EstateSettings es = World.RegionInfo.EstateSettings;
  1524. bool changed = false;
  1525. bool changedSeeAvs = false;
  1526. bool changedoverlay = false;
  1527. bool changedneedupdate = false;
  1528. string arg;
  1529. int iarg;
  1530. // Process the rules, not sure what the impact would be of changing owner or group
  1531. for (int idx = 0; idx < rules.Length;)
  1532. {
  1533. int code = rules.GetIntegerItem(idx++);
  1534. switch (code)
  1535. {
  1536. case ScriptBaseClass.PARCEL_DETAILS_NAME:
  1537. arg = rules.GetStrictStringItem(idx++);
  1538. if (newLand.Name != arg)
  1539. {
  1540. newLand.Name = arg;
  1541. changed = true;
  1542. }
  1543. break;
  1544. case ScriptBaseClass.PARCEL_DETAILS_DESC:
  1545. arg = rules.GetStrictStringItem(idx++);
  1546. if (newLand.Description != arg)
  1547. {
  1548. newLand.Description = arg;
  1549. changed = true;
  1550. }
  1551. break;
  1552. case ScriptBaseClass.PARCEL_DETAILS_OWNER:
  1553. arg = rules.GetStrictStringItem(idx++);
  1554. if (es is not null && !es.IsEstateManagerOrOwner(m_host.OwnerID))
  1555. {
  1556. OSSLShoutError("script owner does not have permission to modify the parcel owner");
  1557. }
  1558. else
  1559. {
  1560. if (UUID.TryParse(arg, out uuid))
  1561. {
  1562. if(newLand.OwnerID.NotEqual(uuid))
  1563. {
  1564. changed = true;
  1565. newLand.OwnerID = uuid;
  1566. newLand.GroupID = UUID.Zero;
  1567. }
  1568. }
  1569. }
  1570. break;
  1571. case ScriptBaseClass.PARCEL_DETAILS_GROUP:
  1572. arg = rules.GetStrictStringItem(idx++);
  1573. if (m_host.OwnerID.Equals(newLand.OwnerID) || es == null || es.IsEstateManagerOrOwner(m_host.OwnerID))
  1574. {
  1575. if (UUID.TryParse(arg, out uuid))
  1576. {
  1577. if(newLand.GroupID.NotEqual(uuid))
  1578. {
  1579. if(uuid.IsZero())
  1580. {
  1581. changed = true;
  1582. newLand.GroupID = uuid;
  1583. }
  1584. else
  1585. {
  1586. GroupMembershipData member = null;
  1587. if (m_groupsModule is not null)
  1588. member = m_groupsModule.GetMembershipData(uuid, newLand.OwnerID);
  1589. if (member is null)
  1590. OSSLShoutError(string.Format("land owner is not member of the new group for parcel"));
  1591. else
  1592. {
  1593. changed = true;
  1594. newLand.GroupID = uuid;
  1595. }
  1596. }
  1597. }
  1598. }
  1599. }
  1600. else
  1601. {
  1602. OSSLShoutError("script owner does not have permission to modify the parcel group");
  1603. }
  1604. break;
  1605. case ScriptBaseClass.PARCEL_DETAILS_CLAIMDATE:
  1606. if(es is not null && !es.IsEstateManagerOrOwner(m_host.OwnerID))
  1607. {
  1608. OSSLShoutError("script owner does not have permission to modify the parcel CLAIM DATE");
  1609. }
  1610. else
  1611. {
  1612. int date = rules.GetIntegerItem(idx++);
  1613. if (date == 0)
  1614. date = Util.UnixTimeSinceEpoch();
  1615. if(newLand.ClaimDate != date)
  1616. {
  1617. changed = true;
  1618. newLand.ClaimDate = date;
  1619. }
  1620. }
  1621. break;
  1622. case ScriptBaseClass.PARCEL_DETAILS_SEE_AVATARS:
  1623. iarg = rules.GetIntegerItem(idx++);
  1624. bool newavs = iarg != 0;
  1625. if(newLand.SeeAVs != newavs)
  1626. {
  1627. changed = true;
  1628. changedSeeAvs = true;
  1629. changedoverlay = true;
  1630. changedneedupdate = true;
  1631. newLand.SeeAVs = newavs;
  1632. }
  1633. break;
  1634. case ScriptBaseClass.PARCEL_DETAILS_ANY_AVATAR_SOUNDS:
  1635. iarg = rules.GetIntegerItem(idx++);
  1636. bool newavsounds = iarg != 0;
  1637. if(newLand.AnyAVSounds != newavsounds)
  1638. {
  1639. changed = true;
  1640. newLand.AnyAVSounds = newavsounds;
  1641. }
  1642. break;
  1643. case ScriptBaseClass.PARCEL_DETAILS_GROUP_SOUNDS:
  1644. iarg = rules.GetIntegerItem(idx++);
  1645. bool newgrpsounds = iarg != 0;
  1646. if(newLand.GroupAVSounds != newgrpsounds)
  1647. {
  1648. changed = true;
  1649. newLand.GroupAVSounds = newgrpsounds;
  1650. }
  1651. break;
  1652. }
  1653. }
  1654. if(changed)
  1655. {
  1656. World.LandChannel.UpdateLandObject(newLand.LocalID, newLand);
  1657. if(changedneedupdate)
  1658. {
  1659. UUID parcelID= newLand.GlobalID;
  1660. World.ForEachRootScenePresence(delegate (ScenePresence avatar)
  1661. {
  1662. if (avatar is null || avatar.IsDeleted || avatar.IsInTransit)
  1663. return;
  1664. if(changedSeeAvs && avatar.currentParcelUUID.Equals(parcelID))
  1665. avatar.currentParcelUUID = parcelID; // force parcel flags review
  1666. if(avatar.ControllingClient is null)
  1667. return;
  1668. // this will be needed for some things like damage etc
  1669. // if(avatar.currentParcelUUID == parcelID)
  1670. // startLandObject.SendLandUpdateToClient(avatar.ControllingClient);
  1671. if(changedoverlay && !avatar.IsNPC)
  1672. World.LandChannel.SendParcelsOverlay(avatar.ControllingClient);
  1673. });
  1674. }
  1675. }
  1676. }
  1677. public void osSetParcelMusicURL(LSL_String url)
  1678. {
  1679. CheckThreatLevel(ThreatLevel.VeryLow, "osSetParcelMusicURL");
  1680. ILandObject land = World.LandChannel.GetLandObject(m_host.AbsolutePosition);
  1681. land?.SetMusicUrl(url);
  1682. }
  1683. public void osSetParcelMediaURL(LSL_String url)
  1684. {
  1685. CheckThreatLevel(ThreatLevel.VeryLow, "osSetParcelMediaURL");
  1686. ILandObject land = World.LandChannel.GetLandObject(m_host.AbsolutePosition);
  1687. land?.SetMediaUrl(url);
  1688. }
  1689. public void osSetParcelSIPAddress(string SIPAddress)
  1690. {
  1691. // What actually is the difference to the LL function?
  1692. //
  1693. CheckThreatLevel(ThreatLevel.VeryLow, "osSetParcelSIPAddress");
  1694. ILandObject land = World.LandChannel.GetLandObject(m_host.AbsolutePosition);
  1695. if (land.LandData.OwnerID.NotEqual(m_host.OwnerID))
  1696. {
  1697. OSSLError("osSetParcelSIPAddress: Sorry, you need to own the land to use this function");
  1698. return;
  1699. }
  1700. // get the voice module
  1701. IVoiceModule voiceModule = World.RequestModuleInterface<IVoiceModule>();
  1702. if (voiceModule is not null)
  1703. voiceModule.setLandSIPAddress(SIPAddress,land.LandData.GlobalID);
  1704. else
  1705. OSSLError("osSetParcelSIPAddress: No voice module enabled for this land");
  1706. }
  1707. public string osGetScriptEngineName()
  1708. {
  1709. // This gets a "high" because knowing the engine may be used
  1710. // to exploit engine-specific bugs or induce usage patterns
  1711. // that trigger engine-specific failures.
  1712. // Besides, public grid users aren't supposed to know.
  1713. //
  1714. CheckThreatLevel(ThreatLevel.High, "osGetScriptEngineName");
  1715. int scriptEngineNameIndex = 0;
  1716. if (!string.IsNullOrEmpty(m_ScriptEngine.ScriptEngineName))
  1717. {
  1718. // parse off the "ScriptEngine."
  1719. scriptEngineNameIndex = m_ScriptEngine.ScriptEngineName.IndexOf('.', scriptEngineNameIndex);
  1720. scriptEngineNameIndex++; // get past delimiter
  1721. int scriptEngineNameLength = m_ScriptEngine.ScriptEngineName.Length - scriptEngineNameIndex;
  1722. // create char array then a string that is only the script engine name
  1723. Char[] scriptEngineNameCharArray = m_ScriptEngine.ScriptEngineName.ToCharArray(scriptEngineNameIndex, scriptEngineNameLength);
  1724. string scriptEngineName = new(scriptEngineNameCharArray);
  1725. return scriptEngineName;
  1726. }
  1727. return string.Empty;
  1728. }
  1729. public LSL_Integer osCheckODE()
  1730. {
  1731. CheckThreatLevel();
  1732. if (m_ScriptEngine.World.PhysicsScene is not null)
  1733. {
  1734. if (m_ScriptEngine.World.PhysicsScene.EngineType == "OpenDynamicsEngine")
  1735. {
  1736. return new LSL_Integer(1); // true
  1737. }
  1738. }
  1739. return new LSL_Integer(0);
  1740. }
  1741. public string osGetPhysicsEngineType()
  1742. {
  1743. // High because it can be used to target attacks to known weaknesses
  1744. // This would allow a new class of griefer scripts that don't even
  1745. // require their user to know what they are doing (see script
  1746. // kiddie)
  1747. // Because it would be nice if scripts didn't blow up if the information
  1748. // about the physics engine, this function returns an empty string if
  1749. // the user does not have permission to see it. This as opposed to
  1750. // throwing an exception.
  1751. string ret = string.Empty;
  1752. if (string.IsNullOrEmpty(CheckThreatLevelTest(ThreatLevel.High, "osGetPhysicsEngineType")))
  1753. {
  1754. if (m_ScriptEngine.World.PhysicsScene != null)
  1755. {
  1756. ret = m_ScriptEngine.World.PhysicsScene.EngineType;
  1757. // An old physics engine might have an uninitialized engine type
  1758. ret ??= "unknown";
  1759. }
  1760. }
  1761. return ret;
  1762. }
  1763. public string osGetPhysicsEngineName()
  1764. {
  1765. CheckThreatLevel();
  1766. string ret = "NoEngine";
  1767. if (m_ScriptEngine.World.PhysicsScene != null)
  1768. {
  1769. ret = m_ScriptEngine.World.PhysicsScene.EngineName;
  1770. // An old physics engine might have an uninitialized engine type
  1771. ret ??= "UnknownEngine";
  1772. }
  1773. return ret;
  1774. }
  1775. public string osGetSimulatorVersion()
  1776. {
  1777. // High because it can be used to target attacks to known weaknesses
  1778. // This would allow a new class of griefer scripts that don't even
  1779. // require their user to know what they are doing (see script
  1780. // kiddie)
  1781. //
  1782. CheckThreatLevel(ThreatLevel.High,"osGetSimulatorVersion");
  1783. return m_ScriptEngine.World.GetSimulatorVersion();
  1784. }
  1785. /// <summary>
  1786. /// Send a message to to object identified by the given UUID
  1787. /// </summary>
  1788. /// <remarks>
  1789. /// A script in the object must implement the dataserver function
  1790. /// the dataserver function is passed the ID of the calling function and a string message
  1791. /// </remarks>
  1792. /// <param name="objectUUID"></param>
  1793. /// <param name="message"></param>
  1794. public void osMessageObject(LSL_Key objectUUID, string message)
  1795. {
  1796. CheckThreatLevel(ThreatLevel.Low, "osMessageObject");
  1797. if (!UUID.TryParse(objectUUID, out UUID objUUID)) // prior to patching, a thrown exception regarding invalid GUID format would be shouted instead.
  1798. {
  1799. OSSLShoutError("osMessageObject() cannot send messages to objects with invalid UUIDs");
  1800. return;
  1801. }
  1802. MessageObject(objUUID, message);
  1803. //ScriptSleep(25); // mostly a thread yield
  1804. }
  1805. private void MessageObject(UUID objUUID, string message)
  1806. {
  1807. object[] resobj = new object[] { new LSL_String(m_host.UUID.ToString()), new LSL_String(message) };
  1808. SceneObjectPart sceneOP = World.GetSceneObjectPart(objUUID);
  1809. if (sceneOP == null) // prior to patching, PostObjectEvent() would cause a throw exception to be shouted instead.
  1810. {
  1811. OSSLShoutError("osMessageObject() cannot send message to " + objUUID.ToString() + ", object was not found in scene.");
  1812. return;
  1813. }
  1814. m_ScriptEngine.PostObjectEvent(
  1815. sceneOP.LocalId, new EventParams(
  1816. "dataserver", resobj, Array.Empty<DetectParams>()));
  1817. }
  1818. /// <summary>
  1819. /// Similar to llDie but given an object UUID
  1820. /// </summary>
  1821. /// <param name="objectUUID"></param>
  1822. public void osDie(LSL_Key objectUUID)
  1823. {
  1824. CheckThreatLevel(ThreatLevel.Low, "osDie");
  1825. if (!UUID.TryParse(objectUUID, out UUID objUUID))
  1826. {
  1827. OSSLShoutError("osDie() cannot delete objects with invalid UUIDs");
  1828. return;
  1829. }
  1830. if(objUUID.IsZero())
  1831. return;
  1832. SceneObjectGroup sceneOG = World.GetSceneObjectGroup(objUUID);
  1833. if (sceneOG is null || sceneOG.IsDeleted || sceneOG.IsAttachment)
  1834. return;
  1835. if (sceneOG.OwnerID.NotEqual(m_host.OwnerID))
  1836. return;
  1837. // restrict to objects rezzed by host
  1838. if(sceneOG.RezzerID.Equals(m_host.ParentGroup.UUID))
  1839. {
  1840. // harakiri check should be true alwaya
  1841. if (sceneOG.UUID.NotEqual(m_host.ParentGroup.UUID))
  1842. World.DeleteSceneObject(sceneOG, false);
  1843. }
  1844. }
  1845. /// <summary>
  1846. /// Write a notecard directly to the prim's inventory.
  1847. /// </summary>
  1848. /// <remarks>
  1849. /// This needs ThreatLevel high. It is an excellent griefer tool,
  1850. /// In a loop, it can cause asset bloat and DOS levels of asset
  1851. /// writes.
  1852. /// </remarks>
  1853. /// <param name="notecardName">The name of the notecard to write.</param>
  1854. /// <param name="contents">The contents of the notecard.</param>
  1855. public void osMakeNotecard(string notecardName, LSL_String contents)
  1856. {
  1857. CheckThreatLevel(ThreatLevel.High, "osMakeNotecard");
  1858. SaveNotecard(notecardName, "Script generated notecard", contents + "\n", false);
  1859. }
  1860. public void osMakeNotecard(string notecardName, LSL_List contents)
  1861. {
  1862. CheckThreatLevel(ThreatLevel.High, "osMakeNotecard");
  1863. StringBuilder notecardData = new();
  1864. for (int i = 0; i < contents.Length; i++)
  1865. notecardData.Append(contents.GetStringItem(i) + "\n");
  1866. SaveNotecard(notecardName, "Script generated notecard", notecardData.ToString(), false);
  1867. }
  1868. /// <summary>
  1869. /// Save a notecard to prim inventory.
  1870. /// </summary>
  1871. /// <param name="name"></param>
  1872. /// <param name="description">Description of notecard</param>
  1873. /// <param name="notecardData"></param>
  1874. /// <param name="forceSameName">
  1875. /// If true, then if an item exists with the same name, it is replaced.
  1876. /// If false, then a new item is created witha slightly different name (e.g. name 1)
  1877. /// </param>
  1878. /// <returns>Prim inventory item created.</returns>
  1879. protected TaskInventoryItem SaveNotecard(string name, string description, string data, bool forceSameName)
  1880. {
  1881. // Create new asset
  1882. AssetBase asset = new(UUID.Random(), name, (sbyte)AssetType.Notecard, m_host.OwnerID.ToString())
  1883. {
  1884. Description = description
  1885. };
  1886. osUTF8 contents = new(data, 65536);
  1887. int len = contents.Length;
  1888. osUTF8Slice utf = new(len + 128);
  1889. utf.AppendASCII("Linden text version 2\n{\nLLEmbeddedItems version 1\n{\ncount 0\n}\nText length ");
  1890. utf.AppendASCII(len.ToString());
  1891. utf.AppendASCII("\n");
  1892. utf.Append(contents);
  1893. utf.AppendASCII("}");
  1894. asset.Data = utf.ToArray();
  1895. World.AssetService.Store(asset);
  1896. // Create Task Entry
  1897. TaskInventoryItem taskItem = new()
  1898. {
  1899. ParentID = m_host.UUID,
  1900. CreationDate = (uint)Util.UnixTimeSinceEpoch(),
  1901. Name = name,
  1902. Description = description,
  1903. Type = (int)AssetType.Notecard,
  1904. InvType = (int)InventoryType.Notecard,
  1905. OwnerID = m_host.OwnerID,
  1906. CreatorID = m_host.OwnerID,
  1907. BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export,
  1908. CurrentPermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export,
  1909. EveryonePermissions = 0,
  1910. NextPermissions = (uint)PermissionMask.All,
  1911. GroupID = m_host.GroupID,
  1912. GroupPermissions = 0,
  1913. Flags = 0,
  1914. PermsGranter = UUID.Zero,
  1915. PermsMask = 0,
  1916. AssetID = asset.FullID
  1917. };
  1918. taskItem.ResetIDs(m_host.UUID);
  1919. if (forceSameName)
  1920. m_host.Inventory.AddInventoryItemExclusive(taskItem, false);
  1921. else
  1922. m_host.Inventory.AddInventoryItem(taskItem, false);
  1923. m_host.ParentGroup.InvalidateDeepEffectivePerms();
  1924. return taskItem;
  1925. }
  1926. /// <summary>
  1927. /// Load the notecard data found at the given prim inventory item name or asset uuid.
  1928. /// </summary>
  1929. /// <param name="notecardNameOrUuid"></param>
  1930. /// <returns>The text loaded. Null if no notecard was found.</returns>
  1931. protected string LoadNotecard(string notecardNameOrUuid)
  1932. {
  1933. UUID assetID = CacheNotecard(notecardNameOrUuid);
  1934. if (!assetID.IsZero())
  1935. {
  1936. StringBuilder notecardData = new();
  1937. for (int count = 0; count < NotecardCache.GetLines(assetID); count++)
  1938. {
  1939. string line = NotecardCache.GetLine(assetID, count) + "\n";
  1940. // m_log.DebugFormat("[OSSL]: From notecard {0} loading line {1}", notecardNameOrUuid, line);
  1941. notecardData.Append(line);
  1942. }
  1943. return notecardData.ToString();
  1944. }
  1945. return null;
  1946. }
  1947. /// <summary>
  1948. /// Cache a notecard's contents.
  1949. /// </summary>
  1950. /// <param name="notecardNameOrUuid"></param>
  1951. /// <returns>
  1952. /// The asset id of the notecard, which is used for retrieving the cached data.
  1953. /// UUID.Zero if no asset could be found.
  1954. /// </returns>
  1955. protected UUID CacheNotecard(string notecardNameOrUuid)
  1956. {
  1957. if (!UUID.TryParse(notecardNameOrUuid, out UUID assetID))
  1958. {
  1959. assetID = SearchTaskInventoryForAssetId(notecardNameOrUuid);
  1960. }
  1961. if (assetID.IsZero())
  1962. return UUID.Zero;
  1963. if (!NotecardCache.IsCached(assetID))
  1964. {
  1965. AssetBase a = World.AssetService.Get(assetID.ToString());
  1966. if (a == null)
  1967. {
  1968. // Whoops, it's still possible here that the notecard name was properly
  1969. // formatted like a UUID but isn't an asset UUID so lets look it up by name after all
  1970. assetID = SearchTaskInventoryForAssetId(notecardNameOrUuid);
  1971. if (assetID.IsZero())
  1972. return UUID.Zero;
  1973. if (!NotecardCache.IsCached(assetID))
  1974. {
  1975. a = World.AssetService.Get(assetID.ToString());
  1976. if (a == null)
  1977. {
  1978. return UUID.Zero;
  1979. }
  1980. }
  1981. }
  1982. NotecardCache.Cache(assetID, a.Data);
  1983. }
  1984. return assetID;
  1985. }
  1986. protected UUID SearchTaskInventoryForAssetId(string name)
  1987. {
  1988. UUID assetId = UUID.Zero;
  1989. m_host.TaskInventory.LockItemsForRead(true);
  1990. foreach (TaskInventoryItem item in m_host.TaskInventory.Values)
  1991. {
  1992. if (item.Type == 7 && item.Name == name)
  1993. {
  1994. assetId = item.AssetID;
  1995. }
  1996. }
  1997. m_host.TaskInventory.LockItemsForRead(false);
  1998. return assetId;
  1999. }
  2000. /// <summary>
  2001. /// Directly get an entire notecard at once.
  2002. /// </summary>
  2003. /// <remarks>
  2004. /// Instead of using the LSL Dataserver event to pull notecard data
  2005. /// this will simply read the entire notecard and return its data as a string.
  2006. ///
  2007. /// Warning - due to the synchronous method this function uses to fetch assets, its use
  2008. /// may be dangerous and unreliable while running in grid mode.
  2009. /// </remarks>
  2010. /// <param name="name">Name of the notecard or its asset id</param>
  2011. /// <param name="line">The line number to read. The first line is line 0</param>
  2012. /// <returns>Notecard line</returns>
  2013. public string osGetNotecardLine(string name, int line)
  2014. {
  2015. CheckThreatLevel(ThreatLevel.VeryHigh, "osGetNotecardLine");
  2016. UUID assetID = CacheNotecard(name);
  2017. if (assetID.IsZero())
  2018. {
  2019. OSSLShoutError("Notecard '" + name + "' could not be found.");
  2020. return "ERROR!";
  2021. }
  2022. return NotecardCache.GetLine(assetID, line);
  2023. }
  2024. /// <summary>
  2025. /// Get an entire notecard at once.
  2026. /// </summary>
  2027. /// <remarks>
  2028. /// Instead of using the LSL Dataserver event to pull notecard data line by line,
  2029. /// this will simply read the entire notecard and return its data as a string.
  2030. ///
  2031. /// Warning - due to the synchronous method this function uses to fetch assets, its use
  2032. /// may be dangerous and unreliable while running in grid mode.
  2033. /// </remarks>
  2034. /// <param name="name">Name of the notecard or its asset id</param>
  2035. /// <returns>Notecard text</returns>
  2036. public string osGetNotecard(string name)
  2037. {
  2038. CheckThreatLevel(ThreatLevel.VeryHigh, "osGetNotecard");
  2039. string text = LoadNotecard(name);
  2040. if (text == null)
  2041. {
  2042. OSSLShoutError("Notecard '" + name + "' could not be found.");
  2043. return "ERROR!";
  2044. }
  2045. else
  2046. {
  2047. return text;
  2048. }
  2049. }
  2050. /// <summary>
  2051. /// Get the number of lines in the given notecard.
  2052. /// </summary>
  2053. /// <remarks>
  2054. /// Instead of using the LSL Dataserver event to pull notecard data,
  2055. /// this will simply read the number of note card lines and return this data as an integer.
  2056. ///
  2057. /// Warning - due to the synchronous method this function uses to fetch assets, its use
  2058. /// may be dangerous and unreliable while running in grid mode.
  2059. /// </remarks>
  2060. /// <param name="name">Name of the notecard or its asset id</param>
  2061. /// <returns></returns>
  2062. public int osGetNumberOfNotecardLines(string name)
  2063. {
  2064. CheckThreatLevel(ThreatLevel.VeryHigh, "osGetNumberOfNotecardLines");
  2065. UUID assetID = CacheNotecard(name);
  2066. if (assetID.IsZero())
  2067. {
  2068. OSSLShoutError("Notecard '" + name + "' could not be found.");
  2069. return -1;
  2070. }
  2071. return NotecardCache.GetLines(assetID);
  2072. }
  2073. public string osAvatarName2Key(string firstname, string lastname)
  2074. {
  2075. CheckThreatLevel(ThreatLevel.Low, "osAvatarName2Key");
  2076. ScenePresence sp = World.GetScenePresence(firstname, lastname);
  2077. if(sp is not null)
  2078. return sp.UUID.ToString();
  2079. IUserManagement userManager = World.RequestModuleInterface<IUserManagement>();
  2080. if (userManager is null)
  2081. {
  2082. OSSLShoutError("osAvatarName2Key: UserManagement module not available");
  2083. return string.Empty;
  2084. }
  2085. // Check local grid
  2086. UUID userID = userManager.GetUserIdByName(firstname, lastname);
  2087. if (!userID.IsZero())
  2088. return userID.ToString();
  2089. // HG ?
  2090. if (Util.ParseForeignAvatarName(firstname, lastname, out string realFirstName, out string realLastName, out string serverURI))
  2091. {
  2092. try
  2093. {
  2094. UserAgentServiceConnector userConnection = new(serverURI);
  2095. if (userConnection is not null)
  2096. {
  2097. userID = userConnection.GetUUID(realFirstName, realLastName);
  2098. if (!userID.IsZero())
  2099. {
  2100. userManager.AddUser(userID, realFirstName, realLastName, serverURI);
  2101. return userID.ToString();
  2102. }
  2103. }
  2104. }
  2105. catch (Exception /*e*/)
  2106. {
  2107. // m_log.Warn("[osAvatarName2Key] UserAgentServiceConnector - Unable to connect to destination grid ", e);
  2108. }
  2109. }
  2110. return ScriptBaseClass.NULL_KEY;
  2111. }
  2112. public string osKey2Name(string id)
  2113. {
  2114. CheckThreatLevel(ThreatLevel.Low, "osKey2Name");
  2115. if (UUID.TryParse(id, out UUID key))
  2116. {
  2117. ScenePresence sp = World.GetScenePresence(key);
  2118. if(sp is not null)
  2119. return sp.Name;
  2120. UserAccount account = World.UserAccountService.GetUserAccount(World.RegionInfo.ScopeID, key);
  2121. if (account is not null)
  2122. return account.Name;
  2123. if (m_ScriptEngine.World.GridUserService is not null)
  2124. {
  2125. GridUserInfo uInfo = m_ScriptEngine.World.GridUserService.GetGridUserInfo(key.ToString());
  2126. if (uInfo is not null)
  2127. {
  2128. if (Util.ParseFullUniversalUserIdentifier(uInfo.UserID, out _,
  2129. out string gridURL, out string firstName, out string lastName))
  2130. {
  2131. string grid = new Uri(gridURL).Authority;
  2132. return firstName + "." + lastName + " @" + grid;
  2133. }
  2134. }
  2135. }
  2136. }
  2137. return "";
  2138. }
  2139. private enum InfoType
  2140. {
  2141. Nick,
  2142. Name,
  2143. Login,
  2144. Home,
  2145. Custom
  2146. };
  2147. private string GridUserInfo(InfoType type)
  2148. {
  2149. return GridUserInfo(type, "");
  2150. }
  2151. private string GridUserInfo(InfoType type, string key)
  2152. {
  2153. IConfigSource config = m_ScriptEngine.ConfigSource;
  2154. string url = null;
  2155. IConfig gridInfoConfig = config.Configs["GridInfo"];
  2156. if (gridInfoConfig is not null)
  2157. url = gridInfoConfig.GetString("GridInfoURI", String.Empty);
  2158. if (string.IsNullOrEmpty(url))
  2159. return "Configuration Error!";
  2160. string verb ="/json_grid_info";
  2161. OSDMap info = WebUtil.GetFromService($"{url}{verb}", 3000);
  2162. if (info["Success"].AsBoolean() != true)
  2163. return "Get GridInfo Failed!";
  2164. OSDMap json = (OSDMap)OSDParser.DeserializeJson(info["_RawResult"].AsString());
  2165. return type switch
  2166. {
  2167. InfoType.Nick => (string)json["gridnick"],
  2168. InfoType.Name => (string)json["gridname"],
  2169. InfoType.Login => (string)json["login"],
  2170. InfoType.Home => (string)json["home"],
  2171. InfoType.Custom => (string)json[key],
  2172. _ => "error",
  2173. };
  2174. }
  2175. public string osSHA256(string input)
  2176. {
  2177. byte[] bytes;
  2178. // Create a SHA256
  2179. using (SHA256 sha256Hash = SHA256.Create())
  2180. {
  2181. // ComputeHash - returns byte array
  2182. bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
  2183. }
  2184. return Util.bytesToLowcaseHexString(bytes);
  2185. }
  2186. /// <summary>
  2187. /// Get the nickname of this grid, as set in the [GridInfo] config section.
  2188. /// </summary>
  2189. /// <remarks>
  2190. /// </remarks>
  2191. /// <returns></returns>
  2192. public string osGetGridNick()
  2193. {
  2194. return World.SceneGridInfo == null ? string.Empty : World.SceneGridInfo.GridNick;
  2195. }
  2196. public string osGetGridName()
  2197. {
  2198. return World.SceneGridInfo == null ? string.Empty : World.SceneGridInfo.GridName;
  2199. }
  2200. public string osGetGridLoginURI()
  2201. {
  2202. CheckThreatLevel(ThreatLevel.Moderate, "osGetGridLoginURI");
  2203. string loginURI = string.Empty;
  2204. IConfigSource config = m_ScriptEngine.ConfigSource;
  2205. if (config.Configs[GridInfoServiceConfigSectionName] != null)
  2206. loginURI = config.Configs[GridInfoServiceConfigSectionName].GetString("login", loginURI);
  2207. if (string.IsNullOrEmpty(loginURI))
  2208. loginURI = GridUserInfo(InfoType.Login);
  2209. return loginURI;
  2210. }
  2211. public string osGetGridHomeURI()
  2212. {
  2213. CheckThreatLevel(ThreatLevel.Moderate, "osGetGridHomeURI");
  2214. return World.SceneGridInfo == null ? string.Empty : World.SceneGridInfo.HomeURLNoEndSlash;
  2215. }
  2216. public string osGetGridGatekeeperURI()
  2217. {
  2218. CheckThreatLevel(ThreatLevel.Moderate, "osGetGridGatekeeperURI");
  2219. return World.SceneGridInfo == null ? string.Empty : World.SceneGridInfo.GateKeeperURLNoEndSlash;
  2220. }
  2221. public string osGetGridCustom(string key)
  2222. {
  2223. CheckThreatLevel(ThreatLevel.Moderate, "osGetGridCustom");
  2224. string retval = string.Empty;
  2225. IConfigSource config = m_ScriptEngine.ConfigSource;
  2226. if (config.Configs[GridInfoServiceConfigSectionName] != null)
  2227. retval = config.Configs[GridInfoServiceConfigSectionName].GetString(key, retval);
  2228. if (string.IsNullOrEmpty(retval))
  2229. retval = GridUserInfo(InfoType.Custom, key);
  2230. return retval;
  2231. }
  2232. public string osGetAvatarHomeURI(string uuid)
  2233. {
  2234. CheckThreatLevel(ThreatLevel.Low, "osGetAvatarHomeURI");
  2235. IUserManagement userManager = m_ScriptEngine.World.RequestModuleInterface<IUserManagement>();
  2236. string returnValue;
  2237. if (userManager is null)
  2238. returnValue = string.Empty;
  2239. else
  2240. returnValue = userManager.GetUserServerURL(new UUID(uuid), "HomeURI");
  2241. if (returnValue.Length == 0)
  2242. return World.SceneGridInfo.HomeURLNoEndSlash;
  2243. return returnValue;
  2244. }
  2245. public LSL_String osFormatString(string str, LSL_List strings)
  2246. {
  2247. CheckThreatLevel(ThreatLevel.VeryLow, "osFormatString");
  2248. return string.Format(str, strings.Data);
  2249. }
  2250. public LSL_List osMatchString(string src, string pattern, int start)
  2251. {
  2252. CheckThreatLevel(ThreatLevel.VeryLow, "osMatchString");
  2253. LSL_List result = new();
  2254. // Normalize indices (if negative).
  2255. // After normlaization they may still be
  2256. // negative, but that is now relative to
  2257. // the start, rather than the end, of the
  2258. // sequence.
  2259. if (start < 0)
  2260. {
  2261. start = src.Length + start;
  2262. }
  2263. if (start < 0 || start >= src.Length)
  2264. {
  2265. return result; // empty list
  2266. }
  2267. // Find matches beginning at start position
  2268. Regex matcher = new(pattern);
  2269. Match match = matcher.Match(src, start);
  2270. while (match.Success)
  2271. {
  2272. foreach (System.Text.RegularExpressions.Group g in match.Groups)
  2273. {
  2274. if (g.Success)
  2275. {
  2276. result.Add(new LSL_String(g.Value));
  2277. result.Add(new LSL_Integer(g.Index));
  2278. }
  2279. }
  2280. match = match.NextMatch();
  2281. }
  2282. return result;
  2283. }
  2284. public LSL_String osReplaceString(string src, string pattern, string replace, int count, int start)
  2285. {
  2286. CheckThreatLevel(ThreatLevel.VeryLow, "osReplaceString");
  2287. // Normalize indices (if negative).
  2288. // After normalization they may still be
  2289. // negative, but that is now relative to
  2290. // the start, rather than the end, of the
  2291. // sequence.
  2292. if (start < 0)
  2293. {
  2294. start = src.Length + start;
  2295. }
  2296. if (start < 0 || start >= src.Length)
  2297. {
  2298. return src;
  2299. }
  2300. // Find matches beginning at start position
  2301. Regex matcher = new(pattern);
  2302. return matcher.Replace(src,replace,count,start);
  2303. }
  2304. public string osLoadedCreationDate()
  2305. {
  2306. CheckThreatLevel(ThreatLevel.Low, "osLoadedCreationDate");
  2307. return World.RegionInfo.RegionSettings.LoadedCreationDate;
  2308. }
  2309. public string osLoadedCreationTime()
  2310. {
  2311. CheckThreatLevel(ThreatLevel.Low, "osLoadedCreationTime");
  2312. return World.RegionInfo.RegionSettings.LoadedCreationTime;
  2313. }
  2314. public string osLoadedCreationID()
  2315. {
  2316. CheckThreatLevel(ThreatLevel.Low, "osLoadedCreationID");
  2317. return World.RegionInfo.RegionSettings.LoadedCreationID;
  2318. }
  2319. /// <summary>
  2320. /// Get the primitive parameters of a linked prim.
  2321. /// </summary>
  2322. /// <remarks>
  2323. /// Threat level is 'Low' because certain users could possibly be tricked into
  2324. /// dropping an unverified script into one of their own objects, which could
  2325. /// then gather the physical construction details of the object and transmit it
  2326. /// to an unscrupulous third party, thus permitting unauthorized duplication of
  2327. /// the object's form.
  2328. /// </remarks>
  2329. /// <param name="linknumber"></param>
  2330. /// <param name="rules"></param>
  2331. /// <returns></returns>
  2332. public LSL_List osGetLinkPrimitiveParams(int linknumber, LSL_List rules)
  2333. {
  2334. CheckThreatLevel(ThreatLevel.High, "osGetLinkPrimitiveParams");
  2335. InitLSL();
  2336. // One needs to cast m_LSL_Api because we're using functions not
  2337. // on the ILSL_Api interface.
  2338. LSL_List retVal = new();
  2339. LSL_List remaining = new();
  2340. List<SceneObjectPart> parts = m_LSL_Api.GetLinkParts(linknumber);
  2341. foreach (SceneObjectPart part in parts)
  2342. {
  2343. remaining = m_LSL_Api.GetPrimParams(part, rules, ref retVal);
  2344. }
  2345. while (remaining.Length > 1)
  2346. {
  2347. linknumber = remaining.GetIntegerItem(0);
  2348. parts = m_LSL_Api.GetLinkParts(linknumber);
  2349. if(parts.Count == 0)
  2350. break;
  2351. rules = remaining.GetSublist(1, -1);
  2352. foreach (SceneObjectPart part in parts)
  2353. remaining = m_LSL_Api.GetPrimParams(part, rules, ref retVal);
  2354. }
  2355. return retVal;
  2356. }
  2357. public void osForceCreateLink(string target, int parent)
  2358. {
  2359. CheckThreatLevel(ThreatLevel.VeryLow, "osForceCreateLink");
  2360. InitLSL();
  2361. m_LSL_Api.CreateLink(target, parent);
  2362. }
  2363. public void osForceBreakLink(int linknum)
  2364. {
  2365. CheckThreatLevel(ThreatLevel.VeryLow, "osForceBreakLink");
  2366. InitLSL();
  2367. m_LSL_Api.BreakLink(linknum);
  2368. }
  2369. public void osForceBreakAllLinks()
  2370. {
  2371. CheckThreatLevel(ThreatLevel.VeryLow, "osForceBreakAllLinks");
  2372. InitLSL();
  2373. m_LSL_Api.BreakAllLinks();
  2374. }
  2375. public LSL_Integer osIsNpc(LSL_Key npc)
  2376. {
  2377. CheckThreatLevel();
  2378. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2379. if (module is not null)
  2380. {
  2381. if (UUID.TryParse(npc.m_string, out UUID npcId))
  2382. if (module.IsNPC(npcId, World))
  2383. return ScriptBaseClass.TRUE;
  2384. }
  2385. return ScriptBaseClass.FALSE;
  2386. }
  2387. public LSL_Key osNpcCreate(string firstname, string lastname, LSL_Vector position, string notecard)
  2388. {
  2389. CheckThreatLevel(ThreatLevel.High, "osNpcCreate");
  2390. // have to get the npc module also here to set the default Not Owned
  2391. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2392. if(module is null)
  2393. return LSL_Key.NullKey;
  2394. bool owned = (module.NPCOptionFlags & NPCOptionsFlags.AllowNotOwned) == 0;
  2395. return NpcCreate(firstname, lastname, position, notecard, owned, false, false);
  2396. }
  2397. public LSL_Key osNpcCreate(string firstname, string lastname, LSL_Vector position, string notecard, int options)
  2398. {
  2399. CheckThreatLevel(ThreatLevel.High, "osNpcCreate");
  2400. return NpcCreate(
  2401. firstname, lastname, position, notecard,
  2402. (options & ScriptBaseClass.OS_NPC_NOT_OWNED) == 0,
  2403. (options & ScriptBaseClass.OS_NPC_SENSE_AS_AGENT) != 0,
  2404. (options & ScriptBaseClass.OS_NPC_OBJECT_GROUP) != 0);
  2405. }
  2406. private LSL_Key NpcCreate(
  2407. string firstname, string lastname, LSL_Vector position, string notecard, bool owned, bool senseAsAgent, bool hostGroupID)
  2408. {
  2409. if (!World.Permissions.CanRezObject(1, m_host.OwnerID, new Vector3((float)position.x, (float)position.y, (float)position.z)))
  2410. {
  2411. OSSLError("no permission to rez NPC at requested location");
  2412. return LSL_Key.NullKey;
  2413. }
  2414. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2415. if(module is null)
  2416. {
  2417. OSSLError("NPC module not enabled");
  2418. return LSL_Key.NullKey;
  2419. }
  2420. string groupTitle = String.Empty;
  2421. UUID groupID = UUID.Zero;
  2422. AvatarAppearance appearance = null;
  2423. // check creation options
  2424. NPCOptionsFlags createFlags = module.NPCOptionFlags;
  2425. if((createFlags & NPCOptionsFlags.AllowNotOwned) == 0 && !owned)
  2426. {
  2427. OSSLError("Not owned NPCs disabled");
  2428. owned = true; // we should get here...
  2429. }
  2430. if((createFlags & NPCOptionsFlags.AllowSenseAsAvatar) == 0 && senseAsAgent)
  2431. {
  2432. OSSLError("NPC allow sense as Avatar disabled");
  2433. senseAsAgent = false;
  2434. }
  2435. if(hostGroupID && !m_host.GroupID.IsZero())
  2436. {
  2437. if (m_groupsModule != null)
  2438. {
  2439. GroupMembershipData member = m_groupsModule.GetMembershipData(m_host.GroupID, m_host.OwnerID);
  2440. if (member == null)
  2441. {
  2442. OSSLError(string.Format("osNpcCreate: the object owner is not member of the object group"));
  2443. return LSL_Key.NullKey;
  2444. }
  2445. groupID = m_host.GroupID;
  2446. if((createFlags & NPCOptionsFlags.NoNPCGroup) != 0)
  2447. {
  2448. GroupRecord grprec = m_groupsModule.GetGroupRecord(m_host.GroupID);
  2449. if(grprec != null && grprec.GroupName != "")
  2450. groupTitle = grprec.GroupName;
  2451. }
  2452. }
  2453. }
  2454. if((createFlags & NPCOptionsFlags.NoNPCGroup) == 0)
  2455. {
  2456. if (!string.IsNullOrEmpty(firstname) || !string.IsNullOrEmpty(lastname))
  2457. {
  2458. if (firstname != "Shown outfit:")
  2459. groupTitle = "- NPC -";
  2460. }
  2461. }
  2462. if((createFlags & NPCOptionsFlags.AllowCloneOtherAvatars) != 0)
  2463. {
  2464. if (UUID.TryParse(notecard, out UUID id))
  2465. {
  2466. ScenePresence clonePresence = World.GetScenePresence(id);
  2467. if (clonePresence != null)
  2468. appearance = clonePresence.Appearance;
  2469. }
  2470. }
  2471. if (appearance is null)
  2472. {
  2473. if(!string.IsNullOrWhiteSpace(notecard))
  2474. {
  2475. string appearanceSerialized = LoadNotecard(notecard);
  2476. if (appearanceSerialized is null)
  2477. {
  2478. OSSLError(string.Format("osNpcCreate: Notecard '{0}' not found.", notecard));
  2479. return LSL_Key.NullKey;
  2480. }
  2481. try
  2482. {
  2483. OSDMap appearanceOsd = (OSDMap)OSDParser.DeserializeLLSDXml(appearanceSerialized);
  2484. appearance = new AvatarAppearance();
  2485. appearance.Unpack(appearanceOsd);
  2486. }
  2487. catch
  2488. {
  2489. OSSLError(string.Format("osNpcCreate: Error processing notecard '{0}'", notecard));
  2490. return LSL_Key.NullKey;
  2491. }
  2492. }
  2493. }
  2494. UUID x = module.CreateNPC(firstname,
  2495. lastname,
  2496. position,
  2497. UUID.Random(),
  2498. owned ? m_host.OwnerID : UUID.Zero,
  2499. groupTitle,
  2500. groupID,
  2501. senseAsAgent,
  2502. World,
  2503. appearance);
  2504. if (World.TryGetScenePresence(x, out ScenePresence sp))
  2505. {
  2506. sp.SendAvatarDataToAllAgents();
  2507. }
  2508. return new LSL_Key(x.ToString());
  2509. }
  2510. /// <summary>
  2511. /// Save the current appearance of the NPC permanently to the named notecard.
  2512. /// </summary>
  2513. /// <param name="avatar"></param>
  2514. /// <param name="notecard">The name of the notecard to which to save the appearance.</param>
  2515. /// <returns>The asset ID of the notecard saved.</returns>
  2516. public LSL_Key osNpcSaveAppearance(LSL_Key npc, LSL_String notecard)
  2517. {
  2518. return NpcSaveAppearance(npc, notecard, false);
  2519. }
  2520. public LSL_Key osNpcSaveAppearance(LSL_Key npc, LSL_String notecard, LSL_Integer includeHuds)
  2521. {
  2522. return NpcSaveAppearance(npc, notecard, includeHuds == 0);
  2523. }
  2524. protected LSL_Key NpcSaveAppearance(LSL_Key npc, string notecard, bool NoHUds)
  2525. {
  2526. CheckThreatLevel(ThreatLevel.High, "osNpcSaveAppearance");
  2527. INPCModule npcModule = World.RequestModuleInterface<INPCModule>();
  2528. if (npcModule is not null)
  2529. {
  2530. if (!UUID.TryParse(npc.m_string, out UUID npcId))
  2531. return LSL_Key.NullKey;
  2532. if (!npcModule.CheckPermissions(npcId, m_host.OwnerID))
  2533. return LSL_Key.NullKey;
  2534. return SaveAppearanceToNotecard(npcId, notecard, NoHUds);
  2535. }
  2536. return LSL_Key.NullKey;
  2537. }
  2538. public void osNpcLoadAppearance(LSL_Key npc, string notecard)
  2539. {
  2540. CheckThreatLevel(ThreatLevel.High, "osNpcLoadAppearance");
  2541. INPCModule npcModule = World.RequestModuleInterface<INPCModule>();
  2542. if (npcModule is not null)
  2543. {
  2544. if (!UUID.TryParse(npc.m_string, out UUID npcId))
  2545. return;
  2546. if (!npcModule.CheckPermissions(npcId, m_host.OwnerID))
  2547. return;
  2548. string appearanceSerialized = LoadNotecard(notecard);
  2549. if (appearanceSerialized is null)
  2550. OSSLError(string.Format("osNpcCreate: Notecard reference '{0}' not found.", notecard));
  2551. OSDMap appearanceOsd = (OSDMap)OSDParser.DeserializeLLSDXml(appearanceSerialized);
  2552. // OSD a = OSDParser.DeserializeLLSDXml(appearanceSerialized);
  2553. // Console.WriteLine("appearanceSerialized {0}", appearanceSerialized);
  2554. // Console.WriteLine("a.Type {0}, a.ToString() {1}", a.Type, a);
  2555. AvatarAppearance appearance = new();
  2556. appearance.Unpack(appearanceOsd);
  2557. npcModule.SetNPCAppearance(npcId, appearance, m_host.ParentGroup.Scene);
  2558. }
  2559. }
  2560. public LSL_Key osNpcGetOwner(LSL_Key npc)
  2561. {
  2562. CheckThreatLevel(ThreatLevel.None, "osNpcGetOwner");
  2563. INPCModule npcModule = World.RequestModuleInterface<INPCModule>();
  2564. if (npcModule is not null)
  2565. {
  2566. if (UUID.TryParse(npc.m_string, out UUID npcId))
  2567. {
  2568. UUID owner = npcModule.GetOwner(npcId);
  2569. if (!owner.IsZero())
  2570. return new LSL_Key(owner.ToString());
  2571. else
  2572. return npc;
  2573. }
  2574. }
  2575. return LSL_Key.NullKey;
  2576. }
  2577. public LSL_Vector osNpcGetPos(LSL_Key npc)
  2578. {
  2579. CheckThreatLevel(ThreatLevel.High, "osNpcGetPos");
  2580. INPCModule npcModule = World.RequestModuleInterface<INPCModule>();
  2581. if (npcModule is not null)
  2582. {
  2583. if (!UUID.TryParse(npc.m_string, out UUID npcId))
  2584. return LSL_Vector.Zero;
  2585. if (!npcModule.CheckPermissions(npcId, m_host.OwnerID))
  2586. return LSL_Vector.Zero;
  2587. ScenePresence sp = World.GetScenePresence(npcId);
  2588. if (sp is not null)
  2589. return new LSL_Vector(sp.AbsolutePosition);
  2590. }
  2591. return LSL_Vector.Zero;
  2592. }
  2593. public void osNpcMoveTo(LSL_Key npc, LSL_Vector pos)
  2594. {
  2595. CheckThreatLevel(ThreatLevel.High, "osNpcMoveTo");
  2596. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2597. if (module is not null)
  2598. {
  2599. if (!UUID.TryParse(npc.m_string, out UUID npcId))
  2600. return;
  2601. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2602. return;
  2603. module.MoveToTarget(npcId, World, pos, false, true, false);
  2604. }
  2605. }
  2606. public void osNpcMoveToTarget(LSL_Key npc, LSL_Vector target, int options)
  2607. {
  2608. CheckThreatLevel(ThreatLevel.High, "osNpcMoveToTarget");
  2609. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2610. if (module is not null)
  2611. {
  2612. if (!UUID.TryParse(npc.m_string, out UUID npcId))
  2613. return;
  2614. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2615. return;
  2616. module.MoveToTarget(
  2617. new UUID(npc.m_string),
  2618. World,
  2619. target,
  2620. (options & ScriptBaseClass.OS_NPC_NO_FLY) != 0,
  2621. (options & ScriptBaseClass.OS_NPC_LAND_AT_TARGET) != 0,
  2622. (options & ScriptBaseClass.OS_NPC_RUNNING) != 0);
  2623. }
  2624. }
  2625. public LSL_Rotation osNpcGetRot(LSL_Key npc)
  2626. {
  2627. CheckThreatLevel(ThreatLevel.High, "osNpcGetRot");
  2628. INPCModule npcModule = World.RequestModuleInterface<INPCModule>();
  2629. if (npcModule is not null)
  2630. {
  2631. if (!UUID.TryParse(npc.m_string, out UUID npcId))
  2632. return LSL_Rotation.Identity;
  2633. if (!npcModule.CheckPermissions(npcId, m_host.OwnerID))
  2634. return LSL_Rotation.Identity;
  2635. ScenePresence sp = World.GetScenePresence(npcId);
  2636. if (sp is not null)
  2637. return new LSL_Rotation(sp.GetWorldRotation());
  2638. }
  2639. return LSL_Rotation.Identity;
  2640. }
  2641. public void osNpcSetRot(LSL_Key npc, LSL_Rotation rotation)
  2642. {
  2643. CheckThreatLevel(ThreatLevel.High, "osNpcSetRot");
  2644. INPCModule npcModule = World.RequestModuleInterface<INPCModule>();
  2645. if (npcModule is not null)
  2646. {
  2647. if (!UUID.TryParse(npc.m_string, out UUID npcId))
  2648. return;
  2649. if (!npcModule.CheckPermissions(npcId, m_host.OwnerID))
  2650. return;
  2651. ScenePresence sp = World.GetScenePresence(npcId);
  2652. if (sp is not null)
  2653. sp.Rotation = rotation;
  2654. }
  2655. }
  2656. public void osNpcStopMoveToTarget(LSL_Key npc)
  2657. {
  2658. CheckThreatLevel(ThreatLevel.High, "osNpcStopMoveToTarget");
  2659. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2660. if (module is not null)
  2661. {
  2662. UUID npcId = new(npc.m_string);
  2663. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2664. return;
  2665. module.StopMoveToTarget(npcId, World);
  2666. }
  2667. }
  2668. public void osNpcSetProfileAbout(LSL_Key npc, string about)
  2669. {
  2670. CheckThreatLevel(ThreatLevel.Low, "osNpcSetProfileAbout");
  2671. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2672. if (module is not null)
  2673. {
  2674. UUID npcId = new(npc.m_string);
  2675. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2676. return;
  2677. ScenePresence sp = World.GetScenePresence(npcId);
  2678. if (sp is not null)
  2679. ((INPC)(sp.ControllingClient)).profileAbout = about;
  2680. }
  2681. }
  2682. public void osNpcSetProfileImage(LSL_Key npc, string image)
  2683. {
  2684. CheckThreatLevel(ThreatLevel.Low, "osNpcSetProfileImage");
  2685. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2686. if (module is not null)
  2687. {
  2688. UUID npcId = new(npc.m_string);
  2689. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2690. return;
  2691. UUID ImageID = ScriptUtils.GetAssetIdFromItemName(m_host, image, (int)AssetType.Texture);
  2692. if (ImageID.IsZero())
  2693. {
  2694. if (!UUID.TryParse(image, out ImageID))
  2695. return;
  2696. }
  2697. ScenePresence sp = World.GetScenePresence(npcId);
  2698. if (sp is not null)
  2699. ((INPC)(sp.ControllingClient)).profileImage = ImageID;
  2700. }
  2701. }
  2702. public void osNpcSay(LSL_Key npc, string message)
  2703. {
  2704. osNpcSay(npc, 0, message);
  2705. }
  2706. public void osNpcSay(LSL_Key npc, int channel, string message)
  2707. {
  2708. CheckThreatLevel(ThreatLevel.High, "osNpcSay");
  2709. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2710. if (module is not null)
  2711. {
  2712. UUID npcId = new(npc.m_string);
  2713. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2714. return;
  2715. InitLSL();
  2716. m_LSL_Api.ThrottleSay(channel, 2000);
  2717. module.Say(npcId, World, message, channel);
  2718. }
  2719. }
  2720. public void osNpcSayTo(LSL_Key npc, LSL_Key target, int channel, string msg)
  2721. {
  2722. CheckThreatLevel(ThreatLevel.High, "osNpcSayTo");
  2723. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2724. if (module is null)
  2725. return;
  2726. IWorldComm wComm = m_ScriptEngine.World.RequestModuleInterface<IWorldComm>();
  2727. if (wComm is null)
  2728. return;
  2729. if (!UUID.TryParse(npc.m_string, out UUID npcId))
  2730. return;
  2731. if (!UUID.TryParse(target.m_string, out UUID TargetID))
  2732. return;
  2733. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2734. return;
  2735. ScenePresence NPCpresence = World.GetScenePresence(npcId);
  2736. if (NPCpresence is null || NPCpresence.IsDeleted || !NPCpresence.IsNPC)
  2737. return;
  2738. Vector3 npcPOS = NPCpresence.AbsolutePosition;
  2739. string npcNAME = NPCpresence.Name;
  2740. InitLSL();
  2741. m_LSL_Api.ThrottleSay(channel, 2000);
  2742. wComm.DeliverMessageTo(TargetID, channel, npcPOS, npcNAME, npcId, msg);
  2743. }
  2744. public void osNpcShout(LSL_Key npc, int channel, string message)
  2745. {
  2746. CheckThreatLevel(ThreatLevel.High, "osNpcShout");
  2747. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2748. if (module is not null)
  2749. {
  2750. UUID npcId = new(npc.m_string);
  2751. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2752. return;
  2753. InitLSL();
  2754. m_LSL_Api.ThrottleSay(channel, 2000);
  2755. module.Shout(npcId, World, message, channel);
  2756. }
  2757. }
  2758. public void osNpcSit(LSL_Key npc, LSL_Key target, int options)
  2759. {
  2760. CheckThreatLevel(ThreatLevel.High, "osNpcSit");
  2761. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2762. if (module is not null)
  2763. {
  2764. UUID npcId = new(npc.m_string);
  2765. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2766. return;
  2767. module.Sit(npcId, new UUID(target.m_string), World);
  2768. }
  2769. }
  2770. public void osNpcStand(LSL_Key npc)
  2771. {
  2772. CheckThreatLevel(ThreatLevel.High, "osNpcStand");
  2773. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2774. if (module is not null)
  2775. {
  2776. UUID npcId = new(npc.m_string);
  2777. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2778. return;
  2779. module.Stand(npcId, World);
  2780. }
  2781. }
  2782. public void osNpcRemove(LSL_Key npc)
  2783. {
  2784. CheckThreatLevel(ThreatLevel.High, "osNpcRemove");
  2785. try
  2786. {
  2787. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2788. if (module is not null)
  2789. {
  2790. UUID npcId = new(npc.m_string);
  2791. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2792. return;
  2793. module.DeleteNPC(npcId, World);
  2794. }
  2795. }
  2796. catch { }
  2797. }
  2798. public void osNpcPlayAnimation(LSL_Key npc, string animation)
  2799. {
  2800. CheckThreatLevel(ThreatLevel.High, "osNpcPlayAnimation");
  2801. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2802. if (module is null)
  2803. return;
  2804. if (!UUID.TryParse(npc.m_string, out UUID npcID))
  2805. return;
  2806. ScenePresence target = World.GetScenePresence(npcID);
  2807. if (target is null || !target.IsNPC)
  2808. return;
  2809. if (!module.CheckPermissions(npcID, m_host.OwnerID))
  2810. return;
  2811. UUID animID = UUID.Zero;
  2812. m_host.TaskInventory.LockItemsForRead(true);
  2813. foreach (KeyValuePair<UUID, TaskInventoryItem> inv in m_host.TaskInventory)
  2814. {
  2815. if (inv.Value.Type == (int)AssetType.Animation)
  2816. {
  2817. if (inv.Value.Name == animation)
  2818. {
  2819. animID = inv.Value.AssetID;
  2820. break;
  2821. }
  2822. }
  2823. }
  2824. m_host.TaskInventory.LockItemsForRead(false);
  2825. if (animID.IsZero())
  2826. target.Animator.AddAnimation(animation, m_host.UUID);
  2827. else
  2828. target.Animator.AddAnimation(animID, m_host.UUID);
  2829. }
  2830. public void osNpcStopAnimation(LSL_Key npc, string animation)
  2831. {
  2832. CheckThreatLevel(ThreatLevel.High, "osNpcStopAnimation");
  2833. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2834. if (module is null)
  2835. return;
  2836. if (!UUID.TryParse(npc.m_string, out UUID npcID))
  2837. return;
  2838. ScenePresence target = World.GetScenePresence(npcID);
  2839. if (target is null || !target.IsNPC)
  2840. return;
  2841. if (!module.CheckPermissions(npcID, m_host.OwnerID))
  2842. return;
  2843. if (!UUID.TryParse(animation, out UUID animID))
  2844. {
  2845. TaskInventoryItem item = m_host.Inventory.GetInventoryItem(animation);
  2846. if (item is not null && item.Type == (int)AssetType.Animation)
  2847. animID = item.AssetID;
  2848. else
  2849. animID = UUID.Zero;
  2850. }
  2851. if (animID.IsZero())
  2852. target.Animator.RemoveAnimation(animation);
  2853. else
  2854. target.Animator.RemoveAnimation(animID, true);
  2855. }
  2856. public void osNpcWhisper(LSL_Key npc, int channel, string message)
  2857. {
  2858. CheckThreatLevel(ThreatLevel.High, "osNpcWhisper");
  2859. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2860. if (module is not null)
  2861. {
  2862. UUID npcId = new(npc.m_string);
  2863. if (!module.CheckPermissions(npcId, m_host.OwnerID))
  2864. return;
  2865. module.Whisper(npcId, World, message, channel);
  2866. }
  2867. }
  2868. public void osNpcTouch(LSL_Key npcLSL_Key, LSL_Key object_key, LSL_Integer link_num)
  2869. {
  2870. CheckThreatLevel(ThreatLevel.High, "osNpcTouch");
  2871. INPCModule module = World.RequestModuleInterface<INPCModule>();
  2872. int linkNum = link_num.value;
  2873. if (module is not null || (linkNum < 0 && linkNum != ScriptBaseClass.LINK_THIS))
  2874. {
  2875. if (!UUID.TryParse(npcLSL_Key, out UUID npcId) || !module.CheckPermissions(npcId, m_host.OwnerID))
  2876. return;
  2877. SceneObjectPart part = null;
  2878. if (UUID.TryParse(object_key.m_string, out UUID objectId))
  2879. part = World.GetSceneObjectPart(objectId);
  2880. if (part is null)
  2881. return;
  2882. if (linkNum != ScriptBaseClass.LINK_THIS)
  2883. {
  2884. if (linkNum == 0 || linkNum == ScriptBaseClass.LINK_ROOT)
  2885. { // 0 and 1 are treated as root, find the root if the current part isnt it
  2886. part = part.ParentGroup.RootPart;
  2887. }
  2888. else
  2889. { // Find the prim with the given link number if not found then fail silently
  2890. part = part.ParentGroup.GetLinkNumPart(linkNum);
  2891. }
  2892. }
  2893. if (part is null)
  2894. return;
  2895. module.Touch(npcId, part.UUID);
  2896. }
  2897. }
  2898. /// <summary>
  2899. /// Save the current appearance of the script owner permanently to the named notecard.
  2900. /// </summary>
  2901. /// <param name="notecard">The name of the notecard to which to save the appearance.</param>
  2902. /// <returns>The asset ID of the notecard saved.</returns>
  2903. public LSL_Key osOwnerSaveAppearance(LSL_String notecard)
  2904. {
  2905. CheckThreatLevel(ThreatLevel.High, "osOwnerSaveAppearance");
  2906. return SaveAppearanceToNotecard(m_host.OwnerID, notecard, false);
  2907. }
  2908. public LSL_Key osOwnerSaveAppearance(LSL_String notecard, LSL_Integer includeHuds)
  2909. {
  2910. CheckThreatLevel(ThreatLevel.High, "osOwnerSaveAppearance");
  2911. return SaveAppearanceToNotecard(m_host.OwnerID, notecard, includeHuds == 0);
  2912. }
  2913. public LSL_Key osAgentSaveAppearance(LSL_Key avatarKey, LSL_String notecard)
  2914. {
  2915. CheckThreatLevel(ThreatLevel.VeryHigh, "osAgentSaveAppearance");
  2916. if (!UUID.TryParse(avatarKey, out UUID avatarId))
  2917. return new LSL_Key(ScriptBaseClass.NULL_KEY);
  2918. return SaveAppearanceToNotecard(avatarId, notecard, false);
  2919. }
  2920. public LSL_Key osAgentSaveAppearance(LSL_Key avatarKey, LSL_String notecard, LSL_Integer includeHuds)
  2921. {
  2922. CheckThreatLevel(ThreatLevel.VeryHigh, "osAgentSaveAppearance");
  2923. if (!UUID.TryParse(avatarKey, out UUID avatarId))
  2924. return LSL_Key.NullKey;
  2925. return SaveAppearanceToNotecard(avatarId, notecard, includeHuds == 0);
  2926. }
  2927. protected LSL_Key SaveAppearanceToNotecard(UUID avatarId, string notecard, bool NoHuds)
  2928. {
  2929. ScenePresence sp = World.GetScenePresence(avatarId);
  2930. if (sp is null || sp.IsChildAgent)
  2931. return LSL_Key.NullKey;
  2932. return SaveAppearanceToNotecard(sp, notecard, NoHuds);
  2933. }
  2934. protected LSL_Key SaveAppearanceToNotecard(ScenePresence sp, string notecard, bool NoHuds)
  2935. {
  2936. IAvatarFactoryModule appearanceModule = World.RequestModuleInterface<IAvatarFactoryModule>();
  2937. if (appearanceModule is not null)
  2938. {
  2939. appearanceModule.SaveBakedTextures(sp.UUID);
  2940. OSDMap appearancePacked = sp.Appearance.PackForNotecard(NoHuds);
  2941. TaskInventoryItem item
  2942. = SaveNotecard(notecard, "Avatar Appearance", Util.GetFormattedXml(appearancePacked as OSD), true);
  2943. return new LSL_Key(item.AssetID.ToString());
  2944. }
  2945. return LSL_Key.NullKey;
  2946. }
  2947. /// <summary>
  2948. /// Get the gender as specified in avatar appearance for a given avatar key
  2949. /// </summary>
  2950. /// <param name="rawAvatarId"></param>
  2951. /// <returns>"male" or "female" or "unknown"</returns>
  2952. public LSL_String osGetGender(LSL_Key rawAvatarId)
  2953. {
  2954. CheckThreatLevel(ThreatLevel.None, "osGetGender");
  2955. if (!UUID.TryParse(rawAvatarId, out UUID avatarId))
  2956. return new LSL_String("unknown");
  2957. ScenePresence sp = World.GetScenePresence(avatarId);
  2958. if (sp is null || sp.IsChildAgent || sp.Appearance is null || sp.Appearance.VisualParams is null)
  2959. return new LSL_String("unknown");
  2960. // find the index of "shape" parameter "male"
  2961. int vpShapeMaleIndex = 0;
  2962. bool indexFound = false;
  2963. VisualParam param = new();
  2964. foreach(var vpEntry in VisualParams.Params)
  2965. {
  2966. param = vpEntry.Value;
  2967. if (param.Name == "male" && param.Wearable == "shape")
  2968. {
  2969. indexFound = true;
  2970. break;
  2971. }
  2972. if (param.Group == 0)
  2973. vpShapeMaleIndex++;
  2974. }
  2975. if (!indexFound)
  2976. return new LSL_String("unknown");
  2977. float vpShapeMale = Utils.ByteToFloat(sp.Appearance.VisualParams[vpShapeMaleIndex], param.MinValue, param.MaxValue);
  2978. bool isMale = vpShapeMale > 0.5f;
  2979. return new LSL_String(isMale ? "male" : "female");
  2980. }
  2981. /// <summary>
  2982. /// Get current region's map texture UUID
  2983. /// </summary>
  2984. /// <returns></returns>
  2985. public LSL_Key osGetMapTexture()
  2986. {
  2987. CheckThreatLevel();
  2988. return m_ScriptEngine.World.RegionInfo.RegionSettings.TerrainImageID.ToString();
  2989. }
  2990. /// <summary>
  2991. /// Get a region's map texture UUID by region UUID or name.
  2992. /// </summary>
  2993. /// <param name="regionName"></param>
  2994. /// <returns></returns>
  2995. public LSL_Key osGetRegionMapTexture(string regionNameOrID)
  2996. {
  2997. CheckThreatLevel(ThreatLevel.High, "osGetRegionMapTexture");
  2998. Scene scene = m_ScriptEngine.World;
  2999. GridRegion region;
  3000. if(string.IsNullOrWhiteSpace(regionNameOrID))
  3001. return scene.RegionInfo.RegionSettings.TerrainImageID.ToString();
  3002. //If string is a key, use it. Otherwise, try to locate region by name.
  3003. if (UUID.TryParse(regionNameOrID, out UUID key))
  3004. region = scene.GridService.GetRegionByUUID(UUID.Zero, key);
  3005. else
  3006. region = scene.GridService.GetRegionByName(UUID.Zero, regionNameOrID);
  3007. // If region was found, return the regions map texture key.
  3008. if (region is not null)
  3009. key = region.TerrainImage;
  3010. ScriptSleep(1000);
  3011. return new LSL_Key(key.ToString());
  3012. }
  3013. /// <summary>
  3014. /// Return information regarding various simulator statistics (sim fps, physics fps, time
  3015. /// dilation, total number of prims, total number of active scripts, script lps, various
  3016. /// timing data, packets in/out, etc. Basically much the information that's shown in the
  3017. /// client's Statistics Bar (Ctrl-Shift-1)
  3018. /// </summary>
  3019. /// <returns>List of floats</returns>
  3020. public LSL_List osGetRegionStats()
  3021. {
  3022. CheckThreatLevel(ThreatLevel.Moderate, "osGetRegionStats");
  3023. LSL_List ret = new();
  3024. float[] stats = World.StatsReporter.LastReportedSimStats;
  3025. for (int i = 0; i < stats.Length; i++)
  3026. {
  3027. ret.Add(new LSL_Float(stats[i]));
  3028. }
  3029. return ret;
  3030. }
  3031. public LSL_Vector osGetRegionSize()
  3032. {
  3033. CheckThreatLevel();
  3034. //Scene scene = m_ScriptEngine.World;
  3035. RegionInfo reg = World.RegionInfo;
  3036. //GridRegion region = scene.GridService.GetRegionByUUID(UUID.Zero, World.RegionInfo.RegionID);
  3037. //return new LSL_Vector((float)region.RegionSizeX, (float)region.RegionSizeY, (float)Constants.RegionHeight);
  3038. return new LSL_Vector((float)reg.RegionSizeX, (float)reg.RegionSizeY, 0.0f);
  3039. }
  3040. public int osGetSimulatorMemory()
  3041. {
  3042. CheckThreatLevel(ThreatLevel.Moderate, "osGetSimulatorMemory");
  3043. long pws = Util.GetPhysicalMemUse();
  3044. if (pws > Int32.MaxValue)
  3045. return Int32.MaxValue;
  3046. if (pws < 0)
  3047. return 0;
  3048. return (int)pws;
  3049. }
  3050. public int osGetSimulatorMemoryKB()
  3051. {
  3052. CheckThreatLevel(ThreatLevel.Moderate, "osGetSimulatorMemoryKB");
  3053. long pws = Util.GetPhysicalMemUse();
  3054. if ((pws & 0x3FFL) != 0)
  3055. pws += 0x400L;
  3056. pws >>= 10;
  3057. if (pws > Int32.MaxValue)
  3058. return Int32.MaxValue;
  3059. return (int)pws;
  3060. }
  3061. public void osSetSpeed(string ID, LSL_Float SpeedModifier)
  3062. {
  3063. CheckThreatLevel(ThreatLevel.Moderate, "osSetSpeed");
  3064. if (!UUID.TryParse(ID, out UUID avid))
  3065. return;
  3066. ScenePresence avatar = World.GetScenePresence(avid);
  3067. if (avatar is not null)
  3068. avatar.SpeedModifier = (float)SpeedModifier;
  3069. }
  3070. public void osSetOwnerSpeed(LSL_Float SpeedModifier)
  3071. {
  3072. CheckThreatLevel(ThreatLevel.Moderate, "osSetOwnerSpeed");
  3073. if(SpeedModifier > 4)
  3074. SpeedModifier = 4;
  3075. ScenePresence avatar = World.GetScenePresence(m_host.OwnerID);
  3076. if (avatar is not null)
  3077. avatar.SpeedModifier = (float)SpeedModifier;
  3078. }
  3079. public void osKickAvatar(string FirstName, string SurName, string alert)
  3080. {
  3081. CheckThreatLevel(ThreatLevel.Severe, "osKickAvatar");
  3082. if(string.IsNullOrEmpty(alert))
  3083. {
  3084. World.ForEachRootScenePresence(delegate (ScenePresence sp)
  3085. {
  3086. if (sp.Firstname == FirstName && sp.Lastname == SurName)
  3087. sp.Scene.CloseAgent(sp.UUID, false);
  3088. });
  3089. }
  3090. else
  3091. {
  3092. World.ForEachRootScenePresence(delegate (ScenePresence sp)
  3093. {
  3094. if (sp.Firstname == FirstName && sp.Lastname == SurName)
  3095. {
  3096. sp.ControllingClient.Kick(alert);
  3097. sp.Scene.CloseAgent(sp.UUID, false);
  3098. }
  3099. });
  3100. }
  3101. }
  3102. public void osKickAvatar(LSL_Key agentKey, string alert)
  3103. {
  3104. CheckThreatLevel(ThreatLevel.Severe, "osKickAvatar");
  3105. if (!UUID.TryParse(agentKey, out UUID id) || id.IsZero())
  3106. return;
  3107. ScenePresence sp = World.GetScenePresence(id);
  3108. if(sp is null)
  3109. return;
  3110. // kick client...
  3111. if (!string.IsNullOrEmpty(alert))
  3112. sp.ControllingClient.Kick(alert);
  3113. // ...and close on our side
  3114. sp.Scene.CloseAgent(id, false);
  3115. }
  3116. public LSL_Float osGetHealth(LSL_Key agentKey)
  3117. {
  3118. CheckThreatLevel(ThreatLevel.None, "osGetHealth");
  3119. LSL_Float health = new(-1);
  3120. if (!UUID.TryParse(agentKey, out UUID id) || id.IsZero())
  3121. return health;
  3122. ScenePresence presence = World.GetScenePresence(id);
  3123. if (presence is not null)
  3124. health = presence.Health;
  3125. return health;
  3126. }
  3127. public void osCauseDamage(LSL_Key avatar, LSL_Float damage)
  3128. {
  3129. CheckThreatLevel(ThreatLevel.High, "osCauseDamage");
  3130. if (!UUID.TryParse(avatar, out UUID avatarId))
  3131. return;
  3132. ScenePresence presence = World.GetScenePresence(avatarId);
  3133. if (presence is null)
  3134. return;
  3135. Vector3 pos = m_host.GetWorldPosition();
  3136. LandData land = World.GetLandData(pos);
  3137. if ((land.Flags & (uint)ParcelFlags.AllowDamage) == (uint)ParcelFlags.AllowDamage)
  3138. {
  3139. float health = presence.Health;
  3140. health -= (float)damage;
  3141. presence.setHealthWithUpdate(health);
  3142. if (health <= 0)
  3143. {
  3144. // check to see if it is an NPC and just remove it
  3145. if (presence.IsNPC)
  3146. {
  3147. INPCModule NPCmodule = World.RequestModuleInterface<INPCModule>();
  3148. NPCmodule?.DeleteNPC(presence.UUID, World);
  3149. return;
  3150. }
  3151. float healthliveagain = 100;
  3152. presence.ControllingClient.SendAgentAlertMessage("You died!", true);
  3153. presence.setHealthWithUpdate(healthliveagain);
  3154. presence.Scene.TeleportClientHome(presence.UUID, presence.ControllingClient);
  3155. }
  3156. }
  3157. }
  3158. public void osCauseHealing(LSL_Key avatar, LSL_Float healing)
  3159. {
  3160. CheckThreatLevel(ThreatLevel.High, "osCauseHealing");
  3161. if (!UUID.TryParse(avatar, out UUID avatarId))
  3162. return;
  3163. ScenePresence presence = World.GetScenePresence(avatarId);
  3164. if (presence is null)
  3165. return;
  3166. float health = presence.Health;
  3167. health += (float)healing;
  3168. if (health >= 100)
  3169. health = 100;
  3170. presence.setHealthWithUpdate(health);
  3171. }
  3172. public void osSetHealth(LSL_Key avatar, LSL_Float health)
  3173. {
  3174. CheckThreatLevel(ThreatLevel.High, "osSetHealth");
  3175. if (!UUID.TryParse(avatar, out UUID avatarId))
  3176. return;
  3177. ScenePresence presence = World.GetScenePresence(avatarId);
  3178. if (presence is not null)
  3179. {
  3180. if (health > 100.0)
  3181. health = 100.0;
  3182. else if (health < 1.0)
  3183. health = 1.0;
  3184. presence.setHealthWithUpdate((float)health);
  3185. }
  3186. }
  3187. public void osSetHealRate(LSL_Key avatar, LSL_Float healrate)
  3188. {
  3189. CheckThreatLevel(ThreatLevel.High, "osSetHealRate");
  3190. if (!UUID.TryParse(avatar, out UUID avatarId))
  3191. return;
  3192. ScenePresence presence = World.GetScenePresence(avatarId);
  3193. if (presence is null)
  3194. return;
  3195. presence.HealRate = (float)healrate;
  3196. }
  3197. public LSL_Float osGetHealRate(LSL_Key avatar)
  3198. {
  3199. CheckThreatLevel(ThreatLevel.None, "osGetHealRate");
  3200. LSL_Float rate = new(0);
  3201. if (!UUID.TryParse(avatar, out UUID avatarId))
  3202. return rate;
  3203. ScenePresence presence = World.GetScenePresence(avatarId);
  3204. if (presence is not null)
  3205. rate = presence.HealRate;
  3206. return rate;
  3207. }
  3208. public LSL_List osGetPrimitiveParams(LSL_Key prim, LSL_List rules)
  3209. {
  3210. CheckThreatLevel();
  3211. InitLSL();
  3212. return m_LSL_Api.GetPrimitiveParamsEx(prim, rules);
  3213. }
  3214. public void osSetPrimitiveParams(LSL_Key prim, LSL_List rules)
  3215. {
  3216. CheckThreatLevel();
  3217. InitLSL();
  3218. m_LSL_Api.SetPrimitiveParamsEx(prim, rules, "osSetPrimitiveParams");
  3219. }
  3220. /// <summary>
  3221. /// Set parameters for light projection in host prim
  3222. /// </summary>
  3223. public void osSetProjectionParams(LSL_Integer projection, LSL_Key texture, LSL_Float fov, LSL_Float focus, LSL_Float amb)
  3224. {
  3225. SetProjectionParams(m_host, projection, texture, fov, focus, amb);
  3226. }
  3227. /// <summary>
  3228. /// Set parameters for light projection of a linkset prim
  3229. /// </summary>
  3230. public void osSetProjectionParams(LSL_Integer linknum, LSL_Integer projection, LSL_Key texture, LSL_Float fov, LSL_Float focus, LSL_Float amb)
  3231. {
  3232. if (linknum == ScriptBaseClass.LINK_THIS || linknum == m_host.LinkNum)
  3233. {
  3234. SetProjectionParams(m_host, projection, texture, fov, focus, amb);
  3235. return;
  3236. }
  3237. if (linknum < 0 || linknum > m_host.ParentGroup.PrimCount)
  3238. return;
  3239. if(linknum < 2 && m_host.LinkNum < 2)
  3240. {
  3241. SetProjectionParams(m_host, projection, texture, fov, focus, amb);
  3242. return;
  3243. }
  3244. SceneObjectPart obj = m_host.ParentGroup.GetLinkNumPart(linknum);
  3245. if(obj is not null)
  3246. SetProjectionParams(obj, projection, texture, fov, focus, amb);
  3247. }
  3248. /// <summary>
  3249. /// Set parameters for light projection with uuid of target prim
  3250. /// </summary>
  3251. public void osSetProjectionParams(LSL_Key prim, LSL_Integer llprojection, LSL_Key texture, LSL_Float fov, LSL_Float focus, LSL_Float amb)
  3252. {
  3253. if(UUID.TryParse(prim, out UUID pID) && pID.IsNotZero())
  3254. {
  3255. SceneObjectPart obj = World.GetSceneObjectPart(pID);
  3256. if(obj is not null)
  3257. {
  3258. if(obj.OwnerID.Equals(m_host.OwnerID))
  3259. SetProjectionParams(obj, llprojection, texture, fov, focus, amb);
  3260. }
  3261. }
  3262. else
  3263. SetProjectionParams(m_host, llprojection, texture, fov, focus, amb);
  3264. }
  3265. private static void SetProjectionParams(SceneObjectPart obj, LSL_Integer llprojection, LSL_Key texture, LSL_Float fov, LSL_Float focus, LSL_Float amb)
  3266. {
  3267. if(obj is null || obj.IsDeleted || obj.Shape == null)
  3268. return;
  3269. if(llprojection != 0)
  3270. {
  3271. if (!UUID.TryParse(texture, out UUID texID))
  3272. return;
  3273. obj.Shape.ProjectionEntry = true;
  3274. obj.Shape.ProjectionTextureUUID = texID;
  3275. obj.Shape.ProjectionFOV = Math.Clamp((float)fov, 0, 3.0f);
  3276. obj.Shape.ProjectionFocus = Math.Clamp((float)focus, -20.0f, 20.0f);
  3277. obj.Shape.ProjectionAmbiance = Math.Clamp((float)amb, 0, 1.0f);
  3278. obj.ParentGroup.HasGroupChanged = true;
  3279. obj.ScheduleFullUpdate();
  3280. return;
  3281. }
  3282. if(obj.Shape.ProjectionEntry)
  3283. {
  3284. obj.Shape.ProjectionEntry = false;
  3285. obj.ParentGroup.HasGroupChanged = true;
  3286. obj.ScheduleFullUpdate();
  3287. }
  3288. }
  3289. /// <summary>
  3290. /// Like osGetAgents but returns enough info for a radar
  3291. /// </summary>
  3292. /// <returns>Strided list of the UUID, position and name of each avatar in the region</returns>
  3293. public LSL_List osGetAvatarList()
  3294. {
  3295. CheckThreatLevel(ThreatLevel.None, "osGetAvatarList");
  3296. LSL_List result = new();
  3297. World.ForEachRootScenePresence(delegate (ScenePresence avatar)
  3298. {
  3299. if (avatar is not null && !avatar.IsDeleted && avatar.UUID.NotEqual(m_host.OwnerID))
  3300. {
  3301. result.Add(new LSL_String(avatar.UUID.ToString()));
  3302. result.Add(new LSL_Vector(avatar.AbsolutePosition));
  3303. result.Add(new LSL_String(avatar.Name));
  3304. }
  3305. });
  3306. return result;
  3307. }
  3308. public LSL_List osGetNPCList()
  3309. {
  3310. CheckThreatLevel(ThreatLevel.None, "osGetNPCList");
  3311. LSL_List result = new();
  3312. World.ForEachRootScenePresence(delegate (ScenePresence avatar)
  3313. {
  3314. // npcs are not childagents but that is now.
  3315. if (avatar is not null && avatar.IsNPC && !avatar.IsDeleted && !avatar.IsChildAgent && !avatar.IsInTransit)
  3316. {
  3317. result.Add(new LSL_String(avatar.UUID.ToString()));
  3318. result.Add(new LSL_Vector(avatar.AbsolutePosition));
  3319. result.Add(new LSL_String(avatar.Name));
  3320. }
  3321. });
  3322. return result;
  3323. }
  3324. /// <summary>
  3325. /// Convert a unix time to a llGetTimestamp() like string
  3326. /// </summary>
  3327. /// <param name="unixTime"></param>
  3328. /// <returns></returns>
  3329. public LSL_String osUnixTimeToTimestamp(LSL_Integer time)
  3330. {
  3331. return new LSL_String(Util.ToDateTime(time.value).ToString("yyyy-MM-ddTHH:mm:ss.fffffffZ"));
  3332. }
  3333. /// <summary>
  3334. /// Invite user to the group this object is set to
  3335. /// </summary>
  3336. /// <param name="agentId"></param>
  3337. /// <returns></returns>
  3338. public LSL_Integer osInviteToGroup(LSL_Key agentId)
  3339. {
  3340. CheckThreatLevel(ThreatLevel.VeryLow, "osInviteToGroup");
  3341. // groups module is required
  3342. if (m_groupsModule is null)
  3343. return ScriptBaseClass.FALSE;
  3344. if (!UUID.TryParse(agentId, out UUID agent))
  3345. return ScriptBaseClass.FALSE;
  3346. // object has to be set to a group, but not group owned
  3347. if (m_host.GroupID.IsZero() || m_host.GroupID.Equals(m_host.OwnerID))
  3348. return ScriptBaseClass.FALSE;
  3349. // invited agent has to be present in this scene
  3350. ScenePresence sp = World.GetScenePresence(agent);
  3351. if (sp is null || sp.IsNPC || sp.IsChildAgent || !sp.ControllingClient.IsActive)
  3352. return ScriptBaseClass.FALSE;
  3353. if (sp.ControllingClient.IsGroupMember(m_host.GroupID))
  3354. return 2;
  3355. // object owner needs invite power
  3356. ulong ownerPowers = m_groupsModule.GetFullGroupPowers(m_host.OwnerID, m_host.GroupID);
  3357. if ((ownerPowers & (ulong)GroupPowers.Invite) == 0)
  3358. return ScriptBaseClass.FALSE;
  3359. m_groupsModule.InviteGroup(null, m_host.OwnerID, m_host.GroupID, agent, UUID.Zero);
  3360. return ScriptBaseClass.TRUE;
  3361. }
  3362. /// <summary>
  3363. /// Eject user from the group this object is set to
  3364. /// </summary>
  3365. /// <param name="agentId"></param>
  3366. /// <returns></returns>
  3367. public LSL_Integer osEjectFromGroup(LSL_Key agentId)
  3368. {
  3369. CheckThreatLevel(ThreatLevel.VeryLow, "osEjectFromGroup");
  3370. // groups module is required
  3371. if (m_groupsModule is null)
  3372. return ScriptBaseClass.FALSE;
  3373. if (!UUID.TryParse(agentId, out UUID agent))
  3374. return ScriptBaseClass.FALSE;
  3375. // object has to be set to a group, but not group owned
  3376. if (m_host.GroupID.IsZero() || m_host.GroupID.Equals(m_host.OwnerID))
  3377. return ScriptBaseClass.FALSE;
  3378. // object owner needs eject power
  3379. ulong ownerPowers = m_groupsModule.GetFullGroupPowers(m_host.OwnerID, m_host.GroupID);
  3380. if ((ownerPowers & (ulong)GroupPowers.Eject) == 0)
  3381. return ScriptBaseClass.FALSE;
  3382. m_groupsModule.EjectGroupMember(null, m_host.OwnerID, m_host.GroupID, agent);
  3383. return ScriptBaseClass.TRUE;
  3384. }
  3385. /// <summary>
  3386. /// Sets terrain estate texture
  3387. /// </summary>
  3388. /// <param name="level"></param>
  3389. /// <param name="texture"></param>
  3390. /// <returns></returns>
  3391. public void osSetTerrainTexture(int level, LSL_Key texture)
  3392. {
  3393. CheckThreatLevel(ThreatLevel.High, "osSetTerrainTexture");
  3394. //Check to make sure that the script's owner is the estate manager/master
  3395. //World.Permissions.GenericEstatePermission(
  3396. if (World.Permissions.IsGod(m_host.OwnerID))
  3397. {
  3398. if (level < 0 || level > 3)
  3399. return;
  3400. if (!UUID.TryParse(texture, out UUID textureID))
  3401. return;
  3402. // estate module is required
  3403. IEstateModule estate = World.RequestModuleInterface<IEstateModule>();
  3404. estate?.setEstateTerrainBaseTexture(level, textureID);
  3405. }
  3406. }
  3407. /// <summary>
  3408. /// Sets terrain heights of estate
  3409. /// </summary>
  3410. /// <param name="corner"></param>
  3411. /// <param name="low"></param>
  3412. /// <param name="high"></param>
  3413. /// <returns></returns>
  3414. public void osSetTerrainTextureHeight(int corner, double low, double high)
  3415. {
  3416. CheckThreatLevel(ThreatLevel.High, "osSetTerrainTextureHeight");
  3417. //Check to make sure that the script's owner is the estate manager/master
  3418. //World.Permissions.GenericEstatePermission(
  3419. if (World.Permissions.IsGod(m_host.OwnerID))
  3420. {
  3421. if (corner < 0 || corner > 3)
  3422. return;
  3423. // estate module is required
  3424. IEstateModule estate = World.RequestModuleInterface<IEstateModule>();
  3425. estate?.setEstateTerrainTextureHeights(corner, (float)low, (float)high);
  3426. }
  3427. }
  3428. #region Attachment commands
  3429. public void osForceAttachToAvatar(int attachmentPoint)
  3430. {
  3431. CheckThreatLevel(ThreatLevel.High, "osForceAttachToAvatar");
  3432. InitLSL();
  3433. m_LSL_Api.AttachToAvatar(attachmentPoint);
  3434. }
  3435. public void osForceAttachToAvatarFromInventory(string itemName, int attachmentPoint)
  3436. {
  3437. CheckThreatLevel(ThreatLevel.High, "osForceAttachToAvatarFromInventory");
  3438. ForceAttachToAvatarFromInventory(m_host.OwnerID, itemName, attachmentPoint);
  3439. }
  3440. public void osForceAttachToOtherAvatarFromInventory(string rawAvatarId, string itemName, int attachmentPoint)
  3441. {
  3442. CheckThreatLevel(ThreatLevel.VeryHigh, "osForceAttachToOtherAvatarFromInventory");
  3443. if (!UUID.TryParse(rawAvatarId, out UUID avatarId))
  3444. return;
  3445. ForceAttachToAvatarFromInventory(avatarId, itemName, attachmentPoint);
  3446. }
  3447. public void ForceAttachToAvatarFromInventory(UUID avatarId, string itemName, int attachmentPoint)
  3448. {
  3449. IAttachmentsModule attachmentsModule = m_ScriptEngine.World.AttachmentsModule;
  3450. if (attachmentsModule is null)
  3451. return;
  3452. InitLSL();
  3453. TaskInventoryItem item = m_host.Inventory.GetInventoryItem(itemName);
  3454. if (item is null)
  3455. {
  3456. m_LSL_Api.llSay(0, $"Could not find object '{itemName}'");
  3457. throw new Exception($"The inventory item '{itemName}' could not be found");
  3458. }
  3459. if (item.InvType != (int)InventoryType.Object)
  3460. {
  3461. m_LSL_Api.llSay(0, $"Unable to attach, item '{itemName}' is not an object.");
  3462. throw new Exception($"The inventory item '{itemName}' is not an object");
  3463. }
  3464. if ((item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) != 0)
  3465. {
  3466. m_LSL_Api.llSay(0, $"Unable to attach coalesced object, item '{itemName}'");
  3467. throw new Exception($"The inventory item '{itemName}' is a coalesced object");
  3468. }
  3469. ScenePresence sp = World.GetScenePresence(avatarId);
  3470. if (sp is null)
  3471. return;
  3472. InventoryItemBase newItem = World.MoveTaskInventoryItem(sp.UUID, UUID.Zero, m_host, item.ItemID, out string message);
  3473. if (newItem is null)
  3474. {
  3475. m_log.ErrorFormat(
  3476. "[OSSL API]: Could not create user inventory item {0} for {1}, attach point {2} in {3}: {4}",
  3477. itemName, m_host.Name, attachmentPoint, World.Name, message);
  3478. m_LSL_Api.llSay(0, message);
  3479. return;
  3480. }
  3481. attachmentsModule.RezSingleAttachmentFromInventory(sp, newItem.ID, (uint)attachmentPoint);
  3482. }
  3483. public void osForceDetachFromAvatar()
  3484. {
  3485. CheckThreatLevel(ThreatLevel.High, "osForceDetachFromAvatar");
  3486. InitLSL();
  3487. m_LSL_Api.DetachFromAvatar();
  3488. }
  3489. private static bool listObjToInt(object p, out int i)
  3490. {
  3491. try
  3492. {
  3493. if (p is LSL_Integer lpi)
  3494. i = lpi.value;
  3495. else if (p is int pi)
  3496. i = pi;
  3497. else if (p is uint upi)
  3498. i = (int)upi;
  3499. else if (p is string ps)
  3500. return int.TryParse(ps, out i);
  3501. else if (p is LSL_String ps1)
  3502. return int.TryParse(ps1.m_string, out i);
  3503. else
  3504. {
  3505. i = 0;
  3506. return false;
  3507. }
  3508. return true;
  3509. }
  3510. catch
  3511. {
  3512. i = 0;
  3513. return false;
  3514. }
  3515. }
  3516. public LSL_List osGetNumberOfAttachments(LSL_Key avatar, LSL_List attachmentPoints)
  3517. {
  3518. CheckThreatLevel(ThreatLevel.Moderate, "osGetNumberOfAttachments");
  3519. LSL_List resp = new();
  3520. if (attachmentPoints.Length >= 1 && UUID.TryParse(avatar.ToString(), out UUID targetUUID) && World.TryGetScenePresence(targetUUID, out ScenePresence target))
  3521. {
  3522. foreach (object point in attachmentPoints.Data)
  3523. {
  3524. if(listObjToInt(point, out int ipoint))
  3525. {
  3526. resp.Add(new LSL_Integer(ipoint));
  3527. if (ipoint <= 0)
  3528. {
  3529. // indicates zero attachments
  3530. resp.Add(new LSL_Integer(0));
  3531. }
  3532. else
  3533. {
  3534. // gets the number of attachments on the attachment point
  3535. resp.Add(new LSL_Integer(target.GetAttachments((uint)ipoint).Count));
  3536. }
  3537. }
  3538. }
  3539. }
  3540. return resp;
  3541. }
  3542. public void osMessageAttachments(LSL_Key avatar, string message, LSL_List attachmentPoints, int options)
  3543. {
  3544. CheckThreatLevel(ThreatLevel.Moderate, "osMessageAttachments");
  3545. if (!UUID.TryParse(avatar.ToString(), out UUID targetUUID) || targetUUID.IsZero())
  3546. return;
  3547. if (!World.TryGetScenePresence(targetUUID, out ScenePresence target))
  3548. return;
  3549. if (target.IsDeleted || target.IsInTransit)
  3550. return;
  3551. if(target.GetAttachmentsCount() == 0)
  3552. return;
  3553. bool invertPoints = (options & ScriptBaseClass.OS_ATTACH_MSG_INVERT_POINTS) != 0;
  3554. bool msgAll = false;
  3555. List<int> aps;
  3556. if(attachmentPoints.Length > 0)
  3557. {
  3558. aps = new List<int>(attachmentPoints.Length);
  3559. foreach (object point in attachmentPoints.Data)
  3560. {
  3561. if (!listObjToInt(point, out int ipoint))
  3562. return;
  3563. if(ipoint == ScriptBaseClass.OS_ATTACH_MSG_ALL)
  3564. {
  3565. if(invertPoints)
  3566. return;
  3567. msgAll = true;
  3568. break;
  3569. }
  3570. else if(ipoint > 0)
  3571. aps.Add(ipoint);
  3572. }
  3573. }
  3574. else
  3575. aps = new List<int>();
  3576. if(aps.Count == 0)
  3577. {
  3578. if (!invertPoints && !msgAll)
  3579. return;
  3580. msgAll = true;
  3581. invertPoints = false;
  3582. }
  3583. List<SceneObjectGroup> attachments;
  3584. if (msgAll || invertPoints)
  3585. {
  3586. attachments = target.GetAttachments();
  3587. }
  3588. else
  3589. {
  3590. attachments = new List<SceneObjectGroup>();
  3591. foreach (int point in aps)
  3592. attachments.AddRange(target.GetAttachments((uint)point));
  3593. }
  3594. // if we have no attachments at this point, exit now
  3595. if (attachments.Count == 0)
  3596. return;
  3597. bool optionObjCreator = (options & ScriptBaseClass.OS_ATTACH_MSG_OBJECT_CREATOR) != 0;
  3598. bool optionScriptCreator = (options & ScriptBaseClass.OS_ATTACH_MSG_SCRIPT_CREATOR) != 0;
  3599. UUID hostCreatorID = m_host.CreatorID;
  3600. UUID itemCreatorID = m_item.CreatorID;
  3601. //int penalty = 100;
  3602. foreach (SceneObjectGroup sog in attachments)
  3603. {
  3604. if(sog.IsDeleted || sog.inTransit || ((sog.ScriptEvents & scriptEvents.dataserver) == 0))
  3605. continue;
  3606. if (invertPoints && aps.Contains((int)sog.AttachmentPoint))
  3607. continue;
  3608. UUID CreatorID = sog.RootPart.CreatorID;
  3609. if (optionObjCreator && CreatorID.NotEqual(hostCreatorID))
  3610. continue;
  3611. if (optionScriptCreator && CreatorID.NotEqual(itemCreatorID))
  3612. continue;
  3613. SceneObjectPart[] parts = sog.Parts;
  3614. foreach(SceneObjectPart p in parts)
  3615. {
  3616. if((p.ScriptEvents & scriptEvents.dataserver) != 0)
  3617. {
  3618. MessageObject(p.UUID, message);
  3619. //penalty += 10;
  3620. }
  3621. }
  3622. }
  3623. //ScriptSleep(penalty);
  3624. }
  3625. #endregion
  3626. /// <summary>
  3627. /// Checks if thing is a UUID.
  3628. /// </summary>
  3629. /// <param name="thing"></param>
  3630. /// <returns>1 if thing is a valid UUID, 0 otherwise</returns>
  3631. public LSL_Integer osIsUUID(string thing)
  3632. {
  3633. return UUID.TryParse(thing, out _) ? 1 : 0;
  3634. }
  3635. /// <summary>
  3636. /// Wraps to Math.Min()
  3637. /// </summary>
  3638. /// <param name="a"></param>
  3639. /// <param name="b"></param>
  3640. /// <returns></returns>
  3641. public LSL_Float osMin(double a, double b)
  3642. {
  3643. return Math.Min(a, b);
  3644. }
  3645. /// <summary>
  3646. /// Wraps to Math.max()
  3647. /// </summary>
  3648. /// <param name="a"></param>
  3649. /// <param name="b"></param>
  3650. /// <returns></returns>
  3651. public LSL_Float osMax(double a, double b)
  3652. {
  3653. return Math.Max(a, b);
  3654. }
  3655. public LSL_Key osGetRezzingObject()
  3656. {
  3657. CheckThreatLevel(ThreatLevel.None, "osGetRezzingObject");
  3658. UUID rezID = m_host.ParentGroup.RezzerID;
  3659. if(rezID.IsZero() || m_host.ParentGroup.Scene.GetScenePresence(rezID) is not null)
  3660. return LSL_Key.NullKey;
  3661. return new LSL_Key(rezID.ToString());
  3662. }
  3663. /// <summary>
  3664. /// Sets the response type for an HTTP request/response
  3665. /// </summary>
  3666. /// <returns></returns>
  3667. public void osSetContentType(LSL_Key id, string type)
  3668. {
  3669. CheckThreatLevel(ThreatLevel.Severe, "osSetContentType");
  3670. m_UrlModule?.HttpContentType(new UUID(id),type);
  3671. }
  3672. /// Shout an error if the object owner did not grant the script the specified permissions.
  3673. /// </summary>
  3674. /// <param name="perms"></param>
  3675. /// <returns>boolean indicating whether an error was shouted.</returns>
  3676. protected bool ShoutErrorOnLackingOwnerPerms(int perms, string errorPrefix)
  3677. {
  3678. if ((m_item.PermsMask & perms) == 0)
  3679. {
  3680. OSSLShoutError($"{errorPrefix}. Permissions not granted.");
  3681. return true;
  3682. }
  3683. if (m_item.PermsGranter.NotEqual(m_host.OwnerID))
  3684. {
  3685. OSSLShoutError($"{errorPrefix}. Permissions not granted to owner.");
  3686. return true;
  3687. }
  3688. return false;
  3689. }
  3690. protected void DropAttachment(bool checkPerms)
  3691. {
  3692. if (checkPerms && ShoutErrorOnLackingOwnerPerms(ScriptBaseClass.PERMISSION_ATTACH, "Cannot drop attachment"))
  3693. return;
  3694. IAttachmentsModule attachmentsModule = m_ScriptEngine.World.AttachmentsModule;
  3695. if (attachmentsModule is null)
  3696. return;
  3697. ScenePresence sp = m_host.ParentGroup.Scene.GetScenePresence(m_host.ParentGroup.OwnerID);
  3698. if (sp is not null)
  3699. attachmentsModule.DetachSingleAttachmentToGround(sp, m_host.ParentGroup.LocalId);
  3700. }
  3701. protected void DropAttachmentAt(bool checkPerms, LSL_Vector pos, LSL_Rotation rot)
  3702. {
  3703. if (checkPerms && ShoutErrorOnLackingOwnerPerms(ScriptBaseClass.PERMISSION_ATTACH, "Cannot drop attachment"))
  3704. return;
  3705. IAttachmentsModule attachmentsModule = m_ScriptEngine.World.AttachmentsModule;
  3706. if (attachmentsModule is null)
  3707. return;
  3708. ScenePresence sp = m_host.ParentGroup.Scene.GetScenePresence(m_host.ParentGroup.OwnerID);
  3709. if (sp is not null)
  3710. attachmentsModule.DetachSingleAttachmentToGround(sp, m_host.ParentGroup.LocalId, pos, rot);
  3711. }
  3712. public void osDropAttachment()
  3713. {
  3714. CheckThreatLevel(ThreatLevel.Moderate, "osDropAttachment");
  3715. DropAttachment(true);
  3716. }
  3717. public void osForceDropAttachment()
  3718. {
  3719. CheckThreatLevel(ThreatLevel.High, "osForceDropAttachment");
  3720. DropAttachment(false);
  3721. }
  3722. public void osDropAttachmentAt(LSL_Vector pos, LSL_Rotation rot)
  3723. {
  3724. CheckThreatLevel(ThreatLevel.Moderate, "osDropAttachmentAt");
  3725. DropAttachmentAt(true, pos, rot);
  3726. }
  3727. public void osForceDropAttachmentAt(LSL_Vector pos, LSL_Rotation rot)
  3728. {
  3729. CheckThreatLevel(ThreatLevel.High, "osForceDropAttachmentAt");
  3730. DropAttachmentAt(false, pos, rot);
  3731. }
  3732. public LSL_Integer osListenRegex(int channelID, string name, string ID, string msg, int regexBitfield)
  3733. {
  3734. CheckThreatLevel(ThreatLevel.Low, "osListenRegex");
  3735. IWorldComm wComm = m_ScriptEngine.World.RequestModuleInterface<IWorldComm>();
  3736. if(wComm is null)
  3737. return -1;
  3738. if(!UUID.TryParse(ID, out UUID keyID))
  3739. return -1;
  3740. // if we want the name to be used as a regular expression, ensure it is valid first.
  3741. if ((regexBitfield & ScriptBaseClass.OS_LISTEN_REGEX_NAME) == ScriptBaseClass.OS_LISTEN_REGEX_NAME)
  3742. {
  3743. try
  3744. {
  3745. Regex.IsMatch("", name);
  3746. }
  3747. catch
  3748. {
  3749. OSSLShoutError("Name regex is invalid.");
  3750. return -1;
  3751. }
  3752. }
  3753. // if we want the msg to be used as a regular expression, ensure it is valid first.
  3754. if ((regexBitfield & ScriptBaseClass.OS_LISTEN_REGEX_MESSAGE) == ScriptBaseClass.OS_LISTEN_REGEX_MESSAGE)
  3755. {
  3756. try
  3757. {
  3758. Regex.IsMatch("", msg);
  3759. }
  3760. catch
  3761. {
  3762. OSSLShoutError("Message regex is invalid.");
  3763. return -1;
  3764. }
  3765. }
  3766. return wComm.Listen(m_item.ItemID, m_host.UUID,
  3767. channelID, name, keyID, msg, regexBitfield);
  3768. }
  3769. public LSL_Integer osRegexIsMatch(string input, string pattern)
  3770. {
  3771. CheckThreatLevel(ThreatLevel.Low, "osRegexIsMatch");
  3772. try
  3773. {
  3774. return Regex.IsMatch(input, pattern) ? 1 : 0;
  3775. }
  3776. catch (Exception)
  3777. {
  3778. OSSLShoutError("Possible invalid regular expression detected.");
  3779. return 0;
  3780. }
  3781. }
  3782. public LSL_Key osRequestURL(LSL_List options)
  3783. {
  3784. CheckThreatLevel(ThreatLevel.Moderate, "osRequestURL");
  3785. Hashtable opts = new();
  3786. for (int i = 0 ; i < options.Length ; i++)
  3787. {
  3788. object opt = options.Data[i];
  3789. if (opt.ToString() == "allowXss")
  3790. opts["allowXss"] = true;
  3791. }
  3792. if (m_UrlModule is not null)
  3793. return m_UrlModule.RequestURL(m_ScriptEngine.ScriptModule, m_host, m_item.ItemID, opts).ToString();
  3794. return LSL_Key.NullKey;
  3795. }
  3796. public LSL_Key osRequestSecureURL(LSL_List options)
  3797. {
  3798. CheckThreatLevel(ThreatLevel.Moderate, "osRequestSecureURL");
  3799. Hashtable opts = new();
  3800. for (int i = 0 ; i < options.Length ; i++)
  3801. {
  3802. object opt = options.Data[i];
  3803. if (opt.ToString() == "allowXss")
  3804. opts["allowXss"] = true;
  3805. }
  3806. if (m_UrlModule != null)
  3807. return m_UrlModule.RequestSecureURL(m_ScriptEngine.ScriptModule, m_host, m_item.ItemID, opts).ToString();
  3808. return LSL_Key.NullKey;
  3809. }
  3810. public void osCollisionSound(string impact_sound, double impact_volume)
  3811. {
  3812. CheckThreatLevel();
  3813. if(impact_sound.Length == 0)
  3814. {
  3815. m_host.CollisionSoundVolume = (float)impact_volume;
  3816. m_host.CollisionSound = m_host.invalidCollisionSoundUUID;
  3817. if(impact_volume == 0.0)
  3818. m_host.CollisionSoundType = -1; // disable all sounds
  3819. else if(impact_volume == 1.0f)
  3820. m_host.CollisionSoundType = 0; // full return to default sounds
  3821. else
  3822. m_host.CollisionSoundType = 2; // default sounds with volume
  3823. m_host.aggregateScriptEvents();
  3824. return;
  3825. }
  3826. // TODO: Parameter check logic required.
  3827. UUID soundId = ScriptUtils.GetAssetIdFromKeyOrItemName(m_host, impact_sound, AssetType.Sound);
  3828. if(soundId.IsZero())
  3829. m_host.CollisionSoundType = -1;
  3830. else
  3831. {
  3832. m_host.CollisionSound = soundId;
  3833. m_host.CollisionSoundVolume = (float)impact_volume;
  3834. m_host.CollisionSoundType = 1;
  3835. }
  3836. m_host.aggregateScriptEvents();
  3837. }
  3838. // still not very usefull, detector is lost on rez, restarts, etc
  3839. public void osVolumeDetect(int detect)
  3840. {
  3841. CheckThreatLevel();
  3842. if (m_host.ParentGroup is null || m_host.ParentGroup.IsDeleted || m_host.ParentGroup.IsAttachment)
  3843. return;
  3844. m_host.ScriptSetVolumeDetect(detect != 0);
  3845. }
  3846. /// <summary>
  3847. /// Get inertial data
  3848. /// </summary>
  3849. /// <remarks>
  3850. /// </remarks>
  3851. /// <returns>
  3852. /// a LSL list with contents:
  3853. /// LSL_Float mass, the total mass of a linkset
  3854. /// LSL_Vector CenterOfMass, center mass relative to root prim
  3855. /// LSL_Vector Inertia, elements of diagonal of inertia Ixx,Iyy,Izz divided by total mass
  3856. /// LSL_Vector aux, elements of upper triagle of inertia Ixy (= Iyx), Ixz (= Izx), Iyz(= Izy) divided by total mass
  3857. /// </returns>
  3858. public LSL_List osGetInertiaData()
  3859. {
  3860. CheckThreatLevel();
  3861. LSL_List result = new();
  3862. SceneObjectGroup sog = m_host.ParentGroup;
  3863. if (sog is null || sog.IsDeleted)
  3864. return result;
  3865. sog.GetInertiaData(out float TotalMass, out Vector3 CenterOfMass, out Vector3 Inertia, out Vector4 aux );
  3866. if(TotalMass > 0)
  3867. {
  3868. float t = 1.0f/TotalMass;
  3869. Inertia.X *= t;
  3870. Inertia.Y *= t;
  3871. Inertia.Z *= t;
  3872. aux.X *= t;
  3873. aux.Y *= t;
  3874. aux.Z *= t;
  3875. }
  3876. result.Add(new LSL_Float(TotalMass));
  3877. result.Add(new LSL_Vector(CenterOfMass.X, CenterOfMass.Y, CenterOfMass.Z));
  3878. result.Add(new LSL_Vector(Inertia.X, Inertia.Y, Inertia.Z));
  3879. result.Add(new LSL_Vector(aux.X, aux.Y, aux.Z));
  3880. return result;
  3881. }
  3882. /// <summary>
  3883. /// set inertial data
  3884. /// replaces the automatic calculation of mass, center of mass and inertia
  3885. ///
  3886. /// </summary>
  3887. /// <param name="Mass">total mass of linkset</param>
  3888. /// <param name="centerOfMass">location of center of mass relative to root prim in local coords</param>
  3889. /// <param name="principalInertiaScaled">moment of inertia relative to principal axis and center of mass,Ixx, Iyy, Izz divided by mass</param>
  3890. /// <param name="lslrot">rotation of the inertia, relative to local axis</param>
  3891. /// <remarks>
  3892. /// the inertia argument is is inertia divided by mass, so corresponds only to the geometric distribution of mass and both can be changed independently.
  3893. /// </remarks>
  3894. public void osSetInertia(LSL_Float mass, LSL_Vector centerOfMass, LSL_Vector principalInertiaScaled, LSL_Rotation lslrot)
  3895. {
  3896. CheckThreatLevel();
  3897. SceneObjectGroup sog = m_host.ParentGroup;
  3898. if(sog is null || sog.IsDeleted)
  3899. return;
  3900. if(mass < 0 || principalInertiaScaled.x < 0 || principalInertiaScaled.y < 0 || principalInertiaScaled.z < 0)
  3901. return;
  3902. // need more checks
  3903. Vector3 CenterOfMass = new((float)centerOfMass.x, (float)centerOfMass.y, (float)centerOfMass.z);
  3904. float m = (float)mass;
  3905. Vector3 Inertia = new(
  3906. m * (float)principalInertiaScaled.x,
  3907. m * (float)principalInertiaScaled.y,
  3908. m * (float)principalInertiaScaled.z);
  3909. Vector4 rot = new((float)lslrot.x, (float)lslrot.y, (float)lslrot.y, (float)lslrot.s);
  3910. rot.Normalize();
  3911. sog.SetInertiaData(m, CenterOfMass, Inertia, rot );
  3912. }
  3913. /// <summary>
  3914. /// set inertial data as a sphere
  3915. /// replaces the automatic calculation of mass, center of mass and inertia
  3916. ///
  3917. /// </summary>
  3918. /// <param name="Mass">total mass of linkset</param>
  3919. /// <param name="boxsize">size of the Box</param>
  3920. /// <param name="centerOfMass">location of center of mass relative to root prim in local coords</param>
  3921. /// <param name="lslrot">rotation of the box, and so inertia, relative to local axis</param>
  3922. /// <remarks>
  3923. /// </remarks>
  3924. public void osSetInertiaAsBox(LSL_Float mass, LSL_Vector boxSize, LSL_Vector centerOfMass, LSL_Rotation lslrot)
  3925. {
  3926. CheckThreatLevel();
  3927. SceneObjectGroup sog = m_host.ParentGroup;
  3928. if(sog is null || sog.IsDeleted)
  3929. return;
  3930. if(mass < 0)
  3931. return;
  3932. // need more checks
  3933. Vector3 CenterOfMass = new((float)centerOfMass.x, (float)centerOfMass.y, (float)centerOfMass.z);
  3934. float lx = (float)boxSize.x;
  3935. float ly = (float)boxSize.y;
  3936. float lz = (float)boxSize.z;
  3937. float m = (float)mass;
  3938. float t = m / 12.0f;
  3939. Vector3 Inertia = new( t * (ly*ly + lz*lz),
  3940. t * (lx*lx + lz*lz),
  3941. t * (lx*lx + ly*ly));
  3942. Vector4 rot = new((float)lslrot.x, (float)lslrot.y, (float)lslrot.z, (float)lslrot.s);
  3943. rot.Normalize();
  3944. sog.SetInertiaData(m, CenterOfMass, Inertia, rot );
  3945. }
  3946. /// <summary>
  3947. /// set inertial data as a sphere
  3948. /// replaces the automatic calculation of mass, center of mass and inertia
  3949. ///
  3950. /// </summary>
  3951. /// <param name="Mass">total mass of linkset</param>
  3952. /// <param name="radius">radius of the sphere</param>
  3953. /// <param name="centerOfMass">location of center of mass relative to root prim in local coords</param>
  3954. /// <remarks>
  3955. /// </remarks>
  3956. public void osSetInertiaAsSphere(LSL_Float mass, LSL_Float radius, LSL_Vector centerOfMass)
  3957. {
  3958. CheckThreatLevel();
  3959. SceneObjectGroup sog = m_host.ParentGroup;
  3960. if(sog is null || sog.IsDeleted)
  3961. return;
  3962. if(mass < 0)
  3963. return;
  3964. // need more checks
  3965. Vector3 CenterOfMass = new((float)centerOfMass.x, (float)centerOfMass.y, (float)centerOfMass.z);
  3966. float r = (float)radius;
  3967. float m = (float)mass;
  3968. float t = 0.4f * m * r * r;
  3969. Vector3 Inertia = new(t, t, t);
  3970. sog.SetInertiaData(m, CenterOfMass, Inertia, new Vector4(0f, 0f, 0f,1.0f));
  3971. }
  3972. /// <summary>
  3973. /// set inertial data as a cylinder
  3974. /// replaces the automatic calculation of mass, center of mass and inertia
  3975. ///
  3976. /// </summary>
  3977. /// <param name="Mass">total mass of linkset</param>
  3978. /// <param name="radius">radius of the cylinder</param>
  3979. /// <param name="length">length of the cylinder</param>
  3980. /// <param name="centerOfMass">location of center of mass relative to root prim in local coords</param>
  3981. /// <param name="lslrot">rotation of the cylinder, and so inertia, relative to local axis</param>
  3982. /// <remarks>
  3983. /// cylinder axis aligned with Z axis. For other orientations provide the rotation.
  3984. /// </remarks>
  3985. public void osSetInertiaAsCylinder(LSL_Float mass, LSL_Float radius, LSL_Float length, LSL_Vector centerOfMass, LSL_Rotation lslrot)
  3986. {
  3987. CheckThreatLevel();
  3988. SceneObjectGroup sog = m_host.ParentGroup;
  3989. if(sog is null || sog.IsDeleted)
  3990. return;
  3991. if(mass < 0)
  3992. return;
  3993. // need more checks
  3994. Vector3 CenterOfMass = new((float)centerOfMass.x, (float)centerOfMass.y, (float)centerOfMass.z);
  3995. float m = (float)mass;
  3996. float r = (float)radius;
  3997. r *= r;
  3998. float t = (float)length;
  3999. t *= t;
  4000. t += 3.0f * r;
  4001. t *= 8.333333e-2f * m;
  4002. Vector3 Inertia = new(t, t, 0.5f * m * r);
  4003. Vector4 rot = new((float)lslrot.x, (float)lslrot.y, (float)lslrot.z, (float)lslrot.s);
  4004. rot.Normalize();
  4005. sog.SetInertiaData(m, CenterOfMass, Inertia, rot);
  4006. }
  4007. /// <summary>
  4008. /// removes inertial data manual override
  4009. /// default automatic calculation is used again
  4010. ///
  4011. /// </summary>
  4012. public void osClearInertia()
  4013. {
  4014. CheckThreatLevel();
  4015. SceneObjectGroup sog = m_host.ParentGroup;
  4016. if(sog is null || sog.IsDeleted)
  4017. return;
  4018. sog.SetInertiaData(-1, Vector3.Zero, Vector3.Zero, Vector4.Zero );
  4019. }
  4020. private bool checkAllowObjectTPbyLandOwner(Vector3 pos)
  4021. {
  4022. ILandObject land = World.LandChannel.GetLandObject(pos);
  4023. if(land is null)
  4024. return true;
  4025. LandData landdata = land.LandData;
  4026. if(landdata is null)
  4027. return true;
  4028. UUID hostOwner = m_host.OwnerID;
  4029. if(landdata.OwnerID.Equals(hostOwner))
  4030. return true;
  4031. EstateSettings es = World.RegionInfo.EstateSettings;
  4032. if(es is not null && es.IsEstateManagerOrOwner(hostOwner))
  4033. return true;
  4034. if(!landdata.IsGroupOwned)
  4035. return false;
  4036. UUID landGroup = landdata.GroupID;
  4037. if(landGroup.IsZero())
  4038. return false;
  4039. if(landGroup.Equals(m_host.GroupID))
  4040. return true;
  4041. return false;
  4042. }
  4043. /// <summary>
  4044. /// teleports a object (full linkset)
  4045. /// </summary>
  4046. /// <param name="objectUUID">the id of the linkset to teleport</param>
  4047. /// <param name="targetPos">target position</param>
  4048. /// <param name="rotation"> a rotation to apply</param>
  4049. /// <param name="flags">several flags/param>
  4050. /// <remarks>
  4051. /// only does teleport local to region
  4052. /// if object has scripts, owner must have rights to run scripts on target location
  4053. /// object owner must have rights to enter ojects on target location
  4054. /// target location parcel must have enought free prims capacity for the linkset prims
  4055. /// all avatars siting on the object must have access to target location
  4056. /// has a cool down time. retries before expire reset it
  4057. /// fail conditions are silent ignored
  4058. /// </remarks>
  4059. public LSL_Integer osTeleportObject(LSL_Key objectUUID, LSL_Vector targetPos, LSL_Rotation rotation, LSL_Integer flags)
  4060. {
  4061. CheckThreatLevel(ThreatLevel.Severe, "osTeleportObject");
  4062. if (!UUID.TryParse(objectUUID, out UUID objUUID))
  4063. {
  4064. OSSLShoutError("osTeleportObject() invalid object Key");
  4065. return -1;
  4066. }
  4067. SceneObjectGroup sog = World.GetSceneObjectGroup(objUUID);
  4068. if(sog is null || sog.IsDeleted || sog.inTransit)
  4069. return -1;
  4070. if(sog.OwnerID.NotEqual(m_host.OwnerID))
  4071. {
  4072. Vector3 pos = sog.AbsolutePosition;
  4073. if(!checkAllowObjectTPbyLandOwner(pos))
  4074. return -1;
  4075. }
  4076. return sog.TeleportObject(m_host.ParentGroup.UUID, targetPos, rotation, flags);
  4077. // a delay here may break vehicles
  4078. }
  4079. public LSL_Integer osGetLinkNumber(LSL_String name)
  4080. {
  4081. CheckThreatLevel();
  4082. SceneObjectGroup sog = m_host.ParentGroup;
  4083. if(sog is null || sog.IsDeleted)
  4084. return -1;
  4085. return sog.GetLinkNumber(name);
  4086. }
  4087. // rounds to the nearest number with provided number of decimal places
  4088. public LSL_Float osRound(LSL_Float value, LSL_Integer ndigits)
  4089. {
  4090. if(ndigits <= 0)
  4091. return Math.Round(value, MidpointRounding.AwayFromZero);
  4092. if(ndigits > 15)
  4093. ndigits = 15;
  4094. return Math.Round(value, ndigits, MidpointRounding.AwayFromZero);
  4095. }
  4096. public LSL_Float osVecMagSquare(LSL_Vector a)
  4097. {
  4098. return LSL_Vector.MagSquare(a);
  4099. }
  4100. public LSL_Float osVecDistSquare(LSL_Vector a, LSL_Vector b)
  4101. {
  4102. return LSL_Vector.MagSquare(a - b);
  4103. }
  4104. // returns the angle between 2 vectors 0 to pi
  4105. public LSL_Float osAngleBetween(LSL_Vector a, LSL_Vector b)
  4106. {
  4107. double dot = LSL_Vector.Dot(a,b);
  4108. double mcross = LSL_Vector.Mag(LSL_Vector.Cross(a,b));
  4109. return Math.Atan2(mcross, dot);
  4110. }
  4111. public void osAdjustSoundVolume(LSL_Integer linknum, LSL_Float volume)
  4112. {
  4113. SceneObjectPart sop = GetSingleLinkPart(linknum);
  4114. sop?.AdjustSoundGain(volume);
  4115. }
  4116. public void osSetSoundRadius(LSL_Integer linknum, LSL_Float radius)
  4117. {
  4118. SceneObjectPart sop = GetSingleLinkPart(linknum);
  4119. if(sop is not null)
  4120. sop.SoundRadius = radius;
  4121. }
  4122. public void osPlaySound(LSL_Integer linknum, LSL_String sound, LSL_Float volume)
  4123. {
  4124. if (m_SoundModule is null)
  4125. return;
  4126. SceneObjectPart sop = GetSingleLinkPart(linknum);
  4127. if(sop is null)
  4128. return;
  4129. UUID soundID = ScriptUtils.GetAssetIdFromKeyOrItemName(sop, m_host, sound, AssetType.Sound);
  4130. if (soundID.IsZero())
  4131. return;
  4132. // send the sound, once, to all clients in range
  4133. m_SoundModule.SendSound(sop, soundID, volume, false, 0, false, false);
  4134. }
  4135. public void osLoopSound(LSL_Integer linknum, LSL_String sound, LSL_Float volume)
  4136. {
  4137. if (m_SoundModule is null)
  4138. return;
  4139. SceneObjectPart sop = GetSingleLinkPart(linknum);
  4140. if(sop is null)
  4141. return;
  4142. UUID soundID = ScriptUtils.GetAssetIdFromKeyOrItemName(sop, m_host, sound, AssetType.Sound);
  4143. if (soundID.IsZero())
  4144. return;
  4145. m_SoundModule.LoopSound(sop, soundID, volume, false, false);
  4146. }
  4147. public void osLoopSoundMaster(LSL_Integer linknum, LSL_String sound, LSL_Float volume)
  4148. {
  4149. if (m_SoundModule is null)
  4150. return;
  4151. SceneObjectPart sop = GetSingleLinkPart(linknum);
  4152. if(sop is null)
  4153. return;
  4154. UUID soundID = ScriptUtils.GetAssetIdFromKeyOrItemName(sop, m_host, sound, AssetType.Sound);
  4155. if (soundID.IsZero())
  4156. return;
  4157. m_SoundModule.LoopSound(sop, soundID, volume, true, false);
  4158. }
  4159. public void osLoopSoundSlave(LSL_Integer linknum, LSL_String sound, LSL_Float volume)
  4160. {
  4161. if (m_SoundModule is null)
  4162. return;
  4163. SceneObjectPart sop = GetSingleLinkPart(linknum);
  4164. if(sop is null)
  4165. return;
  4166. UUID soundID = ScriptUtils.GetAssetIdFromKeyOrItemName(sop, m_host, sound, AssetType.Sound);
  4167. if (soundID.IsNotZero())
  4168. m_SoundModule.LoopSound(sop, soundID, volume, false, true);
  4169. }
  4170. public void osPlaySoundSlave(LSL_Integer linknum, LSL_String sound, LSL_Float volume)
  4171. {
  4172. if (m_SoundModule is null)
  4173. return;
  4174. SceneObjectPart sop = GetSingleLinkPart(linknum);
  4175. if(sop is null)
  4176. return;
  4177. UUID soundID = ScriptUtils.GetAssetIdFromKeyOrItemName(sop, m_host, sound, AssetType.Sound);
  4178. if (soundID.IsNotZero())
  4179. m_SoundModule.SendSound(sop, soundID, volume, false, 0, true, false);
  4180. }
  4181. public void osTriggerSound(LSL_Integer linknum, LSL_String sound, LSL_Float volume)
  4182. {
  4183. if (m_SoundModule is null)
  4184. return;
  4185. SceneObjectPart sop = GetSingleLinkPart(linknum);
  4186. if(sop is null)
  4187. return;
  4188. UUID soundID = ScriptUtils.GetAssetIdFromKeyOrItemName(sop, m_host, sound, AssetType.Sound);
  4189. if (soundID.IsNotZero())
  4190. m_SoundModule.SendSound(sop, soundID, volume, true, 0, false, false);
  4191. }
  4192. public void osTriggerSoundLimited(LSL_Integer linknum, LSL_String sound, LSL_Float volume,
  4193. LSL_Vector top_north_east, LSL_Vector bottom_south_west)
  4194. {
  4195. if (m_SoundModule is null)
  4196. return;
  4197. SceneObjectPart sop = GetSingleLinkPart(linknum);
  4198. if(sop is null)
  4199. return;
  4200. UUID soundID = ScriptUtils.GetAssetIdFromKeyOrItemName(sop, m_host, sound, AssetType.Sound);
  4201. if (soundID.IsNotZero())
  4202. m_SoundModule.TriggerSoundLimited(sop.UUID, soundID, volume,
  4203. bottom_south_west, top_north_east);
  4204. }
  4205. public void osStopSound(LSL_Integer linknum)
  4206. {
  4207. if (m_SoundModule is null)
  4208. return;
  4209. InitLSL();
  4210. List<SceneObjectPart> sops = m_LSL_Api.GetLinkParts(linknum);
  4211. if(sops is null || sops.Count == 0)
  4212. return;
  4213. for(int i = 0; i < sops.Count; ++i)
  4214. m_SoundModule.StopSound(sops[i]);
  4215. }
  4216. public void osPreloadSound(LSL_Integer linknum, LSL_String sound)
  4217. {
  4218. if (m_SoundModule is null)
  4219. return;
  4220. SceneObjectPart sop = GetSingleLinkPart(linknum);
  4221. if(sop is null)
  4222. return;
  4223. UUID soundID = ScriptUtils.GetAssetIdFromKeyOrItemName(sop, m_host, sound, AssetType.Sound);
  4224. if (soundID.IsZero())
  4225. return;
  4226. m_SoundModule.PreloadSound(sop, soundID);
  4227. ScriptSleep(1000);
  4228. }
  4229. // get only one part
  4230. private SceneObjectPart GetSingleLinkPart(int linkType)
  4231. {
  4232. if (m_host.ParentGroup is null || m_host.ParentGroup.IsDeleted)
  4233. return null;
  4234. switch (linkType)
  4235. {
  4236. case ScriptBaseClass.LINK_SET:
  4237. case ScriptBaseClass.LINK_ALL_OTHERS:
  4238. case ScriptBaseClass.LINK_ALL_CHILDREN:
  4239. return null;
  4240. case 0:
  4241. case ScriptBaseClass.LINK_ROOT:
  4242. return m_host.ParentGroup.RootPart;
  4243. case ScriptBaseClass.LINK_THIS:
  4244. return m_host;
  4245. default:
  4246. if(linkType < 0)
  4247. return null;
  4248. return m_host.ParentGroup.GetLinkNumPart(linkType);
  4249. }
  4250. }
  4251. // funtions to retrieve user country
  4252. // adaptation cm* counter parts from Avination Careminster extensions API
  4253. // included in Avination code contribution
  4254. // for now users country can only be set directly on DB
  4255. public LSL_String osDetectedCountry(LSL_Integer number)
  4256. {
  4257. CheckThreatLevel(ThreatLevel.Moderate, "osDetectedCountry");
  4258. if (World.UserAccountService is null)
  4259. return LSL_String.Empty;
  4260. DetectParams detectedParams = m_ScriptEngine.GetDetectParams(m_item.ItemID, number);
  4261. if (detectedParams is null)
  4262. return LSL_String.Empty;
  4263. UUID key = detectedParams.Key;
  4264. if (key.IsZero())
  4265. return LSL_String.Empty;
  4266. UserAccount account = World.UserAccountService.GetUserAccount(World.RegionInfo.ScopeID, key);
  4267. return account.UserCountry;
  4268. }
  4269. public LSL_String osGetAgentCountry(LSL_Key id)
  4270. {
  4271. CheckThreatLevel(ThreatLevel.Moderate, "osGetAgentCountry");
  4272. if (World.UserAccountService == null)
  4273. return LSL_String.Empty;
  4274. if (!UUID.TryParse(id, out UUID key))
  4275. return LSL_String.Empty;
  4276. if (key.IsZero())
  4277. return LSL_String.Empty;
  4278. //if owner is not god, target must be in region, or nearby regions
  4279. if (!World.Permissions.IsGod(m_host.OwnerID))
  4280. {
  4281. ScenePresence sp = World.GetScenePresence(key);
  4282. if(sp is null)
  4283. return LSL_String.Empty;
  4284. }
  4285. UserAccount account = World.UserAccountService.GetUserAccount(World.RegionInfo.ScopeID, key);
  4286. return account.UserCountry;
  4287. }
  4288. public LSL_String osStringSubString(LSL_String src, LSL_Integer offset)
  4289. {
  4290. CheckThreatLevel();
  4291. if (string.IsNullOrEmpty(src))
  4292. return LSL_String.Empty;
  4293. if (offset >= src.Length)
  4294. return LSL_String.Empty;
  4295. if (offset <= 0)
  4296. return src;
  4297. return src.m_string[(offset.value)..];
  4298. }
  4299. public LSL_String osStringSubString(LSL_String src, LSL_Integer offset, LSL_Integer length)
  4300. {
  4301. CheckThreatLevel();
  4302. if (string.IsNullOrEmpty(src))
  4303. return LSL_String.Empty;
  4304. if (length <= 0 || offset >= src.Length)
  4305. return LSL_String.Empty;
  4306. if (offset <= 0)
  4307. {
  4308. if(length == src.Length)
  4309. return src;
  4310. offset = 0;
  4311. }
  4312. if (length > src.Length - offset)
  4313. length = src.Length - offset;
  4314. return src.m_string.Substring(offset, length);
  4315. }
  4316. public LSL_Integer osStringStartsWith(LSL_String src, LSL_String value, LSL_Integer ignorecase)
  4317. {
  4318. CheckThreatLevel();
  4319. if (string.IsNullOrEmpty(src))
  4320. return 0;
  4321. if (string.IsNullOrEmpty(value))
  4322. return 0;
  4323. return src.m_string.StartsWith(value, ignorecase != 0, Culture.GetDefaultCurrentCulture()) ? 1 : 0;
  4324. }
  4325. public LSL_Integer osStringEndsWith(LSL_String src, LSL_String value, LSL_Integer ignorecase)
  4326. {
  4327. CheckThreatLevel();
  4328. if (string.IsNullOrEmpty(src))
  4329. return 0;
  4330. if (string.IsNullOrEmpty(value))
  4331. return 0;
  4332. return src.m_string.EndsWith(value, ignorecase != 0, Culture.GetDefaultCurrentCulture()) ? 1 : 0;
  4333. }
  4334. public LSL_Integer osStringIndexOf(LSL_String src, LSL_String value, LSL_Integer ignorecase)
  4335. {
  4336. CheckThreatLevel();
  4337. if (string.IsNullOrEmpty(src))
  4338. return -1;
  4339. if (string.IsNullOrEmpty(value))
  4340. return -1;
  4341. if (ignorecase == 0)
  4342. return src.m_string.IndexOf(value, StringComparison.Ordinal);
  4343. return src.m_string.IndexOf(value, StringComparison.OrdinalIgnoreCase);
  4344. }
  4345. public LSL_Integer osStringIndexOf(LSL_String src, LSL_String value,
  4346. LSL_Integer offset, LSL_Integer count, LSL_Integer ignorecase)
  4347. {
  4348. CheckThreatLevel();
  4349. if (string.IsNullOrEmpty(src))
  4350. return -1;
  4351. if (string.IsNullOrEmpty(value))
  4352. return -1;
  4353. if (offset >= src.Length)
  4354. return -1;
  4355. else if (offset < 0)
  4356. offset = 0;
  4357. if (count <= 0)
  4358. count = src.Length - offset;
  4359. else if (count > src.Length - offset)
  4360. count = src.Length - offset;
  4361. if (ignorecase == 0)
  4362. return src.m_string.IndexOf(value, offset, count, StringComparison.Ordinal);
  4363. return src.m_string.IndexOf(value, offset, count, StringComparison.OrdinalIgnoreCase);
  4364. }
  4365. public LSL_Integer osStringLastIndexOf(LSL_String src, LSL_String value, LSL_Integer ignorecase)
  4366. {
  4367. CheckThreatLevel();
  4368. if (string.IsNullOrEmpty(src))
  4369. return -1;
  4370. if (string.IsNullOrEmpty(value))
  4371. return -1;
  4372. if (ignorecase == 0)
  4373. return src.m_string.LastIndexOf(value, StringComparison.Ordinal);
  4374. return src.m_string.LastIndexOf(value, StringComparison.OrdinalIgnoreCase);
  4375. }
  4376. public LSL_Integer osStringLastIndexOf(LSL_String src, LSL_String value,
  4377. LSL_Integer offset, LSL_Integer count, LSL_Integer ignorecase)
  4378. {
  4379. CheckThreatLevel();
  4380. if (string.IsNullOrEmpty(src))
  4381. return -1;
  4382. if (string.IsNullOrEmpty(value))
  4383. return -1;
  4384. if (offset >= src.Length)
  4385. return -1;
  4386. if (offset < 0)
  4387. offset = 0;
  4388. if (count <= 0)
  4389. count = src.Length - offset;
  4390. else if (count > src.Length - offset)
  4391. count = src.Length - offset;
  4392. if (ignorecase == 0)
  4393. return src.m_string.LastIndexOf(value, offset, count, StringComparison.Ordinal);
  4394. return src.m_string.LastIndexOf(value, offset, count, StringComparison.OrdinalIgnoreCase);
  4395. }
  4396. public LSL_String osStringRemove(LSL_String src, LSL_Integer offset, LSL_Integer count)
  4397. {
  4398. if (string.IsNullOrEmpty(src))
  4399. return LSL_String.Empty;
  4400. if (offset >= src.Length)
  4401. return LSL_String.Empty;
  4402. if (offset < 0)
  4403. offset = 0;
  4404. if (count <= 0)
  4405. count = src.Length - offset;
  4406. else if (count > src.Length - offset)
  4407. count = src.Length - offset;
  4408. if (count >= src.Length)
  4409. return LSL_String.Empty;
  4410. return src.m_string.Remove(offset, count);
  4411. }
  4412. public LSL_String osStringReplace(LSL_String src, LSL_String oldvalue, LSL_String newvalue)
  4413. {
  4414. if (string.IsNullOrEmpty(src))
  4415. return LSL_String.Empty;
  4416. if (string.IsNullOrEmpty(oldvalue))
  4417. return LSL_String.Empty;
  4418. if (string.IsNullOrEmpty(newvalue))
  4419. newvalue = null;
  4420. return src.m_string.Replace(oldvalue, newvalue);
  4421. }
  4422. public LSL_Integer osApproxEquals(LSL_Float a, LSL_Float b)
  4423. {
  4424. if (a > b + 1.0e-6 || a < b - 1.0e-6)
  4425. return 0;
  4426. return 1;
  4427. }
  4428. public LSL_Integer osApproxEquals(LSL_Float a, LSL_Float b, LSL_Float margin)
  4429. {
  4430. double e = Math.Abs(margin);
  4431. if (a > b + e || a < b - e)
  4432. return 0;
  4433. return 1;
  4434. }
  4435. public LSL_Integer osApproxEquals(LSL_Vector va, LSL_Vector vb)
  4436. {
  4437. double a = va.x;
  4438. double b = vb.x;
  4439. if (a > b + 1.0e-6 || a < b - 1.0e-6)
  4440. return 0;
  4441. a = va.y;
  4442. b = vb.y;
  4443. if (a > b + 1.0e-6 || a < b - 1.0e-6)
  4444. return 0;
  4445. a = va.z;
  4446. b = vb.z;
  4447. if (a > b + 1.0e-6 || a < b - 1.0e-6)
  4448. return 0;
  4449. return 1;
  4450. }
  4451. public LSL_Integer osApproxEquals(LSL_Vector va, LSL_Vector vb, LSL_Float margin)
  4452. {
  4453. double e = Math.Abs(margin);
  4454. double a = va.x;
  4455. double b = vb.x;
  4456. if (a > b + e || a < b - e)
  4457. return 0;
  4458. a = va.y;
  4459. b = vb.y;
  4460. if (a > b + e || a < b - e)
  4461. return 0;
  4462. a = va.z;
  4463. b = vb.z;
  4464. if (a > b + e || a < b - e)
  4465. return 0;
  4466. return 1;
  4467. }
  4468. public LSL_Integer osApproxEquals(LSL_Rotation ra, LSL_Rotation rb)
  4469. {
  4470. double a = ra.x;
  4471. double b = rb.x;
  4472. if (a > b + 1.0e-6 || a < b - 1.0e-6)
  4473. return 0;
  4474. a = ra.y;
  4475. b = rb.y;
  4476. if (a > b + 1.0e-6 || a < b - 1.0e-6)
  4477. return 0;
  4478. a = ra.z;
  4479. b = rb.z;
  4480. if (a > b + 1.0e-6 || a < b - 1.0e-6)
  4481. return 0;
  4482. a = ra.s;
  4483. b = rb.s;
  4484. if (a > b + 1.0e-6 || a < b - 1.0e-6)
  4485. return 0;
  4486. return 1;
  4487. }
  4488. public LSL_Integer osApproxEquals(LSL_Rotation ra, LSL_Rotation rb, LSL_Float margin)
  4489. {
  4490. double e = Math.Abs(margin);
  4491. double a = ra.x;
  4492. double b = rb.x;
  4493. if (a > b + e || a < b - e)
  4494. return 0;
  4495. a = ra.y;
  4496. b = rb.y;
  4497. if (a > b + e || a < b - e)
  4498. return 0;
  4499. a = ra.z;
  4500. b = rb.z;
  4501. if (a > b + e || a < b - e)
  4502. return 0;
  4503. a = ra.s;
  4504. b = rb.s;
  4505. if (a > b + e || a < b - e)
  4506. return 0;
  4507. return 1;
  4508. }
  4509. public LSL_Key osGetInventoryLastOwner(LSL_String itemNameorid)
  4510. {
  4511. TaskInventoryItem item = UUID.TryParse(itemNameorid, out UUID itemID) ?
  4512. m_host.Inventory.GetInventoryItem(itemID) :
  4513. m_host.Inventory.GetInventoryItem(itemNameorid);
  4514. if (item is null)
  4515. return LSL_String.NullKey;
  4516. UUID id = item.LastOwnerID.IsNotZero() ? item.LastOwnerID : item.OwnerID;
  4517. return new LSL_Key(id.ToString());
  4518. }
  4519. public LSL_Key osGetInventoryItemKey(LSL_String name)
  4520. {
  4521. TaskInventoryItem item = m_host.Inventory.GetInventoryItem(name);
  4522. if (item is null)
  4523. return LSL_String.NullKey;
  4524. if ((item.CurrentPermissions
  4525. & (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify))
  4526. == (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify))
  4527. {
  4528. return new LSL_Key(item.ItemID.ToString());
  4529. }
  4530. return LSL_String.NullKey;
  4531. }
  4532. public LSL_String osGetInventoryName(LSL_Key itemId)
  4533. {
  4534. TaskInventoryItem item = null;
  4535. if (UUID.TryParse(itemId, out UUID itemID))
  4536. item = m_host.Inventory.GetInventoryItem(itemID);
  4537. return (item is null) ? LSL_String.Empty : item.Name;
  4538. }
  4539. public LSL_String osGetLinkInventoryName(LSL_Integer linkNumber, LSL_Key itemId)
  4540. {
  4541. TaskInventoryItem item = null;
  4542. if (UUID.TryParse(itemId, out UUID itemID))
  4543. {
  4544. SceneObjectPart part = GetSingleLinkPart(linkNumber);
  4545. if(part == null)
  4546. return LSL_String.Empty;
  4547. item = part.Inventory.GetInventoryItem(itemID);
  4548. }
  4549. return (item is null) ? LSL_String.Empty : item.Name;
  4550. }
  4551. public LSL_String osGetInventoryDesc(LSL_String itemNameorid)
  4552. {
  4553. TaskInventoryItem item = UUID.TryParse(itemNameorid, out UUID itemID) ?
  4554. m_host.Inventory.GetInventoryItem(itemID) :
  4555. m_host.Inventory.GetInventoryItem(itemNameorid);
  4556. return (item == null) ? LSL_String.Empty : item.Description;
  4557. }
  4558. public LSL_String osGetLinkInventoryDesc(LSL_Integer linkNumber, LSL_String itemNameorid)
  4559. {
  4560. SceneObjectPart part = GetSingleLinkPart(linkNumber);
  4561. if(part == null)
  4562. return LSL_String.Empty;
  4563. TaskInventoryItem item = UUID.TryParse(itemNameorid, out UUID itemID) ?
  4564. part.Inventory.GetInventoryItem(itemID) :
  4565. part.Inventory.GetInventoryItem(itemNameorid);
  4566. return (item == null) ? LSL_String.Empty : item.Description;
  4567. }
  4568. public LSL_Key osGetLinkInventoryKey(LSL_Integer linkNumber, LSL_String name, LSL_Integer type)
  4569. {
  4570. SceneObjectPart part = GetSingleLinkPart(linkNumber);
  4571. if(part == null)
  4572. return LSL_String.NullKey;
  4573. TaskInventoryItem item = part.Inventory.GetInventoryItem(name, type);
  4574. if (item is null)
  4575. return LSL_String.NullKey;
  4576. if ((item.CurrentPermissions
  4577. & (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify))
  4578. == (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify))
  4579. {
  4580. return new LSL_Key(item.AssetID.ToString());
  4581. }
  4582. return LSL_String.NullKey;
  4583. }
  4584. public LSL_List osGetLinkInventoryKeys(LSL_Integer linkNumber, LSL_Integer type)
  4585. {
  4586. LSL_List ret = new();
  4587. SceneObjectPart part = GetSingleLinkPart(linkNumber);
  4588. if(part == null)
  4589. return ret;
  4590. part.TaskInventory.LockItemsForRead(true);
  4591. foreach (KeyValuePair<UUID, TaskInventoryItem> inv in part.TaskInventory)
  4592. {
  4593. if (inv.Value.Type == type || type == -1 &&
  4594. (inv.Value.CurrentPermissions
  4595. & (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify))
  4596. == (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify))
  4597. ret.Add(inv.Value.AssetID.ToString());
  4598. }
  4599. part.TaskInventory.LockItemsForRead(false);
  4600. return ret;
  4601. }
  4602. public LSL_Key osGetLinkInventoryItemKey(LSL_Integer linkNumber, LSL_String name)
  4603. {
  4604. SceneObjectPart part = GetSingleLinkPart(linkNumber);
  4605. if(part == null)
  4606. return LSL_String.NullKey;
  4607. TaskInventoryItem item = part.Inventory.GetInventoryItem(name);
  4608. if (item is null)
  4609. return LSL_String.NullKey;
  4610. if ((item.CurrentPermissions
  4611. & (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify))
  4612. == (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify))
  4613. {
  4614. return new LSL_Key(item.ItemID.ToString());
  4615. }
  4616. return LSL_String.NullKey;
  4617. }
  4618. public LSL_List osGetInventoryItemKeys(LSL_Integer type)
  4619. {
  4620. LSL_List ret = new();
  4621. m_host.TaskInventory.LockItemsForRead(true);
  4622. foreach (KeyValuePair<UUID, TaskInventoryItem> inv in m_host.TaskInventory)
  4623. {
  4624. if ((inv.Value.Type == type || type == -1) &&
  4625. (inv.Value.CurrentPermissions
  4626. & (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify))
  4627. == (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify))
  4628. ret.Add(inv.Value.ItemID.ToString());
  4629. }
  4630. m_host.TaskInventory.LockItemsForRead(false);
  4631. return ret;
  4632. }
  4633. public LSL_List osGetLinkInventoryItemKeys(LSL_Integer linkNumber, LSL_Integer type)
  4634. {
  4635. LSL_List ret = new();
  4636. SceneObjectPart part = GetSingleLinkPart(linkNumber);
  4637. if(part == null)
  4638. return ret;
  4639. part.TaskInventory.LockItemsForRead(true);
  4640. foreach (KeyValuePair<UUID, TaskInventoryItem> inv in part.TaskInventory)
  4641. {
  4642. if (inv.Value.Type == type || type == -1 &&
  4643. (inv.Value.CurrentPermissions
  4644. & (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify))
  4645. == (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify))
  4646. ret.Add(inv.Value.ItemID.ToString());
  4647. }
  4648. part.TaskInventory.LockItemsForRead(false);
  4649. return ret;
  4650. }
  4651. public LSL_List osGetInventoryNames(LSL_Integer type)
  4652. {
  4653. LSL_List ret = new();
  4654. m_host.TaskInventory.LockItemsForRead(true);
  4655. foreach (KeyValuePair<UUID, TaskInventoryItem> inv in m_host.TaskInventory)
  4656. {
  4657. if (inv.Value.Type == type || type == -1)
  4658. ret.Add(inv.Value.Name);
  4659. }
  4660. m_host.TaskInventory.LockItemsForRead(false);
  4661. return ret;
  4662. }
  4663. public LSL_List osGetLinkInventoryNames(LSL_Integer linkNumber, LSL_Integer type)
  4664. {
  4665. LSL_List ret = new();
  4666. SceneObjectPart part = GetSingleLinkPart(linkNumber);
  4667. if(part == null)
  4668. return ret;
  4669. part.TaskInventory.LockItemsForRead(true);
  4670. foreach (KeyValuePair<UUID, TaskInventoryItem> inv in part.TaskInventory)
  4671. {
  4672. if (inv.Value.Type == type || type == -1)
  4673. ret.Add(inv.Value.Name);
  4674. }
  4675. part.TaskInventory.LockItemsForRead(false);
  4676. return ret;
  4677. }
  4678. public void osRemoveLinkInventory(LSL_Integer linkNumber, LSL_String name)
  4679. {
  4680. SceneObjectPart part = GetSingleLinkPart(linkNumber);
  4681. if(part == null)
  4682. return;
  4683. TaskInventoryItem item = part.Inventory.GetInventoryItem(name);
  4684. if (item == null)
  4685. return;
  4686. if (item.ItemID == m_item.ItemID)
  4687. throw new ScriptDeleteException();
  4688. else
  4689. part.Inventory.RemoveInventoryItem(item.ItemID);
  4690. }
  4691. ///<summary>
  4692. /// Give a specified item from a child prim inventory
  4693. /// to a destination (object or avatar).
  4694. ///</summary>
  4695. ///<param name="linkNumber">The link number of the child prim.</param>
  4696. ///<param name="destination">The UUID of the destination avatar or object.</param>
  4697. ///<param name="inventory">The name of the item to give.</param>
  4698. public void osGiveLinkInventory(LSL_Integer linkNumber, LSL_Key destination, LSL_String inventory)
  4699. {
  4700. if (!UUID.TryParse(destination, out UUID destId) || destId.IsZero())
  4701. return;
  4702. SceneObjectPart part = GetSingleLinkPart(linkNumber);
  4703. if(part == null)
  4704. return;
  4705. TaskInventoryItem item = part.Inventory.GetInventoryItem(inventory);
  4706. if (item is null)
  4707. return;
  4708. if (World.TryGetSceneObjectPart(destId, out _))
  4709. {
  4710. // destination is an object
  4711. World.MoveTaskInventoryItem(destId, part, item.ItemID);
  4712. }
  4713. else
  4714. {
  4715. if(!World.TryGetScenePresence(destId, out ScenePresence _))
  4716. {
  4717. UserAccount account = World.UserAccountService.GetUserAccount(World.RegionInfo.ScopeID, destId);
  4718. if (account == null)
  4719. {
  4720. GridUserInfo info = World.GridUserService.GetGridUserInfo(destId.ToString());
  4721. if(info == null || info.Online == false)
  4722. return;
  4723. }
  4724. }
  4725. // destination is an avatar
  4726. InventoryItemBase agentItem = World.MoveTaskInventoryItem(destId, UUID.Zero, part, item.ItemID, out string message);
  4727. if (agentItem is null)
  4728. {
  4729. m_LSL_Api.llSay(0, message);
  4730. return;
  4731. }
  4732. byte[] bucket = new byte[1];
  4733. bucket[0] = (byte)item.Type;
  4734. GridInstantMessage msg = new GridInstantMessage(World,
  4735. m_host.OwnerID, m_host.Name, destId,
  4736. (byte)InstantMessageDialog.TaskInventoryOffered,
  4737. m_host.OwnerID.Equals(m_host.GroupID), "'"+item.Name+"'. ("+m_host.Name+" is located at "+
  4738. World.RegionInfo.RegionName + " "+ m_host.AbsolutePosition.ToString() + ")",
  4739. agentItem.ID, true, m_host.AbsolutePosition,
  4740. bucket, true);
  4741. if (World.TryGetScenePresence(destId, out ScenePresence sp))
  4742. sp.ControllingClient.SendInstantMessage(msg);
  4743. else
  4744. m_TransferModule?.SendInstantMessage(msg, delegate(bool success) {});
  4745. //This delay should only occur when giving inventory to avatars.
  4746. ScriptSleep(3000);
  4747. }
  4748. }
  4749. public void osGiveLinkInventoryList(LSL_Integer linkNumber, LSL_Key destination, LSL_String category, LSL_List inventory)
  4750. {
  4751. if (inventory.Length == 0)
  4752. return;
  4753. SceneObjectPart part = GetSingleLinkPart(linkNumber);
  4754. if(part == null)
  4755. return;
  4756. if (!UUID.TryParse(destination, out UUID destID) || destID.IsZero())
  4757. return;
  4758. bool isNotOwner = true;
  4759. if (!World.TryGetSceneObjectPart(destID, out SceneObjectPart destSop))
  4760. {
  4761. if (!World.TryGetScenePresence(destID, out ScenePresence sp))
  4762. {
  4763. // we could check if it is a grid user and allow the transfer as in older code
  4764. // but that increases security risk
  4765. OSSLShoutError("osGiveLinkInventoryList: Unable to give list, destination not found");
  4766. ScriptSleep(100);
  4767. return;
  4768. }
  4769. isNotOwner = sp.UUID.NotEqual(m_host.OwnerID);
  4770. }
  4771. List<UUID> itemList = new(inventory.Length);
  4772. foreach (object item in inventory.Data)
  4773. {
  4774. string rawItemString = item.ToString();
  4775. TaskInventoryItem taskItem = (UUID.TryParse(rawItemString, out UUID itemID)) ?
  4776. part.Inventory.GetInventoryItem(itemID) : part.Inventory.GetInventoryItem(rawItemString);
  4777. if(taskItem is null)
  4778. continue;
  4779. if ((taskItem.CurrentPermissions & (uint)PermissionMask.Copy) == 0)
  4780. continue;
  4781. if (destSop is not null)
  4782. {
  4783. if(!World.Permissions.CanDoObjectInvToObjectInv(taskItem, m_host, destSop))
  4784. continue;
  4785. }
  4786. else
  4787. {
  4788. if(isNotOwner)
  4789. {
  4790. if ((taskItem.CurrentPermissions & (uint)PermissionMask.Transfer) == 0)
  4791. continue;
  4792. }
  4793. }
  4794. itemList.Add(taskItem.ItemID);
  4795. }
  4796. if (itemList.Count == 0)
  4797. {
  4798. OSSLShoutError("osGiveLinkInventoryList: Unable to give list, no items found");
  4799. ScriptSleep(100);
  4800. return;
  4801. }
  4802. UUID folderID = m_ScriptEngine.World.MoveTaskInventoryItems(destID, category, part, itemList, false);
  4803. if (folderID.IsZero())
  4804. {
  4805. OSSLShoutError("osGiveLinkInventoryList: Unable to give list");
  4806. ScriptSleep(100);
  4807. return;
  4808. }
  4809. if (destSop is not null)
  4810. {
  4811. ScriptSleep(100);
  4812. return;
  4813. }
  4814. if (m_TransferModule != null)
  4815. {
  4816. byte[] bucket = new byte[] { (byte)AssetType.Folder };
  4817. Vector3 pos = m_host.AbsolutePosition;
  4818. GridInstantMessage msg = new(World, m_host.OwnerID, m_host.Name, destID,
  4819. (byte)InstantMessageDialog.TaskInventoryOffered,
  4820. m_host.OwnerID.Equals(m_host.GroupID), string.Format("'{0}'", category), folderID, false, pos,bucket, false);
  4821. m_TransferModule.SendInstantMessage(msg, delegate(bool success) {});
  4822. }
  4823. ScriptSleep(3000);
  4824. }
  4825. public LSL_Key osGetLastChangedEventKey()
  4826. {
  4827. DetectParams detectedParams = m_ScriptEngine.GetDetectParams(m_item.ItemID, 0);
  4828. if (detectedParams is null)
  4829. return string.Empty;
  4830. return detectedParams.Key.ToString();
  4831. }
  4832. // returns PST or PDT wall clock
  4833. public LSL_Float osGetPSTWallclock()
  4834. {
  4835. if(PSTTimeZone is null)
  4836. return DateTime.Now.TimeOfDay.TotalSeconds;
  4837. DateTime time = TimeZoneInfo.ConvertTime(DateTime.UtcNow, PSTTimeZone);
  4838. return time.TimeOfDay.TotalSeconds;
  4839. }
  4840. public LSL_Rotation osSlerp(LSL_Rotation a, LSL_Rotation b, LSL_Float amount)
  4841. {
  4842. if(amount < 0)
  4843. amount= 0;
  4844. else if(amount > 1.0)
  4845. amount = 1.0;
  4846. a.Normalize();
  4847. b.Normalize();
  4848. return LSL_Rotation.Slerp(a, b, amount);
  4849. }
  4850. public LSL_Vector osSlerp(LSL_Vector a, LSL_Vector b, LSL_Float amount)
  4851. {
  4852. if (amount < 0)
  4853. amount = 0;
  4854. else if (amount > 1.0)
  4855. amount = 1.0;
  4856. return LSL_Vector.Slerp(a, b, amount);
  4857. }
  4858. public void osResetAllScripts(LSL_Integer linkset)
  4859. {
  4860. UUID me = m_item.ItemID;
  4861. List<TaskInventoryItem> scripts = new();
  4862. if(linkset != 0)
  4863. {
  4864. SceneObjectGroup sog = m_host.ParentGroup;
  4865. if(sog.inTransit || sog.IsDeleted)
  4866. return;
  4867. SceneObjectPart[] parts = sog.Parts;
  4868. for (int i = 0; i < parts.Length; i++)
  4869. {
  4870. scripts.AddRange(parts[i].Inventory.GetInventoryItems(InventoryType.LSL));
  4871. }
  4872. }
  4873. else
  4874. scripts.AddRange(m_host.Inventory.GetInventoryItems(InventoryType.LSL));
  4875. foreach(TaskInventoryItem script in scripts)
  4876. {
  4877. if(script.ItemID.Equals(me))
  4878. continue;
  4879. m_ScriptEngine.ResetScript(script.ItemID);
  4880. }
  4881. m_UrlModule?.ScriptRemoved(me);
  4882. m_ScriptEngine.ApiResetScript(me);
  4883. }
  4884. public LSL_Integer osIsNotValidNumber(LSL_Float v)
  4885. {
  4886. double d = v.value;
  4887. if (double.IsNaN(d))
  4888. return 1;
  4889. if (double.IsNegativeInfinity(d))
  4890. return 2;
  4891. if (double.IsPositiveInfinity(d))
  4892. return 3;
  4893. return 0;
  4894. }
  4895. public LSL_Vector osGetSitTargetPos()
  4896. {
  4897. return m_host.SitTargetPosition;
  4898. }
  4899. public LSL_Rotation osGetSitTargetRot()
  4900. {
  4901. return m_host.SitTargetOrientation;
  4902. }
  4903. public void osSetSitActiveRange(LSL_Float v)
  4904. {
  4905. float fv = (float)v.value;
  4906. if (fv > 128f)
  4907. fv = 128f;
  4908. if(m_host.SitActiveRange != fv)
  4909. {
  4910. m_host.SitActiveRange = fv;
  4911. m_host.ParentGroup.HasGroupChanged = true;
  4912. }
  4913. }
  4914. public void osSetLinkSitActiveRange(LSL_Integer linkNumber, LSL_Float v)
  4915. {
  4916. InitLSL();
  4917. float fv = (float)v.value;
  4918. if (fv > 128f)
  4919. fv = 128f;
  4920. bool changed = false;
  4921. List<SceneObjectPart> parts = m_LSL_Api.GetLinkParts(linkNumber);
  4922. for(int i = 0; i < parts.Count; ++i)
  4923. {
  4924. SceneObjectPart sop = parts[i];
  4925. if(sop.SitActiveRange != fv)
  4926. {
  4927. sop.SitActiveRange = fv;
  4928. changed = true;
  4929. }
  4930. }
  4931. if (changed)
  4932. m_host.ParentGroup.HasGroupChanged = true;
  4933. }
  4934. public LSL_Float osGetSitActiveRange()
  4935. {
  4936. return m_host.SitActiveRange;
  4937. }
  4938. public LSL_Float osGetLinkSitActiveRange(LSL_Integer linkNumber)
  4939. {
  4940. if (linkNumber == ScriptBaseClass.LINK_THIS)
  4941. return m_host.SitActiveRange;
  4942. if (linkNumber < 0)
  4943. return int.MinValue;
  4944. if (linkNumber < 2)
  4945. return m_host.ParentGroup.RootPart.SitActiveRange;
  4946. SceneObjectPart target = m_host.ParentGroup.GetLinkNumPart(linkNumber);
  4947. if (target is null)
  4948. return int.MinValue;
  4949. return target.SitActiveRange;
  4950. }
  4951. public void osSetStandTarget(LSL_Vector v)
  4952. {
  4953. // todo add limits ?
  4954. Vector3 old = m_host.StandOffset;
  4955. m_host.StandOffset = v;
  4956. if(!old.ApproxEquals(v))
  4957. m_host.ParentGroup.HasGroupChanged = true;
  4958. }
  4959. public void osSetLinkStandTarget(LSL_Integer linkNumber, LSL_Vector v)
  4960. {
  4961. // todo add limits ?
  4962. SceneObjectPart target;
  4963. if (linkNumber == ScriptBaseClass.LINK_THIS)
  4964. target = m_host;
  4965. else if (linkNumber < 0)
  4966. return;
  4967. else if (linkNumber < 2)
  4968. target = m_host.ParentGroup.RootPart;
  4969. else
  4970. target = m_host.ParentGroup.GetLinkNumPart(linkNumber);
  4971. if (target is null)
  4972. return;
  4973. Vector3 newv = v;
  4974. if (!newv.ApproxEquals(target.StandOffset))
  4975. {
  4976. target.StandOffset = v;
  4977. m_host.ParentGroup.HasGroupChanged = true;
  4978. }
  4979. }
  4980. public LSL_Vector osGetStandTarget()
  4981. {
  4982. return m_host.StandOffset;
  4983. }
  4984. public LSL_Vector osGetLinkStandTarget(LSL_Integer linkNumber)
  4985. {
  4986. if (linkNumber == ScriptBaseClass.LINK_THIS)
  4987. return m_host.StandOffset;
  4988. if (linkNumber < 0)
  4989. return Vector3.Zero;
  4990. if (linkNumber < 2)
  4991. return m_host.ParentGroup.RootPart.StandOffset;
  4992. SceneObjectPart target = m_host.ParentGroup.GetLinkNumPart(linkNumber);
  4993. if (target is null)
  4994. return Vector3.Zero;
  4995. return target.StandOffset;
  4996. }
  4997. public LSL_Integer osClearObjectAnimations()
  4998. {
  4999. return m_host.ClearObjectAnimations();
  5000. }
  5001. public LSL_Integer osReplaceAgentEnvironment(LSL_Key agentkey, LSL_Integer transition, LSL_String daycycle)
  5002. {
  5003. if(!string.IsNullOrEmpty(CheckThreatLevelTest(ThreatLevel.Moderate, "osReplaceAgentEnvironment")))
  5004. return -2;
  5005. if (!UUID.TryParse(agentkey, out UUID agentid))
  5006. return -4;
  5007. ScenePresence sp = World.GetScenePresence(agentid);
  5008. if(sp is null || sp.IsChildAgent || sp.IsNPC || sp.IsInTransit)
  5009. return -4;
  5010. if(string.IsNullOrEmpty(daycycle) || daycycle == ScriptBaseClass.NULL_KEY)
  5011. {
  5012. sp.Environment = null;
  5013. m_envModule.WindlightRefreshForced(sp, transition);
  5014. return 1;
  5015. }
  5016. UUID envID = ScriptUtils.GetAssetIdFromKeyOrItemName(m_host, daycycle);
  5017. if (envID.IsZero())
  5018. return -3;
  5019. AssetBase asset = World.AssetService.Get(envID.ToString());
  5020. if(asset is null || asset.Type != (byte)AssetType.Settings)
  5021. return -3;
  5022. // cant use stupid broken asset flags for subtype
  5023. try
  5024. {
  5025. OSD oenv = OSDParser.Deserialize(asset.Data);
  5026. ViewerEnvironment VEnv = m_envModule.GetRegionEnvironment().Clone();
  5027. if(!VEnv.CycleFromOSD(oenv))
  5028. return -3;
  5029. sp.Environment = VEnv;
  5030. m_envModule.WindlightRefreshForced(sp, transition);
  5031. }
  5032. catch
  5033. {
  5034. sp.Environment = null;
  5035. m_envModule.WindlightRefreshForced(sp, transition);
  5036. return -5;
  5037. }
  5038. return 1;
  5039. }
  5040. public LSL_Integer osReplaceParcelEnvironment(LSL_Integer transition, LSL_String daycycle)
  5041. {
  5042. if (!World.RegionInfo.EstateSettings.AllowEnvironmentOverride)
  5043. return -1;
  5044. ILandObject parcel = World.LandChannel.GetLandObject(m_host.GetWorldPosition().X, m_host.GetWorldPosition().Y);
  5045. if (parcel is null)
  5046. return -2;
  5047. if (!World.Permissions.CanEditParcelProperties(m_host.OwnerID, parcel, (GroupPowers.AllowEnvironment), true))
  5048. return -3;
  5049. ViewerEnvironment VEnv;
  5050. if (parcel.LandData.Environment is null)
  5051. VEnv = m_envModule.GetRegionEnvironment().Clone();
  5052. else
  5053. VEnv = parcel.LandData.Environment;
  5054. bool changed = false;
  5055. if (!string.IsNullOrEmpty(daycycle) && (daycycle != ScriptBaseClass.NULL_KEY))
  5056. {
  5057. UUID envID = ScriptUtils.GetAssetIdFromKeyOrItemName(m_host, daycycle);
  5058. if (envID.IsZero())
  5059. return -4;
  5060. AssetBase asset = World.AssetService.Get(envID.ToString());
  5061. if (asset is null || asset.Type != (byte)AssetType.Settings)
  5062. return -4;
  5063. // cant use stupid broken asset flags for subtype
  5064. try
  5065. {
  5066. OSD oenv = OSDParser.Deserialize(asset.Data);
  5067. if (!VEnv.CycleFromOSD(oenv))
  5068. return -5;
  5069. changed = true;
  5070. }
  5071. catch
  5072. {
  5073. return -5;
  5074. }
  5075. }
  5076. if (changed)
  5077. {
  5078. parcel.StoreEnvironment(VEnv);
  5079. m_envModule.WindlightRefresh(transition, false);
  5080. }
  5081. return 1;
  5082. }
  5083. public LSL_Integer osReplaceRegionEnvironment(LSL_Integer transition, LSL_String daycycle,
  5084. LSL_Float daylen, LSL_Float dayoffset,
  5085. LSL_Float altitude1, LSL_Float altitude2, LSL_Float altitude3)
  5086. {
  5087. if (!World.Permissions.CanIssueEstateCommand(m_host.OwnerID, true))
  5088. return -3;
  5089. ViewerEnvironment VEnv = m_envModule.GetRegionEnvironment().Clone();
  5090. bool changed = false;
  5091. if (!string.IsNullOrEmpty(daycycle) && (daycycle != ScriptBaseClass.NULL_KEY))
  5092. {
  5093. UUID envID = ScriptUtils.GetAssetIdFromKeyOrItemName(m_host, daycycle);
  5094. if (envID.IsZero())
  5095. return -4;
  5096. AssetBase asset = World.AssetService.Get(envID.ToString());
  5097. if (asset is null || asset.Type != (byte)AssetType.Settings)
  5098. return -4;
  5099. // cant use stupid broken asset flags for subtype
  5100. try
  5101. {
  5102. OSD oenv = OSDParser.Deserialize(asset.Data);
  5103. if (!VEnv.CycleFromOSD(oenv))
  5104. return -5;
  5105. changed = true;
  5106. }
  5107. catch
  5108. {
  5109. return -5;
  5110. }
  5111. }
  5112. if (daylen >= 4 && daylen <= 24 * 7)
  5113. {
  5114. int ll = VEnv.DayLength;
  5115. VEnv.DayLength = (int)(daylen * 3600f);
  5116. changed |= ll != VEnv.DayLength;
  5117. }
  5118. if (dayoffset >= -11.5 && dayoffset <= 11.5)
  5119. {
  5120. int lo = VEnv.DayLength;
  5121. if (dayoffset <= 0)
  5122. dayoffset+= 24;
  5123. VEnv.DayOffset = (int)(dayoffset * 3600f);
  5124. changed |= lo != VEnv.DayOffset;
  5125. }
  5126. bool needSort = false;
  5127. if (altitude1 > 0 && altitude1 < 4000 && VEnv.Altitudes[0] != (float)altitude1)
  5128. {
  5129. VEnv.Altitudes[0] = (float)altitude1;
  5130. needSort = true;
  5131. }
  5132. if (altitude2 > 0 && altitude2 < 4000 && VEnv.Altitudes[1] != (float)altitude2)
  5133. {
  5134. VEnv.Altitudes[1] = (float)altitude2;
  5135. needSort = true;
  5136. }
  5137. if (altitude3 > 0 && altitude2 < 4000 && VEnv.Altitudes[2] != (float)altitude3)
  5138. {
  5139. VEnv.Altitudes[2] = (float)altitude3;
  5140. needSort = true;
  5141. }
  5142. if(needSort)
  5143. {
  5144. VEnv.SortAltitudes();
  5145. changed = true;
  5146. }
  5147. if(changed)
  5148. {
  5149. m_envModule.StoreOnRegion(VEnv);
  5150. m_envModule.WindlightRefresh(transition);
  5151. }
  5152. return 1;
  5153. }
  5154. public LSL_Integer osResetEnvironment(LSL_Integer parcelOrRegion, LSL_Integer transition)
  5155. {
  5156. if (parcelOrRegion > 0)
  5157. {
  5158. if (!World.RegionInfo.EstateSettings.AllowEnvironmentOverride)
  5159. return -1;
  5160. ILandObject parcel = World.LandChannel.GetLandObject(m_host.GetWorldPosition().X, m_host.GetWorldPosition().Y);
  5161. if (parcel is null)
  5162. return -2;
  5163. if (!World.Permissions.CanEditParcelProperties(m_host.OwnerID, parcel, (GroupPowers.AllowEnvironment), true))
  5164. return -3;
  5165. if (parcel.LandData.Environment is null)
  5166. return 1;
  5167. parcel.StoreEnvironment(null);
  5168. m_envModule.WindlightRefresh(transition, false);
  5169. return 1;
  5170. }
  5171. if (!World.Permissions.CanIssueEstateCommand(m_host.OwnerID, true))
  5172. return -3;
  5173. m_envModule.StoreOnRegion(null);
  5174. m_envModule.WindlightRefresh(transition);
  5175. return 1;
  5176. }
  5177. public void osParticleSystem(LSL_List rules)
  5178. {
  5179. InitLSL();
  5180. m_LSL_Api.SetParticleSystem(m_host, rules, "osParticleSystem", true);
  5181. }
  5182. public void osLinkParticleSystem(LSL_Integer linknumber, LSL_List rules)
  5183. {
  5184. InitLSL();
  5185. List<SceneObjectPart> parts = m_LSL_Api.GetLinkParts(linknumber);
  5186. foreach (SceneObjectPart part in parts)
  5187. {
  5188. m_LSL_Api.SetParticleSystem(part, rules, "osLinkParticleSystem", true);
  5189. }
  5190. }
  5191. public LSL_Integer osNpcLookAt(LSL_Key npckey, LSL_Integer ltype, LSL_Key objkey, LSL_Vector offset)
  5192. {
  5193. if (World.GetNumberOfClients() == 0)
  5194. return 0;
  5195. if (ltype < 0 || ltype > ScriptBaseClass.NPCLOOKAT_CLEAR)
  5196. return -1;
  5197. if (!UUID.TryParse(npckey, out UUID npc))
  5198. return -2;
  5199. ScenePresence npcSP = World.GetScenePresence(npc);
  5200. if((npcSP is null) || !npcSP.IsNPC)
  5201. return -3;
  5202. if (!UUID.TryParse(objkey, out UUID obj))
  5203. return -4;
  5204. if(!obj.IsZero())
  5205. {
  5206. ScenePresence objSP = World.GetScenePresence(obj);
  5207. if(objSP == null)
  5208. {
  5209. SceneObjectPart objSOP = World.GetSceneObjectPart(obj);
  5210. if(objSOP == null)
  5211. return -5;
  5212. }
  5213. }
  5214. byte[] data = new byte[57];
  5215. npc.ToBytes(data, 0);
  5216. obj.ToBytes(data, 16);
  5217. Vector3d vd = new(offset.x, offset.y, offset.z);
  5218. vd.ToBytes(data, 32);
  5219. data[56] = (byte)(int)ltype;
  5220. OpenMetaverse.Packets.ViewerEffectPacket.EffectBlock effect = new()
  5221. {
  5222. AgentID = npc,
  5223. Color = new byte[4],
  5224. Duration = 0,
  5225. ID = UUID.Random(),
  5226. Type = 14,
  5227. TypeData = data
  5228. };
  5229. OpenMetaverse.Packets.ViewerEffectPacket.EffectBlock[] effectblock = new OpenMetaverse.Packets.ViewerEffectPacket.EffectBlock[1];
  5230. effectblock[0] = effect;
  5231. World.ForEachScenePresence(
  5232. sp =>
  5233. {
  5234. if(!sp.IsNPC && !sp.IsDeleted)
  5235. {
  5236. sp.ControllingClient.SendViewerEffect(effectblock);
  5237. }
  5238. });
  5239. return 0;
  5240. }
  5241. public LSL_Integer osAvatarType(LSL_Key avkey)
  5242. {
  5243. if (!UUID.TryParse(avkey.m_string, out UUID avId))
  5244. return -1;
  5245. ScenePresence av = World.GetScenePresence(avId);
  5246. if (av is null || av.IsDeleted || av.IsChildAgent)
  5247. return 0;
  5248. return av.IsNPC ? 2 : 1;
  5249. }
  5250. public LSL_Integer osAvatarType(LSL_String sFirstName, LSL_String sLastName)
  5251. {
  5252. ScenePresence av = World.GetScenePresence(sFirstName.m_string, sLastName.m_string);
  5253. if (av is null || av.IsDeleted || av.IsChildAgent)
  5254. return 0;
  5255. return av.IsNPC ? 2 : 1;
  5256. }
  5257. public void osListSortInPlace(LSL_List src, LSL_Integer stride, LSL_Integer ascending)
  5258. {
  5259. src.SortInPlace(stride, ascending == 1);
  5260. }
  5261. public void osListSortInPlaceStrided(LSL_List src, LSL_Integer stride, LSL_Integer stride_index, LSL_Integer ascending)
  5262. {
  5263. src.SortInPlace(stride, stride_index, ascending == 1);
  5264. }
  5265. public LSL_List osGetParcelDetails(LSL_Key id, LSL_List param)
  5266. {
  5267. if (!UUID.TryParse(id, out UUID parcelID))
  5268. return new LSL_List(0);
  5269. InitLSL();
  5270. if (m_LSL_Api is null)
  5271. return new LSL_List(0);
  5272. ILandObject parcel = World.LandChannel.GetLandObject(parcelID);
  5273. if (parcel is null)
  5274. return new LSL_List(0);
  5275. return m_LSL_Api.GetParcelDetails(parcel, param);
  5276. }
  5277. public LSL_List osGetParcelIDs()
  5278. {
  5279. //if(!World.Permissions.IsEstateManager(m_host.OwnerID))
  5280. // return new LSL_List();
  5281. List<ILandObject> parcels = World.LandChannel.AllParcels();
  5282. if (parcels is null || parcels.Count == 0)
  5283. return new LSL_List();
  5284. LSL_List ret = new();
  5285. foreach (ILandObject obj in parcels)
  5286. {
  5287. // some sanity check
  5288. if(obj.GlobalID.IsZero())
  5289. continue;
  5290. if(obj.LandData is null || obj.LandData.Area == 0)
  5291. continue;
  5292. ret.Add(new LSL_Key(obj.GlobalID.ToString()));
  5293. }
  5294. return ret;
  5295. }
  5296. public LSL_Key osGetParcelID()
  5297. {
  5298. ILandObject parcel = World.LandChannel.GetLandObject(m_host.AbsolutePosition);
  5299. return parcel is null ? ScriptBaseClass.NULL_KEY : new LSL_Key(parcel.GlobalID.ToString());
  5300. }
  5301. // old List2ListStrided for compatibility
  5302. /// <summary>
  5303. /// Elements in the source list starting with 0 and then
  5304. /// every i+stride. If the stride is negative then the scan
  5305. /// Only those elements that are also in the specified
  5306. /// range are included in the result.
  5307. /// </summary>
  5308. public LSL_List osOldList2ListStrided(LSL_List src, int start, int end, int stride)
  5309. {
  5310. LSL_List result = new();
  5311. int[] si = new int[2];
  5312. int[] ei = new int[2];
  5313. bool twopass = false;
  5314. // First step is always to deal with negative indices
  5315. if (start < 0)
  5316. start += src.Length;
  5317. if (end < 0)
  5318. end += src.Length;
  5319. // Out of bounds indices are OK, just trim them
  5320. // accordingly
  5321. if (start > src.Length)
  5322. start = src.Length;
  5323. if (end > src.Length)
  5324. end = src.Length;
  5325. if (stride == 0)
  5326. stride = 1;
  5327. // There may be one or two ranges to be considered
  5328. if (start != end)
  5329. {
  5330. if (start <= end)
  5331. {
  5332. si[0] = start;
  5333. ei[0] = end;
  5334. }
  5335. else
  5336. {
  5337. si[1] = start;
  5338. ei[1] = src.Length;
  5339. si[0] = 0;
  5340. ei[0] = end;
  5341. twopass = true;
  5342. }
  5343. // The scan always starts from the beginning of the
  5344. // source list, but members are only selected if they
  5345. // fall within the specified sub-range. The specified
  5346. // range values are inclusive.
  5347. // A negative stride reverses the direction of the
  5348. // scan producing an inverted list as a result.
  5349. if (stride > 0)
  5350. {
  5351. for (int i = 0; i < src.Length; i += stride)
  5352. {
  5353. if (i<=ei[0] && i>=si[0])
  5354. result.Add(src.Data[i]);
  5355. if (twopass && i>=si[1] && i<=ei[1])
  5356. result.Add(src.Data[i]);
  5357. }
  5358. }
  5359. else if (stride < 0)
  5360. {
  5361. for (int i = src.Length - 1; i >= 0; i += stride)
  5362. {
  5363. if (i <= ei[0] && i >= si[0])
  5364. result.Add(src.Data[i]);
  5365. if (twopass && i >= si[1] && i <= ei[1])
  5366. result.Add(src.Data[i]);
  5367. }
  5368. }
  5369. }
  5370. else
  5371. {
  5372. if (start%stride == 0)
  5373. {
  5374. result.Add(src.Data[start]);
  5375. }
  5376. }
  5377. return result;
  5378. }
  5379. public LSL_Integer osGetPrimCount()
  5380. {
  5381. return m_host.ParentGroup.PrimCount;
  5382. }
  5383. public LSL_Integer osGetPrimCount(LSL_Key object_id)
  5384. {
  5385. if (!UUID.TryParse(object_id.m_string, out UUID id) || id.IsZero())
  5386. return 0;
  5387. return World.TryGetSceneObjectPart(id, out SceneObjectPart part) ? part.ParentGroup.PrimCount : 0;
  5388. }
  5389. public LSL_Integer osGetSittingAvatarsCount()
  5390. {
  5391. return m_host.ParentGroup.GetSittingAvatarsCount();
  5392. }
  5393. public LSL_Integer osGetSittingAvatarsCount(LSL_Key object_id)
  5394. {
  5395. if (!UUID.TryParse(object_id.m_string, out UUID id) || id.IsZero())
  5396. return 0;
  5397. return World.TryGetSceneObjectPart(id, out SceneObjectPart part) ? part.ParentGroup.GetSittingAvatarsCount() : 0;
  5398. }
  5399. public LSL_String osAESEncrypt(string secret, string plainText)
  5400. {
  5401. if(string.IsNullOrEmpty(secret) || string.IsNullOrEmpty(plainText))
  5402. return LSL_String.Empty;
  5403. ReadOnlySpan<char> ret = Util.AESEncrypt(secret.AsSpan(), plainText.AsSpan());
  5404. if(ret.Length == 0)
  5405. {
  5406. OSSLShoutError("osAESEncrypt: Failed to encrypt!");
  5407. return LSL_String.Empty;
  5408. }
  5409. return ret.ToString();
  5410. }
  5411. public LSL_String osAESDecrypt(string secret, string encryptedText)
  5412. {
  5413. if(string.IsNullOrEmpty(secret) || string.IsNullOrEmpty(encryptedText))
  5414. return LSL_String.Empty;
  5415. ReadOnlySpan<char> ret = Util.AESDecrypt(secret.AsSpan(), encryptedText.AsSpan());
  5416. if(ret.Length == 0)
  5417. {
  5418. OSSLShoutError("osAESDecrypt: Failed to Decrypt!");
  5419. return LSL_String.Empty;
  5420. }
  5421. return ret.ToString();
  5422. }
  5423. public LSL_String osAESEncryptTo(string secret, string plainText, string ivString)
  5424. {
  5425. if(string.IsNullOrEmpty(secret) || string.IsNullOrEmpty(plainText) || string.IsNullOrEmpty(ivString))
  5426. return LSL_String.Empty;
  5427. ReadOnlySpan<char> ret = Util.AESEncryptTo(secret.AsSpan(), plainText.AsSpan(), ivString.AsSpan());
  5428. if (ret.Length == 0)
  5429. {
  5430. OSSLShoutError("osAESEncryptTo: Failed to encrypt!");
  5431. return LSL_String.Empty;
  5432. }
  5433. return ret.ToString();
  5434. }
  5435. public LSL_String osAESDecryptFrom(string secret, string encryptedText, string ivString)
  5436. {
  5437. if(string.IsNullOrEmpty(secret) || string.IsNullOrEmpty(encryptedText) || string.IsNullOrEmpty(ivString))
  5438. return LSL_String.Empty;
  5439. ReadOnlySpan<char> ret = Util.AESDecryptFrom(secret.AsSpan(), encryptedText.AsSpan(), ivString.AsSpan());
  5440. if (ret.Length == 0)
  5441. {
  5442. OSSLShoutError("osAESDecryptFrom: Failed to decrypt!");
  5443. return LSL_String.Empty;
  5444. }
  5445. return ret.ToString();
  5446. }
  5447. public LSL_Vector osGetLinkColor(LSL_Integer link, LSL_Integer face)
  5448. {
  5449. SceneObjectPart linkedPart = link.value switch
  5450. {
  5451. ScriptBaseClass.LINK_ROOT => m_host.ParentGroup.RootPart,
  5452. ScriptBaseClass.LINK_THIS => m_host,
  5453. _ => m_host.ParentGroup.GetLinkNumPart(link.value)
  5454. };
  5455. if (linkedPart != null)
  5456. {
  5457. InitLSL();
  5458. return m_LSL_Api.GetColor(linkedPart, face.value);
  5459. }
  5460. return LSL_Vector.Zero;
  5461. }
  5462. public LSL_Vector osTemperature2sRGB(LSL_Float dtemp)
  5463. {
  5464. //aproximate fit to http://www.vendian.org/mncharity/dir3/blackbody/ 10degree D65 tables
  5465. float temp = (float)dtemp.value;
  5466. if (temp <= 1000f)
  5467. return new LSL_Vector(1.0, 0.0401, 0);
  5468. else if (temp >= 40000f)
  5469. return new LSL_Vector(0.3277, 0.5022, 1.0);
  5470. float green;
  5471. if (temp < 6600f)
  5472. {
  5473. green = temp - 1000f;
  5474. green = ((((-7.87308e-13f * green) - 7.10085e-9f) * green) + 0.00022693f) * green + 0.0374249f;
  5475. green = Math.Clamp(green, 0, 1.0f);
  5476. if (temp <= 19.0f)
  5477. return new LSL_Vector(1.0, green, 0);
  5478. float blue = temp - 1900f;
  5479. blue = ((((-5.97E-12f * blue) + 5.49E-08f) * blue) + 8.85465E-05f) * blue - 0.0058959f;
  5480. blue = Math.Clamp(blue, 0f, 1.0f);
  5481. return new LSL_Vector(1.0, green, blue);
  5482. }
  5483. temp = 0.01f * (temp - 6000f);
  5484. float red = 1.897315f * MathF.Pow(temp, -0.346837f) + 0.0622044f;
  5485. red = Math.Clamp(red, 0, 1.0f);
  5486. green = 1.261989f * MathF.Pow(temp, -0.251708f) + 0.200836f;
  5487. green = Math.Clamp(green, 0, 1.0f);
  5488. return new LSL_Vector(red, green, 1.0f);
  5489. }
  5490. }
  5491. }