MaterialsModule.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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. namespace OpenSim.Region.OptionalModules.Materials
  45. {
  46. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MaterialsModule")]
  47. public class MaterialsModule : INonSharedRegionModule, IMaterialsModule
  48. {
  49. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  50. public string Name { get { return "MaterialsModule"; } }
  51. public Type ReplaceableInterface { get { return null; } }
  52. IAssetCache m_cache;
  53. private Scene m_scene = null;
  54. private bool m_enabled = false;
  55. private int m_maxMaterialsPerTransaction = 50;
  56. private object materialslock = new object();
  57. public Dictionary<UUID, FaceMaterial> m_Materials = new Dictionary<UUID, FaceMaterial>();
  58. public Dictionary<UUID, int> m_MaterialsRefCount = new Dictionary<UUID, int>();
  59. private Dictionary<FaceMaterial, double> m_changed = new Dictionary<FaceMaterial, double>();
  60. public void Initialise(IConfigSource source)
  61. {
  62. m_enabled = true; // default is enabled
  63. IConfig config = source.Configs["Materials"];
  64. if (config != null)
  65. {
  66. m_enabled = config.GetBoolean("enable_materials", m_enabled);
  67. m_maxMaterialsPerTransaction = config.GetInt("MaxMaterialsPerTransaction", m_maxMaterialsPerTransaction);
  68. }
  69. if (m_enabled)
  70. m_log.DebugFormat("[Materials]: Initialized");
  71. }
  72. public void Close()
  73. {
  74. if (!m_enabled)
  75. return;
  76. }
  77. public void AddRegion(Scene scene)
  78. {
  79. if (!m_enabled)
  80. return;
  81. m_scene = scene;
  82. m_scene.RegisterModuleInterface<IMaterialsModule>(this);
  83. m_scene.EventManager.OnRegisterCaps += OnRegisterCaps;
  84. m_scene.EventManager.OnObjectAddedToScene += EventManager_OnObjectAddedToScene;
  85. m_scene.EventManager.OnObjectBeingRemovedFromScene += EventManager_OnObjectDeleteFromScene;
  86. m_scene.EventManager.OnBackup += EventManager_OnBackup;
  87. }
  88. public void RemoveRegion(Scene scene)
  89. {
  90. if (!m_enabled)
  91. return;
  92. m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
  93. m_scene.EventManager.OnObjectAddedToScene -= EventManager_OnObjectAddedToScene;
  94. m_scene.EventManager.OnObjectBeingRemovedFromScene -= EventManager_OnObjectDeleteFromScene;
  95. m_scene.EventManager.OnBackup -= EventManager_OnBackup;
  96. m_scene.UnregisterModuleInterface<IMaterialsModule>(this);
  97. }
  98. public void RegionLoaded(Scene scene)
  99. {
  100. if (!m_enabled) return;
  101. m_cache = scene.RequestModuleInterface<IAssetCache>();
  102. ISimulatorFeaturesModule featuresModule = scene.RequestModuleInterface<ISimulatorFeaturesModule>();
  103. if (featuresModule != null)
  104. featuresModule.OnSimulatorFeaturesRequest += OnSimulatorFeaturesRequest;
  105. }
  106. private void EventManager_OnBackup(ISimulationDataService datastore, bool forcedBackup)
  107. {
  108. List<FaceMaterial> toStore;
  109. lock (materialslock)
  110. {
  111. if(m_changed.Count == 0)
  112. return;
  113. if(forcedBackup)
  114. {
  115. toStore = new List<FaceMaterial>(m_changed.Keys);
  116. m_changed.Clear();
  117. }
  118. else
  119. {
  120. toStore = new List<FaceMaterial>();
  121. double storetime = Util.GetTimeStamp() - 60.0;
  122. foreach(KeyValuePair<FaceMaterial, double> kvp in m_changed)
  123. {
  124. if(kvp.Value < storetime)
  125. {
  126. toStore.Add(kvp.Key);
  127. }
  128. }
  129. foreach(FaceMaterial fm in toStore)
  130. {
  131. m_changed.Remove(fm);
  132. }
  133. }
  134. if(toStore.Count > 0)
  135. Util.FireAndForget(delegate
  136. {
  137. foreach(FaceMaterial fm in toStore)
  138. {
  139. AssetBase a = MakeAsset(fm, false);
  140. m_scene.AssetService.Store(a);
  141. }
  142. });
  143. }
  144. }
  145. private void EventManager_OnObjectAddedToScene(SceneObjectGroup obj)
  146. {
  147. foreach (var part in obj.Parts)
  148. if (part != null)
  149. GetStoredMaterialsInPart(part);
  150. }
  151. private void EventManager_OnObjectDeleteFromScene(SceneObjectGroup obj)
  152. {
  153. foreach (var part in obj.Parts)
  154. if (part != null)
  155. RemoveMaterialsInPart(part);
  156. }
  157. private void OnRegisterCaps(OpenMetaverse.UUID agentID, OpenSim.Framework.Capabilities.Caps caps)
  158. {
  159. string capsBase = "/CAPS/" + caps.CapsObjectPath;
  160. IRequestHandler renderMaterialsPostHandler
  161. = new RestStreamHandler("POST", capsBase + "/",
  162. (request, path, param, httpRequest, httpResponse)
  163. => RenderMaterialsPostCap(request, agentID),
  164. "RenderMaterials", null);
  165. caps.RegisterHandler("RenderMaterials", renderMaterialsPostHandler);
  166. // OpenSimulator CAPs infrastructure seems to be somewhat hostile towards any CAP that requires both GET
  167. // and POST handlers, (at least at the time this was originally written), so we first set up a POST
  168. // handler normally and then add a GET handler via MainServer
  169. IRequestHandler renderMaterialsGetHandler
  170. = new RestStreamHandler("GET", capsBase + "/",
  171. (request, path, param, httpRequest, httpResponse)
  172. => RenderMaterialsGetCap(request),
  173. "RenderMaterials", null);
  174. MainServer.Instance.AddStreamHandler(renderMaterialsGetHandler);
  175. // materials viewer seems to use either POST or PUT, so assign POST handler for PUT as well
  176. IRequestHandler renderMaterialsPutHandler
  177. = new RestStreamHandler("PUT", capsBase + "/",
  178. (request, path, param, httpRequest, httpResponse)
  179. => RenderMaterialsPutCap(request, agentID),
  180. "RenderMaterials", null);
  181. MainServer.Instance.AddStreamHandler(renderMaterialsPutHandler);
  182. }
  183. private void OnSimulatorFeaturesRequest(UUID agentID, ref OSDMap features)
  184. {
  185. features["MaxMaterialsPerTransaction"] = m_maxMaterialsPerTransaction;
  186. }
  187. /// <summary>
  188. /// Finds any legacy materials stored in DynAttrs that may exist for this part and add them to 'm_regionMaterials'.
  189. /// </summary>
  190. /// <param name="part"></param>
  191. private bool GetLegacyStoredMaterialsInPart(SceneObjectPart part)
  192. {
  193. if (part.DynAttrs == null)
  194. return false;
  195. OSD OSMaterials = null;
  196. OSDArray matsArr = null;
  197. bool partchanged = false;
  198. lock (part.DynAttrs)
  199. {
  200. if (part.DynAttrs.ContainsStore("OpenSim", "Materials"))
  201. {
  202. OSDMap materialsStore = part.DynAttrs.GetStore("OpenSim", "Materials");
  203. if (materialsStore == null)
  204. return false;
  205. materialsStore.TryGetValue("Materials", out OSMaterials);
  206. part.DynAttrs.RemoveStore("OpenSim", "Materials");
  207. partchanged = true;
  208. }
  209. if (OSMaterials != null && OSMaterials is OSDArray)
  210. matsArr = OSMaterials as OSDArray;
  211. else
  212. return partchanged;
  213. }
  214. if (matsArr == null)
  215. return partchanged;
  216. foreach (OSD elemOsd in matsArr)
  217. {
  218. if (elemOsd != null && elemOsd is OSDMap)
  219. {
  220. OSDMap matMap = elemOsd as OSDMap;
  221. if (matMap.ContainsKey("ID") && matMap.ContainsKey("Material"))
  222. {
  223. try
  224. {
  225. lock (materialslock)
  226. {
  227. UUID id = matMap["ID"].AsUUID();
  228. if(m_Materials.ContainsKey(id))
  229. continue;
  230. OSDMap theMatMap = (OSDMap)matMap["Material"];
  231. FaceMaterial fmat = new FaceMaterial(theMatMap);
  232. if(fmat == null ||
  233. ( fmat.DiffuseAlphaMode == 1
  234. && fmat.NormalMapID == UUID.Zero
  235. && fmat.SpecularMapID == UUID.Zero))
  236. continue;
  237. fmat.ID = id;
  238. m_Materials[id] = fmat;
  239. m_MaterialsRefCount[id] = 0;
  240. }
  241. }
  242. catch (Exception e)
  243. {
  244. m_log.Warn("[Materials]: exception decoding persisted legacy material: " + e.ToString());
  245. }
  246. }
  247. }
  248. }
  249. return partchanged;
  250. }
  251. /// <summary>
  252. /// Find the materials used in the SOP, and add them to 'm_regionMaterials'.
  253. /// </summary>
  254. private void GetStoredMaterialsInPart(SceneObjectPart part)
  255. {
  256. if (part.Shape == null)
  257. return;
  258. bool partchanged = false;
  259. bool facechanged = false;
  260. var te = new Primitive.TextureEntry(part.Shape.TextureEntry, 0, part.Shape.TextureEntry.Length);
  261. if (te == null)
  262. return;
  263. partchanged = GetLegacyStoredMaterialsInPart(part);
  264. if (te.DefaultTexture != null)
  265. facechanged = GetStoredMaterialInFace(part, te.DefaultTexture);
  266. else
  267. m_log.WarnFormat(
  268. "[Materials]: Default texture for part {0} (part of object {1}) in {2} unexpectedly null. Ignoring.",
  269. part.Name, part.ParentGroup.Name, m_scene.Name);
  270. foreach (Primitive.TextureEntryFace face in te.FaceTextures)
  271. {
  272. if (face != null)
  273. facechanged |= GetStoredMaterialInFace(part, face);
  274. }
  275. if(facechanged)
  276. part.Shape.TextureEntry = te.GetBytes(9);
  277. if(facechanged || partchanged)
  278. {
  279. if (part.ParentGroup != null && !part.ParentGroup.IsDeleted)
  280. part.ParentGroup.HasGroupChanged = true;
  281. }
  282. }
  283. /// <summary>
  284. /// Find the materials used in one Face, and add them to 'm_regionMaterials'.
  285. /// </summary>
  286. private bool GetStoredMaterialInFace(SceneObjectPart part, Primitive.TextureEntryFace face)
  287. {
  288. UUID id = face.MaterialID;
  289. if (id == UUID.Zero)
  290. return false;
  291. OSDMap mat;
  292. lock (materialslock)
  293. {
  294. if(m_Materials.ContainsKey(id))
  295. {
  296. m_MaterialsRefCount[id]++;
  297. return false;
  298. }
  299. AssetBase matAsset = m_scene.AssetService.Get(id.ToString());
  300. if (matAsset == null || matAsset.Data == null || matAsset.Data.Length == 0 )
  301. {
  302. // grid may just be down...
  303. return false;
  304. }
  305. byte[] data = matAsset.Data;
  306. // string txt = System.Text.Encoding.ASCII.GetString(data);
  307. try
  308. {
  309. mat = (OSDMap)OSDParser.DeserializeLLSDXml(data);
  310. }
  311. catch (Exception e)
  312. {
  313. m_log.WarnFormat("[Materials]: cannot decode material asset {0}: {1}", id, e.Message);
  314. return false;
  315. }
  316. FaceMaterial fmat = new FaceMaterial(mat);
  317. if(fmat == null ||
  318. (fmat.DiffuseAlphaMode == 1
  319. && fmat.NormalMapID == UUID.Zero
  320. && fmat.SpecularMapID == UUID.Zero))
  321. {
  322. face.MaterialID = UUID.Zero;
  323. return true;
  324. }
  325. fmat.ID = id;
  326. if (m_Materials.ContainsKey(id))
  327. {
  328. m_MaterialsRefCount[id]++;
  329. }
  330. else
  331. {
  332. m_Materials[id] = fmat;
  333. m_MaterialsRefCount[id] = 1;
  334. }
  335. return false;
  336. }
  337. }
  338. private void RemoveMaterialsInPart(SceneObjectPart part)
  339. {
  340. if (part.Shape == null)
  341. return;
  342. var te = new Primitive.TextureEntry(part.Shape.TextureEntry, 0, part.Shape.TextureEntry.Length);
  343. if (te == null)
  344. return;
  345. if (te.DefaultTexture != null)
  346. RemoveMaterialInFace(te.DefaultTexture);
  347. foreach (Primitive.TextureEntryFace face in te.FaceTextures)
  348. {
  349. if(face != null)
  350. RemoveMaterialInFace(face);
  351. }
  352. }
  353. private void RemoveMaterialInFace(Primitive.TextureEntryFace face)
  354. {
  355. UUID id = face.MaterialID;
  356. if (id == UUID.Zero)
  357. return;
  358. lock (materialslock)
  359. {
  360. if(!m_Materials.ContainsKey(id))
  361. return;
  362. else
  363. {
  364. m_MaterialsRefCount[id]--;
  365. if(m_MaterialsRefCount[id] <= 0)
  366. {
  367. FaceMaterial oldFaceMat = m_Materials[id];
  368. m_changed.Remove(oldFaceMat);
  369. m_Materials.Remove(id);
  370. m_MaterialsRefCount.Remove(id);
  371. m_cache.Expire(id.ToString());
  372. }
  373. }
  374. }
  375. }
  376. public string RenderMaterialsPostCap(string request, UUID agentID)
  377. {
  378. OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
  379. OSDMap resp = new OSDMap();
  380. OSDArray respArr = new OSDArray();
  381. if (req.ContainsKey("Zipped"))
  382. {
  383. OSD osd = null;
  384. byte[] inBytes = req["Zipped"].AsBinary();
  385. try
  386. {
  387. osd = ZDecompressBytesToOsd(inBytes);
  388. if (osd != null && osd is OSDArray)
  389. {
  390. foreach (OSD elem in (OSDArray)osd)
  391. {
  392. try
  393. {
  394. UUID id = new UUID(elem.AsBinary(), 0);
  395. lock (materialslock)
  396. {
  397. if (m_Materials.ContainsKey(id))
  398. {
  399. OSDMap matMap = new OSDMap();
  400. matMap["ID"] = OSD.FromBinary(id.GetBytes());
  401. matMap["Material"] = m_Materials[id].toOSD();
  402. respArr.Add(matMap);
  403. }
  404. else
  405. {
  406. m_log.Warn("[Materials]: request for unknown material ID: " + id.ToString());
  407. // Theoretically we could try to load the material from the assets service,
  408. // but that shouldn't be necessary because the viewer should only request
  409. // materials that exist in a prim on the region, and all of these materials
  410. // are already stored in m_regionMaterials.
  411. }
  412. }
  413. }
  414. catch (Exception e)
  415. {
  416. m_log.Error("Error getting materials in response to viewer request", e);
  417. continue;
  418. }
  419. }
  420. }
  421. }
  422. catch (Exception e)
  423. {
  424. m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e);
  425. //return "";
  426. }
  427. }
  428. resp["Zipped"] = ZCompressOSD(respArr, false);
  429. string response = OSDParser.SerializeLLSDXmlString(resp);
  430. //m_log.Debug("[Materials]: cap request: " + request);
  431. //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
  432. //m_log.Debug("[Materials]: cap response: " + response);
  433. return response;
  434. }
  435. public string RenderMaterialsPutCap(string request, UUID agentID)
  436. {
  437. OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
  438. OSDMap resp = new OSDMap();
  439. OSDMap materialsFromViewer = null;
  440. OSDArray respArr = new OSDArray();
  441. HashSet<SceneObjectPart> parts = new HashSet<SceneObjectPart>();
  442. if (req.ContainsKey("Zipped"))
  443. {
  444. OSD osd = null;
  445. byte[] inBytes = req["Zipped"].AsBinary();
  446. try
  447. {
  448. osd = ZDecompressBytesToOsd(inBytes);
  449. if (osd != null && osd is OSDMap)
  450. {
  451. materialsFromViewer = osd as OSDMap;
  452. if (materialsFromViewer.ContainsKey("FullMaterialsPerFace"))
  453. {
  454. OSD matsOsd = materialsFromViewer["FullMaterialsPerFace"];
  455. if (matsOsd is OSDArray)
  456. {
  457. OSDArray matsArr = matsOsd as OSDArray;
  458. try
  459. {
  460. foreach (OSDMap matsMap in matsArr)
  461. {
  462. uint primLocalID = 0;
  463. try
  464. {
  465. primLocalID = matsMap["ID"].AsUInteger();
  466. }
  467. catch (Exception e)
  468. {
  469. m_log.Warn("[Materials]: cannot decode \"ID\" from matsMap: " + e.Message);
  470. continue;
  471. }
  472. SceneObjectPart sop = m_scene.GetSceneObjectPart(primLocalID);
  473. if (sop == null)
  474. {
  475. m_log.WarnFormat("[Materials]: SOP not found for localId: {0}", primLocalID.ToString());
  476. continue;
  477. }
  478. if (!m_scene.Permissions.CanEditObject(sop.UUID, agentID))
  479. {
  480. m_log.WarnFormat("User {0} can't edit object {1} {2}", agentID, sop.Name, sop.UUID);
  481. continue;
  482. }
  483. OSDMap mat = null;
  484. try
  485. {
  486. mat = matsMap["Material"] as OSDMap;
  487. }
  488. catch (Exception e)
  489. {
  490. m_log.Warn("[Materials]: cannot decode \"Material\" from matsMap: " + e.Message);
  491. continue;
  492. }
  493. Primitive.TextureEntry te = new Primitive.TextureEntry(sop.Shape.TextureEntry, 0, sop.Shape.TextureEntry.Length);
  494. if (te == null)
  495. {
  496. m_log.WarnFormat("[Materials]: Error in TextureEntry for SOP {0} {1}", sop.Name, sop.UUID);
  497. continue;
  498. }
  499. int face = -1;
  500. UUID oldid = UUID.Zero;
  501. Primitive.TextureEntryFace faceEntry = null;
  502. if (matsMap.ContainsKey("Face"))
  503. {
  504. face = matsMap["Face"].AsInteger();
  505. faceEntry = te.CreateFace((uint)face);
  506. }
  507. else
  508. faceEntry = te.DefaultTexture;
  509. if (faceEntry == null)
  510. continue;
  511. UUID id;
  512. FaceMaterial newFaceMat = null;
  513. if (mat == null)
  514. {
  515. // This happens then the user removes a material from a prim
  516. id = UUID.Zero;
  517. }
  518. else
  519. {
  520. newFaceMat = new FaceMaterial(mat);
  521. if(newFaceMat.DiffuseAlphaMode == 1
  522. && newFaceMat.NormalMapID == UUID.Zero
  523. && newFaceMat.SpecularMapID == UUID.Zero
  524. )
  525. id = UUID.Zero;
  526. else
  527. {
  528. newFaceMat.genID();
  529. id = newFaceMat.ID;
  530. }
  531. }
  532. oldid = faceEntry.MaterialID;
  533. if(oldid == id)
  534. continue;
  535. if (faceEntry != null)
  536. {
  537. faceEntry.MaterialID = id;
  538. //m_log.DebugFormat("[Materials]: in \"{0}\" {1}, setting material ID for face {2} to {3}", sop.Name, sop.UUID, face, id);
  539. // We can't use sop.UpdateTextureEntry(te) because it filters, so do it manually
  540. sop.Shape.TextureEntry = te.GetBytes(9);
  541. }
  542. if(oldid != UUID.Zero)
  543. RemoveMaterial(oldid);
  544. lock(materialslock)
  545. {
  546. if(id != UUID.Zero)
  547. {
  548. if (m_Materials.ContainsKey(id))
  549. m_MaterialsRefCount[id]++;
  550. else
  551. {
  552. m_Materials[id] = newFaceMat;
  553. m_MaterialsRefCount[id] = 1;
  554. m_changed[newFaceMat] = Util.GetTimeStamp();
  555. }
  556. }
  557. }
  558. if(!parts.Contains(sop))
  559. parts.Add(sop);
  560. }
  561. foreach(SceneObjectPart sop in parts)
  562. {
  563. if (sop.ParentGroup != null && !sop.ParentGroup.IsDeleted)
  564. {
  565. sop.TriggerScriptChangedEvent(Changed.TEXTURE);
  566. sop.ScheduleFullUpdate();
  567. sop.ParentGroup.HasGroupChanged = true;
  568. }
  569. }
  570. }
  571. catch (Exception e)
  572. {
  573. m_log.Warn("[Materials]: exception processing received material ", e);
  574. }
  575. }
  576. }
  577. }
  578. }
  579. catch (Exception e)
  580. {
  581. m_log.Warn("[Materials]: exception decoding zipped CAP payload ", e);
  582. //return "";
  583. }
  584. }
  585. resp["Zipped"] = ZCompressOSD(respArr, false);
  586. string response = OSDParser.SerializeLLSDXmlString(resp);
  587. //m_log.Debug("[Materials]: cap request: " + request);
  588. //m_log.Debug("[Materials]: cap request (zipped portion): " + ZippedOsdBytesToString(req["Zipped"].AsBinary()));
  589. //m_log.Debug("[Materials]: cap response: " + response);
  590. return response;
  591. }
  592. private AssetBase MakeAsset(FaceMaterial fm, bool local)
  593. {
  594. // this are not true assets, should had never been...
  595. AssetBase asset = null;
  596. string txt = fm.toLLSDxml();
  597. byte[] data = System.Text.Encoding.ASCII.GetBytes(txt);
  598. asset = new AssetBase(fm.ID, "llmaterial", (sbyte)OpenSimAssetType.Material, "00000000-0000-0000-0000-000000000000");
  599. asset.Data = data;
  600. asset.Local = local;
  601. return asset;
  602. }
  603. public string RenderMaterialsGetCap(string request)
  604. {
  605. OSDMap resp = new OSDMap();
  606. OSDArray allOsd = new OSDArray();
  607. /*
  608. // this violates all idea of caching and geting things only if needed, so disabled
  609. int matsCount = 0;
  610. lock (m_Materials)
  611. {
  612. foreach (KeyValuePair<UUID, FaceMaterial> kvp in m_Materials)
  613. {
  614. OSDMap matMap = new OSDMap();
  615. matMap["ID"] = OSD.FromBinary(kvp.Key.GetBytes());
  616. matMap["Material"] = kvp.Value.toOSD();
  617. allOsd.Add(matMap);
  618. matsCount++;
  619. }
  620. }
  621. */
  622. resp["Zipped"] = ZCompressOSD(allOsd, false);
  623. return OSDParser.SerializeLLSDXmlString(resp);
  624. }
  625. private static string ZippedOsdBytesToString(byte[] bytes)
  626. {
  627. try
  628. {
  629. return OSDParser.SerializeJsonString(ZDecompressBytesToOsd(bytes));
  630. }
  631. catch (Exception e)
  632. {
  633. return "ZippedOsdBytesToString caught an exception: " + e.ToString();
  634. }
  635. }
  636. public static OSD ZCompressOSD(OSD inOsd, bool useHeader)
  637. {
  638. OSD osd = null;
  639. byte[] data = OSDParser.SerializeLLSDBinary(inOsd, useHeader);
  640. using (MemoryStream msSinkCompressed = new MemoryStream())
  641. {
  642. using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkCompressed,
  643. Ionic.Zlib.CompressionMode.Compress, CompressionLevel.BestCompression, true))
  644. {
  645. zOut.Write(data, 0, data.Length);
  646. }
  647. msSinkCompressed.Seek(0L, SeekOrigin.Begin);
  648. osd = OSD.FromBinary(msSinkCompressed.ToArray());
  649. }
  650. return osd;
  651. }
  652. public static OSD ZDecompressBytesToOsd(byte[] input)
  653. {
  654. OSD osd = null;
  655. using (MemoryStream msSinkUnCompressed = new MemoryStream())
  656. {
  657. using (Ionic.Zlib.ZlibStream zOut = new Ionic.Zlib.ZlibStream(msSinkUnCompressed, CompressionMode.Decompress, true))
  658. {
  659. zOut.Write(input, 0, input.Length);
  660. }
  661. msSinkUnCompressed.Seek(0L, SeekOrigin.Begin);
  662. osd = OSDParser.DeserializeLLSDBinary(msSinkUnCompressed.ToArray());
  663. }
  664. return osd;
  665. }
  666. public FaceMaterial GetMaterial(UUID ID)
  667. {
  668. FaceMaterial fm = null;
  669. if(m_Materials.TryGetValue(ID, out fm))
  670. return fm;
  671. return null;
  672. }
  673. public FaceMaterial GetMaterialCopy(UUID ID)
  674. {
  675. FaceMaterial fm = null;
  676. if(m_Materials.TryGetValue(ID, out fm))
  677. return new FaceMaterial(fm);
  678. return null;
  679. }
  680. public UUID AddNewMaterial(FaceMaterial fm)
  681. {
  682. if(fm.DiffuseAlphaMode == 1 && fm.NormalMapID == UUID.Zero && fm.SpecularMapID == UUID.Zero)
  683. {
  684. fm.ID = UUID.Zero;
  685. return UUID.Zero;
  686. }
  687. fm.genID();
  688. UUID id = fm.ID;
  689. lock(materialslock)
  690. {
  691. if(m_Materials.ContainsKey(id))
  692. m_MaterialsRefCount[id]++;
  693. else
  694. {
  695. m_Materials[id] = fm;
  696. m_MaterialsRefCount[id] = 1;
  697. m_changed[fm] = Util.GetTimeStamp();
  698. }
  699. }
  700. return id;
  701. }
  702. public void RemoveMaterial(UUID id)
  703. {
  704. if(id == UUID.Zero)
  705. return;
  706. lock(materialslock)
  707. {
  708. if(m_Materials.ContainsKey(id))
  709. {
  710. m_MaterialsRefCount[id]--;
  711. if(m_MaterialsRefCount[id] <= 0)
  712. {
  713. FaceMaterial fm = m_Materials[id];
  714. m_changed.Remove(fm);
  715. m_Materials.Remove(id);
  716. m_MaterialsRefCount.Remove(id);
  717. m_cache.Expire(id.ToString());
  718. }
  719. }
  720. }
  721. }
  722. }
  723. }