AvatarFactoryModule.cs 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375
  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.Threading;
  31. using System.Text;
  32. using System.Timers;
  33. using log4net;
  34. using Nini.Config;
  35. using OpenMetaverse;
  36. using OpenSim.Framework;
  37. using OpenSim.Region.Framework.Interfaces;
  38. using OpenSim.Region.Framework.Scenes;
  39. using OpenSim.Services.Interfaces;
  40. using Mono.Addins;
  41. using PermissionMask = OpenSim.Framework.PermissionMask;
  42. namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
  43. {
  44. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AvatarFactoryModule")]
  45. public class AvatarFactoryModule : IAvatarFactoryModule, INonSharedRegionModule
  46. {
  47. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  48. public const string BAKED_TEXTURES_REPORT_FORMAT = "{0,-9} {1}";
  49. private Scene m_scene = null;
  50. private int m_savetime = 5; // seconds to wait before saving changed appearance
  51. private int m_sendtime = 2; // seconds to wait before sending changed appearance
  52. private bool m_reusetextures = false;
  53. private int m_checkTime = 500; // milliseconds to wait between checks for appearance updates
  54. private System.Timers.Timer m_updateTimer = new System.Timers.Timer();
  55. private Dictionary<UUID,long> m_savequeue = new Dictionary<UUID,long>();
  56. private Dictionary<UUID,long> m_sendqueue = new Dictionary<UUID,long>();
  57. private object m_setAppearanceLock = new object();
  58. #region Region Module interface
  59. public void Initialise(IConfigSource config)
  60. {
  61. IConfig appearanceConfig = config.Configs["Appearance"];
  62. if (appearanceConfig != null)
  63. {
  64. m_savetime = Convert.ToInt32(appearanceConfig.GetString("DelayBeforeAppearanceSave",Convert.ToString(m_savetime)));
  65. m_sendtime = Convert.ToInt32(appearanceConfig.GetString("DelayBeforeAppearanceSend",Convert.ToString(m_sendtime)));
  66. m_reusetextures = appearanceConfig.GetBoolean("ReuseTextures",m_reusetextures);
  67. // m_log.InfoFormat("[AVFACTORY] configured for {0} save and {1} send",m_savetime,m_sendtime);
  68. }
  69. }
  70. public void AddRegion(Scene scene)
  71. {
  72. if (m_scene == null)
  73. m_scene = scene;
  74. scene.RegisterModuleInterface<IAvatarFactoryModule>(this);
  75. scene.EventManager.OnNewClient += SubscribeToClientEvents;
  76. }
  77. public void RemoveRegion(Scene scene)
  78. {
  79. if (scene == m_scene)
  80. {
  81. scene.UnregisterModuleInterface<IAvatarFactoryModule>(this);
  82. scene.EventManager.OnNewClient -= SubscribeToClientEvents;
  83. }
  84. m_scene = null;
  85. }
  86. public void RegionLoaded(Scene scene)
  87. {
  88. m_updateTimer.Enabled = false;
  89. m_updateTimer.AutoReset = true;
  90. m_updateTimer.Interval = m_checkTime; // 500 milliseconds wait to start async ops
  91. m_updateTimer.Elapsed += new ElapsedEventHandler(HandleAppearanceUpdateTimer);
  92. }
  93. public void Close()
  94. {
  95. }
  96. public string Name
  97. {
  98. get { return "Default Avatar Factory"; }
  99. }
  100. public bool IsSharedModule
  101. {
  102. get { return false; }
  103. }
  104. public Type ReplaceableInterface
  105. {
  106. get { return null; }
  107. }
  108. private void SubscribeToClientEvents(IClientAPI client)
  109. {
  110. client.OnRequestWearables += Client_OnRequestWearables;
  111. client.OnSetAppearance += Client_OnSetAppearance;
  112. client.OnAvatarNowWearing += Client_OnAvatarNowWearing;
  113. client.OnCachedTextureRequest += Client_OnCachedTextureRequest;
  114. }
  115. #endregion
  116. #region IAvatarFactoryModule
  117. /// </summary>
  118. /// <param name="sp"></param>
  119. /// <param name="texture"></param>
  120. /// <param name="visualParam"></param>
  121. public void SetAppearance(IScenePresence sp, AvatarAppearance appearance, WearableCacheItem[] cacheItems)
  122. {
  123. SetAppearance(sp, appearance.Texture, appearance.VisualParams, cacheItems);
  124. }
  125. public void SetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams, Vector3 avSize, WearableCacheItem[] cacheItems)
  126. {
  127. float oldoff = sp.Appearance.AvatarFeetOffset;
  128. Vector3 oldbox = sp.Appearance.AvatarBoxSize;
  129. SetAppearance(sp, textureEntry, visualParams, cacheItems);
  130. sp.Appearance.SetSize(avSize);
  131. float off = sp.Appearance.AvatarFeetOffset;
  132. Vector3 box = sp.Appearance.AvatarBoxSize;
  133. if (oldoff != off || oldbox != box)
  134. ((ScenePresence)sp).SetSize(box, off);
  135. }
  136. /// <summary>
  137. /// Set appearance data (texture asset IDs and slider settings)
  138. /// </summary>
  139. /// <param name="sp"></param>
  140. /// <param name="texture"></param>
  141. /// <param name="visualParam"></param>
  142. public void SetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams, WearableCacheItem[] cacheItems)
  143. {
  144. // m_log.DebugFormat(
  145. // "[AVFACTORY]: start SetAppearance for {0}, te {1}, visualParams {2}",
  146. // sp.Name, textureEntry, visualParams);
  147. // TODO: This is probably not necessary any longer, just assume the
  148. // textureEntry set implies that the appearance transaction is complete
  149. bool changed = false;
  150. // Process the texture entry transactionally, this doesn't guarantee that Appearance is
  151. // going to be handled correctly but it does serialize the updates to the appearance
  152. lock (m_setAppearanceLock)
  153. {
  154. // Process the visual params, this may change height as well
  155. if (visualParams != null)
  156. {
  157. changed = sp.Appearance.SetVisualParams(visualParams);
  158. }
  159. // Process the baked texture array
  160. if (textureEntry != null)
  161. {
  162. m_log.DebugFormat("[AVFACTORY]: Received texture update for {0} {1}", sp.Name, sp.UUID);
  163. // WriteBakedTexturesReport(sp, m_log.DebugFormat);
  164. changed = sp.Appearance.SetTextureEntries(textureEntry) || changed;
  165. // WriteBakedTexturesReport(sp, m_log.DebugFormat);
  166. UpdateBakedTextureCache(sp, cacheItems);
  167. // This appears to be set only in the final stage of the appearance
  168. // update transaction. In theory, we should be able to do an immediate
  169. // appearance send and save here.
  170. }
  171. // NPC should send to clients immediately and skip saving appearance
  172. if (((ScenePresence)sp).PresenceType == PresenceType.Npc)
  173. {
  174. SendAppearance((ScenePresence)sp);
  175. return;
  176. }
  177. // save only if there were changes, send no matter what (doesn't hurt to send twice)
  178. if (changed)
  179. QueueAppearanceSave(sp.ControllingClient.AgentId);
  180. QueueAppearanceSend(sp.ControllingClient.AgentId);
  181. }
  182. // m_log.WarnFormat("[AVFACTORY]: complete SetAppearance for {0}:\n{1}",client.AgentId,sp.Appearance.ToString());
  183. }
  184. private void SendAppearance(ScenePresence sp)
  185. {
  186. // Send the appearance to everyone in the scene
  187. sp.SendAppearanceToAllOtherAgents();
  188. // Send animations back to the avatar as well
  189. sp.Animator.SendAnimPack();
  190. }
  191. public bool SendAppearance(UUID agentId)
  192. {
  193. // m_log.DebugFormat("[AVFACTORY]: Sending appearance for {0}", agentId);
  194. ScenePresence sp = m_scene.GetScenePresence(agentId);
  195. if (sp == null)
  196. {
  197. // This is expected if the user has gone away.
  198. // m_log.DebugFormat("[AVFACTORY]: Agent {0} no longer in the scene", agentId);
  199. return false;
  200. }
  201. SendAppearance(sp);
  202. return true;
  203. }
  204. public Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(UUID agentId)
  205. {
  206. ScenePresence sp = m_scene.GetScenePresence(agentId);
  207. if (sp == null)
  208. return new Dictionary<BakeType, Primitive.TextureEntryFace>();
  209. return GetBakedTextureFaces(sp);
  210. }
  211. public WearableCacheItem[] GetCachedItems(UUID agentId)
  212. {
  213. ScenePresence sp = m_scene.GetScenePresence(agentId);
  214. WearableCacheItem[] items = sp.Appearance.WearableCacheItems;
  215. //foreach (WearableCacheItem item in items)
  216. //{
  217. //}
  218. return items;
  219. }
  220. public bool SaveBakedTextures(UUID agentId)
  221. {
  222. ScenePresence sp = m_scene.GetScenePresence(agentId);
  223. if (sp == null)
  224. return false;
  225. m_log.DebugFormat(
  226. "[AV FACTORY]: Permanently saving baked textures for {0} in {1}",
  227. sp.Name, m_scene.RegionInfo.RegionName);
  228. Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = GetBakedTextureFaces(sp);
  229. if (bakedTextures.Count == 0)
  230. return false;
  231. IAssetCache cache = sp.Scene.RequestModuleInterface<IAssetCache>();
  232. if(cache == null)
  233. return true; // no baked local caching so nothing to do
  234. foreach (BakeType bakeType in bakedTextures.Keys)
  235. {
  236. Primitive.TextureEntryFace bakedTextureFace = bakedTextures[bakeType];
  237. if (bakedTextureFace == null)
  238. continue;
  239. AssetBase asset;
  240. cache.Get(bakedTextureFace.TextureID.ToString(), out asset);
  241. if (asset != null && asset.Local)
  242. {
  243. // cache does not update asset contents
  244. cache.Expire(bakedTextureFace.TextureID.ToString());
  245. // Replace an HG ID with the simple asset ID so that we can persist textures for foreign HG avatars
  246. asset.ID = asset.FullID.ToString();
  247. asset.Temporary = false;
  248. asset.Local = false;
  249. m_scene.AssetService.Store(asset);
  250. }
  251. if (asset == null)
  252. {
  253. m_log.WarnFormat(
  254. "[AV FACTORY]: Baked texture id {0} not found for bake {1} for avatar {2} in {3} when trying to save permanently",
  255. bakedTextureFace.TextureID, bakeType, sp.Name, m_scene.RegionInfo.RegionName);
  256. }
  257. }
  258. return true;
  259. }
  260. /// <summary>
  261. /// Queue up a request to send appearance.
  262. /// </summary>
  263. /// <remarks>
  264. /// Makes it possible to accumulate changes without sending out each one separately.
  265. /// </remarks>
  266. /// <param name="agentId"></param>
  267. public void QueueAppearanceSend(UUID agentid)
  268. {
  269. // m_log.DebugFormat("[AVFACTORY]: Queue appearance send for {0}", agentid);
  270. // 10000 ticks per millisecond, 1000 milliseconds per second
  271. long timestamp = DateTime.Now.Ticks + Convert.ToInt64(m_sendtime * 1000 * 10000);
  272. lock (m_sendqueue)
  273. {
  274. m_sendqueue[agentid] = timestamp;
  275. m_updateTimer.Start();
  276. }
  277. }
  278. public void QueueAppearanceSave(UUID agentid)
  279. {
  280. // m_log.DebugFormat("[AVFACTORY]: Queueing appearance save for {0}", agentid);
  281. // 10000 ticks per millisecond, 1000 milliseconds per second
  282. long timestamp = DateTime.Now.Ticks + Convert.ToInt64(m_savetime * 1000 * 10000);
  283. lock (m_savequeue)
  284. {
  285. m_savequeue[agentid] = timestamp;
  286. m_updateTimer.Start();
  287. }
  288. }
  289. // called on textures update
  290. public bool UpdateBakedTextureCache(IScenePresence sp, WearableCacheItem[] cacheItems)
  291. {
  292. if(cacheItems == null)
  293. return false;
  294. // npcs dont have baked cache
  295. if (((ScenePresence)sp).IsNPC)
  296. return true;
  297. // uploaded baked textures will be in assets local cache
  298. IAssetService cache = m_scene.AssetService;
  299. IBakedTextureModule m_BakedTextureModule = m_scene.RequestModuleInterface<IBakedTextureModule>();
  300. int validDirtyBakes = 0;
  301. int hits = 0;
  302. // our main cacheIDs mapper is p.Appearance.WearableCacheItems
  303. WearableCacheItem[] wearableCache = sp.Appearance.WearableCacheItems;
  304. if (wearableCache == null)
  305. {
  306. wearableCache = WearableCacheItem.GetDefaultCacheItem();
  307. }
  308. List<UUID> missing = new List<UUID>();
  309. bool haveSkirt = (wearableCache[19].TextureAsset != null);
  310. bool haveNewSkirt = false;
  311. // Process received baked textures
  312. for (int i = 0; i < cacheItems.Length; i++)
  313. {
  314. int idx = (int)cacheItems[i].TextureIndex;
  315. Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx];
  316. // No face
  317. if (face == null)
  318. {
  319. // for some reason viewer is cleaning this
  320. if(idx != 19) // skirt is optional
  321. {
  322. sp.Appearance.Texture.FaceTextures[idx] = sp.Appearance.Texture.CreateFace((uint) idx);
  323. sp.Appearance.Texture.FaceTextures[idx].TextureID = AppearanceManager.DEFAULT_AVATAR_TEXTURE;
  324. }
  325. wearableCache[idx].CacheId = UUID.Zero;
  326. wearableCache[idx].TextureID = UUID.Zero;
  327. wearableCache[idx].TextureAsset = null;
  328. continue;
  329. }
  330. else
  331. {
  332. if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE)
  333. {
  334. wearableCache[idx].CacheId = UUID.Zero;
  335. wearableCache[idx].TextureID = UUID.Zero;
  336. wearableCache[idx].TextureAsset = null;
  337. continue;
  338. }
  339. if(idx == 19)
  340. haveNewSkirt = true;
  341. /*
  342. if (face.TextureID == wearableCache[idx].TextureID && m_BakedTextureModule != null)
  343. {
  344. if (wearableCache[idx].CacheId != cacheItems[i].CacheId)
  345. {
  346. wearableCache[idx].CacheId = cacheItems[i].CacheId;
  347. validDirtyBakes++;
  348. //assuming this can only happen if asset is in cache
  349. }
  350. hits++;
  351. continue;
  352. }
  353. */
  354. wearableCache[idx].TextureAsset = null;
  355. if (cache != null)
  356. wearableCache[idx].TextureAsset = cache.GetCached(face.TextureID.ToString());
  357. if (wearableCache[idx].TextureAsset != null)
  358. {
  359. if ( wearableCache[idx].TextureID != face.TextureID ||
  360. wearableCache[idx].CacheId != cacheItems[i].CacheId)
  361. validDirtyBakes++;
  362. wearableCache[idx].TextureID = face.TextureID;
  363. wearableCache[idx].CacheId = cacheItems[i].CacheId;
  364. hits++;
  365. }
  366. else
  367. {
  368. wearableCache[idx].CacheId = UUID.Zero;
  369. wearableCache[idx].TextureID = UUID.Zero;
  370. wearableCache[idx].TextureAsset = null;
  371. missing.Add(face.TextureID);
  372. continue;
  373. }
  374. }
  375. }
  376. // handle optional skirt case
  377. if(!haveNewSkirt && haveSkirt)
  378. {
  379. wearableCache[19].CacheId = UUID.Zero;
  380. wearableCache[19].TextureID = UUID.Zero;
  381. wearableCache[19].TextureAsset = null;
  382. validDirtyBakes++;
  383. }
  384. sp.Appearance.WearableCacheItems = wearableCache;
  385. if (missing.Count > 0)
  386. {
  387. foreach (UUID id in missing)
  388. sp.ControllingClient.SendRebakeAvatarTextures(id);
  389. }
  390. if (validDirtyBakes > 0 && hits == cacheItems.Length)
  391. {
  392. // if we got a full set of baked textures save all in BakedTextureModule
  393. if (m_BakedTextureModule != null)
  394. {
  395. m_log.Debug("[UpdateBakedCache] start async uploading to bakedModule cache");
  396. m_BakedTextureModule.Store(sp.UUID, wearableCache);
  397. }
  398. }
  399. // debug
  400. m_log.Debug("[UpdateBakedCache] cache hits: " + hits.ToString() + " changed entries: " + validDirtyBakes.ToString() + " rebakes " + missing.Count);
  401. /*
  402. for (int iter = 0; iter < AvatarAppearance.BAKE_INDICES.Length; iter++)
  403. {
  404. int j = AvatarAppearance.BAKE_INDICES[iter];
  405. m_log.Debug("[UpdateBCache] {" + iter + "/" +
  406. sp.Appearance.WearableCacheItems[j].TextureIndex + "}: c-" +
  407. sp.Appearance.WearableCacheItems[j].CacheId + ", t-" +
  408. sp.Appearance.WearableCacheItems[j].TextureID);
  409. }
  410. */
  411. return (hits == cacheItems.Length);
  412. }
  413. // called when we get a new root avatar
  414. public bool ValidateBakedTextureCache(IScenePresence sp)
  415. {
  416. int hits = 0;
  417. if (((ScenePresence)sp).IsNPC)
  418. return true;
  419. lock (m_setAppearanceLock)
  420. {
  421. IAssetService cache = m_scene.AssetService;
  422. IBakedTextureModule bakedModule = m_scene.RequestModuleInterface<IBakedTextureModule>();
  423. WearableCacheItem[] bakedModuleCache = null;
  424. if (cache == null)
  425. return false;
  426. WearableCacheItem[] wearableCache = sp.Appearance.WearableCacheItems;
  427. // big debug
  428. m_log.DebugFormat("[AVFACTORY]: ValidateBakedTextureCache start for {0} {1}", sp.Name, sp.UUID);
  429. /*
  430. for (int iter = 0; iter < AvatarAppearance.BAKE_INDICES.Length; iter++)
  431. {
  432. int j = AvatarAppearance.BAKE_INDICES[iter];
  433. Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[j];
  434. if (wearableCache == null)
  435. {
  436. if (face != null)
  437. m_log.Debug("[ValidateBakedCache] {" + iter + "/" + j + " t- " + face.TextureID);
  438. else
  439. m_log.Debug("[ValidateBakedCache] {" + iter + "/" + j + " t- No texture");
  440. }
  441. else
  442. {
  443. if (face != null)
  444. m_log.Debug("[ValidateBakedCache] {" + iter + "/" + j + " ft- " + face.TextureID +
  445. "}: cc-" +
  446. wearableCache[j].CacheId + ", ct-" +
  447. wearableCache[j].TextureID
  448. );
  449. else
  450. m_log.Debug("[ValidateBakedCache] {" + iter + "/" + j + " t - No texture" +
  451. "}: cc-" +
  452. wearableCache[j].CacheId + ", ct-" +
  453. wearableCache[j].TextureID
  454. );
  455. }
  456. }
  457. */
  458. bool wearableCacheValid = false;
  459. if (wearableCache == null)
  460. {
  461. wearableCache = WearableCacheItem.GetDefaultCacheItem();
  462. }
  463. else
  464. {
  465. // we may have received a full cache
  466. // check same coerence and store
  467. wearableCacheValid = true;
  468. for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++)
  469. {
  470. int idx = AvatarAppearance.BAKE_INDICES[i];
  471. Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx];
  472. if (face != null)
  473. {
  474. if (face.TextureID == wearableCache[idx].TextureID &&
  475. face.TextureID != UUID.Zero)
  476. {
  477. if (wearableCache[idx].TextureAsset != null)
  478. {
  479. hits++;
  480. wearableCache[idx].TextureAsset.Temporary = true;
  481. wearableCache[idx].TextureAsset.Local = true;
  482. cache.Store(wearableCache[idx].TextureAsset);
  483. continue;
  484. }
  485. if (cache.GetCached((wearableCache[idx].TextureID).ToString()) != null)
  486. {
  487. hits++;
  488. continue;
  489. }
  490. }
  491. wearableCacheValid = false;
  492. }
  493. }
  494. wearableCacheValid = (wearableCacheValid && (hits >= AvatarAppearance.BAKE_INDICES.Length - 1));
  495. if (wearableCacheValid)
  496. m_log.Debug("[ValidateBakedCache] have valid local cache");
  497. else
  498. wearableCache[19].TextureAsset = null; // clear optional skirt
  499. }
  500. bool checkExternal = false;
  501. if (!wearableCacheValid)
  502. {
  503. hits = 0;
  504. // only use external bake module on login condition check
  505. // ScenePresence ssp = null;
  506. // if (sp is ScenePresence)
  507. {
  508. // ssp = (ScenePresence)sp;
  509. // checkExternal = (((uint)ssp.TeleportFlags & (uint)TeleportFlags.ViaLogin) != 0) &&
  510. // bakedModule != null;
  511. // or do it anytime we dont have the cache
  512. checkExternal = bakedModule != null;
  513. }
  514. }
  515. if (checkExternal)
  516. {
  517. bool gotbacked = false;
  518. m_log.Debug("[ValidateBakedCache] local cache invalid, checking bakedModule");
  519. try
  520. {
  521. bakedModuleCache = bakedModule.Get(sp.UUID);
  522. }
  523. catch (Exception e)
  524. {
  525. m_log.ErrorFormat(e.ToString());
  526. bakedModuleCache = null;
  527. }
  528. if (bakedModuleCache != null)
  529. {
  530. m_log.Debug("[ValidateBakedCache] got bakedModule " + bakedModuleCache.Length + " cached textures");
  531. for (int i = 0; i < bakedModuleCache.Length; i++)
  532. {
  533. int j = (int)bakedModuleCache[i].TextureIndex;
  534. if (bakedModuleCache[i].TextureAsset != null)
  535. {
  536. wearableCache[j].TextureID = bakedModuleCache[i].TextureID;
  537. wearableCache[j].CacheId = bakedModuleCache[i].CacheId;
  538. wearableCache[j].TextureAsset = bakedModuleCache[i].TextureAsset;
  539. bakedModuleCache[i].TextureAsset.Temporary = true;
  540. bakedModuleCache[i].TextureAsset.Local = true;
  541. cache.Store(bakedModuleCache[i].TextureAsset);
  542. }
  543. }
  544. gotbacked = true;
  545. }
  546. if (gotbacked)
  547. {
  548. // force the ones we got
  549. for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++)
  550. {
  551. int idx = AvatarAppearance.BAKE_INDICES[i];
  552. if(wearableCache[idx].TextureAsset == null)
  553. {
  554. if(idx == 19)
  555. {
  556. sp.Appearance.Texture.FaceTextures[idx] = null;
  557. hits++;
  558. }
  559. continue;
  560. }
  561. Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx];
  562. if (face == null)
  563. {
  564. face = sp.Appearance.Texture.CreateFace((uint)idx);
  565. sp.Appearance.Texture.FaceTextures[idx] = face;
  566. }
  567. face.TextureID = wearableCache[idx].TextureID;
  568. hits++;
  569. }
  570. }
  571. }
  572. sp.Appearance.WearableCacheItems = wearableCache;
  573. }
  574. // debug
  575. m_log.DebugFormat("[ValidateBakedCache]: Completed texture check for {0} {1} with {2} hits", sp.Name, sp.UUID, hits);
  576. /*
  577. for (int iter = 0; iter < AvatarAppearance.BAKE_INDICES.Length; iter++)
  578. {
  579. int j = AvatarAppearance.BAKE_INDICES[iter];
  580. m_log.Debug("[ValidateBakedCache] {" + iter + "/" +
  581. sp.Appearance.WearableCacheItems[j].TextureIndex + "}: c-" +
  582. sp.Appearance.WearableCacheItems[j].CacheId + ", t-" +
  583. sp.Appearance.WearableCacheItems[j].TextureID);
  584. }
  585. */
  586. return (hits >= AvatarAppearance.BAKE_INDICES.Length - 1); // skirt is optional
  587. }
  588. public int RequestRebake(IScenePresence sp, bool missingTexturesOnly)
  589. {
  590. if (((ScenePresence)sp).IsNPC)
  591. return 0;
  592. int texturesRebaked = 0;
  593. // IAssetCache cache = m_scene.RequestModuleInterface<IAssetCache>();
  594. for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++)
  595. {
  596. int idx = AvatarAppearance.BAKE_INDICES[i];
  597. Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx];
  598. // if there is no texture entry, skip it
  599. if (face == null)
  600. continue;
  601. if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE)
  602. continue;
  603. if (missingTexturesOnly)
  604. {
  605. if (m_scene.AssetService.Get(face.TextureID.ToString()) != null)
  606. {
  607. continue;
  608. }
  609. else
  610. {
  611. // On inter-simulator teleports, this occurs if baked textures are not being stored by the
  612. // grid asset service (which means that they are not available to the new region and so have
  613. // to be re-requested from the client).
  614. //
  615. // The only available core OpenSimulator behaviour right now
  616. // is not to store these textures, temporarily or otherwise.
  617. m_log.DebugFormat(
  618. "[AVFACTORY]: Missing baked texture {0} ({1}) for {2}, requesting rebake.",
  619. face.TextureID, idx, sp.Name);
  620. }
  621. }
  622. else
  623. {
  624. m_log.DebugFormat(
  625. "[AVFACTORY]: Requesting rebake of {0} ({1}) for {2}.",
  626. face.TextureID, idx, sp.Name);
  627. }
  628. texturesRebaked++;
  629. sp.ControllingClient.SendRebakeAvatarTextures(face.TextureID);
  630. }
  631. return texturesRebaked;
  632. }
  633. #endregion
  634. #region AvatarFactoryModule private methods
  635. private Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(ScenePresence sp)
  636. {
  637. if (sp.IsChildAgent)
  638. return new Dictionary<BakeType, Primitive.TextureEntryFace>();
  639. Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures
  640. = new Dictionary<BakeType, Primitive.TextureEntryFace>();
  641. AvatarAppearance appearance = sp.Appearance;
  642. Primitive.TextureEntryFace[] faceTextures = appearance.Texture.FaceTextures;
  643. foreach (int i in Enum.GetValues(typeof(BakeType)))
  644. {
  645. BakeType bakeType = (BakeType)i;
  646. if (bakeType == BakeType.Unknown)
  647. continue;
  648. // m_log.DebugFormat(
  649. // "[AVFACTORY]: NPC avatar {0} has texture id {1} : {2}",
  650. // acd.AgentID, i, acd.Appearance.Texture.FaceTextures[i]);
  651. int ftIndex = (int)AppearanceManager.BakeTypeToAgentTextureIndex(bakeType);
  652. Primitive.TextureEntryFace texture = faceTextures[ftIndex]; // this will be null if there's no such baked texture
  653. bakedTextures[bakeType] = texture;
  654. }
  655. return bakedTextures;
  656. }
  657. private void HandleAppearanceUpdateTimer(object sender, EventArgs ea)
  658. {
  659. long now = DateTime.Now.Ticks;
  660. lock (m_sendqueue)
  661. {
  662. Dictionary<UUID, long> sends = new Dictionary<UUID, long>(m_sendqueue);
  663. foreach (KeyValuePair<UUID, long> kvp in sends)
  664. {
  665. // We have to load the key and value into local parameters to avoid a race condition if we loop
  666. // around and load kvp with a different value before FireAndForget has launched its thread.
  667. UUID avatarID = kvp.Key;
  668. long sendTime = kvp.Value;
  669. // m_log.DebugFormat("[AVFACTORY]: Handling queued appearance updates for {0}, update delta to now is {1}", avatarID, sendTime - now);
  670. if (sendTime < now)
  671. {
  672. Util.FireAndForget(o => SendAppearance(avatarID), null, "AvatarFactoryModule.SendAppearance");
  673. m_sendqueue.Remove(avatarID);
  674. }
  675. }
  676. }
  677. lock (m_savequeue)
  678. {
  679. Dictionary<UUID, long> saves = new Dictionary<UUID, long>(m_savequeue);
  680. foreach (KeyValuePair<UUID, long> kvp in saves)
  681. {
  682. // We have to load the key and value into local parameters to avoid a race condition if we loop
  683. // around and load kvp with a different value before FireAndForget has launched its thread.
  684. UUID avatarID = kvp.Key;
  685. long sendTime = kvp.Value;
  686. if (sendTime < now)
  687. {
  688. Util.FireAndForget(o => SaveAppearance(avatarID), null, "AvatarFactoryModule.SaveAppearance");
  689. m_savequeue.Remove(avatarID);
  690. }
  691. }
  692. // We must lock both queues here so that QueueAppearanceSave() or *Send() don't m_updateTimer.Start() on
  693. // another thread inbetween the first count calls and m_updateTimer.Stop() on this thread.
  694. lock (m_sendqueue)
  695. if (m_savequeue.Count == 0 && m_sendqueue.Count == 0)
  696. m_updateTimer.Stop();
  697. }
  698. }
  699. private void SaveAppearance(UUID agentid)
  700. {
  701. // We must set appearance parameters in the en_US culture in order to avoid issues where values are saved
  702. // in a culture where decimal points are commas and then reloaded in a culture which just treats them as
  703. // number seperators.
  704. Culture.SetCurrentCulture();
  705. ScenePresence sp = m_scene.GetScenePresence(agentid);
  706. if (sp == null)
  707. {
  708. // This is expected if the user has gone away.
  709. // m_log.DebugFormat("[AVFACTORY]: Agent {0} no longer in the scene", agentid);
  710. return;
  711. }
  712. // m_log.DebugFormat("[AVFACTORY]: Saving appearance for avatar {0}", agentid);
  713. // This could take awhile since it needs to pull inventory
  714. // We need to do it at the point of save so that there is a sufficient delay for any upload of new body part/shape
  715. // assets and item asset id changes to complete.
  716. // I don't think we need to worry about doing this within m_setAppearanceLock since the queueing avoids
  717. // multiple save requests.
  718. SetAppearanceAssets(sp.UUID, sp.Appearance);
  719. // List<AvatarAttachment> attachments = sp.Appearance.GetAttachments();
  720. // foreach (AvatarAttachment att in attachments)
  721. // {
  722. // m_log.DebugFormat(
  723. // "[AVFACTORY]: For {0} saving attachment {1} at point {2}",
  724. // sp.Name, att.ItemID, att.AttachPoint);
  725. // }
  726. m_scene.AvatarService.SetAppearance(agentid, sp.Appearance);
  727. // Trigger this here because it's the final step in the set/queue/save process for appearance setting.
  728. // Everything has been updated and stored. Ensures bakes have been persisted (if option is set to persist bakes).
  729. m_scene.EventManager.TriggerAvatarAppearanceChanged(sp);
  730. }
  731. /// <summary>
  732. /// For a given set of appearance items, check whether the items are valid and add their asset IDs to
  733. /// appearance data.
  734. /// </summary>
  735. /// <param name='userID'></param>
  736. /// <param name='appearance'></param>
  737. private void SetAppearanceAssets(UUID userID, AvatarAppearance appearance)
  738. {
  739. IInventoryService invService = m_scene.InventoryService;
  740. if (invService.GetRootFolder(userID) != null)
  741. {
  742. for (int i = 0; i < appearance.Wearables.Length; i++)
  743. {
  744. for (int j = 0; j < appearance.Wearables[i].Count; j++)
  745. {
  746. if (appearance.Wearables[i][j].ItemID == UUID.Zero)
  747. {
  748. m_log.WarnFormat(
  749. "[AVFACTORY]: Wearable item {0}:{1} for user {2} unexpectedly UUID.Zero. Ignoring.",
  750. i, j, userID);
  751. continue;
  752. }
  753. // Ignore ruth's assets
  754. if (i < AvatarWearable.DefaultWearables.Length)
  755. {
  756. if (appearance.Wearables[i][j].ItemID == AvatarWearable.DefaultWearables[i][0].ItemID)
  757. continue;
  758. }
  759. InventoryItemBase baseItem = invService.GetItem(userID, appearance.Wearables[i][j].ItemID);
  760. if (baseItem != null)
  761. {
  762. appearance.Wearables[i].Add(appearance.Wearables[i][j].ItemID, baseItem.AssetID);
  763. }
  764. else
  765. {
  766. m_log.WarnFormat(
  767. "[AVFACTORY]: Can't find inventory item {0} for {1}, setting to default",
  768. appearance.Wearables[i][j].ItemID, (WearableType)i);
  769. appearance.Wearables[i].RemoveItem(appearance.Wearables[i][j].ItemID);
  770. }
  771. }
  772. }
  773. }
  774. else
  775. {
  776. m_log.WarnFormat("[AVFACTORY]: user {0} has no inventory, appearance isn't going to work", userID);
  777. }
  778. // IInventoryService invService = m_scene.InventoryService;
  779. // bool resetwearable = false;
  780. // if (invService.GetRootFolder(userID) != null)
  781. // {
  782. // for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++)
  783. // {
  784. // for (int j = 0; j < appearance.Wearables[i].Count; j++)
  785. // {
  786. // // Check if the default wearables are not set
  787. // if (appearance.Wearables[i][j].ItemID == UUID.Zero)
  788. // {
  789. // switch ((WearableType) i)
  790. // {
  791. // case WearableType.Eyes:
  792. // case WearableType.Hair:
  793. // case WearableType.Shape:
  794. // case WearableType.Skin:
  795. // //case WearableType.Underpants:
  796. // TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance);
  797. // resetwearable = true;
  798. // m_log.Warn("[AVFACTORY]: UUID.Zero Wearables, passing fake values.");
  799. // resetwearable = true;
  800. // break;
  801. //
  802. // }
  803. // continue;
  804. // }
  805. //
  806. // // Ignore ruth's assets except for the body parts! missing body parts fail avatar appearance on V1
  807. // if (appearance.Wearables[i][j].ItemID == AvatarWearable.DefaultWearables[i][0].ItemID)
  808. // {
  809. // switch ((WearableType)i)
  810. // {
  811. // case WearableType.Eyes:
  812. // case WearableType.Hair:
  813. // case WearableType.Shape:
  814. // case WearableType.Skin:
  815. // //case WearableType.Underpants:
  816. // TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance);
  817. //
  818. // m_log.WarnFormat("[AVFACTORY]: {0} Default Wearables, passing existing values.", (WearableType)i);
  819. // resetwearable = true;
  820. // break;
  821. //
  822. // }
  823. // continue;
  824. // }
  825. //
  826. // InventoryItemBase baseItem = new InventoryItemBase(appearance.Wearables[i][j].ItemID, userID);
  827. // baseItem = invService.GetItem(baseItem);
  828. //
  829. // if (baseItem != null)
  830. // {
  831. // appearance.Wearables[i].Add(appearance.Wearables[i][j].ItemID, baseItem.AssetID);
  832. // int unmodifiedWearableIndexForClosure = i;
  833. // m_scene.AssetService.Get(baseItem.AssetID.ToString(), this,
  834. // delegate(string x, object y, AssetBase z)
  835. // {
  836. // if (z == null)
  837. // {
  838. // TryAndRepairBrokenWearable(
  839. // (WearableType)unmodifiedWearableIndexForClosure, invService,
  840. // userID, appearance);
  841. // }
  842. // });
  843. // }
  844. // else
  845. // {
  846. // m_log.ErrorFormat(
  847. // "[AVFACTORY]: Can't find inventory item {0} for {1}, setting to default",
  848. // appearance.Wearables[i][j].ItemID, (WearableType)i);
  849. //
  850. // TryAndRepairBrokenWearable((WearableType)i, invService, userID, appearance);
  851. // resetwearable = true;
  852. //
  853. // }
  854. // }
  855. // }
  856. //
  857. // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason....
  858. // if (appearance.Wearables[(int) WearableType.Eyes] == null)
  859. // {
  860. // m_log.WarnFormat("[AVFACTORY]: {0} Eyes are Null, passing existing values.", (WearableType.Eyes));
  861. //
  862. // TryAndRepairBrokenWearable(WearableType.Eyes, invService, userID, appearance);
  863. // resetwearable = true;
  864. // }
  865. // else
  866. // {
  867. // if (appearance.Wearables[(int) WearableType.Eyes][0].ItemID == UUID.Zero)
  868. // {
  869. // m_log.WarnFormat("[AVFACTORY]: Eyes are UUID.Zero are broken, {0} {1}",
  870. // appearance.Wearables[(int) WearableType.Eyes][0].ItemID,
  871. // appearance.Wearables[(int) WearableType.Eyes][0].AssetID);
  872. // TryAndRepairBrokenWearable(WearableType.Eyes, invService, userID, appearance);
  873. // resetwearable = true;
  874. //
  875. // }
  876. //
  877. // }
  878. // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason....
  879. // if (appearance.Wearables[(int)WearableType.Shape] == null)
  880. // {
  881. // m_log.WarnFormat("[AVFACTORY]: {0} shape is Null, passing existing values.", (WearableType.Shape));
  882. //
  883. // TryAndRepairBrokenWearable(WearableType.Shape, invService, userID, appearance);
  884. // resetwearable = true;
  885. // }
  886. // else
  887. // {
  888. // if (appearance.Wearables[(int)WearableType.Shape][0].ItemID == UUID.Zero)
  889. // {
  890. // m_log.WarnFormat("[AVFACTORY]: Shape is UUID.Zero and broken, {0} {1}",
  891. // appearance.Wearables[(int)WearableType.Shape][0].ItemID,
  892. // appearance.Wearables[(int)WearableType.Shape][0].AssetID);
  893. // TryAndRepairBrokenWearable(WearableType.Shape, invService, userID, appearance);
  894. // resetwearable = true;
  895. //
  896. // }
  897. //
  898. // }
  899. // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason....
  900. // if (appearance.Wearables[(int)WearableType.Hair] == null)
  901. // {
  902. // m_log.WarnFormat("[AVFACTORY]: {0} Hair is Null, passing existing values.", (WearableType.Hair));
  903. //
  904. // TryAndRepairBrokenWearable(WearableType.Hair, invService, userID, appearance);
  905. // resetwearable = true;
  906. // }
  907. // else
  908. // {
  909. // if (appearance.Wearables[(int)WearableType.Hair][0].ItemID == UUID.Zero)
  910. // {
  911. // m_log.WarnFormat("[AVFACTORY]: Hair is UUID.Zero and broken, {0} {1}",
  912. // appearance.Wearables[(int)WearableType.Hair][0].ItemID,
  913. // appearance.Wearables[(int)WearableType.Hair][0].AssetID);
  914. // TryAndRepairBrokenWearable(WearableType.Hair, invService, userID, appearance);
  915. // resetwearable = true;
  916. //
  917. // }
  918. //
  919. // }
  920. // // I don't know why we have to test for this again... but the above switches do not capture these scenarios for some reason....
  921. // if (appearance.Wearables[(int)WearableType.Skin] == null)
  922. // {
  923. // m_log.WarnFormat("[AVFACTORY]: {0} Skin is Null, passing existing values.", (WearableType.Skin));
  924. //
  925. // TryAndRepairBrokenWearable(WearableType.Skin, invService, userID, appearance);
  926. // resetwearable = true;
  927. // }
  928. // else
  929. // {
  930. // if (appearance.Wearables[(int)WearableType.Skin][0].ItemID == UUID.Zero)
  931. // {
  932. // m_log.WarnFormat("[AVFACTORY]: Skin is UUID.Zero and broken, {0} {1}",
  933. // appearance.Wearables[(int)WearableType.Skin][0].ItemID,
  934. // appearance.Wearables[(int)WearableType.Skin][0].AssetID);
  935. // TryAndRepairBrokenWearable(WearableType.Skin, invService, userID, appearance);
  936. // resetwearable = true;
  937. //
  938. // }
  939. //
  940. // }
  941. // if (resetwearable)
  942. // {
  943. // ScenePresence presence = null;
  944. // if (m_scene.TryGetScenePresence(userID, out presence))
  945. // {
  946. // presence.ControllingClient.SendWearables(presence.Appearance.Wearables,
  947. // presence.Appearance.Serial++);
  948. // }
  949. // }
  950. //
  951. // }
  952. // else
  953. // {
  954. // m_log.WarnFormat("[AVFACTORY]: user {0} has no inventory, appearance isn't going to work", userID);
  955. // }
  956. }
  957. private void TryAndRepairBrokenWearable(WearableType type, IInventoryService invService, UUID userID,AvatarAppearance appearance)
  958. {
  959. UUID defaultwearable = GetDefaultItem(type);
  960. if (defaultwearable != UUID.Zero)
  961. {
  962. UUID newInvItem = UUID.Random();
  963. InventoryItemBase itembase = new InventoryItemBase(newInvItem, userID)
  964. {
  965. AssetID = defaultwearable,
  966. AssetType = (int)FolderType.BodyPart,
  967. CreatorId = userID.ToString(),
  968. //InvType = (int)InventoryType.Wearable,
  969. Description = "Failed Wearable Replacement",
  970. Folder = invService.GetFolderForType(userID, FolderType.BodyPart).ID,
  971. Flags = (uint) type, Name = Enum.GetName(typeof (WearableType), type),
  972. BasePermissions = (uint) PermissionMask.Copy,
  973. CurrentPermissions = (uint) PermissionMask.Copy,
  974. EveryOnePermissions = (uint) PermissionMask.Copy,
  975. GroupPermissions = (uint) PermissionMask.Copy,
  976. NextPermissions = (uint) PermissionMask.Copy
  977. };
  978. invService.AddItem(itembase);
  979. UUID LinkInvItem = UUID.Random();
  980. itembase = new InventoryItemBase(LinkInvItem, userID)
  981. {
  982. AssetID = newInvItem,
  983. AssetType = (int)AssetType.Link,
  984. CreatorId = userID.ToString(),
  985. InvType = (int) InventoryType.Wearable,
  986. Description = "Failed Wearable Replacement",
  987. Folder = invService.GetFolderForType(userID, FolderType.CurrentOutfit).ID,
  988. Flags = (uint) type,
  989. Name = Enum.GetName(typeof (WearableType), type),
  990. BasePermissions = (uint) PermissionMask.Copy,
  991. CurrentPermissions = (uint) PermissionMask.Copy,
  992. EveryOnePermissions = (uint) PermissionMask.Copy,
  993. GroupPermissions = (uint) PermissionMask.Copy,
  994. NextPermissions = (uint) PermissionMask.Copy
  995. };
  996. invService.AddItem(itembase);
  997. appearance.Wearables[(int)type] = new AvatarWearable(newInvItem, GetDefaultItem(type));
  998. ScenePresence presence = null;
  999. if (m_scene.TryGetScenePresence(userID, out presence))
  1000. {
  1001. m_scene.SendInventoryUpdate(presence.ControllingClient,
  1002. invService.GetFolderForType(userID, FolderType.CurrentOutfit), false, true);
  1003. }
  1004. }
  1005. }
  1006. private UUID GetDefaultItem(WearableType wearable)
  1007. {
  1008. // These are ruth
  1009. UUID ret = UUID.Zero;
  1010. switch (wearable)
  1011. {
  1012. case WearableType.Eyes:
  1013. ret = new UUID("4bb6fa4d-1cd2-498a-a84c-95c1a0e745a7");
  1014. break;
  1015. case WearableType.Hair:
  1016. ret = new UUID("d342e6c0-b9d2-11dc-95ff-0800200c9a66");
  1017. break;
  1018. case WearableType.Pants:
  1019. ret = new UUID("00000000-38f9-1111-024e-222222111120");
  1020. break;
  1021. case WearableType.Shape:
  1022. ret = new UUID("66c41e39-38f9-f75a-024e-585989bfab73");
  1023. break;
  1024. case WearableType.Shirt:
  1025. ret = new UUID("00000000-38f9-1111-024e-222222111110");
  1026. break;
  1027. case WearableType.Skin:
  1028. ret = new UUID("77c41e39-38f9-f75a-024e-585989bbabbb");
  1029. break;
  1030. case WearableType.Undershirt:
  1031. ret = new UUID("16499ebb-3208-ec27-2def-481881728f47");
  1032. break;
  1033. case WearableType.Underpants:
  1034. ret = new UUID("4ac2e9c7-3671-d229-316a-67717730841d");
  1035. break;
  1036. }
  1037. return ret;
  1038. }
  1039. #endregion
  1040. #region Client Event Handlers
  1041. /// <summary>
  1042. /// Tell the client for this scene presence what items it should be wearing now
  1043. /// </summary>
  1044. /// <param name="client"></param>
  1045. private void Client_OnRequestWearables(IClientAPI client)
  1046. {
  1047. Util.FireAndForget(delegate(object x)
  1048. {
  1049. Thread.Sleep(4000);
  1050. // m_log.DebugFormat("[AVFACTORY]: Client_OnRequestWearables called for {0} ({1})", client.Name, client.AgentId);
  1051. ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
  1052. if (sp != null)
  1053. client.SendWearables(sp.Appearance.Wearables, sp.Appearance.Serial++);
  1054. else
  1055. m_log.WarnFormat("[AVFACTORY]: Client_OnRequestWearables unable to find presence for {0}", client.AgentId);
  1056. }, null, "AvatarFactoryModule.OnClientRequestWearables");
  1057. }
  1058. /// <summary>
  1059. /// Set appearance data (texture asset IDs and slider settings) received from a client
  1060. /// </summary>
  1061. /// <param name="client"></param>
  1062. /// <param name="texture"></param>
  1063. /// <param name="visualParam"></param>
  1064. private void Client_OnSetAppearance(IClientAPI client, Primitive.TextureEntry textureEntry, byte[] visualParams, Vector3 avSize, WearableCacheItem[] cacheItems)
  1065. {
  1066. // m_log.WarnFormat("[AVFACTORY]: Client_OnSetAppearance called for {0} ({1})", client.Name, client.AgentId);
  1067. ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
  1068. if (sp != null)
  1069. SetAppearance(sp, textureEntry, visualParams,avSize, cacheItems);
  1070. else
  1071. m_log.WarnFormat("[AVFACTORY]: Client_OnSetAppearance unable to find presence for {0}", client.AgentId);
  1072. }
  1073. /// <summary>
  1074. /// Update what the avatar is wearing using an item from their inventory.
  1075. /// </summary>
  1076. /// <param name="client"></param>
  1077. /// <param name="e"></param>
  1078. private void Client_OnAvatarNowWearing(IClientAPI client, AvatarWearingArgs e)
  1079. {
  1080. // m_log.WarnFormat("[AVFACTORY]: Client_OnAvatarNowWearing called for {0} ({1})", client.Name, client.AgentId);
  1081. ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
  1082. if (sp == null)
  1083. {
  1084. m_log.WarnFormat("[AVFACTORY]: Client_OnAvatarNowWearing unable to find presence for {0}", client.AgentId);
  1085. return;
  1086. }
  1087. // we need to clean out the existing textures
  1088. sp.Appearance.ResetAppearance();
  1089. // operate on a copy of the appearance so we don't have to lock anything yet
  1090. AvatarAppearance avatAppearance = new AvatarAppearance(sp.Appearance, false);
  1091. foreach (AvatarWearingArgs.Wearable wear in e.NowWearing)
  1092. {
  1093. // If the wearable type is larger than the current array, expand it
  1094. if (avatAppearance.Wearables.Length <= wear.Type)
  1095. {
  1096. int currentLength = avatAppearance.Wearables.Length;
  1097. AvatarWearable[] wears = avatAppearance.Wearables;
  1098. Array.Resize(ref wears, wear.Type + 1);
  1099. for (int i = currentLength ; i <= wear.Type ; i++)
  1100. wears[i] = new AvatarWearable();
  1101. avatAppearance.Wearables = wears;
  1102. }
  1103. avatAppearance.Wearables[wear.Type].Add(wear.ItemID, UUID.Zero);
  1104. }
  1105. avatAppearance.GetAssetsFrom(sp.Appearance);
  1106. lock (m_setAppearanceLock)
  1107. {
  1108. // Update only those fields that we have changed. This is important because the viewer
  1109. // often sends AvatarIsWearing and SetAppearance packets at once, and AvatarIsWearing
  1110. // shouldn't overwrite the changes made in SetAppearance.
  1111. sp.Appearance.Wearables = avatAppearance.Wearables;
  1112. sp.Appearance.Texture = avatAppearance.Texture;
  1113. // We don't need to send the appearance here since the "iswearing" will trigger a new set
  1114. // of visual param and baked texture changes. When those complete, the new appearance will be sent
  1115. QueueAppearanceSave(client.AgentId);
  1116. }
  1117. }
  1118. /// <summary>
  1119. /// Respond to the cached textures request from the client
  1120. /// </summary>
  1121. /// <param name="client"></param>
  1122. /// <param name="serial"></param>
  1123. /// <param name="cachedTextureRequest"></param>
  1124. private void Client_OnCachedTextureRequest(IClientAPI client, int serial, List<CachedTextureRequestArg> cachedTextureRequest)
  1125. {
  1126. // m_log.WarnFormat("[AVFACTORY]: Client_OnCachedTextureRequest called for {0} ({1})", client.Name, client.AgentId);
  1127. ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
  1128. List<CachedTextureResponseArg> cachedTextureResponse = new List<CachedTextureResponseArg>();
  1129. foreach (CachedTextureRequestArg request in cachedTextureRequest)
  1130. {
  1131. UUID texture = UUID.Zero;
  1132. int index = request.BakedTextureIndex;
  1133. if (m_reusetextures)
  1134. {
  1135. // this is the most insanely dumb way to do this... however it seems to
  1136. // actually work. if the appearance has been reset because wearables have
  1137. // changed then the texture entries are zero'd out until the bakes are
  1138. // uploaded. on login, if the textures exist in the cache (eg if you logged
  1139. // into the simulator recently, then the appearance will pull those and send
  1140. // them back in the packet and you won't have to rebake. if the textures aren't
  1141. // in the cache then the intial makeroot() call in scenepresence will zero
  1142. // them out.
  1143. //
  1144. // a better solution (though how much better is an open question) is to
  1145. // store the hashes in the appearance and compare them. Thats's coming.
  1146. Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[index];
  1147. if (face != null)
  1148. texture = face.TextureID;
  1149. // m_log.WarnFormat("[AVFACTORY]: reuse texture {0} for index {1}",texture,index);
  1150. }
  1151. CachedTextureResponseArg response = new CachedTextureResponseArg();
  1152. response.BakedTextureIndex = index;
  1153. response.BakedTextureID = texture;
  1154. response.HostName = null;
  1155. cachedTextureResponse.Add(response);
  1156. }
  1157. // m_log.WarnFormat("[AVFACTORY]: serial is {0}",serial);
  1158. // The serial number appears to be used to match requests and responses
  1159. // in the texture transaction. We just send back the serial number
  1160. // that was provided in the request. The viewer bumps this for us.
  1161. client.SendCachedTextureResponse(sp, serial, cachedTextureResponse);
  1162. }
  1163. #endregion
  1164. public void WriteBakedTexturesReport(IScenePresence sp, ReportOutputAction outputAction)
  1165. {
  1166. outputAction("For {0} in {1}", sp.Name, m_scene.RegionInfo.RegionName);
  1167. outputAction(BAKED_TEXTURES_REPORT_FORMAT, "Bake Type", "UUID");
  1168. Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = GetBakedTextureFaces(sp.UUID);
  1169. foreach (BakeType bt in bakedTextures.Keys)
  1170. {
  1171. string rawTextureID;
  1172. if (bakedTextures[bt] == null)
  1173. {
  1174. rawTextureID = "not set";
  1175. }
  1176. else
  1177. {
  1178. rawTextureID = bakedTextures[bt].TextureID.ToString();
  1179. if (m_scene.AssetService.Get(rawTextureID) == null)
  1180. rawTextureID += " (not found)";
  1181. else
  1182. rawTextureID += " (uploaded)";
  1183. }
  1184. outputAction(BAKED_TEXTURES_REPORT_FORMAT, bt, rawTextureID);
  1185. }
  1186. bool bakedTextureValid = m_scene.AvatarFactory.ValidateBakedTextureCache(sp);
  1187. outputAction("{0} baked appearance texture is {1}", sp.Name, bakedTextureValid ? "OK" : "incomplete");
  1188. }
  1189. }
  1190. }