AttachmentsModule.cs 52 KB

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