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