MaterialsModule.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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.Security.Cryptography; // for computing md5 hash
  32. using log4net;
  33. using Mono.Addins;
  34. using Nini.Config;
  35. using OpenMetaverse;
  36. using OpenMetaverse.StructuredData;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Servers;
  39. using OpenSim.Framework.Servers.HttpServer;
  40. using OpenSim.Region.Framework.Interfaces;
  41. using OpenSim.Region.Framework.Scenes;
  42. using OpenSimAssetType = OpenSim.Framework.SLUtil.OpenSimAssetType;
  43. using Ionic.Zlib;
  44. // You will need to uncomment these lines if you are adding a region module to some other assembly which does not already
  45. // specify its assembly. Otherwise, the region modules in the assembly will not be picked up when OpenSimulator scans
  46. // the available DLLs
  47. //[assembly: Addin("MaterialsModule", "1.0")]
  48. //[assembly: AddinDependency("OpenSim", "0.5")]
  49. namespace OpenSim.Region.OptionalModules.Materials
  50. {
  51. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MaterialsModule")]
  52. public class MaterialsModule : INonSharedRegionModule
  53. {
  54. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  55. public string Name { get { return "MaterialsModule"; } }
  56. public Type ReplaceableInterface { get { return null; } }
  57. private Scene m_scene = null;
  58. private bool m_enabled = false;
  59. public Dictionary<UUID, OSDMap> m_regionMaterials = new Dictionary<UUID, OSDMap>();
  60. public void Initialise(IConfigSource source)
  61. {
  62. IConfig config = source.Configs["Materials"];
  63. if (config == null)
  64. return;
  65. m_enabled = config.GetBoolean("enable_materials", true);
  66. if (!m_enabled)
  67. return;
  68. m_log.DebugFormat("[Materials]: Initialized");
  69. }
  70. public void Close()
  71. {
  72. if (!m_enabled)
  73. return;
  74. }
  75. public void AddRegion(Scene scene)
  76. {
  77. if (!m_enabled)
  78. return;
  79. m_scene = scene;
  80. m_scene.EventManager.OnRegisterCaps += OnRegisterCaps;
  81. m_scene.EventManager.OnObjectAddedToScene += EventManager_OnObjectAddedToScene;
  82. }
  83. private void EventManager_OnObjectAddedToScene(SceneObjectGroup obj)
  84. {
  85. foreach (var part in obj.Parts)
  86. if (part != null)
  87. GetStoredMaterialsInPart(part);
  88. }
  89. private void OnRegisterCaps(OpenMetaverse.UUID agentID, OpenSim.Framework.Capabilities.Caps caps)
  90. {
  91. string capsBase = "/CAPS/" + caps.CapsObjectPath;
  92. IRequestHandler renderMaterialsPostHandler
  93. = new RestStreamHandler("POST", capsBase + "/",
  94. (request, path, param, httpRequest, httpResponse)
  95. => RenderMaterialsPostCap(request, agentID),
  96. "RenderMaterials", null);
  97. caps.RegisterHandler("RenderMaterials", renderMaterialsPostHandler);
  98. // OpenSimulator CAPs infrastructure seems to be somewhat hostile towards any CAP that requires both GET
  99. // and POST handlers, (at least at the time this was originally written), so we first set up a POST
  100. // handler normally and then add a GET handler via MainServer
  101. IRequestHandler renderMaterialsGetHandler
  102. = new RestStreamHandler("GET", capsBase + "/",
  103. (request, path, param, httpRequest, httpResponse)
  104. => RenderMaterialsGetCap(request),
  105. "RenderMaterials", null);
  106. MainServer.Instance.AddStreamHandler(renderMaterialsGetHandler);
  107. // materials viewer seems to use either POST or PUT, so assign POST handler for PUT as well
  108. IRequestHandler renderMaterialsPutHandler
  109. = new RestStreamHandler("PUT", capsBase + "/",
  110. (request, path, param, httpRequest, httpResponse)
  111. => RenderMaterialsPostCap(request, agentID),
  112. "RenderMaterials", null);
  113. MainServer.Instance.AddStreamHandler(renderMaterialsPutHandler);
  114. }
  115. public void RemoveRegion(Scene scene)
  116. {
  117. if (!m_enabled)
  118. return;
  119. m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
  120. m_scene.EventManager.OnObjectAddedToScene -= EventManager_OnObjectAddedToScene;
  121. }
  122. public void RegionLoaded(Scene scene)
  123. {
  124. }
  125. /// <summary>
  126. /// Finds any legacy materials stored in DynAttrs that may exist for this part and add them to 'm_regionMaterials'.
  127. /// </summary>
  128. /// <param name="part"></param>
  129. private void GetLegacyStoredMaterialsInPart(SceneObjectPart part)
  130. {
  131. if (part.DynAttrs == null)
  132. return;
  133. OSD OSMaterials = null;
  134. OSDArray matsArr = null;
  135. lock (part.DynAttrs)
  136. {
  137. if (part.DynAttrs.ContainsStore("OpenSim", "Materials"))
  138. {
  139. OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials");
  140. if (materialsStore == null)
  141. return;
  142. materialsStore.TryGetValue("Materials", out OSMaterials);
  143. }
  144. if (OSMaterials != null && OSMaterials is OSDArray)
  145. matsArr = OSMaterials as OSDArray;
  146. else
  147. return;
  148. }
  149. if (matsArr == null)
  150. return;
  151. foreach (OSD elemOsd in matsArr)
  152. {
  153. if (elemOsd != null && elemOsd is OSDMap)
  154. {
  155. OSDMap matMap = elemOsd as OSDMap;
  156. if (matMap.ContainsKey("ID") && matMap.ContainsKey("Material"))
  157. {
  158. try
  159. {
  160. lock (m_regionMaterials)
  161. m_regionMaterials[matMap["ID"].AsUUID()] = (OSDMap)matMap["Material"];
  162. }
  163. catch (Exception e)
  164. {
  165. m_log.Warn("[Materials]: exception decoding persisted legacy material: " + e.ToString());
  166. }
  167. }
  168. }
  169. }
  170. }
  171. /// <summary>
  172. /// Find the materials used in the SOP, and add them to 'm_regionMaterials'.
  173. /// </summary>
  174. private void GetStoredMaterialsInPart(SceneObjectPart part)
  175. {
  176. if (part.Shape == null)
  177. return;
  178. var te = new Primitive.TextureEntry(part.Shape.TextureEntry, 0, part.Shape.TextureEntry.Length);
  179. if (te == null)
  180. return;
  181. GetLegacyStoredMaterialsInPart(part);
  182. GetStoredMaterialInFace(part, te.DefaultTexture);
  183. foreach (Primitive.TextureEntryFace face in te.FaceTextures)
  184. {
  185. if (face != null)
  186. GetStoredMaterialInFace(part, face);
  187. }
  188. }
  189. /// <summary>
  190. /// Find the materials used in one Face, and add them to 'm_regionMaterials'.
  191. /// </summary>
  192. private void GetStoredMaterialInFace(SceneObjectPart part, Primitive.TextureEntryFace face)
  193. {
  194. UUID id = face.MaterialID;
  195. if (id == UUID.Zero)
  196. return;
  197. lock (m_regionMaterials)
  198. {
  199. if (m_regionMaterials.ContainsKey(id))
  200. return;
  201. byte[] data = m_scene.AssetService.GetData(id.ToString());
  202. if (data == null)
  203. {
  204. m_log.WarnFormat("[Materials]: Prim \"{0}\" ({1}) contains unknown material ID {2}", part.Name, part.UUID, id);
  205. return;
  206. }
  207. OSDMap mat;
  208. try
  209. {
  210. mat = (OSDMap)OSDParser.DeserializeLLSDXml(data);
  211. }
  212. catch (Exception e)
  213. {
  214. m_log.WarnFormat("[Materials]: cannot decode material asset {0}: {1}", id, e.Message);
  215. return;
  216. }
  217. m_regionMaterials[id] = mat;
  218. }
  219. }
  220. public string RenderMaterialsPostCap(string request, UUID agentID)
  221. {
  222. OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
  223. OSDMap resp = new OSDMap();
  224. OSDMap materialsFromViewer = null;
  225. OSDArray respArr = new OSDArray();
  226. if (req.ContainsKey("Zipped"))
  227. {
  228. OSD osd = null;
  229. byte[] inBytes = req["Zipped"].AsBinary();
  230. try
  231. {
  232. osd = ZDecompressBytesToOsd(inBytes);
  233. if (osd != null)
  234. {
  235. if (osd is OSDArray) // assume array of MaterialIDs designating requested material entries
  236. {
  237. foreach (OSD elem in (OSDArray)osd)
  238. {
  239. try
  240. {
  241. UUID id = new UUID(elem.AsBinary(), 0);
  242. lock (m_regionMaterials)
  243. {
  244. if (m_regionMaterials.ContainsKey(id))
  245. {
  246. OSDMap matMap = new OSDMap();
  247. matMap["ID"] = OSD.FromBinary(id.GetBytes());
  248. matMap["Material"] = m_regionMaterials[id];
  249. respArr.Add(matMap);
  250. }
  251. else
  252. {
  253. m_log.Warn("[Materials]: request for unknown material ID: " + id.ToString());
  254. // Theoretically we could try to load the material from the assets service,
  255. // but that shouldn't be necessary because the viewer should only request
  256. // materials that exist in a prim on the region, and all of these materials
  257. // are already stored in m_regionMaterials.
  258. }
  259. }
  260. }
  261. catch (Exception e)
  262. {
  263. m_log.Error("Error getting materials in response to viewer request", e);
  264. continue;
  265. }
  266. }
  267. }
  268. else if (osd is OSDMap) // request to assign a material
  269. {
  270. materialsFromViewer = osd as OSDMap;
  271. if (materialsFromViewer.ContainsKey("FullMaterialsPerFace"))
  272. {
  273. OSD matsOsd = materialsFromViewer["FullMaterialsPerFace"];
  274. if (matsOsd is OSDArray)
  275. {
  276. OSDArray matsArr = matsOsd as OSDArray;
  277. try
  278. {
  279. foreach (OSDMap matsMap in matsArr)
  280. {
  281. uint primLocalID = 0;
  282. try {
  283. primLocalID = matsMap["ID"].AsUInteger();
  284. }
  285. catch (Exception e) {
  286. m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message);
  287. continue;
  288. }
  289. OSDMap mat = null;
  290. try
  291. {
  292. mat = matsMap["Material"] as OSDMap;
  293. }
  294. catch (Exception e)
  295. {
  296. m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message);
  297. continue;
  298. }
  299. SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID);
  300. if (sop == null)
  301. {
  302. m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString());
  303. continue;
  304. }
  305. if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID))
  306. {
  307. m_log.WarnFormat("User {0} can't edit object {1} {2}", agentID, sop.Name, sop.UUID);
  308. continue;
  309. }
  310. Primitive.TextureEntry te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length);
  311. if (te == null)
  312. {
  313. m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID);
  314. continue;
  315. }
  316. UUID id;
  317. if (mat == null)
  318. {
  319. // This happens then the user removes a material from a prim
  320. id = UUID.Zero;
  321. }
  322. else
  323. {
  324. id = StoreMaterialAsAsset(agentID, mat, sop);
  325. }
  326. int face = -1;
  327. if (matsMap.ContainsKey("Face"))
  328. {
  329. face = matsMap["Face"].AsInteger();
  330. Primitive.TextureEntryFace faceEntry = te.CreateFace((uint)face);
  331. faceEntry.MaterialID = id;
  332. }
  333. else
  334. {
  335. if (te.DefaultTexture == null)
  336. m_log.WarnFormat("[Materials]: TextureEntry.DefaultTexture is null in {0} {1}", sop.Name, sop.UUID);
  337. else
  338. te.DefaultTexture.MaterialID = id;
  339. }
  340. //m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id);
  341. // We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually
  342. sop.Shape.TextureEntry = te.GetBytes();
  343. if (sop.ParentGroup != null)
  344. {
  345. sop.TriggerScriptChangedEvent(Changed.TEXTURE);
  346. sop.UpdateFlag = UpdateRequired.FULL;
  347. sop.ParentGroup.HasGroupChanged = true;
  348. sop.ScheduleFullUpdate();
  349. }
  350. }
  351. }
  352. catch (Exception e)
  353. {
  354. m_log.Warn("[Materials]: exception processing received material ", e);
  355. }
  356. }
  357. }
  358. }
  359. }
  360. }
  361. catch (Exception e)
  362. {
  363. m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e);
  364. //return "";
  365. }
  366. }
  367. resp["Zipped"] = ZCompressOSD(respArr, false);
  368. string response = OSDParser.SerializeLLSDXmlString(resp);
  369. //m_log.Debug("[Materials]: cap request: " + request);
  370. //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
  371. //m_log.Debug("[Materials]: cap response: " + response);
  372. return response;
  373. }
  374. private UUID StoreMaterialAsAsset(UUID agentID, OSDMap mat, SceneObjectPart sop)
  375. {
  376. UUID id;
  377. // Material UUID = hash of the material's data.
  378. // This makes materials deduplicate across the entire grid (but isn't otherwise required).
  379. byte[] data = System.Text.Encoding.ASCII.GetBytes(OSDParser.SerializeLLSDXmlString(mat));
  380. using (var md5 = MD5.Create())
  381. id = new UUID(md5.ComputeHash(data), 0);
  382. lock (m_regionMaterials)
  383. {
  384. if (!m_regionMaterials.ContainsKey(id))
  385. {
  386. m_regionMaterials[id] = mat;
  387. // This asset might exist already, but it's ok to try to store it again
  388. string name = "Material " + ChooseMaterialName(mat, sop);
  389. name = name.Substring(0, Math.Min(64, name.Length)).Trim();
  390. AssetBase asset = new AssetBase(id, name, (sbyte)OpenSimAssetType.Material, agentID.ToString());
  391. asset.Data = data;
  392. m_scene.AssetService.Store(asset);
  393. }
  394. }
  395. return id;
  396. }
  397. /// <summary>
  398. /// Use heuristics to choose a good name for the material.
  399. /// </summary>
  400. private string ChooseMaterialName(OSDMap mat, SceneObjectPart sop)
  401. {
  402. UUID normMap = mat["NormMap"].AsUUID();
  403. if (normMap != UUID.Zero)
  404. {
  405. AssetBase asset = m_scene.AssetService.GetCached(normMap.ToString());
  406. if ((asset != null) && (asset.Name.Length > 0) && !asset.Name.Equals("From IAR"))
  407. return asset.Name;
  408. }
  409. UUID specMap = mat["SpecMap"].AsUUID();
  410. if (specMap != UUID.Zero)
  411. {
  412. AssetBase asset = m_scene.AssetService.GetCached(specMap.ToString());
  413. if ((asset != null) && (asset.Name.Length > 0) && !asset.Name.Equals("From IAR"))
  414. return asset.Name;
  415. }
  416. if (sop.Name != "Primitive")
  417. return sop.Name;
  418. if ((sop.ParentGroup != null) && (sop.ParentGroup.Name != "Primitive"))
  419. return sop.ParentGroup.Name;
  420. return "";
  421. }
  422. public string RenderMaterialsGetCap(string request)
  423. {
  424. OSDMap resp = new OSDMap();
  425. int matsCount = 0;
  426. OSDArray allOsd = new OSDArray();
  427. lock (m_regionMaterials)
  428. {
  429. foreach (KeyValuePair<UUID, OSDMap> kvp in m_regionMaterials)
  430. {
  431. OSDMap matMap = new OSDMap();
  432. matMap["ID"] = OSD.FromBinary(kvp.Key.GetBytes());
  433. matMap["Material"] = kvp.Value;
  434. allOsd.Add(matMap);
  435. matsCount++;
  436. }
  437. }
  438. resp["Zipped"] = ZCompressOSD(allOsd, false);
  439. return OSDParser.SerializeLLSDXmlString(resp);
  440. }
  441. private static string ZippedOsdBytesToString(byte[] bytes)
  442. {
  443. try
  444. {
  445. return OSDParser.SerializeJsonString(ZDecompressBytesToOsd(bytes));
  446. }
  447. catch (Exception e)
  448. {
  449. return "ZippedOsdBytesToString caught an exception: " + e.ToString();
  450. }
  451. }
  452. /// <summary>
  453. /// computes a UUID by hashing a OSD object
  454. /// </summary>
  455. /// <param name="osd"></param>
  456. /// <returns></returns>
  457. private static UUID HashOsd(OSD osd)
  458. {
  459. byte[] data = OSDParser.SerializeLLSDBinary(osd, false);
  460. using (var md5 = MD5.Create())
  461. return new UUID(md5.ComputeHash(data), 0);
  462. }
  463. public static OSD ZCompressOSD(OSD inOsd, bool useHeader)
  464. {
  465. OSD osd = null;
  466. byte[] data = OSDParser.SerializeLLSDBinary(inOsd, useHeader);
  467. using (MemoryStream msSinkCompressed = new MemoryStream())
  468. {
  469. using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkCompressed,
  470. Ionic.Zlib.CompressionMode.Compress, CompressionLevel.BestCompression, true))
  471. {
  472. zOut.Write(data, 0, data.Length);
  473. }
  474. msSinkCompressed.Seek(0L, SeekOrigin.Begin);
  475. osd = OSD.FromBinary(msSinkCompressed.ToArray());
  476. }
  477. return osd;
  478. }
  479. public static OSD ZDecompressBytesToOsd(byte[] input)
  480. {
  481. OSD osd = null;
  482. using (MemoryStream msSinkUnCompressed = new MemoryStream())
  483. {
  484. using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkUnCompressed, CompressionMode.Decompress, true))
  485. {
  486. zOut.Write(input, 0, input.Length);
  487. }
  488. msSinkUnCompressed.Seek(0L, SeekOrigin.Begin);
  489. osd = OSDParser.DeserializeLLSDBinary(msSinkUnCompressed.ToArray());
  490. }
  491. return osd;
  492. }
  493. }
  494. }