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