SceneObjectGroup.cs 195 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494
  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 OpenMetaverse;
  28. using OpenMetaverse.Packets;
  29. using OpenSim.Framework;
  30. using OpenSim.Region.Framework.Interfaces;
  31. using OpenSim.Region.Framework.Scenes.Serialization;
  32. using OpenSim.Region.PhysicsModules.SharedBase;
  33. using System;
  34. using System.Collections.Generic;
  35. using System.Drawing;
  36. using System.Linq;
  37. using System.Threading;
  38. using System.Xml;
  39. using PermissionMask = OpenSim.Framework.PermissionMask;
  40. namespace OpenSim.Region.Framework.Scenes
  41. {
  42. // this is not the right place for this
  43. // for now it must match similar enums duplicated on scritp engines
  44. public enum ScriptEventCode : int
  45. {
  46. None = -1,
  47. attach = 0,
  48. state_exit = 1,
  49. timer = 2,
  50. touch = 3,
  51. collision = 4,
  52. collision_end = 5,
  53. collision_start = 6,
  54. control = 7,
  55. dataserver = 8,
  56. email = 9,
  57. http_response = 10,
  58. land_collision = 11,
  59. land_collision_end = 12,
  60. land_collision_start = 13,
  61. at_target = 14,
  62. listen = 15,
  63. money = 16,
  64. moving_end = 17,
  65. moving_start = 18,
  66. not_at_rot_target = 19,
  67. not_at_target = 20,
  68. touch_start = 21,
  69. object_rez = 22,
  70. remote_data = 23,
  71. at_rot_target = 24,
  72. transaction_result = 25,
  73. //
  74. //
  75. run_time_permissions = 28,
  76. touch_end = 29,
  77. state_entry = 30,
  78. //
  79. //
  80. changed = 33,
  81. link_message = 34,
  82. no_sensor = 35,
  83. on_rez = 36,
  84. sensor = 37,
  85. http_request = 38,
  86. path_update = 40,
  87. linkset_data = 41,
  88. // marks highest numbered event
  89. Size = 42
  90. }
  91. // this is not the right place for this
  92. // for now it must match similar enums duplicated on scritp engines
  93. // ignore this flags, do not use .net flags handle, it is bad
  94. [Flags]
  95. public enum scriptEvents : ulong
  96. {
  97. None = 0,
  98. attach = 1,
  99. state_exit = 1UL << 1,
  100. timer = 1UL << 2,
  101. touch = 1UL << 3,
  102. collision = 1UL << 4,
  103. collision_end = 1UL << 5,
  104. collision_start = 1UL << 6,
  105. control = 1UL << 7,
  106. dataserver = 1UL << 8,
  107. email = 1UL << 9,
  108. http_response = 1UL << 10,
  109. land_collision = 1UL << 11,
  110. land_collision_end = 1UL << 12,
  111. land_collision_start = 1UL << 13,
  112. at_target = 1UL << 14,
  113. listen = 1UL << 15,
  114. money = 1UL << 16,
  115. moving_end = 1UL << 17,
  116. moving_start = 1UL << 18,
  117. not_at_rot_target = 1UL << 19,
  118. not_at_target = 1UL << 20,
  119. touch_start = 1UL << 21,
  120. object_rez = 1UL << 22,
  121. remote_data = 1UL << 23,
  122. at_rot_target = 1UL << 24,
  123. transaction_result = 1UL << 25,
  124. //
  125. //
  126. run_time_permissions = 1UL << 28,
  127. touch_end = 1UL << 29,
  128. state_entry = 1UL << 30,
  129. //
  130. //
  131. changed = 1UL << 33,
  132. link_message = 1UL << 34,
  133. no_sensor = 1UL << 35,
  134. on_rez = 1UL << 36,
  135. sensor = 1UL << 37,
  136. http_request = 1UL << 38,
  137. path_update = 1UL << 40,
  138. linkset_data = 1UL << 41,
  139. anytouch = touch | touch_end | touch_start,
  140. anyTarget = at_target | not_at_target | at_rot_target | not_at_rot_target,
  141. anyobjcollision = collision | collision_end | collision_start,
  142. anylandcollision = land_collision | land_collision_end | land_collision_start
  143. }
  144. public struct scriptPosTarget
  145. {
  146. public Vector3 targetPos;
  147. public float tolerance;
  148. public int handle;
  149. public UUID scriptID;
  150. }
  151. public struct scriptRotTarget
  152. {
  153. public Quaternion targetRot;
  154. public float tolerance;
  155. public int handle;
  156. public UUID scriptID;
  157. }
  158. public delegate void PrimCountTaintedDelegate();
  159. /// <summary>
  160. /// A scene object group is conceptually an object in the scene. The object is constituted of SceneObjectParts
  161. /// (often known as prims), one of which is considered the root part.
  162. /// </summary>
  163. public partial class SceneObjectGroup : EntityBase, ISceneObject, IDisposable
  164. {
  165. // Axis selection bitmask used by SetAxisRotation()
  166. // Just happen to be the same bits used by llSetStatus() and defined in ScriptBaseClass.
  167. public enum axisSelect : int
  168. {
  169. STATUS_ROTATE_X = 0x002,
  170. STATUS_ROTATE_Y = 0x004,
  171. STATUS_ROTATE_Z = 0x008,
  172. NOT_STATUS_ROTATE_X = 0xFD,
  173. NOT_STATUS_ROTATE_Y = 0xFB,
  174. NOT_STATUS_ROTATE_Z = 0xF7
  175. }
  176. // private PrimCountTaintedDelegate handlerPrimCountTainted = null;
  177. public bool IsViewerCachable
  178. {
  179. get
  180. {
  181. // needs more exclusion ?
  182. return(Backup && !IsTemporary && !inTransit && !UsesPhysics && !IsSelected && !IsAttachmentCheckFull() &&
  183. !RootPart.Shape.MeshFlagEntry && // animations are not sent correctly for now
  184. RootPart.KeyframeMotion is null &&
  185. (DateTime.UtcNow.Ticks - timeLastChanged > 3000000000) //&& //3000000000 is 5min
  186. //(DateTime.UtcNow.Ticks - timeLastChanged > 36000000000) //&& //36000000000 is one hour
  187. );
  188. }
  189. }
  190. /// <summary>
  191. /// Signal whether the non-inventory attributes of any prims in the group have changed
  192. /// since the group's last persistent backup
  193. /// </summary>
  194. private bool m_hasGroupChanged = false;
  195. private long timeFirstChanged = 0;
  196. private long timeLastChanged = 0;
  197. private long m_maxPersistTime = 0;
  198. private long m_minPersistTime = 0;
  199. /// <summary>
  200. /// This indicates whether the object has changed such that it needs to be repersisted to permenant storage
  201. /// (the database).
  202. /// </summary>
  203. /// <remarks>
  204. /// Ultimately, this should be managed such that region modules can change it at the end of a set of operations
  205. /// so that either all changes are preserved or none at all. However, currently, a large amount of internal
  206. /// code will set this anyway when some object properties are changed.
  207. /// </remarks>
  208. public bool HasGroupChanged
  209. {
  210. set
  211. {
  212. if (value)
  213. {
  214. if (Backup)
  215. m_scene.SceneGraph.FireChangeBackup(this);
  216. timeLastChanged = DateTime.UtcNow.Ticks;
  217. if (!m_hasGroupChanged)
  218. timeFirstChanged = timeLastChanged;
  219. if (m_rootPart is not null && m_scene is not null)
  220. {
  221. if (m_scene.GetRootAgentCount() == 0)
  222. {
  223. //If the region is empty, this change has been made by an automated process
  224. //and thus we delay the persist time by a random amount between 1.5 and 2.5.
  225. float factor = 2.0f;
  226. m_maxPersistTime = (long)(m_scene.m_persistAfter * factor);
  227. m_minPersistTime = (long)(m_scene.m_dontPersistBefore * factor);
  228. }
  229. else
  230. {
  231. m_maxPersistTime = m_scene.m_persistAfter;
  232. m_minPersistTime = m_scene.m_dontPersistBefore;
  233. }
  234. }
  235. }
  236. m_hasGroupChanged = value;
  237. //m_log.DebugFormat(
  238. // "[SCENE OBJECT GROUP]: HasGroupChanged set to {0} for {1} {2}", m_hasGroupChanged, Name, LocalId);
  239. }
  240. get { return m_hasGroupChanged; }
  241. }
  242. public bool TemporaryInstance = false;
  243. private bool m_groupContainsForeignPrims = false;
  244. /// <summary>
  245. /// Whether the group contains prims that came from a different group. This happens when
  246. /// linking or delinking groups. The implication is that until the group is persisted,
  247. /// the prims in the database still use the old SceneGroupID. That's a problem if the group
  248. /// is deleted, because we delete groups by searching for prims by their SceneGroupID.
  249. /// </summary>
  250. public bool GroupContainsForeignPrims
  251. {
  252. private set
  253. {
  254. m_groupContainsForeignPrims = value;
  255. if (m_groupContainsForeignPrims)
  256. HasGroupChanged = true;
  257. }
  258. get { return m_groupContainsForeignPrims; }
  259. }
  260. public bool HasGroupChangedDueToDelink { get; set; }
  261. private bool isTimeToPersist()
  262. {
  263. if (IsSelected || IsDeleted || IsAttachment)
  264. return false;
  265. if (!m_hasGroupChanged)
  266. return false;
  267. if (m_scene.ShuttingDown)
  268. return true;
  269. if (m_minPersistTime == 0 || m_maxPersistTime == 0)
  270. {
  271. m_maxPersistTime = m_scene.m_persistAfter;
  272. m_minPersistTime = m_scene.m_dontPersistBefore;
  273. }
  274. long currentTime = DateTime.UtcNow.Ticks;
  275. if (timeLastChanged == 0) timeLastChanged = currentTime;
  276. if (timeFirstChanged == 0) timeFirstChanged = currentTime;
  277. return currentTime - timeLastChanged > m_minPersistTime || currentTime - timeFirstChanged > m_maxPersistTime;
  278. }
  279. /// <summary>
  280. /// Is this scene object acting as an attachment?
  281. /// </summary>
  282. public bool IsAttachment { get; set; }
  283. /// <summary>
  284. /// The avatar to which this scene object is attached.
  285. /// </summary>
  286. /// <remarks>
  287. /// If we're not attached to an avatar then this is UUID.Zero
  288. /// </remarks>
  289. public UUID AttachedAvatar { get; set; }
  290. /// <summary>
  291. /// Attachment point of this scene object to an avatar.
  292. /// </summary>
  293. /// <remarks>
  294. /// 0 if we're not attached to anything
  295. /// </remarks>
  296. public uint AttachmentPoint
  297. {
  298. get
  299. {
  300. return m_rootPart.Shape.State;
  301. }
  302. set
  303. {
  304. IsAttachment = value != 0;
  305. m_rootPart.Shape.State = (byte)value;
  306. }
  307. }
  308. /// <summary>
  309. /// If this scene object has an attachment point then indicate whether there is a point where
  310. /// attachments are perceivable by avatars other than the avatar to which this object is attached.
  311. /// </summary>
  312. /// <remarks>
  313. /// HUDs are not perceivable by other avatars.
  314. /// </remarks>
  315. public bool HasPrivateAttachmentPoint
  316. {
  317. get
  318. {
  319. return AttachmentPoint >= (uint)OpenMetaverse.AttachmentPoint.HUDCenter2
  320. && AttachmentPoint <= (uint)OpenMetaverse.AttachmentPoint.HUDBottomRight;
  321. }
  322. }
  323. public void ClearPartAttachmentData()
  324. {
  325. AttachmentPoint = 0;
  326. // Don't zap trees
  327. if (RootPart.Shape.PCode == (byte)PCode.Tree ||
  328. RootPart.Shape.PCode == (byte)PCode.NewTree)
  329. return;
  330. // Even though we don't use child part state parameters for attachments any more, we still need to set
  331. // these to zero since having them non-zero in rezzed scene objects will crash some clients. Even if
  332. // we store them correctly, scene objects that we receive from elsewhere might not.
  333. foreach (SceneObjectPart part in Parts)
  334. part.Shape.State = 0;
  335. }
  336. /// <summary>
  337. /// Is this scene object phantom?
  338. /// </summary>
  339. /// <remarks>
  340. /// Updating must currently take place through UpdatePrimFlags()
  341. /// </remarks>
  342. public bool IsPhantom
  343. {
  344. get { return (RootPart.Flags & PrimFlags.Phantom) != 0; }
  345. }
  346. /// <summary>
  347. /// Does this scene object use physics?
  348. /// </summary>
  349. /// <remarks>
  350. /// Updating must currently take place through UpdatePrimFlags()
  351. /// </remarks>
  352. public bool UsesPhysics
  353. {
  354. get { return (RootPart.Flags & PrimFlags.Physics) != 0; }
  355. }
  356. /// <summary>
  357. /// Is this scene object temporary?
  358. /// </summary>
  359. /// <remarks>
  360. /// Updating must currently take place through UpdatePrimFlags()
  361. /// </remarks>
  362. public bool IsTemporary
  363. {
  364. get { return (RootPart.Flags & PrimFlags.TemporaryOnRez) != 0; }
  365. }
  366. public bool IsVolumeDetect
  367. {
  368. get { return RootPart.VolumeDetectActive; }
  369. }
  370. /// <summary>
  371. /// Is this entity set to be saved in persistent storage?
  372. /// </summary>
  373. public bool Backup { get; private set; }
  374. protected MapAndArray<UUID, SceneObjectPart> m_parts = new();
  375. protected ulong m_regionHandle;
  376. protected SceneObjectPart m_rootPart;
  377. // private Dictionary<UUID, scriptEvents> m_scriptEvents = new Dictionary<UUID, scriptEvents>();
  378. private Dictionary<int, scriptPosTarget> m_targets = new();
  379. private Dictionary<int, scriptRotTarget> m_rotTargets = new();
  380. private Dictionary<UUID, List<int>> m_targetsByScript = new();
  381. public Dictionary<int, scriptPosTarget> AtTargets
  382. {
  383. get { return m_targets; }
  384. }
  385. public Dictionary<int, scriptRotTarget> RotTargets
  386. {
  387. get { return m_rotTargets; }
  388. }
  389. private bool m_scriptListens_atTarget;
  390. private bool m_scriptListens_notAtTarget;
  391. private bool m_scriptListens_atRotTarget;
  392. private bool m_scriptListens_notAtRotTarget;
  393. public bool m_dupeInProgress = false;
  394. internal Dictionary<UUID, string> m_savedScriptState;
  395. public string RezStringParameter = null;
  396. public UUID MonitoringObject { get; set; }
  397. #region Properties
  398. /// <summary>
  399. /// The name of an object grouping is always the same as its root part
  400. /// </summary>
  401. public override string Name
  402. {
  403. get { return RootPart.Name; }
  404. set { RootPart.Name = value; }
  405. }
  406. public string Description
  407. {
  408. get { return RootPart.Description; }
  409. set { RootPart.Description = value; }
  410. }
  411. /// <summary>
  412. /// Added because the Parcel code seems to use it
  413. /// but not sure a object should have this
  414. /// as what does it tell us? that some avatar has selected it (but not what Avatar/user)
  415. /// think really there should be a list (or whatever) in each scenepresence
  416. /// saying what prim(s) that user has selected.
  417. /// </summary>
  418. protected bool m_isSelected = false;
  419. /// <summary>
  420. /// Number of prims in this group
  421. /// </summary>
  422. public int PrimCount
  423. {
  424. get { return m_parts.Count; }
  425. }
  426. //protected Quaternion m_rotation = Quaternion.Identity;
  427. //public virtual Quaternion Rotation
  428. //{
  429. // get { return m_rotation; }
  430. // set { m_rotation = value; }
  431. //}
  432. public Quaternion GroupRotation
  433. {
  434. get { return m_rootPart.RotationOffset; }
  435. }
  436. public Vector3 GroupScale
  437. {
  438. get
  439. {
  440. SceneObjectPart[] parts = m_parts.GetArray();
  441. SceneObjectPart part;
  442. Vector3 partscale;
  443. float ftmp;
  444. float minScaleX = float.MaxValue;
  445. float minScaleY = float.MaxValue;
  446. float minScaleZ = float.MaxValue;
  447. float maxScaleX = 0f;
  448. float maxScaleY = 0f;
  449. float maxScaleZ = 0f;
  450. for (int i = 0; i < parts.Length; i++)
  451. {
  452. part = parts[i];
  453. partscale = part.Scale + part.OffsetPosition;
  454. ftmp = partscale.X;
  455. if (ftmp < minScaleX)
  456. minScaleX = ftmp;
  457. if (ftmp > maxScaleX)
  458. maxScaleX = ftmp;
  459. ftmp = partscale.Y;
  460. if (ftmp < minScaleY)
  461. minScaleY = ftmp;
  462. if (ftmp > maxScaleY)
  463. maxScaleY = ftmp;
  464. ftmp = partscale.Z;
  465. if (ftmp < minScaleZ)
  466. minScaleZ = ftmp;
  467. if (ftmp > maxScaleZ)
  468. maxScaleZ = ftmp;
  469. }
  470. partscale.X = (minScaleX > maxScaleX) ? minScaleX : maxScaleX;
  471. partscale.Y = (minScaleY > maxScaleY) ? minScaleY : maxScaleY;
  472. partscale.Z = (minScaleZ > maxScaleZ) ? minScaleZ : maxScaleZ;
  473. return partscale;
  474. }
  475. }
  476. public UUID GroupID
  477. {
  478. get { return m_rootPart.GroupID; }
  479. set { m_rootPart.GroupID = value; }
  480. }
  481. public SceneObjectPart[] Parts
  482. {
  483. get { return m_parts.GetArray(); }
  484. }
  485. public bool ContainsPart(UUID partID)
  486. {
  487. return m_parts.ContainsKey(partID);
  488. }
  489. /// <summary>
  490. /// Does this group contain the given part?
  491. /// <param name="localID"></param>
  492. /// <returns></returns>
  493. public bool ContainsPart(uint localID)
  494. {
  495. SceneObjectPart[] parts = m_parts.GetArray();
  496. for (int i = 0; i < parts.Length; i++)
  497. {
  498. if (parts[i].LocalId == localID)
  499. return true;
  500. }
  501. return false;
  502. }
  503. /// <value>
  504. /// The root part of this scene object
  505. /// </value>
  506. public SceneObjectPart RootPart
  507. {
  508. get { return m_rootPart; }
  509. }
  510. public ulong RegionHandle
  511. {
  512. get { return m_regionHandle; }
  513. set
  514. {
  515. m_regionHandle = value;
  516. SceneObjectPart[] parts = m_parts.GetArray();
  517. for (int i = 0; i < parts.Length; i++)
  518. parts[i].RegionHandle = value;
  519. }
  520. }
  521. /// <summary>
  522. /// Check both the attachment property and the relevant properties of the underlying root part.
  523. /// </summary>
  524. /// <remarks>
  525. /// This is necessary in some cases, particularly when a scene object has just crossed into a region and doesn't
  526. /// have the IsAttachment property yet checked.
  527. ///
  528. /// FIXME: However, this should be fixed so that this property
  529. /// propertly reflects the underlying status.
  530. /// </remarks>
  531. /// <returns></returns>
  532. public bool IsAttachmentCheckFull()
  533. {
  534. return (IsAttachment ||
  535. (m_rootPart.Shape.PCode == (byte)PCodeEnum.Primitive && m_rootPart.Shape.State != 0));
  536. }
  537. private struct avtocrossInfo
  538. {
  539. public ScenePresence av;
  540. public uint ParentID;
  541. }
  542. public LinksetData LinksetData;
  543. public bool inTransit = false;
  544. private delegate SceneObjectGroup SOGCrossDelegate(SceneObjectGroup sog,Vector3 pos, TeleportObjectData tpData);
  545. /// <summary>
  546. /// The absolute position of this scene object in the scene
  547. /// </summary>
  548. public override Vector3 AbsolutePosition
  549. {
  550. get { return m_rootPart.GroupPosition; }
  551. set
  552. {
  553. Vector3 val = value;
  554. if (Scene is not null
  555. && !Scene.PositionIsInCurrentRegion(val)
  556. && !IsAttachmentCheckFull()
  557. && !Scene.LoadingPrims
  558. && !Scene.DisableObjectTransfer
  559. )
  560. {
  561. if (!inTransit)
  562. {
  563. inTransit = true;
  564. SceneObjectGroup sog = this;
  565. Util.FireAndForget(delegate
  566. {
  567. sog = CrossAsync(sog, val, null);
  568. CrossAsyncCompleted(sog);
  569. }, null, "ObjCross-"+sog.UUID.ToString(), false);
  570. }
  571. return;
  572. }
  573. if (RootPart.GetStatusSandbox())
  574. {
  575. if (Vector3.DistanceSquared(RootPart.StatusSandboxPos, value) > 100)
  576. {
  577. RootPart.ScriptSetPhysicsStatus(false);
  578. Scene?.SimChat(Utils.StringToBytes("Hit Sandbox Limit"),
  579. ChatTypeEnum.DebugChannel, 0x7FFFFFFF, RootPart.AbsolutePosition, Name, UUID, false);
  580. return;
  581. }
  582. }
  583. bool triggerScriptEvent;
  584. if (m_dupeInProgress || IsDeleted)
  585. triggerScriptEvent = false;
  586. else
  587. triggerScriptEvent = !m_rootPart.GroupPosition.ApproxEquals(val, 1e-3f);
  588. m_rootPart.GroupPosition = val;
  589. // Restuff the new GroupPosition into each child SOP of the linkset.
  590. // this is needed because physics may not have linksets but just loose SOPs in world
  591. SceneObjectPart[] parts = m_parts.GetArray();
  592. foreach (SceneObjectPart part in parts)
  593. {
  594. if (part != m_rootPart)
  595. part.GroupPosition = val;
  596. }
  597. foreach (ScenePresence av in m_sittingAvatars)
  598. {
  599. av.sitSOGmoved();
  600. }
  601. // now that position is changed tell it to scripts
  602. if (triggerScriptEvent && (ScriptEvents & scriptEvents.changed) != 0)
  603. {
  604. foreach (SceneObjectPart part in parts)
  605. {
  606. part.TriggerScriptChangedEvent(Changed.POSITION);
  607. }
  608. }
  609. Scene?.EventManager.TriggerParcelPrimCountTainted();
  610. }
  611. }
  612. private SceneObjectGroup CrossAsync(SceneObjectGroup sog, Vector3 val, TeleportObjectData tpdata)
  613. {
  614. Scene sogScene = sog.m_scene;
  615. SceneObjectPart root = sog.RootPart;
  616. bool isTeleport = tpdata is not null;
  617. if(!isTeleport)
  618. {
  619. if (root.DIE_AT_EDGE)
  620. {
  621. try
  622. {
  623. sogScene.DeleteSceneObject(sog, false);
  624. }
  625. catch (Exception)
  626. {
  627. m_log.Warn("[SCENE]: exception when trying to remove the prim that crossed the border.");
  628. }
  629. return sog;
  630. }
  631. if (root.RETURN_AT_EDGE)
  632. {
  633. // We remove the object here
  634. try
  635. {
  636. List<uint> localIDs = new(){root.LocalId};
  637. sogScene.AddReturn(sog.OwnerID, sog.Name, sog.AbsolutePosition,
  638. "Returned at region cross");
  639. sogScene.DeRezObjects(null, localIDs, UUID.Zero, DeRezAction.Return, UUID.Zero, false);
  640. }
  641. catch (Exception)
  642. {
  643. m_log.Warn("[SCENE]: exception when trying to return the prim that crossed the border.");
  644. }
  645. return sog;
  646. }
  647. }
  648. //if(!m_scene.IsRunning)
  649. // return sog;
  650. root.KeyframeMotion?.StartCrossingCheck();
  651. root.PhysActor?.CrossingStart();
  652. IEntityTransferModule entityTransfer = sogScene.RequestModuleInterface<IEntityTransferModule>();
  653. if (entityTransfer is null)
  654. return sog;
  655. Vector3 newpos = Vector3.Zero;
  656. OpenSim.Services.Interfaces.GridRegion destination = null;
  657. destination = entityTransfer.GetObjectDestination(sog, val, out newpos);
  658. if (destination is null)
  659. return sog;
  660. if (sog.m_sittingAvatars.Count == 0)
  661. {
  662. if(entityTransfer.CrossPrimGroupIntoNewRegion(destination, newpos, sog, !isTeleport, true))
  663. return null;
  664. return sog;
  665. }
  666. string reason = string.Empty;
  667. EntityTransferContext ctx = new();
  668. Vector3 curPos = root.GroupPosition;
  669. foreach (ScenePresence av in sog.m_sittingAvatars)
  670. {
  671. // We need to cross these agents. First, let's find
  672. // out if any of them can't cross for some reason.
  673. // We have to deny the crossing entirely if any
  674. // of them are banned. Alternatively, we could
  675. // unsit banned agents....
  676. // We set the avatar position as being the object
  677. // position to get the region to send to
  678. if(av.IsNPC)
  679. continue;
  680. if(av.IsInTransit)
  681. return sog;
  682. if(!entityTransfer.checkAgentAccessToRegion(av, destination, newpos, ctx, out reason))
  683. return sog;
  684. m_log.Debug($"[SCENE OBJECT]: Avatar {av.Name} needs to be crossed to {destination.RegionName}");
  685. }
  686. // We unparent the SP quietly so that it won't
  687. // be made to stand up
  688. List<avtocrossInfo> avsToCross = new();
  689. List<ScenePresence> avsToCrossFar = new();
  690. ulong destHandle = destination.RegionHandle;
  691. List<ScenePresence> sittingAvatars = GetSittingAvatars();
  692. foreach (ScenePresence av in sittingAvatars)
  693. {
  694. byte cflags = 1;
  695. avtocrossInfo avinfo = new();
  696. SceneObjectPart parentPart = sogScene.GetSceneObjectPart(av.ParentID);
  697. if (parentPart is not null)
  698. {
  699. av.ParentUUID = parentPart.UUID;
  700. if(parentPart.SitTargetAvatar.Equals(av.UUID))
  701. cflags = 7; // low 3 bits set
  702. else
  703. cflags = 3;
  704. }
  705. if(!av.knowsNeighbourRegion(destHandle))
  706. cflags |= 8;
  707. // 1 is crossing
  708. // 2 is sitting
  709. // 4 is sitting at sittarget
  710. // 8 far crossing
  711. avinfo.av = av;
  712. avinfo.ParentID = av.ParentID;
  713. avsToCross.Add(avinfo);
  714. if(!av.knowsNeighbourRegion(destHandle))
  715. {
  716. cflags |= 8;
  717. avsToCrossFar.Add(av);
  718. }
  719. if(av.IsNPC)
  720. av.m_crossingFlags = 0;
  721. else
  722. av.m_crossingFlags = cflags;
  723. av.PrevSitOffset = av.OffsetPosition;
  724. av.ParentID = 0;
  725. }
  726. Vector3 vel = root.Velocity;
  727. Vector3 avel = root.AngularVelocity;
  728. Vector3 acc = root.Acceleration;
  729. Quaternion ori = root.RotationOffset;
  730. if(isTeleport)
  731. {
  732. root.Stop();
  733. sogScene.ForEachScenePresence(delegate(ScenePresence av)
  734. {
  735. av.ControllingClient.SendEntityUpdate(root,PrimUpdateFlags.SendInTransit);
  736. av.ControllingClient.SendEntityTerseUpdateImmediate(root);
  737. });
  738. root.Velocity = tpdata.vel;
  739. root.AngularVelocity = tpdata.avel;
  740. root.Acceleration = tpdata.acc;
  741. root.RotationOffset = tpdata.ori;
  742. }
  743. if (entityTransfer.CrossPrimGroupIntoNewRegion(destination, newpos, sog, true, false))
  744. {
  745. if(isTeleport)
  746. {
  747. sogScene.ForEachScenePresence(delegate(ScenePresence oav)
  748. {
  749. if(sittingAvatars.Contains(oav))
  750. return;
  751. if(oav.knowsNeighbourRegion(destHandle))
  752. return;
  753. oav.ControllingClient.SendEntityUpdate(root, PrimUpdateFlags.Kill);
  754. foreach (ScenePresence sav in sittingAvatars)
  755. {
  756. sav.SendKillTo(oav);
  757. }
  758. });
  759. }
  760. bool crossedfar = false;
  761. foreach (ScenePresence av in avsToCrossFar)
  762. {
  763. if(entityTransfer.CrossAgentCreateFarChild(av,destination, newpos, ctx))
  764. crossedfar = true;
  765. else
  766. av.m_crossingFlags = 0;
  767. }
  768. if(crossedfar)
  769. Thread.Sleep(1000);
  770. foreach (avtocrossInfo avinfo in avsToCross)
  771. {
  772. ScenePresence av = avinfo.av;
  773. av.IsInLocalTransit = true;
  774. av.IsInTransit = true;
  775. m_log.Debug($"[SCENE OBJECT]: Crossing avatar {av.Name} to {val}");
  776. if(av.m_crossingFlags > 0)
  777. entityTransfer.CrossAgentToNewRegionAsync(av, newpos, destination, false, ctx);
  778. if (av.IsChildAgent)
  779. {
  780. // avatar crossed do some extra cleanup
  781. if (av.ParentUUID.IsNotZero())
  782. {
  783. av.ClearControls();
  784. av.ParentPart = null;
  785. }
  786. av.ParentUUID = UUID.Zero;
  787. av.ParentPart = null;
  788. // In any case
  789. av.IsInTransit = false;
  790. av.m_crossingFlags = 0;
  791. m_log.Debug($"[SCENE OBJECT]: Crossing agent {av.Firstname} {av.Lastname} completed.");
  792. }
  793. else
  794. {
  795. // avatar cross failed we need do dedicated standUp
  796. // part of it was done at CrossAgentToNewRegionAsync
  797. // so for now just remove the sog controls
  798. // this may need extra care
  799. av.UnRegisterSeatControls(sog.UUID);
  800. av.ParentUUID = UUID.Zero;
  801. av.ParentPart = null;
  802. Vector3 oldp = curPos;
  803. oldp.X = Utils.Clamp(oldp.X, 0.5f, sog.m_scene.RegionInfo.RegionSizeX - 0.5f);
  804. oldp.Y = Utils.Clamp(oldp.Y, 0.5f, sog.m_scene.RegionInfo.RegionSizeY - 0.5f);
  805. av.AbsolutePosition = oldp;
  806. av.m_crossingFlags = 0;
  807. av.sitAnimation = "SIT";
  808. av.IsInTransit = false;
  809. av.Animator?.SetMovementAnimations("STAND");
  810. av.AddToPhysicalScene(false);
  811. sogScene.ForEachScenePresence(delegate(ScenePresence oav)
  812. {
  813. if(sittingAvatars.Contains(oav))
  814. return;
  815. if(oav.knowsNeighbourRegion(destHandle))
  816. av.SendAvatarDataToAgent(oav);
  817. else
  818. {
  819. av.SendAvatarDataToAgent(oav);
  820. av.SendAppearanceToAgent(oav);
  821. av.Animator?.SendAnimPackToClient(oav.ControllingClient);
  822. av.SendAttachmentsToAgentNF(oav); // not ok
  823. }
  824. });
  825. m_log.Debug($"[SCENE OBJECT]: Crossing agent {av.Firstname} {av.Lastname} failed.");
  826. }
  827. }
  828. if(crossedfar)
  829. {
  830. Thread.Sleep(10000);
  831. foreach (ScenePresence av in avsToCrossFar)
  832. {
  833. if(av.IsChildAgent)
  834. {
  835. av.Scene.CloseAgent(av.UUID, false);
  836. }
  837. else
  838. av.RemoveNeighbourRegion(destHandle);
  839. }
  840. }
  841. avsToCrossFar.Clear();
  842. avsToCross.Clear();
  843. sog.RemoveScriptInstances(true);
  844. sog.Dispose();
  845. return null;
  846. }
  847. else
  848. {
  849. if(isTeleport)
  850. {
  851. if((tpdata.flags & OSTPOBJ_STOPONFAIL) == 0)
  852. {
  853. root.Velocity = vel;
  854. root.AngularVelocity = avel;
  855. root.Acceleration = acc;
  856. }
  857. root.RotationOffset = ori;
  858. }
  859. foreach (avtocrossInfo avinfo in avsToCross)
  860. {
  861. ScenePresence av = avinfo.av;
  862. av.ParentUUID = UUID.Zero;
  863. av.ParentID = avinfo.ParentID;
  864. av.m_crossingFlags = 0;
  865. }
  866. }
  867. avsToCross.Clear();
  868. return sog;
  869. }
  870. public void CrossAsyncCompleted(SceneObjectGroup sog)
  871. {
  872. if (sog is null || sog.IsDeleted)
  873. return;
  874. SceneObjectPart rootp = sog.m_rootPart;
  875. Vector3 oldp = rootp.GroupPosition;
  876. oldp.X = Utils.Clamp(oldp.X, 0.5f, sog.m_scene.RegionInfo.RegionSizeX - 0.5f);
  877. oldp.Y = Utils.Clamp(oldp.Y, 0.5f, sog.m_scene.RegionInfo.RegionSizeY - 0.5f);
  878. rootp.GroupPosition = oldp;
  879. rootp.Stop();
  880. SceneObjectPart[] parts = sog.m_parts.GetArray();
  881. foreach (SceneObjectPart part in parts)
  882. {
  883. if (part != rootp)
  884. part.GroupPosition = oldp;
  885. }
  886. foreach (ScenePresence av in sog.m_sittingAvatars)
  887. {
  888. av.sitSOGmoved();
  889. }
  890. sog.m_rootPart.KeyframeMotion?.CrossingFailure();
  891. sog.RootPart.PhysActor?.CrossingFailure();
  892. sog.inTransit = false;
  893. AttachToBackup();
  894. sog.ScheduleGroupForUpdate(PrimUpdateFlags.FullUpdatewithAnimMatOvr);
  895. }
  896. private class TeleportObjectData
  897. {
  898. public int flags;
  899. public Vector3 vel;
  900. public Vector3 avel;
  901. public Vector3 acc;
  902. public Quaternion ori;
  903. public UUID sourceID;
  904. }
  905. // copy from LSL_constants.cs
  906. const int OSTPOBJ_STOPATTARGET = 0x1; // stops at destination
  907. const int OSTPOBJ_STOPONFAIL = 0x2; // stops at start if tp fails
  908. const int OSTPOBJ_SETROT = 0x4; // the rotation is the final rotation, otherwise is a added rotation
  909. public int TeleportObject(UUID sourceID, Vector3 targetPosition, Quaternion rotation, int flags)
  910. {
  911. if(inTransit || IsDeleted || IsAttachmentCheckFull() || IsSelected || Scene is null)
  912. return -1;
  913. inTransit = true;
  914. PhysicsActor pa = RootPart.PhysActor;
  915. if(/*pa is null ||*/ RootPart.KeyframeMotion is not null /*|| m_sittingAvatars.Count == 0*/)
  916. {
  917. inTransit = false;
  918. return -1;
  919. }
  920. bool stop = (flags & OSTPOBJ_STOPATTARGET) != 0;
  921. bool setrot = (flags & OSTPOBJ_SETROT) != 0;
  922. rotation.Normalize();
  923. Quaternion currentRot = RootPart.RotationOffset;
  924. if(setrot)
  925. rotation = Quaternion.Conjugate(currentRot) * rotation;
  926. bool dorot = setrot || (Math.Abs(rotation.W) < 0.99999);
  927. Vector3 vel = Vector3.Zero;
  928. Vector3 avel = Vector3.Zero;
  929. Vector3 acc = Vector3.Zero;
  930. if(!stop)
  931. {
  932. vel = RootPart.Velocity;
  933. avel = RootPart.AngularVelocity;
  934. acc = RootPart.Acceleration;
  935. }
  936. Quaternion ori = RootPart.RotationOffset;
  937. if(dorot)
  938. {
  939. if(!stop)
  940. {
  941. vel *= rotation;
  942. avel *= rotation;
  943. acc *= rotation;
  944. }
  945. ori *= rotation;
  946. }
  947. if(Scene.PositionIsInCurrentRegion(targetPosition))
  948. {
  949. if(Scene.InTeleportTargetsCoolDown(UUID, sourceID, 1000))
  950. {
  951. inTransit = false;
  952. return -2;
  953. }
  954. Vector3 curPos = AbsolutePosition;
  955. ILandObject curLand = Scene.LandChannel.GetLandObject(curPos.X, curPos.Y);
  956. float posX = targetPosition.X;
  957. float posY = targetPosition.Y;
  958. ILandObject land = Scene.LandChannel.GetLandObject(posX, posY);
  959. if(land is not null && land != curLand)
  960. {
  961. if(!Scene.Permissions.CanObjectEnterWithScripts(this, land))
  962. {
  963. inTransit = false;
  964. return -3;
  965. }
  966. UUID agentID;
  967. foreach (ScenePresence av in m_sittingAvatars)
  968. {
  969. agentID = av.UUID;
  970. if(land.IsRestrictedFromLand(agentID) || land.IsBannedFromLand(agentID))
  971. {
  972. inTransit = false;
  973. return -4;
  974. }
  975. }
  976. }
  977. RootPart.Velocity = vel;
  978. RootPart.AngularVelocity = avel;
  979. RootPart.Acceleration = acc;
  980. RootPart.RotationOffset = ori;
  981. Vector3 s = RootPart.Scale * RootPart.RotationOffset;
  982. float h = Scene.GetGroundHeight(posX, posY) + 0.5f * (float)Math.Abs(s.Z) + 0.01f;
  983. if(targetPosition.Z < h)
  984. targetPosition.Z = h;
  985. inTransit = false;
  986. AbsolutePosition = targetPosition;
  987. RootPart.ScheduleTerseUpdate();
  988. return 1;
  989. }
  990. if(Scene.InTeleportTargetsCoolDown(UUID, sourceID, 20000))
  991. {
  992. inTransit = false;
  993. return -1;
  994. }
  995. TeleportObjectData tdata = new()
  996. {
  997. flags = flags,
  998. vel = vel,
  999. avel = avel,
  1000. acc = acc,
  1001. ori = ori,
  1002. sourceID = sourceID
  1003. };
  1004. SceneObjectGroup sog = this;
  1005. Util.FireAndForget(delegate
  1006. {
  1007. sog = CrossAsync(sog, targetPosition, tdata);
  1008. CrossAsyncCompleted(sog);
  1009. }, null, "ObjTeleport-" + sog.UUID.ToString(), false);
  1010. return 0;
  1011. }
  1012. public override Vector3 Velocity
  1013. {
  1014. get { return RootPart.Velocity; }
  1015. set { RootPart.Velocity = value; }
  1016. }
  1017. public override uint LocalId
  1018. {
  1019. get { return m_rootPart.LocalId; }
  1020. set { m_rootPart.LocalId = value; }
  1021. }
  1022. public override UUID UUID
  1023. {
  1024. get { return m_rootPart.UUID; }
  1025. set
  1026. {
  1027. lock (m_parts.SyncRoot)
  1028. {
  1029. m_parts.Remove(m_rootPart.UUID);
  1030. m_rootPart.UUID = value;
  1031. m_parts.Add(value, m_rootPart);
  1032. }
  1033. }
  1034. }
  1035. public UUID LastOwnerID
  1036. {
  1037. get { return m_rootPart.LastOwnerID; }
  1038. set { m_rootPart.LastOwnerID = value; }
  1039. }
  1040. public UUID RezzerID
  1041. {
  1042. get { return m_rootPart.RezzerID; }
  1043. set { m_rootPart.RezzerID = value; }
  1044. }
  1045. public UUID OwnerID
  1046. {
  1047. get { return m_rootPart.OwnerID; }
  1048. set { m_rootPart.OwnerID = value; }
  1049. }
  1050. public float Damage
  1051. {
  1052. get { return m_rootPart.Damage; }
  1053. set { m_rootPart.Damage = value; }
  1054. }
  1055. public Color Color
  1056. {
  1057. get { return m_rootPart.Color; }
  1058. set { m_rootPart.Color = value; }
  1059. }
  1060. public string Text
  1061. {
  1062. get
  1063. {
  1064. return m_rootPart.Text.Length > 255 ? m_rootPart.Text[..255] : m_rootPart.Text;
  1065. }
  1066. set { m_rootPart.Text = value; }
  1067. }
  1068. /// <summary>
  1069. /// If set to true then the scene object can be backed up in principle, though this will only actually occur
  1070. /// if Backup is set. If false then the scene object will never be backed up, Backup will always be false.
  1071. /// </summary>
  1072. protected virtual bool CanBeBackedUp
  1073. {
  1074. get { return true; }
  1075. }
  1076. public bool IsSelected
  1077. {
  1078. get { return m_isSelected; }
  1079. set
  1080. {
  1081. m_isSelected = value;
  1082. // Tell physics engine that group is selected
  1083. // this is not right
  1084. // but ode engines should only really need to know about root part
  1085. // so they can put entire object simulation on hold and not colliding
  1086. // keep as was for now
  1087. PhysicsActor pa = m_rootPart.PhysActor;
  1088. if (pa is not null)
  1089. {
  1090. pa.Selected = value;
  1091. // Pass it on to the children.
  1092. SceneObjectPart[] parts = m_parts.GetArray();
  1093. for (int i = 0; i < parts.Length; i++)
  1094. {
  1095. SceneObjectPart child = parts[i];
  1096. PhysicsActor childPa = child.PhysActor;
  1097. if (childPa is not null)
  1098. childPa.Selected = value;
  1099. }
  1100. }
  1101. if (RootPart.KeyframeMotion is not null)
  1102. RootPart.KeyframeMotion.Selected = value;
  1103. }
  1104. }
  1105. public void PartSelectChanged(bool partSelect)
  1106. {
  1107. // any part selected makes group selected
  1108. if (m_isSelected == partSelect)
  1109. return;
  1110. if (partSelect)
  1111. {
  1112. IsSelected = partSelect;
  1113. //if (!IsAttachment)
  1114. // ScheduleGroupForFullUpdate();
  1115. }
  1116. else
  1117. {
  1118. // bad bad bad 2 heavy for large linksets
  1119. // since viewer does send lot of (un)selects
  1120. // this needs to be replaced by a specific list or count ?
  1121. // but that will require extra code in several places
  1122. SceneObjectPart[] parts = m_parts.GetArray();
  1123. for (int i = 0; i < parts.Length; i++)
  1124. {
  1125. SceneObjectPart part = parts[i];
  1126. if (part.IsSelected)
  1127. return;
  1128. }
  1129. IsSelected = partSelect;
  1130. //if (!IsAttachment)
  1131. //{
  1132. // ScheduleGroupForFullUpdate();
  1133. //}
  1134. }
  1135. }
  1136. private double m_lastCollisionSoundMS;
  1137. /// <summary>
  1138. /// The UUID for the region this object is in.
  1139. /// </summary>
  1140. public UUID RegionUUID
  1141. {
  1142. get
  1143. {
  1144. return m_scene is not null ? m_scene.RegionInfo.RegionID : UUID.Zero;
  1145. }
  1146. }
  1147. /// <summary>
  1148. /// The item ID that this object was rezzed from, if applicable.
  1149. /// </summary>
  1150. /// <remarks>
  1151. /// If not applicable will be UUID.Zero
  1152. /// </remarks>
  1153. public UUID FromItemID { get; set; }
  1154. /// <summary>
  1155. /// Refers to the SceneObjectPart.UUID property of the object that this object was rezzed from, if applicable.
  1156. /// </summary>
  1157. /// <remarks>
  1158. /// If not applicable will be UUID.Zero
  1159. /// </remarks>
  1160. /// obsolete use RezzerID
  1161. public UUID FromPartID
  1162. {
  1163. get { return RezzerID; }
  1164. set {RezzerID = value; }
  1165. }
  1166. /// <summary>
  1167. /// The folder ID that this object was rezzed from, if applicable.
  1168. /// </summary>
  1169. /// <remarks>
  1170. /// If not applicable will be UUID.Zero
  1171. /// </remarks>
  1172. public UUID FromFolderID { get; set; }
  1173. /// <summary>
  1174. /// If true then grabs are blocked no matter what the individual part BlockGrab setting.
  1175. /// </summary>
  1176. /// <value><c>true</c> if block grab override; otherwise, <c>false</c>.</value>
  1177. public bool BlockGrabOverride { get; set; }
  1178. /// <summary>
  1179. /// IDs of all avatars sat on this scene object.
  1180. /// </summary>
  1181. /// <remarks>
  1182. /// We need this so that we can maintain a linkset wide ordering of avatars sat on different parts.
  1183. /// This must be locked before it is read or written.
  1184. /// SceneObjectPart sitting avatar add/remove code also locks on this object to avoid race conditions.
  1185. /// No avatar should appear more than once in this list.
  1186. /// Do not manipulate this list directly - use the Add/Remove sitting avatar methods on SceneObjectPart.
  1187. /// </remarks>
  1188. protected internal List<ScenePresence> m_sittingAvatars = new();
  1189. #endregion
  1190. #region Constructors
  1191. /// <summary>
  1192. /// Constructor
  1193. /// </summary>
  1194. public SceneObjectGroup()
  1195. {
  1196. m_lastCollisionSoundMS = Util.GetTimeStampMS() + 1000.0;
  1197. }
  1198. /// <summary>
  1199. /// This constructor creates a SceneObjectGroup using a pre-existing SceneObjectPart.
  1200. /// The original SceneObjectPart will be used rather than a copy, preserving
  1201. /// its existing localID and UUID.
  1202. /// </summary>
  1203. /// <param name='part'>Root part for this scene object.</param>
  1204. public SceneObjectGroup(SceneObjectPart part) : this()
  1205. {
  1206. SetRootPart(part);
  1207. }
  1208. /// <summary>
  1209. /// Constructor. This object is added to the scene later via AttachToScene()
  1210. /// </summary>
  1211. public SceneObjectGroup(UUID ownerID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
  1212. {
  1213. SetRootPart(new SceneObjectPart(ownerID, shape, pos, rot, Vector3.Zero));
  1214. }
  1215. /// <summary>
  1216. /// Constructor.
  1217. /// </summary>
  1218. public SceneObjectGroup(UUID ownerID, Vector3 pos, PrimitiveBaseShape shape)
  1219. : this(ownerID, pos, Quaternion.Identity, shape)
  1220. {
  1221. }
  1222. ~SceneObjectGroup()
  1223. {
  1224. Dispose(false);
  1225. }
  1226. private bool disposed = false;
  1227. public void Dispose()
  1228. {
  1229. Dispose(true);
  1230. GC.SuppressFinalize(this);
  1231. }
  1232. protected void Dispose(bool disposing)
  1233. {
  1234. // Check to see if Dispose has already been called.
  1235. if (!disposed)
  1236. {
  1237. IsDeleted = true;
  1238. disposed = true;
  1239. SceneObjectPart[] parts = m_parts.GetArray();
  1240. for(int i= 0; i < parts.Length; ++i)
  1241. parts[i].Dispose();
  1242. }
  1243. }
  1244. public void LoadScriptState(XmlDocument doc)
  1245. {
  1246. XmlNodeList nodes = doc.GetElementsByTagName("SavedScriptState");
  1247. if (nodes.Count > 0)
  1248. {
  1249. m_savedScriptState ??= new Dictionary<UUID, string>();
  1250. foreach (XmlNode node in nodes)
  1251. {
  1252. if (node.Attributes["UUID"] is not null)
  1253. {
  1254. UUID itemid = new(node.Attributes["UUID"].Value);
  1255. if (itemid.IsNotZero())
  1256. m_savedScriptState[itemid] = node.InnerXml;
  1257. }
  1258. }
  1259. }
  1260. }
  1261. public void LoadScriptState(XmlReader reader)
  1262. {
  1263. //m_log.DebugFormat("[SCENE OBJECT GROUP]: Looking for script state for {0}", Name);
  1264. while (true)
  1265. {
  1266. if (reader.Name.Equals("SavedScriptState") && reader.NodeType == XmlNodeType.Element)
  1267. {
  1268. //m_log.DebugFormat("[SCENE OBJECT GROUP]: Loading script state for {0}", Name);
  1269. m_savedScriptState ??= new Dictionary<UUID, string>();
  1270. string uuid = reader.GetAttribute("UUID");
  1271. // Even if there is no UUID attribute for some strange reason, we must always read the inner XML
  1272. // so we don't continually keep checking the same SavedScriptedState element.
  1273. string innerXml = reader.ReadInnerXml();
  1274. if (!string.IsNullOrEmpty(uuid))
  1275. {
  1276. //m_log.DebugFormat("[SCENE OBJECT GROUP]: Found state for item ID {0} in object {1}", uuid, Name);
  1277. if (UUID.TryParse(uuid, out UUID itemid) && itemid.IsNotZero())
  1278. m_savedScriptState[itemid] = innerXml;
  1279. }
  1280. else
  1281. {
  1282. m_log.Warn($"[SCENE OBJECT GROUP]: SavedScriptState element had no UUID in object {Name} id: {UUID}");
  1283. }
  1284. }
  1285. else
  1286. {
  1287. if (!reader.Read())
  1288. break;
  1289. }
  1290. }
  1291. }
  1292. /// <summary>
  1293. /// Hooks this object up to the backup event so that it is persisted to the database when the update thread executes.
  1294. /// </summary>
  1295. public virtual void AttachToBackup()
  1296. {
  1297. if (IsAttachment)
  1298. return;
  1299. if (!Backup)
  1300. {
  1301. m_scene.SceneGraph.FireAttachToBackup(this);
  1302. m_scene.EventManager.OnBackup += ProcessBackup;
  1303. }
  1304. Backup = true;
  1305. }
  1306. /// <summary>
  1307. /// Attach this object to a scene. It will also now appear to agents.
  1308. /// </summary>
  1309. /// <param name="scene"></param>
  1310. public void AttachToScene(Scene scene)
  1311. {
  1312. m_scene = scene;
  1313. RegionHandle = m_scene.RegionInfo.RegionHandle;
  1314. if (m_rootPart.Shape.PCode != 9 || m_rootPart.Shape.State == 0)
  1315. m_rootPart.ParentID = 0;
  1316. if (m_rootPart.LocalId == 0)
  1317. m_rootPart.LocalId = m_scene.AllocateLocalId();
  1318. SceneObjectPart[] parts = m_parts.GetArray();
  1319. for (int i = 0; i < parts.Length; i++)
  1320. {
  1321. SceneObjectPart part = parts[i];
  1322. part.KeyframeMotion?.UpdateSceneObject(this);
  1323. if (Object.ReferenceEquals(part, m_rootPart))
  1324. continue;
  1325. if (part.LocalId == 0)
  1326. part.LocalId = m_scene.AllocateLocalId();
  1327. part.ParentID = m_rootPart.LocalId;
  1328. //m_log.DebugFormat("[SCENE]: Given local id {0} to part {1}, linknum {2}, parent {3} {4}", part.LocalId, part.UUID, part.LinkNum, part.ParentID, part.ParentUUID);
  1329. }
  1330. ApplyPhysics();
  1331. // Don't trigger the update here - otherwise some client issues occur when multiple updates are scheduled
  1332. // for the same object with very different properties. The caller must schedule the update.
  1333. //ScheduleGroupForFullUpdate();
  1334. }
  1335. public EntityIntersection TestIntersection(Ray hRay, bool frontFacesOnly, bool faceCenters)
  1336. {
  1337. // We got a request from the inner_scene to raytrace along the Ray hRay
  1338. // We're going to check all of the prim in this group for intersection with the ray
  1339. // If we get a result, we're going to find the closest result to the origin of the ray
  1340. // and send back the intersection information back to the innerscene.
  1341. EntityIntersection result = new();
  1342. SceneObjectPart[] parts = m_parts.GetArray();
  1343. // Find closest hit here
  1344. float idist = float.MaxValue;
  1345. for (int i = 0; i < parts.Length; i++)
  1346. {
  1347. SceneObjectPart part = parts[i];
  1348. // Temporary commented to stop compiler warning
  1349. //Vector3 partPosition =
  1350. // new Vector3(part.AbsolutePosition.X, part.AbsolutePosition.Y, part.AbsolutePosition.Z);
  1351. Quaternion parentrotation = GroupRotation;
  1352. // Telling the prim to raytrace.
  1353. //EntityIntersection inter = part.TestIntersection(hRay, parentrotation);
  1354. EntityIntersection inter = part.TestIntersectionOBB(hRay, parentrotation, frontFacesOnly, faceCenters);
  1355. if (inter.HitTF)
  1356. {
  1357. // We need to find the closest prim to return to the testcaller along the ray
  1358. if (inter.distance < idist)
  1359. {
  1360. result.HitTF = true;
  1361. result.ipoint = inter.ipoint;
  1362. result.obj = part;
  1363. result.normal = inter.normal;
  1364. result.distance = inter.distance;
  1365. idist = inter.distance;
  1366. }
  1367. }
  1368. }
  1369. return result;
  1370. }
  1371. public void GetBoundingBox(out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ)
  1372. {
  1373. uint rootid = RootPart.LocalId;
  1374. Vector3 scale = RootPart.Scale * 0.5f;
  1375. minX = -scale.X;
  1376. maxX = scale.X;
  1377. minY = -scale.Y;
  1378. maxY = scale.Y;
  1379. minZ = -scale.Z;
  1380. maxZ = scale.Z;
  1381. SceneObjectPart[] parts = m_parts.GetArray();
  1382. for (int i = 0; i < parts.Length; ++i)
  1383. {
  1384. SceneObjectPart part = parts[i];
  1385. if(part.LocalId == rootid)
  1386. continue;
  1387. Vector3 offset = part.OffsetPosition;
  1388. scale = part.Scale * 0.5f;
  1389. Matrix4 m = Matrix4.CreateFromQuaternion(part.RotationOffset);
  1390. Vector3 a = m.AtAxis;
  1391. a.X = Math.Abs(a.X);
  1392. a.Y = Math.Abs(a.Y);
  1393. a.Z = Math.Abs(a.Z);
  1394. float tmpS = Vector3.Dot(a, scale);
  1395. float tmp = offset.X - tmpS;
  1396. if (tmp < minX)
  1397. minX = tmp;
  1398. tmp = offset.X + tmpS;
  1399. if (tmp > maxX)
  1400. maxX = tmp;
  1401. a = m.LeftAxis;
  1402. a.X = Math.Abs(a.X);
  1403. a.Y = Math.Abs(a.Y);
  1404. a.Z = Math.Abs(a.Z);
  1405. tmpS = Vector3.Dot(a, scale);
  1406. tmp = offset.Y - tmpS;
  1407. if (tmp < minY)
  1408. minY = tmp;
  1409. tmp = offset.Y + tmpS;
  1410. if (tmp > maxY)
  1411. maxY = tmp;
  1412. a = m.UpAxis;
  1413. a.X = Math.Abs(a.X);
  1414. a.Y = Math.Abs(a.Y);
  1415. a.Z = Math.Abs(a.Z);
  1416. tmpS = Vector3.Dot(a, scale);
  1417. tmp = offset.Z - tmpS;
  1418. if (tmp < minZ)
  1419. minZ = tmp;
  1420. tmp = offset.Z + tmpS;
  1421. if (tmp > maxZ)
  1422. maxZ = tmp;
  1423. }
  1424. }
  1425. /// <summary>
  1426. /// Gets a vector representing the size of the bounding box containing all the prims in the group
  1427. /// Treats all prims as rectangular, so no shape (cut etc) is taken into account
  1428. /// </summary>
  1429. /// <returns></returns>
  1430. public void GetAxisAlignedBoundingBoxRaw(out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ)
  1431. {
  1432. maxX = float.MinValue;
  1433. maxY = float.MinValue;
  1434. maxZ = float.MinValue;
  1435. minX = float.MaxValue;
  1436. minY = float.MaxValue;
  1437. minZ = float.MaxValue;
  1438. Vector3 absPos = AbsolutePosition;
  1439. SceneObjectPart[] parts = m_parts.GetArray();
  1440. for(int i = 0; i< parts.Length; ++i)
  1441. {
  1442. SceneObjectPart part = parts[i];
  1443. Vector3 offset = part.GetWorldPosition() - absPos;
  1444. Vector3 scale = part.Scale * 0.5f;
  1445. Matrix4 m = Matrix4.CreateFromQuaternion(part.GetWorldRotation());
  1446. Vector3 a = m.AtAxis;
  1447. a.X = MathF.Abs(a.X);
  1448. a.Y = MathF.Abs(a.Y);
  1449. a.Z = MathF.Abs(a.Z);
  1450. float tmpS = Vector3.Dot(a, scale);
  1451. float tmp = offset.X - tmpS;
  1452. if (tmp < minX)
  1453. minX = tmp;
  1454. tmp = offset.X + tmpS;
  1455. if (tmp > maxX)
  1456. maxX = tmp;
  1457. a = m.LeftAxis;
  1458. a.X = MathF.Abs(a.X);
  1459. a.Y = MathF.Abs(a.Y);
  1460. a.Z = MathF.Abs(a.Z);
  1461. tmpS = Vector3.Dot(a, scale);
  1462. tmp = offset.Y - tmpS;
  1463. if (tmp < minY)
  1464. minY = tmp;
  1465. tmp = offset.Y + tmpS;
  1466. if (tmp > maxY)
  1467. maxY = tmp;
  1468. a = m.UpAxis;
  1469. a.X = MathF.Abs(a.X);
  1470. a.Y = MathF.Abs(a.Y);
  1471. a.Z = MathF.Abs(a.Z);
  1472. tmpS = Vector3.Dot(a, scale);
  1473. tmp = offset.Z - tmpS;
  1474. if (tmp < minZ)
  1475. minZ = tmp;
  1476. tmp = offset.Z + tmpS;
  1477. if (tmp > maxZ)
  1478. maxZ = tmp;
  1479. }
  1480. }
  1481. /// <summary>
  1482. /// Gets a vector representing the size of the bounding box containing all the prims in the group
  1483. /// Treats all prims as rectangular, so no shape (cut etc) is taken into account
  1484. /// offsetHeight is the offset in the Z axis from the centre of the bounding box to the centre of the root prim
  1485. /// </summary>
  1486. /// <returns></returns>
  1487. public Vector3 GetAxisAlignedBoundingBox(out float offsetHeight)
  1488. {
  1489. GetAxisAlignedBoundingBoxRaw(out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ);
  1490. Vector3 boundingBox = new(maxX - minX, maxY - minY, maxZ - minZ);
  1491. offsetHeight = 0;
  1492. float lower = -minZ;
  1493. if (lower > maxZ)
  1494. offsetHeight = lower - 0.5f * boundingBox.Z;
  1495. else if (maxZ > lower)
  1496. offsetHeight = 0.5f * boundingBox.Z - maxZ;
  1497. // m_log.InfoFormat("BoundingBox is {0} , {1} , {2} ", boundingBox.X, boundingBox.Y, boundingBox.Z);
  1498. return boundingBox;
  1499. }
  1500. #endregion
  1501. private float? m_boundsRadius = null;
  1502. public void InvalidBoundsRadius()
  1503. {
  1504. m_boundsRadius = null;
  1505. }
  1506. private Vector3 m_boundsCenter;
  1507. private Vector3 m_LastCenterOffset;
  1508. private Vector3 last_boundsRot = new(-10, -10, -10);
  1509. public Vector3 getCenterOffset()
  1510. {
  1511. // math is done in GetBoundsRadius();
  1512. if(m_boundsRadius is null)
  1513. GetBoundsRadius();
  1514. Quaternion rot = m_rootPart.RotationOffset;
  1515. if (last_boundsRot.X != rot.X ||
  1516. last_boundsRot.Y != rot.Y ||
  1517. last_boundsRot.Z != rot.Z)
  1518. {
  1519. m_LastCenterOffset = m_boundsCenter * rot;
  1520. last_boundsRot.X = rot.X;
  1521. last_boundsRot.Y = rot.Y;
  1522. last_boundsRot.Z = rot.Z;
  1523. }
  1524. return m_rootPart.GroupPosition + m_LastCenterOffset;
  1525. }
  1526. private float m_areaFactor;
  1527. public float getAreaFactor()
  1528. {
  1529. // math is done in GetBoundsRadius();
  1530. if(m_boundsRadius is null)
  1531. GetBoundsRadius();
  1532. return m_areaFactor;
  1533. }
  1534. public float GetBoundsRadius()
  1535. {
  1536. // this may need more threading work
  1537. if(m_boundsRadius is null)
  1538. {
  1539. float res = 0;
  1540. float areaF = 0;
  1541. float partR;
  1542. Vector3 offset = Vector3.Zero;
  1543. SceneObjectPart[] parts = m_parts.GetArray();
  1544. for (int i = 0; i < parts.Length; i++)
  1545. {
  1546. SceneObjectPart p = parts[i];
  1547. partR = 0.5f * p.Scale.Length();
  1548. if(p != RootPart)
  1549. {
  1550. partR += p.OffsetPosition.Length();
  1551. offset += p.OffsetPosition;
  1552. }
  1553. if(partR > res)
  1554. res = partR;
  1555. if(p.maxSimpleArea() > areaF)
  1556. areaF = p.maxSimpleArea();
  1557. }
  1558. if(parts.Length > 1)
  1559. {
  1560. offset /= parts.Length; // basicly geometric center
  1561. }
  1562. areaF = 0.5f / areaF; // scale it
  1563. areaF = Utils.Clamp(areaF, 0.05f, 100f); // clamp it
  1564. m_areaFactor = MathF.Sqrt(areaF);
  1565. m_boundsCenter = offset;
  1566. m_boundsRadius = res;
  1567. return res;
  1568. }
  1569. return m_boundsRadius.Value;
  1570. }
  1571. public void GetResourcesCosts(SceneObjectPart apart,
  1572. out float linksetResCost, out float linksetPhysCost, out float partCost, out float partPhysCost)
  1573. {
  1574. // this information may need to be cached
  1575. float cost;
  1576. float tmpcost;
  1577. bool ComplexCost = false;
  1578. SceneObjectPart[] parts = m_parts.GetArray();
  1579. for (int i = 0; i < parts.Length; i++)
  1580. {
  1581. if (parts[i].UsesComplexCost)
  1582. {
  1583. ComplexCost = true;
  1584. break;
  1585. }
  1586. }
  1587. if (ComplexCost)
  1588. {
  1589. linksetResCost = 0;
  1590. linksetPhysCost = 0;
  1591. partCost = 0;
  1592. partPhysCost = 0;
  1593. for (int i = 0; i < parts.Length; i++)
  1594. {
  1595. SceneObjectPart p = parts[i];
  1596. cost = p.StreamingCost;
  1597. tmpcost = p.SimulationCost;
  1598. if (tmpcost > cost)
  1599. cost = tmpcost;
  1600. tmpcost = p.PhysicsCost;
  1601. if (tmpcost > cost)
  1602. cost = tmpcost;
  1603. linksetPhysCost += tmpcost;
  1604. linksetResCost += cost;
  1605. if (p == apart)
  1606. {
  1607. partCost = cost;
  1608. partPhysCost = tmpcost;
  1609. }
  1610. }
  1611. }
  1612. else
  1613. {
  1614. partPhysCost = 1.0f;
  1615. partCost = 1.0f;
  1616. linksetResCost = parts.Length;
  1617. linksetPhysCost = linksetResCost;
  1618. }
  1619. }
  1620. public void GetSelectedCosts(out float PhysCost, out float StreamCost, out float SimulCost)
  1621. {
  1622. SceneObjectPart p;
  1623. SceneObjectPart[] parts = m_parts.GetArray();
  1624. PhysCost = 0;
  1625. StreamCost = 0;
  1626. SimulCost = 0;
  1627. for (int i = 0; i < parts.Length; i++)
  1628. {
  1629. p = parts[i];
  1630. StreamCost += p.StreamingCost;
  1631. SimulCost += p.SimulationCost;
  1632. PhysCost += p.PhysicsCost;
  1633. }
  1634. }
  1635. public void SaveScriptedState(XmlTextWriter writer)
  1636. {
  1637. SaveScriptedState(writer, false);
  1638. }
  1639. public void SaveScriptedState(XmlTextWriter writer, bool oldIDs)
  1640. {
  1641. XmlDocument doc = new();
  1642. Dictionary<UUID,string> states = new();
  1643. SceneObjectPart[] parts = m_parts.GetArray();
  1644. for (int i = 0; i < parts.Length; i++)
  1645. {
  1646. Dictionary<UUID, string> pstates = parts[i].Inventory.GetScriptStates(oldIDs);
  1647. foreach (KeyValuePair<UUID, string> kvp in pstates)
  1648. states[kvp.Key] = kvp.Value;
  1649. }
  1650. if (states.Count > 0)
  1651. {
  1652. // Now generate the necessary XML wrappings
  1653. writer.WriteStartElement(String.Empty, "GroupScriptStates", String.Empty);
  1654. foreach (UUID itemid in states.Keys)
  1655. {
  1656. doc.LoadXml(states[itemid]);
  1657. writer.WriteStartElement(String.Empty, "SavedScriptState", String.Empty);
  1658. writer.WriteAttributeString(String.Empty, "UUID", String.Empty, itemid.ToString());
  1659. writer.WriteRaw(doc.DocumentElement.OuterXml); // Writes ScriptState element
  1660. writer.WriteEndElement(); // End of SavedScriptState
  1661. }
  1662. writer.WriteEndElement(); // End of GroupScriptStates
  1663. }
  1664. }
  1665. public byte GetAttachmentPoint()
  1666. {
  1667. return m_rootPart.Shape.State;
  1668. }
  1669. public void DetachToGround()
  1670. {
  1671. ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
  1672. if (avatar is null)
  1673. return;
  1674. m_rootPart.Shape.LastAttachPoint = m_rootPart.Shape.State;
  1675. m_rootPart.AttachedPos = m_rootPart.OffsetPosition;
  1676. avatar.RemoveAttachment(this);
  1677. if (avatar is null)
  1678. return;
  1679. Vector3 detachedpos = avatar.AbsolutePosition;
  1680. FromItemID = UUID.Zero;
  1681. AbsolutePosition = detachedpos;
  1682. AttachedAvatar = UUID.Zero;
  1683. //SceneObjectPart[] parts = m_parts.GetArray();
  1684. //for (int i = 0; i < parts.Length; i++)
  1685. // parts[i].AttachedAvatar = UUID.Zero;
  1686. m_rootPart.SetParentLocalId(0);
  1687. AttachmentPoint = 0;
  1688. // must check if buildind should be true or false here
  1689. //m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive,false);
  1690. ApplyPhysics();
  1691. HasGroupChanged = true;
  1692. RootPart.Rezzed = DateTime.Now;
  1693. RootPart.RemFlag(PrimFlags.TemporaryOnRez);
  1694. AttachToBackup();
  1695. m_scene.EventManager.TriggerParcelPrimCountTainted();
  1696. m_rootPart.ScheduleFullUpdate();
  1697. m_rootPart.ClearUndoState();
  1698. }
  1699. public void DetachToInventoryPrep()
  1700. {
  1701. ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
  1702. //Vector3 detachedpos = new Vector3(127f, 127f, 127f);
  1703. //detachedpos = avatar.AbsolutePosition;
  1704. avatar?.RemoveAttachment(this);
  1705. AttachedAvatar = UUID.Zero;
  1706. /*SceneObjectPart[] parts = m_parts.GetArray();
  1707. for (int i = 0; i < parts.Length; i++)
  1708. parts[i].AttachedAvatar = UUID.Zero;*/
  1709. m_rootPart.SetParentLocalId(0);
  1710. //m_rootPart.SetAttachmentPoint((byte)0);
  1711. IsAttachment = false;
  1712. AbsolutePosition = m_rootPart.AttachedPos;
  1713. //m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_scene.m_physicalPrim);
  1714. //AttachToBackup();
  1715. //m_rootPart.ScheduleFullUpdate();
  1716. }
  1717. /// <summary>
  1718. ///
  1719. /// </summary>
  1720. /// <param name="part"></param>
  1721. private void SetPartAsNonRoot(SceneObjectPart part)
  1722. {
  1723. part.ParentID = m_rootPart.LocalId;
  1724. part.ClearUndoState();
  1725. }
  1726. /// <summary>
  1727. /// Set a part to act as the root part for this scene object
  1728. /// </summary>
  1729. /// <param name="part"></param>
  1730. public void SetRootPart(SceneObjectPart part)
  1731. {
  1732. if (part is null)
  1733. throw new ArgumentNullException("Cannot give SceneObjectGroup a null root SceneObjectPart");
  1734. part.SetParent(this);
  1735. m_rootPart = part;
  1736. if (!IsAttachment)
  1737. part.ParentID = 0;
  1738. part.LinkNum = 0;
  1739. m_parts.Add(m_rootPart.UUID, m_rootPart);
  1740. }
  1741. /// <summary>
  1742. /// Add a new part to this scene object. The part must already be correctly configured.
  1743. /// </summary>
  1744. /// <param name="part"></param>
  1745. public void AddPart(SceneObjectPart part)
  1746. {
  1747. part.SetParent(this);
  1748. m_parts.Add(part.UUID, part);
  1749. part.LinkNum = m_parts.Count;
  1750. if (part.LinkNum == 2)
  1751. RootPart.LinkNum = 1;
  1752. InvalidatePartsLinkMaps();
  1753. }
  1754. /// <summary>
  1755. /// Make sure that every non root part has the proper parent root part local id
  1756. /// </summary>
  1757. private void UpdateParentIDs()
  1758. {
  1759. SceneObjectPart[] parts = m_parts.GetArray();
  1760. for (int i = 0; i < parts.Length; i++)
  1761. {
  1762. SceneObjectPart part = parts[i];
  1763. if (part.UUID.NotEqual(m_rootPart.UUID))
  1764. part.ParentID = m_rootPart.LocalId;
  1765. }
  1766. }
  1767. public void RegenerateFullIDs()
  1768. {
  1769. SceneObjectPart[] parts = m_parts.GetArray();
  1770. for (int i = 0; i < parts.Length; i++)
  1771. parts[i].UUID = UUID.Random();
  1772. }
  1773. // helper provided for parts.
  1774. public int GetSceneMaxUndo()
  1775. {
  1776. if (m_scene is not null)
  1777. return m_scene.MaxUndoCount;
  1778. return 5;
  1779. }
  1780. public void ResetChildPrimPhysicsPositions()
  1781. {
  1782. // Setting this SOG's absolute position also loops through and sets the positions
  1783. // of the SOP's in this SOG's linkset. This has the side affect of making sure
  1784. // the physics world matches the simulated world.
  1785. Vector3 groupPosition = m_rootPart.GroupPosition;
  1786. SceneObjectPart[] parts = m_parts.GetArray();
  1787. foreach (SceneObjectPart part in parts)
  1788. {
  1789. if (part != m_rootPart)
  1790. part.GroupPosition = groupPosition;
  1791. }
  1792. }
  1793. public UUID GetPartsFullID(uint localID)
  1794. {
  1795. SceneObjectPart part = GetPart(localID);
  1796. return part is not null ? part.UUID : UUID.Zero;
  1797. }
  1798. public void ObjectGrabHandler(uint localId, Vector3 offsetPos, IClientAPI remoteClient)
  1799. {
  1800. if (m_rootPart.LocalId == localId)
  1801. {
  1802. if((RootPart.ScriptEvents & scriptEvents.anytouch) != 0)
  1803. lastTouchTime = Util.GetTimeStampMS();
  1804. OnGrabGroup(offsetPos, remoteClient);
  1805. }
  1806. else
  1807. {
  1808. SceneObjectPart part = GetPart(localId);
  1809. if (((part.ScriptEvents & scriptEvents.anytouch) != 0) || (RootPart.ScriptEvents & scriptEvents.anytouch) != 0)
  1810. lastTouchTime = Util.GetTimeStampMS();
  1811. OnGrabPart(part, offsetPos, remoteClient);
  1812. }
  1813. }
  1814. public virtual void OnGrabPart(SceneObjectPart part, Vector3 offsetPos, IClientAPI remoteClient)
  1815. {
  1816. //m_log.DebugFormat(
  1817. // "[SCENE OBJECT GROUP]: Processing OnGrabPart for {0} on {1} {2}, offsetPos {3}",
  1818. // remoteClient.Name, part.Name, part.LocalId, offsetPos);
  1819. //part.StoreUndoState();
  1820. part.OnGrab(offsetPos, remoteClient);
  1821. }
  1822. public virtual void OnGrabGroup(Vector3 offsetPos, IClientAPI remoteClient)
  1823. {
  1824. m_scene.EventManager.TriggerGroupGrab(UUID, offsetPos, remoteClient.AgentId);
  1825. }
  1826. /// <summary>
  1827. /// Delete this group from its scene.
  1828. /// </summary>
  1829. /// <remarks>
  1830. /// This only handles the in-world consequences of deletion (e.g. any avatars sitting on it are forcibly stood
  1831. /// up and all avatars receive notification of its removal. Removal of the scene object from database backup
  1832. /// must be handled by the caller.
  1833. /// </remarks>
  1834. /// <param name="silent">If true then deletion is not broadcast to clients</param>
  1835. public void DeleteGroupFromScene(bool silent)
  1836. {
  1837. // We need to keep track of this state in case this group is still queued for backup.
  1838. IsDeleted = true;
  1839. DetachFromBackup();
  1840. if(Scene is null) // should not happen unless restart/shutdown ?
  1841. return;
  1842. SceneObjectPart[] parts = m_parts.GetArray();
  1843. for (int i = 0; i < parts.Length; i++)
  1844. {
  1845. SceneObjectPart part = parts[i];
  1846. Scene.ForEachScenePresence(delegate(ScenePresence avatar)
  1847. {
  1848. if (!avatar.IsChildAgent && avatar.ParentID == part.LocalId && avatar.ParentUUID.IsZero())
  1849. avatar.StandUp();
  1850. if (!silent)
  1851. {
  1852. part.ClearUpdateSchedule();
  1853. if (part == m_rootPart)
  1854. {
  1855. if (!IsAttachment
  1856. || AttachedAvatar == avatar.ControllingClient.AgentId
  1857. || !HasPrivateAttachmentPoint)
  1858. {
  1859. // Send a kill object immediately
  1860. avatar.ControllingClient.SendKillObject(new List<uint> { part.LocalId });
  1861. //direct enqueue another delayed kill
  1862. avatar.ControllingClient.SendEntityUpdate(part,PrimUpdateFlags.Kill);
  1863. }
  1864. }
  1865. }
  1866. });
  1867. }
  1868. }
  1869. public void AddScriptLPS(int count)
  1870. {
  1871. //legacy
  1872. //m_scene.SceneGraph.AddToScriptLPS(count);
  1873. }
  1874. public void AddActiveScriptCount(int count)
  1875. {
  1876. SceneGraph d = m_scene.SceneGraph;
  1877. d.AddActiveScripts(count);
  1878. }
  1879. private const scriptEvents PhysicsNeeedSubsEvents = (
  1880. scriptEvents.collision | scriptEvents.collision_start | scriptEvents.collision_end |
  1881. scriptEvents.land_collision | scriptEvents.land_collision_start | scriptEvents.land_collision_end);
  1882. private scriptEvents lastRootPartPhysEvents = 0;
  1883. public scriptEvents ScriptEvents;
  1884. public void aggregateScriptEvents()
  1885. {
  1886. PrimFlags objectflagupdate = (PrimFlags)RootPart.GetEffectiveObjectFlags();
  1887. scriptEvents aggregatedScriptEvents = 0;
  1888. SceneObjectPart[] parts = m_parts.GetArray();
  1889. for (int i = 0; i < parts.Length; i++)
  1890. {
  1891. SceneObjectPart part = parts[i];
  1892. if (part != RootPart)
  1893. part.Flags = objectflagupdate;
  1894. aggregatedScriptEvents |= part.AggregatedScriptEvents;
  1895. }
  1896. m_scriptListens_atTarget = ((aggregatedScriptEvents & scriptEvents.at_target) != 0);
  1897. m_scriptListens_notAtTarget = ((aggregatedScriptEvents & scriptEvents.not_at_target) != 0);
  1898. if (!m_scriptListens_atTarget && !m_scriptListens_notAtTarget)
  1899. {
  1900. lock (m_targets)
  1901. {
  1902. if (m_targets.Count > 0)
  1903. {
  1904. m_targets.Clear();
  1905. m_scene.RemoveGroupTarget(this);
  1906. }
  1907. }
  1908. }
  1909. m_scriptListens_atRotTarget = ((aggregatedScriptEvents & scriptEvents.at_rot_target) != 0);
  1910. m_scriptListens_notAtRotTarget = ((aggregatedScriptEvents & scriptEvents.not_at_rot_target) != 0);
  1911. if (!m_scriptListens_atRotTarget && !m_scriptListens_notAtRotTarget)
  1912. {
  1913. lock (m_rotTargets)
  1914. {
  1915. if (m_rotTargets.Count > 0)
  1916. {
  1917. m_rotTargets.Clear();
  1918. m_scene.RemoveGroupTarget(this);
  1919. }
  1920. }
  1921. }
  1922. scriptEvents rootPartPhysEvents = RootPart.AggregatedScriptEvents;
  1923. rootPartPhysEvents &= PhysicsNeeedSubsEvents;
  1924. if (rootPartPhysEvents != lastRootPartPhysEvents)
  1925. {
  1926. lastRootPartPhysEvents = rootPartPhysEvents;
  1927. for (int i = 0; i < parts.Length; i++)
  1928. parts[i].UpdatePhysicsSubscribedEvents();
  1929. }
  1930. ScriptEvents = aggregatedScriptEvents;
  1931. ScheduleGroupForFullUpdate();
  1932. }
  1933. public void SetText(string text, Vector3 color, double alpha)
  1934. {
  1935. Color = Color.FromArgb(0xff - (int) (alpha * 0xff),
  1936. (int) (color.X * 0xff),
  1937. (int) (color.Y * 0xff),
  1938. (int) (color.Z * 0xff));
  1939. Text = text;
  1940. HasGroupChanged = true;
  1941. m_rootPart.ScheduleFullUpdate();
  1942. }
  1943. /// <summary>
  1944. /// Apply physics to this group
  1945. /// </summary>
  1946. public void ApplyPhysics()
  1947. {
  1948. SceneObjectPart[] parts = m_parts.GetArray();
  1949. if (parts.Length > 1)
  1950. {
  1951. ResetChildPrimPhysicsPositions();
  1952. // Apply physics to the root prim
  1953. m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive, true);
  1954. for (int i = 0; i < parts.Length; i++)
  1955. {
  1956. SceneObjectPart part = parts[i];
  1957. if (part.LocalId != m_rootPart.LocalId)
  1958. part.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), part.VolumeDetectActive, true);
  1959. }
  1960. if (m_rootPart.PhysActor is not null)
  1961. m_rootPart.PhysActor.Building = false;
  1962. }
  1963. else
  1964. {
  1965. // Apply physics to the root prim
  1966. m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive, false);
  1967. }
  1968. }
  1969. public void SetOwnerId(UUID userId)
  1970. {
  1971. ForEachPart(delegate(SceneObjectPart part)
  1972. {
  1973. if (part.OwnerID.NotEqual(userId))
  1974. {
  1975. if(part.GroupID.NotEqual(part.OwnerID))
  1976. part.LastOwnerID = part.OwnerID;
  1977. part.OwnerID = userId;
  1978. }
  1979. });
  1980. }
  1981. public void ForEachPart(Action<SceneObjectPart> whatToDo)
  1982. {
  1983. SceneObjectPart[] parts = m_parts.GetArray();
  1984. for (int i = 0; i < parts.Length; i++)
  1985. whatToDo(parts[i]);
  1986. }
  1987. #region Events
  1988. /// <summary>
  1989. /// Processes backup.
  1990. /// </summary>
  1991. /// <param name="datastore"></param>
  1992. public virtual void ProcessBackup(ISimulationDataService datastore, bool forcedBackup)
  1993. {
  1994. if (!Backup)
  1995. {
  1996. //m_log.DebugFormat(
  1997. // "[WATER WARS]: Ignoring backup of {0} {1} since object is not marked to be backed up", Name, UUID);
  1998. return;
  1999. }
  2000. if (IsDeleted || inTransit || UUID.IsZero())
  2001. {
  2002. //m_log.DebugFormat(
  2003. // "[WATER WARS]: Ignoring backup of {0} {1} since object is marked as already deleted", Name, UUID);
  2004. return;
  2005. }
  2006. if ((RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
  2007. return;
  2008. // Since this is the top of the section of call stack for backing up a particular scene object, don't let
  2009. // any exception propogate upwards.
  2010. try
  2011. {
  2012. // if shutting down then there will be nothing to handle the return so leave till next restart
  2013. if (!m_scene.ShuttingDown &&
  2014. m_scene.LoginsEnabled && // We're starting up or doing maintenance, don't mess with things
  2015. !m_scene.LoadingPrims) // Land may not be valid yet
  2016. {
  2017. ILandObject parcel = m_scene.LandChannel.GetLandObject(
  2018. m_rootPart.GroupPosition.X, m_rootPart.GroupPosition.Y);
  2019. if (parcel is not null && parcel.LandData is not null &&
  2020. parcel.LandData.OtherCleanTime != 0)
  2021. {
  2022. if (parcel.LandData.OwnerID.NotEqual(OwnerID) &&
  2023. (parcel.LandData.GroupID.NotEqual(GroupID) ||
  2024. parcel.LandData.GroupID.IsZero()))
  2025. {
  2026. if ((DateTime.UtcNow - RootPart.Rezzed).TotalMinutes >
  2027. parcel.LandData.OtherCleanTime)
  2028. {
  2029. // don't autoreturn if we have a sitting avatar
  2030. // mantis 7828 (but none the provided patchs)
  2031. if(GetSittingAvatarsCount() > 0)
  2032. {
  2033. // do not respect npcs
  2034. List<ScenePresence> sitters = GetSittingAvatars();
  2035. foreach(ScenePresence sp in sitters)
  2036. {
  2037. if(!sp.IsDeleted && !sp.IsNPC && sp.IsSatOnObject)
  2038. return;
  2039. }
  2040. }
  2041. DetachFromBackup();
  2042. m_log.Debug(
  2043. $"[SCENE OBJECT GROUP]: Returning object {RootPart.UUID} due to parcel autoreturn");
  2044. m_scene.AddReturn(OwnerID.Equals(GroupID) ? LastOwnerID : OwnerID, Name, AbsolutePosition, "parcel autoreturn");
  2045. m_scene.DeRezObjects(null, new List<uint>() { RootPart.LocalId }, UUID.Zero,
  2046. DeRezAction.Return, UUID.Zero, false);
  2047. return;
  2048. }
  2049. }
  2050. }
  2051. }
  2052. if (HasGroupChanged && m_scene.UseBackup)
  2053. {
  2054. // don't backup while it's selected or you're asking for changes mid stream.
  2055. if (isTimeToPersist() || forcedBackup)
  2056. {
  2057. if (RootPart.Shape.PCode == 9 && RootPart.Shape.State != 0)
  2058. {
  2059. RootPart.Shape.LastAttachPoint = RootPart.Shape.State;
  2060. RootPart.Shape.State = 0;
  2061. ScheduleGroupForFullUpdate();
  2062. }
  2063. SceneObjectGroup backup_group = Copy(false);
  2064. backup_group.RootPart.Velocity = RootPart.Velocity;
  2065. backup_group.RootPart.Acceleration = RootPart.Acceleration;
  2066. backup_group.RootPart.AngularVelocity = RootPart.AngularVelocity;
  2067. HasGroupChanged = false;
  2068. GroupContainsForeignPrims = false;
  2069. m_scene.EventManager.TriggerOnSceneObjectPreSave(backup_group, this);
  2070. datastore.StoreObject(backup_group, m_scene.RegionInfo.RegionID);
  2071. backup_group.ForEachPart(delegate(SceneObjectPart part)
  2072. {
  2073. part.Inventory.ProcessInventoryBackup(datastore);
  2074. if(part.KeyframeMotion is not null)
  2075. {
  2076. part.KeyframeMotion.Delete();
  2077. part.KeyframeMotion = null;
  2078. }
  2079. });
  2080. backup_group.Dispose();
  2081. backup_group = null;
  2082. }
  2083. }
  2084. }
  2085. catch (Exception e)
  2086. {
  2087. m_log.Error($"[SCENE]: Storing of {Name}, {UUID} in {m_scene.RegionInfo.RegionName} failed: {e.Message}");
  2088. }
  2089. }
  2090. #endregion
  2091. /// <summary>
  2092. /// Send the parts of this SOG to a single client
  2093. /// </summary>
  2094. /// <remarks>
  2095. /// Used when the client initially connects and when client sends RequestPrim packet
  2096. /// </remarks>
  2097. /// <param name="remoteClient"></param>
  2098. public void SendFullAnimUpdateToClient(IClientAPI remoteClient)
  2099. {
  2100. PrimUpdateFlags update = RootPart.Shape.MeshFlagEntry ?
  2101. PrimUpdateFlags.FullUpdatewithAnim :
  2102. PrimUpdateFlags.FullUpdate;
  2103. if (RootPart.Shape.RenderMaterials is not null &&
  2104. RootPart.Shape.ReflectionProbe is null &&
  2105. RootPart.Shape.RenderMaterials.overrides is not null &&
  2106. RootPart.Shape.RenderMaterials.overrides.Length > 0)
  2107. RootPart.SendUpdate(remoteClient, update | PrimUpdateFlags.MaterialOvr);
  2108. else
  2109. RootPart.SendUpdate(remoteClient, update);
  2110. SceneObjectPart[] parts = m_parts.GetArray();
  2111. for (int i = 0; i < parts.Length; i++)
  2112. {
  2113. SceneObjectPart part = parts[i];
  2114. if (part.LocalId != RootPart.LocalId)
  2115. {
  2116. if (part.Shape.RenderMaterials is not null &&
  2117. part.Shape.ReflectionProbe is null &&
  2118. part.Shape.RenderMaterials.overrides is not null &&
  2119. part.Shape.RenderMaterials.overrides.Length > 0)
  2120. part.SendUpdate(remoteClient, update | PrimUpdateFlags.MaterialOvr);
  2121. else
  2122. part.SendUpdate(remoteClient, update);
  2123. }
  2124. }
  2125. }
  2126. public void SendUpdateProbes(IClientAPI remoteClient)
  2127. {
  2128. PrimUpdateFlags update = PrimUpdateFlags.UpdateProbe;
  2129. RootPart.SendUpdate(remoteClient, update);
  2130. SceneObjectPart[] parts = m_parts.GetArray();
  2131. for (int i = 0; i < parts.Length; i++)
  2132. {
  2133. SceneObjectPart part = parts[i];
  2134. if (part.LocalId != RootPart.LocalId)
  2135. part.SendUpdate(remoteClient, update);
  2136. }
  2137. }
  2138. #region Copying
  2139. /// <summary>
  2140. /// Duplicates this object, including operations such as physics set up and attaching to the backup event.
  2141. /// </summary>
  2142. /// <param name="userExposed">True if the duplicate will immediately be in the scene, false otherwise</param>
  2143. /// <returns></returns>
  2144. public SceneObjectGroup Copy(bool userExposed)
  2145. {
  2146. m_dupeInProgress = true;
  2147. SceneObjectGroup dupe = (SceneObjectGroup)MemberwiseClone();
  2148. dupe.m_parts = new MapAndArray<UUID, SceneObjectPart>();
  2149. dupe.m_targets = new Dictionary<int, scriptPosTarget>();
  2150. dupe.m_rotTargets = new Dictionary<int, scriptRotTarget>();
  2151. dupe.m_targetsByScript = new Dictionary<UUID, List<int>>();
  2152. // a copy isnt backedup
  2153. dupe.Backup = false;
  2154. dupe.InvalidBoundsRadius();
  2155. // a copy is not in transit hopefully
  2156. dupe.inTransit = false;
  2157. // new group as no sitting avatars
  2158. dupe.m_sittingAvatars = new List<ScenePresence>();
  2159. if(LinksetData is not null)
  2160. dupe.LinksetData = LinksetData.Copy();
  2161. dupe.CopyRootPart(m_rootPart, OwnerID, GroupID, userExposed);
  2162. dupe.m_rootPart.LinkNum = m_rootPart.LinkNum;
  2163. if (userExposed)
  2164. dupe.m_rootPart.TrimPermissions();
  2165. List<SceneObjectPart> partList = new(m_parts.GetArray());
  2166. partList.Sort(delegate(SceneObjectPart p1, SceneObjectPart p2)
  2167. {
  2168. return p1.LinkNum.CompareTo(p2.LinkNum);
  2169. }
  2170. );
  2171. foreach (SceneObjectPart part in partList)
  2172. {
  2173. SceneObjectPart newPart;
  2174. if (part.UUID.NotEqual(m_rootPart.UUID))
  2175. {
  2176. newPart = dupe.CopyPart(part, OwnerID, GroupID, userExposed);
  2177. newPart.LinkNum = part.LinkNum;
  2178. //if (userExposed)
  2179. newPart.ParentID = dupe.m_rootPart.LocalId;
  2180. }
  2181. else
  2182. {
  2183. newPart = dupe.m_rootPart;
  2184. }
  2185. if (userExposed)
  2186. newPart.ApplyPhysics((uint)newPart.Flags,newPart.VolumeDetectActive,true);
  2187. // copy keyframemotion
  2188. if (part.KeyframeMotion is not null)
  2189. newPart.KeyframeMotion = part.KeyframeMotion.Copy(dupe);
  2190. }
  2191. if (userExposed)
  2192. {
  2193. if (dupe.m_rootPart.PhysActor is not null)
  2194. dupe.m_rootPart.PhysActor.Building = false; // tell physics to finish building
  2195. dupe.InvalidateDeepEffectivePerms();
  2196. dupe.HasGroupChanged = true;
  2197. dupe.AttachToBackup();
  2198. dupe.ScheduleGroupForUpdate(PrimUpdateFlags.FullUpdatewithAnimMatOvr);
  2199. }
  2200. dupe.InvalidatePartsLinkMaps();
  2201. m_dupeInProgress = false;
  2202. return dupe;
  2203. }
  2204. /// <summary>
  2205. /// Copy the given part as the root part of this scene object.
  2206. /// </summary>
  2207. /// <param name="part"></param>
  2208. /// <param name="cAgentID"></param>
  2209. /// <param name="cGroupID"></param>
  2210. public void CopyRootPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed)
  2211. {
  2212. SceneObjectPart newpart = part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, 0, userExposed);
  2213. //SceneObjectPart newpart = part.Copy(part.LocalId, OwnerID, GroupID, 0, userExposed);
  2214. //newpart.LocalId = m_scene.AllocateLocalId();
  2215. SetRootPart(newpart);
  2216. if (userExposed)
  2217. RootPart.Velocity = Vector3.Zero; // In case source is moving
  2218. }
  2219. public void ScriptSetPhysicsStatus(bool usePhysics)
  2220. {
  2221. if (usePhysics)
  2222. {
  2223. RootPart.KeyframeMotion?.Stop();
  2224. RootPart.KeyframeMotion = null;
  2225. }
  2226. UpdateFlags(usePhysics, IsTemporary, IsPhantom, IsVolumeDetect);
  2227. }
  2228. public void ScriptSetTemporaryStatus(bool makeTemporary)
  2229. {
  2230. UpdateFlags(UsesPhysics, makeTemporary, IsPhantom, IsVolumeDetect);
  2231. }
  2232. public void ScriptSetPhantomStatus(bool makePhantom)
  2233. {
  2234. UpdateFlags(UsesPhysics, IsTemporary, makePhantom, IsVolumeDetect);
  2235. }
  2236. public void ScriptSetVolumeDetect(bool makeVolumeDetect)
  2237. {
  2238. UpdateFlags(UsesPhysics, IsTemporary, IsPhantom, makeVolumeDetect);
  2239. }
  2240. public void applyImpulse(Vector3 impulse)
  2241. {
  2242. if (IsAttachment)
  2243. {
  2244. ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
  2245. avatar?.PushForce(impulse);
  2246. }
  2247. else
  2248. {
  2249. PhysicsActor pa = RootPart.PhysActor;
  2250. if (pa is not null)
  2251. {
  2252. // false to be applied as a impulse
  2253. pa.AddForce(impulse, false);
  2254. }
  2255. }
  2256. }
  2257. public void ApplyAngularImpulse(Vector3 impulse)
  2258. {
  2259. PhysicsActor pa = RootPart.PhysActor;
  2260. if (pa is not null)
  2261. {
  2262. if (!IsAttachment)
  2263. {
  2264. // false to be applied as a impulse
  2265. pa.AddAngularForce(impulse, false);
  2266. }
  2267. }
  2268. }
  2269. public Vector3 GetTorque()
  2270. {
  2271. return RootPart.Torque;
  2272. }
  2273. // This is used by both Double-Click Auto-Pilot and llMoveToTarget() in an attached object
  2274. public void MoveToTarget(Vector3 target, float tau)
  2275. {
  2276. if(tau > 0)
  2277. {
  2278. if (IsAttachment)
  2279. {
  2280. ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
  2281. if (avatar is not null && !avatar.IsSatOnObject)
  2282. avatar.MoveToTarget(target, false, true, false, tau);
  2283. }
  2284. else
  2285. {
  2286. PhysicsActor pa = RootPart.PhysActor;
  2287. if (pa is not null)
  2288. {
  2289. pa.PIDTarget = target;
  2290. pa.PIDTau = tau;
  2291. pa.PIDActive = true;
  2292. }
  2293. }
  2294. }
  2295. else
  2296. StopMoveToTarget();
  2297. }
  2298. public void StopMoveToTarget()
  2299. {
  2300. if (IsAttachment)
  2301. {
  2302. ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
  2303. avatar?.ResetMoveToTarget();
  2304. }
  2305. else
  2306. {
  2307. PhysicsActor pa = RootPart.PhysActor;
  2308. if (pa is not null)
  2309. pa.PIDActive = false;
  2310. RootPart.ScheduleTerseUpdate(); // send a stop information
  2311. }
  2312. }
  2313. public void RotLookAt(Quaternion target, float strength, float damping)
  2314. {
  2315. if(IsDeleted)
  2316. return;
  2317. // non physical is handle in LSL api
  2318. if(!UsesPhysics || IsAttachment)
  2319. return;
  2320. SceneObjectPart rootpart = m_rootPart;
  2321. if (rootpart is not null)
  2322. {
  2323. /* physics still doesnt suport this
  2324. if (rootpart.PhysActor is not null)
  2325. {
  2326. rootpart.PhysActor.APIDTarget = new Quaternion(target.X, target.Y, target.Z, target.W);
  2327. rootpart.PhysActor.APIDStrength = strength;
  2328. rootpart.PhysActor.APIDDamping = damping;
  2329. rootpart.PhysActor.APIDActive = true;
  2330. }
  2331. */
  2332. // so do it in rootpart
  2333. rootpart.RotLookAt(target, strength, damping);
  2334. }
  2335. }
  2336. public void StartLookAt(Quaternion target, float strength, float damping)
  2337. {
  2338. if(IsDeleted)
  2339. return;
  2340. // non physical is done by LSL APi
  2341. if(!UsesPhysics || IsAttachment)
  2342. return;
  2343. m_rootPart?.RotLookAt(target, strength, damping);
  2344. }
  2345. public void StopLookAt()
  2346. {
  2347. SceneObjectPart rootpart = m_rootPart;
  2348. if (rootpart is not null)
  2349. {
  2350. if (rootpart.PhysActor is not null)
  2351. {
  2352. rootpart.PhysActor.APIDActive = false;
  2353. }
  2354. rootpart.StopLookAt();
  2355. }
  2356. }
  2357. /// <summary>
  2358. /// Uses a PID to attempt to clamp the object on the Z axis at the given height over tau seconds.
  2359. /// </summary>
  2360. /// <param name="height">Height to hover. Height of zero disables hover.</param>
  2361. /// <param name="hoverType">Determines what the height is relative to </param>
  2362. /// <param name="tau">Number of seconds over which to reach target</param>
  2363. public void SetHoverHeight(float height, PIDHoverType hoverType, float tau)
  2364. {
  2365. PhysicsActor pa = null;
  2366. if(IsAttachment)
  2367. {
  2368. ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
  2369. if (avatar is not null)
  2370. pa = avatar.PhysicsActor;
  2371. }
  2372. else
  2373. pa = RootPart.PhysActor;
  2374. if (pa is not null)
  2375. {
  2376. if (height != 0f)
  2377. {
  2378. pa.PIDHoverHeight = height;
  2379. pa.PIDHoverType = hoverType;
  2380. pa.PIDHoverTau = tau;
  2381. pa.PIDHoverActive = true;
  2382. }
  2383. else
  2384. {
  2385. pa.PIDHoverActive = false;
  2386. }
  2387. }
  2388. }
  2389. /// <summary>
  2390. /// Set the owner of all linkset.
  2391. /// </summary>
  2392. /// <param name="cAgentID"></param>
  2393. /// <param name="cGroupID"></param>
  2394. public void SetOwner(UUID cAgentID, UUID cGroupID)
  2395. {
  2396. SceneObjectPart rpart = RootPart;
  2397. UUID oldowner = rpart.OwnerID;
  2398. ForEachPart(delegate(SceneObjectPart part)
  2399. {
  2400. if(part.GroupID.NotEqual(part.OwnerID))
  2401. part.LastOwnerID = part.OwnerID;
  2402. part.OwnerID = cAgentID;
  2403. part.GroupID = cGroupID;
  2404. });
  2405. if (oldowner.NotEqual(cAgentID))
  2406. {
  2407. // Apply Next Owner Permissions if we're not bypassing permissions
  2408. if (!m_scene.Permissions.BypassPermissions())
  2409. {
  2410. ApplyNextOwnerPermissions();
  2411. InvalidateEffectivePerms();
  2412. }
  2413. }
  2414. rpart.ScheduleFullUpdate();
  2415. }
  2416. /// <summary>
  2417. /// Make a copy of the given part.
  2418. /// </summary>
  2419. /// <param name="part"></param>
  2420. /// <param name="cAgentID"></param>
  2421. /// <param name="cGroupID"></param>
  2422. public SceneObjectPart CopyPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed)
  2423. {
  2424. SceneObjectPart newPart = part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, m_parts.Count, userExposed);
  2425. //SceneObjectPart newPart = part.Copy(part.LocalId, OwnerID, GroupID, m_parts.Count, userExposed);
  2426. //newPart.LocalId = m_scene.AllocateLocalId();
  2427. AddPart(newPart);
  2428. SetPartAsNonRoot(newPart);
  2429. return newPart;
  2430. }
  2431. /// <summary>
  2432. /// Reset the UUIDs for all the prims that make up this group.
  2433. /// </summary>
  2434. /// <remarks>
  2435. /// This is called by methods which want to add a new group to an existing scene, in order
  2436. /// to ensure that there are no clashes with groups already present.
  2437. /// </remarks>
  2438. public void ResetIDs()
  2439. {
  2440. lock (m_parts.SyncRoot)
  2441. {
  2442. SceneObjectPart[] partsList = m_parts.GetArray();
  2443. m_parts.Clear();
  2444. foreach (SceneObjectPart part in partsList)
  2445. {
  2446. part.ResetIDs(part.LinkNum); // Don't change link nums
  2447. m_parts.Add(part.UUID, part);
  2448. }
  2449. }
  2450. }
  2451. /// <summary>
  2452. ///
  2453. /// </summary>
  2454. /// <param name="part"></param>
  2455. public void ServiceObjectPropertiesFamilyRequest(IClientAPI remoteClient, UUID AgentID, uint RequestFlags)
  2456. {
  2457. remoteClient.SendObjectPropertiesFamilyData(RootPart, RequestFlags);
  2458. //remoteClient.SendObjectPropertiesFamilyData(RequestFlags, RootPart.UUID, RootPart.OwnerID, RootPart.GroupID, RootPart.BaseMask,
  2459. // RootPart.OwnerMask, RootPart.GroupMask, RootPart.EveryoneMask, RootPart.NextOwnerMask,
  2460. // RootPart.OwnershipCost, RootPart.ObjectSaleType, RootPart.SalePrice, RootPart.Category,
  2461. // RootPart.CreatorID, RootPart.Name, RootPart.Description);
  2462. }
  2463. public void SetPartOwner(SceneObjectPart part, UUID cAgentID, UUID cGroupID)
  2464. {
  2465. part.OwnerID = cAgentID;
  2466. part.GroupID = cGroupID;
  2467. }
  2468. #endregion
  2469. public override void Update()
  2470. {
  2471. // Check that the group was not deleted before the scheduled update
  2472. // FIXME: This is merely a temporary measure to reduce the incidence of failure when
  2473. // an object has been deleted from a scene before update was processed.
  2474. // A more fundamental overhaul of the update mechanism is required to eliminate all
  2475. // the race conditions.
  2476. if (IsDeleted || inTransit)
  2477. return;
  2478. if (IsAttachment)
  2479. {
  2480. ScenePresence sp = m_scene.GetScenePresence(AttachedAvatar);
  2481. sp?.SendAttachmentScheduleUpdate(this);
  2482. return;
  2483. }
  2484. // while physics doesn't suports LookAt, we do it in RootPart
  2485. if (!IsSelected)
  2486. RootPart.UpdateLookAt();
  2487. double now = Util.GetTimeStampMS();
  2488. RootPart.SendScheduledUpdates(now);
  2489. SceneObjectPart[] parts = m_parts.GetArray();
  2490. for (int i = 0; i < parts.Length; i++)
  2491. {
  2492. SceneObjectPart part = parts[i];
  2493. if(part != RootPart)
  2494. part.SendScheduledUpdates(now);
  2495. }
  2496. }
  2497. /// <summary>
  2498. /// Schedule a full update for this scene object to all interested viewers.
  2499. /// </summary>
  2500. /// <remarks>
  2501. /// Ultimately, this should be managed such that region modules can invoke it at the end of a set of operations
  2502. /// so that either all changes are sent at once. However, currently, a large amount of internal
  2503. /// code will set this anyway when some object properties are changed.
  2504. /// </remarks>
  2505. public void ScheduleGroupForFullUpdate()
  2506. {
  2507. //if (IsAttachment)
  2508. // m_log.DebugFormat("[SOG]: Scheduling full update for {0} {1}", Name, LocalId);
  2509. if (Scene.GetNumberOfClients() == 0)
  2510. return;
  2511. RootPart.ScheduleFullUpdate();
  2512. SceneObjectPart[] parts = m_parts.GetArray();
  2513. for (int i = 0; i < parts.Length; i++)
  2514. {
  2515. SceneObjectPart part = parts[i];
  2516. if (part != RootPart)
  2517. part.ScheduleFullUpdate();
  2518. }
  2519. }
  2520. public void ScheduleGroupForFullAnimUpdate()
  2521. {
  2522. //if (IsAttachment)
  2523. // m_log.DebugFormat("[SOG]: Scheduling full update for {0} {1}", Name, LocalId);
  2524. if (Scene.GetNumberOfClients() == 0)
  2525. return;
  2526. SceneObjectPart[] parts = m_parts.GetArray();
  2527. if (!RootPart.Shape.MeshFlagEntry)
  2528. {
  2529. RootPart.ScheduleFullUpdate();
  2530. for (int i = 0; i < parts.Length; i++)
  2531. {
  2532. SceneObjectPart part = parts[i];
  2533. if (part != RootPart)
  2534. part.ScheduleFullUpdate();
  2535. }
  2536. return;
  2537. }
  2538. RootPart.ScheduleFullAnimUpdate();
  2539. for (int i = 0; i < parts.Length; i++)
  2540. {
  2541. SceneObjectPart part = parts[i];
  2542. if (part != RootPart)
  2543. part.ScheduleFullAnimUpdate();
  2544. }
  2545. }
  2546. public void ScheduleGroupForUpdate(PrimUpdateFlags update)
  2547. {
  2548. //if (IsAttachment)
  2549. // m_log.DebugFormat("[SOG]: Scheduling full update for {0} {1}", Name, LocalId);
  2550. if (Scene.GetNumberOfClients() == 0)
  2551. return;
  2552. SceneObjectPart[] parts = m_parts.GetArray();
  2553. if (!RootPart.Shape.MeshFlagEntry)
  2554. update &= ~PrimUpdateFlags.Animations;
  2555. RootPart.ScheduleUpdate(update);
  2556. for (int i = 0; i < parts.Length; i++)
  2557. {
  2558. SceneObjectPart part = parts[i];
  2559. if (part != RootPart)
  2560. part.ScheduleUpdate(update);
  2561. }
  2562. }
  2563. /// <summary>
  2564. /// Schedule a terse update for this scene object to all interested viewers.
  2565. /// </summary>
  2566. /// <remarks>
  2567. /// Ultimately, this should be managed such that region modules can invoke it at the end of a set of operations
  2568. /// so that either all changes are sent at once. However, currently, a large amount of internal
  2569. /// code will set this anyway when some object properties are changed.
  2570. /// </remarks>
  2571. public void ScheduleGroupForTerseUpdate()
  2572. {
  2573. //m_log.DebugFormat("[SOG]: Scheduling terse update for {0} {1}", Name, UUID);
  2574. SceneObjectPart[] parts = m_parts.GetArray();
  2575. for (int i = 0; i < parts.Length; i++)
  2576. parts[i].ScheduleTerseUpdate();
  2577. }
  2578. /// <summary>
  2579. /// Immediately send an update for this scene object's root prim only.
  2580. /// This is for updates regarding the object as a whole, and none of its parts in particular.
  2581. /// Note: this may not be used by opensim (it probably should) but it's used by
  2582. /// external modules.
  2583. /// </summary>
  2584. public void SendGroupRootTerseUpdate()
  2585. {
  2586. if (IsDeleted || inTransit)
  2587. return;
  2588. RootPart.SendTerseUpdateToAllClients();
  2589. }
  2590. public void QueueForUpdateCheck()
  2591. {
  2592. if (m_scene is null) // Need to check here as it's null during object creation
  2593. return;
  2594. m_scene.SceneGraph.AddToUpdateList(this);
  2595. }
  2596. /// <summary>
  2597. /// Immediately send a terse update for this scene object.
  2598. /// </summary>
  2599. public void SendGroupTerseUpdate()
  2600. {
  2601. if (IsDeleted || inTransit)
  2602. return;
  2603. if (IsAttachment)
  2604. {
  2605. ScenePresence sp = m_scene.GetScenePresence(AttachedAvatar);
  2606. if (sp is not null)
  2607. {
  2608. sp.SendAttachmentUpdate(this, PrimUpdateFlags.TerseUpdate);
  2609. return;
  2610. }
  2611. }
  2612. SceneObjectPart[] parts = m_parts.GetArray();
  2613. for (int i = 0; i < parts.Length; i++)
  2614. parts[i].SendTerseUpdateToAllClientsInternal();
  2615. }
  2616. /// <summary>
  2617. /// Send metadata about the root prim (name, description, sale price, permissions, etc.) to a client.
  2618. /// </summary>
  2619. /// <param name="client"></param>
  2620. public void SendPropertiesToClient(IClientAPI client)
  2621. {
  2622. m_rootPart.SendPropertiesToClient(client);
  2623. }
  2624. #region SceneGroupPart Methods
  2625. /// <summary>
  2626. /// Get the child part by LinkNum
  2627. /// </summary>
  2628. /// <param name="linknum"></param>
  2629. /// <returns>null if no child part with that linknum or child part</returns>
  2630. public SceneObjectPart GetLinkNumPart(int linknum)
  2631. {
  2632. if (linknum < 2)
  2633. {
  2634. return linknum switch
  2635. {
  2636. <0 => null,
  2637. // old code and sl do ignore linknum = 0 on linksets with more than one prim
  2638. 0 => m_parts.Count > 1 ? null : RootPart,
  2639. _ => RootPart
  2640. };
  2641. }
  2642. Span<SceneObjectPart> parts = m_parts.GetArray().AsSpan();
  2643. if (linknum <= parts.Length)
  2644. {
  2645. SceneObjectPart sop = parts[linknum - 1];
  2646. if (sop.LinkNum == linknum)
  2647. return sop;
  2648. }
  2649. for (int i = 0; i < parts.Length; i++)
  2650. {
  2651. if (parts[i].LinkNum == linknum)
  2652. return parts[i];
  2653. }
  2654. return null;
  2655. }
  2656. /// <summary>
  2657. /// Get a part with a given UUID
  2658. /// </summary>
  2659. /// <param name="primID"></param>
  2660. /// <returns>null if a part with the primID was not found</returns>
  2661. public SceneObjectPart GetPart(UUID primID)
  2662. {
  2663. if(m_parts.TryGetValue(primID, out SceneObjectPart childPart))
  2664. return childPart;
  2665. return null;
  2666. }
  2667. /// <summary>
  2668. /// Get a part with a given local ID
  2669. /// </summary>
  2670. /// <param name="localID"></param>
  2671. /// <returns>null if a part with the local ID was not found</returns>
  2672. public SceneObjectPart GetPart(uint localID)
  2673. {
  2674. SceneObjectPart sop = m_scene.GetSceneObjectPart(localID);
  2675. if(sop.ParentGroup.LocalId == LocalId)
  2676. return sop;
  2677. return null;
  2678. }
  2679. #endregion
  2680. #region Packet Handlers
  2681. /// <summary>
  2682. /// Link the prims in a given group to this group
  2683. /// </summary>
  2684. /// <remarks>
  2685. /// Do not call this method directly - use Scene.LinkObjects() instead to avoid races between threads.
  2686. /// FIXME: There are places where scripts call these methods directly without locking. This is a potential race condition.
  2687. /// </remarks>
  2688. /// <param name="objectGroup">The group of prims which should be linked to this group</param>
  2689. public void LinkToGroup(SceneObjectGroup objectGroup)
  2690. {
  2691. LinkToGroup(objectGroup, false);
  2692. }
  2693. // Link an existing group to this group.
  2694. // The group being linked need not be a linkset -- it can have just one prim.
  2695. public void LinkToGroup(SceneObjectGroup objectGroup, bool insert)
  2696. {
  2697. //m_log.DebugFormat(
  2698. // "[SCENE OBJECT GROUP]: Linking group with root part {0}, {1} to group with root part {2}, {3}",
  2699. // objectGroup.RootPart.Name, objectGroup.RootPart.UUID, RootPart.Name, RootPart.UUID);
  2700. // Linking to ourselves is not a valid operation.
  2701. if (objectGroup == this)
  2702. return;
  2703. // If the configured linkset capacity is greater than zero,
  2704. // and the new linkset would have a prim count higher than this
  2705. // value, do not link it.
  2706. if (m_scene.m_linksetCapacity > 0 &&
  2707. (PrimCount + objectGroup.PrimCount) >
  2708. m_scene.m_linksetCapacity)
  2709. {
  2710. m_log.DebugFormat(
  2711. "[SCENE OBJECT GROUP]: Cannot link group with root" +
  2712. " part {0}, {1} ({2} prims) to group with root part" +
  2713. " {3}, {4} ({5} prims) because the new linkset" +
  2714. " would exceed the configured maximum of {6}",
  2715. objectGroup.RootPart.Name, objectGroup.RootPart.UUID,
  2716. objectGroup.PrimCount, RootPart.Name, RootPart.UUID,
  2717. PrimCount, m_scene.m_linksetCapacity);
  2718. return;
  2719. }
  2720. // physical prims count limit
  2721. // not very eficient :(
  2722. if (UsesPhysics && m_scene.m_linksetPhysCapacity > 0 && (PrimCount + objectGroup.PrimCount) >
  2723. m_scene.m_linksetPhysCapacity)
  2724. {
  2725. int cntr = 0;
  2726. foreach (SceneObjectPart part in Parts)
  2727. {
  2728. if (part.PhysicsShapeType != (byte)PhysicsShapeType.None)
  2729. cntr++;
  2730. }
  2731. foreach (SceneObjectPart part in objectGroup.Parts)
  2732. {
  2733. if (part.PhysicsShapeType != (byte)PhysicsShapeType.None)
  2734. cntr++;
  2735. }
  2736. if (cntr > m_scene.m_linksetPhysCapacity)
  2737. {
  2738. // cancel physics
  2739. RootPart.Flags &= ~PrimFlags.Physics;
  2740. ApplyPhysics();
  2741. }
  2742. }
  2743. if(objectGroup.LinksetData is not null)
  2744. {
  2745. LinksetData ??= new LinksetData(m_scene.m_LinkSetDataLimit);
  2746. LinksetData.MergeOther(objectGroup.LinksetData);
  2747. objectGroup.LinksetData = null;
  2748. }
  2749. // 'linkPart' == the root of the group being linked into this group
  2750. SceneObjectPart linkPart = objectGroup.m_rootPart;
  2751. if (m_rootPart.PhysActor is not null)
  2752. m_rootPart.PhysActor.Building = true;
  2753. if (linkPart.PhysActor is not null)
  2754. linkPart.PhysActor.Building = true;
  2755. // physics flags from group to be applied to linked parts
  2756. bool grpusephys = UsesPhysics;
  2757. bool grptemporary = IsTemporary;
  2758. // Remember where the group being linked thought it was
  2759. Vector3 oldGroupPosition = linkPart.GroupPosition;
  2760. Quaternion oldRootRotation = linkPart.RotationOffset;
  2761. // A linked SOP remembers its location and rotation relative to the root of a group.
  2762. // Convert the root of the group being linked to be relative to the
  2763. // root of the group being linked to.
  2764. // Note: Some of the assignments have complex side effects.
  2765. // First move the new group's root SOP's position to be relative to ours
  2766. // (radams1: Not sure if the multiple setting of OffsetPosition is required. If not,
  2767. // this code can be reordered to have a more logical flow.)
  2768. linkPart.setOffsetPosition(linkPart.GroupPosition - AbsolutePosition);
  2769. // Assign the new parent to the root of the old group
  2770. linkPart.ParentID = m_rootPart.LocalId;
  2771. // Now that it's a child, it's group position is our root position
  2772. linkPart.setGroupPosition(AbsolutePosition);
  2773. // Rotate the linking root SOP's position to be relative to the new root prim
  2774. Quaternion parentRot = m_rootPart.RotationOffset;
  2775. // Make the linking root SOP's rotation relative to the new root prim
  2776. Quaternion oldRot = linkPart.RotationOffset;
  2777. Quaternion newRot = Quaternion.Conjugate(parentRot) * oldRot;
  2778. linkPart.setRotationOffset(newRot);
  2779. Vector3 axPos = linkPart.OffsetPosition;
  2780. axPos *= Quaternion.Conjugate(parentRot);
  2781. linkPart.OffsetPosition = axPos;
  2782. // If there is only one SOP in a SOG, the LinkNum is zero. I.e., not a linkset.
  2783. // Now that we know this SOG has at least two SOPs in it, the new root
  2784. // SOP becomes the first in the linkset.
  2785. if (m_rootPart.LinkNum == 0)
  2786. m_rootPart.LinkNum = 1;
  2787. lock (m_parts.SyncRoot)
  2788. {
  2789. // Calculate the new link number for the old root SOP
  2790. int linkNum;
  2791. if (insert)
  2792. {
  2793. linkNum = 2;
  2794. int insertSize = objectGroup.PrimCount;
  2795. foreach (SceneObjectPart part in Parts)
  2796. {
  2797. if (part.LinkNum > 1)
  2798. part.LinkNum += insertSize;
  2799. }
  2800. }
  2801. else
  2802. {
  2803. linkNum = PrimCount + 1;
  2804. }
  2805. // Add the old root SOP as a part in our group's list
  2806. m_parts.Add(linkPart.UUID, linkPart);
  2807. linkPart.SetParent(this);
  2808. //linkPart.CreateSelected = true;
  2809. linkPart.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (linkPart.Flags & PrimFlags.Phantom) != 0), linkPart.VolumeDetectActive || RootPart.VolumeDetectActive, true);
  2810. // If the added SOP is physical, also tell the physics engine about the link relationship.
  2811. if (linkPart.PhysActor is not null && m_rootPart.PhysActor is not null && m_rootPart.PhysActor.IsPhysical)
  2812. {
  2813. linkPart.PhysActor.link(m_rootPart.PhysActor);
  2814. }
  2815. linkPart.LinkNum = linkNum++;
  2816. linkPart.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect, false);
  2817. // Get a list of the SOP's in the source group in order of their linknum's.
  2818. SceneObjectPart[] ogParts = objectGroup.Parts;
  2819. Array.Sort(ogParts, delegate(SceneObjectPart a, SceneObjectPart b)
  2820. {
  2821. return a.LinkNum - b.LinkNum;
  2822. });
  2823. // Add each of the SOP's from the source linkset to our linkset
  2824. for (int i = 0; i < ogParts.Length; i++)
  2825. {
  2826. SceneObjectPart part = ogParts[i];
  2827. if (part.UUID != objectGroup.m_rootPart.UUID)
  2828. {
  2829. LinkNonRootPart(part, oldGroupPosition, oldRootRotation, linkNum++);
  2830. // Update the physics flags for the newly added SOP
  2831. // (Is this necessary? LinkNonRootPart() has already called UpdatePrimFlags but with different flags!??)
  2832. part.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (part.Flags & PrimFlags.Phantom) != 0), part.VolumeDetectActive, true);
  2833. // If the added SOP is physical, also tell the physics engine about the link relationship.
  2834. if (part.PhysActor is not null && m_rootPart.PhysActor is not null && m_rootPart.PhysActor.IsPhysical)
  2835. {
  2836. part.PhysActor.link(m_rootPart.PhysActor);
  2837. }
  2838. }
  2839. part.ClearUndoState();
  2840. }
  2841. }
  2842. // Now that we've aquired all of the old SOG's parts, remove the old SOG from the scene.
  2843. m_scene.UnlinkSceneObject(objectGroup, true);
  2844. objectGroup.m_parts.Clear(); // do not dispose the parts moved to new group
  2845. objectGroup.Dispose();
  2846. // Can't do this yet since backup still makes use of the root part without any synchronization
  2847. // objectGroup.m_rootPart = null;
  2848. // If linking prims with different permissions, fix them
  2849. AdjustChildPrimPermissions(false);
  2850. GroupContainsForeignPrims = true;
  2851. AttachToBackup();
  2852. // Here's the deal, this is ABSOLUTELY CRITICAL so the physics scene gets the update about the
  2853. // position of linkset prims. IF YOU CHANGE THIS, YOU MUST TEST colliding with just linked and
  2854. // unmoved prims!
  2855. ResetChildPrimPhysicsPositions();
  2856. InvalidBoundsRadius();
  2857. InvalidatePartsLinkMaps();
  2858. if (m_rootPart.PhysActor is not null)
  2859. m_rootPart.PhysActor.Building = false;
  2860. //HasGroupChanged = true;
  2861. //ScheduleGroupForFullUpdate();
  2862. }
  2863. /// <summary>
  2864. /// Delink the given prim from this group. The delinked prim is established as
  2865. /// an independent SceneObjectGroup.
  2866. /// </summary>
  2867. /// <remarks>
  2868. /// FIXME: This method should not be called directly since it bypasses update locking, allowing a potential race
  2869. /// condition. But currently there is no
  2870. /// alternative method that does take a lonk to delink a single prim.
  2871. /// </remarks>
  2872. /// <param name="partID"></param>
  2873. /// <returns>The object group of the newly delinked prim. Null if part could not be found</returns>
  2874. public SceneObjectGroup DelinkFromGroup(uint partID)
  2875. {
  2876. return DelinkFromGroup(partID, true);
  2877. }
  2878. /// <summary>
  2879. /// Delink the given prim from this group. The delinked prim is established as
  2880. /// an independent SceneObjectGroup.
  2881. /// </summary>
  2882. /// <remarks>
  2883. /// FIXME: This method should not be called directly since it bypasses update locking, allowing a potential race
  2884. /// condition. But currently there is no
  2885. /// alternative method that does take a lonk to delink a single prim.
  2886. /// </remarks>
  2887. /// <param name="partID"></param>
  2888. /// <param name="sendEvents"></param>
  2889. /// <returns>The object group of the newly delinked prim. Null if part could not be found</returns>
  2890. public SceneObjectGroup DelinkFromGroup(uint partID, bool sendEvents)
  2891. {
  2892. SceneObjectPart linkPart = GetPart(partID);
  2893. if (linkPart is not null)
  2894. {
  2895. return DelinkFromGroup(linkPart, sendEvents);
  2896. }
  2897. else
  2898. {
  2899. m_log.Warn($"[SCENE OBJECT GROUP]: DelinkFromGroup(): prim {partID} not found in object {UUID}");
  2900. return null;
  2901. }
  2902. }
  2903. /// <summary>
  2904. /// Delink the given prim from this group. The delinked prim is established as
  2905. /// an independent SceneObjectGroup.
  2906. /// </summary>
  2907. /// <remarks>
  2908. /// FIXME: This method should not be called directly since it bypasses update locking, allowing a potential race
  2909. /// condition. But currently there is no
  2910. /// alternative method that does take a lock to delink a single prim.
  2911. /// </remarks>
  2912. /// <param name="partID"></param>
  2913. /// <param name="sendEvents"></param>
  2914. /// <returns>The object group of the newly delinked prim.</returns>
  2915. public SceneObjectGroup DelinkFromGroup(SceneObjectPart linkPart, bool sendEvents)
  2916. {
  2917. //m_log.DebugFormat(
  2918. // "[SCENE OBJECT GROUP]: Delinking part {0}, {1} from group with root part {2}, {3}",
  2919. // linkPart.Name, linkPart.UUID, RootPart.Name, RootPart.UUID);
  2920. if (m_rootPart.PhysActor is not null)
  2921. m_rootPart.PhysActor.Building = true;
  2922. linkPart.ClearUndoState();
  2923. Vector3 worldPos = linkPart.GetWorldPosition();
  2924. Quaternion worldRot = linkPart.GetWorldRotation();
  2925. // Remove the part from this object
  2926. lock (m_parts.SyncRoot)
  2927. {
  2928. m_parts.Remove(linkPart.UUID);
  2929. SceneObjectPart[] parts = m_parts.GetArray();
  2930. // Rejigger the linknum's of the remaining SOP's to fill any gap
  2931. if (parts.Length == 1 && RootPart is not null)
  2932. {
  2933. // Single prim left
  2934. RootPart.LinkNum = 0;
  2935. }
  2936. else
  2937. {
  2938. for (int i = 0; i < parts.Length; i++)
  2939. {
  2940. SceneObjectPart part = parts[i];
  2941. if (part.LinkNum > linkPart.LinkNum)
  2942. part.LinkNum--;
  2943. }
  2944. }
  2945. }
  2946. linkPart.ParentID = 0;
  2947. linkPart.LinkNum = 0;
  2948. PhysicsActor linkPartPa = linkPart.PhysActor;
  2949. // Remove the SOP from the physical scene.
  2950. // If the new SOG is physical, it is re-created later.
  2951. // (There is a problem here in that we have not yet told the physics
  2952. // engine about the delink. Someday, linksets should be made first
  2953. // class objects in the physics engine interface).
  2954. if (linkPartPa is not null)
  2955. {
  2956. m_scene.PhysicsScene.RemovePrim(linkPartPa);
  2957. m_scene.RemovePhysicalPrim(1);
  2958. linkPart.PhysActor = null;
  2959. }
  2960. // We need to reset the child part's position
  2961. // ready for life as a separate object after being a part of another object
  2962. /* This commented out code seems to recompute what GetWorldPosition already does.
  2963. * Replace with a call to GetWorldPosition (before unlinking)
  2964. Quaternion parentRot = m_rootPart.RotationOffset;
  2965. Vector3 axPos = linkPart.OffsetPosition;
  2966. axPos *= parentRot;
  2967. linkPart.OffsetPosition = new Vector3(axPos.X, axPos.Y, axPos.Z);
  2968. linkPart.GroupPosition = AbsolutePosition + linkPart.OffsetPosition;
  2969. linkPart.OffsetPosition = new Vector3(0, 0, 0);
  2970. */
  2971. linkPart.setGroupPosition(worldPos);
  2972. linkPart.setOffsetPosition(Vector3.Zero);
  2973. linkPart.setRotationOffset(worldRot);
  2974. // Create a new SOG to go around this unlinked and unattached SOP
  2975. SceneObjectGroup objectGroup = new(linkPart);
  2976. m_scene.AddNewSceneObject(objectGroup, true);
  2977. linkPart.Rezzed = RootPart.Rezzed;
  2978. InvalidBoundsRadius();
  2979. InvalidatePartsLinkMaps();
  2980. InvalidateEffectivePerms();
  2981. if (m_rootPart.PhysActor is not null)
  2982. m_rootPart.PhysActor.Building = false;
  2983. objectGroup.HasGroupChangedDueToDelink = true;
  2984. if (sendEvents)
  2985. linkPart.TriggerScriptChangedEvent(Changed.LINK);
  2986. return objectGroup;
  2987. }
  2988. /* working on it
  2989. public void DelinkFromGroup(List<SceneObjectPart> linkParts, bool sendEvents)
  2990. {
  2991. //m_log.DebugFormat(
  2992. // "[SCENE OBJECT GROUP]: Delinking part {0}, {1} from group with root part {2}, {3}",
  2993. // linkPart.Name, linkPart.UUID, RootPart.Name, RootPart.UUID);
  2994. if(PrimCount == 1)
  2995. return;
  2996. if (m_rootPart.PhysActor is not null)
  2997. m_rootPart.PhysActor.Building = true;
  2998. bool unlinkroot = false;
  2999. foreach(SceneObjectPart linkPart in linkParts)
  3000. {
  3001. // first we only remove child parts
  3002. if(linkPart.LocalId == m_rootPart.LocalId)
  3003. {
  3004. unlinkroot = true;
  3005. continue;
  3006. }
  3007. lock (m_parts.SyncRoot)
  3008. if(!m_parts.Remove(linkPart.UUID))
  3009. continue;
  3010. linkPart.ClearUndoState();
  3011. Vector3 worldPos = linkPart.GetWorldPosition();
  3012. Quaternion worldRot = linkPart.GetWorldRotation();
  3013. linkPart.ParentID = 0;
  3014. linkPart.LinkNum = 0;
  3015. PhysicsActor linkPartPa = linkPart.PhysActor;
  3016. // Remove the SOP from the physical scene.
  3017. // If the new SOG is physical, it is re-created later.
  3018. // (There is a problem here in that we have not yet told the physics
  3019. // engine about the delink. Someday, linksets should be made first
  3020. // class objects in the physics engine interface).
  3021. if (linkPartPa is not null)
  3022. {
  3023. m_scene.PhysicsScene.RemovePrim(linkPartPa);
  3024. linkPart.PhysActor = null;
  3025. }
  3026. linkPart.setGroupPosition(worldPos);
  3027. linkPart.setOffsetPosition(Vector3.Zero);
  3028. linkPart.setRotationOffset(worldRot);
  3029. // Create a new SOG to go around this unlinked and unattached SOP
  3030. SceneObjectGroup objectGroup = new SceneObjectGroup(linkPart);
  3031. m_scene.AddNewSceneObject(objectGroup, true);
  3032. linkPart.Rezzed = RootPart.Rezzed;
  3033. // this is as it seems to be in sl now
  3034. if(linkPart.PhysicsShapeType == (byte)PhysShapeType.none)
  3035. linkPart.PhysicsShapeType = linkPart.DefaultPhysicsShapeType(); // root prims can't have type none for now
  3036. objectGroup.HasGroupChangedDueToDelink = true;
  3037. if (sendEvents)
  3038. linkPart.TriggerScriptChangedEvent(Changed.LINK);
  3039. }
  3040. if(unlinkroot)
  3041. {
  3042. //TODO
  3043. }
  3044. lock (m_parts.SyncRoot)
  3045. {
  3046. SceneObjectPart[] parts = m_parts.GetArray();
  3047. if (parts.Length == 1)
  3048. {
  3049. // Single prim left
  3050. m_rootPart.LinkNum = 0;
  3051. }
  3052. else
  3053. {
  3054. m_rootPart.LinkNum = 1;
  3055. int linknum = 2;
  3056. for (int i = 1; i < parts.Length; i++)
  3057. parts[i].LinkNum = linknum++;
  3058. }
  3059. }
  3060. InvalidBoundsRadius();
  3061. if (m_rootPart.PhysActor is not null)
  3062. m_rootPart.PhysActor.Building = false;
  3063. // When we delete a group, we currently have to force persist to the database if the object id has changed
  3064. // (since delete works by deleting all rows which have a given object id)
  3065. Scene.SimulationDataService.RemoveObject(UUID, Scene.RegionInfo.RegionID);
  3066. HasGroupChangedDueToDelink = true;
  3067. TriggerScriptChangedEvent(Changed.LINK);
  3068. return;
  3069. }
  3070. */
  3071. /// <summary>
  3072. /// Stop this object from being persisted over server restarts.
  3073. /// </summary>
  3074. /// <param name="objectGroup"></param>
  3075. public virtual void DetachFromBackup()
  3076. {
  3077. if (m_scene is not null)
  3078. {
  3079. m_scene.SceneGraph.FireDetachFromBackup(this);
  3080. if (Backup)
  3081. m_scene.EventManager.OnBackup -= ProcessBackup;
  3082. }
  3083. Backup = false;
  3084. }
  3085. // This links an SOP from a previous linkset into my linkset.
  3086. // The trick is that the SOP's position and rotation are relative to the old root SOP's
  3087. // so we are passed in the position and rotation of the old linkset so this can
  3088. // unjigger this SOP's position and rotation from the previous linkset and
  3089. // then make them relative to my linkset root.
  3090. private void LinkNonRootPart(SceneObjectPart part, Vector3 oldGroupPosition, Quaternion oldGroupRotation, int linkNum)
  3091. {
  3092. Quaternion parentRot = oldGroupRotation;
  3093. Quaternion oldRot = part.RotationOffset;
  3094. // Move our position in world
  3095. Vector3 axPos = part.OffsetPosition;
  3096. axPos *= parentRot;
  3097. Vector3 newPos = oldGroupPosition + axPos;
  3098. part.setGroupPosition(newPos);
  3099. part.setOffsetPosition(Vector3.Zero);
  3100. // Compution our rotation in world
  3101. Quaternion worldRot = parentRot * oldRot;
  3102. part.RotationOffset = worldRot;
  3103. // Add this SOP to our linkset
  3104. part.SetParent(this);
  3105. part.ParentID = m_rootPart.LocalId;
  3106. m_parts.Add(part.UUID, part);
  3107. part.LinkNum = linkNum;
  3108. // Compute the new position of this SOP relative to the group position
  3109. part.setOffsetPosition(newPos - AbsolutePosition);
  3110. // (radams1 20120711: I don't know why part.OffsetPosition is set multiple times.
  3111. // It would have the affect of setting the physics engine position multiple
  3112. // times. In theory, that is not necessary but I don't have a good linkset
  3113. // test to know that cleaning up this code wouldn't break things.)
  3114. // Compute the SOP's rotation relative to the rotation of the group.
  3115. parentRot = m_rootPart.RotationOffset;
  3116. Quaternion newRot = Quaternion.Conjugate(parentRot) * worldRot;
  3117. part.setRotationOffset(newRot);
  3118. Vector3 pos = part.OffsetPosition;
  3119. pos *= Quaternion.Conjugate(parentRot);
  3120. part.OffsetPosition = pos; // update position and orientation on physics also
  3121. // Since this SOP's state has changed, push those changes into the physics engine
  3122. // and the simulator.
  3123. // done on caller
  3124. //part.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect, false);
  3125. }
  3126. double lastTouchTime = 0;
  3127. /// <summary>
  3128. /// If object is physical, apply force to move it around
  3129. /// If object is not physical, just put it at the resulting location
  3130. /// </summary>
  3131. /// <param name="partID">Part ID to check for grab</param>
  3132. /// <param name="offset">Always seems to be 0,0,0, so ignoring</param>
  3133. /// <param name="pos">New position. We do the math here to turn it into a force</param>
  3134. /// <param name="remoteClient"></param>
  3135. public void GrabMovement(UUID partID, Vector3 offset, Vector3 pos, IClientAPI remoteClienth)
  3136. {
  3137. if (m_scene.EventManager.TriggerGroupMove(UUID, pos))
  3138. {
  3139. if (BlockGrabOverride)
  3140. return;
  3141. SceneObjectPart part = GetPart(partID);
  3142. if (part is null)
  3143. return;
  3144. if (part.BlockGrab)
  3145. return;
  3146. PhysicsActor pa = m_rootPart.PhysActor;
  3147. if (pa is not null && pa.IsPhysical)
  3148. {
  3149. // empirically convert distance diference to a impulse
  3150. Vector3 grabforce = pos - AbsolutePosition;
  3151. grabforce *= pa.Mass * 0.1f;
  3152. pa.AddForce(grabforce, false);
  3153. }
  3154. else
  3155. {
  3156. if(IsAttachment)
  3157. return;
  3158. // block movement if there was a touch at start
  3159. double now = Util.GetTimeStampMS();
  3160. if (now - lastTouchTime < 250)
  3161. {
  3162. lastTouchTime = now;
  3163. return;
  3164. }
  3165. // a touch or pass may had become active ??
  3166. if (((part.ScriptEvents & scriptEvents.anytouch) != 0) || (RootPart.ScriptEvents & scriptEvents.anytouch) != 0)
  3167. {
  3168. lastTouchTime = now;
  3169. return;
  3170. }
  3171. lastTouchTime = 0;
  3172. UpdateGroupPosition(pos);
  3173. }
  3174. }
  3175. }
  3176. /// <summary>
  3177. /// If object is physical, prepare for spinning torques (set flag to save old orientation)
  3178. /// </summary>
  3179. /// <param name="rotation">Rotation. We do the math here to turn it into a torque</param>
  3180. /// <param name="remoteClient"></param>
  3181. public void SpinStart(IClientAPI remoteClient)
  3182. {
  3183. if (BlockGrabOverride || m_rootPart.BlockGrab)
  3184. return;
  3185. if (m_scene.EventManager.TriggerGroupSpinStart(UUID))
  3186. {
  3187. PhysicsActor pa = m_rootPart.PhysActor;
  3188. if (pa is not null)
  3189. {
  3190. if (pa.IsPhysical)
  3191. {
  3192. m_rootPart.IsWaitingForFirstSpinUpdatePacket = true;
  3193. }
  3194. }
  3195. }
  3196. }
  3197. /// <summary>
  3198. /// If object is physical, apply torque to spin it around
  3199. /// </summary>
  3200. /// <param name="rotation">Rotation. We do the math here to turn it into a torque</param>
  3201. /// <param name="remoteClient"></param>
  3202. public void SpinMovement(Quaternion newOrientation, IClientAPI remoteClient)
  3203. {
  3204. // The incoming newOrientation, sent by the client, "seems" to be the
  3205. // desired target orientation. This needs further verification; in particular,
  3206. // one would expect that the initial incoming newOrientation should be
  3207. // fairly close to the original prim's physical orientation,
  3208. // m_rootPart.PhysActor.Orientation. This however does not seem to be the
  3209. // case (might just be an issue with different quaternions representing the
  3210. // same rotation, or it might be a coordinate system issue).
  3211. //
  3212. // Since it's not clear what the relationship is between the PhysActor.Orientation
  3213. // and the incoming orientations sent by the client, we take an alternative approach
  3214. // of calculating the delta rotation between the orientations being sent by the
  3215. // client. (Since a spin is invoked by ctrl+shift+drag in the client, we expect
  3216. // a steady stream of several new orientations coming in from the client.)
  3217. // This ensures that the delta rotations are being calculated from self-consistent
  3218. // pairs of old/new rotations. Given the delta rotation, we apply a torque around
  3219. // the delta rotation axis, scaled by the object mass times an arbitrary scaling
  3220. // factor (to ensure the resulting torque is not "too strong" or "too weak").
  3221. //
  3222. // Ideally we need to calculate (probably iteratively) the exact torque or series
  3223. // of torques needed to arrive exactly at the destination orientation. However, since
  3224. // it is not yet clear how to map the destination orientation (provided by the viewer)
  3225. // into PhysActor orientations (needed by the physics engine), we omit this step.
  3226. // This means that the resulting torque will at least be in the correct direction,
  3227. // but it will result in over-shoot or under-shoot of the target orientation.
  3228. // For the end user, this means that ctrl+shift+drag can be used for relative,
  3229. // but not absolute, adjustments of orientation for physical prims.
  3230. if (BlockGrabOverride || m_rootPart.BlockGrab)
  3231. return;
  3232. if (m_scene.EventManager.TriggerGroupSpin(UUID, newOrientation))
  3233. {
  3234. PhysicsActor pa = m_rootPart.PhysActor;
  3235. if (pa is not null && pa.IsPhysical)
  3236. {
  3237. if (m_rootPart.IsWaitingForFirstSpinUpdatePacket)
  3238. {
  3239. // first time initialization of "old" orientation for calculation of delta rotations
  3240. m_rootPart.SpinOldOrientation = newOrientation;
  3241. m_rootPart.IsWaitingForFirstSpinUpdatePacket = false;
  3242. }
  3243. else
  3244. {
  3245. // save and update old orientation
  3246. Quaternion old = m_rootPart.SpinOldOrientation;
  3247. m_rootPart.SpinOldOrientation = newOrientation;
  3248. //m_log.Error("[SCENE OBJECT GROUP]: Old orientation is " + old);
  3249. //m_log.Error("[SCENE OBJECT GROUP]: Incoming new orientation is " + newOrientation);
  3250. // compute difference between previous old rotation and new incoming rotation
  3251. Quaternion minimalRotationFromQ1ToQ2 = newOrientation * Quaternion.Inverse(old);
  3252. minimalRotationFromQ1ToQ2.GetAxisAngle(out Vector3 spinforce, out float rotationAngle);
  3253. if(Math.Abs(rotationAngle)< 0.001)
  3254. return;
  3255. spinforce.Normalize();
  3256. //m_log.Error("SCENE OBJECT GROUP]: rotation axis is " + rotationAxis);
  3257. if(rotationAngle > 0)
  3258. spinforce = spinforce * pa.Mass * 0.1f; // 0.1 is an arbitrary torque scaling factor
  3259. else
  3260. spinforce = spinforce * pa.Mass * -0.1f; // 0.1 is an arbitrary torque scaling
  3261. pa.AddAngularForce(spinforce,true);
  3262. }
  3263. }
  3264. else
  3265. {
  3266. NonPhysicalSpinMovement(newOrientation);
  3267. }
  3268. }
  3269. }
  3270. /// <summary>
  3271. /// Apply rotation for spinning non-physical linksets (Ctrl+Shift+Drag)
  3272. /// As with dragging, scripted objects must be blocked from spinning
  3273. /// </summary>
  3274. /// <param name="newOrientation">New Rotation</param>
  3275. private void NonPhysicalSpinMovement(Quaternion newOrientation)
  3276. {
  3277. if(!IsAttachment && ScriptCount() == 0)
  3278. UpdateGroupRotationR(newOrientation);
  3279. }
  3280. /// <summary>
  3281. /// Set the name of a prim
  3282. /// </summary>
  3283. /// <param name="name"></param>
  3284. /// <param name="localID"></param>
  3285. public void SetPartName(string name, uint localID)
  3286. {
  3287. SceneObjectPart part = GetPart(localID);
  3288. if (part is not null)
  3289. {
  3290. part.Name = name;
  3291. }
  3292. }
  3293. public void SetPartDescription(string des, uint localID)
  3294. {
  3295. SceneObjectPart part = GetPart(localID);
  3296. if (part is not null)
  3297. {
  3298. part.Description = des;
  3299. }
  3300. }
  3301. public void SetPartText(string text, uint localID)
  3302. {
  3303. SceneObjectPart part = GetPart(localID);
  3304. part?.SetText(text);
  3305. }
  3306. public void SetPartText(string text, UUID partID)
  3307. {
  3308. SceneObjectPart part = GetPart(partID);
  3309. part?.SetText(text);
  3310. }
  3311. public string GetPartName(uint localID)
  3312. {
  3313. SceneObjectPart part = GetPart(localID);
  3314. return part is not null ? part.Name : string.Empty;
  3315. }
  3316. public string GetPartDescription(uint localID)
  3317. {
  3318. SceneObjectPart part = GetPart(localID);
  3319. return part is not null ? part.Description : string.Empty;
  3320. }
  3321. /// <summary>
  3322. /// Update prim flags for this group.
  3323. /// </summary>
  3324. /// <param name="localID"></param>
  3325. /// <param name="UsePhysics"></param>
  3326. /// <param name="SetTemporary"></param>
  3327. /// <param name="SetPhantom"></param>
  3328. /// <param name="SetVolumeDetect"></param>
  3329. public void UpdateFlags(bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVolumeDetect)
  3330. {
  3331. if (m_scene is null || IsDeleted)
  3332. return;
  3333. HasGroupChanged = true;
  3334. if (SetTemporary)
  3335. {
  3336. DetachFromBackup();
  3337. // Remove from database and parcel prim count
  3338. //
  3339. m_scene.DeleteFromStorage(UUID);
  3340. }
  3341. else if (!Backup)
  3342. {
  3343. // Previously been temporary now switching back so make it
  3344. // available for persisting again
  3345. AttachToBackup();
  3346. }
  3347. SceneObjectPart[] parts = m_parts.GetArray();
  3348. if (UsePhysics)
  3349. {
  3350. int maxprims = m_scene.m_linksetPhysCapacity;
  3351. bool checkShape = maxprims > 0 && parts.Length > maxprims;
  3352. for (int i = 0; i < parts.Length; i++)
  3353. {
  3354. SceneObjectPart part = parts[i];
  3355. if(part.PhysicsShapeType == (byte)PhysicsShapeType.None)
  3356. continue; // assuming root type was checked elsewhere
  3357. if (checkShape)
  3358. {
  3359. if (--maxprims < 0)
  3360. {
  3361. UsePhysics = false;
  3362. break;
  3363. }
  3364. }
  3365. if (part.Scale.X > m_scene.m_maxPhys ||
  3366. part.Scale.Y > m_scene.m_maxPhys ||
  3367. part.Scale.Z > m_scene.m_maxPhys )
  3368. {
  3369. UsePhysics = false; // Reset physics
  3370. break;
  3371. }
  3372. }
  3373. }
  3374. if (parts.Length > 1)
  3375. {
  3376. m_rootPart.UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, true);
  3377. for (int i = 0; i < parts.Length; i++)
  3378. {
  3379. if (parts[i].UUID != m_rootPart.UUID)
  3380. parts[i].UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, true);
  3381. }
  3382. if (m_rootPart.PhysActor is not null)
  3383. m_rootPart.PhysActor.Building = false;
  3384. }
  3385. else
  3386. m_rootPart.UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, false);
  3387. m_scene.EventManager.TriggerParcelPrimCountTainted();
  3388. }
  3389. public void UpdateExtraParam(uint localID, ushort type, bool inUse, byte[] data)
  3390. {
  3391. SceneObjectPart part = GetPart(localID);
  3392. part?.UpdateExtraParam(type, inUse, data);
  3393. }
  3394. /// <summary>
  3395. /// Gets the number of parts
  3396. /// </summary>
  3397. /// <returns></returns>
  3398. public int GetPartCount()
  3399. {
  3400. return Parts.Length;
  3401. }
  3402. public void AdjustChildPrimPermissions(bool forceTaskInventoryPermissive)
  3403. {
  3404. uint newOwnerMask = (uint)(PermissionMask.All | PermissionMask.Export) & 0xfffffff0; // Mask folded bits
  3405. uint foldedPerms = RootPart.OwnerMask & (uint)PermissionMask.FoldedMask;
  3406. ForEachPart(part =>
  3407. {
  3408. newOwnerMask &= part.BaseMask;
  3409. if (part != RootPart)
  3410. part.ClonePermissions(RootPart);
  3411. if (forceTaskInventoryPermissive)
  3412. part.Inventory.ApplyGodPermissions(part.BaseMask);
  3413. });
  3414. uint lockMask = ~(uint)(PermissionMask.Move);
  3415. uint lockBit = RootPart.OwnerMask & (uint)(PermissionMask.Move);
  3416. RootPart.OwnerMask = (RootPart.OwnerMask & lockBit) | ((newOwnerMask | foldedPerms) & lockMask);
  3417. //m_log.DebugFormat(
  3418. // "[SCENE OBJECT GROUP]: RootPart.OwnerMask now {0} for {1} in {2}",
  3419. // (OpenMetaverse.PermissionMask)RootPart.OwnerMask, Name, Scene.Name);
  3420. InvalidateEffectivePerms();
  3421. RootPart.ScheduleFullUpdate();
  3422. }
  3423. public void UpdatePermissions(UUID AgentID, byte field, uint localID,
  3424. uint mask, byte addRemTF)
  3425. {
  3426. RootPart.UpdatePermissions(AgentID, field, localID, mask, addRemTF);
  3427. bool god = Scene.Permissions.IsGod(AgentID);
  3428. if (field == 1 && god)
  3429. {
  3430. ForEachPart(part =>
  3431. {
  3432. part.BaseMask = RootPart.BaseMask;
  3433. });
  3434. }
  3435. AdjustChildPrimPermissions(false);
  3436. if (field == 1 && god) // Base mask was set. Update all child part inventories
  3437. {
  3438. foreach (SceneObjectPart part in Parts)
  3439. part.Inventory.ApplyGodPermissions(RootPart.BaseMask);
  3440. InvalidateEffectivePerms();
  3441. }
  3442. HasGroupChanged = true;
  3443. // Send the group's properties to all clients once all parts are updated
  3444. if (Scene.TryGetClient(AgentID, out IClientAPI client))
  3445. SendPropertiesToClient(client);
  3446. }
  3447. #endregion
  3448. #region Shape
  3449. /// <summary>
  3450. ///
  3451. /// </summary>
  3452. /// <param name="shapeBlock"></param>
  3453. public void UpdateShape(ObjectShapePacket.ObjectDataBlock shapeBlock, uint localID)
  3454. {
  3455. SceneObjectPart part = GetPart(localID);
  3456. part?.UpdateShape(shapeBlock);
  3457. InvalidBoundsRadius();
  3458. }
  3459. #endregion
  3460. #region Resize
  3461. /// <summary>
  3462. /// Resize the entire group of prims.
  3463. /// </summary>
  3464. /// <param name="scale"></param>
  3465. public void GroupResize(Vector3 scale)
  3466. {
  3467. //m_log.DebugFormat(
  3468. // "[SCENE OBJECT GROUP]: Group resizing {0} {1} from {2} to {3}", Name, LocalId, RootPart.Scale, scale);
  3469. if (Scene is null)
  3470. return;
  3471. PhysicsActor pa = m_rootPart.PhysActor;
  3472. float minsize = Scene.m_minNonphys;
  3473. float maxsize = Scene.m_maxNonphys;
  3474. if (pa is not null && pa.IsPhysical)
  3475. {
  3476. minsize = Scene.m_minPhys;
  3477. maxsize = Scene.m_maxPhys;
  3478. }
  3479. scale.X = Utils.Clamp(scale.X, minsize, maxsize);
  3480. scale.Y = Utils.Clamp(scale.Y, minsize, maxsize);
  3481. scale.Z = Utils.Clamp(scale.Z, minsize, maxsize);
  3482. // requested scaling factors
  3483. float x = scale.X / RootPart.Scale.X;
  3484. float y = scale.Y / RootPart.Scale.Y;
  3485. float z = scale.Z / RootPart.Scale.Z;
  3486. SceneObjectPart[] parts = m_parts.GetArray();
  3487. // fix scaling factors so parts don't violate dimensions
  3488. for(int i = 0; i < parts.Length; i++)
  3489. {
  3490. SceneObjectPart obPart = parts[i];
  3491. if(obPart.UUID != m_rootPart.UUID)
  3492. {
  3493. Vector3 oldSize = obPart.Scale;
  3494. float f;
  3495. if(oldSize.X * x > maxsize)
  3496. {
  3497. f = maxsize / oldSize.X;
  3498. f /= x;
  3499. x *= f;
  3500. y *= f;
  3501. z *= f;
  3502. }
  3503. else if(oldSize.X * x < minsize)
  3504. {
  3505. f = minsize / oldSize.X;
  3506. f /= x;
  3507. x *= f;
  3508. y *= f;
  3509. z *= f;
  3510. }
  3511. if(oldSize.Y * y > maxsize)
  3512. {
  3513. f = maxsize / oldSize.Y;
  3514. f /= y;
  3515. x *= f;
  3516. y *= f;
  3517. z *= f;
  3518. }
  3519. else if(oldSize.Y * y < minsize)
  3520. {
  3521. f = minsize / oldSize.Y;
  3522. f /= y;
  3523. x *= f;
  3524. y *= f;
  3525. z *= f;
  3526. }
  3527. if(oldSize.Z * z > maxsize)
  3528. {
  3529. f = maxsize / oldSize.Z;
  3530. f /= z;
  3531. x *= f;
  3532. y *= f;
  3533. z *= f;
  3534. }
  3535. else if(oldSize.Z * z < minsize)
  3536. {
  3537. f = minsize / oldSize.Z;
  3538. f /= z;
  3539. x *= f;
  3540. y *= f;
  3541. z *= f;
  3542. }
  3543. }
  3544. }
  3545. Vector3 rootScale = RootPart.Scale;
  3546. rootScale.X *= x;
  3547. rootScale.Y *= y;
  3548. rootScale.Z *= z;
  3549. RootPart.Scale = rootScale;
  3550. for (int i = 0; i < parts.Length; i++)
  3551. {
  3552. SceneObjectPart obPart = parts[i];
  3553. if (obPart != m_rootPart)
  3554. {
  3555. Vector3 currentpos = obPart.OffsetPosition;
  3556. currentpos.X *= x;
  3557. currentpos.Y *= y;
  3558. currentpos.Z *= z;
  3559. Vector3 newSize = obPart.Scale;
  3560. newSize.X *= x;
  3561. newSize.Y *= y;
  3562. newSize.Z *= z;
  3563. obPart.Scale = newSize;
  3564. obPart.UpdateOffSet(currentpos);
  3565. }
  3566. }
  3567. InvalidBoundsRadius();
  3568. HasGroupChanged = true;
  3569. m_rootPart.TriggerScriptChangedEvent(Changed.SCALE);
  3570. ScheduleGroupForFullUpdate();
  3571. }
  3572. public bool GroupResize(double fscale)
  3573. {
  3574. //m_log.DebugFormat(
  3575. // "[SCENE OBJECT GROUP]: Group resizing {0} {1} from {2} to {3}", Name, LocalId, RootPart.Scale, fscale);
  3576. if (Scene is null || IsDeleted || inTransit || fscale < 0)
  3577. return false;
  3578. // ignore lsl restrictions. let them be done a LSL
  3579. PhysicsActor pa = m_rootPart.PhysActor;
  3580. RootPart.KeyframeMotion?.Suspend();
  3581. float minsize = Scene.m_minNonphys;
  3582. float maxsize = Scene.m_maxNonphys;
  3583. // assuming physics is more restrictive
  3584. if (pa is not null && pa.IsPhysical)
  3585. {
  3586. minsize = Scene.m_minPhys;
  3587. maxsize = Scene.m_maxPhys;
  3588. }
  3589. SceneObjectPart[] parts = m_parts.GetArray();
  3590. float tmp;
  3591. // check scaling factor so parts don't violate dimensions
  3592. for(int i = 0; i < parts.Length; i++)
  3593. {
  3594. SceneObjectPart obPart = parts[i];
  3595. Vector3 oldSize = obPart.Scale;
  3596. tmp = (float)(oldSize.X * fscale);
  3597. if(tmp > maxsize)
  3598. return false;
  3599. if(tmp < minsize)
  3600. return false;
  3601. tmp = (float)(oldSize.Y * fscale);
  3602. if(tmp > maxsize)
  3603. return false;
  3604. if(tmp < minsize)
  3605. return false;
  3606. tmp = (float)(oldSize.Z * fscale);
  3607. if(tmp > maxsize)
  3608. return false;
  3609. if(tmp < minsize)
  3610. return false;
  3611. }
  3612. Vector3 newSize = RootPart.Scale * (float)fscale;
  3613. if(pa is not null)
  3614. pa.Building = true;
  3615. RootPart.Scale = newSize;
  3616. Vector3 currentpos;
  3617. for (int i = 0; i < parts.Length; i++)
  3618. {
  3619. SceneObjectPart obPart = parts[i];
  3620. if (obPart != m_rootPart)
  3621. {
  3622. obPart.Scale *= (float)fscale;
  3623. currentpos = obPart.OffsetPosition * (float)fscale;
  3624. obPart.UpdateOffSet(currentpos);
  3625. }
  3626. }
  3627. if(pa is not null)
  3628. pa.Building = false;
  3629. InvalidBoundsRadius();
  3630. HasGroupChanged = true;
  3631. m_rootPart.TriggerScriptChangedEvent(Changed.SCALE);
  3632. ScheduleGroupForFullUpdate();
  3633. RootPart.KeyframeMotion?.Resume();
  3634. return true;
  3635. }
  3636. public float GetMaxGroupResizeScale()
  3637. {
  3638. if (Scene is null || IsDeleted || inTransit)
  3639. return 1.0f;
  3640. float maxsize = Scene.m_maxNonphys;
  3641. PhysicsActor pa = m_rootPart.PhysActor;
  3642. // assuming physics is more restrictive
  3643. if (pa is not null && pa.IsPhysical)
  3644. maxsize = Scene.m_maxPhys;
  3645. SceneObjectPart[] parts = m_parts.GetArray();
  3646. float larger = float.MinValue;
  3647. for(int i = 0; i < parts.Length; i++)
  3648. {
  3649. SceneObjectPart obPart = parts[i];
  3650. Vector3 oldSize = obPart.Scale;
  3651. if(larger < oldSize.X)
  3652. larger = oldSize.X;
  3653. if(larger < oldSize.Y)
  3654. larger = oldSize.Y;
  3655. if(larger < oldSize.Z)
  3656. larger = oldSize.Z;
  3657. }
  3658. if(larger >= maxsize)
  3659. return 1.0f;
  3660. larger += 1e-3f;
  3661. float fscale = maxsize / larger;
  3662. return fscale;
  3663. }
  3664. public float GetMinGroupResizeScale()
  3665. {
  3666. if (Scene is null || IsDeleted || inTransit)
  3667. return 1.0f;
  3668. float minsize = Scene.m_minNonphys;
  3669. PhysicsActor pa = m_rootPart.PhysActor;
  3670. // assuming physics is more restrictive
  3671. if (pa is not null && pa.IsPhysical)
  3672. minsize = Scene.m_minPhys;
  3673. SceneObjectPart[] parts = m_parts.GetArray();
  3674. float smaller = float.MaxValue;
  3675. for(int i = 0; i < parts.Length; i++)
  3676. {
  3677. SceneObjectPart obPart = parts[i];
  3678. Vector3 oldSize = obPart.Scale;
  3679. if(smaller > oldSize.X)
  3680. smaller = oldSize.X;
  3681. if(smaller > oldSize.Y)
  3682. smaller = oldSize.Y;
  3683. if(smaller > oldSize.Z)
  3684. smaller = oldSize.Z;
  3685. }
  3686. if(smaller <= minsize)
  3687. return 1.0f;
  3688. if(smaller > 2e-3f)
  3689. smaller -= 1e-3f;
  3690. float fscale = minsize / smaller;
  3691. if(fscale < 1e-8f)
  3692. fscale = 1e-8f;
  3693. return fscale;
  3694. }
  3695. #endregion
  3696. #region Position
  3697. /// <summary>
  3698. /// Move this scene object
  3699. /// </summary>
  3700. /// <param name="pos"></param>
  3701. public void UpdateGroupPosition(Vector3 pos)
  3702. {
  3703. if (m_scene.EventManager.TriggerGroupMove(UUID, pos))
  3704. {
  3705. if (IsAttachment)
  3706. {
  3707. m_rootPart.AttachedPos = pos;
  3708. }
  3709. else if (RootPart.GetStatusSandbox())
  3710. {
  3711. Vector3 mov = pos - RootPart.StatusSandboxPos;
  3712. float movLenSQ = mov.LengthSquared();
  3713. if (movLenSQ > 100.5f)
  3714. {
  3715. mov *= 10.0f / MathF.Sqrt(movLenSQ);
  3716. AbsolutePosition = RootPart.StatusSandboxPos + mov;
  3717. RootPart.ScriptSetPhysicsStatus(false);
  3718. Scene.SimChat(Utils.StringToBytes("Hit Sandbox Limit"),
  3719. ChatTypeEnum.DebugChannel, 0x7FFFFFFF, RootPart.AbsolutePosition, Name, UUID, false);
  3720. HasGroupChanged = true;
  3721. return;
  3722. }
  3723. }
  3724. AbsolutePosition = pos;
  3725. HasGroupChanged = true;
  3726. }
  3727. //we need to do a terse update even if the move wasn't allowed
  3728. // so that the position is reset in the client (the object snaps back)
  3729. RootPart.ScheduleTerseUpdate();
  3730. }
  3731. /// <summary>
  3732. /// Update the position of a single part of this scene object
  3733. /// </summary>
  3734. /// <param name="pos"></param>
  3735. /// <param name="localID"></param>
  3736. ///
  3737. public void UpdateSinglePosition(Vector3 pos, uint localID)
  3738. {
  3739. SceneObjectPart part = GetPart(localID);
  3740. if (part is not null)
  3741. {
  3742. // unlock parts position change
  3743. if (m_rootPart.PhysActor is not null)
  3744. m_rootPart.PhysActor.Building = true;
  3745. if (part.UUID == m_rootPart.UUID)
  3746. {
  3747. UpdateRootPosition(pos);
  3748. }
  3749. else
  3750. {
  3751. part.UpdateOffSet(pos);
  3752. }
  3753. if (m_rootPart.PhysActor is not null)
  3754. m_rootPart.PhysActor.Building = false;
  3755. HasGroupChanged = true;
  3756. }
  3757. }
  3758. /// <summary>
  3759. /// Update just the root prim position in a linkset
  3760. /// </summary>
  3761. /// <param name="newPos"></param>
  3762. public void UpdateRootPosition(Vector3 newPos)
  3763. {
  3764. // needs to be called with phys building true
  3765. Vector3 oldPos;
  3766. if (IsAttachment)
  3767. oldPos = m_rootPart.AttachedPos + m_rootPart.OffsetPosition; // OffsetPosition should always be 0 in an attachments's root prim
  3768. else
  3769. oldPos = AbsolutePosition + m_rootPart.OffsetPosition;
  3770. Vector3 diff = oldPos - newPos;
  3771. Quaternion partRotation = m_rootPart.RotationOffset;
  3772. diff *= Quaternion.Inverse(partRotation);
  3773. SceneObjectPart[] parts = m_parts.GetArray();
  3774. for (int i = 0; i < parts.Length; i++)
  3775. {
  3776. SceneObjectPart obPart = parts[i];
  3777. if (obPart != m_rootPart)
  3778. obPart.OffsetPosition += diff;
  3779. }
  3780. AbsolutePosition = newPos;
  3781. if (IsAttachment)
  3782. m_rootPart.AttachedPos = newPos;
  3783. HasGroupChanged = true;
  3784. if (m_rootPart.Undoing)
  3785. {
  3786. ScheduleGroupForFullUpdate();
  3787. }
  3788. else
  3789. {
  3790. ScheduleGroupForTerseUpdate();
  3791. }
  3792. }
  3793. #endregion
  3794. #region Rotation
  3795. /// <summary>
  3796. /// Update the rotation of the group.
  3797. /// </summary>
  3798. /// <param name="rot"></param>
  3799. public void UpdateGroupRotationR(Quaternion rot)
  3800. {
  3801. m_rootPart.UpdateRotation(rot);
  3802. /* this is done by rootpart RotationOffset set called by UpdateRotation
  3803. PhysicsActor actor = m_rootPart.PhysActor;
  3804. if (actor is not null)
  3805. {
  3806. actor.Orientation = m_rootPart.RotationOffset;
  3807. m_scene.PhysicsScene.AddPhysicsActorTaint(actor);
  3808. }
  3809. */
  3810. HasGroupChanged = true;
  3811. ScheduleGroupForTerseUpdate();
  3812. }
  3813. /// <summary>
  3814. /// Update the position and rotation of a group simultaneously.
  3815. /// </summary>
  3816. /// <param name="pos"></param>
  3817. /// <param name="rot"></param>
  3818. public void UpdateGroupRotationPR(Vector3 pos, Quaternion rot)
  3819. {
  3820. m_rootPart.UpdateRotation(rot);
  3821. //already done above
  3822. //PhysicsActor actor = m_rootPart.PhysActor;
  3823. //if (actor is not null)
  3824. //{
  3825. // actor.Orientation = m_rootPart.RotationOffset;
  3826. //}
  3827. if (IsAttachment)
  3828. {
  3829. m_rootPart.AttachedPos = pos;
  3830. }
  3831. AbsolutePosition = pos;
  3832. HasGroupChanged = true;
  3833. ScheduleGroupForTerseUpdate();
  3834. }
  3835. /// <summary>
  3836. /// Update the rotation of a single prim within the group.
  3837. /// </summary>
  3838. /// <param name="rot"></param>
  3839. /// <param name="localID"></param>
  3840. public void UpdateSingleRotation(Quaternion rot, uint localID)
  3841. {
  3842. SceneObjectPart part = GetPart(localID);
  3843. if (part is not null)
  3844. {
  3845. if (m_rootPart.PhysActor is not null)
  3846. m_rootPart.PhysActor.Building = true;
  3847. if (part == m_rootPart)
  3848. {
  3849. UpdateRootRotation(rot);
  3850. }
  3851. else
  3852. {
  3853. part.UpdateRotation(rot);
  3854. }
  3855. if (m_rootPart.PhysActor is not null)
  3856. m_rootPart.PhysActor.Building = false;
  3857. }
  3858. }
  3859. /// <summary>
  3860. /// Update the position and rotation simultaneously of a single prim within the group.
  3861. /// </summary>
  3862. /// <param name="rot"></param>
  3863. /// <param name="localID"></param>
  3864. public void UpdateSingleRotation(Quaternion rot, Vector3 pos, uint localID)
  3865. {
  3866. SceneObjectPart part = GetPart(localID);
  3867. if (part is not null)
  3868. {
  3869. if (m_rootPart.PhysActor is not null)
  3870. m_rootPart.PhysActor.Building = true;
  3871. if (part.UUID == m_rootPart.UUID)
  3872. {
  3873. UpdateRootRotation(rot);
  3874. AbsolutePosition = pos;
  3875. }
  3876. else
  3877. {
  3878. part.UpdateRotation(rot);
  3879. part.OffsetPosition = pos;
  3880. }
  3881. if (m_rootPart.PhysActor is not null)
  3882. m_rootPart.PhysActor.Building = false;
  3883. }
  3884. }
  3885. /// <summary>
  3886. /// Update the rotation of just the root prim of a linkset.
  3887. /// </summary>
  3888. /// <param name="rot"></param>
  3889. public void UpdateRootRotation(Quaternion rot)
  3890. {
  3891. // needs to be called with phys building true
  3892. Quaternion transformRot = Quaternion.Inverse(rot) * m_rootPart.RotationOffset;
  3893. //Don't use UpdateRotation because it schedules an update prematurely
  3894. m_rootPart.RotationOffset = rot;
  3895. PhysicsActor pa = m_rootPart.PhysActor;
  3896. if (pa is not null)
  3897. pa.Orientation = rot;
  3898. SceneObjectPart[] parts = m_parts.GetArray();
  3899. for (int i = 0; i < parts.Length; i++)
  3900. {
  3901. SceneObjectPart prim = parts[i];
  3902. if (prim != m_rootPart)
  3903. {
  3904. prim.RotationOffset = transformRot * prim.RotationOffset;
  3905. prim.OffsetPosition *= transformRot;
  3906. }
  3907. }
  3908. HasGroupChanged = true;
  3909. ScheduleGroupForFullUpdate();
  3910. }
  3911. private enum updatetype :int
  3912. {
  3913. none = 0,
  3914. partterse = 1,
  3915. partfull = 2,
  3916. groupterse = 3,
  3917. groupfull = 4
  3918. }
  3919. public void doChangeObject(SceneObjectPart part, ObjectChangeData data)
  3920. {
  3921. // TODO this still as excessive *.Schedule*Update()s
  3922. if (part is not null && part.ParentGroup is not null)
  3923. {
  3924. ObjectChangeType change = data.change;
  3925. bool togroup = (change & ObjectChangeType.Group) != 0;
  3926. SceneObjectGroup group = part.ParentGroup;
  3927. PhysicsActor pha = group.RootPart.PhysActor;
  3928. updatetype updateType = updatetype.none;
  3929. if (togroup)
  3930. {
  3931. // related to group
  3932. if ((change & (ObjectChangeType.Rotation | ObjectChangeType.Position)) != 0)
  3933. {
  3934. if ((change & ObjectChangeType.Rotation) != 0)
  3935. {
  3936. group.RootPart.UpdateRotation(data.rotation);
  3937. updateType = updatetype.none;
  3938. }
  3939. if ((change & ObjectChangeType.Position) != 0)
  3940. {
  3941. if (IsAttachment || m_scene.Permissions.CanObjectEntry(group, false, data.position))
  3942. UpdateGroupPosition(data.position);
  3943. updateType = updatetype.groupterse;
  3944. }
  3945. else
  3946. // ugly rotation update of all parts
  3947. {
  3948. group.ResetChildPrimPhysicsPositions();
  3949. }
  3950. }
  3951. if ((change & ObjectChangeType.Scale) != 0)
  3952. {
  3953. if (pha is not null)
  3954. pha.Building = true;
  3955. group.GroupResize(data.scale);
  3956. updateType = updatetype.none;
  3957. if (pha is not null)
  3958. pha.Building = false;
  3959. }
  3960. }
  3961. else
  3962. {
  3963. // related to single prim in a link-set ( ie group)
  3964. if (pha is not null)
  3965. pha.Building = true;
  3966. // root part is special
  3967. // parts offset positions or rotations need to change also
  3968. if (part == group.RootPart)
  3969. {
  3970. if ((change & ObjectChangeType.Rotation) != 0)
  3971. group.UpdateRootRotation(data.rotation);
  3972. if ((change & ObjectChangeType.Position) != 0)
  3973. group.UpdateRootPosition(data.position);
  3974. if ((change & ObjectChangeType.Scale) != 0)
  3975. part.Resize(data.scale);
  3976. }
  3977. else
  3978. {
  3979. if ((change & ObjectChangeType.Position) != 0)
  3980. {
  3981. part.OffsetPosition = data.position;
  3982. updateType = updatetype.partterse;
  3983. }
  3984. if ((change & ObjectChangeType.Rotation) != 0)
  3985. {
  3986. part.UpdateRotation(data.rotation);
  3987. updateType = updatetype.none;
  3988. }
  3989. if ((change & ObjectChangeType.Scale) != 0)
  3990. {
  3991. part.Resize(data.scale);
  3992. updateType = updatetype.none;
  3993. }
  3994. }
  3995. if (pha is not null)
  3996. pha.Building = false;
  3997. }
  3998. if (updateType != updatetype.none)
  3999. {
  4000. group.HasGroupChanged = true;
  4001. switch (updateType)
  4002. {
  4003. case updatetype.partterse:
  4004. part.ScheduleTerseUpdate();
  4005. break;
  4006. case updatetype.partfull:
  4007. part.ScheduleFullUpdate();
  4008. break;
  4009. case updatetype.groupterse:
  4010. group.ScheduleGroupForTerseUpdate();
  4011. break;
  4012. case updatetype.groupfull:
  4013. group.ScheduleGroupForFullUpdate();
  4014. break;
  4015. default:
  4016. break;
  4017. }
  4018. }
  4019. }
  4020. }
  4021. #endregion
  4022. public void SetAxisRotation(int axis, int rotate10)
  4023. {
  4024. if((axis & (int)(axisSelect.STATUS_ROTATE_X | axisSelect.STATUS_ROTATE_Y | axisSelect.STATUS_ROTATE_Z)) == 0)
  4025. return;
  4026. bool lockaxis = rotate10 == 0; // zero means axis locked
  4027. byte locks = RootPart.RotationAxisLocks;
  4028. if ((axis & (int)axisSelect.STATUS_ROTATE_X) != 0)
  4029. {
  4030. if (lockaxis)
  4031. locks |= (byte)axisSelect.STATUS_ROTATE_X;
  4032. else
  4033. locks &= (byte)axisSelect.NOT_STATUS_ROTATE_X;
  4034. }
  4035. if ((axis & (int)axisSelect.STATUS_ROTATE_Y) != 0)
  4036. {
  4037. if (lockaxis)
  4038. locks |= (byte)axisSelect.STATUS_ROTATE_Y;
  4039. else
  4040. locks &= (byte)axisSelect.NOT_STATUS_ROTATE_Y;
  4041. }
  4042. if ((axis & (int)axisSelect.STATUS_ROTATE_Z) != 0)
  4043. {
  4044. if (lockaxis)
  4045. locks |= (byte)axisSelect.STATUS_ROTATE_Z;
  4046. else
  4047. locks &= (byte)axisSelect.NOT_STATUS_ROTATE_Z;
  4048. }
  4049. RootPart.RotationAxisLocks = locks;
  4050. RootPart.SetPhysicsAxisRotation();
  4051. }
  4052. public int GetAxisRotation(int axis)
  4053. {
  4054. byte rotAxislocks = RootPart.RotationAxisLocks;
  4055. // if multiple return the one with higher id
  4056. if (axis == (int)axisSelect.STATUS_ROTATE_Z)
  4057. return (rotAxislocks & (byte)axisSelect.STATUS_ROTATE_Z) == 0 ? 1:0;
  4058. if (axis == (int)axisSelect.STATUS_ROTATE_Y)
  4059. return (rotAxislocks & (byte)axisSelect.STATUS_ROTATE_Y) == 0 ? 1:0;
  4060. if (axis == (int)axisSelect.STATUS_ROTATE_X)
  4061. return (rotAxislocks & (byte)SceneObjectGroup.axisSelect.STATUS_ROTATE_X) == 0 ? 1:0;
  4062. return 0;
  4063. }
  4064. public int RegisterRotTargetWaypoint(UUID scriptID, Quaternion target, float tolerance)
  4065. {
  4066. int handle = m_scene.AllocateIntId();
  4067. scriptRotTarget waypoint = new()
  4068. {
  4069. targetRot = target,
  4070. tolerance = tolerance,
  4071. scriptID = scriptID,
  4072. handle = handle
  4073. };
  4074. lock (m_targets)
  4075. {
  4076. if(m_targetsByScript.TryGetValue(scriptID, out List<int> handles))
  4077. {
  4078. if (handles.Count >= 8)
  4079. {
  4080. int todel = handles[0];
  4081. handles.RemoveAt(0);
  4082. if(!m_rotTargets.Remove(todel))
  4083. m_targets.Remove(todel);
  4084. }
  4085. handles.Add(handle);
  4086. }
  4087. else
  4088. m_targetsByScript[scriptID] = new List<int>(){handle};
  4089. m_rotTargets.Add(handle, waypoint);
  4090. m_scene.AddGroupTarget(this);
  4091. }
  4092. return handle;
  4093. }
  4094. public void UnRegisterRotTargetWaypoint(int handle)
  4095. {
  4096. lock (m_targets)
  4097. {
  4098. if(m_rotTargets.TryGetValue(handle, out scriptRotTarget waypoint))
  4099. {
  4100. if(m_targetsByScript.TryGetValue(waypoint.scriptID, out List<int>handles))
  4101. {
  4102. handles.Remove(handle);
  4103. if(handles.Count == 0)
  4104. m_targetsByScript.Remove(waypoint.scriptID);
  4105. }
  4106. m_rotTargets.Remove(handle);
  4107. }
  4108. if (m_targets.Count == 0 && m_rotTargets.Count == 0)
  4109. m_scene.RemoveGroupTarget(this);
  4110. }
  4111. }
  4112. public int RegisterTargetWaypoint(UUID scriptID, Vector3 target, float tolerance)
  4113. {
  4114. int handle = m_scene.AllocateIntId();
  4115. scriptPosTarget waypoint = new()
  4116. {
  4117. targetPos = target,
  4118. tolerance = tolerance * tolerance,
  4119. scriptID = scriptID,
  4120. handle = handle
  4121. };
  4122. lock (m_targets)
  4123. {
  4124. if (m_targetsByScript.TryGetValue(scriptID, out List<int> handles))
  4125. {
  4126. if (handles.Count >= 8)
  4127. {
  4128. int todel = handles[0];
  4129. handles.RemoveAt(0);
  4130. if(!m_targets.Remove(todel))
  4131. m_rotTargets.Remove(todel);
  4132. }
  4133. handles.Add(handle);
  4134. }
  4135. else
  4136. m_targetsByScript[scriptID] = new List<int>() { handle };
  4137. m_targets.Add(handle, waypoint);
  4138. m_scene.AddGroupTarget(this);
  4139. }
  4140. return handle;
  4141. }
  4142. public void UnregisterTargetWaypoint(int handle)
  4143. {
  4144. lock (m_targets)
  4145. {
  4146. if (m_targets.TryGetValue(handle, out scriptPosTarget waypoint))
  4147. {
  4148. if (m_targetsByScript.TryGetValue(waypoint.scriptID, out List<int> handles))
  4149. {
  4150. handles.Remove(handle);
  4151. if (handles.Count == 0)
  4152. m_targetsByScript.Remove(waypoint.scriptID);
  4153. }
  4154. m_targets.Remove(handle);
  4155. }
  4156. if (m_targets.Count == 0 && m_rotTargets.Count == 0)
  4157. m_scene.RemoveGroupTarget(this);
  4158. }
  4159. }
  4160. public void RemoveScriptTargets(UUID scriptID)
  4161. {
  4162. lock (m_targets)
  4163. {
  4164. if(m_targetsByScript.TryGetValue(scriptID, out List<int> toremove))
  4165. {
  4166. m_targetsByScript.Remove(scriptID);
  4167. if (toremove.Count > 0)
  4168. {
  4169. for (int i = 0; i < toremove.Count; ++i)
  4170. {
  4171. if(!m_targets.Remove(toremove[i]))
  4172. m_rotTargets.Remove(toremove[i]);
  4173. }
  4174. }
  4175. }
  4176. m_scene.RemoveGroupTarget(this);
  4177. }
  4178. }
  4179. public void CheckAtTargets()
  4180. {
  4181. int targetsCount = m_targets.Count;
  4182. if (targetsCount > 0 && (m_scriptListens_atTarget || m_scriptListens_notAtTarget))
  4183. {
  4184. List<scriptPosTarget> atTargets = new();
  4185. HashSet<UUID> notatTargets = new();
  4186. Vector3 pos = m_rootPart.GroupPosition;
  4187. lock (m_targets)
  4188. {
  4189. foreach (scriptPosTarget target in m_targets.Values)
  4190. {
  4191. if (Vector3.DistanceSquared(target.targetPos, pos) <= target.tolerance)
  4192. {
  4193. if (m_scriptListens_atTarget)
  4194. atTargets.Add(target);
  4195. notatTargets.Remove(target.scriptID);
  4196. }
  4197. else
  4198. {
  4199. if (m_scriptListens_notAtTarget)
  4200. notatTargets.Add(target.scriptID);
  4201. }
  4202. }
  4203. }
  4204. if (atTargets.Count > 0)
  4205. {
  4206. for (int target = 0; target < atTargets.Count; ++target)
  4207. {
  4208. scriptPosTarget att = atTargets[target];
  4209. m_scene.EventManager.TriggerAtTargetEvent(att.scriptID, (uint)att.handle, att.targetPos, pos);
  4210. }
  4211. }
  4212. if (notatTargets.Count > 0)
  4213. {
  4214. foreach (UUID id in notatTargets)
  4215. {
  4216. m_scene.EventManager.TriggerNotAtTargetEvent(id);
  4217. }
  4218. }
  4219. }
  4220. targetsCount = m_rotTargets.Count;
  4221. if (targetsCount > 0 && (m_scriptListens_atRotTarget || m_scriptListens_notAtRotTarget))
  4222. {
  4223. List<scriptRotTarget> atRotTargets = new(targetsCount);
  4224. HashSet<UUID> notatRotTargets = new();
  4225. Quaternion rot = m_rootPart.RotationOffset;
  4226. lock (m_targets)
  4227. {
  4228. foreach (scriptRotTarget target in m_rotTargets.Values)
  4229. {
  4230. double angle = 2 * Math.Acos(Quaternion.Dot(target.targetRot, rot));
  4231. if (angle < 0)
  4232. angle = -angle;
  4233. if (angle > Math.PI)
  4234. angle = (2 * Math.PI - angle);
  4235. if (angle <= target.tolerance)
  4236. {
  4237. if (m_scriptListens_atRotTarget)
  4238. atRotTargets.Add(target);
  4239. notatRotTargets.Remove(target.scriptID);
  4240. }
  4241. else
  4242. {
  4243. if (m_scriptListens_notAtRotTarget)
  4244. notatRotTargets.Add(target.scriptID);
  4245. }
  4246. }
  4247. }
  4248. if (atRotTargets.Count > 0)
  4249. {
  4250. for (int target = 0; target < atRotTargets.Count; ++target)
  4251. {
  4252. scriptRotTarget att = atRotTargets[target];
  4253. m_scene.EventManager.TriggerAtRotTargetEvent(att.scriptID, (uint)att.handle, att.targetRot, rot);
  4254. }
  4255. }
  4256. if (notatRotTargets.Count > 0)
  4257. {
  4258. foreach (UUID id in notatRotTargets)
  4259. {
  4260. m_scene.EventManager.TriggerNotAtRotTargetEvent(id);
  4261. }
  4262. }
  4263. }
  4264. }
  4265. public Vector3 GetGeometricCenter()
  4266. {
  4267. // this is not real geometric center but a average of positions relative to root prim acording to
  4268. // http://wiki.secondlife.com/wiki/llGetGeometricCenter
  4269. // ignoring tortured prims details since sl also seems to ignore
  4270. // so no real use in doing it on physics
  4271. SceneObjectPart[] parts = m_parts.GetArray();
  4272. if (parts.Length < 2)
  4273. return Vector3.Zero;
  4274. Vector3 gc = Vector3.Zero;
  4275. // average all parts positions
  4276. for (int i = 0; i < parts.Length; i++)
  4277. {
  4278. if (parts[i] != RootPart)
  4279. gc += parts[i].OffsetPosition;
  4280. }
  4281. gc /= parts.Length;
  4282. return gc;
  4283. }
  4284. public float GetMass()
  4285. {
  4286. float retmass = 0f;
  4287. SceneObjectPart[] parts = m_parts.GetArray();
  4288. for (int i = 0; i < parts.Length; i++)
  4289. retmass += parts[i].GetMass();
  4290. return retmass;
  4291. }
  4292. // center of mass of full object
  4293. public Vector3 GetCenterOfMass()
  4294. {
  4295. PhysicsActor pa = RootPart.PhysActor;
  4296. if(((RootPart.Flags & PrimFlags.Physics) !=0) && pa !=null)
  4297. {
  4298. // physics knows better about center of mass of physical prims
  4299. Vector3 tmp = pa.CenterOfMass;
  4300. return tmp;
  4301. }
  4302. Vector3 Ptot = Vector3.Zero;
  4303. float totmass = 0f;
  4304. float m;
  4305. SceneObjectPart[] parts = m_parts.GetArray();
  4306. for (int i = 0; i < parts.Length; i++)
  4307. {
  4308. m = parts[i].GetMass();
  4309. Ptot += parts[i].GetPartCenterOfMass() * m;
  4310. totmass += m;
  4311. }
  4312. if (totmass == 0)
  4313. totmass = 0;
  4314. else
  4315. totmass = 1 / totmass;
  4316. Ptot *= totmass;
  4317. return Ptot;
  4318. }
  4319. public void GetInertiaData(out float TotalMass, out Vector3 CenterOfMass, out Vector3 Inertia, out Vector4 aux )
  4320. {
  4321. PhysicsActor pa = RootPart.PhysActor;
  4322. if(((RootPart.Flags & PrimFlags.Physics) !=0) && pa !=null)
  4323. {
  4324. PhysicsInertiaData inertia;
  4325. inertia = pa.GetInertiaData();
  4326. TotalMass = inertia.TotalMass;
  4327. CenterOfMass = inertia.CenterOfMass;
  4328. Inertia = inertia.Inertia;
  4329. aux = inertia.InertiaRotation;
  4330. return;
  4331. }
  4332. TotalMass = GetMass();
  4333. CenterOfMass = GetCenterOfMass() - AbsolutePosition;
  4334. CenterOfMass *= Quaternion.Conjugate(RootPart.RotationOffset);
  4335. Inertia = Vector3.Zero;
  4336. aux = Vector4.Zero;
  4337. }
  4338. public void SetInertiaData(float TotalMass, Vector3 CenterOfMass, Vector3 Inertia, Vector4 aux )
  4339. {
  4340. PhysicsInertiaData inertiaData = new()
  4341. {
  4342. TotalMass = TotalMass,
  4343. CenterOfMass = CenterOfMass,
  4344. Inertia = Inertia,
  4345. InertiaRotation = aux
  4346. };
  4347. if(TotalMass < 0)
  4348. RootPart.PhysicsInertia = null;
  4349. else
  4350. RootPart.PhysicsInertia = inertiaData;
  4351. PhysicsActor pa = RootPart.PhysActor;
  4352. pa?.SetInertiaData(inertiaData);
  4353. }
  4354. /// <summary>
  4355. /// Set the user group to which this scene object belongs.
  4356. /// </summary>
  4357. /// <param name="GroupID"></param>
  4358. /// <param name="client"></param>
  4359. public void SetGroup(UUID GroupID, IClientAPI client)
  4360. {
  4361. SceneObjectPart[] parts = m_parts.GetArray();
  4362. for (int i = 0; i < parts.Length; i++)
  4363. {
  4364. SceneObjectPart part = parts[i];
  4365. part.SetGroup(GroupID, client);
  4366. part.Inventory.ChangeInventoryGroup(GroupID);
  4367. }
  4368. HasGroupChanged = true;
  4369. // Don't trigger the update here - otherwise some client issues occur when multiple updates are scheduled
  4370. // for the same object with very different properties. The caller must schedule the update.
  4371. //ScheduleGroupForFullUpdate();
  4372. }
  4373. public void TriggerScriptChangedEvent(Changed val)
  4374. {
  4375. SceneObjectPart[] parts = m_parts.GetArray();
  4376. for (int i = 0; i < parts.Length; i++)
  4377. parts[i].TriggerScriptChangedEvent(val);
  4378. }
  4379. /// <summary>
  4380. /// Returns a count of the number of scripts in this groups parts.
  4381. /// </summary>
  4382. public int ScriptCount()
  4383. {
  4384. int count = 0;
  4385. SceneObjectPart[] parts = m_parts.GetArray();
  4386. for (int i = 0; i < parts.Length; i++)
  4387. count += parts[i].Inventory.ScriptCount();
  4388. return count;
  4389. }
  4390. /// <summary>
  4391. /// A float the value is a representative execution time in milliseconds of all scripts in the link set.
  4392. /// </summary>
  4393. public float ScriptExecutionTime()
  4394. {
  4395. IScriptModule[] engines = Scene.RequestModuleInterfaces<IScriptModule>();
  4396. if (engines.Length == 0) // No engine at all
  4397. return 0.0f;
  4398. try
  4399. {
  4400. float time = 0.0f;
  4401. // get all the scripts in all parts
  4402. SceneObjectPart[] parts = m_parts.GetArray();
  4403. List<TaskInventoryItem> scripts = new();
  4404. for (int i = 0; i < parts.Length; i++)
  4405. {
  4406. IEntityInventory inv = parts[i].Inventory;
  4407. if (inv is not null)
  4408. scripts.AddRange(parts[i].Inventory.GetInventoryItems(InventoryType.LSL));
  4409. }
  4410. // extract the UUIDs
  4411. HashSet<UUID> unique = new();
  4412. foreach (TaskInventoryItem script in scripts)
  4413. unique.Add(script.ItemID);
  4414. List<UUID> ids = unique.ToList();
  4415. // Offer the list of script UUIDs to each engine found and accumulate the time
  4416. foreach (IScriptModule e in engines)
  4417. {
  4418. if (e is not null)
  4419. {
  4420. time += e.GetScriptExecutionTime(ids);
  4421. }
  4422. }
  4423. return time;
  4424. }
  4425. catch
  4426. {
  4427. return 0.0f;
  4428. }
  4429. }
  4430. public bool ScriptsMemory(out int memory)
  4431. {
  4432. memory = 0;
  4433. IScriptModule[] engines = Scene.RequestModuleInterfaces<IScriptModule>();
  4434. if (engines.Length == 0) // No engine at all
  4435. return false;
  4436. try
  4437. {
  4438. // get all the scripts in all parts
  4439. SceneObjectPart[] parts = m_parts.GetArray();
  4440. List<TaskInventoryItem> scripts = new();
  4441. for (int i = 0; i < parts.Length; i++)
  4442. {
  4443. IEntityInventory inv = parts[i].Inventory;
  4444. if(inv is not null)
  4445. scripts.AddRange(inv.GetInventoryItems(InventoryType.LSL));
  4446. }
  4447. if (scripts.Count == 0)
  4448. return false;
  4449. // extract the UUIDs
  4450. HashSet<UUID> unique = new();
  4451. foreach (TaskInventoryItem script in scripts)
  4452. unique.Add(script.ItemID);
  4453. List<UUID> ids = unique.ToList();
  4454. // Offer the list of script UUIDs to each engine found and accumulate the memory
  4455. foreach (IScriptModule e in engines)
  4456. {
  4457. if (e is not null)
  4458. {
  4459. memory += e.GetScriptsMemory(ids);
  4460. }
  4461. }
  4462. return true;
  4463. }
  4464. catch
  4465. {
  4466. return false;
  4467. }
  4468. }
  4469. /// <summary>
  4470. /// Returns a count of the number of running scripts in this groups parts.
  4471. /// </summary>
  4472. public int RunningScriptCount()
  4473. {
  4474. int count = 0;
  4475. SceneObjectPart[] parts = m_parts.GetArray();
  4476. for (int i = 0; i < parts.Length; i++)
  4477. count += parts[i].Inventory.RunningScriptCount();
  4478. return count;
  4479. }
  4480. /// <summary>
  4481. /// Get a copy of the list of sitting avatars on all prims of this object.
  4482. /// </summary>
  4483. /// <remarks>
  4484. /// This is sorted by the order in which avatars sat down. If an avatar stands up then all avatars that sat
  4485. /// down after it move one place down the list.
  4486. /// </remarks>
  4487. /// <returns>A list of the sitting avatars. Returns an empty list if there are no sitting avatars.</returns>
  4488. public List<ScenePresence> GetSittingAvatars()
  4489. {
  4490. lock (m_sittingAvatars)
  4491. return new List<ScenePresence>(m_sittingAvatars);
  4492. }
  4493. public bool HasSittingAvatar(UUID avatarID)
  4494. {
  4495. // locked O(n) :(
  4496. lock (m_sittingAvatars)
  4497. {
  4498. for(int i = 0; i < m_sittingAvatars.Count; ++i)
  4499. {
  4500. if(m_sittingAvatars[i].UUID.Equals(avatarID))
  4501. return true;
  4502. }
  4503. }
  4504. return false;
  4505. }
  4506. /// <summary>
  4507. /// Gets the number of sitting avatars.
  4508. /// </summary>
  4509. /// <remarks>This applies to all sitting avatars whether there is a sit target set or not.</remarks>
  4510. /// <returns></returns>
  4511. public int GetSittingAvatarsCount()
  4512. {
  4513. lock (m_sittingAvatars)
  4514. return m_sittingAvatars.Count;
  4515. }
  4516. public ScenePresence GetLinkSitingAvatar(int linknumber)
  4517. {
  4518. lock(m_parts)
  4519. linknumber -= (m_parts.Count + 1);
  4520. lock (m_sittingAvatars)
  4521. {
  4522. if (linknumber < m_sittingAvatars.Count && linknumber >= 0)
  4523. return m_sittingAvatars[linknumber];
  4524. }
  4525. return null;
  4526. }
  4527. public override string ToString()
  4528. {
  4529. return $"{Name} {UUID} ({AbsolutePosition})";
  4530. }
  4531. #region ISceneObject
  4532. public virtual ISceneObject CloneForNewScene()
  4533. {
  4534. SceneObjectGroup sog = Copy(false);
  4535. sog.IsDeleted = false;
  4536. return sog;
  4537. }
  4538. public virtual string ToXml2()
  4539. {
  4540. return SceneObjectSerializer.ToXml2Format(this);
  4541. }
  4542. public virtual string ExtraToXmlString()
  4543. {
  4544. return $"<ExtraFromItemID>{FromItemID}</ExtraFromItemID>";
  4545. }
  4546. public virtual void ExtraFromXmlString(string xmlstr)
  4547. {
  4548. if (string.IsNullOrEmpty(xmlstr))
  4549. {
  4550. FromItemID = UUID.Zero;
  4551. return;
  4552. }
  4553. int indx = xmlstr.IndexOf("<ExtraFromItemID>");
  4554. if (indx < 0)
  4555. {
  4556. FromItemID = UUID.Zero;
  4557. return;
  4558. }
  4559. indx += 17;
  4560. if(indx >= xmlstr.Length)
  4561. {
  4562. FromItemID = UUID.Zero;
  4563. return;
  4564. }
  4565. int indx2 = xmlstr.IndexOf("</ExtraFromItemID>", indx);
  4566. UUID uuid;
  4567. if (indx2 < 0)
  4568. _ = UUID.TryParse(xmlstr.AsSpan()[indx..], out uuid);
  4569. else
  4570. _ = UUID.TryParse(xmlstr.AsSpan()[indx..indx2], out uuid);
  4571. FromItemID = uuid;
  4572. }
  4573. public void ResetOwnerChangeFlag()
  4574. {
  4575. ForEachPart(delegate(SceneObjectPart part)
  4576. {
  4577. part.ResetOwnerChangeFlag();
  4578. });
  4579. InvalidateEffectivePerms();
  4580. }
  4581. private readonly Dictionary<string,int> m_partsNameToLinkMap = new();
  4582. private string GetLinkNumber_lastname;
  4583. private int GetLinkNumber_lastnumber;
  4584. public int GetLinkNumber(string name)
  4585. {
  4586. if(string.IsNullOrEmpty(name) || name == "Object" || name == "Primitive")
  4587. return -1;
  4588. lock(m_partsNameToLinkMap)
  4589. {
  4590. if (name == GetLinkNumber_lastname)
  4591. return GetLinkNumber_lastnumber;
  4592. if (m_partsNameToLinkMap.Count == 0)
  4593. {
  4594. GetLinkNumber_lastname = string.Empty;
  4595. GetLinkNumber_lastnumber = -1;
  4596. SceneObjectPart[] parts = m_parts.GetArray();
  4597. for (int i = 0; i < parts.Length; i++)
  4598. {
  4599. string s = parts[i].Name;
  4600. if(string.IsNullOrEmpty(s) || s == "Object" || s == "Primitive")
  4601. continue;
  4602. if(m_partsNameToLinkMap.ContainsKey(s))
  4603. {
  4604. int ol = parts[i].LinkNum;
  4605. if(ol < m_partsNameToLinkMap[s])
  4606. m_partsNameToLinkMap[s] = ol;
  4607. }
  4608. else
  4609. m_partsNameToLinkMap[s] = parts[i].LinkNum;
  4610. }
  4611. }
  4612. if(m_partsNameToLinkMap.ContainsKey(name))
  4613. {
  4614. GetLinkNumber_lastname = name;
  4615. GetLinkNumber_lastnumber = m_partsNameToLinkMap[name];
  4616. return GetLinkNumber_lastnumber;
  4617. }
  4618. }
  4619. if(m_sittingAvatars.Count > 0)
  4620. {
  4621. int j = m_parts.Count + 1;
  4622. ScenePresence[] avs = m_sittingAvatars.ToArray();
  4623. for (int i = 0; i < avs.Length; i++, j++)
  4624. {
  4625. if (avs[i].Name == name)
  4626. {
  4627. GetLinkNumber_lastname = name;
  4628. GetLinkNumber_lastnumber = j;
  4629. return j;
  4630. }
  4631. }
  4632. }
  4633. return -1;
  4634. }
  4635. public void InvalidatePartsLinkMaps(bool all = true)
  4636. {
  4637. lock(m_partsNameToLinkMap)
  4638. {
  4639. if(all)
  4640. m_partsNameToLinkMap.Clear();
  4641. GetLinkNumber_lastname = string.Empty;
  4642. GetLinkNumber_lastnumber = -1;
  4643. }
  4644. }
  4645. public bool CollisionSoundThrottled(int collisionSoundType)
  4646. {
  4647. double time = m_lastCollisionSoundMS;
  4648. //m_lastCollisionSoundMS = Util.GetTimeStampMS();
  4649. //time = m_lastCollisionSoundMS - time;
  4650. double now = Util.GetTimeStampMS();
  4651. time = now - time;
  4652. switch (collisionSoundType)
  4653. {
  4654. case 0: // default sounds
  4655. case 2: // default sounds with volume set by script
  4656. if(time < 300.0)
  4657. return true;
  4658. break;
  4659. case 1: // selected sound
  4660. if(time < 200.0)
  4661. return true;
  4662. break;
  4663. default:
  4664. break;
  4665. }
  4666. m_lastCollisionSoundMS = now;
  4667. return false;
  4668. }
  4669. public bool GetOwnerName(out string FirstName, out string LastName)
  4670. {
  4671. if (RootPart is not null)
  4672. {
  4673. if(RootPart.OwnerID.Equals(RootPart.GroupID))
  4674. {
  4675. IGroupsModule groups = m_scene.RequestModuleInterface<IGroupsModule>();
  4676. if (groups is not null)
  4677. {
  4678. GroupRecord grprec = groups.GetGroupRecord(RootPart.OwnerID);
  4679. if (grprec is not null)
  4680. {
  4681. FirstName = string.Empty;
  4682. LastName = grprec.GroupName;
  4683. return true;
  4684. }
  4685. }
  4686. }
  4687. else
  4688. return m_scene.UserManagementModule.GetUserName(RootPart.OwnerID, out FirstName, out LastName);
  4689. }
  4690. FirstName = string.Empty;
  4691. LastName = string.Empty;
  4692. return false;
  4693. }
  4694. #endregion
  4695. }
  4696. }