UuidGatherer.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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.IO;
  30. using System.Reflection;
  31. using System.Text.RegularExpressions;
  32. using System.Threading;
  33. using log4net;
  34. using OpenMetaverse;
  35. using OpenMetaverse.Assets;
  36. using OpenMetaverse.StructuredData;
  37. using OpenSim.Framework;
  38. using OpenSim.Region.Framework.Scenes.Serialization;
  39. using OpenSim.Services.Interfaces;
  40. namespace OpenSim.Region.Framework.Scenes
  41. {
  42. /// <summary>
  43. /// Gather uuids for a given entity.
  44. /// </summary>
  45. /// <remarks>
  46. /// This does a deep inspection of the entity to retrieve all the assets it uses (whether as textures, as scripts
  47. /// contained in inventory, as scripts contained in objects contained in another object's inventory, etc. Assets
  48. /// are only retrieved when they are necessary to carry out the inspection (i.e. a serialized object needs to be
  49. /// retrieved to work out which assets it references).
  50. /// </remarks>
  51. public class UuidGatherer
  52. {
  53. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  54. protected IAssetService m_assetService;
  55. // /// <summary>
  56. // /// Used as a temporary store of an asset which represents an object. This can be a null if no appropriate
  57. // /// asset was found by the asset service.
  58. // /// </summary>
  59. // private AssetBase m_requestedObjectAsset;
  60. //
  61. // /// <summary>
  62. // /// Signal whether we are currently waiting for the asset service to deliver an asset.
  63. // /// </summary>
  64. // private bool m_waitingForObjectAsset;
  65. public UuidGatherer(IAssetService assetService)
  66. {
  67. m_assetService = assetService;
  68. }
  69. /// <summary>
  70. /// Gather all the asset uuids associated with the asset referenced by a given uuid
  71. /// </summary>
  72. /// <remarks>
  73. /// This includes both those directly associated with
  74. /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained
  75. /// within this object).
  76. /// </remarks>
  77. /// <param name="assetUuid">The uuid of the asset for which to gather referenced assets</param>
  78. /// <param name="assetType">The type of the asset for the uuid given</param>
  79. /// <param name="assetUuids">The assets gathered</param>
  80. public void GatherAssetUuids(UUID assetUuid, AssetType assetType, IDictionary<UUID, AssetType> assetUuids)
  81. {
  82. // avoid infinite loops
  83. if (assetUuids.ContainsKey(assetUuid))
  84. return;
  85. try
  86. {
  87. assetUuids[assetUuid] = assetType;
  88. if (AssetType.Bodypart == assetType || AssetType.Clothing == assetType)
  89. {
  90. GetWearableAssetUuids(assetUuid, assetUuids);
  91. }
  92. else if (AssetType.Gesture == assetType)
  93. {
  94. GetGestureAssetUuids(assetUuid, assetUuids);
  95. }
  96. else if (AssetType.Notecard == assetType)
  97. {
  98. GetTextEmbeddedAssetUuids(assetUuid, assetUuids);
  99. }
  100. else if (AssetType.LSLText == assetType)
  101. {
  102. GetTextEmbeddedAssetUuids(assetUuid, assetUuids);
  103. }
  104. else if (AssetType.Object == assetType)
  105. {
  106. GetSceneObjectAssetUuids(assetUuid, assetUuids);
  107. }
  108. }
  109. catch (Exception)
  110. {
  111. m_log.ErrorFormat(
  112. "[UUID GATHERER]: Failed to gather uuids for asset id {0}, type {1}",
  113. assetUuid, assetType);
  114. throw;
  115. }
  116. }
  117. /// <summary>
  118. /// Gather all the asset uuids associated with a given object.
  119. /// </summary>
  120. /// <remarks>
  121. /// This includes both those directly associated with
  122. /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained
  123. /// within this object).
  124. /// </remarks>
  125. /// <param name="sceneObject">The scene object for which to gather assets</param>
  126. /// <param name="assetUuids">
  127. /// A dictionary which is populated with the asset UUIDs gathered and the type of that asset.
  128. /// For assets where the type is not clear (e.g. UUIDs extracted from LSL and notecards), the type is Unknown.
  129. /// </param>
  130. public void GatherAssetUuids(SceneObjectGroup sceneObject, IDictionary<UUID, AssetType> assetUuids)
  131. {
  132. // m_log.DebugFormat(
  133. // "[ASSET GATHERER]: Getting assets for object {0}, {1}", sceneObject.Name, sceneObject.UUID);
  134. SceneObjectPart[] parts = sceneObject.Parts;
  135. for (int i = 0; i < parts.Length; i++)
  136. {
  137. SceneObjectPart part = parts[i];
  138. // m_log.DebugFormat(
  139. // "[ARCHIVER]: Getting part {0}, {1} for object {2}", part.Name, part.UUID, sceneObject.UUID);
  140. try
  141. {
  142. Primitive.TextureEntry textureEntry = part.Shape.Textures;
  143. if (textureEntry != null)
  144. {
  145. // Get the prim's default texture. This will be used for faces which don't have their own texture
  146. if (textureEntry.DefaultTexture != null)
  147. assetUuids[textureEntry.DefaultTexture.TextureID] = AssetType.Texture;
  148. if (textureEntry.FaceTextures != null)
  149. {
  150. // Loop through the rest of the texture faces (a non-null face means the face is different from DefaultTexture)
  151. foreach (Primitive.TextureEntryFace texture in textureEntry.FaceTextures)
  152. {
  153. if (texture != null)
  154. assetUuids[texture.TextureID] = AssetType.Texture;
  155. }
  156. }
  157. }
  158. // If the prim is a sculpt then preserve this information too
  159. if (part.Shape.SculptTexture != UUID.Zero)
  160. assetUuids[part.Shape.SculptTexture] = AssetType.Texture;
  161. TaskInventoryDictionary taskDictionary = (TaskInventoryDictionary)part.TaskInventory.Clone();
  162. // Now analyze this prim's inventory items to preserve all the uuids that they reference
  163. foreach (TaskInventoryItem tii in taskDictionary.Values)
  164. {
  165. // m_log.DebugFormat(
  166. // "[ARCHIVER]: Analysing item {0} asset type {1} in {2} {3}",
  167. // tii.Name, tii.Type, part.Name, part.UUID);
  168. if (!assetUuids.ContainsKey(tii.AssetID))
  169. GatherAssetUuids(tii.AssetID, (AssetType)tii.Type, assetUuids);
  170. }
  171. // FIXME: We need to make gathering modular but we cannot yet, since gatherers are not guaranteed
  172. // to be called with scene objects that are in a scene (e.g. in the case of hg asset mapping and
  173. // inventory transfer. There needs to be a way for a module to register a method without assuming a
  174. // Scene.EventManager is present.
  175. // part.ParentGroup.Scene.EventManager.TriggerGatherUuids(part, assetUuids);
  176. GatherMaterialsUuids(part, assetUuids);
  177. }
  178. catch (Exception e)
  179. {
  180. m_log.ErrorFormat("[UUID GATHERER]: Failed to get part - {0}", e);
  181. m_log.DebugFormat(
  182. "[UUID GATHERER]: Texture entry length for prim was {0} (min is 46)",
  183. part.Shape.TextureEntry.Length);
  184. }
  185. }
  186. }
  187. // /// <summary>
  188. // /// The callback made when we request the asset for an object from the asset service.
  189. // /// </summary>
  190. // private void AssetReceived(string id, Object sender, AssetBase asset)
  191. // {
  192. // lock (this)
  193. // {
  194. // m_requestedObjectAsset = asset;
  195. // m_waitingForObjectAsset = false;
  196. // Monitor.Pulse(this);
  197. // }
  198. // }
  199. /// <summary>
  200. /// Gather all of the texture asset UUIDs used to reference "Materials" such as normal and specular maps
  201. /// </summary>
  202. /// <param name="part"></param>
  203. /// <param name="assetUuids"></param>
  204. public void GatherMaterialsUuids(SceneObjectPart part, IDictionary<UUID, AssetType> assetUuids)
  205. {
  206. // scan thru the dynAttrs map of this part for any textures used as materials
  207. OSD osdMaterials = null;
  208. lock (part.DynAttrs)
  209. {
  210. if (part.DynAttrs.ContainsStore("OpenSim", "Materials"))
  211. {
  212. OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials");
  213. if (materialsStore == null)
  214. return;
  215. materialsStore.TryGetValue("Materials", out osdMaterials);
  216. }
  217. if (osdMaterials != null)
  218. {
  219. //m_log.Info("[UUID Gatherer]: found Materials: " + OSDParser.SerializeJsonString(osd));
  220. if (osdMaterials is OSDArray)
  221. {
  222. OSDArray matsArr = osdMaterials as OSDArray;
  223. foreach (OSDMap matMap in matsArr)
  224. {
  225. try
  226. {
  227. if (matMap.ContainsKey("Material"))
  228. {
  229. OSDMap mat = matMap["Material"] as OSDMap;
  230. if (mat.ContainsKey("NormMap"))
  231. {
  232. UUID normalMapId = mat["NormMap"].AsUUID();
  233. if (normalMapId != UUID.Zero)
  234. {
  235. assetUuids[normalMapId] = AssetType.Texture;
  236. //m_log.Info("[UUID Gatherer]: found normal map ID: " + normalMapId.ToString());
  237. }
  238. }
  239. if (mat.ContainsKey("SpecMap"))
  240. {
  241. UUID specularMapId = mat["SpecMap"].AsUUID();
  242. if (specularMapId != UUID.Zero)
  243. {
  244. assetUuids[specularMapId] = AssetType.Texture;
  245. //m_log.Info("[UUID Gatherer]: found specular map ID: " + specularMapId.ToString());
  246. }
  247. }
  248. }
  249. }
  250. catch (Exception e)
  251. {
  252. m_log.Warn("[UUID Gatherer]: exception getting materials: " + e.Message);
  253. }
  254. }
  255. }
  256. }
  257. }
  258. }
  259. /// <summary>
  260. /// Get an asset synchronously, potentially using an asynchronous callback. If the
  261. /// asynchronous callback is used, we will wait for it to complete.
  262. /// </summary>
  263. /// <param name="uuid"></param>
  264. /// <returns></returns>
  265. protected virtual AssetBase GetAsset(UUID uuid)
  266. {
  267. return m_assetService.Get(uuid.ToString());
  268. // XXX: Switching to do this synchronously where the call was async before but we always waited for it
  269. // to complete anyway!
  270. // m_waitingForObjectAsset = true;
  271. // m_assetCache.Get(uuid.ToString(), this, AssetReceived);
  272. //
  273. // // The asset cache callback can either
  274. // //
  275. // // 1. Complete on the same thread (if the asset is already in the cache) or
  276. // // 2. Come in via a different thread (if we need to go fetch it).
  277. // //
  278. // // The code below handles both these alternatives.
  279. // lock (this)
  280. // {
  281. // if (m_waitingForObjectAsset)
  282. // {
  283. // Monitor.Wait(this);
  284. // m_waitingForObjectAsset = false;
  285. // }
  286. // }
  287. //
  288. // return m_requestedObjectAsset;
  289. }
  290. /// <summary>
  291. /// Record the asset uuids embedded within the given script.
  292. /// </summary>
  293. /// <param name="scriptUuid"></param>
  294. /// <param name="assetUuids">Dictionary in which to record the references</param>
  295. private void GetTextEmbeddedAssetUuids(UUID embeddingAssetId, IDictionary<UUID, AssetType> assetUuids)
  296. {
  297. // m_log.DebugFormat("[ASSET GATHERER]: Getting assets for uuid references in asset {0}", embeddingAssetId);
  298. AssetBase embeddingAsset = GetAsset(embeddingAssetId);
  299. if (null != embeddingAsset)
  300. {
  301. string script = Utils.BytesToString(embeddingAsset.Data);
  302. // m_log.DebugFormat("[ARCHIVER]: Script {0}", script);
  303. MatchCollection uuidMatches = Util.PermissiveUUIDPattern.Matches(script);
  304. // m_log.DebugFormat("[ARCHIVER]: Found {0} matches in text", uuidMatches.Count);
  305. foreach (Match uuidMatch in uuidMatches)
  306. {
  307. UUID uuid = new UUID(uuidMatch.Value);
  308. // m_log.DebugFormat("[ARCHIVER]: Recording {0} in text", uuid);
  309. // Embedded asset references (if not false positives) could be for many types of asset, so we will
  310. // label these as unknown.
  311. assetUuids[uuid] = AssetType.Unknown;
  312. }
  313. }
  314. }
  315. /// <summary>
  316. /// Record the uuids referenced by the given wearable asset
  317. /// </summary>
  318. /// <param name="wearableAssetUuid"></param>
  319. /// <param name="assetUuids">Dictionary in which to record the references</param>
  320. private void GetWearableAssetUuids(UUID wearableAssetUuid, IDictionary<UUID, AssetType> assetUuids)
  321. {
  322. AssetBase assetBase = GetAsset(wearableAssetUuid);
  323. if (null != assetBase)
  324. {
  325. //m_log.Debug(new System.Text.ASCIIEncoding().GetString(bodypartAsset.Data));
  326. AssetWearable wearableAsset = new AssetBodypart(wearableAssetUuid, assetBase.Data);
  327. wearableAsset.Decode();
  328. //m_log.DebugFormat(
  329. // "[ARCHIVER]: Wearable asset {0} references {1} assets", wearableAssetUuid, wearableAsset.Textures.Count);
  330. foreach (UUID uuid in wearableAsset.Textures.Values)
  331. {
  332. assetUuids[uuid] = AssetType.Texture;
  333. }
  334. }
  335. }
  336. /// <summary>
  337. /// Get all the asset uuids associated with a given object. This includes both those directly associated with
  338. /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained
  339. /// within this object).
  340. /// </summary>
  341. /// <param name="sceneObject"></param>
  342. /// <param name="assetUuids"></param>
  343. private void GetSceneObjectAssetUuids(UUID sceneObjectUuid, IDictionary<UUID, AssetType> assetUuids)
  344. {
  345. AssetBase objectAsset = GetAsset(sceneObjectUuid);
  346. if (null != objectAsset)
  347. {
  348. string xml = Utils.BytesToString(objectAsset.Data);
  349. CoalescedSceneObjects coa;
  350. if (CoalescedSceneObjectsSerializer.TryFromXml(xml, out coa))
  351. {
  352. foreach (SceneObjectGroup sog in coa.Objects)
  353. GatherAssetUuids(sog, assetUuids);
  354. }
  355. else
  356. {
  357. SceneObjectGroup sog = SceneObjectSerializer.FromOriginalXmlFormat(xml);
  358. if (null != sog)
  359. GatherAssetUuids(sog, assetUuids);
  360. }
  361. }
  362. }
  363. /// <summary>
  364. /// Get the asset uuid associated with a gesture
  365. /// </summary>
  366. /// <param name="gestureUuid"></param>
  367. /// <param name="assetUuids"></param>
  368. private void GetGestureAssetUuids(UUID gestureUuid, IDictionary<UUID, AssetType> assetUuids)
  369. {
  370. AssetBase assetBase = GetAsset(gestureUuid);
  371. if (null == assetBase)
  372. return;
  373. MemoryStream ms = new MemoryStream(assetBase.Data);
  374. StreamReader sr = new StreamReader(ms);
  375. sr.ReadLine(); // Unknown (Version?)
  376. sr.ReadLine(); // Unknown
  377. sr.ReadLine(); // Unknown
  378. sr.ReadLine(); // Name
  379. sr.ReadLine(); // Comment ?
  380. int count = Convert.ToInt32(sr.ReadLine()); // Item count
  381. for (int i = 0 ; i < count ; i++)
  382. {
  383. string type = sr.ReadLine();
  384. if (type == null)
  385. break;
  386. string name = sr.ReadLine();
  387. if (name == null)
  388. break;
  389. string id = sr.ReadLine();
  390. if (id == null)
  391. break;
  392. string unknown = sr.ReadLine();
  393. if (unknown == null)
  394. break;
  395. // If it can be parsed as a UUID, it is an asset ID
  396. UUID uuid;
  397. if (UUID.TryParse(id, out uuid))
  398. assetUuids[uuid] = AssetType.Animation;
  399. }
  400. }
  401. }
  402. public class HGUuidGatherer : UuidGatherer
  403. {
  404. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  405. protected string m_assetServerURL;
  406. public HGUuidGatherer(IAssetService assetService, string assetServerURL)
  407. : base(assetService)
  408. {
  409. m_assetServerURL = assetServerURL;
  410. if (!m_assetServerURL.EndsWith("/") && !m_assetServerURL.EndsWith("="))
  411. m_assetServerURL = m_assetServerURL + "/";
  412. }
  413. protected override AssetBase GetAsset(UUID uuid)
  414. {
  415. if (string.Empty == m_assetServerURL)
  416. return base.GetAsset(uuid);
  417. else
  418. return FetchAsset(uuid);
  419. }
  420. public AssetBase FetchAsset(UUID assetID)
  421. {
  422. // Test if it's already here
  423. AssetBase asset = m_assetService.Get(assetID.ToString());
  424. if (asset == null)
  425. {
  426. // It's not, so fetch it from abroad
  427. asset = m_assetService.Get(m_assetServerURL + assetID.ToString());
  428. if (asset != null)
  429. m_log.DebugFormat("[HGUUIDGatherer]: Copied asset {0} from {1} to local asset server", assetID, m_assetServerURL);
  430. else
  431. m_log.DebugFormat("[HGUUIDGatherer]: Failed to fetch asset {0} from {1}", assetID, m_assetServerURL);
  432. }
  433. //else
  434. // m_log.DebugFormat("[HGUUIDGatherer]: Asset {0} from {1} was already here", assetID, m_assetServerURL);
  435. return asset;
  436. }
  437. }
  438. }