AttachmentsModule.cs 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  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.Xml;
  32. using log4net;
  33. using Mono.Addins;
  34. using Nini.Config;
  35. using OpenMetaverse;
  36. using OpenMetaverse.Packets;
  37. using OpenSim.Framework;
  38. using OpenSim.Region.Framework;
  39. using OpenSim.Region.Framework.Interfaces;
  40. using OpenSim.Region.Framework.Scenes;
  41. using OpenSim.Region.Framework.Scenes.Serialization;
  42. namespace OpenSim.Region.CoreModules.Avatar.Attachments
  43. {
  44. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AttachmentsModule")]
  45. public class AttachmentsModule : IAttachmentsModule, INonSharedRegionModule
  46. {
  47. #region INonSharedRegionModule
  48. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  49. private Scene m_scene;
  50. private IInventoryAccessModule m_invAccessModule;
  51. /// <summary>
  52. /// Are attachments enabled?
  53. /// </summary>
  54. public bool Enabled { get; private set; }
  55. public string Name { get { return "Attachments Module"; } }
  56. public Type ReplaceableInterface { get { return null; } }
  57. public void Initialise(IConfigSource source)
  58. {
  59. IConfig config = source.Configs["Attachments"];
  60. if (config != null)
  61. Enabled = config.GetBoolean("Enabled", true);
  62. else
  63. Enabled = true;
  64. }
  65. public void AddRegion(Scene scene)
  66. {
  67. m_scene = scene;
  68. m_scene.RegisterModuleInterface<IAttachmentsModule>(this);
  69. if (Enabled)
  70. m_scene.EventManager.OnNewClient += SubscribeToClientEvents;
  71. // TODO: Should probably be subscribing to CloseClient too, but this doesn't yet give us IClientAPI
  72. }
  73. public void RemoveRegion(Scene scene)
  74. {
  75. m_scene.UnregisterModuleInterface<IAttachmentsModule>(this);
  76. if (Enabled)
  77. m_scene.EventManager.OnNewClient -= SubscribeToClientEvents;
  78. }
  79. public void RegionLoaded(Scene scene)
  80. {
  81. m_invAccessModule = m_scene.RequestModuleInterface<IInventoryAccessModule>();
  82. }
  83. public void Close()
  84. {
  85. RemoveRegion(m_scene);
  86. }
  87. #endregion
  88. #region IAttachmentsModule
  89. public void CopyAttachments(IScenePresence sp, AgentData ad)
  90. {
  91. lock (sp.AttachmentsSyncLock)
  92. {
  93. // Attachment objects
  94. List<SceneObjectGroup> attachments = sp.GetAttachments();
  95. if (attachments.Count > 0)
  96. {
  97. ad.AttachmentObjects = new List<ISceneObject>();
  98. ad.AttachmentObjectStates = new List<string>();
  99. // IScriptModule se = m_scene.RequestModuleInterface<IScriptModule>();
  100. sp.InTransitScriptStates.Clear();
  101. foreach (SceneObjectGroup sog in attachments)
  102. {
  103. // We need to make a copy and pass that copy
  104. // because of transfers withn the same sim
  105. ISceneObject clone = sog.CloneForNewScene();
  106. // Attachment module assumes that GroupPosition holds the offsets...!
  107. ((SceneObjectGroup)clone).RootPart.GroupPosition = sog.RootPart.AttachedPos;
  108. ((SceneObjectGroup)clone).IsAttachment = false;
  109. ad.AttachmentObjects.Add(clone);
  110. string state = sog.GetStateSnapshot();
  111. ad.AttachmentObjectStates.Add(state);
  112. sp.InTransitScriptStates.Add(state);
  113. // Let's remove the scripts of the original object here
  114. sog.RemoveScriptInstances(true);
  115. }
  116. }
  117. }
  118. }
  119. public void CopyAttachments(AgentData ad, IScenePresence sp)
  120. {
  121. if (ad.AttachmentObjects != null && ad.AttachmentObjects.Count > 0)
  122. {
  123. lock (sp.AttachmentsSyncLock)
  124. sp.ClearAttachments();
  125. int i = 0;
  126. foreach (ISceneObject so in ad.AttachmentObjects)
  127. {
  128. ((SceneObjectGroup)so).LocalId = 0;
  129. ((SceneObjectGroup)so).RootPart.ClearUpdateSchedule();
  130. so.SetState(ad.AttachmentObjectStates[i++], m_scene);
  131. m_scene.IncomingCreateObject(Vector3.Zero, so);
  132. }
  133. }
  134. }
  135. /// <summary>
  136. /// RezAttachments. This should only be called upon login on the first region.
  137. /// Attachment rezzings on crossings and TPs are done in a different way.
  138. /// </summary>
  139. public void RezAttachments(IScenePresence sp)
  140. {
  141. if (!Enabled)
  142. return;
  143. if (null == sp.Appearance)
  144. {
  145. m_log.WarnFormat("[ATTACHMENTS MODULE]: Appearance has not been initialized for agent {0}", sp.UUID);
  146. return;
  147. }
  148. // m_log.DebugFormat("[ATTACHMENTS MODULE]: Rezzing any attachments for {0}", sp.Name);
  149. List<AvatarAttachment> attachments = sp.Appearance.GetAttachments();
  150. foreach (AvatarAttachment attach in attachments)
  151. {
  152. uint p = (uint)attach.AttachPoint;
  153. // m_log.DebugFormat(
  154. // "[ATTACHMENTS MODULE]: Doing initial rez of attachment with itemID {0}, assetID {1}, point {2} for {3} in {4}",
  155. // attach.ItemID, attach.AssetID, p, sp.Name, m_scene.RegionInfo.RegionName);
  156. // For some reason assetIDs are being written as Zero's in the DB -- need to track tat down
  157. // But they're not used anyway, the item is being looked up for now, so let's proceed.
  158. //if (UUID.Zero == assetID)
  159. //{
  160. // m_log.DebugFormat("[ATTACHMENT]: Cannot rez attachment in point {0} with itemID {1}", p, itemID);
  161. // continue;
  162. //}
  163. try
  164. {
  165. // If we're an NPC then skip all the item checks and manipulations since we don't have an
  166. // inventory right now.
  167. if (sp.PresenceType == PresenceType.Npc)
  168. RezSingleAttachmentFromInventoryInternal(sp, UUID.Zero, attach.AssetID, p);
  169. else
  170. RezSingleAttachmentFromInventory(sp, attach.ItemID, p);
  171. }
  172. catch (Exception e)
  173. {
  174. UUID agentId = (sp.ControllingClient == null) ? (UUID)null : sp.ControllingClient.AgentId;
  175. m_log.ErrorFormat("[ATTACHMENTS MODULE]: Unable to rez attachment with itemID {0}, assetID {1}, point {2} for {3}: {4}\n{5}",
  176. attach.ItemID, attach.AssetID, p, agentId, e.Message, e.StackTrace);
  177. }
  178. }
  179. }
  180. public void DeRezAttachments(IScenePresence sp)
  181. {
  182. if (!Enabled)
  183. return;
  184. // m_log.DebugFormat("[ATTACHMENTS MODULE]: Saving changed attachments for {0}", sp.Name);
  185. lock (sp.AttachmentsSyncLock)
  186. {
  187. foreach (SceneObjectGroup so in sp.GetAttachments())
  188. {
  189. UpdateDetachedObject(sp, so);
  190. }
  191. sp.ClearAttachments();
  192. }
  193. }
  194. public void DeleteAttachmentsFromScene(IScenePresence sp, bool silent)
  195. {
  196. if (!Enabled)
  197. return;
  198. // m_log.DebugFormat(
  199. // "[ATTACHMENTS MODULE]: Deleting attachments from scene {0} for {1}, silent = {2}",
  200. // m_scene.RegionInfo.RegionName, sp.Name, silent);
  201. foreach (SceneObjectGroup sop in sp.GetAttachments())
  202. {
  203. sop.Scene.DeleteSceneObject(sop, silent);
  204. }
  205. sp.ClearAttachments();
  206. }
  207. public bool AttachObject(IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool temp)
  208. {
  209. if (!Enabled)
  210. return false;
  211. if (AttachObjectInternal(sp, group, attachmentPt, silent, temp))
  212. {
  213. m_scene.EventManager.TriggerOnAttach(group.LocalId, group.FromItemID, sp.UUID);
  214. return true;
  215. }
  216. return false;
  217. }
  218. private bool AttachObjectInternal(IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool silent, bool temp)
  219. {
  220. lock (sp.AttachmentsSyncLock)
  221. {
  222. // m_log.DebugFormat(
  223. // "[ATTACHMENTS MODULE]: Attaching object {0} {1} to {2} point {3} from ground (silent = {4})",
  224. // group.Name, group.LocalId, sp.Name, attachmentPt, silent);
  225. if (group.GetSittingAvatarsCount() != 0)
  226. {
  227. // m_log.WarnFormat(
  228. // "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since {4} avatars are still sitting on it",
  229. // group.Name, group.LocalId, sp.Name, attachmentPt, group.GetSittingAvatarsCount());
  230. return false;
  231. }
  232. if (sp.GetAttachments(attachmentPt).Contains(group))
  233. {
  234. // m_log.WarnFormat(
  235. // "[ATTACHMENTS MODULE]: Ignoring request to attach {0} {1} to {2} on {3} since it's already attached",
  236. // group.Name, group.LocalId, sp.Name, AttachmentPt);
  237. return false;
  238. }
  239. Vector3 attachPos = group.AbsolutePosition;
  240. // TODO: this short circuits multiple attachments functionality in LL viewer 2.1+ and should
  241. // be removed when that functionality is implemented in opensim
  242. attachmentPt &= 0x7f;
  243. // If the attachment point isn't the same as the one previously used
  244. // set it's offset position = 0 so that it appears on the attachment point
  245. // and not in a weird location somewhere unknown.
  246. if (attachmentPt != 0 && attachmentPt != group.AttachmentPoint)
  247. {
  248. attachPos = Vector3.Zero;
  249. }
  250. // AttachmentPt 0 means the client chose to 'wear' the attachment.
  251. if (attachmentPt == 0)
  252. {
  253. // Check object for stored attachment point
  254. attachmentPt = group.AttachmentPoint;
  255. }
  256. // if we still didn't find a suitable attachment point.......
  257. if (attachmentPt == 0)
  258. {
  259. // Stick it on left hand with Zero Offset from the attachment point.
  260. attachmentPt = (uint)AttachmentPoint.LeftHand;
  261. attachPos = Vector3.Zero;
  262. }
  263. group.AttachmentPoint = attachmentPt;
  264. group.AbsolutePosition = attachPos;
  265. if (sp.PresenceType != PresenceType.Npc)
  266. UpdateUserInventoryWithAttachment(sp, group, attachmentPt, temp);
  267. AttachToAgent(sp, group, attachmentPt, attachPos, silent);
  268. }
  269. return true;
  270. }
  271. private void UpdateUserInventoryWithAttachment(IScenePresence sp, SceneObjectGroup group, uint attachmentPt, bool temp)
  272. {
  273. // Remove any previous attachments
  274. List<SceneObjectGroup> attachments = sp.GetAttachments(attachmentPt);
  275. // At the moment we can only deal with a single attachment
  276. if (attachments.Count != 0)
  277. {
  278. if (attachments[0].FromItemID != UUID.Zero)
  279. DetachSingleAttachmentToInvInternal(sp, attachments[0]);
  280. // Error logging commented because UUID.Zero now means temp attachment
  281. // else
  282. // m_log.WarnFormat(
  283. // "[ATTACHMENTS MODULE]: When detaching existing attachment {0} {1} at point {2} to make way for {3} {4} for {5}, couldn't find the associated item ID to adjust inventory attachment record!",
  284. // attachments[0].Name, attachments[0].LocalId, attachmentPt, group.Name, group.LocalId, sp.Name);
  285. }
  286. // Add the new attachment to inventory if we don't already have it.
  287. if (!temp)
  288. {
  289. UUID newAttachmentItemID = group.FromItemID;
  290. if (newAttachmentItemID == UUID.Zero)
  291. newAttachmentItemID = AddSceneObjectAsNewAttachmentInInv(sp, group).ID;
  292. ShowAttachInUserInventory(sp, attachmentPt, newAttachmentItemID, group);
  293. }
  294. }
  295. public SceneObjectGroup RezSingleAttachmentFromInventory(IScenePresence sp, UUID itemID, uint AttachmentPt)
  296. {
  297. if (!Enabled)
  298. return null;
  299. // m_log.DebugFormat(
  300. // "[ATTACHMENTS MODULE]: RezSingleAttachmentFromInventory to point {0} from item {1} for {2}",
  301. // (AttachmentPoint)AttachmentPt, itemID, sp.Name);
  302. // TODO: this short circuits multiple attachments functionality in LL viewer 2.1+ and should
  303. // be removed when that functionality is implemented in opensim
  304. AttachmentPt &= 0x7f;
  305. // Viewer 2/3 sometimes asks to re-wear items that are already worn (and show up in it's inventory as such).
  306. // This often happens during login - not sure the exact reason.
  307. // For now, we will ignore the request. Unfortunately, this means that we need to dig through all the
  308. // ScenePresence attachments. We can't use the data in AvatarAppearance because that's present at login
  309. // before anything has actually been attached.
  310. bool alreadyOn = false;
  311. List<SceneObjectGroup> existingAttachments = sp.GetAttachments();
  312. foreach (SceneObjectGroup so in existingAttachments)
  313. {
  314. if (so.FromItemID == itemID)
  315. {
  316. alreadyOn = true;
  317. break;
  318. }
  319. }
  320. // if (sp.Appearance.GetAttachmentForItem(itemID) != null)
  321. if (alreadyOn)
  322. {
  323. // m_log.WarnFormat(
  324. // "[ATTACHMENTS MODULE]: Ignoring request by {0} to wear item {1} at {2} since it is already worn",
  325. // sp.Name, itemID, AttachmentPt);
  326. return null;
  327. }
  328. return RezSingleAttachmentFromInventoryInternal(sp, itemID, UUID.Zero, AttachmentPt);
  329. }
  330. public void RezMultipleAttachmentsFromInventory(IScenePresence sp, List<KeyValuePair<UUID, uint>> rezlist)
  331. {
  332. if (!Enabled)
  333. return;
  334. // m_log.DebugFormat("[ATTACHMENTS MODULE]: Rezzing multiple attachments from inventory for {0}", sp.Name);
  335. lock (sp.AttachmentsSyncLock)
  336. {
  337. foreach (KeyValuePair<UUID, uint> rez in rezlist)
  338. {
  339. RezSingleAttachmentFromInventory(sp, rez.Key, rez.Value);
  340. }
  341. }
  342. }
  343. public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId)
  344. {
  345. DetachSingleAttachmentToGround(sp, soLocalId, sp.AbsolutePosition, Quaternion.Identity);
  346. }
  347. public void DetachSingleAttachmentToGround(IScenePresence sp, uint soLocalId, Vector3 absolutePos, Quaternion absoluteRot)
  348. {
  349. if (!Enabled)
  350. return;
  351. // m_log.DebugFormat(
  352. // "[ATTACHMENTS MODULE]: DetachSingleAttachmentToGround() for {0}, object {1}",
  353. // sp.UUID, soLocalId);
  354. SceneObjectGroup so = m_scene.GetGroupByPrim(soLocalId);
  355. if (so == null)
  356. return;
  357. if (so.AttachedAvatar != sp.UUID)
  358. return;
  359. UUID inventoryID = so.FromItemID;
  360. // As per Linden spec, drop is disabled for temp attachs
  361. if (inventoryID == UUID.Zero)
  362. return;
  363. // m_log.DebugFormat(
  364. // "[ATTACHMENTS MODULE]: In DetachSingleAttachmentToGround(), object is {0} {1}, associated item is {2}",
  365. // so.Name, so.LocalId, inventoryID);
  366. lock (sp.AttachmentsSyncLock)
  367. {
  368. if (!m_scene.Permissions.CanRezObject(
  369. so.PrimCount, sp.UUID, sp.AbsolutePosition))
  370. return;
  371. bool changed = false;
  372. if (inventoryID != UUID.Zero)
  373. changed = sp.Appearance.DetachAttachment(inventoryID);
  374. if (changed && m_scene.AvatarFactory != null)
  375. m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
  376. sp.RemoveAttachment(so);
  377. so.FromItemID = UUID.Zero;
  378. SceneObjectPart rootPart = so.RootPart;
  379. so.AbsolutePosition = absolutePos;
  380. if (absoluteRot != Quaternion.Identity)
  381. {
  382. so.UpdateGroupRotationR(absoluteRot);
  383. }
  384. so.AttachedAvatar = UUID.Zero;
  385. rootPart.SetParentLocalId(0);
  386. so.ClearPartAttachmentData();
  387. rootPart.ApplyPhysics(rootPart.GetEffectiveObjectFlags(), rootPart.VolumeDetectActive);
  388. so.HasGroupChanged = true;
  389. rootPart.Rezzed = DateTime.Now;
  390. rootPart.RemFlag(PrimFlags.TemporaryOnRez);
  391. so.AttachToBackup();
  392. m_scene.EventManager.TriggerParcelPrimCountTainted();
  393. rootPart.ScheduleFullUpdate();
  394. rootPart.ClearUndoState();
  395. List<UUID> uuids = new List<UUID>();
  396. uuids.Add(inventoryID);
  397. m_scene.InventoryService.DeleteItems(sp.UUID, uuids);
  398. sp.ControllingClient.SendRemoveInventoryItem(inventoryID);
  399. }
  400. m_scene.EventManager.TriggerOnAttach(so.LocalId, so.UUID, UUID.Zero);
  401. }
  402. public void DetachSingleAttachmentToInv(IScenePresence sp, SceneObjectGroup so)
  403. {
  404. lock (sp.AttachmentsSyncLock)
  405. {
  406. // Save avatar attachment information
  407. // m_log.Debug("[ATTACHMENTS MODULE]: Detaching from UserID: " + sp.UUID + ", ItemID: " + itemID);
  408. if (so.AttachedAvatar != sp.UUID)
  409. {
  410. m_log.WarnFormat(
  411. "[ATTACHMENTS MODULE]: Tried to detach object {0} from {1} {2} but attached avatar id was {3} in {4}",
  412. so.Name, sp.Name, sp.UUID, so.AttachedAvatar, m_scene.RegionInfo.RegionName);
  413. return;
  414. }
  415. bool changed = sp.Appearance.DetachAttachment(so.FromItemID);
  416. if (changed && m_scene.AvatarFactory != null)
  417. m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
  418. DetachSingleAttachmentToInvInternal(sp, so);
  419. }
  420. }
  421. public void UpdateAttachmentPosition(SceneObjectGroup sog, Vector3 pos)
  422. {
  423. if (!Enabled)
  424. return;
  425. sog.UpdateGroupPosition(pos);
  426. sog.HasGroupChanged = true;
  427. }
  428. #endregion
  429. #region AttachmentModule private methods
  430. // This is public but is not part of the IAttachmentsModule interface.
  431. // RegionCombiner module needs to poke at it to deliver client events.
  432. // This breaks the encapsulation of the module and should get fixed somehow.
  433. public void SubscribeToClientEvents(IClientAPI client)
  434. {
  435. client.OnRezSingleAttachmentFromInv += Client_OnRezSingleAttachmentFromInv;
  436. client.OnRezMultipleAttachmentsFromInv += Client_OnRezMultipleAttachmentsFromInv;
  437. client.OnObjectAttach += Client_OnObjectAttach;
  438. client.OnObjectDetach += Client_OnObjectDetach;
  439. client.OnDetachAttachmentIntoInv += Client_OnDetachAttachmentIntoInv;
  440. client.OnObjectDrop += Client_OnObjectDrop;
  441. }
  442. // This is public but is not part of the IAttachmentsModule interface.
  443. // RegionCombiner module needs to poke at it to deliver client events.
  444. // This breaks the encapsulation of the module and should get fixed somehow.
  445. public void UnsubscribeFromClientEvents(IClientAPI client)
  446. {
  447. client.OnRezSingleAttachmentFromInv -= Client_OnRezSingleAttachmentFromInv;
  448. client.OnRezMultipleAttachmentsFromInv -= Client_OnRezMultipleAttachmentsFromInv;
  449. client.OnObjectAttach -= Client_OnObjectAttach;
  450. client.OnObjectDetach -= Client_OnObjectDetach;
  451. client.OnDetachAttachmentIntoInv -= Client_OnDetachAttachmentIntoInv;
  452. client.OnObjectDrop -= Client_OnObjectDrop;
  453. }
  454. /// <summary>
  455. /// Update the attachment asset for the new sog details if they have changed.
  456. /// </summary>
  457. /// <remarks>
  458. /// This is essential for preserving attachment attributes such as permission. Unlike normal scene objects,
  459. /// these details are not stored on the region.
  460. /// </remarks>
  461. /// <param name="sp"></param>
  462. /// <param name="grp"></param>
  463. /// <param name="saveAllScripted"></param>
  464. private void UpdateKnownItem(IScenePresence sp, SceneObjectGroup grp, string scriptedState)
  465. {
  466. if (grp.FromItemID == UUID.Zero)
  467. {
  468. // We can't save temp attachments
  469. grp.HasGroupChanged = false;
  470. return;
  471. }
  472. // Saving attachments for NPCs messes them up for the real owner!
  473. INPCModule module = m_scene.RequestModuleInterface<INPCModule>();
  474. if (module != null)
  475. {
  476. if (module.IsNPC(sp.UUID, m_scene))
  477. return;
  478. }
  479. if (grp.HasGroupChanged)
  480. {
  481. m_log.DebugFormat(
  482. "[ATTACHMENTS MODULE]: Updating asset for attachment {0}, attachpoint {1}",
  483. grp.UUID, grp.AttachmentPoint);
  484. string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(grp, scriptedState);
  485. InventoryItemBase item = new InventoryItemBase(grp.FromItemID, sp.UUID);
  486. item = m_scene.InventoryService.GetItem(item);
  487. if (item != null)
  488. {
  489. AssetBase asset = m_scene.CreateAsset(
  490. grp.GetPartName(grp.LocalId),
  491. grp.GetPartDescription(grp.LocalId),
  492. (sbyte)AssetType.Object,
  493. Utils.StringToBytes(sceneObjectXml),
  494. sp.UUID);
  495. m_scene.AssetService.Store(asset);
  496. item.AssetID = asset.FullID;
  497. item.Description = asset.Description;
  498. item.Name = asset.Name;
  499. item.AssetType = asset.Type;
  500. item.InvType = (int)InventoryType.Object;
  501. m_scene.InventoryService.UpdateItem(item);
  502. // If the name of the object has been changed whilst attached then we want to update the inventory
  503. // item in the viewer.
  504. if (sp.ControllingClient != null)
  505. sp.ControllingClient.SendInventoryItemCreateUpdate(item, 0);
  506. }
  507. grp.HasGroupChanged = false; // Prevent it being saved over and over
  508. }
  509. // else
  510. // {
  511. // m_log.DebugFormat(
  512. // "[ATTACHMENTS MODULE]: Don't need to update asset for unchanged attachment {0}, attachpoint {1}",
  513. // grp.UUID, grp.AttachmentPoint);
  514. // }
  515. }
  516. /// <summary>
  517. /// Attach this scene object to the given avatar.
  518. /// </summary>
  519. /// <remarks>
  520. /// This isn't publicly available since attachments should always perform the corresponding inventory
  521. /// operation (to show the attach in user inventory and update the asset with positional information).
  522. /// </remarks>
  523. /// <param name="sp"></param>
  524. /// <param name="so"></param>
  525. /// <param name="attachmentpoint"></param>
  526. /// <param name="attachOffset"></param>
  527. /// <param name="silent"></param>
  528. private void AttachToAgent(
  529. IScenePresence sp, SceneObjectGroup so, uint attachmentpoint, Vector3 attachOffset, bool silent)
  530. {
  531. // m_log.DebugFormat(
  532. // "[ATTACHMENTS MODULE]: Adding attachment {0} to avatar {1} in pt {2} pos {3} {4}",
  533. // so.Name, sp.Name, attachmentpoint, attachOffset, so.RootPart.AttachedPos);
  534. so.DetachFromBackup();
  535. // Remove from database and parcel prim count
  536. m_scene.DeleteFromStorage(so.UUID);
  537. m_scene.EventManager.TriggerParcelPrimCountTainted();
  538. so.AttachedAvatar = sp.UUID;
  539. if (so.RootPart.PhysActor != null)
  540. so.RootPart.RemoveFromPhysics();
  541. so.AbsolutePosition = attachOffset;
  542. so.RootPart.AttachedPos = attachOffset;
  543. so.IsAttachment = true;
  544. so.RootPart.SetParentLocalId(sp.LocalId);
  545. so.AttachmentPoint = attachmentpoint;
  546. sp.AddAttachment(so);
  547. if (!silent)
  548. {
  549. // Killing it here will cause the client to deselect it
  550. // It then reappears on the avatar, deselected
  551. // through the full update below
  552. //
  553. if (so.IsSelected)
  554. {
  555. m_scene.SendKillObject(new List<uint> { so.RootPart.LocalId });
  556. }
  557. else if (so.HasPrivateAttachmentPoint)
  558. {
  559. // m_log.DebugFormat(
  560. // "[ATTACHMENTS MODULE]: Killing private HUD {0} for avatars other than {1} at attachment point {2}",
  561. // so.Name, sp.Name, so.AttachmentPoint);
  562. // As this scene object can now only be seen by the attaching avatar, tell everybody else in the
  563. // scene that it's no longer in their awareness.
  564. m_scene.ForEachClient(
  565. client =>
  566. { if (client.AgentId != so.AttachedAvatar)
  567. client.SendKillObject(m_scene.RegionInfo.RegionHandle, new List<uint>() { so.LocalId });
  568. });
  569. }
  570. so.IsSelected = false; // fudge....
  571. so.ScheduleGroupForFullUpdate();
  572. }
  573. // In case it is later dropped again, don't let
  574. // it get cleaned up
  575. so.RootPart.RemFlag(PrimFlags.TemporaryOnRez);
  576. }
  577. /// <summary>
  578. /// Add a scene object as a new attachment in the user inventory.
  579. /// </summary>
  580. /// <param name="remoteClient"></param>
  581. /// <param name="grp"></param>
  582. /// <returns>The user inventory item created that holds the attachment.</returns>
  583. private InventoryItemBase AddSceneObjectAsNewAttachmentInInv(IScenePresence sp, SceneObjectGroup grp)
  584. {
  585. if (m_invAccessModule == null)
  586. return null;
  587. // m_log.DebugFormat(
  588. // "[ATTACHMENTS MODULE]: Called AddSceneObjectAsAttachment for object {0} {1} for {2}",
  589. // grp.Name, grp.LocalId, remoteClient.Name);
  590. InventoryItemBase newItem
  591. = m_invAccessModule.CopyToInventory(
  592. DeRezAction.TakeCopy,
  593. m_scene.InventoryService.GetFolderForType(sp.UUID, AssetType.Object).ID,
  594. new List<SceneObjectGroup> { grp },
  595. sp.ControllingClient, true)[0];
  596. // sets itemID so client can show item as 'attached' in inventory
  597. grp.FromItemID = newItem.ID;
  598. return newItem;
  599. }
  600. private string GetObjectScriptStates(SceneObjectGroup grp)
  601. {
  602. using (StringWriter sw = new StringWriter())
  603. {
  604. using (XmlTextWriter writer = new XmlTextWriter(sw))
  605. {
  606. grp.SaveScriptedState(writer);
  607. }
  608. return sw.ToString();
  609. }
  610. }
  611. private void UpdateDetachedObject(IScenePresence sp, SceneObjectGroup so)
  612. {
  613. // Don't save attachments for HG visitors, it
  614. // messes up their inventory. When a HG visitor logs
  615. // out on a foreign grid, their attachments will be
  616. // reloaded in the state they were in when they left
  617. // the home grid. This is best anyway as the visited
  618. // grid may use an incompatible script engine.
  619. bool saveChanged
  620. = sp.PresenceType != PresenceType.Npc
  621. && (m_scene.UserManagementModule == null
  622. || m_scene.UserManagementModule.IsLocalGridUser(sp.UUID));
  623. // Scripts MUST be snapshotted before the object is
  624. // removed from the scene because doing otherwise will
  625. // clobber the run flag
  626. string scriptedState = GetObjectScriptStates(so);
  627. // Remove the object from the scene so no more updates
  628. // are sent. Doing this before the below changes will ensure
  629. // updates can't cause "HUD artefacts"
  630. m_scene.DeleteSceneObject(so, false, false);
  631. // Prepare sog for storage
  632. so.AttachedAvatar = UUID.Zero;
  633. so.RootPart.SetParentLocalId(0);
  634. so.IsAttachment = false;
  635. if (saveChanged)
  636. {
  637. // We cannot use AbsolutePosition here because that would
  638. // attempt to cross the prim as it is detached
  639. so.ForEachPart(x => { x.GroupPosition = so.RootPart.AttachedPos; });
  640. UpdateKnownItem(sp, so, scriptedState);
  641. }
  642. // Now, remove the scripts
  643. so.RemoveScriptInstances(true);
  644. }
  645. private void DetachSingleAttachmentToInvInternal(IScenePresence sp, SceneObjectGroup so)
  646. {
  647. // m_log.DebugFormat("[ATTACHMENTS MODULE]: Detaching item {0} to inventory for {1}", itemID, sp.Name);
  648. m_scene.EventManager.TriggerOnAttach(so.LocalId, so.FromItemID, UUID.Zero);
  649. sp.RemoveAttachment(so);
  650. UpdateDetachedObject(sp, so);
  651. }
  652. private SceneObjectGroup RezSingleAttachmentFromInventoryInternal(
  653. IScenePresence sp, UUID itemID, UUID assetID, uint attachmentPt)
  654. {
  655. if (m_invAccessModule == null)
  656. return null;
  657. lock (sp.AttachmentsSyncLock)
  658. {
  659. SceneObjectGroup objatt;
  660. if (itemID != UUID.Zero)
  661. objatt = m_invAccessModule.RezObject(sp.ControllingClient,
  662. itemID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true,
  663. false, false, sp.UUID, true);
  664. else
  665. objatt = m_invAccessModule.RezObject(sp.ControllingClient,
  666. null, assetID, Vector3.Zero, Vector3.Zero, UUID.Zero, (byte)1, true,
  667. false, false, sp.UUID, true);
  668. if (objatt != null)
  669. {
  670. // m_log.DebugFormat(
  671. // "[ATTACHMENTS MODULE]: Rezzed single object {0} for attachment to {1} on point {2} in {3}",
  672. // objatt.Name, sp.Name, attachmentPt, m_scene.Name);
  673. // HasGroupChanged is being set from within RezObject. Ideally it would be set by the caller.
  674. objatt.HasGroupChanged = false;
  675. bool tainted = false;
  676. if (attachmentPt != 0 && attachmentPt != objatt.AttachmentPoint)
  677. tainted = true;
  678. // FIXME: Detect whether it's really likely for AttachObject to throw an exception in the normal
  679. // course of events. If not, then it's probably not worth trying to recover the situation
  680. // since this is more likely to trigger further exceptions and confuse later debugging. If
  681. // exceptions can be thrown in expected error conditions (not NREs) then make this consistent
  682. // since other normal error conditions will simply return false instead.
  683. // This will throw if the attachment fails
  684. try
  685. {
  686. AttachObjectInternal(sp, objatt, attachmentPt, false, false);
  687. }
  688. catch (Exception e)
  689. {
  690. m_log.ErrorFormat(
  691. "[ATTACHMENTS MODULE]: Failed to attach {0} {1} for {2}, exception {3}{4}",
  692. objatt.Name, objatt.UUID, sp.Name, e.Message, e.StackTrace);
  693. // Make sure the object doesn't stick around and bail
  694. sp.RemoveAttachment(objatt);
  695. m_scene.DeleteSceneObject(objatt, false);
  696. return null;
  697. }
  698. if (tainted)
  699. objatt.HasGroupChanged = true;
  700. // Fire after attach, so we don't get messy perms dialogs
  701. // 4 == AttachedRez
  702. objatt.CreateScriptInstances(0, true, m_scene.DefaultScriptEngine, 4);
  703. objatt.ResumeScripts();
  704. // Do this last so that event listeners have access to all the effects of the attachment
  705. m_scene.EventManager.TriggerOnAttach(objatt.LocalId, itemID, sp.UUID);
  706. return objatt;
  707. }
  708. else
  709. {
  710. m_log.WarnFormat(
  711. "[ATTACHMENTS MODULE]: Could not retrieve item {0} for attaching to avatar {1} at point {2}",
  712. itemID, sp.Name, attachmentPt);
  713. }
  714. }
  715. return null;
  716. }
  717. /// <summary>
  718. /// Update the user inventory to reflect an attachment
  719. /// </summary>
  720. /// <param name="sp"></param>
  721. /// <param name="AttachmentPt"></param>
  722. /// <param name="itemID"></param>
  723. /// <param name="att"></param>
  724. private void ShowAttachInUserInventory(IScenePresence sp, uint AttachmentPt, UUID itemID, SceneObjectGroup att)
  725. {
  726. // m_log.DebugFormat(
  727. // "[USER INVENTORY]: Updating attachment {0} for {1} at {2} using item ID {3}",
  728. // att.Name, sp.Name, AttachmentPt, itemID);
  729. if (UUID.Zero == itemID)
  730. {
  731. m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error inventory item ID.");
  732. return;
  733. }
  734. if (0 == AttachmentPt)
  735. {
  736. m_log.Error("[ATTACHMENTS MODULE]: Unable to save attachment. Error attachment point.");
  737. return;
  738. }
  739. InventoryItemBase item = new InventoryItemBase(itemID, sp.UUID);
  740. item = m_scene.InventoryService.GetItem(item);
  741. if (item == null)
  742. return;
  743. bool changed = sp.Appearance.SetAttachment((int)AttachmentPt, itemID, item.AssetID);
  744. if (changed && m_scene.AvatarFactory != null)
  745. {
  746. // m_log.DebugFormat(
  747. // "[ATTACHMENTS MODULE]: Queueing appearance save for {0}, attachment {1} point {2} in ShowAttachInUserInventory()",
  748. // sp.Name, att.Name, AttachmentPt);
  749. m_scene.AvatarFactory.QueueAppearanceSave(sp.UUID);
  750. }
  751. }
  752. #endregion
  753. #region Client Event Handlers
  754. private ISceneEntity Client_OnRezSingleAttachmentFromInv(IClientAPI remoteClient, UUID itemID, uint AttachmentPt)
  755. {
  756. if (!Enabled)
  757. return null;
  758. // m_log.DebugFormat(
  759. // "[ATTACHMENTS MODULE]: Rezzing attachment to point {0} from item {1} for {2}",
  760. // (AttachmentPoint)AttachmentPt, itemID, remoteClient.Name);
  761. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  762. if (sp == null)
  763. {
  764. m_log.ErrorFormat(
  765. "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1} in RezSingleAttachmentFromInventory()",
  766. remoteClient.Name, remoteClient.AgentId);
  767. return null;
  768. }
  769. return RezSingleAttachmentFromInventory(sp, itemID, AttachmentPt);
  770. }
  771. private void Client_OnRezMultipleAttachmentsFromInv(IClientAPI remoteClient, List<KeyValuePair<UUID, uint>> rezlist)
  772. {
  773. if (!Enabled)
  774. return;
  775. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  776. if (sp != null)
  777. RezMultipleAttachmentsFromInventory(sp, rezlist);
  778. else
  779. m_log.ErrorFormat(
  780. "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1} in RezMultipleAttachmentsFromInventory()",
  781. remoteClient.Name, remoteClient.AgentId);
  782. }
  783. private void Client_OnObjectAttach(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt, bool silent)
  784. {
  785. // m_log.DebugFormat(
  786. // "[ATTACHMENTS MODULE]: Attaching object local id {0} to {1} point {2} from ground (silent = {3})",
  787. // objectLocalID, remoteClient.Name, AttachmentPt, silent);
  788. if (!Enabled)
  789. return;
  790. try
  791. {
  792. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  793. if (sp == null)
  794. {
  795. m_log.ErrorFormat(
  796. "[ATTACHMENTS MODULE]: Could not find presence for client {0} {1}", remoteClient.Name, remoteClient.AgentId);
  797. return;
  798. }
  799. // If we can't take it, we can't attach it!
  800. SceneObjectPart part = m_scene.GetSceneObjectPart(objectLocalID);
  801. if (part == null)
  802. return;
  803. if (!m_scene.Permissions.CanTakeObject(part.UUID, remoteClient.AgentId))
  804. {
  805. remoteClient.SendAgentAlertMessage(
  806. "You don't have sufficient permissions to attach this object", false);
  807. return;
  808. }
  809. // TODO: this short circuits multiple attachments functionality in LL viewer 2.1+ and should
  810. // be removed when that functionality is implemented in opensim
  811. AttachmentPt &= 0x7f;
  812. // Calls attach with a Zero position
  813. AttachObject(sp, part.ParentGroup, AttachmentPt, false, false);
  814. }
  815. catch (Exception e)
  816. {
  817. m_log.ErrorFormat("[ATTACHMENTS MODULE]: exception upon Attach Object {0}{1}", e.Message, e.StackTrace);
  818. }
  819. }
  820. private void Client_OnObjectDetach(uint objectLocalID, IClientAPI remoteClient)
  821. {
  822. if (!Enabled)
  823. return;
  824. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  825. SceneObjectGroup group = m_scene.GetGroupByPrim(objectLocalID);
  826. if (sp != null && group != null && group.FromItemID != UUID.Zero)
  827. DetachSingleAttachmentToInv(sp, group);
  828. }
  829. private void Client_OnDetachAttachmentIntoInv(UUID itemID, IClientAPI remoteClient)
  830. {
  831. if (!Enabled)
  832. return;
  833. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  834. if (sp != null)
  835. {
  836. lock (sp.AttachmentsSyncLock)
  837. {
  838. List<SceneObjectGroup> attachments = sp.GetAttachments();
  839. foreach (SceneObjectGroup group in attachments)
  840. {
  841. if (group.FromItemID == itemID && group.FromItemID != UUID.Zero)
  842. {
  843. DetachSingleAttachmentToInv(sp, group);
  844. return;
  845. }
  846. }
  847. }
  848. }
  849. }
  850. private void Client_OnObjectDrop(uint soLocalId, IClientAPI remoteClient)
  851. {
  852. if (!Enabled)
  853. return;
  854. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  855. if (sp != null)
  856. DetachSingleAttachmentToGround(sp, soLocalId);
  857. }
  858. #endregion
  859. }
  860. }