DynamicTextureModule.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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.Drawing;
  30. using System.Drawing.Drawing2D;
  31. using System.Drawing.Imaging;
  32. using Nini.Config;
  33. using OpenMetaverse;
  34. using OpenMetaverse.Imaging;
  35. using OpenSim.Framework;
  36. using OpenSim.Region.Framework.Interfaces;
  37. using OpenSim.Region.Framework.Scenes;
  38. using log4net;
  39. using System.Reflection;
  40. using Mono.Addins;
  41. namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
  42. {
  43. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "DynamicTextureModule")]
  44. public class DynamicTextureModule : ISharedRegionModule, IDynamicTextureManager
  45. {
  46. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  47. private const int ALL_SIDES = -1;
  48. public const int DISP_EXPIRE = 1;
  49. public const int DISP_TEMP = 2;
  50. /// <summary>
  51. /// If true then where possible dynamic textures are reused.
  52. /// </summary>
  53. public bool ReuseTextures { get; set; }
  54. /// <summary>
  55. /// If false, then textures which have a low data size are not reused when ReuseTextures = true.
  56. /// </summary>
  57. /// <remarks>
  58. /// LL viewers 3.3.4 and before appear to not fully render textures pulled from the viewer cache if those
  59. /// textures have a relatively high pixel surface but a small data size. Typically, this appears to happen
  60. /// if the data size is smaller than the viewer's discard level 2 size estimate. So if this is setting is
  61. /// false, textures smaller than the calculation in IsSizeReuseable are always regenerated rather than reused
  62. /// to work around this problem.</remarks>
  63. public bool ReuseLowDataTextures { get; set; }
  64. private Dictionary<UUID, Scene> RegisteredScenes = new Dictionary<UUID, Scene>();
  65. private Dictionary<string, IDynamicTextureRender> RenderPlugins =
  66. new Dictionary<string, IDynamicTextureRender>();
  67. private Dictionary<UUID, DynamicTextureUpdater> Updaters = new Dictionary<UUID, DynamicTextureUpdater>();
  68. /// <summary>
  69. /// Record dynamic textures that we can reuse for a given data and parameter combination rather than
  70. /// regenerate.
  71. /// </summary>
  72. /// <remarks>
  73. /// Key is string.Format("{0}{1}", data
  74. /// </remarks>
  75. private Cache m_reuseableDynamicTextures;
  76. /// <summary>
  77. /// This constructor is only here because of the Unit Tests...
  78. /// Don't use it.
  79. /// </summary>
  80. public DynamicTextureModule()
  81. {
  82. m_reuseableDynamicTextures = new Cache(CacheMedium.Memory, CacheStrategy.Conservative);
  83. m_reuseableDynamicTextures.DefaultTTL = new TimeSpan(24, 0, 0);
  84. }
  85. #region IDynamicTextureManager Members
  86. public void RegisterRender(string handleType, IDynamicTextureRender render)
  87. {
  88. if (!RenderPlugins.ContainsKey(handleType))
  89. {
  90. RenderPlugins.Add(handleType, render);
  91. }
  92. }
  93. /// <summary>
  94. /// Called by code which actually renders the dynamic texture to supply texture data.
  95. /// </summary>
  96. /// <param name="updaterId"></param>
  97. /// <param name="texture"></param>
  98. public void ReturnData(UUID updaterId, IDynamicTexture texture)
  99. {
  100. DynamicTextureUpdater updater = null;
  101. lock (Updaters)
  102. {
  103. if (Updaters.ContainsKey(updaterId))
  104. {
  105. updater = Updaters[updaterId];
  106. }
  107. }
  108. if (updater != null)
  109. {
  110. if (RegisteredScenes.ContainsKey(updater.SimUUID))
  111. {
  112. Scene scene = RegisteredScenes[updater.SimUUID];
  113. UUID newTextureID = updater.DataReceived(texture.Data, scene);
  114. if (ReuseTextures
  115. && !updater.BlendWithOldTexture
  116. && texture.IsReuseable
  117. && (ReuseLowDataTextures || IsDataSizeReuseable(texture)))
  118. {
  119. m_reuseableDynamicTextures.Store(
  120. GenerateReusableTextureKey(texture.InputCommands, texture.InputParams), newTextureID);
  121. }
  122. updater.newTextureID = newTextureID;
  123. }
  124. lock (Updaters)
  125. {
  126. if (Updaters.ContainsKey(updater.UpdaterID))
  127. Updaters.Remove(updater.UpdaterID);
  128. }
  129. }
  130. }
  131. /// <summary>
  132. /// Determines whether the texture is reuseable based on its data size.
  133. /// </summary>
  134. /// <remarks>
  135. /// This is a workaround for a viewer bug where very small data size textures relative to their pixel size
  136. /// are not redisplayed properly when pulled from cache. The calculation here is based on the typical discard
  137. /// level of 2, a 'rate' of 0.125 and 4 components (which makes for a factor of 0.5).
  138. /// </remarks>
  139. /// <returns></returns>
  140. private bool IsDataSizeReuseable(IDynamicTexture texture)
  141. {
  142. // Console.WriteLine("{0} {1}", texture.Size.Width, texture.Size.Height);
  143. int discardLevel2DataThreshold = (int)Math.Ceiling((texture.Size.Width >> 2) * (texture.Size.Height >> 2) * 0.5);
  144. // m_log.DebugFormat(
  145. // "[DYNAMIC TEXTURE MODULE]: Discard level 2 threshold {0}, texture data length {1}",
  146. // discardLevel2DataThreshold, texture.Data.Length);
  147. return discardLevel2DataThreshold < texture.Data.Length;
  148. }
  149. public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url,
  150. string extraParams)
  151. {
  152. return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, false, 255);
  153. }
  154. public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url,
  155. string extraParams, bool SetBlending, byte AlphaValue)
  156. {
  157. return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, SetBlending,
  158. (DISP_TEMP|DISP_EXPIRE), AlphaValue, ALL_SIDES);
  159. }
  160. public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url,
  161. string extraParams, bool SetBlending,
  162. int disp, byte AlphaValue, int face)
  163. {
  164. if (RenderPlugins.ContainsKey(contentType))
  165. {
  166. DynamicTextureUpdater updater = new DynamicTextureUpdater();
  167. updater.SimUUID = simID;
  168. updater.PrimID = primID;
  169. updater.ContentType = contentType;
  170. updater.Url = url;
  171. updater.UpdaterID = UUID.Random();
  172. updater.Params = extraParams;
  173. updater.BlendWithOldTexture = SetBlending;
  174. updater.FrontAlpha = AlphaValue;
  175. updater.Face = face;
  176. updater.Disp = disp;
  177. lock (Updaters)
  178. {
  179. if (!Updaters.ContainsKey(updater.UpdaterID))
  180. {
  181. Updaters.Add(updater.UpdaterID, updater);
  182. }
  183. }
  184. RenderPlugins[contentType].AsyncConvertUrl(updater.UpdaterID, url, extraParams);
  185. return updater.newTextureID;
  186. }
  187. return UUID.Zero;
  188. }
  189. public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
  190. string extraParams)
  191. {
  192. return AddDynamicTextureData(simID, primID, contentType, data, extraParams, false,
  193. (DISP_TEMP|DISP_EXPIRE), 255, ALL_SIDES);
  194. }
  195. public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
  196. string extraParams, bool SetBlending, byte AlphaValue)
  197. {
  198. return AddDynamicTextureData(simID, primID, contentType, data, extraParams, SetBlending,
  199. (DISP_TEMP|DISP_EXPIRE), AlphaValue, ALL_SIDES);
  200. }
  201. public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
  202. string extraParams, bool SetBlending, int disp, byte AlphaValue, int face)
  203. {
  204. if (!RenderPlugins.ContainsKey(contentType))
  205. return UUID.Zero;
  206. Scene scene;
  207. RegisteredScenes.TryGetValue(simID, out scene);
  208. if (scene == null)
  209. return UUID.Zero;
  210. SceneObjectPart part = scene.GetSceneObjectPart(primID);
  211. if (part == null)
  212. return UUID.Zero;
  213. // If we want to reuse dynamic textures then we have to ignore any request from the caller to expire
  214. // them.
  215. if (ReuseTextures)
  216. disp = disp & ~DISP_EXPIRE;
  217. DynamicTextureUpdater updater = new DynamicTextureUpdater();
  218. updater.SimUUID = simID;
  219. updater.PrimID = primID;
  220. updater.ContentType = contentType;
  221. updater.BodyData = data;
  222. updater.UpdaterID = UUID.Random();
  223. updater.Params = extraParams;
  224. updater.BlendWithOldTexture = SetBlending;
  225. updater.FrontAlpha = AlphaValue;
  226. updater.Face = face;
  227. updater.Url = "Local image";
  228. updater.Disp = disp;
  229. object objReusableTextureUUID = null;
  230. if (ReuseTextures && !updater.BlendWithOldTexture)
  231. {
  232. string reuseableTextureKey = GenerateReusableTextureKey(data, extraParams);
  233. objReusableTextureUUID = m_reuseableDynamicTextures.Get(reuseableTextureKey);
  234. if (objReusableTextureUUID != null)
  235. {
  236. // If something else has removed this temporary asset from the cache, detect and invalidate
  237. // our cached uuid.
  238. if (scene.AssetService.GetMetadata(objReusableTextureUUID.ToString()) == null)
  239. {
  240. m_reuseableDynamicTextures.Invalidate(reuseableTextureKey);
  241. objReusableTextureUUID = null;
  242. }
  243. }
  244. }
  245. // We cannot reuse a dynamic texture if the data is going to be blended with something already there.
  246. if (objReusableTextureUUID == null)
  247. {
  248. lock (Updaters)
  249. {
  250. if (!Updaters.ContainsKey(updater.UpdaterID))
  251. {
  252. Updaters.Add(updater.UpdaterID, updater);
  253. }
  254. }
  255. // m_log.DebugFormat(
  256. // "[DYNAMIC TEXTURE MODULE]: Requesting generation of new dynamic texture for {0} in {1}",
  257. // part.Name, part.ParentGroup.Scene.Name);
  258. RenderPlugins[contentType].AsyncConvertData(updater.UpdaterID, data, extraParams);
  259. }
  260. else
  261. {
  262. // m_log.DebugFormat(
  263. // "[DYNAMIC TEXTURE MODULE]: Reusing cached texture {0} for {1} in {2}",
  264. // objReusableTextureUUID, part.Name, part.ParentGroup.Scene.Name);
  265. // No need to add to updaters as the texture is always the same. Not that this functionality
  266. // apppears to be implemented anyway.
  267. updater.UpdatePart(part, (UUID)objReusableTextureUUID);
  268. }
  269. return updater.newTextureID;
  270. }
  271. private string GenerateReusableTextureKey(string data, string extraParams)
  272. {
  273. return string.Format("{0}{1}", data, extraParams);
  274. }
  275. public void GetDrawStringSize(string contentType, string text, string fontName, int fontSize,
  276. out double xSize, out double ySize)
  277. {
  278. xSize = 0;
  279. ySize = 0;
  280. if (RenderPlugins.ContainsKey(contentType))
  281. {
  282. RenderPlugins[contentType].GetDrawStringSize(text, fontName, fontSize, out xSize, out ySize);
  283. }
  284. }
  285. #endregion
  286. #region ISharedRegionModule Members
  287. public void Initialise(IConfigSource config)
  288. {
  289. IConfig texturesConfig = config.Configs["Textures"];
  290. if (texturesConfig != null)
  291. {
  292. ReuseTextures = texturesConfig.GetBoolean("ReuseDynamicTextures", false);
  293. ReuseLowDataTextures = texturesConfig.GetBoolean("ReuseDynamicLowDataTextures", false);
  294. if (ReuseTextures)
  295. {
  296. m_reuseableDynamicTextures = new Cache(CacheMedium.Memory, CacheStrategy.Conservative);
  297. m_reuseableDynamicTextures.DefaultTTL = new TimeSpan(24, 0, 0);
  298. }
  299. }
  300. }
  301. public void PostInitialise()
  302. {
  303. }
  304. public void AddRegion(Scene scene)
  305. {
  306. if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID))
  307. {
  308. RegisteredScenes.Add(scene.RegionInfo.RegionID, scene);
  309. scene.RegisterModuleInterface<IDynamicTextureManager>(this);
  310. }
  311. }
  312. public void RegionLoaded(Scene scene)
  313. {
  314. }
  315. public void RemoveRegion(Scene scene)
  316. {
  317. if (RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID))
  318. RegisteredScenes.Remove(scene.RegionInfo.RegionID);
  319. }
  320. public void Close()
  321. {
  322. }
  323. public string Name
  324. {
  325. get { return "DynamicTextureModule"; }
  326. }
  327. public Type ReplaceableInterface
  328. {
  329. get { return null; }
  330. }
  331. #endregion
  332. #region Nested type: DynamicTextureUpdater
  333. public class DynamicTextureUpdater
  334. {
  335. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  336. public bool BlendWithOldTexture = false;
  337. public string BodyData;
  338. public string ContentType;
  339. public byte FrontAlpha = 255;
  340. public string Params;
  341. public UUID PrimID;
  342. public UUID SimUUID;
  343. public UUID UpdaterID;
  344. public int Face;
  345. public int Disp;
  346. public string Url;
  347. public UUID newTextureID;
  348. public DynamicTextureUpdater()
  349. {
  350. BodyData = null;
  351. }
  352. /// <summary>
  353. /// Update the given part with the new texture.
  354. /// </summary>
  355. /// <returns>
  356. /// The old texture UUID.
  357. /// </returns>
  358. public UUID UpdatePart(SceneObjectPart part, UUID textureID)
  359. {
  360. UUID oldID;
  361. lock (part)
  362. {
  363. // mostly keep the values from before
  364. Primitive.TextureEntry tmptex = part.Shape.Textures;
  365. // FIXME: Need to return the appropriate ID if only a single face is replaced.
  366. oldID = tmptex.DefaultTexture.TextureID;
  367. // not using parts number of faces because that fails on old meshs
  368. if (Face == ALL_SIDES)
  369. {
  370. oldID = tmptex.DefaultTexture.TextureID;
  371. tmptex.DefaultTexture.TextureID = textureID;
  372. for(int i = 0; i < tmptex.FaceTextures.Length; i++)
  373. {
  374. if(tmptex.FaceTextures[i] != null)
  375. tmptex.FaceTextures[i].TextureID = textureID;
  376. }
  377. }
  378. else
  379. {
  380. try
  381. {
  382. Primitive.TextureEntryFace texface = tmptex.CreateFace((uint)Face);
  383. oldID = texface.TextureID;
  384. texface.TextureID = textureID;
  385. tmptex.FaceTextures[Face] = texface;
  386. }
  387. catch (Exception)
  388. {
  389. tmptex.DefaultTexture.TextureID = textureID;
  390. }
  391. }
  392. part.UpdateTextureEntry(tmptex);
  393. }
  394. return oldID;
  395. }
  396. /// <summary>
  397. /// Called once new texture data has been received for this updater.
  398. /// </summary>
  399. /// <param name="data"></param>
  400. /// <param name="scene"></param>
  401. /// <param name="isReuseable">True if the data given is reuseable.</param>
  402. /// <returns>The asset UUID given to the incoming data.</returns>
  403. public UUID DataReceived(byte[] data, Scene scene)
  404. {
  405. SceneObjectPart part = scene.GetSceneObjectPart(PrimID);
  406. if (part == null || data == null || data.Length <= 1)
  407. {
  408. string msg =
  409. String.Format("DynamicTextureModule: Error preparing image using URL {0}", Url);
  410. scene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say,
  411. 0, part.ParentGroup.RootPart.AbsolutePosition, part.Name, part.UUID, false);
  412. return UUID.Zero;
  413. }
  414. byte[] assetData = null;
  415. AssetBase oldAsset = null;
  416. if (BlendWithOldTexture)
  417. {
  418. Primitive.TextureEntryFace curFace;
  419. if(Face == ALL_SIDES)
  420. curFace = part.Shape.Textures.DefaultTexture;
  421. else
  422. {
  423. try
  424. {
  425. curFace = part.Shape.Textures.GetFace((uint)Face);
  426. }
  427. catch
  428. {
  429. curFace = null;
  430. }
  431. }
  432. if (curFace != null)
  433. {
  434. oldAsset = scene.AssetService.Get(curFace.TextureID.ToString());
  435. if (oldAsset != null)
  436. assetData = BlendTextures(data, oldAsset.Data, FrontAlpha);
  437. }
  438. }
  439. else if(FrontAlpha < 255)
  440. assetData = BlendTextures(data, null, FrontAlpha);
  441. if (assetData == null)
  442. {
  443. assetData = new byte[data.Length];
  444. Array.Copy(data, assetData, data.Length);
  445. }
  446. // Create a new asset for user
  447. AssetBase asset
  448. = new AssetBase(
  449. UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000), (sbyte)AssetType.Texture,
  450. scene.RegionInfo.RegionID.ToString());
  451. asset.Data = assetData;
  452. asset.Description = String.Format("URL image : {0}", Url);
  453. if (asset.Description.Length > 128)
  454. asset.Description = asset.Description.Substring(0, 128);
  455. asset.Local = true; // dynamic images aren't saved in the assets server
  456. asset.Temporary = ((Disp & DISP_TEMP) != 0);
  457. scene.AssetService.Store(asset); // this will only save the asset in the local asset cache
  458. IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>();
  459. if (cacheLayerDecode != null)
  460. {
  461. if (!cacheLayerDecode.Decode(asset.FullID, asset.Data))
  462. m_log.WarnFormat(
  463. "[DYNAMIC TEXTURE MODULE]: Decoding of dynamically generated asset {0} for {1} in {2} failed",
  464. asset.ID, part.Name, part.ParentGroup.Scene.Name);
  465. }
  466. UUID oldID = UpdatePart(part, asset.FullID);
  467. if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0))
  468. {
  469. if (oldAsset == null)
  470. oldAsset = scene.AssetService.Get(oldID.ToString());
  471. if (oldAsset != null)
  472. {
  473. if (oldAsset.Temporary)
  474. {
  475. scene.AssetService.Delete(oldID.ToString());
  476. }
  477. }
  478. }
  479. return asset.FullID;
  480. }
  481. private byte[] BlendTextures(byte[] frontImage, byte[] backImage, byte newAlpha)
  482. {
  483. ManagedImage managedImage;
  484. Image image;
  485. if (!OpenJPEG.DecodeToImage(frontImage, out managedImage, out image) || image == null)
  486. return null;
  487. Bitmap image1 = new Bitmap(image);
  488. image.Dispose();
  489. if(backImage == null)
  490. {
  491. SetAlpha(ref image1, newAlpha);
  492. byte[] result = new byte[0];
  493. try
  494. {
  495. result = OpenJPEG.EncodeFromImage(image1, false);
  496. }
  497. catch (Exception e)
  498. {
  499. m_log.ErrorFormat(
  500. "[DYNAMICTEXTUREMODULE]: OpenJpeg Encode Failed. Exception {0}{1}",
  501. e.Message, e.StackTrace);
  502. }
  503. image1.Dispose();
  504. return result;
  505. }
  506. if (!OpenJPEG.DecodeToImage(backImage, out managedImage, out image) || image == null)
  507. {
  508. image1.Dispose();
  509. return null;
  510. }
  511. Bitmap image2 = new Bitmap(image);
  512. image.Dispose();
  513. using(Bitmap joint = MergeBitMaps(image1, image2, newAlpha))
  514. {
  515. image1.Dispose();
  516. image2.Dispose();
  517. byte[] result = new byte[0];
  518. try
  519. {
  520. result = OpenJPEG.EncodeFromImage(joint, false);
  521. }
  522. catch (Exception e)
  523. {
  524. m_log.ErrorFormat(
  525. "[DYNAMICTEXTUREMODULE]: OpenJpeg Encode Failed. Exception {0}{1}",
  526. e.Message, e.StackTrace);
  527. }
  528. return result;
  529. }
  530. }
  531. public Bitmap MergeBitMaps(Bitmap front, Bitmap back, byte alpha)
  532. {
  533. Bitmap joint;
  534. Graphics jG;
  535. int Width = back.Width;
  536. int Height = back.Height;
  537. PixelFormat format;
  538. if(alpha < 255 || front.PixelFormat == PixelFormat.Format32bppArgb || back.PixelFormat == PixelFormat.Format32bppArgb)
  539. format = PixelFormat.Format32bppArgb;
  540. else
  541. format = PixelFormat.Format32bppRgb;
  542. joint = new Bitmap(Width, Height, format);
  543. if (alpha >= 255)
  544. {
  545. using (jG = Graphics.FromImage(joint))
  546. {
  547. jG.CompositingQuality = CompositingQuality.HighQuality;
  548. jG.CompositingMode = CompositingMode.SourceCopy;
  549. jG.DrawImage(back, 0, 0, Width, Height);
  550. jG.CompositingMode = CompositingMode.SourceOver;
  551. jG.DrawImage(front, 0, 0, Width, Height);
  552. return joint;
  553. }
  554. }
  555. using (jG = Graphics.FromImage(joint))
  556. {
  557. jG.CompositingQuality = CompositingQuality.HighQuality;
  558. jG.CompositingMode = CompositingMode.SourceCopy;
  559. jG.DrawImage(back, 0, 0, Width, Height);
  560. if (alpha > 0)
  561. {
  562. ColorMatrix matrix = new ColorMatrix(new float[][]{
  563. new float[] {1F, 0, 0, 0, 0},
  564. new float[] {0, 1F, 0, 0, 0},
  565. new float[] {0, 0, 1F, 0, 0},
  566. new float[] {0, 0, 0, alpha/255f, 0},
  567. new float[] {0, 0, 0, 0, 1F}});
  568. ImageAttributes imageAttributes = new ImageAttributes();
  569. imageAttributes.SetColorMatrix(matrix);
  570. jG.CompositingMode = CompositingMode.SourceOver;
  571. jG.DrawImage(front, new Rectangle(0, 0, Width, Height), 0, 0, front.Width, front.Height, GraphicsUnit.Pixel, imageAttributes);
  572. }
  573. return joint;
  574. }
  575. }
  576. private void SetAlpha(ref Bitmap b, byte alpha)
  577. {
  578. int Width = b.Width;
  579. int Height = b.Height;
  580. Bitmap joint = new Bitmap(Width, Height, PixelFormat.Format32bppArgb);
  581. if(alpha > 0)
  582. {
  583. ColorMatrix matrix = new ColorMatrix(new float[][]{
  584. new float[] {1F, 0, 0, 0, 0},
  585. new float[] {0, 1F, 0, 0, 0},
  586. new float[] {0, 0, 1F, 0, 0},
  587. new float[] {0, 0, 0, alpha/255f, 0},
  588. new float[] {0, 0, 0, 0, 1F}});
  589. ImageAttributes imageAttributes = new ImageAttributes();
  590. imageAttributes.SetColorMatrix(matrix);
  591. using (Graphics jG = Graphics.FromImage(joint))
  592. {
  593. jG.CompositingQuality = CompositingQuality.HighQuality;
  594. jG.CompositingMode = CompositingMode.SourceCopy;
  595. jG.DrawImage(b, new Rectangle(0, 0, Width, Height), 0, 0, Width, Height, GraphicsUnit.Pixel, imageAttributes);
  596. }
  597. }
  598. Bitmap t = b;
  599. b = joint;
  600. t.Dispose();
  601. }
  602. }
  603. #endregion
  604. }
  605. }