AttachmentsModule.cs 56 KB

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