Warp3DImageModule.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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.Imaging;
  31. using System.IO;
  32. using System.Reflection;
  33. using CSJ2K;
  34. using Nini.Config;
  35. using log4net;
  36. using Rednettle.Warp3D;
  37. using OpenMetaverse;
  38. using OpenMetaverse.Imaging;
  39. using OpenMetaverse.Rendering;
  40. using OpenMetaverse.StructuredData;
  41. using OpenSim.Framework;
  42. using OpenSim.Region.Framework.Interfaces;
  43. using OpenSim.Region.Framework.Scenes;
  44. using OpenSim.Region.Physics.Manager;
  45. using OpenSim.Services.Interfaces;
  46. using WarpRenderer = global::Warp3D.Warp3D;
  47. namespace OpenSim.Region.CoreModules.World.Warp3DMap
  48. {
  49. public class Warp3DImageModule : IMapImageGenerator, INonSharedRegionModule
  50. {
  51. private static readonly UUID TEXTURE_METADATA_MAGIC = new UUID("802dc0e0-f080-4931-8b57-d1be8611c4f3");
  52. private static readonly Color4 WATER_COLOR = new Color4(29, 72, 96, 216);
  53. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  54. private Scene m_scene;
  55. private IRendering m_primMesher;
  56. private IConfigSource m_config;
  57. private Dictionary<UUID, Color4> m_colors = new Dictionary<UUID, Color4>();
  58. private bool m_useAntiAliasing = false; // TODO: Make this a config option
  59. private bool m_Enabled = false;
  60. #region IRegionModule Members
  61. public void Initialise(IConfigSource source)
  62. {
  63. m_config = source;
  64. IConfig startupConfig = m_config.Configs["Startup"];
  65. if (startupConfig.GetString("MapImageModule", "MapImageModule") != "Warp3DImageModule")
  66. return;
  67. m_Enabled = true;
  68. }
  69. public void AddRegion(Scene scene)
  70. {
  71. if (!m_Enabled)
  72. return;
  73. m_scene = scene;
  74. List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
  75. if (renderers.Count > 0)
  76. {
  77. m_primMesher = RenderingLoader.LoadRenderer(renderers[0]);
  78. m_log.DebugFormat("[WARP 3D IMAGE MODULE]: Loaded prim mesher {0}", m_primMesher);
  79. }
  80. else
  81. {
  82. m_log.Debug("[WARP 3D IMAGE MODULE]: No prim mesher loaded, prim rendering will be disabled");
  83. }
  84. m_scene.RegisterModuleInterface<IMapImageGenerator>(this);
  85. }
  86. public void RegionLoaded(Scene scene)
  87. {
  88. }
  89. public void RemoveRegion(Scene scene)
  90. {
  91. }
  92. public void Close()
  93. {
  94. }
  95. public string Name
  96. {
  97. get { return "Warp3DImageModule"; }
  98. }
  99. public Type ReplaceableInterface
  100. {
  101. get { return null; }
  102. }
  103. #endregion
  104. #region IMapImageGenerator Members
  105. public Bitmap CreateMapTile()
  106. {
  107. Vector3 camPos = new Vector3(127.5f, 127.5f, 221.7025033688163f);
  108. Viewport viewport = new Viewport(camPos, -Vector3.UnitZ, 1024f, 0.1f, (int)Constants.RegionSize, (int)Constants.RegionSize, (float)Constants.RegionSize, (float)Constants.RegionSize);
  109. return CreateMapTile(viewport, false);
  110. }
  111. public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float fov, int width, int height, bool useTextures)
  112. {
  113. Viewport viewport = new Viewport(camPos, camDir, fov, (float)Constants.RegionSize, 0.1f, width, height);
  114. return CreateMapTile(viewport, useTextures);
  115. }
  116. public Bitmap CreateMapTile(Viewport viewport, bool useTextures)
  117. {
  118. bool drawPrimVolume = true;
  119. bool textureTerrain = true;
  120. try
  121. {
  122. IConfig startupConfig = m_config.Configs["Startup"];
  123. drawPrimVolume = startupConfig.GetBoolean("DrawPrimOnMapTile", drawPrimVolume);
  124. textureTerrain = startupConfig.GetBoolean("TextureOnMapTile", textureTerrain);
  125. }
  126. catch
  127. {
  128. m_log.Warn("[WARP 3D IMAGE MODULE]: Failed to load StartupConfig");
  129. }
  130. m_colors.Clear();
  131. int width = viewport.Width;
  132. int height = viewport.Height;
  133. if (m_useAntiAliasing)
  134. {
  135. width *= 2;
  136. height *= 2;
  137. }
  138. WarpRenderer renderer = new WarpRenderer();
  139. renderer.CreateScene(width, height);
  140. renderer.Scene.autoCalcNormals = false;
  141. #region Camera
  142. warp_Vector pos = ConvertVector(viewport.Position);
  143. pos.z -= 0.001f; // Works around an issue with the Warp3D camera
  144. warp_Vector lookat = warp_Vector.add(ConvertVector(viewport.Position), ConvertVector(viewport.LookDirection));
  145. renderer.Scene.defaultCamera.setPos(pos);
  146. renderer.Scene.defaultCamera.lookAt(lookat);
  147. if (viewport.Orthographic)
  148. {
  149. renderer.Scene.defaultCamera.isOrthographic = true;
  150. renderer.Scene.defaultCamera.orthoViewWidth = viewport.OrthoWindowWidth;
  151. renderer.Scene.defaultCamera.orthoViewHeight = viewport.OrthoWindowHeight;
  152. }
  153. else
  154. {
  155. float fov = viewport.FieldOfView;
  156. fov *= 1.75f; // FIXME: ???
  157. renderer.Scene.defaultCamera.setFov(fov);
  158. }
  159. #endregion Camera
  160. renderer.Scene.addLight("Light1", new warp_Light(new warp_Vector(1.0f, 0.5f, 1f), 0xffffff, 0, 320, 40));
  161. renderer.Scene.addLight("Light2", new warp_Light(new warp_Vector(-1f, -1f, 1f), 0xffffff, 0, 100, 40));
  162. CreateWater(renderer);
  163. CreateTerrain(renderer, textureTerrain);
  164. if (drawPrimVolume)
  165. CreateAllPrims(renderer, useTextures);
  166. renderer.Render();
  167. Bitmap bitmap = renderer.Scene.getImage();
  168. if (m_useAntiAliasing)
  169. {
  170. using (Bitmap origBitmap = bitmap)
  171. bitmap = ImageUtils.ResizeImage(origBitmap, viewport.Width, viewport.Height);
  172. }
  173. return bitmap;
  174. }
  175. public byte[] WriteJpeg2000Image()
  176. {
  177. try
  178. {
  179. using (Bitmap mapbmp = CreateMapTile())
  180. return OpenJPEG.EncodeFromImage(mapbmp, true);
  181. }
  182. catch (Exception e)
  183. {
  184. // JPEG2000 encoder failed
  185. m_log.Error("[WARP 3D IMAGE MODULE]: Failed generating terrain map: ", e);
  186. }
  187. return null;
  188. }
  189. #endregion
  190. #region Rendering Methods
  191. private void CreateWater(WarpRenderer renderer)
  192. {
  193. float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
  194. renderer.AddPlane("Water", 256f * 0.5f);
  195. renderer.Scene.sceneobject("Water").setPos(127.5f, waterHeight, 127.5f);
  196. renderer.AddMaterial("WaterColor", ConvertColor(WATER_COLOR));
  197. renderer.Scene.material("WaterColor").setReflectivity(0); // match water color with standard map module thanks lkalif
  198. renderer.Scene.material("WaterColor").setTransparency((byte)((1f - WATER_COLOR.A) * 255f));
  199. renderer.SetObjectMaterial("Water", "WaterColor");
  200. }
  201. private void CreateTerrain(WarpRenderer renderer, bool textureTerrain)
  202. {
  203. ITerrainChannel terrain = m_scene.Heightmap;
  204. float[] heightmap = terrain.GetFloatsSerialised();
  205. warp_Object obj = new warp_Object(256 * 256, 255 * 255 * 2);
  206. for (int y = 0; y < 256; y++)
  207. {
  208. for (int x = 0; x < 256; x++)
  209. {
  210. int v = y * 256 + x;
  211. float height = heightmap[v];
  212. warp_Vector pos = ConvertVector(new Vector3(x, y, height));
  213. obj.addVertex(new warp_Vertex(pos, (float)x / 255f, (float)(255 - y) / 255f));
  214. }
  215. }
  216. for (int y = 0; y < 256; y++)
  217. {
  218. for (int x = 0; x < 256; x++)
  219. {
  220. if (x < 255 && y < 255)
  221. {
  222. int v = y * 256 + x;
  223. // Normal
  224. Vector3 v1 = new Vector3(x, y, heightmap[y * 256 + x]);
  225. Vector3 v2 = new Vector3(x + 1, y, heightmap[y * 256 + x + 1]);
  226. Vector3 v3 = new Vector3(x, y + 1, heightmap[(y + 1) * 256 + x]);
  227. warp_Vector norm = ConvertVector(SurfaceNormal(v1, v2, v3));
  228. norm = norm.reverse();
  229. obj.vertex(v).n = norm;
  230. // Triangle 1
  231. obj.addTriangle(
  232. v,
  233. v + 1,
  234. v + 256);
  235. // Triangle 2
  236. obj.addTriangle(
  237. v + 256 + 1,
  238. v + 256,
  239. v + 1);
  240. }
  241. }
  242. }
  243. renderer.Scene.addObject("Terrain", obj);
  244. UUID[] textureIDs = new UUID[4];
  245. float[] startHeights = new float[4];
  246. float[] heightRanges = new float[4];
  247. RegionSettings regionInfo = m_scene.RegionInfo.RegionSettings;
  248. textureIDs[0] = regionInfo.TerrainTexture1;
  249. textureIDs[1] = regionInfo.TerrainTexture2;
  250. textureIDs[2] = regionInfo.TerrainTexture3;
  251. textureIDs[3] = regionInfo.TerrainTexture4;
  252. startHeights[0] = (float)regionInfo.Elevation1SW;
  253. startHeights[1] = (float)regionInfo.Elevation1NW;
  254. startHeights[2] = (float)regionInfo.Elevation1SE;
  255. startHeights[3] = (float)regionInfo.Elevation1NE;
  256. heightRanges[0] = (float)regionInfo.Elevation2SW;
  257. heightRanges[1] = (float)regionInfo.Elevation2NW;
  258. heightRanges[2] = (float)regionInfo.Elevation2SE;
  259. heightRanges[3] = (float)regionInfo.Elevation2NE;
  260. uint globalX, globalY;
  261. Utils.LongToUInts(m_scene.RegionInfo.RegionHandle, out globalX, out globalY);
  262. warp_Texture texture;
  263. using (
  264. Bitmap image
  265. = TerrainSplat.Splat(
  266. heightmap, textureIDs, startHeights, heightRanges,
  267. new Vector3d(globalX, globalY, 0.0), m_scene.AssetService, textureTerrain))
  268. {
  269. texture = new warp_Texture(image);
  270. }
  271. warp_Material material = new warp_Material(texture);
  272. material.setReflectivity(50);
  273. renderer.Scene.addMaterial("TerrainColor", material);
  274. renderer.Scene.material("TerrainColor").setReflectivity(0); // reduces tile seams a bit thanks lkalif
  275. renderer.SetObjectMaterial("Terrain", "TerrainColor");
  276. }
  277. private void CreateAllPrims(WarpRenderer renderer, bool useTextures)
  278. {
  279. if (m_primMesher == null)
  280. return;
  281. m_scene.ForEachSOG(
  282. delegate(SceneObjectGroup group)
  283. {
  284. CreatePrim(renderer, group.RootPart, useTextures);
  285. foreach (SceneObjectPart child in group.Parts)
  286. CreatePrim(renderer, child, useTextures);
  287. }
  288. );
  289. }
  290. private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim,
  291. bool useTextures)
  292. {
  293. const float MIN_SIZE = 2f;
  294. if ((PCode)prim.Shape.PCode != PCode.Prim)
  295. return;
  296. if (prim.Scale.LengthSquared() < MIN_SIZE * MIN_SIZE)
  297. return;
  298. Primitive omvPrim = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset);
  299. FacetedMesh renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);
  300. if (renderMesh == null)
  301. return;
  302. warp_Vector primPos = ConvertVector(prim.GetWorldPosition());
  303. warp_Quaternion primRot = ConvertQuaternion(prim.RotationOffset);
  304. warp_Matrix m = warp_Matrix.quaternionMatrix(primRot);
  305. if (prim.ParentID != 0)
  306. {
  307. SceneObjectGroup group = m_scene.SceneGraph.GetGroupByPrim(prim.LocalId);
  308. if (group != null)
  309. m.transform(warp_Matrix.quaternionMatrix(ConvertQuaternion(group.RootPart.RotationOffset)));
  310. }
  311. warp_Vector primScale = ConvertVector(prim.Scale);
  312. string primID = prim.UUID.ToString();
  313. // Create the prim faces
  314. // TODO: Implement the useTextures flag behavior
  315. for (int i = 0; i < renderMesh.Faces.Count; i++)
  316. {
  317. Face face = renderMesh.Faces[i];
  318. string meshName = primID + "-Face-" + i.ToString();
  319. // Avoid adding duplicate meshes to the scene
  320. if (renderer.Scene.objectData.ContainsKey(meshName))
  321. {
  322. continue;
  323. }
  324. warp_Object faceObj = new warp_Object(face.Vertices.Count, face.Indices.Count / 3);
  325. for (int j = 0; j < face.Vertices.Count; j++)
  326. {
  327. Vertex v = face.Vertices[j];
  328. warp_Vector pos = ConvertVector(v.Position);
  329. warp_Vector norm = ConvertVector(v.Normal);
  330. if (prim.Shape.SculptTexture == UUID.Zero)
  331. norm = norm.reverse();
  332. warp_Vertex vert = new warp_Vertex(pos, norm, v.TexCoord.X, v.TexCoord.Y);
  333. faceObj.addVertex(vert);
  334. }
  335. for (int j = 0; j < face.Indices.Count; j += 3)
  336. {
  337. faceObj.addTriangle(
  338. face.Indices[j + 0],
  339. face.Indices[j + 1],
  340. face.Indices[j + 2]);
  341. }
  342. Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
  343. Color4 faceColor = GetFaceColor(teFace);
  344. string materialName = GetOrCreateMaterial(renderer, faceColor);
  345. faceObj.transform(m);
  346. faceObj.setPos(primPos);
  347. faceObj.scaleSelf(primScale.x, primScale.y, primScale.z);
  348. renderer.Scene.addObject(meshName, faceObj);
  349. renderer.SetObjectMaterial(meshName, materialName);
  350. }
  351. }
  352. private Color4 GetFaceColor(Primitive.TextureEntryFace face)
  353. {
  354. Color4 color;
  355. if (face.TextureID == UUID.Zero)
  356. return face.RGBA;
  357. if (!m_colors.TryGetValue(face.TextureID, out color))
  358. {
  359. bool fetched = false;
  360. // Attempt to fetch the texture metadata
  361. UUID metadataID = UUID.Combine(face.TextureID, TEXTURE_METADATA_MAGIC);
  362. AssetBase metadata = m_scene.AssetService.GetCached(metadataID.ToString());
  363. if (metadata != null)
  364. {
  365. OSDMap map = null;
  366. try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { }
  367. if (map != null)
  368. {
  369. color = map["X-JPEG2000-RGBA"].AsColor4();
  370. fetched = true;
  371. }
  372. }
  373. if (!fetched)
  374. {
  375. // Fetch the texture, decode and get the average color,
  376. // then save it to a temporary metadata asset
  377. AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString());
  378. if (textureAsset != null)
  379. {
  380. int width, height;
  381. color = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height);
  382. OSDMap data = new OSDMap { { "X-JPEG2000-RGBA", OSD.FromColor4(color) } };
  383. metadata = new AssetBase
  384. {
  385. Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)),
  386. Description = "Metadata for JPEG2000 texture " + face.TextureID.ToString(),
  387. Flags = AssetFlags.Collectable,
  388. FullID = metadataID,
  389. ID = metadataID.ToString(),
  390. Local = true,
  391. Temporary = true,
  392. Name = String.Empty,
  393. Type = (sbyte)AssetType.Unknown
  394. };
  395. m_scene.AssetService.Store(metadata);
  396. }
  397. else
  398. {
  399. color = new Color4(0.5f, 0.5f, 0.5f, 1.0f);
  400. }
  401. }
  402. m_colors[face.TextureID] = color;
  403. }
  404. return color * face.RGBA;
  405. }
  406. private string GetOrCreateMaterial(WarpRenderer renderer, Color4 color)
  407. {
  408. string name = color.ToString();
  409. warp_Material material = renderer.Scene.material(name);
  410. if (material != null)
  411. return name;
  412. renderer.AddMaterial(name, ConvertColor(color));
  413. if (color.A < 1f)
  414. renderer.Scene.material(name).setTransparency((byte)((1f - color.A) * 255f));
  415. return name;
  416. }
  417. #endregion Rendering Methods
  418. #region Static Helpers
  419. private static warp_Vector ConvertVector(Vector3 vector)
  420. {
  421. return new warp_Vector(vector.X, vector.Z, vector.Y);
  422. }
  423. private static warp_Quaternion ConvertQuaternion(Quaternion quat)
  424. {
  425. return new warp_Quaternion(quat.X, quat.Z, quat.Y, -quat.W);
  426. }
  427. private static int ConvertColor(Color4 color)
  428. {
  429. int c = warp_Color.getColor((byte)(color.R * 255f), (byte)(color.G * 255f), (byte)(color.B * 255f));
  430. if (color.A < 1f)
  431. c |= (byte)(color.A * 255f) << 24;
  432. return c;
  433. }
  434. private static Vector3 SurfaceNormal(Vector3 c1, Vector3 c2, Vector3 c3)
  435. {
  436. Vector3 edge1 = new Vector3(c2.X - c1.X, c2.Y - c1.Y, c2.Z - c1.Z);
  437. Vector3 edge2 = new Vector3(c3.X - c1.X, c3.Y - c1.Y, c3.Z - c1.Z);
  438. Vector3 normal = Vector3.Cross(edge1, edge2);
  439. normal.Normalize();
  440. return normal;
  441. }
  442. public static Color4 GetAverageColor(UUID textureID, byte[] j2kData, out int width, out int height)
  443. {
  444. ulong r = 0;
  445. ulong g = 0;
  446. ulong b = 0;
  447. ulong a = 0;
  448. using (MemoryStream stream = new MemoryStream(j2kData))
  449. {
  450. try
  451. {
  452. int pixelBytes;
  453. using (Bitmap bitmap = (Bitmap)J2kImage.FromStream(stream))
  454. {
  455. width = bitmap.Width;
  456. height = bitmap.Height;
  457. BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
  458. pixelBytes = (bitmap.PixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4;
  459. // Sum up the individual channels
  460. unsafe
  461. {
  462. if (pixelBytes == 4)
  463. {
  464. for (int y = 0; y < height; y++)
  465. {
  466. byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
  467. for (int x = 0; x < width; x++)
  468. {
  469. b += row[x * pixelBytes + 0];
  470. g += row[x * pixelBytes + 1];
  471. r += row[x * pixelBytes + 2];
  472. a += row[x * pixelBytes + 3];
  473. }
  474. }
  475. }
  476. else
  477. {
  478. for (int y = 0; y < height; y++)
  479. {
  480. byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
  481. for (int x = 0; x < width; x++)
  482. {
  483. b += row[x * pixelBytes + 0];
  484. g += row[x * pixelBytes + 1];
  485. r += row[x * pixelBytes + 2];
  486. }
  487. }
  488. }
  489. }
  490. }
  491. // Get the averages for each channel
  492. const decimal OO_255 = 1m / 255m;
  493. decimal totalPixels = (decimal)(width * height);
  494. decimal rm = ((decimal)r / totalPixels) * OO_255;
  495. decimal gm = ((decimal)g / totalPixels) * OO_255;
  496. decimal bm = ((decimal)b / totalPixels) * OO_255;
  497. decimal am = ((decimal)a / totalPixels) * OO_255;
  498. if (pixelBytes == 3)
  499. am = 1m;
  500. return new Color4((float)rm, (float)gm, (float)bm, (float)am);
  501. }
  502. catch (Exception ex)
  503. {
  504. m_log.WarnFormat(
  505. "[WARP 3D IMAGE MODULE]: Error decoding JPEG2000 texture {0} ({1} bytes): {2}",
  506. textureID, j2kData.Length, ex.Message);
  507. width = 0;
  508. height = 0;
  509. return new Color4(0.5f, 0.5f, 0.5f, 1.0f);
  510. }
  511. }
  512. }
  513. #endregion Static Helpers
  514. }
  515. public static class ImageUtils
  516. {
  517. /// <summary>
  518. /// Performs bilinear interpolation between four values
  519. /// </summary>
  520. /// <param name="v00">First, or top left value</param>
  521. /// <param name="v01">Second, or top right value</param>
  522. /// <param name="v10">Third, or bottom left value</param>
  523. /// <param name="v11">Fourth, or bottom right value</param>
  524. /// <param name="xPercent">Interpolation value on the X axis, between 0.0 and 1.0</param>
  525. /// <param name="yPercent">Interpolation value on fht Y axis, between 0.0 and 1.0</param>
  526. /// <returns>The bilinearly interpolated result</returns>
  527. public static float Bilinear(float v00, float v01, float v10, float v11, float xPercent, float yPercent)
  528. {
  529. return Utils.Lerp(Utils.Lerp(v00, v01, xPercent), Utils.Lerp(v10, v11, xPercent), yPercent);
  530. }
  531. /// <summary>
  532. /// Performs a high quality image resize
  533. /// </summary>
  534. /// <param name="image">Image to resize</param>
  535. /// <param name="width">New width</param>
  536. /// <param name="height">New height</param>
  537. /// <returns>Resized image</returns>
  538. public static Bitmap ResizeImage(Image image, int width, int height)
  539. {
  540. Bitmap result = new Bitmap(width, height);
  541. using (Graphics graphics = Graphics.FromImage(result))
  542. {
  543. graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  544. graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  545. graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  546. graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
  547. graphics.DrawImage(image, 0, 0, result.Width, result.Height);
  548. }
  549. return result;
  550. }
  551. }
  552. }