private bool LoadTexture(string basePath, UUID textureID, ref System.Drawing.Image texture) { if (Textures.ContainsKey(textureID)) { texture = Textures[textureID]; return(true); } string texturePath = System.IO.Path.Combine(basePath, textureID.ToString()); if (File.Exists(texturePath + ".tga")) { try { texture = (Image)LoadTGAClass.LoadTGA(texturePath + ".tga"); Textures[textureID] = texture; return(true); } catch (Exception) { } } else if (File.Exists(texturePath + ".jp2")) { try { ManagedImage managedImage; if (OpenJPEG.DecodeToImage(File.ReadAllBytes(texturePath + ".jp2"), out managedImage, out texture)) { Textures[textureID] = texture; return(true); } } catch (Exception) { } } return(false); }
void LoadTerrain(string mapFile) { if (File.Exists(mapFile)) { lock (heightmap) { Bitmap bmp = LoadTGAClass.LoadTGA(mapFile); Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); IntPtr ptr = bmpData.Scan0; int bytes = bmpData.Stride * bmp.Height; byte[] rgbValues = new byte[bytes]; Marshal.Copy(ptr, rgbValues, 0, bytes); bmp.UnlockBits(bmpData); for (int i = 1, pos = 0; i < heightmap.Length; i++, pos += 3) { heightmap[i] = (float)rgbValues[pos]; } if (OnTerrainUpdated != null) { OnTerrainUpdated(this); } } } else { Logger.Log("Map file " + mapFile + " not found, defaulting to 25m", Helpers.LogLevel.Info); server.Scene.Heightmap = new float[65536]; for (int i = 0; i < server.Scene.Heightmap.Length; i++) { server.Scene.Heightmap[i] = 25f; } } }
/// <summary> /// Decode JPEG2000 data to an <seealso cref = "System.Drawing.Image" /> and /// <seealso cref = "ManagedImage" /> /// </summary> /// <param name = "encoded">JPEG2000 encoded data</param> /// <param name = "managedImage">ManagedImage object to decode to</param> /// <param name = "image">Image object to decode to</param> /// <returns>True if the decode succeeds, otherwise false</returns> public static bool DecodeToImage(byte[] encoded, out ManagedImage managedImage, out Image image) { managedImage = null; image = null; if (DecodeToImage(encoded, out managedImage)) { try { image = LoadTGAClass.LoadTGA(new MemoryStream(managedImage.ExportTGA())); return(true); } catch (Exception ex) { Logger.Log("Failed to export and load TGA data from decoded image", Helpers.LogLevel.Error, ex); return(false); } } else { return(false); } }
/// <summary> /// Generate a mesh from the sculpt data the accompanies a prim. /// </summary> /// <param name="primName"></param> /// <param name="primShape"></param> /// <param name="size"></param> /// <param name="lod"></param> /// <param name="key"></param> /// <returns>created mesh or null if invalid</returns> Mesh GenerateFromPrimSculptData(string primName, PrimitiveBaseShape primShape, Vector3 size, float lod, ulong key) { SculptMesh sculptMesh; Image idata = null; string decodedSculptFileName = ""; if (cacheSculptMaps && primShape.SculptTexture != UUID.Zero) { decodedSculptFileName = System.IO.Path.Combine(decodedSculptMapPath, "smap_" + primShape.SculptTexture); try { if (File.Exists(decodedSculptFileName)) { idata = Image.FromFile(decodedSculptFileName); } } catch (Exception e) { MainConsole.Instance.Error("[Sculpt]: unable to load cached sculpt map " + decodedSculptFileName + " " + e); } //if (idata != null) // MainConsole.Instance.Debug("[SCULPT]: loaded cached map asset for map ID: " + primShape.SculptTexture.ToString()); } if (idata == null) { if (primShape.SculptData == null || primShape.SculptData.Length == 0) { return(null); } try { //idata = m_j2kDecoder.DecodeToImage (primShape.SculptData); ManagedImage mImage; OpenJPEG.DecodeToImage(primShape.SculptData, out mImage); if (mImage == null) { // In some cases it seems that the decode can return a null bitmap without throwing an exception MainConsole.Instance.WarnFormat("[Sculpt]: OpenJPEG decoded sculpt data for {0} to a null bitmap. Ignoring.", primName); return(null); } if ((mImage.Channels & ManagedImage.ImageChannels.Alpha) != 0) { mImage.ConvertChannels(mImage.Channels & ~ManagedImage.ImageChannels.Alpha); } Bitmap imgData = LoadTGAClass.LoadTGA(new MemoryStream(mImage.ExportTGA())); idata = imgData; mImage = null; if (idata != null && cacheSculptMaps && (cacheSculptAlphaMaps || (((ImageFlags)(idata.Flags) & ImageFlags.HasAlpha) == 0))) { try { idata.Save(decodedSculptFileName, ImageFormat.MemoryBmp); } catch (Exception e) { MainConsole.Instance.Error("[Sculpt]: unable to cache sculpt map " + decodedSculptFileName + " " + e); } } } catch (DllNotFoundException) { MainConsole.Instance.Error( "[Physics]: OpenJpeg is not installed correctly on this system. Physics Proxy generation failed.\n" + "Often times this is because of an old version of GLIBC. You must have version 2.4 or above!"); return(null); } catch (IndexOutOfRangeException) { MainConsole.Instance.Error( "[Physics]: OpenJpeg was unable to decode this. Physics Proxy generation failed"); return(null); } catch (Exception ex) { MainConsole.Instance.Error( "[Physics]: Unable to generate a Sculpty physics proxy. Sculpty texture decode failed: " + ex); return(null); } } SculptMesh.SculptType sculptType; switch ((SculptType)primShape.SculptType) { case SculptType.Cylinder: sculptType = SculptMesh.SculptType.cylinder; break; case SculptType.Plane: sculptType = SculptMesh.SculptType.plane; break; case SculptType.Torus: sculptType = SculptMesh.SculptType.torus; break; case SculptType.Sphere: sculptType = SculptMesh.SculptType.sphere; break; default: sculptType = SculptMesh.SculptType.plane; break; } bool mirror = ((primShape.SculptType & 128) != 0); bool invert = ((primShape.SculptType & 64) != 0); if (idata == null) { return(null); } sculptMesh = new SculptMesh((Bitmap)idata, sculptType, (int)lod, false, mirror, invert); idata.Dispose(); #if SPAM sculptMesh.DumpRaw(baseDir, primName, "primMesh"); #endif sculptMesh.Scale(size.X, size.Y, size.Z); var coords = sculptMesh.coords; var faces = sculptMesh.faces; Mesh mesh = new Mesh(key); mesh.Set(coords, faces); coords.Clear(); faces.Clear(); // debug info only //Console.Write ("S"); return(mesh); }
void LoadImage(ModelMaterial material) { var fname = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(FileName), material.Texture); try { string ext = System.IO.Path.GetExtension(material.Texture).ToLower(); Bitmap bitmap = null; switch (ext) { case ".jp2": case ".j2c": material.TextureData = File.ReadAllBytes(fname); return; case ".tga": bitmap = LoadTGAClass.LoadTGA(fname); break; default: bitmap = (Bitmap)Image.FromFile(fname); break; } int width = bitmap.Width; int height = bitmap.Height; // Handle resizing to prevent excessively large images and irregular dimensions if (!IsPowerOfTwo((uint)width) || !IsPowerOfTwo((uint)height) || width > 1024 || height > 1024) { var origWidth = width; var origHieght = height; width = ClosestPowerOwTwo(width); height = ClosestPowerOwTwo(height); width = width > 1024 ? 1024 : width; height = height > 1024 ? 1024 : height; Logger.Log("Image has irregular dimensions " + origWidth + "x" + origHieght + ". Resizing to " + width + "x" + height, Helpers.LogLevel.Info); Bitmap resized = new Bitmap(width, height, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, width, height); bitmap.Dispose(); bitmap = resized; } using (var writer = new OpenJpegDotNet.IO.Writer(bitmap)) { material.TextureData = writer.Encode(); } Logger.Log("Successfully encoded " + fname, Helpers.LogLevel.Info); } catch (Exception ex) { Logger.Log("Failed loading " + fname + ": " + ex.Message, Helpers.LogLevel.Warning); } }
private void TraverseDir(InventoryNode node, string path) { var nodes = new List <InventoryNode>(node.Nodes.Values); foreach (InventoryNode n in nodes) { traversed++; try { backupTaskCancelToken.Token.ThrowIfCancellationRequested(); if (IsHandleCreated && (traversed % 13 == 0)) { BeginInvoke(new MethodInvoker(() => { lblStatus.Text = string.Format("Traversed {0} nodes...", traversed); })); } if (n.Data is InventoryFolder) { WriteCSVLine("Folder", path, n.Data.Name, "", "", "", ""); TraverseDir(n, Path.Combine(path, RadegastInstance.SafeFileName(n.Data.Name))); } else { InventoryItem item = (InventoryItem)n.Data; string creator = item.CreatorID == UUID.Zero ? string.Empty : instance.Names.Get(item.CreatorID, true); string lastOwner = item.LastOwnerID == UUID.Zero ? string.Empty : instance.Names.Get(item.LastOwnerID, true); string type = item.AssetType.ToString(); if (item.InventoryType == InventoryType.Wearable) { type = ((WearableType)item.Flags).ToString(); } string created = item.CreationDate.ToString("yyyy-MM-dd HH:mm:ss"); WriteCSVLine(type, path, item.Name, item.Description, created, creator, lastOwner); PermissionMask fullPerm = PermissionMask.Modify | PermissionMask.Copy | PermissionMask.Transfer; if ((item.Permissions.OwnerMask & fullPerm) != fullPerm) { continue; } string filePartial = Path.Combine(path, RadegastInstance.SafeFileName(n.Data.Name)); string fullName = folderName + filePartial; switch (item.AssetType) { case AssetType.LSLText: client.Settings.USE_ASSET_CACHE = false; fullName += ".lsl"; break; case AssetType.Notecard: fullName += ".txt"; break; case AssetType.Texture: fullName += ".png"; break; default: fullName += ".bin"; break; } string dirName = Path.GetDirectoryName(fullName); bool dateOK = item.CreationDate > new DateTime(1970, 1, 2); if ( (item.AssetType == AssetType.LSLText && cbScripts.Checked) || (item.AssetType == AssetType.Notecard && cbNoteCards.Checked) || (item.AssetType == AssetType.Texture && cbImages.Checked) ) { ListViewItem lvi = new ListViewItem { Text = n.Data.Name, Tag = n.Data, Name = n.Data.UUID.ToString() }; ListViewItem.ListViewSubItem fileName = new ListViewItem.ListViewSubItem(lvi, filePartial); lvi.SubItems.Add(fileName); ListViewItem.ListViewSubItem status = new ListViewItem.ListViewSubItem(lvi, "Fetching asset"); lvi.SubItems.Add(status); //bool cached = dateOK && File.Exists(fullName) && File.GetCreationTimeUtc(fullName) == item.CreationDate; //if (cached) //{ // status.Text = "Cached"; //} backupTaskCancelToken.Token.ThrowIfCancellationRequested(); BeginInvoke(new MethodInvoker(() => { lvwFiles.Items.Add(lvi); lvwFiles.EnsureVisible(lvwFiles.Items.Count - 1); })); //if (cached) continue; backupTaskCancelToken.Token.ThrowIfCancellationRequested(); Asset receivedAsset = null; using (AutoResetEvent done = new AutoResetEvent(false)) { if (item.AssetType == AssetType.Texture) { client.Assets.RequestImage(item.AssetUUID, (state, asset) => { if (state == TextureRequestState.Finished && asset != null && asset.Decode()) { receivedAsset = asset; done.Set(); } }); } else { var transferID = UUID.Random(); client.Assets.RequestInventoryAsset(item, true, transferID, (transfer, asset) => { if (transfer.Success && transfer.ID == transferID) { receivedAsset = asset; } done.Set(); } ); } backupTaskCancelToken.Token.ThrowIfCancellationRequested(); done.WaitOne(30 * 1000, false); } client.Settings.USE_ASSET_CACHE = true; backupTaskCancelToken.Token.ThrowIfCancellationRequested(); if (receivedAsset == null) { BeginInvoke(new MethodInvoker(() => status.Text = "Failed to fetch asset")); } else { BeginInvoke(new MethodInvoker(() => status.Text = "Saving...")); try { backupTaskCancelToken.Token.ThrowIfCancellationRequested(); if (!Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); } switch (item.AssetType) { case AssetType.Notecard: AssetNotecard note = (AssetNotecard)receivedAsset; if (note.Decode()) { File.WriteAllText(fullName, note.BodyText, System.Text.Encoding.UTF8); if (dateOK) { File.SetCreationTimeUtc(fullName, item.CreationDate); File.SetLastWriteTimeUtc(fullName, item.CreationDate); } } else { Logger.Log(string.Format("Falied to decode asset for '{0}' - {1}", item.Name, receivedAsset.AssetID), Helpers.LogLevel.Warning, client); } break; case AssetType.LSLText: AssetScriptText script = (AssetScriptText)receivedAsset; if (script.Decode()) { File.WriteAllText(fullName, script.Source, System.Text.Encoding.UTF8); if (dateOK) { File.SetCreationTimeUtc(fullName, item.CreationDate); File.SetLastWriteTimeUtc(fullName, item.CreationDate); } } else { Logger.Log(string.Format("Falied to decode asset for '{0}' - {1}", item.Name, receivedAsset.AssetID), Helpers.LogLevel.Warning, client); } break; case AssetType.Texture: AssetTexture imgAsset = (AssetTexture)receivedAsset; var img = LoadTGAClass.LoadTGA(new MemoryStream(imgAsset.Image.ExportTGA())); img.Save(fullName, System.Drawing.Imaging.ImageFormat.Png); if (dateOK) { File.SetCreationTimeUtc(fullName, item.CreationDate); File.SetLastWriteTimeUtc(fullName, item.CreationDate); } break; } BeginInvoke(new MethodInvoker(() => { fileName.Text = fullName; status.Text = "Saved"; lblStatus.Text = string.Format("Saved {0} items", ++fetched); })); } catch (OperationCanceledException) { BeginInvoke(new MethodInvoker(() => status.Text = "Operation cancelled.")); return; } catch (Exception ex) { BeginInvoke(new MethodInvoker(() => status.Text = "Failed to save " + Path.GetFileName(fullName) + ": " + ex.Message)); } } } } } catch (OperationCanceledException) { return; } catch { } } }
private byte[] LoadImage(string fileName) { string lowfilename = fileName.ToLower(CultureInfo.CurrentCulture); Bitmap bitmap = null; try { if (lowfilename.EndsWith(".jp2", StringComparison.CurrentCultureIgnoreCase) || lowfilename.EndsWith(".j2c", StringComparison.CurrentCultureIgnoreCase)) { Image image; ManagedImage managedImage; // Upload JPEG2000 images untouched ImgUp = System.IO.File.ReadAllBytes(fileName); OpenJPEG.DecodeToImage(ImgUp, out managedImage, out image); bitmap = (Bitmap)image; } else { if (lowfilename.EndsWith(".tga", StringComparison.CurrentCultureIgnoreCase)) { bitmap = LoadTGAClass.LoadTGA(fileName); } else { bitmap = (Bitmap)System.Drawing.Image.FromFile(fileName); } int oldwidth = bitmap.Width; int oldheight = bitmap.Height; if (!IsPowerOfTwo((uint)oldwidth) || !IsPowerOfTwo((uint)oldheight)) { Bitmap resized = new Bitmap(256, 256, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, 256, 256); bitmap.Dispose(); bitmap = resized; oldwidth = 256; oldheight = 256; } // Handle resizing to prevent excessively large images if (oldwidth > 1024 || oldheight > 1024) { int newwidth = (oldwidth > 1024) ? 1024 : oldwidth; int newheight = (oldheight > 1024) ? 1024 : oldheight; Bitmap resized = new Bitmap(newwidth, newheight, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, newwidth, newheight); bitmap.Dispose(); bitmap = resized; } ImgUp = OpenJPEG.EncodeFromImage(bitmap, false); } } catch (Exception ex) { label3.Text = ex.ToString() + " SL Image Upload "; return(null); } return(ImgUp); }
public void LoadImage(string fname) { FileName = fname; if (String.IsNullOrEmpty(FileName)) { return; } txtStatus.AppendText("Loading...\n"); string extension = Path.GetExtension(FileName).ToLower(); try { Bitmap bitmap = null; switch (extension) { case ".jp2": case ".j2c": Image image; ManagedImage managedImage; // Upload JPEG2000 images untouched UploadData = File.ReadAllBytes(FileName); OpenJPEG.DecodeToImage(UploadData, out managedImage, out image); bitmap = (Bitmap)image; txtStatus.AppendText("Loaded raw JPEG2000 data " + FileName + "\n"); break; case ".tga": bitmap = LoadTGAClass.LoadTGA(FileName); break; default: bitmap = (Bitmap)Image.FromFile(FileName); break; } txtStatus.AppendText("Loaded image " + FileName + "\n"); int width = bitmap.Width; int height = bitmap.Height; // Handle resizing to prevent excessively large images and irregular dimensions if (!IsPowerOfTwo((uint)width) || !IsPowerOfTwo((uint)height) || width > 1024 || height > 1024) { txtStatus.AppendText("Image has irregular dimensions " + width + "x" + height + "\n"); width = ClosestPowerOwTwo(width); height = ClosestPowerOwTwo(height); width = width > 1024 ? 1024 : width; height = height > 1024 ? 1024 : height; txtStatus.AppendText("Resizing to " + width + "x" + height + "\n"); Bitmap resized = new Bitmap(width, height, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, width, height); bitmap.Dispose(); bitmap = resized; } txtStatus.AppendText("Encoding image...\n"); UploadData = OpenJPEG.EncodeFromImage(bitmap, chkLossless.Checked); txtStatus.AppendText("Finished encoding.\n"); ImageLoaded = true; UpdateButtons(); txtAssetID.Text = UUID.Zero.ToString(); pbPreview.Image = bitmap; lblSize.Text = string.Format("{0}x{1} {2} KB", bitmap.Width, bitmap.Height, Math.Round((double)UploadData.Length / 1024.0d, 2)); } catch (Exception ex) { UploadData = null; btnSave.Enabled = false; btnUpload.Enabled = false; txtStatus.AppendText(string.Format("Failed to load the image:\n{0}\n", ex.Message)); } }
private byte[] LoadImage(string fileName) { byte[] UploadData; string lowfilename = fileName.ToLower(); Bitmap bitmap = null; try { if (lowfilename.EndsWith(".jp2") || lowfilename.EndsWith(".j2c")) { Image image; ManagedImage managedImage; // Upload JPEG2000 images untouched UploadData = System.IO.File.ReadAllBytes(fileName); OpenJPEG.DecodeToImage(UploadData, out managedImage, out image); bitmap = (Bitmap)image; } else { if (lowfilename.EndsWith(".tga")) { bitmap = LoadTGAClass.LoadTGA(fileName); } else { bitmap = (Bitmap)Image.FromFile(fileName); } int oldwidth = bitmap.Width; int oldheight = bitmap.Height; if (!IsPowerOfTwo((uint)oldwidth) || !IsPowerOfTwo((uint)oldheight)) { Bitmap resized = new Bitmap(256, 256, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, 256, 256); bitmap.Dispose(); bitmap = resized; oldwidth = 256; oldheight = 256; } // Handle resizing to prevent excessively large images if (oldwidth > 1024 || oldheight > 1024) { int newwidth = (oldwidth > 1024) ? 1024 : oldwidth; int newheight = (oldheight > 1024) ? 1024 : oldheight; Bitmap resized = new Bitmap(newwidth, newheight, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, newwidth, newheight); bitmap.Dispose(); bitmap = resized; } UploadData = OpenJPEG.EncodeFromImage(bitmap, false); } } catch (Exception ex) { Console.WriteLine(ex.ToString() + " SL Image Upload "); return(null); } return(UploadData); }
/// <summary> /// Creates a faceted mesh from a primitive. /// </summary> /// <param name="Client">the client to use for meshing</param> /// <param name="primitive">the primitive to convert</param> /// <param name="mesher">the mesher to use</param> /// <param name="facetedMesh">a reference to an output facted mesh object</param> /// <param name="millisecondsTimeout">the services timeout</param> /// <returns>true if the mesh could be created successfully</returns> public static bool MakeFacetedMesh(GridClient Client, Primitive primitive, MeshmerizerR mesher, ref FacetedMesh facetedMesh, uint millisecondsTimeout) { if (primitive.Sculpt == null || primitive.Sculpt.SculptTexture.Equals(UUID.Zero)) { facetedMesh = mesher.GenerateFacetedMesh(primitive, DetailLevel.Highest); return(true); } if (!primitive.Sculpt.Type.Equals(SculptType.Mesh)) { byte[] assetData = null; switch (!Client.Assets.Cache.HasAsset(primitive.Sculpt.SculptTexture)) { case true: Locks.ClientInstanceAssetsLock.EnterReadLock(); var ImageDownloadedEvent = new ManualResetEventSlim(false); Client.Assets.RequestImage(primitive.Sculpt.SculptTexture, (state, args) => { if (!state.Equals(TextureRequestState.Finished)) { return; } assetData = args.AssetData; ImageDownloadedEvent.Set(); }); if (!ImageDownloadedEvent.Wait((int)millisecondsTimeout)) { Locks.ClientInstanceAssetsLock.ExitReadLock(); return(false); } Locks.ClientInstanceAssetsLock.ExitReadLock(); break; default: assetData = Client.Assets.Cache.GetCachedAssetBytes(primitive.Sculpt.SculptTexture); break; } Image image; ManagedImage managedImage; switch (!OpenJPEG.DecodeToImage(assetData, out managedImage)) { case true: return(false); default: if ((managedImage.Channels & ManagedImage.ImageChannels.Alpha) != 0) { managedImage.ConvertChannels(managedImage.Channels & ~ManagedImage.ImageChannels.Alpha); } image = LoadTGAClass.LoadTGA(new MemoryStream(managedImage.ExportTGA())); break; } facetedMesh = mesher.GenerateFacetedSculptMesh(primitive, (Bitmap)image, DetailLevel.Highest); return(true); } FacetedMesh localFacetedMesh = null; var MeshDownloadedEvent = new ManualResetEventSlim(false); Locks.ClientInstanceAssetsLock.EnterReadLock(); Client.Assets.RequestMesh(primitive.Sculpt.SculptTexture, (success, meshAsset) => { FacetedMesh.TryDecodeFromAsset(primitive, meshAsset, DetailLevel.Highest, out localFacetedMesh); MeshDownloadedEvent.Set(); }); if (!MeshDownloadedEvent.Wait((int)millisecondsTimeout)) { Locks.ClientInstanceAssetsLock.ExitReadLock(); return(false); } Locks.ClientInstanceAssetsLock.ExitReadLock(); switch (localFacetedMesh != null) { case true: facetedMesh = localFacetedMesh; return(true); default: return(false); } }
private void LoadImage() { if (String.IsNullOrEmpty(FileName)) { return; } string extension = System.IO.Path.GetExtension(FileName).ToLower(); Bitmap bitmap = null; try { if (extension == ".jp2" || extension == ".j2c") { Image image; ManagedImage managedImage; // Upload JPEG2000 images untouched UploadData = System.IO.File.ReadAllBytes(FileName); OpenJPEG.DecodeToImage(UploadData, out managedImage, out image); bitmap = (Bitmap)image; Logger.Log("Loaded raw JPEG2000 data " + FileName, Helpers.LogLevel.Info, Client); } else { if (extension == ".tga") { bitmap = LoadTGAClass.LoadTGA(FileName); } else { bitmap = (Bitmap)System.Drawing.Image.FromFile(FileName); } Logger.Log("Loaded image " + FileName, Helpers.LogLevel.Info, Client); int oldwidth = bitmap.Width; int oldheight = bitmap.Height; if (!IsPowerOfTwo((uint)oldwidth) || !IsPowerOfTwo((uint)oldheight)) { Logger.Log("Image has irregular dimensions " + oldwidth + "x" + oldheight + ", resizing to 256x256", Helpers.LogLevel.Info, Client); Bitmap resized = new Bitmap(256, 256, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, 256, 256); bitmap.Dispose(); bitmap = resized; oldwidth = 256; oldheight = 256; } // Handle resizing to prevent excessively large images if (oldwidth > 1024 || oldheight > 1024) { int newwidth = (oldwidth > 1024) ? 1024 : oldwidth; int newheight = (oldheight > 1024) ? 1024 : oldheight; Logger.Log("Image has oversized dimensions " + oldwidth + "x" + oldheight + ", resizing to " + newwidth + "x" + newheight, Helpers.LogLevel.Info, Client); Bitmap resized = new Bitmap(newwidth, newheight, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, newwidth, newheight); bitmap.Dispose(); bitmap = resized; } Logger.Log("Encoding image...", Helpers.LogLevel.Info, Client); UploadData = OpenJPEG.EncodeFromImage(bitmap, chkLossless.Checked); Logger.Log("Finished encoding", Helpers.LogLevel.Info, Client); //System.IO.File.WriteAllBytes("out.jp2", UploadData); } } catch (Exception ex) { UploadData = null; cmdSave.Enabled = false; cmdUpload.Enabled = false; MessageBox.Show(ex.ToString(), "SL Image Upload", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } picPreview.Image = bitmap; lblSize.Text = Math.Round((double)UploadData.Length / 1024.0d, 2) + "KB"; prgUpload.Maximum = UploadData.Length; cmdSave.Enabled = true; if (Client.Network.Connected) { cmdUpload.Enabled = true; } }
private void pic_MouseClick(object sender, MouseEventArgs e) { PictureBox control = (PictureBox)sender; OpenFileDialog dialog = new OpenFileDialog(); // TODO: Setup a dialog.Filter for supported image types if (dialog.ShowDialog() == DialogResult.OK) { try { System.Drawing.Image image = System.Drawing.Image.FromFile(dialog.FileName); #region Dimensions Check if (control == picEyesBake) { // Eyes texture is 128x128 if (Width != 128 || Height != 128) { Bitmap resized = new Bitmap(128, 128, image.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(image, 0, 0, 128, 128); image.Dispose(); image = resized; } } else { // Other textures are 512x512 if (Width != 128 || Height != 128) { Bitmap resized = new Bitmap(512, 512, image.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(image, 0, 0, 512, 512); image.Dispose(); image = resized; } } #endregion Dimensions Check // Set the control image control.Image = image; } catch (Exception ex) { MessageBox.Show("Failed to load image: " + ex.Message); } } else { control.Image = null; } #region Baking Dictionary <int, float> paramValues = GetParamValues(); Dictionary <AvatarTextureIndex, AssetTexture> layers = new Dictionary <AvatarTextureIndex, AssetTexture>(); int textureCount = 0; if ((string)control.Tag == "Head") { if (picHair.Image != null) { layers.Add(AvatarTextureIndex.Hair, new AssetTexture(new ManagedImage((Bitmap)picHair.Image))); ++textureCount; } if (picHeadBodypaint.Image != null) { layers.Add(AvatarTextureIndex.HeadBodypaint, new AssetTexture(new ManagedImage((Bitmap)picHeadBodypaint.Image))); ++textureCount; } // Compute the head bake Baker baker = new Baker(BakeType.Head); foreach (KeyValuePair <AvatarTextureIndex, AssetTexture> kvp in layers) { AppearanceManager.TextureData tdata = new AppearanceManager.TextureData(); tdata.Texture = kvp.Value; baker.AddTexture(tdata); } baker.Bake(); if (baker.BakedTexture != null) { AssetTexture bakeAsset = baker.BakedTexture; // Baked textures use the alpha layer for other purposes, so we need to not use it bakeAsset.Image.Channels = ManagedImage.ImageChannels.Color; picHeadBake.Image = LoadTGAClass.LoadTGA(new MemoryStream(bakeAsset.Image.ExportTGA())); } else { MessageBox.Show("Failed to create the bake layer, unknown error"); } } else if ((string)control.Tag == "Upper") { if (picUpperBodypaint.Image != null) { layers.Add(AvatarTextureIndex.UpperBodypaint, new AssetTexture(new ManagedImage((Bitmap)picUpperBodypaint.Image))); ++textureCount; } if (picUpperGloves.Image != null) { layers.Add(AvatarTextureIndex.UpperGloves, new AssetTexture(new ManagedImage((Bitmap)picUpperGloves.Image))); ++textureCount; } if (picUpperUndershirt.Image != null) { layers.Add(AvatarTextureIndex.UpperUndershirt, new AssetTexture(new ManagedImage((Bitmap)picUpperUndershirt.Image))); ++textureCount; } if (picUpperShirt.Image != null) { layers.Add(AvatarTextureIndex.UpperShirt, new AssetTexture(new ManagedImage((Bitmap)picUpperShirt.Image))); ++textureCount; } if (picUpperJacket.Image != null) { layers.Add(AvatarTextureIndex.UpperJacket, new AssetTexture(new ManagedImage((Bitmap)picUpperJacket.Image))); ++textureCount; } // Compute the upper body bake Baker baker = new Baker(BakeType.UpperBody); foreach (KeyValuePair <AvatarTextureIndex, AssetTexture> kvp in layers) { AppearanceManager.TextureData tdata = new AppearanceManager.TextureData(); tdata.Texture = kvp.Value; baker.AddTexture(tdata); } baker.Bake(); if (baker.BakedTexture != null) { AssetTexture bakeAsset = baker.BakedTexture; // Baked textures use the alpha layer for other purposes, so we need to not use it bakeAsset.Image.Channels = ManagedImage.ImageChannels.Color; picUpperBodyBake.Image = LoadTGAClass.LoadTGA(new MemoryStream(bakeAsset.Image.ExportTGA())); } else { MessageBox.Show("Failed to create the bake layer, unknown error"); } } else if ((string)control.Tag == "Lower") { if (picLowerBodypaint.Image != null) { layers.Add(AvatarTextureIndex.LowerBodypaint, new AssetTexture(new ManagedImage((Bitmap)picLowerBodypaint.Image))); ++textureCount; } if (picLowerUnderpants.Image != null) { layers.Add(AvatarTextureIndex.LowerUnderpants, new AssetTexture(new ManagedImage((Bitmap)picLowerUnderpants.Image))); ++textureCount; } if (picLowerSocks.Image != null) { layers.Add(AvatarTextureIndex.LowerSocks, new AssetTexture(new ManagedImage((Bitmap)picLowerSocks.Image))); ++textureCount; } if (picLowerShoes.Image != null) { layers.Add(AvatarTextureIndex.LowerShoes, new AssetTexture(new ManagedImage((Bitmap)picLowerShoes.Image))); ++textureCount; } if (picLowerPants.Image != null) { layers.Add(AvatarTextureIndex.LowerPants, new AssetTexture(new ManagedImage((Bitmap)picLowerPants.Image))); ++textureCount; } // Compute the lower body bake Baker baker = new Baker(BakeType.LowerBody); foreach (KeyValuePair <AvatarTextureIndex, AssetTexture> kvp in layers) { AppearanceManager.TextureData tdata = new AppearanceManager.TextureData(); tdata.Texture = kvp.Value; baker.AddTexture(tdata); } baker.Bake(); if (baker.BakedTexture != null) { AssetTexture bakeAsset = baker.BakedTexture; // Baked textures use the alpha layer for other purposes, so we need to not use it bakeAsset.Image.Channels = ManagedImage.ImageChannels.Color; picLowerBodyBake.Image = LoadTGAClass.LoadTGA(new MemoryStream(bakeAsset.Image.ExportTGA())); } else { MessageBox.Show("Failed to create the bake layer, unknown error"); } } else if ((string)control.Tag == "Bake") { // Bake image has been set manually, no need to manually calculate a bake // FIXME: } #endregion Baking }
private void LoadImage() { progressBar1.Value = 0; button2free.Enabled = false; if (FileName == null || FileName == "") { return; } string lowfilename = FileName.ToLower(); Bitmap bitmap = null; try { if (lowfilename.EndsWith(".jp2") || lowfilename.EndsWith(".j2c")) { Image image; ManagedImage managedImage; // Upload JPEG2000 images untouched UploadData = System.IO.File.ReadAllBytes(FileName); OpenJPEG.DecodeToImage(UploadData, out managedImage, out image); bitmap = (Bitmap)image; Console.Write("Loaded raw JPEG2000 data " + FileName); } else { if (lowfilename.EndsWith(".tga")) { bitmap = LoadTGAClass.LoadTGA(FileName); } else { bitmap = (Bitmap)System.Drawing.Image.FromFile(FileName); } Console.Write("Loaded image " + FileName); int oldwidth = bitmap.Width; int oldheight = bitmap.Height; if (!IsPowerOfTwo((uint)oldwidth) || !IsPowerOfTwo((uint)oldheight)) { //Console.Write("Image has irregular dimensions " + oldwidth + "x" + oldheight + ", resizing to 256x256"); //int biggestD = (int)Math.Max((decimal)oldwidth, (decimal)oldheight); int newsx = 2; while (newsx < oldwidth && newsx <= 1024) { newsx = newsx * 2; } int newsy = 2; while (newsy < oldheight && newsy <= 1024) { newsy = newsy * 2; } Console.Write("Image has irregular dimensions " + oldwidth + "x" + oldheight + ", resizing to " + newsx + "x" + newsy); Bitmap resized = new Bitmap(newsx, newsy, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, newsx, newsy); bitmap.Dispose(); bitmap = resized; oldwidth = newsx; oldheight = newsy; } // Handle resizing to prevent excessively large images if (oldwidth > 1024 || oldheight > 1024) { int newwidth = (oldwidth > 1024) ? 1024 : oldwidth; int newheight = (oldheight > 1024) ? 1024 : oldheight; Console.Write("Image has oversized dimensions " + oldwidth + "x" + oldheight + ", resizing to " + newwidth + "x" + newheight); Bitmap resized = new Bitmap(newwidth, newheight, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, newwidth, newheight); bitmap.Dispose(); bitmap = resized; } Console.Write("Encoding image..."); UploadData = OpenJPEG.EncodeFromImage(bitmap, checkBox1lossless.Checked); button2free.Enabled = true; Console.Write("Finished encoding"); } } catch (Exception ex) { UploadData = null; button2free.Enabled = false; MessageBox.Show(ex.ToString(), "Gay Lord", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //int test = 16384; //Console.WriteLine(BitConverter.ToString(BitConverter.GetBytes(test),0) + " is hte test size"); this.pictureBox1.Image = bitmap; //lblSize.Text = Math.Round((double)UploadData.Length / 1024.0d, 2) + "KB"; //this.progressBar1.Maximum = UploadData.Length; button2free.Enabled = true; progressBar1.Value = progressBar1.Maximum; }
void DownloadTexture(UUID textureID) { if (!textures.ContainsKey(textureID)) { if (Client.Assets.Cache.HasAsset(textureID)) { Debug.Log("Cache hits!"); byte[] jpg = Client.Assets.Cache.GetCachedAssetBytes(textureID); ManagedImage mi; if (!OpenJPEG.DecodeToImage(jpg, out mi)) { return; } byte[] imageBytes = mi.ExportTGA(); Bitmap img; using (MemoryStream byteData = new MemoryStream(imageBytes)) { img = LoadTGAClass.LoadTGA(byteData); } bitmaps[textureID] = img; } else { TextureDownloadCallback handler = (state, asset) => { Debug.Log("state is " + state.ToString()); try{ switch (state) { case TextureRequestState.Finished: { ManagedImage mi; if (!OpenJPEG.DecodeToImage(asset.AssetData, out mi)) { break; } byte[] imageBytes = mi.ExportTGA(); Bitmap img; using (MemoryStream byteData = new MemoryStream(imageBytes)) { img = LoadTGAClass.LoadTGA(byteData); } bitmaps[textureID] = img; break; } case TextureRequestState.Aborted: case TextureRequestState.NotFound: case TextureRequestState.Timeout: break; } } catch (Exception ex) { Debug.Log("what happened?:" + ex.Message); } }; Client.Assets.RequestImage(textureID, ImageType.Normal, handler); } } }
public void LoadImage(string fname) { FileName = fname; if (string.IsNullOrEmpty(FileName)) { return; } txtStatus.AppendText("Loading..." + Environment.NewLine); string extension = Path.GetExtension(FileName).ToLower(); try { Bitmap bitmap = null; switch (extension) { case ".jp2": case ".j2c": // Upload JPEG2000 images untouched UploadData = File.ReadAllBytes(FileName); using (var reader = new OpenJpegDotNet.IO.Reader(UploadData)) { if (reader.ReadHeader()) { bitmap = reader.DecodeToBitmap(); } } txtStatus.AppendText("Loaded raw JPEG2000 data " + FileName + Environment.NewLine); break; case ".tga": bitmap = LoadTGAClass.LoadTGA(FileName); break; default: bitmap = Image.FromFile(FileName) as Bitmap; break; } if (bitmap == null) { txtStatus.AppendText("Failed to load image " + FileName + Environment.NewLine); return; } txtStatus.AppendText("Loaded image " + FileName + Environment.NewLine); int width = bitmap.Width; int height = bitmap.Height; // Handle resizing to prevent excessively large images and irregular dimensions if (!IsPowerOfTwo((uint)width) || !IsPowerOfTwo((uint)height) || width > 1024 || height > 1024) { txtStatus.AppendText("Image has irregular dimensions " + width + "x" + height + Environment.NewLine); width = ClosestPowerOwTwo(width); height = ClosestPowerOwTwo(height); width = width > 1024 ? 1024 : width; height = height > 1024 ? 1024 : height; txtStatus.AppendText("Resizing to " + width + "x" + height + Environment.NewLine); Bitmap resized = new Bitmap(width, height, bitmap.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(bitmap, 0, 0, width, height); bitmap.Dispose(); bitmap = resized; } txtStatus.AppendText("Encoding image..." + Environment.NewLine); using (var writer = new OpenJpegDotNet.IO.Writer(bitmap)) { var cp = new OpenJpegDotNet.CompressionParameters(); OpenJpegDotNet.OpenJpeg.SetDefaultEncoderParameters(cp); cp.CodingParameterDistortionAllocation = 1; if (chkLossless.Checked) { cp.TcpNumLayers = 1; cp.TcpRates[0] = 0; } else { cp.TcpNumLayers = 5; cp.TcpRates[0] = 1920; cp.TcpRates[1] = 480; cp.TcpRates[2] = 120; cp.TcpRates[3] = 30; cp.TcpRates[4] = 10; cp.Irreversible = true; cp.TcpMCT = 1; } writer.SetupEncoderParameters(cp); UploadData = writer.Encode(); } txtStatus.AppendText("Finished encoding." + Environment.NewLine); ImageLoaded = true; UpdateButtons(); txtAssetID.Text = UUID.Zero.ToString(); pbPreview.Image = bitmap; lblSize.Text = string.Format("{0}x{1} {2} KB", bitmap.Width, bitmap.Height, Math.Round((double)UploadData.Length / 1024.0d, 2)); } catch (Exception ex) { UploadData = null; btnSave.Enabled = false; btnUpload.Enabled = false; txtStatus.AppendText(string.Format("Failed to load the image:" + Environment.NewLine + "{0}" + Environment.NewLine, ex.Message)); } }