clockwerk-opensim-stable – Blame information for rev 1

Subversion Repositories:
Rev:
Rev Author Line No. Line
1 vero 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  
28 using System;
29 using System.Collections.Generic;
30 using System.Reflection;
31 using System.Threading;
32 using System.Text;
33 using System.Timers;
34 using log4net;
35 using Nini.Config;
36 using OpenMetaverse;
37 using OpenSim.Framework;
38 using OpenSim.Region.Framework.Interfaces;
39 using OpenSim.Region.Framework.Scenes;
40 using OpenSim.Services.Interfaces;
41  
42 using Mono.Addins;
43 using PermissionMask = OpenSim.Framework.PermissionMask;
44  
45 namespace OpenSim.Region.CoreModules.Avatar.AvatarFactory
46 {
47 [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AvatarFactoryModule")]
48 public class AvatarFactoryModule : IAvatarFactoryModule, INonSharedRegionModule
49 {
50 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
51  
52 public const string BAKED_TEXTURES_REPORT_FORMAT = "{0,-9} {1}";
53  
54 private Scene m_scene = null;
55  
56 private int m_savetime = 5; // seconds to wait before saving changed appearance
57 private int m_sendtime = 2; // seconds to wait before sending changed appearance
58 private bool m_reusetextures = false;
59  
60 private int m_checkTime = 500; // milliseconds to wait between checks for appearance updates
61 private System.Timers.Timer m_updateTimer = new System.Timers.Timer();
62 private Dictionary<UUID,long> m_savequeue = new Dictionary<UUID,long>();
63 private Dictionary<UUID,long> m_sendqueue = new Dictionary<UUID,long>();
64  
65 private object m_setAppearanceLock = new object();
66  
67 #region Region Module interface
68  
69 public void Initialise(IConfigSource config)
70 {
71  
72 IConfig appearanceConfig = config.Configs["Appearance"];
73 if (appearanceConfig != null)
74 {
75 m_savetime = Convert.ToInt32(appearanceConfig.GetString("DelayBeforeAppearanceSave",Convert.ToString(m_savetime)));
76 m_sendtime = Convert.ToInt32(appearanceConfig.GetString("DelayBeforeAppearanceSend",Convert.ToString(m_sendtime)));
77 m_reusetextures = appearanceConfig.GetBoolean("ReuseTextures",m_reusetextures);
78  
79 // m_log.InfoFormat("[AVFACTORY] configured for {0} save and {1} send",m_savetime,m_sendtime);
80 }
81  
82 }
83  
84 public void AddRegion(Scene scene)
85 {
86 if (m_scene == null)
87 m_scene = scene;
88  
89 scene.RegisterModuleInterface<IAvatarFactoryModule>(this);
90 scene.EventManager.OnNewClient += SubscribeToClientEvents;
91 }
92  
93 public void RemoveRegion(Scene scene)
94 {
95 if (scene == m_scene)
96 {
97 scene.UnregisterModuleInterface<IAvatarFactoryModule>(this);
98 scene.EventManager.OnNewClient -= SubscribeToClientEvents;
99 }
100  
101 m_scene = null;
102 }
103  
104 public void RegionLoaded(Scene scene)
105 {
106 m_updateTimer.Enabled = false;
107 m_updateTimer.AutoReset = true;
108 m_updateTimer.Interval = m_checkTime; // 500 milliseconds wait to start async ops
109 m_updateTimer.Elapsed += new ElapsedEventHandler(HandleAppearanceUpdateTimer);
110 }
111  
112 public void Close()
113 {
114 }
115  
116 public string Name
117 {
118 get { return "Default Avatar Factory"; }
119 }
120  
121 public bool IsSharedModule
122 {
123 get { return false; }
124 }
125  
126 public Type ReplaceableInterface
127 {
128 get { return null; }
129 }
130  
131  
132 private void SubscribeToClientEvents(IClientAPI client)
133 {
134 client.OnRequestWearables += Client_OnRequestWearables;
135 client.OnSetAppearance += Client_OnSetAppearance;
136 client.OnAvatarNowWearing += Client_OnAvatarNowWearing;
137 client.OnCachedTextureRequest += Client_OnCachedTextureRequest;
138 }
139  
140 #endregion
141  
142 #region IAvatarFactoryModule
143  
144 /// </summary>
145 /// <param name="sp"></param>
146 /// <param name="texture"></param>
147 /// <param name="visualParam"></param>
148 public void SetAppearance(IScenePresence sp, AvatarAppearance appearance)
149 {
150 DoSetAppearance(sp, appearance.Texture, appearance.VisualParams, new List<CachedTextureRequestArg>());
151 }
152  
153 /// <summary>
154 /// Set appearance data (texture asset IDs and slider settings)
155 /// </summary>
156 /// <param name="sp"></param>
157 /// <param name="texture"></param>
158 /// <param name="visualParam"></param>
159 public void SetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams)
160 {
161 DoSetAppearance(sp, textureEntry, visualParams, new List<CachedTextureRequestArg>());
162 }
163  
164 /// <summary>
165 /// Set appearance data (texture asset IDs and slider settings)
166 /// </summary>
167 /// <param name="sp"></param>
168 /// <param name="texture"></param>
169 /// <param name="visualParam"></param>
170 protected void DoSetAppearance(IScenePresence sp, Primitive.TextureEntry textureEntry, byte[] visualParams, List<CachedTextureRequestArg> hashes)
171 {
172 // m_log.DebugFormat(
173 // "[AVFACTORY]: start SetAppearance for {0}, te {1}, visualParams {2}",
174 // sp.Name, textureEntry, visualParams);
175  
176 // TODO: This is probably not necessary any longer, just assume the
177 // textureEntry set implies that the appearance transaction is complete
178 bool changed = false;
179  
180 // Process the texture entry transactionally, this doesn't guarantee that Appearance is
181 // going to be handled correctly but it does serialize the updates to the appearance
182 lock (m_setAppearanceLock)
183 {
184 // Process the visual params, this may change height as well
185 if (visualParams != null)
186 {
187 // string[] visualParamsStrings = new string[visualParams.Length];
188 // for (int i = 0; i < visualParams.Length; i++)
189 // visualParamsStrings[i] = visualParams[i].ToString();
190 // m_log.DebugFormat(
191 // "[AVFACTORY]: Setting visual params for {0} to {1}",
192 // client.Name, string.Join(", ", visualParamsStrings));
193  
194 float oldHeight = sp.Appearance.AvatarHeight;
195 changed = sp.Appearance.SetVisualParams(visualParams);
196  
197 if (sp.Appearance.AvatarHeight != oldHeight && sp.Appearance.AvatarHeight > 0)
198 ((ScenePresence)sp).SetHeight(sp.Appearance.AvatarHeight);
199 }
200  
201 // Process the baked texture array
202 if (textureEntry != null)
203 {
204 // m_log.DebugFormat("[AVFACTORY]: Received texture update for {0} {1}", sp.Name, sp.UUID);
205 // WriteBakedTexturesReport(sp, m_log.DebugFormat);
206  
207 changed = sp.Appearance.SetTextureEntries(textureEntry) || changed;
208  
209 // WriteBakedTexturesReport(sp, m_log.DebugFormat);
210  
211 // If bake textures are missing and this is not an NPC, request a rebake from client
212 if (!ValidateBakedTextureCache(sp) && (((ScenePresence)sp).PresenceType != PresenceType.Npc))
213 RequestRebake(sp, true);
214  
215 // Save the wearble hashes in the appearance
216 sp.Appearance.ResetTextureHashes();
217 if (m_reusetextures)
218 {
219 foreach (CachedTextureRequestArg arg in hashes)
220 sp.Appearance.SetTextureHash(arg.BakedTextureIndex,arg.WearableHashID);
221 }
222  
223 // This appears to be set only in the final stage of the appearance
224 // update transaction. In theory, we should be able to do an immediate
225 // appearance send and save here.
226 }
227  
228 // NPC should send to clients immediately and skip saving appearance
229 if (((ScenePresence)sp).PresenceType == PresenceType.Npc)
230 {
231 SendAppearance((ScenePresence)sp);
232 return;
233 }
234  
235 // save only if there were changes, send no matter what (doesn't hurt to send twice)
236 if (changed)
237 QueueAppearanceSave(sp.ControllingClient.AgentId);
238  
239 QueueAppearanceSend(sp.ControllingClient.AgentId);
240 }
241  
242 // m_log.WarnFormat("[AVFACTORY]: complete SetAppearance for {0}:\n{1}",client.AgentId,sp.Appearance.ToString());
243 }
244  
245 private void SendAppearance(ScenePresence sp)
246 {
247 // Send the appearance to everyone in the scene
248 sp.SendAppearanceToAllOtherAgents();
249  
250 // Send animations back to the avatar as well
251 sp.Animator.SendAnimPack();
252 }
253  
254 public bool SendAppearance(UUID agentId)
255 {
256 // m_log.DebugFormat("[AVFACTORY]: Sending appearance for {0}", agentId);
257  
258 ScenePresence sp = m_scene.GetScenePresence(agentId);
259 if (sp == null)
260 {
261 // This is expected if the user has gone away.
262 // m_log.DebugFormat("[AVFACTORY]: Agent {0} no longer in the scene", agentId);
263 return false;
264 }
265  
266 SendAppearance(sp);
267 return true;
268 }
269  
270 public Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(UUID agentId)
271 {
272 ScenePresence sp = m_scene.GetScenePresence(agentId);
273  
274 if (sp == null)
275 return new Dictionary<BakeType, Primitive.TextureEntryFace>();
276  
277 return GetBakedTextureFaces(sp);
278 }
279  
280 public bool SaveBakedTextures(UUID agentId)
281 {
282 ScenePresence sp = m_scene.GetScenePresence(agentId);
283  
284 if (sp == null)
285 return false;
286  
287 m_log.DebugFormat(
288 "[AV FACTORY]: Permanently saving baked textures for {0} in {1}",
289 sp.Name, m_scene.RegionInfo.RegionName);
290  
291 Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = GetBakedTextureFaces(sp);
292  
293 if (bakedTextures.Count == 0)
294 return false;
295  
296 foreach (BakeType bakeType in bakedTextures.Keys)
297 {
298 Primitive.TextureEntryFace bakedTextureFace = bakedTextures[bakeType];
299  
300 if (bakedTextureFace == null)
301 {
302 // This can happen legitimately, since some baked textures might not exist
303 //m_log.WarnFormat(
304 // "[AV FACTORY]: No texture ID set for {0} for {1} in {2} not found when trying to save permanently",
305 // bakeType, sp.Name, m_scene.RegionInfo.RegionName);
306 continue;
307 }
308  
309 AssetBase asset = m_scene.AssetService.Get(bakedTextureFace.TextureID.ToString());
310  
311 if (asset != null)
312 {
313 // Replace an HG ID with the simple asset ID so that we can persist textures for foreign HG avatars
314 asset.ID = asset.FullID.ToString();
315  
316 asset.Temporary = false;
317 asset.Local = false;
318 m_scene.AssetService.Store(asset);
319 }
320 else
321 {
322 m_log.WarnFormat(
323 "[AV FACTORY]: Baked texture id {0} not found for bake {1} for avatar {2} in {3} when trying to save permanently",
324 bakedTextureFace.TextureID, bakeType, sp.Name, m_scene.RegionInfo.RegionName);
325 }
326 }
327 return true;
328 }
329  
330 /// <summary>
331 /// Queue up a request to send appearance.
332 /// </summary>
333 /// <remarks>
334 /// Makes it possible to accumulate changes without sending out each one separately.
335 /// </remarks>
336 /// <param name="agentId"></param>
337 public void QueueAppearanceSend(UUID agentid)
338 {
339 // m_log.DebugFormat("[AVFACTORY]: Queue appearance send for {0}", agentid);
340  
341 // 10000 ticks per millisecond, 1000 milliseconds per second
342 long timestamp = DateTime.Now.Ticks + Convert.ToInt64(m_sendtime * 1000 * 10000);
343 lock (m_sendqueue)
344 {
345 m_sendqueue[agentid] = timestamp;
346 m_updateTimer.Start();
347 }
348 }
349  
350 public void QueueAppearanceSave(UUID agentid)
351 {
352 // m_log.DebugFormat("[AVFACTORY]: Queueing appearance save for {0}", agentid);
353  
354 // 10000 ticks per millisecond, 1000 milliseconds per second
355 long timestamp = DateTime.Now.Ticks + Convert.ToInt64(m_savetime * 1000 * 10000);
356 lock (m_savequeue)
357 {
358 m_savequeue[agentid] = timestamp;
359 m_updateTimer.Start();
360 }
361 }
362  
363 public bool ValidateBakedTextureCache(IScenePresence sp)
364 {
365 bool defonly = true; // are we only using default textures
366  
367 // Process the texture entry
368 for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++)
369 {
370 int idx = AvatarAppearance.BAKE_INDICES[i];
371 Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx];
372  
373 // if there is no texture entry, skip it
374 if (face == null)
375 continue;
376  
377 // m_log.DebugFormat(
378 // "[AVFACTORY]: Looking for texture {0}, id {1} for {2} {3}",
379 // face.TextureID, idx, client.Name, client.AgentId);
380  
381 // if the texture is one of the "defaults" then skip it
382 // this should probably be more intelligent (skirt texture doesnt matter
383 // if the avatar isnt wearing a skirt) but if any of the main baked
384 // textures is default then the rest should be as well
385 if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE)
386 continue;
387  
388 defonly = false; // found a non-default texture reference
389  
390 if (m_scene.AssetService.Get(face.TextureID.ToString()) == null)
391 return false;
392 }
393  
394 // m_log.DebugFormat("[AVFACTORY]: Completed texture check for {0} {1}", sp.Name, sp.UUID);
395  
396 // If we only found default textures, then the appearance is not cached
397 return (defonly ? false : true);
398 }
399  
400 public int RequestRebake(IScenePresence sp, bool missingTexturesOnly)
401 {
402 int texturesRebaked = 0;
403  
404 for (int i = 0; i < AvatarAppearance.BAKE_INDICES.Length; i++)
405 {
406 int idx = AvatarAppearance.BAKE_INDICES[i];
407 Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[idx];
408  
409 // if there is no texture entry, skip it
410 if (face == null)
411 continue;
412  
413 // m_log.DebugFormat(
414 // "[AVFACTORY]: Looking for texture {0}, id {1} for {2} {3}",
415 // face.TextureID, idx, client.Name, client.AgentId);
416  
417 // if the texture is one of the "defaults" then skip it
418 // this should probably be more intelligent (skirt texture doesnt matter
419 // if the avatar isnt wearing a skirt) but if any of the main baked
420 // textures is default then the rest should be as well
421 if (face.TextureID == UUID.Zero || face.TextureID == AppearanceManager.DEFAULT_AVATAR_TEXTURE)
422 continue;
423  
424 if (missingTexturesOnly)
425 {
426 if (m_scene.AssetService.Get(face.TextureID.ToString()) != null)
427 {
428 continue;
429 }
430 else
431 {
432 // On inter-simulator teleports, this occurs if baked textures are not being stored by the
433 // grid asset service (which means that they are not available to the new region and so have
434 // to be re-requested from the client).
435 //
436 // The only available core OpenSimulator behaviour right now
437 // is not to store these textures, temporarily or otherwise.
438 m_log.DebugFormat(
439 "[AVFACTORY]: Missing baked texture {0} ({1}) for {2}, requesting rebake.",
440 face.TextureID, idx, sp.Name);
441 }
442 }
443 else
444 {
445 m_log.DebugFormat(
446 "[AVFACTORY]: Requesting rebake of {0} ({1}) for {2}.",
447 face.TextureID, idx, sp.Name);
448 }
449  
450 texturesRebaked++;
451 sp.ControllingClient.SendRebakeAvatarTextures(face.TextureID);
452 }
453  
454 return texturesRebaked;
455 }
456  
457 #endregion
458  
459 #region AvatarFactoryModule private methods
460  
461 private Dictionary<BakeType, Primitive.TextureEntryFace> GetBakedTextureFaces(ScenePresence sp)
462 {
463 if (sp.IsChildAgent)
464 return new Dictionary<BakeType, Primitive.TextureEntryFace>();
465  
466 Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures
467 = new Dictionary<BakeType, Primitive.TextureEntryFace>();
468  
469 AvatarAppearance appearance = sp.Appearance;
470 Primitive.TextureEntryFace[] faceTextures = appearance.Texture.FaceTextures;
471  
472 foreach (int i in Enum.GetValues(typeof(BakeType)))
473 {
474 BakeType bakeType = (BakeType)i;
475  
476 if (bakeType == BakeType.Unknown)
477 continue;
478  
479 // m_log.DebugFormat(
480 // "[AVFACTORY]: NPC avatar {0} has texture id {1} : {2}",
481 // acd.AgentID, i, acd.Appearance.Texture.FaceTextures[i]);
482  
483 int ftIndex = (int)AppearanceManager.BakeTypeToAgentTextureIndex(bakeType);
484 Primitive.TextureEntryFace texture = faceTextures[ftIndex]; // this will be null if there's no such baked texture
485 bakedTextures[bakeType] = texture;
486 }
487  
488 return bakedTextures;
489 }
490  
491 private void HandleAppearanceUpdateTimer(object sender, EventArgs ea)
492 {
493 long now = DateTime.Now.Ticks;
494  
495 lock (m_sendqueue)
496 {
497 Dictionary<UUID, long> sends = new Dictionary<UUID, long>(m_sendqueue);
498 foreach (KeyValuePair<UUID, long> kvp in sends)
499 {
500 // We have to load the key and value into local parameters to avoid a race condition if we loop
501 // around and load kvp with a different value before FireAndForget has launched its thread.
502 UUID avatarID = kvp.Key;
503 long sendTime = kvp.Value;
504  
505 // m_log.DebugFormat("[AVFACTORY]: Handling queued appearance updates for {0}, update delta to now is {1}", avatarID, sendTime - now);
506  
507 if (sendTime < now)
508 {
509 Util.FireAndForget(o => SendAppearance(avatarID));
510 m_sendqueue.Remove(avatarID);
511 }
512 }
513 }
514  
515 lock (m_savequeue)
516 {
517 Dictionary<UUID, long> saves = new Dictionary<UUID, long>(m_savequeue);
518 foreach (KeyValuePair<UUID, long> kvp in saves)
519 {
520 // We have to load the key and value into local parameters to avoid a race condition if we loop
521 // around and load kvp with a different value before FireAndForget has launched its thread.
522 UUID avatarID = kvp.Key;
523 long sendTime = kvp.Value;
524  
525 if (sendTime < now)
526 {
527 Util.FireAndForget(o => SaveAppearance(avatarID));
528 m_savequeue.Remove(avatarID);
529 }
530 }
531  
532 // We must lock both queues here so that QueueAppearanceSave() or *Send() don't m_updateTimer.Start() on
533 // another thread inbetween the first count calls and m_updateTimer.Stop() on this thread.
534 lock (m_sendqueue)
535 if (m_savequeue.Count == 0 && m_sendqueue.Count == 0)
536 m_updateTimer.Stop();
537 }
538 }
539  
540 private void SaveAppearance(UUID agentid)
541 {
542 // We must set appearance parameters in the en_US culture in order to avoid issues where values are saved
543 // in a culture where decimal points are commas and then reloaded in a culture which just treats them as
544 // number seperators.
545 Culture.SetCurrentCulture();
546  
547 ScenePresence sp = m_scene.GetScenePresence(agentid);
548 if (sp == null)
549 {
550 // This is expected if the user has gone away.
551 // m_log.DebugFormat("[AVFACTORY]: Agent {0} no longer in the scene", agentid);
552 return;
553 }
554  
555 // m_log.DebugFormat("[AVFACTORY]: Saving appearance for avatar {0}", agentid);
556  
557 // This could take awhile since it needs to pull inventory
558 // 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
559 // assets and item asset id changes to complete.
560 // I don't think we need to worry about doing this within m_setAppearanceLock since the queueing avoids
561 // multiple save requests.
562 SetAppearanceAssets(sp.UUID, sp.Appearance);
563  
564 // List<AvatarAttachment> attachments = sp.Appearance.GetAttachments();
565 // foreach (AvatarAttachment att in attachments)
566 // {
567 // m_log.DebugFormat(
568 // "[AVFACTORY]: For {0} saving attachment {1} at point {2}",
569 // sp.Name, att.ItemID, att.AttachPoint);
570 // }
571  
572 m_scene.AvatarService.SetAppearance(agentid, sp.Appearance);
573  
574 // Trigger this here because it's the final step in the set/queue/save process for appearance setting.
575 // Everything has been updated and stored. Ensures bakes have been persisted (if option is set to persist bakes).
576 m_scene.EventManager.TriggerAvatarAppearanceChanged(sp);
577 }
578  
579 private void SetAppearanceAssets(UUID userID, AvatarAppearance appearance)
580 {
581 IInventoryService invService = m_scene.InventoryService;
582  
583 if (invService.GetRootFolder(userID) != null)
584 {
585 for (int i = 0; i < AvatarWearable.MAX_WEARABLES; i++)
586 {
587 for (int j = 0; j < appearance.Wearables[i].Count; j++)
588 {
589 if (appearance.Wearables[i][j].ItemID == UUID.Zero)
590 continue;
591  
592 // Ignore ruth's assets
593 if (appearance.Wearables[i][j].ItemID == AvatarWearable.DefaultWearables[i][0].ItemID)
594 continue;
595  
596 InventoryItemBase baseItem = new InventoryItemBase(appearance.Wearables[i][j].ItemID, userID);
597 baseItem = invService.GetItem(baseItem);
598  
599 if (baseItem != null)
600 {
601 appearance.Wearables[i].Add(appearance.Wearables[i][j].ItemID, baseItem.AssetID);
602 }
603 else
604 {
605 m_log.ErrorFormat(
606 "[AVFACTORY]: Can't find inventory item {0} for {1}, setting to default",
607 appearance.Wearables[i][j].ItemID, (WearableType)i);
608  
609 appearance.Wearables[i].RemoveItem(appearance.Wearables[i][j].ItemID);
610 }
611 }
612 }
613 }
614 else
615 {
616 m_log.WarnFormat("[AVFACTORY]: user {0} has no inventory, appearance isn't going to work", userID);
617 }
618 }
619  
620 #endregion
621  
622 #region Client Event Handlers
623 /// <summary>
624 /// Tell the client for this scene presence what items it should be wearing now
625 /// </summary>
626 /// <param name="client"></param>
627 private void Client_OnRequestWearables(IClientAPI client)
628 {
629 // m_log.DebugFormat("[AVFACTORY]: Client_OnRequestWearables called for {0} ({1})", client.Name, client.AgentId);
630 ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
631 if (sp != null)
632 client.SendWearables(sp.Appearance.Wearables, sp.Appearance.Serial++);
633 else
634 m_log.WarnFormat("[AVFACTORY]: Client_OnRequestWearables unable to find presence for {0}", client.AgentId);
635 }
636  
637 /// <summary>
638 /// Set appearance data (texture asset IDs and slider settings) received from a client
639 /// </summary>
640 /// <param name="client"></param>
641 /// <param name="texture"></param>
642 /// <param name="visualParam"></param>
643 private void Client_OnSetAppearance(IClientAPI client, Primitive.TextureEntry textureEntry, byte[] visualParams, List<CachedTextureRequestArg> hashes)
644 {
645 // m_log.WarnFormat("[AVFACTORY]: Client_OnSetAppearance called for {0} ({1})", client.Name, client.AgentId);
646 ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
647 if (sp != null)
648 DoSetAppearance(sp, textureEntry, visualParams, hashes);
649 else
650 m_log.WarnFormat("[AVFACTORY]: Client_OnSetAppearance unable to find presence for {0}", client.AgentId);
651 }
652  
653 /// <summary>
654 /// Update what the avatar is wearing using an item from their inventory.
655 /// </summary>
656 /// <param name="client"></param>
657 /// <param name="e"></param>
658 private void Client_OnAvatarNowWearing(IClientAPI client, AvatarWearingArgs e)
659 {
660 // m_log.WarnFormat("[AVFACTORY]: Client_OnAvatarNowWearing called for {0} ({1})", client.Name, client.AgentId);
661 ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
662 if (sp == null)
663 {
664 m_log.WarnFormat("[AVFACTORY]: Client_OnAvatarNowWearing unable to find presence for {0}", client.AgentId);
665 return;
666 }
667  
668 // we need to clean out the existing textures
669 sp.Appearance.ResetAppearance();
670  
671 // operate on a copy of the appearance so we don't have to lock anything yet
672 AvatarAppearance avatAppearance = new AvatarAppearance(sp.Appearance, false);
673  
674 foreach (AvatarWearingArgs.Wearable wear in e.NowWearing)
675 {
676 if (wear.Type < AvatarWearable.MAX_WEARABLES)
677 avatAppearance.Wearables[wear.Type].Add(wear.ItemID, UUID.Zero);
678 }
679  
680 avatAppearance.GetAssetsFrom(sp.Appearance);
681  
682 lock (m_setAppearanceLock)
683 {
684 // Update only those fields that we have changed. This is important because the viewer
685 // often sends AvatarIsWearing and SetAppearance packets at once, and AvatarIsWearing
686 // shouldn't overwrite the changes made in SetAppearance.
687 sp.Appearance.Wearables = avatAppearance.Wearables;
688 sp.Appearance.Texture = avatAppearance.Texture;
689  
690 // We don't need to send the appearance here since the "iswearing" will trigger a new set
691 // of visual param and baked texture changes. When those complete, the new appearance will be sent
692  
693 QueueAppearanceSave(client.AgentId);
694 }
695 }
696  
697 /// <summary>
698 /// Respond to the cached textures request from the client
699 /// </summary>
700 /// <param name="client"></param>
701 /// <param name="serial"></param>
702 /// <param name="cachedTextureRequest"></param>
703 private void Client_OnCachedTextureRequest(IClientAPI client, int serial, List<CachedTextureRequestArg> cachedTextureRequest)
704 {
705 // m_log.DebugFormat("[AVFACTORY]: Client_OnCachedTextureRequest called for {0} ({1})", client.Name, client.AgentId);
706 ScenePresence sp = m_scene.GetScenePresence(client.AgentId);
707  
708 List<CachedTextureResponseArg> cachedTextureResponse = new List<CachedTextureResponseArg>();
709 foreach (CachedTextureRequestArg request in cachedTextureRequest)
710 {
711 UUID texture = UUID.Zero;
712 int index = request.BakedTextureIndex;
713  
714 if (m_reusetextures)
715 {
716 if (sp.Appearance.GetTextureHash(index) == request.WearableHashID)
717 {
718 Primitive.TextureEntryFace face = sp.Appearance.Texture.FaceTextures[index];
719 if (face != null)
720 texture = face.TextureID;
721 }
722 else
723 {
724 // We know that that hash is wrong, null it out
725 // and wait for the setappearance call
726 sp.Appearance.SetTextureHash(index,UUID.Zero);
727 }
728  
729 // m_log.WarnFormat("[AVFACTORY]: use texture {0} for index {1}; hash={2}",texture,index,request.WearableHashID);
730 }
731  
732 CachedTextureResponseArg response = new CachedTextureResponseArg();
733 response.BakedTextureIndex = index;
734 response.BakedTextureID = texture;
735 response.HostName = null;
736  
737 cachedTextureResponse.Add(response);
738 }
739  
740 // m_log.WarnFormat("[AVFACTORY]: serial is {0}",serial);
741 // The serial number appears to be used to match requests and responses
742 // in the texture transaction. We just send back the serial number
743 // that was provided in the request. The viewer bumps this for us.
744 client.SendCachedTextureResponse(sp, serial, cachedTextureResponse);
745 }
746  
747  
748 #endregion
749  
750 public void WriteBakedTexturesReport(IScenePresence sp, ReportOutputAction outputAction)
751 {
752 outputAction("For {0} in {1}", sp.Name, m_scene.RegionInfo.RegionName);
753 outputAction(BAKED_TEXTURES_REPORT_FORMAT, "Bake Type", "UUID");
754  
755 Dictionary<BakeType, Primitive.TextureEntryFace> bakedTextures = GetBakedTextureFaces(sp.UUID);
756  
757 foreach (BakeType bt in bakedTextures.Keys)
758 {
759 string rawTextureID;
760  
761 if (bakedTextures[bt] == null)
762 {
763 rawTextureID = "not set";
764 }
765 else
766 {
767 rawTextureID = bakedTextures[bt].TextureID.ToString();
768  
769 if (m_scene.AssetService.Get(rawTextureID) == null)
770 rawTextureID += " (not found)";
771 else
772 rawTextureID += " (uploaded)";
773 }
774  
775 outputAction(BAKED_TEXTURES_REPORT_FORMAT, bt, rawTextureID);
776 }
777  
778 bool bakedTextureValid = m_scene.AvatarFactory.ValidateBakedTextureCache(sp);
779 outputAction("{0} baked appearance texture is {1}", sp.Name, bakedTextureValid ? "OK" : "incomplete");
780 }
781 }
782 }