AttachmentsModule.cs 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Reflection;
  30. using System.IO;
  31. using System.Threading;
  32. using System.Xml;
  33. using log4net;
  34. using Mono.Addins;
  35. using Nini.Config;
  36. using OpenMetaverse;
  37. using OpenMetaverse.Packets;
  38. using OpenSim.Framework;
  39. using OpenSim.Region.Framework;
  40. using OpenSim.Region.Framework.Interfaces;
  41. using OpenSim.Region.Framework.Scenes;
  42. using OpenSim.Region.Framework.Scenes.Serialization;
  43. namespace OpenSim.Region.CoreModules.Avatar.Attachments
  44. {
  45. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AttachmentsModule")]
  46. public class AttachmentsModule : IAttachmentsModule, INonSharedRegionModule
  47. {
  48. #region INonSharedRegionModule
  49. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  50. public int DebugLevel { get; set; }
  51. /// <summary>
  52. /// Period to sleep per 100 prims in order to avoid CPU spikes when an avatar with many attachments logs in/changes
  53. /// outfit or many avatars with a medium levels of attachments login/change outfit simultaneously.
  54. /// </summary>
  55. /// <remarks>
  56. /// A value of 0 will apply no pause. The pause is specified in milliseconds.
  57. /// </remarks>
  58. public int ThrottlePer100PrimsRezzed { get; set; }
  59. private Scene m_scene;
  60. private IInventoryAccessModule m_invAccessModule;
  61. /// <summary>
  62. /// Are attachments enabled?
  63. /// </summary>
  64. public bool Enabled { get; private set; }
  65. public string Name { get { return "Attachments Module"; } }
  66. public Type ReplaceableInterface { get { return null; } }
  67. public void Initialise(IConfigSource source)
  68. {
  69. IConfig config = source.Configs["Attachments"];
  70. if (config != null)
  71. {
  72. Enabled = config.GetBoolean("Enabled", true);
  73. ThrottlePer100PrimsRezzed = config.GetInt("ThrottlePer100PrimsRezzed", 0);
  74. }
  75. else
  76. {
  77. Enabled = true;
  78. }
  79. }
  80. public void AddRegion(Scene scene)
  81. {
  82. m_scene = scene;
  83. if (Enabled)
  84. {
  85. // Only register module with scene if it is enabled. All callers check for a null attachments module.
  86. // Ideally, there should be a null attachments module for when this core attachments module has been
  87. // disabled. Registering only when enabled allows for other attachments module implementations.
  88. m_scene.RegisterModuleInterface<IAttachmentsModule>(this);
  89. m_scene.EventManager.OnNewClient += SubscribeToClientEvents;
  90. m_scene.EventManager.OnStartScript += (localID, itemID) => HandleScriptStateChange(localID, true);
  91. m_scene.EventManager.OnStopScript += (localID, itemID) => HandleScriptStateChange(localID, false);
  92. MainConsole.Instance.Commands.AddCommand(
  93. "Debug",
  94. false,
  95. "debug attachments log",
  96. "debug attachments log [0|1]",
  97. "Turn on attachments debug logging",
  98. " <= 0 - turns off debug logging\n"
  99. + " >= 1 - turns on attachment message debug logging",
  100. HandleDebugAttachmentsLog);
  101. MainConsole.Instance.Commands.AddCommand(
  102. "Debug",
  103. false,
  104. "debug attachments throttle",
  105. "debug attachments throttle <ms>",
  106. "Turn on attachments throttling.",
  107. "This requires a millisecond value. " +
  108. " == 0 - disable throttling.\n"
  109. + " > 0 - sleeps for this number of milliseconds per 100 prims rezzed.",
  110. HandleDebugAttachmentsThrottle);
  111. MainConsole.Instance.Commands.AddCommand(
  112. "Debug",
  113. false,
  114. "debug attachments status",
  115. "debug attachments status",
  116. "Show current attachments debug status",
  117. HandleDebugAttachmentsStatus);
  118. }
  119. // TODO: Should probably be subscribing to CloseClient too, but this doesn't yet give us IClientAPI
  120. }
  121. private void HandleDebugAttachmentsLog(string module, string[] args)
  122. {
  123. int debugLevel;
  124. if (!(args.Length == 4 && int.TryParse(args[3], out debugLevel)))
  125. {
  126. MainConsole.Instance.OutputFormat("Usage: debug attachments log [0|1]");
  127. }
  128. else
  129. {
  130. DebugLevel = debugLevel;
  131. MainConsole.Instance.OutputFormat(
  132. "Set event queue debug level to {0} in {1}", DebugLevel, m_scene.Name);
  133. }
  134. }
  135. private void HandleDebugAttachmentsThrottle(string module, string[] args)
  136. {
  137. int ms;
  138. if (args.Length == 4 && int.TryParse(args[3], out ms))
  139. {
  140. ThrottlePer100PrimsRezzed = ms;
  141. MainConsole.Instance.OutputFormat(
  142. "Attachments rez throttle per 100 prims is now {0} in {1}", ThrottlePer100PrimsRezzed, m_scene.Name);
  143. return;
  144. }
  145. MainConsole.Instance.OutputFormat("Usage: debug attachments throttle <ms>");
  146. }
  147. private void HandleDebugAttachmentsStatus(string module, string[] args)
  148. {
  149. MainConsole.Instance.OutputFormat("Settings for {0}", m_scene.Name);
  150. MainConsole.Instance.OutputFormat("Debug logging level: {0}", DebugLevel);
  151. MainConsole.Instance.OutputFormat("Throttle per 100 prims: {0}ms", ThrottlePer100PrimsRezzed);
  152. }
  153. /// <summary>
  154. /// Listen for client triggered running state changes so that we can persist the script's object if necessary.
  155. /// </summary>
  156. /// <param name='localID'></param>
  157. /// <param name='itemID'></param>
  158. private void HandleScriptStateChange(uint localID, bool started)
  159. {
  160. SceneObjectGroup sog = m_scene.GetGroupByPrim(localID);
  161. if (sog != null && sog.IsAttachment)
  162. {
  163. if (!started)
  164. {
  165. // FIXME: This is a convoluted way for working out whether the script state has changed to stop
  166. // because it has been manually stopped or because the stop was called in UpdateDetachedObject() below
  167. // This needs to be handled in a less tangled way.
  168. ScenePresence sp = m_scene.GetScenePresence(sog.AttachedAvatar);
  169. if (sp.ControllingClient.IsActive)
  170. sog.HasGroupChanged = true;
  171. }
  172. else
  173. {
  174. sog.HasGroupChanged = true;
  175. }
  176. }
  177. }
  178. public void RemoveRegion(Scene scene)
  179. {
  180. m_scene.UnregisterModuleInterface<IAttachmentsModule>(this);
  181. if (Enabled)
  182. m_scene.EventManager.OnNewClient -= SubscribeToClientEvents;
  183. }
  184. public void RegionLoaded(Scene scene)
  185. {
  186. m_invAccessModule = m_scene.RequestModuleInterface<IInventoryAccessModule>();
  187. }
  188. public void Close()
  189. {
  190. RemoveRegion(m_scene);
  191. }
  192. #endregion
  193. #region IAttachmentsModule
  194. public void CopyAttachments(IScenePresence sp, AgentData ad)
  195. {
  196. lock (sp.AttachmentsSyncLock)
  197. {
  198. // Attachment objects
  199. List<SceneObjectGroup> attachments = sp.GetAttachments();
  200. if (attachments.Count > 0)
  201. {
  202. ad.AttachmentObjects = new List<ISceneObject>();
  203. ad.AttachmentObjectStates = new List<string>();
  204. // IScriptModule se = m_scene.RequestModuleInterface<IScriptModule>();
  205. sp.InTransitScriptStates.Clear();
  206. foreach (SceneObjectGroup sog in attachments)
  207. {
  208. // We need to make a copy and pass that copy
  209. // because of transfers withn the same sim
  210. ISceneObject clone = sog.CloneForNewScene();
  211. // Attachment module assumes that GroupPosition holds the offsets...!
  212. ((SceneObjectGroup)clone).RootPart.GroupPosition = sog.RootPart.AttachedPos;
  213. ((SceneObjectGroup)clone).IsAttachment = false;
  214. ad.AttachmentObjects.Add(clone);
  215. string state = sog.GetStateSnapshot();
  216. ad.AttachmentObjectStates.Add(state);
  217. sp.InTransitScriptStates.Add(state);
  218. // Scripts of the originals will be removed when the Agent is successfully removed.
  219. // sog.RemoveScriptInstances(true);
  220. }
  221. }
  222. }
  223. }
  224. public void CopyAttachments(AgentData ad, IScenePresence sp)
  225. {
  226. if (ad.AttachmentObjects != null && ad.AttachmentObjects.Count > 0)
  227. {
  228. lock (sp.AttachmentsSyncLock)
  229. sp.ClearAttachments();
  230. int i = 0;
  231. foreach (ISceneObject so in ad.AttachmentObjects)
  232. {
  233. ((SceneObjectGroup)so).LocalId = 0;
  234. ((SceneObjectGroup)so).RootPart.ClearUpdateSchedule();
  235. so.SetState(ad.AttachmentObjectStates[i++], m_scene);
  236. m_scene.IncomingCreateObject(Vector3.Zero, so);
  237. }
  238. }
  239. }
  240. public void RezAttachments(IScenePresence sp)
  241. {
  242. if (!Enabled)
  243. return;
  244. if (null == sp.Appearance)
  245. {
  246. m_log.WarnFormat("[ATTACHMENTS MODULE]: Appearance has not been initialized for agent {0}", sp.UUID);
  247. return;
  248. }
  249. if (sp.GetAttachments().Count > 0)
  250. {
  251. if (DebugLevel > 0)
  252. m_log.DebugFormat(
  253. "[ATTACHMENTS MODULE]: Not doing simulator-side attachment rez for {0} in {1} as their viewer has already rezzed attachments",
  254. m_scene.Name, sp.Name);
  255. return;
  256. }
  257. if (DebugLevel > 0)
  258. m_log.DebugFormat("[ATTACHMENTS MODULE]: Rezzing any attachments for {0} from simulator-side", sp.Name);
  259. List<AvatarAttachment> attachments = sp.Appearance.GetAttachments();
  260. foreach (AvatarAttachment attach in attachments)
  261. {
  262. uint attachmentPt = (uint)attach.AttachPoint;
  263. // m_log.DebugFormat(
  264. // "[ATTACHMENTS MODULE]: Doing initial rez of attachment with itemID {0}, assetID {1}, point {2} for {3} in {4}",
  265. // attach.ItemID, attach.AssetID, p, sp.Name, m_scene.RegionInfo.RegionName);
  266. // For some reason assetIDs are being written as Zero's in the DB -- need to track tat down
  267. // But they're not used anyway, the item is being looked up for now, so let's proceed.
  268. //if (UUID.Zero == assetID)
  269. //{
  270. // m_log.DebugFormat("[ATTACHMENT]: Cannot rez attachment in point {0} with itemID {1}", p, itemID);
  271. // continue;
  272. //}
  273. try
  274. {
  275. // If we're an NPC then skip all the item checks and manipulations since we don't have an
  276. // inventory right now.
  277. RezSingleAttachmentFromInventoryInternal(
  278. sp, sp.PresenceType == PresenceType.Npc ? UUID.Zero : attach.ItemID, attach.AssetID, attachmentPt, true);
  279. }
  280. catch (Exception e)
  281. {
  282. UUID agentId = (sp.ControllingClient == null) ? default(UUID) : sp.ControllingClient.AgentId;
  283. m_log.ErrorFormat("[ATTACHMENTS MODULE]: Unable to rez attachment with itemID {0}, assetID {1}, point {2} for {3}: {4}\n{5}",
  284. attach.ItemID, attach.AssetID, attachmentPt, agentId, e.Message, e.StackTrace);
  285. }
  286. }
  287. }
  288. public void DeRezAttachments(IScenePresence sp)
  289. {
  290. if (!Enabled)
  291. return;
  292. if (DebugLevel > 0)
  293. m_log.DebugFormat("[ATTACHMENTS MODULE]: Saving changed attachments for {0}", sp.Name);
  294. List<SceneObjectGroup> attachments = sp.GetAttachments();
  295. if (attachments.Count <= 0)
  296. return;
  297. Dictionary<SceneObjectGroup, string> scriptStates = new Dictionary<SceneObjectGroup, string>();
  298. foreach (SceneObjectGroup so in attachments)
  299. {
  300. // Scripts MUST be snapshotted before the object is
  301. // removed from the scene because doing otherwise will
  302. // clobber the run flag
  303. // This must be done outside the sp.AttachmentSyncLock so that there is no risk of a deadlock from
  304. // scripts performing attachment operations at the same time. Getting object states stops the scripts.
  305. scriptStates[so] = PrepareScriptInstanceForSave(so, false);
  306. }
  307. lock (sp.AttachmentsSyncLock)
  308. {
  309. foreach (SceneObjectGroup so in attachments)
  310. UpdateDetachedObject(sp, so, scriptStates[so]);
  311. sp.ClearAttachments();
  312. }
  313. }
  314. public void DeleteAttachmentsFromScene(IScenePresence sp, bool silent)
  315. {
  316. if (!Enabled)
  317. return;
  318. if (DebugLevel > 0)
  319. m_log.DebugFormat(
  320. "[ATTACHMENTS MODULE]: Deleting attachments from scene {0} for {1}, silent = {2}",
  321. m_scene.RegionInfo.RegionName, sp.Name, silent);
  322. foreach (SceneObjectGroup sop in sp.GetAttachments())
  323. {
  324. sop.Scene.DeleteSceneObject(sop, silent);
  325. }
  326. sp.ClearAttachments();
  327. }
  328. public bool AttachObject(
  329. IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool addToInventory, bool append)
  330. {
  331. if (!Enabled)
  332. return false;
  333. return AttachObjectInternal(sp, group, attachmentPt, silent, addToInventory, false, append);
  334. }
  335. /// <summary>
  336. /// Internal method which actually does all the work for attaching an object.
  337. /// </summary>
  338. /// <returns>The object attached.</returns>
  339. /// <param name='sp'></param>
  340. /// <param name='group'>The object to attach.</param>
  341. /// <param name='attachmentPt'></param>
  342. /// <param name='silent'></param>
  343. /// <param name='addToInventory'>If true then add object to user inventory.</param>
  344. /// <param name='resumeScripts'>If true then scripts are resumed on the attached object.</param>
  345. /// <param name='append'>Append to attachment point rather than replace.</param>
  346. private bool AttachObjectInternal(
  347. IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool addToInventory, bool resumeScripts, bool append)
  348. {
  349. if (group.GetSittingAvatarsCount() != 0)
  350. {
  351. if (DebugLevel > 0)
  352. m_log.WarnFormat(
  353. "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since {4} avatars are still sitting on it",
  354. group.Name, group.LocalId, sp.Name, attachmentPt, group.GetSittingAvatarsCount());
  355. return false;
  356. }
  357. Vector3 attachPos = group.AbsolutePosition;
  358. // If the attachment point isn't the same as the one previously used
  359. // set it's offset position = 0 so that it appears on the attachment point
  360. // and not in a weird location somewhere unknown.
  361. if (attachmentPt != (uint)AttachmentPoint.Default && attachmentPt != group.AttachmentPoint)
  362. {
  363. attachPos = Vector3.Zero;
  364. }
  365. // if the attachment point is the same as previous, make sure we get the saved
  366. // position info.
  367. if (attachmentPt != 0 && attachmentPt == group.RootPart.Shape.LastAttachPoint)
  368. {
  369. attachPos = group.RootPart.AttachedPos;
  370. }
  371. // AttachmentPt 0 means the client chose to 'wear' the attachment.
  372. if (attachmentPt == (uint)AttachmentPoint.Default)
  373. {
  374. // Check object for stored attachment point
  375. attachmentPt = group.AttachmentPoint;
  376. }
  377. // if we didn't find an attach point, look for where it was last attached
  378. if (attachmentPt == 0)
  379. {
  380. attachmentPt = (uint)group.RootPart.Shape.LastAttachPoint;
  381. attachPos = group.RootPart.AttachedPos;
  382. group.HasGroupChanged = true;
  383. }
  384. // if we still didn't find a suitable attachment point.......
  385. if (attachmentPt == 0)
  386. {
  387. // Stick it on left hand with Zero Offset from the attachment point.
  388. attachmentPt = (uint)AttachmentPoint.LeftHand;
  389. attachPos = Vector3.Zero;
  390. }
  391. group.AttachmentPoint = attachmentPt;
  392. group.AbsolutePosition = attachPos;
  393. List<SceneObjectGroup> attachments = sp.GetAttachments(attachmentPt);
  394. if (attachments.Contains(group))
  395. {
  396. if (DebugLevel > 0)
  397. m_log.WarnFormat(
  398. "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since it's already attached",
  399. group.Name, group.LocalId, sp.Name, attachmentPt);
  400. return false;
  401. }
  402. // If we already have 5, remove the oldest until only 4 are left. Skip over temp ones
  403. while (attachments.Count >= 5)
  404. {
  405. if (attachments[0].FromItemID != UUID.Zero)
  406. DetachSingleAttachmentToInv(sp, attachments[0]);
  407. attachments.RemoveAt(0);
  408. }
  409. // If we're not appending, remove the rest as well
  410. if (attachments.Count != 0 && !append)
  411. {
  412. foreach (SceneObjectGroup g in attachments)
  413. {
  414. if (g.FromItemID != UUID.Zero)
  415. DetachSingleAttachmentToInv(sp, g);
  416. }
  417. }
  418. lock (sp.AttachmentsSyncLock)
  419. {
  420. if (addToInventory && sp.PresenceType != PresenceType.Npc)
  421. UpdateUserInventoryWithAttachment(sp, group, attachmentPt, append);
  422. AttachToAgent(sp, group, attachmentPt, attachPos, silent);
  423. if (resumeScripts)
  424. {
  425. // Fire after attach, so we don't get messy perms dialogs
  426. // 4 == AttachedRez
  427. group.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 4);
  428. group.ResumeScripts();
  429. }
  430. // Do this last so that event listeners have access to all the effects of the attachment
  431. m_scene.EventManager.TriggerOnAttach(group.LocalId, group.FromItemID, sp.UUID);
  432. }
  433. return true;
  434. }
  435. private void UpdateUserInventoryWithAttachment(IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool append)
  436. {
  437. // Add the new attachment to inventory if we don't already have it.
  438. UUID newAttachmentItemID = group.FromItemID;
  439. if (newAttachmentItemID == UUID.Zero)
  440. newAttachmentItemID = AddSceneObjectAsNewAttachmentInInv(sp, group).ID;
  441. ShowAttachInUserInventory(sp, attachmentPt, newAttachmentItemID, group, append);
  442. }
  443. public SceneObjectGroup RezSingleAttachmentFromInventory(IScenePresence sp, UUID itemID, uint AttachmentPt)
  444. {
  445. if (!Enabled)
  446. return null;
  447. if (DebugLevel > 0)
  448. m_log.DebugFormat(
  449. "[ATTACHMENTS MODULE]: RezSingleAttachmentFromInventory to point {0} from item {1} for {2} in {3}",
  450. (AttachmentPoint)AttachmentPt, itemID, sp.Name, m_scene.Name);
  451. // We check the attachments in the avatar appearance here rather than the objects attached to the
  452. // ScenePresence itself so that we can ignore calls by viewer 2/3 to attach objects on startup. We are
  453. // already doing this in ScenePresence.MakeRootAgent(). Simulator-side attaching needs to be done
  454. // because pre-outfit folder viewers (most version 1 viewers) require it.
  455. bool alreadyOn = false;
  456. List<AvatarAttachment> existingAttachments = sp.Appearance.GetAttachments();
  457. foreach (AvatarAttachment existingAttachment in existingAttachments)
  458. {
  459. if (existingAttachment.ItemID == itemID)
  460. {
  461. alreadyOn = true;
  462. break;
  463. }
  464. }
  465. if (alreadyOn)
  466. {
  467. if (DebugLevel > 0)
  468. m_log.DebugFormat(
  469. "[ATTACHMENTS MODULE]: Ignoring request by {0} to wear item {1} at {2} since it is already worn",
  470. sp.Name, itemID, AttachmentPt);
  471. return null;
  472. }
  473. bool append = (AttachmentPt & 0x80) != 0;
  474. AttachmentPt &= 0x7f;
  475. return RezSingleAttachmentFromInventoryInternal(sp, itemID, UUID.Zero, AttachmentPt, append);
  476. }
  477. public void RezMultipleAttachmentsFromInventory(IScenePresence sp, List<KeyValuePair<UUID, uint>> rezlist)
  478. {
  479. if (!Enabled)
  480. return;
  481. if (DebugLevel > 0)
  482. m_log.DebugFormat(
  483. "[ATTACHMENTS MODULE]: Rezzing {0} attachments from inventory for {1} in {2}",
  484. rezlist.Count, sp.Name, m_scene.Name);
  485. foreach (KeyValuePair<UUID, uint> rez in rezlist)
  486. {
  487. RezSingleAttachmentFromInventory(sp, rez.Key, rez.Value);
  488. }
  489. }
  490. public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId)
  491. {
  492. DetachSingleAttachmentToGround(sp, soLocalId, sp.AbsolutePosition, Quaternion.Identity);
  493. }
  494. public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId, Vector3 absolutePos, Quaternion absoluteRot)
  495. {
  496. if (!Enabled)
  497. return;
  498. if (DebugLevel > 0)
  499. m_log.DebugFormat(
  500. "[ATTACHMENTS MODULE]: DetachSingleAttachmentToGround() for {0}, object {1}",
  501. sp.UUID, soLocalId);
  502. SceneObjectGroup so = m_scene.GetGroupByPrim(soLocalId);
  503. if (so == null)
  504. return;
  505. if (so.AttachedAvatar != sp.UUID)
  506. return;
  507. UUID inventoryID = so.FromItemID;
  508. // As per Linden spec, drop is disabled for temp attachs
  509. if (inventoryID == UUID.Zero)
  510. return;
  511. if (DebugLevel > 0)
  512. m_log.DebugFormat(
  513. "[ATTACHMENTS MODULE]: In DetachSingleAttachmentToGround(), object is {0} {1}, associated item is {2}",
  514. so.Name, so.LocalId, inventoryID);
  515. lock (sp.AttachmentsSyncLock)
  516. {
  517. if (!m_scene.Permissions.CanRezObject(
  518. so.PrimCount, sp.UUID, sp.AbsolutePosition))
  519. return;
  520. bool changed = false;
  521. if (inventoryID != UUID.Zero)
  522. changed = sp.Appearance.DetachAttachment(inventoryID);
  523. if (changed && m_scene.AvatarFactory != null)
  524. m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
  525. sp.RemoveAttachment(so);
  526. so.FromItemID = UUID.Zero;
  527. SceneObjectPart rootPart = so.RootPart;
  528. so.AbsolutePosition = absolutePos;
  529. if (absoluteRot != Quaternion.Identity)
  530. {
  531. so.UpdateGroupRotationR(absoluteRot);
  532. }
  533. so.AttachedAvatar = UUID.Zero;
  534. rootPart.SetParentLocalId(0);
  535. so.ClearPartAttachmentData();
  536. rootPart.ApplyPhysics(rootPart.GetEffectiveObjectFlags(), rootPart.VolumeDetectActive);
  537. so.HasGroupChanged = true;
  538. so.RootPart.Shape.LastAttachPoint = (byte)so.AttachmentPoint;
  539. rootPart.Rezzed = DateTime.Now;
  540. rootPart.RemFlag(PrimFlags.TemporaryOnRez);
  541. so.AttachToBackup();
  542. m_scene.EventManager.TriggerParcelPrimCountTainted();
  543. rootPart.ScheduleFullUpdate();
  544. rootPart.ClearUndoState();
  545. List<UUID> uuids = new List<UUID>();
  546. uuids.Add(inventoryID);
  547. m_scene.InventoryService.DeleteItems(sp.UUID, uuids);
  548. sp.ControllingClient.SendRemoveInventoryItem(inventoryID);
  549. }
  550. m_scene.EventManager.TriggerOnAttach(so.LocalId, so.UUID, UUID.Zero);
  551. }
  552. public void DetachSingleAttachmentToInv(IScenePresence sp, SceneObjectGroup so)
  553. {
  554. if (so.AttachedAvatar != sp.UUID)
  555. {
  556. m_log.WarnFormat(
  557. "[ATTACHMENTS MODULE]: Tried to detach object {0} from {1} {2} but attached avatar id was {3} in {4}",
  558. so.Name, sp.Name, sp.UUID, so.AttachedAvatar, m_scene.RegionInfo.RegionName);
  559. return;
  560. }
  561. if (DebugLevel > 0)
  562. m_log.DebugFormat(
  563. "[ATTACHMENTS MODULE]: Detaching object {0} {1} (FromItemID {2}) for {3} in {4}",
  564. so.Name, so.LocalId, so.FromItemID, sp.Name, m_scene.Name);
  565. // Scripts MUST be snapshotted before the object is
  566. // removed from the scene because doing otherwise will
  567. // clobber the run flag
  568. // This must be done outside the sp.AttachmentSyncLock so that there is no risk of a deadlock from
  569. // scripts performing attachment operations at the same time. Getting object states stops the scripts.
  570. string scriptedState = PrepareScriptInstanceForSave(so, true);
  571. lock (sp.AttachmentsSyncLock)
  572. {
  573. // Save avatar attachment information
  574. // m_log.Debug("[ATTACHMENTS MODULE]: Detaching from UserID: " + sp.UUID + ", ItemID: " + itemID);
  575. bool changed = sp.Appearance.DetachAttachment(so.FromItemID);
  576. if (changed && m_scene.AvatarFactory != null)
  577. m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
  578. sp.RemoveAttachment(so);
  579. UpdateDetachedObject(sp, so, scriptedState);
  580. }
  581. }
  582. public void UpdateAttachmentPosition(SceneObjectGroup sog, Vector3 pos)
  583. {
  584. if (!Enabled)
  585. return;
  586. sog.UpdateGroupPosition(pos);
  587. sog.HasGroupChanged = true;
  588. }
  589. #endregion
  590. #region AttachmentModule private methods
  591. // This is public but is not part of the IAttachmentsModule interface.
  592. // RegionCombiner module needs to poke at it to deliver client events.
  593. // This breaks the encapsulation of the module and should get fixed somehow.
  594. public void SubscribeToClientEvents(IClientAPI client)
  595. {
  596. client.OnRezSingleAttachmentFromInv += Client_OnRezSingleAttachmentFromInv;
  597. client.OnRezMultipleAttachmentsFromInv += Client_OnRezMultipleAttachmentsFromInv;
  598. client.OnObjectAttach += Client_OnObjectAttach;
  599. client.OnObjectDetach += Client_OnObjectDetach;
  600. client.OnDetachAttachmentIntoInv += Client_OnDetachAttachmentIntoInv;
  601. client.OnObjectDrop += Client_OnObjectDrop;
  602. }
  603. // This is public but is not part of the IAttachmentsModule interface.
  604. // RegionCombiner module needs to poke at it to deliver client events.
  605. // This breaks the encapsulation of the module and should get fixed somehow.
  606. public void UnsubscribeFromClientEvents(IClientAPI client)
  607. {
  608. client.OnRezSingleAttachmentFromInv -= Client_OnRezSingleAttachmentFromInv;
  609. client.OnRezMultipleAttachmentsFromInv -= Client_OnRezMultipleAttachmentsFromInv;
  610. client.OnObjectAttach -= Client_OnObjectAttach;
  611. client.OnObjectDetach -= Client_OnObjectDetach;
  612. client.OnDetachAttachmentIntoInv -= Client_OnDetachAttachmentIntoInv;
  613. client.OnObjectDrop -= Client_OnObjectDrop;
  614. }
  615. /// <summary>
  616. /// Update the attachment asset for the new sog details if they have changed.
  617. /// </summary>
  618. /// <remarks>
  619. /// This is essential for preserving attachment attributes such as permission. Unlike normal scene objects,
  620. /// these details are not stored on the region.
  621. /// </remarks>
  622. /// <param name="sp"></param>
  623. /// <param name="grp"></param>
  624. /// <param name="saveAllScripted"></param>
  625. private void UpdateKnownItem(IScenePresence sp, SceneObjectGroup grp, string scriptedState)
  626. {
  627. if (grp.FromItemID == UUID.Zero)
  628. {
  629. // We can't save temp attachments
  630. grp.HasGroupChanged = false;
  631. return;
  632. }
  633. // Saving attachments for NPCs messes them up for the real owner!
  634. INPCModule module = m_scene.RequestModuleInterface<INPCModule>();
  635. if (module != null)
  636. {
  637. if (module.IsNPC(sp.UUID, m_scene))
  638. return;
  639. }
  640. if (grp.HasGroupChanged)
  641. {
  642. m_log.DebugFormat(
  643. "[ATTACHMENTS MODULE]: Updating asset for attachment {0}, attachpoint {1}",
  644. grp.UUID, grp.AttachmentPoint);
  645. string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(grp, scriptedState);
  646. InventoryItemBase item = new InventoryItemBase(grp.FromItemID, sp.UUID);
  647. item = m_scene.InventoryService.GetItem(item);
  648. if (item != null)
  649. {
  650. AssetBase asset = m_scene.CreateAsset(
  651. grp.GetPartName(grp.LocalId),
  652. grp.GetPartDescription(grp.LocalId),
  653. (sbyte)AssetType.Object,
  654. Utils.StringToBytes(sceneObjectXml),
  655. sp.UUID);
  656. m_scene.AssetService.Store(asset);
  657. item.AssetID = asset.FullID;
  658. item.Description = asset.Description;
  659. item.Name = asset.Name;
  660. item.AssetType = asset.Type;
  661. item.InvType = (int)InventoryType.Object;
  662. m_scene.InventoryService.UpdateItem(item);
  663. // If the name of the object has been changed whilst attached then we want to update the inventory
  664. // item in the viewer.
  665. if (sp.ControllingClient != null)
  666. sp.ControllingClient.SendInventoryItemCreateUpdate(item, 0);
  667. }
  668. grp.HasGroupChanged = false; // Prevent it being saved over and over
  669. }
  670. else if (DebugLevel > 0)
  671. {
  672. m_log.DebugFormat(
  673. "[ATTACHMENTS MODULE]: Don't need to update asset for unchanged attachment {0}, attachpoint {1}",
  674. grp.UUID, grp.AttachmentPoint);
  675. }
  676. }
  677. /// <summary>
  678. /// Attach this scene object to the given avatar.
  679. /// </summary>
  680. /// <remarks>
  681. /// This isn't publicly available since attachments should always perform the corresponding inventory
  682. /// operation (to show the attach in user inventory and update the asset with positional information).
  683. /// </remarks>
  684. /// <param name="sp"></param>
  685. /// <param name="so"></param>
  686. /// <param name="attachmentpoint"></param>
  687. /// <param name="attachOffset"></param>
  688. /// <param name="silent"></param>
  689. private void AttachToAgent(
  690. IScenePresence sp, SceneObjectGroup so, uint attachmentpoint, Vector3 attachOffset, bool silent)
  691. {
  692. if (DebugLevel > 0)
  693. m_log.DebugFormat(
  694. "[ATTACHMENTS MODULE]: Adding attachment {0} to avatar {1} in pt {2} pos {3} {4}",
  695. so.Name, sp.Name, attachmentpoint, attachOffset, so.RootPart.AttachedPos);
  696. so.DetachFromBackup();
  697. // Remove from database and parcel prim count
  698. m_scene.DeleteFromStorage(so.UUID);
  699. m_scene.EventManager.TriggerParcelPrimCountTainted();
  700. so.AttachedAvatar = sp.UUID;
  701. if (so.RootPart.PhysActor != null)
  702. so.RootPart.RemoveFromPhysics();
  703. so.AbsolutePosition = attachOffset;
  704. so.RootPart.AttachedPos = attachOffset;
  705. so.IsAttachment = true;
  706. so.RootPart.SetParentLocalId(sp.LocalId);
  707. so.AttachmentPoint = attachmentpoint;
  708. sp.AddAttachment(so);
  709. if (!silent)
  710. {
  711. if (so.HasPrivateAttachmentPoint)
  712. {
  713. if (DebugLevel > 0)
  714. m_log.DebugFormat(
  715. "[ATTACHMENTS MODULE]: Killing private HUD {0} for avatars other than {1} at attachment point {2}",
  716. so.Name, sp.Name, so.AttachmentPoint);
  717. // As this scene object can now only be seen by the attaching avatar, tell everybody else in the
  718. // scene that it's no longer in their awareness.
  719. m_scene.ForEachClient(
  720. client =>
  721. { if (client.AgentId != so.AttachedAvatar)
  722. client.SendKillObject(new List<uint>() { so.LocalId });
  723. });
  724. }
  725. // Fudge below is an extremely unhelpful comment. It's probably here so that the scheduled full update
  726. // will succeed, as that will not update if an attachment is selected.
  727. so.IsSelected = false; // fudge....
  728. so.ScheduleGroupForFullUpdate();
  729. }
  730. // In case it is later dropped again, don't let
  731. // it get cleaned up
  732. so.RootPart.RemFlag(PrimFlags.TemporaryOnRez);
  733. }
  734. /// <summary>
  735. /// Add a scene object as a new attachment in the user inventory.
  736. /// </summary>
  737. /// <param name="remoteClient"></param>
  738. /// <param name="grp"></param>
  739. /// <returns>The user inventory item created that holds the attachment.</returns>
  740. private InventoryItemBase AddSceneObjectAsNewAttachmentInInv(IScenePresence sp, SceneObjectGroup grp)
  741. {
  742. if (m_invAccessModule == null)
  743. return null;
  744. if (DebugLevel > 0)
  745. m_log.DebugFormat(
  746. "[ATTACHMENTS MODULE]: Called AddSceneObjectAsAttachment for object {0} {1} for {2}",
  747. grp.Name, grp.LocalId, sp.Name);
  748. InventoryItemBase newItem
  749. = m_invAccessModule.CopyToInventory(
  750. DeRezAction.TakeCopy,
  751. m_scene.InventoryService.GetFolderForType(sp.UUID, AssetType.Object).ID,
  752. new List<SceneObjectGroup> { grp },
  753. sp.ControllingClient, true)[0];
  754. // sets itemID so client can show item as 'attached' in inventory
  755. grp.FromItemID = newItem.ID;
  756. return newItem;
  757. }
  758. /// <summary>
  759. /// Prepares the script instance for save.
  760. /// </summary>
  761. /// <remarks>
  762. /// This involves triggering the detach event and getting the script state (which also stops the script)
  763. /// This MUST be done outside sp.AttachmentsSyncLock, since otherwise there is a chance of deadlock if a
  764. /// running script is performing attachment operations.
  765. /// </remarks>
  766. /// <returns>
  767. /// The script state ready for persistence.
  768. /// </returns>
  769. /// <param name='grp'>
  770. /// </param>
  771. /// <param name='fireDetachEvent'>
  772. /// If true, then fire the script event before we save its state.
  773. /// </param>
  774. private string PrepareScriptInstanceForSave(SceneObjectGroup grp, bool fireDetachEvent)
  775. {
  776. if (fireDetachEvent)
  777. m_scene.EventManager.TriggerOnAttach(grp.LocalId, grp.FromItemID, UUID.Zero);
  778. using (StringWriter sw = new StringWriter())
  779. {
  780. using (XmlTextWriter writer = new XmlTextWriter(sw))
  781. {
  782. grp.SaveScriptedState(writer);
  783. }
  784. return sw.ToString();
  785. }
  786. }
  787. private void UpdateDetachedObject(IScenePresence sp, SceneObjectGroup so, string scriptedState)
  788. {
  789. // Don't save attachments for HG visitors, it
  790. // messes up their inventory. When a HG visitor logs
  791. // out on a foreign grid, their attachments will be
  792. // reloaded in the state they were in when they left
  793. // the home grid. This is best anyway as the visited
  794. // grid may use an incompatible script engine.
  795. bool saveChanged
  796. = sp.PresenceType != PresenceType.Npc
  797. && (m_scene.UserManagementModule == null
  798. || m_scene.UserManagementModule.IsLocalGridUser(sp.UUID));
  799. // Remove the object from the scene so no more updates
  800. // are sent. Doing this before the below changes will ensure
  801. // updates can't cause "HUD artefacts"
  802. m_scene.DeleteSceneObject(so, false, false);
  803. // Prepare sog for storage
  804. so.AttachedAvatar = UUID.Zero;
  805. so.RootPart.SetParentLocalId(0);
  806. so.IsAttachment = false;
  807. if (saveChanged)
  808. {
  809. // We cannot use AbsolutePosition here because that would
  810. // attempt to cross the prim as it is detached
  811. so.ForEachPart(x => { x.GroupPosition = so.RootPart.AttachedPos; });
  812. UpdateKnownItem(sp, so, scriptedState);
  813. }
  814. // Now, remove the scripts
  815. so.RemoveScriptInstances(true);
  816. }
  817. protected SceneObjectGroup RezSingleAttachmentFromInventoryInternal(
  818. IScenePresence sp, UUID itemID, UUID assetID, uint attachmentPt, bool append)
  819. {
  820. if (m_invAccessModule == null)
  821. return null;
  822. SceneObjectGroup objatt;
  823. if (itemID != UUID.Zero)
  824. objatt = m_invAccessModule.RezObject(sp.ControllingClient,
  825. itemID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true,
  826. false, false, sp.UUID, true);
  827. else
  828. objatt = m_invAccessModule.RezObject(sp.ControllingClient,
  829. null, assetID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true,
  830. false, false, sp.UUID, true);
  831. if (objatt == null)
  832. {
  833. m_log.WarnFormat(
  834. "[ATTACHMENTS MODULE]: Could not retrieve item {0} for attaching to avatar {1} at point {2}",
  835. itemID, sp.Name, attachmentPt);
  836. return null;
  837. }
  838. if (DebugLevel > 0)
  839. m_log.DebugFormat(
  840. "[ATTACHMENTS MODULE]: Rezzed single object {0} with {1} prims for attachment to {2} on point {3} in {4}",
  841. objatt.Name, objatt.PrimCount, sp.Name, attachmentPt, m_scene.Name);
  842. // HasGroupChanged is being set from within RezObject. Ideally it would be set by the caller.
  843. objatt.HasGroupChanged = false;
  844. bool tainted = false;
  845. if (attachmentPt != 0 && attachmentPt != objatt.AttachmentPoint)
  846. tainted = true;
  847. // FIXME: Detect whether it's really likely for AttachObject to throw an exception in the normal
  848. // course of events. If not, then it's probably not worth trying to recover the situation
  849. // since this is more likely to trigger further exceptions and confuse later debugging. If
  850. // exceptions can be thrown in expected error conditions (not NREs) then make this consistent
  851. // since other normal error conditions will simply return false instead.
  852. // This will throw if the attachment fails
  853. try
  854. {
  855. AttachObjectInternal(sp, objatt, attachmentPt, false, true, true, append);
  856. }
  857. catch (Exception e)
  858. {
  859. m_log.ErrorFormat(
  860. "[ATTACHMENTS MODULE]: Failed to attach {0} {1} for {2}, exception {3}{4}",
  861. objatt.Name, objatt.UUID, sp.Name, e.Message, e.StackTrace);
  862. // Make sure the object doesn't stick around and bail
  863. sp.RemoveAttachment(objatt);
  864. m_scene.DeleteSceneObject(objatt, false);
  865. return null;
  866. }
  867. if (tainted)
  868. objatt.HasGroupChanged = true;
  869. if (ThrottlePer100PrimsRezzed > 0)
  870. {
  871. int throttleMs = (int)Math.Round((float)objatt.PrimCount / 100 * ThrottlePer100PrimsRezzed);
  872. if (DebugLevel > 0)
  873. m_log.DebugFormat(
  874. "[ATTACHMENTS MODULE]: Throttling by {0}ms after rez of {1} with {2} prims for attachment to {3} on point {4} in {5}",
  875. throttleMs, objatt.Name, objatt.PrimCount, sp.Name, attachmentPt, m_scene.Name);
  876. Thread.Sleep(throttleMs);
  877. }
  878. return objatt;
  879. }
  880. /// <summary>
  881. /// Update the user inventory to reflect an attachment
  882. /// </summary>
  883. /// <param name="sp"></param>
  884. /// <param name="AttachmentPt"></param>
  885. /// <param name="itemID"></param>
  886. /// <param name="att"></param>
  887. private void ShowAttachInUserInventory(IScenePresence sp, uint AttachmentPt, UUID itemID, SceneObjectGroup att, bool append)
  888. {
  889. // m_log.DebugFormat(
  890. // "[USER INVENTORY]: Updating attachment {0} for {1} at {2} using item ID {3}",
  891. // att.Name, sp.Name, AttachmentPt, itemID);
  892. if (UUID.Zero == itemID)
  893. {
  894. m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error inventory item ID.");
  895. return;
  896. }
  897. if (0 == AttachmentPt)
  898. {
  899. m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error attachment point.");
  900. return;
  901. }
  902. InventoryItemBase item = new InventoryItemBase(itemID, sp.UUID);
  903. item = m_scene.InventoryService.GetItem(item);
  904. if (item == null)
  905. return;
  906. int attFlag = append ? 0x80 : 0;
  907. bool changed = sp.Appearance.SetAttachment((int)AttachmentPt | attFlag, itemID, item.AssetID);
  908. if (changed && m_scene.AvatarFactory != null)
  909. {
  910. if (DebugLevel > 0)
  911. m_log.DebugFormat(
  912. "[ATTACHMENTS MODULE]: Queueing appearance save for {0}, attachment {1} point {2} in ShowAttachInUserInventory()",
  913. sp.Name, att.Name, AttachmentPt);
  914. m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
  915. }
  916. }
  917. #endregion
  918. #region Client Event Handlers
  919. private ISceneEntity Client_OnRezSingleAttachmentFromInv(IClientAPI remoteClient, UUID itemID, uint AttachmentPt)
  920. {
  921. if (!Enabled)
  922. return null;
  923. if (DebugLevel > 0)
  924. m_log.DebugFormat(
  925. "[ATTACHMENTS MODULE]: Rezzing attachment to point {0} from item {1} for {2}",
  926. (AttachmentPoint)AttachmentPt, itemID, remoteClient.Name);
  927. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  928. if (sp == null)
  929. {
  930. m_log.ErrorFormat(
  931. "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1} in RezSingleAttachmentFromInventory()",
  932. remoteClient.Name, remoteClient.AgentId);
  933. return null;
  934. }
  935. return RezSingleAttachmentFromInventory(sp, itemID, AttachmentPt);
  936. }
  937. private void Client_OnRezMultipleAttachmentsFromInv(IClientAPI remoteClient, List<KeyValuePair<UUID, uint>> rezlist)
  938. {
  939. if (!Enabled)
  940. return;
  941. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  942. if (sp != null)
  943. RezMultipleAttachmentsFromInventory(sp, rezlist);
  944. else
  945. m_log.ErrorFormat(
  946. "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1} in RezMultipleAttachmentsFromInventory()",
  947. remoteClient.Name, remoteClient.AgentId);
  948. }
  949. private void Client_OnObjectAttach(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, bool silent)
  950. {
  951. if (DebugLevel > 0)
  952. m_log.DebugFormat(
  953. "[ATTACHMENTS MODULE]: Attaching object local id {0} to {1} point {2} from ground (silent = {3})",
  954. objectLocalID, remoteClient.Name, AttachmentPt, silent);
  955. if (!Enabled)
  956. return;
  957. try
  958. {
  959. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  960. if (sp == null)
  961. {
  962. m_log.ErrorFormat(
  963. "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1}", remoteClient.Name, remoteClient.AgentId);
  964. return;
  965. }
  966. // If we can't take it, we can't attach it!
  967. SceneObjectPart part = m_scene.GetSceneObjectPart(objectLocalID);
  968. if (part == null)
  969. return;
  970. if (!m_scene.Permissions.CanTakeObject(part.UUID, remoteClient.AgentId))
  971. {
  972. remoteClient.SendAgentAlertMessage(
  973. "You don't have sufficient permissions to attach this object", false);
  974. return;
  975. }
  976. bool append = (AttachmentPt & 0x80) != 0;
  977. AttachmentPt &= 0x7f;
  978. // Calls attach with a Zero position
  979. if (AttachObject(sp, part.ParentGroup, AttachmentPt, false, true, append))
  980. {
  981. if (DebugLevel > 0)
  982. m_log.Debug(
  983. "[ATTACHMENTS MODULE]: Saving avatar attachment. AgentID: " + remoteClient.AgentId
  984. + ", AttachmentPoint: " + AttachmentPt);
  985. // Save avatar attachment information
  986. m_scene.EventManager.TriggerOnAttach(objectLocalID, part.ParentGroup.FromItemID, remoteClient.AgentId);
  987. }
  988. }
  989. catch (Exception e)
  990. {
  991. m_log.ErrorFormat("[ATTACHMENTS MODULE]: exception upon Attach Object {0}{1}", e.Message, e.StackTrace);
  992. }
  993. }
  994. private void Client_OnObjectDetach(uint objectLocalID, IClientAPI remoteClient)
  995. {
  996. if (!Enabled)
  997. return;
  998. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  999. SceneObjectGroup group = m_scene.GetGroupByPrim(objectLocalID);
  1000. if (sp != null && group != null && group.FromItemID != UUID.Zero)
  1001. DetachSingleAttachmentToInv(sp, group);
  1002. }
  1003. private void Client_OnDetachAttachmentIntoInv(UUID itemID, IClientAPI remoteClient)
  1004. {
  1005. if (!Enabled)
  1006. return;
  1007. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  1008. if (sp != null)
  1009. {
  1010. List<SceneObjectGroup> attachments = sp.GetAttachments();
  1011. foreach (SceneObjectGroup group in attachments)
  1012. {
  1013. if (group.FromItemID == itemID && group.FromItemID != UUID.Zero)
  1014. {
  1015. DetachSingleAttachmentToInv(sp, group);
  1016. return;
  1017. }
  1018. }
  1019. }
  1020. }
  1021. private void Client_OnObjectDrop(uint soLocalId, IClientAPI remoteClient)
  1022. {
  1023. if (!Enabled)
  1024. return;
  1025. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  1026. if (sp != null)
  1027. DetachSingleAttachmentToGround(sp, soLocalId);
  1028. }
  1029. #endregion
  1030. }
  1031. }