Warp3DImageModule.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  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 Warp3D;
  37. using Mono.Addins;
  38. using OpenSim.Framework;
  39. using OpenSim.Region.Framework.Interfaces;
  40. using OpenSim.Region.Framework.Scenes;
  41. using OpenSim.Region.PhysicsModules.SharedBase;
  42. using OpenSim.Services.Interfaces;
  43. using OpenMetaverse;
  44. using OpenMetaverse.Assets;
  45. using OpenMetaverse.Imaging;
  46. using OpenMetaverse.Rendering;
  47. using OpenMetaverse.StructuredData;
  48. using WarpRenderer = global::Warp3D.Warp3D;
  49. namespace OpenSim.Region.CoreModules.World.Warp3DMap
  50. {
  51. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "Warp3DImageModule")]
  52. public class Warp3DImageModule : IMapImageGenerator, INonSharedRegionModule
  53. {
  54. private static readonly UUID TEXTURE_METADATA_MAGIC = new UUID("802dc0e0-f080-4931-8b57-d1be8611c4f3");
  55. private static readonly Color4 WATER_COLOR = new Color4(29, 72, 96, 216);
  56. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  57. #pragma warning disable 414
  58. private static string LogHeader = "[WARP 3D IMAGE MODULE]";
  59. #pragma warning restore 414
  60. private Scene m_scene;
  61. private IRendering m_primMesher;
  62. private Dictionary<UUID, Color4> m_colors = new Dictionary<UUID, Color4>();
  63. private IConfigSource m_config;
  64. private bool m_drawPrimVolume = true; // true if should render the prims on the tile
  65. private bool m_textureTerrain = true; // true if to create terrain splatting texture
  66. private bool m_texturePrims = true; // true if should texture the rendered prims
  67. private float m_texturePrimSize = 48f; // size of prim before we consider texturing it
  68. private bool m_renderMeshes = false; // true if to render meshes rather than just bounding boxes
  69. private bool m_Enabled = false;
  70. // private Bitmap lastImage = null;
  71. private DateTime lastImageTime = DateTime.MinValue;
  72. #region Region Module interface
  73. public void Initialise(IConfigSource source)
  74. {
  75. m_config = source;
  76. string[] configSections = new string[] { "Map", "Startup" };
  77. if (Util.GetConfigVarFromSections<string>(
  78. m_config, "MapImageModule", configSections, "MapImageModule") != "Warp3DImageModule")
  79. return;
  80. m_Enabled = true;
  81. m_drawPrimVolume
  82. = Util.GetConfigVarFromSections<bool>(m_config, "DrawPrimOnMapTile", configSections, m_drawPrimVolume);
  83. m_textureTerrain
  84. = Util.GetConfigVarFromSections<bool>(m_config, "TextureOnMapTile", configSections, m_textureTerrain);
  85. m_texturePrims
  86. = Util.GetConfigVarFromSections<bool>(m_config, "TexturePrims", configSections, m_texturePrims);
  87. m_texturePrimSize
  88. = Util.GetConfigVarFromSections<float>(m_config, "TexturePrimSize", configSections, m_texturePrimSize);
  89. m_renderMeshes
  90. = Util.GetConfigVarFromSections<bool>(m_config, "RenderMeshes", configSections, m_renderMeshes);
  91. }
  92. public void AddRegion(Scene scene)
  93. {
  94. if (!m_Enabled)
  95. return;
  96. m_scene = scene;
  97. List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
  98. if (renderers.Count > 0)
  99. m_log.Info("[MAPTILE]: Loaded prim mesher " + renderers[0]);
  100. else
  101. m_log.Info("[MAPTILE]: No prim mesher loaded, prim rendering will be disabled");
  102. m_scene.RegisterModuleInterface<IMapImageGenerator>(this);
  103. }
  104. public void RegionLoaded(Scene scene)
  105. {
  106. }
  107. public void RemoveRegion(Scene scene)
  108. {
  109. }
  110. public void Close()
  111. {
  112. }
  113. public string Name
  114. {
  115. get { return "Warp3DImageModule"; }
  116. }
  117. public Type ReplaceableInterface
  118. {
  119. get { return null; }
  120. }
  121. #endregion
  122. #region IMapImageGenerator Members
  123. public Bitmap CreateMapTile()
  124. {
  125. /* this must be on all map, not just its image
  126. if ((DateTime.Now - lastImageTime).TotalSeconds < 3600)
  127. {
  128. return (Bitmap)lastImage.Clone();
  129. }
  130. */
  131. List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
  132. if (renderers.Count > 0)
  133. {
  134. m_primMesher = RenderingLoader.LoadRenderer(renderers[0]);
  135. }
  136. Vector3 camPos = new Vector3(
  137. m_scene.RegionInfo.RegionSizeX / 2 - 0.5f,
  138. m_scene.RegionInfo.RegionSizeY / 2 - 0.5f,
  139. 221.7025033688163f);
  140. // Viewport viewing down onto the region
  141. Viewport viewport = new Viewport(camPos, -Vector3.UnitZ, 1024f, 0.1f,
  142. (int)m_scene.RegionInfo.RegionSizeX, (int)m_scene.RegionInfo.RegionSizeY,
  143. (float)m_scene.RegionInfo.RegionSizeX, (float)m_scene.RegionInfo.RegionSizeY);
  144. Bitmap tile = CreateMapTile(viewport, false);
  145. m_primMesher = null;
  146. return tile;
  147. /*
  148. lastImage = tile;
  149. lastImageTime = DateTime.Now;
  150. return (Bitmap)lastImage.Clone();
  151. */
  152. }
  153. public Bitmap CreateViewImage(Vector3 camPos, Vector3 camDir, float fov, int width, int height, bool useTextures)
  154. {
  155. Viewport viewport = new Viewport(camPos, camDir, fov, Constants.RegionSize, 0.1f, width, height);
  156. return CreateMapTile(viewport, useTextures);
  157. }
  158. public Bitmap CreateMapTile(Viewport viewport, bool useTextures)
  159. {
  160. m_colors.Clear();
  161. int width = viewport.Width;
  162. int height = viewport.Height;
  163. WarpRenderer renderer = new WarpRenderer();
  164. if(!renderer.CreateScene(width, height))
  165. return new Bitmap(width,height);
  166. #region Camera
  167. warp_Vector pos = ConvertVector(viewport.Position);
  168. warp_Vector lookat = warp_Vector.add(ConvertVector(viewport.Position), ConvertVector(viewport.LookDirection));
  169. renderer.Scene.defaultCamera.setPos(pos);
  170. renderer.Scene.defaultCamera.lookAt(lookat);
  171. if (viewport.Orthographic)
  172. {
  173. renderer.Scene.defaultCamera.setOrthographic(true,viewport.OrthoWindowWidth, viewport.OrthoWindowHeight);
  174. }
  175. else
  176. {
  177. float fov = viewport.FieldOfView;
  178. fov *= 1.75f; // FIXME: ???
  179. renderer.Scene.defaultCamera.setFov(fov);
  180. }
  181. #endregion Camera
  182. renderer.Scene.addLight("Light1", new warp_Light(new warp_Vector(1.0f, 0.5f, 1f), 0xffffff, 0, 320, 40));
  183. renderer.Scene.addLight("Light2", new warp_Light(new warp_Vector(-1f, -1f, 1f), 0xffffff, 0, 100, 40));
  184. CreateWater(renderer);
  185. CreateTerrain(renderer, m_textureTerrain);
  186. if (m_drawPrimVolume)
  187. CreateAllPrims(renderer, useTextures);
  188. renderer.Render();
  189. Bitmap bitmap = renderer.Scene.getImage();
  190. renderer.Scene.destroy();
  191. renderer.Reset();
  192. renderer = null;
  193. viewport = null;
  194. m_colors.Clear();
  195. GC.Collect();
  196. m_log.Debug("[WARP 3D IMAGE MODULE]: GC.Collect()");
  197. return bitmap;
  198. }
  199. public byte[] WriteJpeg2000Image()
  200. {
  201. try
  202. {
  203. using (Bitmap mapbmp = CreateMapTile())
  204. return OpenJPEG.EncodeFromImage(mapbmp, true);
  205. }
  206. catch (Exception e)
  207. {
  208. // JPEG2000 encoder failed
  209. m_log.Error("[WARP 3D IMAGE MODULE]: Failed generating terrain map: ", e);
  210. }
  211. return null;
  212. }
  213. #endregion
  214. #region Rendering Methods
  215. // Add a water plane to the renderer.
  216. private void CreateWater(WarpRenderer renderer)
  217. {
  218. float waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
  219. renderer.AddPlane("Water", m_scene.RegionInfo.RegionSizeX * 0.5f);
  220. renderer.Scene.sceneobject("Water").setPos(m_scene.RegionInfo.RegionSizeX * 0.5f - 0.5f,
  221. waterHeight,
  222. m_scene.RegionInfo.RegionSizeY * 0.5f - 0.5f);
  223. warp_Material waterColorMaterial = new warp_Material(ConvertColor(WATER_COLOR));
  224. waterColorMaterial.setReflectivity(0); // match water color with standard map module thanks lkalif
  225. waterColorMaterial.setTransparency((byte)((1f - WATER_COLOR.A) * 255f));
  226. renderer.Scene.addMaterial("WaterColor", waterColorMaterial);
  227. renderer.SetObjectMaterial("Water", "WaterColor");
  228. }
  229. // Add a terrain to the renderer.
  230. // Note that we create a 'low resolution' 256x256 vertex terrain rather than trying for
  231. // full resolution. This saves a lot of memory especially for very large regions.
  232. private void CreateTerrain(WarpRenderer renderer, bool textureTerrain)
  233. {
  234. ITerrainChannel terrain = m_scene.Heightmap;
  235. float regionsx = m_scene.RegionInfo.RegionSizeX;
  236. float regionsy = m_scene.RegionInfo.RegionSizeY;
  237. // 'diff' is the difference in scale between the real region size and the size of terrain we're buiding
  238. float diff = regionsx / 256f;
  239. int npointsx =(int)(regionsx / diff);
  240. int npointsy =(int)(regionsy / diff);
  241. float invsx = 1.0f / regionsx;
  242. float invsy = 1.0f / (float)m_scene.RegionInfo.RegionSizeY;
  243. // Create all the vertices for the terrain
  244. warp_Object obj = new warp_Object();
  245. for (float y = 0; y < regionsy; y += diff)
  246. {
  247. for (float x = 0; x < regionsx; x += diff)
  248. {
  249. warp_Vector pos = ConvertVector(x , y , (float)terrain[(int)x, (int)y]);
  250. obj.addVertex(new warp_Vertex(pos, x * invsx, 1.0f - y * invsy));
  251. }
  252. }
  253. // Now that we have all the vertices, make another pass and
  254. // create the list of triangle indices.
  255. float invdiff = 1.0f / diff;
  256. int limx = npointsx - 1;
  257. int limy = npointsy - 1;
  258. for (float y = 0; y < regionsy; y += diff)
  259. {
  260. for (float x = 0; x < regionsx; x += diff)
  261. {
  262. float newX = x * invdiff;
  263. float newY = y * invdiff;
  264. if (newX < limx && newY < limy)
  265. {
  266. int v = (int)newY * npointsx + (int)newX;
  267. // Make two triangles for each of the squares in the grid of vertices
  268. obj.addTriangle(
  269. v,
  270. v + 1,
  271. v + npointsx);
  272. obj.addTriangle(
  273. v + npointsx + 1,
  274. v + npointsx,
  275. v + 1);
  276. }
  277. }
  278. }
  279. renderer.Scene.addObject("Terrain", obj);
  280. UUID[] textureIDs = new UUID[4];
  281. float[] startHeights = new float[4];
  282. float[] heightRanges = new float[4];
  283. OpenSim.Framework.RegionSettings regionInfo = m_scene.RegionInfo.RegionSettings;
  284. textureIDs[0] = regionInfo.TerrainTexture1;
  285. textureIDs[1] = regionInfo.TerrainTexture2;
  286. textureIDs[2] = regionInfo.TerrainTexture3;
  287. textureIDs[3] = regionInfo.TerrainTexture4;
  288. startHeights[0] = (float)regionInfo.Elevation1SW;
  289. startHeights[1] = (float)regionInfo.Elevation1NW;
  290. startHeights[2] = (float)regionInfo.Elevation1SE;
  291. startHeights[3] = (float)regionInfo.Elevation1NE;
  292. heightRanges[0] = (float)regionInfo.Elevation2SW;
  293. heightRanges[1] = (float)regionInfo.Elevation2NW;
  294. heightRanges[2] = (float)regionInfo.Elevation2SE;
  295. heightRanges[3] = (float)regionInfo.Elevation2NE;
  296. uint globalX, globalY;
  297. Util.RegionHandleToWorldLoc(m_scene.RegionInfo.RegionHandle, out globalX, out globalY);
  298. warp_Texture texture;
  299. using (Bitmap image = TerrainSplat.Splat(
  300. terrain, textureIDs, startHeights, heightRanges,
  301. new Vector3d(globalX, globalY, 0.0), m_scene.AssetService, textureTerrain))
  302. texture = new warp_Texture(image);
  303. warp_Material material = new warp_Material(texture);
  304. material.setReflectivity(50);
  305. renderer.Scene.addMaterial("TerrainColor", material);
  306. renderer.Scene.material("TerrainColor").setReflectivity(0); // reduces tile seams a bit thanks lkalif
  307. renderer.SetObjectMaterial("Terrain", "TerrainColor");
  308. }
  309. private void CreateAllPrims(WarpRenderer renderer, bool useTextures)
  310. {
  311. if (m_primMesher == null)
  312. return;
  313. m_scene.ForEachSOG(
  314. delegate(SceneObjectGroup group)
  315. {
  316. foreach (SceneObjectPart child in group.Parts)
  317. CreatePrim(renderer, child, useTextures);
  318. }
  319. );
  320. }
  321. private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim,
  322. bool useTextures)
  323. {
  324. const float MIN_SIZE_SQUARE = 4f;
  325. if ((PCode)prim.Shape.PCode != PCode.Prim)
  326. return;
  327. float primScaleLenSquared = prim.Scale.LengthSquared();
  328. if (primScaleLenSquared < MIN_SIZE_SQUARE)
  329. return;
  330. FacetedMesh renderMesh = null;
  331. Primitive omvPrim = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset);
  332. if (m_renderMeshes)
  333. {
  334. if (omvPrim.Sculpt != null && omvPrim.Sculpt.SculptTexture != UUID.Zero)
  335. {
  336. // Try fetchinng the asset
  337. byte[] sculptAsset = m_scene.AssetService.GetData(omvPrim.Sculpt.SculptTexture.ToString());
  338. if (sculptAsset != null)
  339. {
  340. // Is it a mesh?
  341. if (omvPrim.Sculpt.Type == SculptType.Mesh)
  342. {
  343. AssetMesh meshAsset = new AssetMesh(omvPrim.Sculpt.SculptTexture, sculptAsset);
  344. FacetedMesh.TryDecodeFromAsset(omvPrim, meshAsset, DetailLevel.Highest, out renderMesh);
  345. meshAsset = null;
  346. }
  347. else // It's sculptie
  348. {
  349. IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>();
  350. if(imgDecoder != null)
  351. {
  352. Image sculpt = imgDecoder.DecodeToImage(sculptAsset);
  353. if(sculpt != null)
  354. {
  355. renderMesh = m_primMesher.GenerateFacetedSculptMesh(omvPrim,(Bitmap)sculpt,
  356. DetailLevel.Medium);
  357. sculpt.Dispose();
  358. }
  359. }
  360. }
  361. }
  362. }
  363. }
  364. // If not a mesh or sculptie, try the regular mesher
  365. if (renderMesh == null)
  366. {
  367. renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);
  368. }
  369. if (renderMesh == null)
  370. return;
  371. string primID = prim.UUID.ToString();
  372. // Create the prim faces
  373. // TODO: Implement the useTextures flag behavior
  374. for (int i = 0; i < renderMesh.Faces.Count; i++)
  375. {
  376. Face face = renderMesh.Faces[i];
  377. string meshName = primID + i.ToString();
  378. // Avoid adding duplicate meshes to the scene
  379. if (renderer.Scene.objectData.ContainsKey(meshName))
  380. continue;
  381. warp_Object faceObj = new warp_Object();
  382. for (int j = 0; j < face.Vertices.Count; j++)
  383. {
  384. Vertex v = face.Vertices[j];
  385. warp_Vector pos = ConvertVector(v.Position);
  386. warp_Vertex vert = new warp_Vertex(pos, v.TexCoord.X, v.TexCoord.Y);
  387. faceObj.addVertex(vert);
  388. }
  389. for (int j = 0; j < face.Indices.Count; j += 3)
  390. {
  391. faceObj.addTriangle(
  392. face.Indices[j + 0],
  393. face.Indices[j + 1],
  394. face.Indices[j + 2]);
  395. }
  396. Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
  397. Color4 faceColor = GetFaceColor(teFace);
  398. string materialName = String.Empty;
  399. if (m_texturePrims && primScaleLenSquared > m_texturePrimSize*m_texturePrimSize)
  400. materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID);
  401. else
  402. materialName = GetOrCreateMaterial(renderer, faceColor);
  403. warp_Vector primPos = ConvertVector(prim.GetWorldPosition());
  404. warp_Quaternion primRot = ConvertQuaternion(prim.GetWorldRotation());
  405. warp_Matrix m = warp_Matrix.quaternionMatrix(primRot);
  406. faceObj.transform(m);
  407. faceObj.setPos(primPos);
  408. faceObj.scaleSelf(prim.Scale.X, prim.Scale.Z, prim.Scale.Y);
  409. renderer.Scene.addObject(meshName, faceObj);
  410. renderer.SetObjectMaterial(meshName, materialName);
  411. }
  412. }
  413. private Color4 GetFaceColor(Primitive.TextureEntryFace face)
  414. {
  415. Color4 color;
  416. if (face.TextureID == UUID.Zero)
  417. return face.RGBA;
  418. if (!m_colors.TryGetValue(face.TextureID, out color))
  419. {
  420. bool fetched = false;
  421. // Attempt to fetch the texture metadata
  422. UUID metadataID = UUID.Combine(face.TextureID, TEXTURE_METADATA_MAGIC);
  423. AssetBase metadata = m_scene.AssetService.GetCached(metadataID.ToString());
  424. if (metadata != null)
  425. {
  426. OSDMap map = null;
  427. try { map = OSDParser.Deserialize(metadata.Data) as OSDMap; } catch { }
  428. if (map != null)
  429. {
  430. color = map["X-JPEG2000-RGBA"].AsColor4();
  431. fetched = true;
  432. }
  433. }
  434. if (!fetched)
  435. {
  436. // Fetch the texture, decode and get the average color,
  437. // then save it to a temporary metadata asset
  438. AssetBase textureAsset = m_scene.AssetService.Get(face.TextureID.ToString());
  439. if (textureAsset != null)
  440. {
  441. int width, height;
  442. color = GetAverageColor(textureAsset.FullID, textureAsset.Data, out width, out height);
  443. OSDMap data = new OSDMap { { "X-JPEG2000-RGBA", OSD.FromColor4(color) } };
  444. metadata = new AssetBase
  445. {
  446. Data = System.Text.Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(data)),
  447. Description = "Metadata for JPEG2000 texture " + face.TextureID.ToString(),
  448. Flags = AssetFlags.Collectable,
  449. FullID = metadataID,
  450. ID = metadataID.ToString(),
  451. Local = true,
  452. Temporary = true,
  453. Name = String.Empty,
  454. Type = (sbyte)AssetType.Unknown
  455. };
  456. m_scene.AssetService.Store(metadata);
  457. }
  458. else
  459. {
  460. color = new Color4(0.5f, 0.5f, 0.5f, 1.0f);
  461. }
  462. }
  463. m_colors[face.TextureID] = color;
  464. }
  465. return color * face.RGBA;
  466. }
  467. private string GetOrCreateMaterial(WarpRenderer renderer, Color4 color)
  468. {
  469. string name = color.ToString();
  470. warp_Material material = renderer.Scene.material(name);
  471. if (material != null)
  472. return name;
  473. renderer.AddMaterial(name, ConvertColor(color));
  474. if (color.A < 1f)
  475. renderer.Scene.material(name).setTransparency((byte)((1f - color.A) * 255f));
  476. return name;
  477. }
  478. public string GetOrCreateMaterial(WarpRenderer renderer, Color4 faceColor, UUID textureID)
  479. {
  480. string materialName = "Color-" + faceColor.ToString() + "-Texture-" + textureID.ToString();
  481. if (renderer.Scene.material(materialName) == null)
  482. {
  483. renderer.AddMaterial(materialName, ConvertColor(faceColor));
  484. if (faceColor.A < 1f)
  485. {
  486. renderer.Scene.material(materialName).setTransparency((byte) ((1f - faceColor.A)*255f));
  487. }
  488. warp_Texture texture = GetTexture(textureID);
  489. if (texture != null)
  490. renderer.Scene.material(materialName).setTexture(texture);
  491. }
  492. return materialName;
  493. }
  494. private warp_Texture GetTexture(UUID id)
  495. {
  496. warp_Texture ret = null;
  497. byte[] asset = m_scene.AssetService.GetData(id.ToString());
  498. if (asset != null)
  499. {
  500. IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>();
  501. try
  502. {
  503. using (Bitmap img = (Bitmap)imgDecoder.DecodeToImage(asset))
  504. ret = new warp_Texture(img);
  505. }
  506. catch (Exception e)
  507. {
  508. m_log.Warn(string.Format("[WARP 3D IMAGE MODULE]: Failed to decode asset {0}, exception ", id), e);
  509. }
  510. }
  511. return ret;
  512. }
  513. #endregion Rendering Methods
  514. #region Static Helpers
  515. // Note: axis change.
  516. private static warp_Vector ConvertVector(float x, float y, float z)
  517. {
  518. return new warp_Vector(x, z, y);
  519. }
  520. private static warp_Vector ConvertVector(Vector3 vector)
  521. {
  522. return new warp_Vector(vector.X, vector.Z, vector.Y);
  523. }
  524. private static warp_Quaternion ConvertQuaternion(Quaternion quat)
  525. {
  526. return new warp_Quaternion(quat.X, quat.Z, quat.Y, -quat.W);
  527. }
  528. private static int ConvertColor(Color4 color)
  529. {
  530. int c = warp_Color.getColor((byte)(color.R * 255f), (byte)(color.G * 255f), (byte)(color.B * 255f));
  531. if (color.A < 1f)
  532. c |= (byte)(color.A * 255f) << 24;
  533. return c;
  534. }
  535. private static Vector3 SurfaceNormal(Vector3 c1, Vector3 c2, Vector3 c3)
  536. {
  537. Vector3 edge1 = new Vector3(c2.X - c1.X, c2.Y - c1.Y, c2.Z - c1.Z);
  538. Vector3 edge2 = new Vector3(c3.X - c1.X, c3.Y - c1.Y, c3.Z - c1.Z);
  539. Vector3 normal = Vector3.Cross(edge1, edge2);
  540. normal.Normalize();
  541. return normal;
  542. }
  543. public static Color4 GetAverageColor(UUID textureID, byte[] j2kData, out int width, out int height)
  544. {
  545. ulong r = 0;
  546. ulong g = 0;
  547. ulong b = 0;
  548. ulong a = 0;
  549. using (MemoryStream stream = new MemoryStream(j2kData))
  550. {
  551. try
  552. {
  553. int pixelBytes;
  554. using (Bitmap bitmap = (Bitmap)J2kImage.FromStream(stream))
  555. {
  556. width = bitmap.Width;
  557. height = bitmap.Height;
  558. BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
  559. pixelBytes = (bitmap.PixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4;
  560. // Sum up the individual channels
  561. unsafe
  562. {
  563. if (pixelBytes == 4)
  564. {
  565. for (int y = 0; y < height; y++)
  566. {
  567. byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
  568. for (int x = 0; x < width; x++)
  569. {
  570. b += row[x * pixelBytes + 0];
  571. g += row[x * pixelBytes + 1];
  572. r += row[x * pixelBytes + 2];
  573. a += row[x * pixelBytes + 3];
  574. }
  575. }
  576. }
  577. else
  578. {
  579. for (int y = 0; y < height; y++)
  580. {
  581. byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
  582. for (int x = 0; x < width; x++)
  583. {
  584. b += row[x * pixelBytes + 0];
  585. g += row[x * pixelBytes + 1];
  586. r += row[x * pixelBytes + 2];
  587. }
  588. }
  589. }
  590. }
  591. }
  592. // Get the averages for each channel
  593. const decimal OO_255 = 1m / 255m;
  594. decimal totalPixels = (decimal)(width * height);
  595. decimal rm = ((decimal)r / totalPixels) * OO_255;
  596. decimal gm = ((decimal)g / totalPixels) * OO_255;
  597. decimal bm = ((decimal)b / totalPixels) * OO_255;
  598. decimal am = ((decimal)a / totalPixels) * OO_255;
  599. if (pixelBytes == 3)
  600. am = 1m;
  601. return new Color4((float)rm, (float)gm, (float)bm, (float)am);
  602. }
  603. catch (Exception ex)
  604. {
  605. m_log.WarnFormat(
  606. "[WARP 3D IMAGE MODULE]: Error decoding JPEG2000 texture {0} ({1} bytes): {2}",
  607. textureID, j2kData.Length, ex.Message);
  608. width = 0;
  609. height = 0;
  610. return new Color4(0.5f, 0.5f, 0.5f, 1.0f);
  611. }
  612. }
  613. }
  614. #endregion Static Helpers
  615. }
  616. public static class ImageUtils
  617. {
  618. /// <summary>
  619. /// Performs bilinear interpolation between four values
  620. /// </summary>
  621. /// <param name="v00">First, or top left value</param>
  622. /// <param name="v01">Second, or top right value</param>
  623. /// <param name="v10">Third, or bottom left value</param>
  624. /// <param name="v11">Fourth, or bottom right value</param>
  625. /// <param name="xPercent">Interpolation value on the X axis, between 0.0 and 1.0</param>
  626. /// <param name="yPercent">Interpolation value on fht Y axis, between 0.0 and 1.0</param>
  627. /// <returns>The bilinearly interpolated result</returns>
  628. public static float Bilinear(float v00, float v01, float v10, float v11, float xPercent, float yPercent)
  629. {
  630. return Utils.Lerp(Utils.Lerp(v00, v01, xPercent), Utils.Lerp(v10, v11, xPercent), yPercent);
  631. }
  632. /// <summary>
  633. /// Performs a high quality image resize
  634. /// </summary>
  635. /// <param name="image">Image to resize</param>
  636. /// <param name="width">New width</param>
  637. /// <param name="height">New height</param>
  638. /// <returns>Resized image</returns>
  639. public static Bitmap ResizeImage(Image image, int width, int height)
  640. {
  641. Bitmap result = new Bitmap(width, height);
  642. using (Graphics graphics = Graphics.FromImage(result))
  643. {
  644. graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  645. graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  646. graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  647. graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
  648. graphics.DrawImage(image, 0, 0, result.Width, result.Height);
  649. }
  650. return result;
  651. }
  652. }
  653. }