Example #1
0
        public byte[] OnHTTPGetTextureImage(string path, Stream request, OSHttpRequest httpRequest,
                                            OSHttpResponse httpResponse)
        {
            byte[]        jpeg           = new byte[0];
            IAssetService m_AssetService = _registry.RequestModuleInterface <IAssetService>();

            using (MemoryStream imgstream = new MemoryStream())
            {
                // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular jpeg data

                // non-async because we know we have the asset immediately.
                byte[] mapasset = m_AssetService.GetData(httpRequest.QueryString["uuid"]);

                if (mapasset != null)
                {
                    // Decode image to System.Drawing.Image
                    Image        image = null;
                    ManagedImage managedImage;
                    if (OpenJPEG.DecodeToImage(mapasset, out managedImage, out image))
                    {
                        // Save to bitmap
                        using (Bitmap texture = ResizeBitmap(image, 256, 256))
                        {
                            EncoderParameters myEncoderParameters = new EncoderParameters();
                            myEncoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,
                                                                                75L);

                            // Save bitmap to stream
                            texture.Save(imgstream, GetEncoderInfo("image/jpeg"), myEncoderParameters);

                            // Write the stream to a byte array for output
                            jpeg = imgstream.ToArray();
                        }
                        image.Dispose();
                    }
                }
            }

            httpResponse.ContentType = "image/jpeg";

            return(jpeg);
        }
Example #2
0
        private void Assets_OnImageReceived(AssetTexture assetTexture)
        {
            if (assetTexture.AssetID != this.imageID)
            {
                return;
            }

            if (InvokeRequired)
            {
                if (IsHandleCreated || !instance.MonoRuntime)
                {
                    BeginInvoke(new MethodInvoker(() => Assets_OnImageReceived(assetTexture)));
                }
                return;
            }

            try
            {
                progressBar1.Hide();
                lblProgress.Hide();

                if (!OpenJPEG.DecodeToImage(assetTexture.AssetData, out imgManaged, out image))
                {
                    throw new Exception("decoding failure");
                }

                Text = Text; // yeah, really ;)

                pictureBox1.Image   = image;
                pictureBox1.Enabled = true;
                jpegdata            = assetTexture.AssetData;
                if (Detached)
                {
                    ClientSize = pictureBox1.Size = new Size(image.Width, image.Height);
                }
            }
            catch (Exception excp)
            {
                this.Hide();
                System.Console.WriteLine("Error decoding image: " + excp.Message);
            }
        }
Example #3
0
// TODO: unused:
//         private void ShadeBuildings(Bitmap map)
//         {
//             lock (map)
//             {
//                 lock (m_scene.Entities)
//                 {
//                     foreach (EntityBase entity in m_scene.Entities.Values)
//                     {
//                         if (entity is SceneObjectGroup)
//                         {
//                             SceneObjectGroup sog = (SceneObjectGroup) entity;
//
//                             foreach (SceneObjectPart primitive in sog.Children.Values)
//                             {
//                                 int x = (int) (primitive.AbsolutePosition.X - (primitive.Scale.X / 2));
//                                 int y = (int) (primitive.AbsolutePosition.Y - (primitive.Scale.Y / 2));
//                                 int w = (int) primitive.Scale.X;
//                                 int h = (int) primitive.Scale.Y;
//
//                                 int dx;
//                                 for (dx = x; dx < x + w; dx++)
//                                 {
//                                     int dy;
//                                     for (dy = y; dy < y + h; dy++)
//                                     {
//                                         if (x < 0 || y < 0)
//                                             continue;
//                                         if (x >= map.Width || y >= map.Height)
//                                             continue;
//
//                                         map.SetPixel(dx, dy, Color.DarkGray);
//                                     }
//                                 }
//                             }
//                         }
//                     }
//                 }
//             }
//         }

        private Bitmap FetchTexture(UUID id)
        {
            AssetBase asset = m_scene.AssetService.Get(id.ToString());

            if (asset != null)
            {
                m_log.DebugFormat("[MAPTILE]: Static map image texture {0} found for {1}", id, m_scene.Name);
            }
            else
            {
                m_log.WarnFormat("[MAPTILE]: Static map image texture {0} not found for {1}", id, m_scene.Name);
                return(null);
            }

            ManagedImage managedImage;
            Image        image;

            try
            {
                if (OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image))
                {
                    return(new Bitmap(image));
                }
                else
                {
                    return(null);
                }
            }
            catch (DllNotFoundException)
            {
                m_log.ErrorFormat("[MAPTILE]: OpenJpeg is not installed correctly on this system.   Asset Data is empty for {0}", id);
            }
            catch (IndexOutOfRangeException)
            {
                m_log.ErrorFormat("[MAPTILE]: OpenJpeg was unable to decode this.   Asset Data is empty for {0}", id);
            }
            catch (Exception)
            {
                m_log.ErrorFormat("[MAPTILE]: OpenJpeg was unable to decode this.   Asset Data is empty for {0}", id);
            }
            return(null);
        }
Example #4
0
        public Image GetTexture(UUID TextureID)
        {
            if (TextureID == UUID.Zero) //Send white instead of null
            {
                TextureID = Util.BLANK_TEXTURE_UUID;
            }

            AssetBase    asset = m_assetService.Get(TextureID.ToString());
            ManagedImage managedImage;
            Image        image;

            if (asset != null && OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image))
            {
                return(image);
            }
            else
            {
                return(new Bitmap(1, 1));
            }
        }
        private Image OpenBackground(string filename)
        {
            string jp2 = Path.ChangeExtension(filename, ".jp2");
            string jpg = Path.ChangeExtension(filename, ".jpg");

            if (File.Exists(jp2))
            {
                byte[] buffer;
                OpenJPEG.ConvertJPEG2(jp2, out buffer, ImageFormat.Png);
                return(Image.FromStream(new MemoryStream(buffer)));
            }
            else if (File.Exists(jpg))
            {
                return(Image.FromFile(jpg));
            }
            else
            {
                return(null);
            }
        }
        public byte[] WriteJpeg2000Image()
        {
            try
            {
                using (Bitmap mapbmp = CreateMapTile())
                {
                    byte[] data;
                    data = OpenJPEG.EncodeFromImage(mapbmp, true);
                    mapbmp.Dispose();
                    return(data);
                }
            }
            catch (Exception e)
            {
                // JPEG2000 encoder failed
                m_log.Error("[WARP 3D IMAGE MODULE]: Failed generating terrain map: ", e);
            }

            return(null);
        }
        private void ExportArchiveImage(UUID imageUUID, string archiveName, string filePath)
        {
            byte[] jpeg = new byte[0];

            using (MemoryStream imgstream = new MemoryStream())
            {
                // Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular jpeg data

                // non-async because we know we have the asset immediately.
                byte[] imageAsset = AssetService.GetData(imageUUID.ToString());

                if (imageAsset != null)
                {
                    // Decode image to System.Drawing.Image
                    Image        image = null;
                    ManagedImage managedImage;
                    if (OpenJPEG.DecodeToImage(imageAsset, out managedImage, out image))
                    {
                        // Save to bitmap
                        using (Bitmap texture = ResizeBitmap(image, 256, 256, archiveName))
                        {
                            EncoderParameters myEncoderParameters = new EncoderParameters();
                            myEncoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,
                                                                                75L);

                            // Save bitmap to stream
                            texture.Save(imgstream, GetEncoderInfo("image/jpeg"), myEncoderParameters);

                            // Write the stream to a byte array for output
                            jpeg = imgstream.ToArray();

                            // save image
                            string fileName = archiveName + ".jpg";
                            string fullPath = Path.Combine(filePath, fileName);
                            File.WriteAllBytes(fullPath, jpeg);
                        }
                        image.Dispose();
                    }
                }
            }
        }
Example #8
0
        private void imageReceivedCallback(TextureRequestState state, AssetTexture asset)
        {
            if (state == TextureRequestState.Timeout)
            {
                // need a re-request if a texture times out but doing it here borks libomv
                //m_user.Assets.RequestImage(asset.AssetID, ImageType.Normal, imageReceivedCallback);
                return;
            }

            if (state != TextureRequestState.Finished)
            {
                return;
            }

            if (OnTextureDownloaded != null)
            {
                VTexture texture = new VTexture();
                texture.TextureId = asset.AssetID;

                ManagedImage managedImage;
                Image        tempImage;

                try
                {
                    if (OpenJPEG.DecodeToImage(asset.AssetData, out managedImage, out tempImage))
                    {
                        Bitmap   textureBitmap = new Bitmap(tempImage.Width, tempImage.Height, PixelFormat.Format32bppArgb);
                        Graphics graphics      = Graphics.FromImage(textureBitmap);
                        graphics.DrawImage(tempImage, 0, 0);
                        graphics.Flush();
                        graphics.Dispose();
                        texture.Image = textureBitmap;
                        OnTextureDownloaded(texture);
                    }
                }
                catch (Exception e)
                {
                    m_log.Error(":( :( :( :( got exception decoding image ): ): ): ):\nException: " + e.ToString());
                }
            }
        }
Example #9
0
        bool LoadTexture(UUID textureID, ref Image texture, bool removeAlpha)
        {
            var   gotImage = new System.Threading.ManualResetEvent(false);
            Image img      = null;

            try
            {
                gotImage.Reset();
                byte[] tgaData;
                Client.Assets.RequestImage(textureID, (state, assetTexture) =>
                {
                    ManagedImage mi;
                    if (state == TextureRequestState.Finished && OpenJPEG.DecodeToImage(assetTexture.AssetData, out mi))
                    {
                        if (removeAlpha)
                        {
                            if ((mi.Channels & ManagedImage.ImageChannels.Alpha) != 0)
                            {
                                mi.ConvertChannels(mi.Channels & ~ManagedImage.ImageChannels.Alpha);
                            }
                        }
                        tgaData = mi.ExportTGA();
                        img     = LoadTGAClass.LoadTGA(new MemoryStream(tgaData));
                    }
                    gotImage.Set();
                });
                gotImage.WaitOne(30 * 1000, false);

                if (img != null)
                {
                    texture = img;
                    return(true);
                }
                return(false);
            }
            catch (Exception e)
            {
                Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e);
                return(false);
            }
        }
Example #10
0
        public void Decode_jp2k(string filename, string decodeType, Asset asset)
        {
            var img = (AssetTexture)asset;

            OpenMetaverse.Imaging.ManagedImage imgImage = img.Image;
            if (imgImage == null)
            {
                OpenJPEG.DecodeToImage(asset.AssetData, out imgImage);
            }
            if (imgImage != null)
            {
                if (filename.ToLower().EndsWith("tga"))
                {
                    File.WriteAllBytes(filename, imgImage.ExportTGA());
                }
                else
                {
                    File.WriteAllBytes(filename, imgImage.ExportRaw());
                }
            }
        }
Example #11
0
 public Image DecodeToImage(byte[] j2kData)
 {
     if (m_useCSJ2K)
     {
         return(J2kImage.FromBytes(j2kData));
     }
     else
     {
         ManagedImage mimage;
         Image        image;
         if (OpenJPEG.DecodeToImage(j2kData, out mimage, out image))
         {
             mimage = null;
             return(image);
         }
         else
         {
             return(null);
         }
     }
 }
        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);
        }
Example #13
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.AddExtension     = true;
            dlg.RestoreDirectory = true;
            dlg.Title            = "Save image as...";
            dlg.Filter           = "PNG (*.png)|*.png|Targa (*.tga)|*.tga|Jpeg2000 (*.j2c)|*.j2c|Jpeg (*.jpg)|*.jpg|Bitmap (*.bmp)|*.bmp";



            if (dlg.ShowDialog() == DialogResult.OK)
            {
                int type = dlg.FilterIndex;
                if (type == 3)
                { // jpeg2000
                    File.WriteAllBytes(dlg.FileName, UploadData);
                }
                else if (type == 2)
                { // targa
                    ManagedImage imgManaged;
                    OpenJPEG.DecodeToImage(UploadData, out imgManaged);
                    File.WriteAllBytes(dlg.FileName, imgManaged.ExportTGA());
                }
                else if (type == 1)
                { // png
                    pbPreview.Image.Save(dlg.FileName, ImageFormat.Png);
                }
                else if (type == 4)
                { // jpg
                    pbPreview.Image.Save(dlg.FileName, ImageFormat.Jpeg);
                }
                else
                { // BMP
                    pbPreview.Image.Save(dlg.FileName, ImageFormat.Bmp);
                }
            }

            dlg.Dispose();
        }
            private byte[] BlendTextures(byte[] frontImage, byte[] backImage, bool setNewAlpha, byte newAlpha)
            {
                ManagedImage managedImage;
                Image        image;

                if (OpenJPEG.DecodeToImage(frontImage, out managedImage, out image))
                {
                    Bitmap image1 = new Bitmap(image);

                    if (OpenJPEG.DecodeToImage(backImage, out managedImage, out image))
                    {
                        Bitmap image2 = new Bitmap(image);

                        if (setNewAlpha)
                        {
                            SetAlpha(ref image1, newAlpha);
                        }

                        Bitmap joint = MergeBitMaps(image1, image2);

                        byte[] result = new byte[0];

                        try
                        {
                            result = OpenJPEG.EncodeFromImage(joint, true);
                        }
                        catch (Exception e)
                        {
                            m_log.ErrorFormat(
                                "[DYNAMICTEXTUREMODULE]: OpenJpeg Encode Failed.  Exception {0}{1}",
                                e.Message, e.StackTrace);
                        }

                        return(result);
                    }
                }

                return(null);
            }
Example #15
0
        void Assets_OnImageReceived(TextureRequestState image, AssetTexture texture)
        {
            if (texture.AssetID == profile.InsigniaID)
            {
                ManagedImage imgData;
                Image        bitmap;

                try
                {
                    OpenJPEG.DecodeToImage(texture.AssetData, out imgData, out bitmap);

                    BeginInvoke(new MethodInvoker(delegate()
                    {
                        picInsignia.Image = bitmap;
                    }));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "METAbolt");
                }
            }
        }
Example #16
0
 private void Assets_OnImageReceived(AssetTexture assetTexture)
 {
     try
     {
         byte[]       jpegdata;
         ManagedImage imgManaged;
         Image        image;
         SimAsset     sa = SimAssetStore.FindOrCreateAsset(assetTexture.AssetID, assetTexture.AssetType);
         if (!OpenJPEG.DecodeToImage(assetTexture.AssetData, out imgManaged, out image))
         {
             throw new Exception("decoding failure");
         }
         jpegdata     = assetTexture.AssetData;
         sa._TypeData = jpegdata;
         UUIDTypeObjectSetValue(assetTexture.AssetID, jpegdata);
         assetTexture.Decode();
     }
     catch (Exception excp)
     {
         System.Console.WriteLine("Error decoding image: " + excp.Message);
     }
 }
            private byte[] BlendTextures(byte[] frontImage, byte[] backImage, bool setNewAlpha, byte newAlpha,
                                         IScene scene)
            {
                Image image = scene.RequestModuleInterface <IJ2KDecoder>().DecodeToImage(frontImage);

                if (image != null)
                {
                    Bitmap image1 = new Bitmap(image);

                    image = scene.RequestModuleInterface <IJ2KDecoder>().DecodeToImage(backImage);
                    if (image != null)
                    {
                        Bitmap image2 = new Bitmap(image);

                        if (setNewAlpha)
                        {
                            SetAlpha(ref image1, newAlpha);
                        }

                        Bitmap joint = MergeBitMaps(image1, image2);

                        byte[] result = new byte[0];

                        try
                        {
                            result = OpenJPEG.EncodeFromImage(joint, true);
                        }
                        catch (Exception)
                        {
                            MainConsole.Instance.Error(
                                "[DYNAMICTEXTUREMODULE]: OpenJpeg Encode Failed.  Empty byte data returned!");
                        }

                        return(result);
                    }
                }

                return(null);
            }
        // This fetches the texture from the asset server synchroneously. That should be ok, as we
        // call map-creation only in those places:
        // - on start: We can wait here until the asset server returns the texture
        // TODO (- on "map" command: We are in the command-line thread, we will wait for completion anyway)
        // TODO (- on "automatic" update after some change: We are called from the mapUpdateTimer here and
        //   will wait anyway)
        private Bitmap fetchTexture(UUID id)
        {
            AssetBase asset = m_scene.AssetService.Get(id.ToString());

            m_log.DebugFormat("Fetched texture {0}, found: {1}", id, asset != null);
            if (asset == null)
            {
                return(null);
            }

            ManagedImage managedImage;
            Image        image;

            try
            {
                if (OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image))
                {
                    return(new Bitmap(image));
                }
                else
                {
                    return(null);
                }
            }
            catch (DllNotFoundException)
            {
                m_log.ErrorFormat("[TexturedMapTileRenderer]: OpenJpeg is not installed correctly on this system.   Asset Data is emtpy for {0}", id);
            }
            catch (IndexOutOfRangeException)
            {
                m_log.ErrorFormat("[TexturedMapTileRenderer]: OpenJpeg was unable to encode this.   Asset Data is emtpy for {0}", id);
            }
            catch (Exception)
            {
                m_log.ErrorFormat("[TexturedMapTileRenderer]: OpenJpeg was unable to encode this.   Asset Data is emtpy for {0}", id);
            }
            return(null);
        }
        private void Assets_OnImageReceived(ImageDownload image, AssetTexture assetTexture)
        {
            lock (OutfitAssets)
            {
                if (OutfitAssets.Contains(image.ID))
                {
                    if (image.Success)
                    {
                        try
                        {
                            File.WriteAllBytes(image.ID.ToString() + ".jp2", image.AssetData);
                            Console.WriteLine("Wrote JPEG2000 image " + image.ID.ToString() + ".jp2");

                            ManagedImage imgData;
                            OpenJPEG.DecodeToImage(image.AssetData, out imgData);
                            byte[] tgaFile = imgData.ExportTGA();
                            File.WriteAllBytes(image.ID.ToString() + ".tga", tgaFile);
                            Console.WriteLine("Wrote TGA image " + image.ID.ToString() + ".tga");
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.ToString());
                        }
                    }
                    else
                    {
                        Console.WriteLine("Failed to download image " + image.ID.ToString());
                    }

                    OutfitAssets.Remove(image.ID);

                    if (OutfitAssets.Count == 0)
                    {
                        Client.Assets.OnImageReceived -= ImageReceivedHandler;
                    }
                }
            }
        }
Example #20
0
        void DisplayPartialImage(AssetTexture assetTexture)
        {
            if (InvokeRequired)
            {
                if (IsHandleCreated || !instance.MonoRuntime)
                {
                    BeginInvoke(new MethodInvoker(() => DisplayPartialImage(assetTexture)));
                }
                return;
            }

            try
            {
                ManagedImage         tmp;
                System.Drawing.Image img;
                if (OpenJPEG.DecodeToImage(assetTexture.AssetData, out tmp, out img))
                {
                    pictureBox1.Image   = img;
                    pictureBox1.Enabled = true;
                }
            }
            catch (Exception) { }
        }
        public UUID GetMapImage(UUID regionID, string imageURL)
        {
            if (m_AssetService == null)
            {
                return(m_MissingTexture);
            }

            try
            {
                WebClient c = new WebClient();
                //m_log.Debug("JPEG: " + imageURL);
                string filename = regionID.ToString();
                c.DownloadFile(imageURL, filename + ".jpg");
                Bitmap m = new Bitmap(filename + ".jpg");
                //m_log.Debug("Size: " + m.PhysicalDimension.Height + "-" + m.PhysicalDimension.Width);
                byte[]    imageData = OpenJPEG.EncodeFromImage(m, true);
                AssetBase ass       = new AssetBase(UUID.Random(), "region " + filename, (sbyte)AssetType.Texture, regionID.ToString());

                // !!! for now
                //info.RegionSettings.TerrainImageID = ass.FullID;

                ass.Temporary = true;
                ass.Local     = true;
                ass.Data      = imageData;

                m_AssetService.Store(ass);

                // finally
                return(ass.FullID);
            }
            catch // LEGIT: Catching problems caused by OpenJPEG p/invoke
            {
                m_log.Warn("[GATEKEEPER SERVICE CONNECTOR]: Failed getting/storing map image, because it is probably already in the cache");
            }
            return(UUID.Zero);
        }
Example #22
0
        private bool ProcessTextureRequest(string param, OSHttpResponse resp)
        {
            UUID assetID;

            if (!UUID.TryParse(param, out assetID))
            {
                return(false);
            }

            AssetBase asset = m_scene.AssetService.Get(assetID.ToString());

            if (asset == null)
            {
                return(false);
            }

            ManagedImage tmp;
            Image        imgData;

            OpenJPEG.DecodeToImage(asset.Data, out tmp, out imgData);

            MemoryStream ms = new MemoryStream();

            imgData.Save(ms, ImageFormat.Jpeg);

            byte[] jpegdata = ms.GetBuffer();

            ms.Close();

            resp.ContentType   = "image/jpeg";
            resp.ContentLength = jpegdata.Length;
            resp.StatusCode    = 200;
            resp.Body.Write(jpegdata, 0, jpegdata.Length);

            return(true);
        }
Example #23
0
        public void ShadeWorld(string[] cmd)
        {
            if (MainConsole.Instance.ConsoleScene == null)
            {
                MainConsole.Instance.Output("Select a scene first");
                return;
            }
            bool  greyScale = MainConsole.Instance.Prompt("Greyscale (yes or no)?").ToLower() == "yes";
            int   R         = 0;
            int   G         = 0;
            int   B         = 0;
            float percent   = 0;

            if (!greyScale)
            {
                R       = int.Parse(MainConsole.Instance.Prompt("R color (0 - 255)"));
                G       = int.Parse(MainConsole.Instance.Prompt("G color (0 - 255)"));
                B       = int.Parse(MainConsole.Instance.Prompt("B color (0 - 255)"));
                percent = float.Parse(MainConsole.Instance.Prompt("Percent to merge in the shade (0 - 100)"));
            }
            if (percent > 1)
            {
                percent /= 100;
            }
            Color shader = Color.FromArgb(R, G, B);

            IJ2KDecoder j2kDecoder = MainConsole.Instance.ConsoleScene.RequestModuleInterface <IJ2KDecoder>();

            ISceneEntity[] entities = MainConsole.Instance.ConsoleScene.Entities.GetEntities();
            foreach (ISceneEntity entity in entities)
            {
                foreach (ISceneChildEntity child in entity.ChildrenEntities())
                {
                    UUID[] textures = GetTextures(child.Shape.Textures);
                    foreach (UUID t in textures)
                    {
                        if (m_previouslyConverted.ContainsKey(t))
                        {
                            child.Shape.Textures = SetTexture(child.Shape, m_previouslyConverted[t], t);
                        }
                        else
                        {
                            AssetBase a = MainConsole.Instance.ConsoleScene.AssetService.Get(t.ToString());
                            if (a != null)
                            {
                                Bitmap texture = (Bitmap)j2kDecoder.DecodeToImage(a.Data);
                                if (texture == null)
                                {
                                    continue;
                                }
                                a.ID    = UUID.Random();
                                texture = Shade(texture, shader, percent, greyScale);
                                a.Data  = OpenJPEG.EncodeFromImage(texture, false);
                                texture.Dispose();
                                a.ID = MainConsole.Instance.ConsoleScene.AssetService.Store(a);
                                child.Shape.Textures = SetTexture(child.Shape, a.ID, t);
                                m_previouslyConverted.Add(t, a.ID);
                                m_revertConverted.Add(a.ID, t);
                            }
                        }
                    }
                }
            }
        }
Example #24
0
        private void HttpRequestReturn(IAsyncResult result)
        {
            RequestState state   = (RequestState)result.AsyncState;
            WebRequest   request = state.Request;
            Stream       stream  = null;

            byte[] imageJ2000 = new byte[0];

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
                if (response != null && response.StatusCode == HttpStatusCode.OK)
                {
                    stream = response.GetResponseStream();
                    if (stream != null)
                    {
                        Bitmap image = new Bitmap(stream);
                        Size   newsize;

                        // TODO: make this a bit less hard coded
                        if ((image.Height < 64) && (image.Width < 64))
                        {
                            newsize = new Size(32, 32);
                        }
                        else if ((image.Height < 128) && (image.Width < 128))
                        {
                            newsize = new Size(64, 64);
                        }
                        else if ((image.Height < 256) && (image.Width < 256))
                        {
                            newsize = new Size(128, 128);
                        }
                        else if ((image.Height < 512 && image.Width < 512))
                        {
                            newsize = new Size(256, 256);
                        }
                        else if ((image.Height < 1024 && image.Width < 1024))
                        {
                            newsize = new Size(512, 512);
                        }
                        else
                        {
                            newsize = new Size(1024, 1024);
                        }

                        Bitmap resize = new Bitmap(image, newsize);

                        try
                        {
                            imageJ2000 = OpenJPEG.EncodeFromImage(resize, true);
                        }
                        catch (Exception)
                        {
                            MainConsole.Instance.Error(
                                "[LOADIMAGEURLMODULE]: OpenJpeg Encode Failed.  Empty byte data returned!");
                        }
                    }
                    else
                    {
                        MainConsole.Instance.WarnFormat("[LOADIMAGEURLMODULE] No data returned");
                    }
                }
            }
            catch (WebException)
            {
            }
            catch (ArgumentException)
            {
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
            MainConsole.Instance.DebugFormat("[LOADIMAGEURLMODULE] Returning {0} bytes of image data for request {1}",
                                             imageJ2000.Length, state.RequestID);
            m_textureManager.ReturnData(state.RequestID, imageJ2000);
        }
        /// <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);
        }
Example #26
0
        private IDynamicTexture Draw(string data, string extraParams)
        {
            // We need to cater for old scripts that didnt use extraParams neatly, they use either an integer size which represents both width and height, or setalpha
            // we will now support multiple comma seperated params in the form  width:256,height:512,alpha:255
            int   width        = 256;
            int   height       = 256;
            int   alpha        = 255;         // 0 is transparent
            Color bgColor      = Color.White; // Default background color
            char  altDataDelim = ';';

            char[] paramDelimiter = { ',' };
            char[] nvpDelimiter   = { ':' };

            extraParams = extraParams.Trim();
            extraParams = extraParams.ToLower();

            string[] nvps = extraParams.Split(paramDelimiter);

            int temp = -1;

            foreach (string pair in nvps)
            {
                string[] nvp   = pair.Split(nvpDelimiter);
                string   name  = "";
                string   value = "";

                if (nvp[0] != null)
                {
                    name = nvp[0].Trim();
                }

                if (nvp.Length == 2)
                {
                    value = nvp[1].Trim();
                }

                switch (name)
                {
                case "width":
                    temp = parseIntParam(value);
                    if (temp != -1)
                    {
                        if (temp < 1)
                        {
                            width = 1;
                        }
                        else if (temp > 2048)
                        {
                            width = 2048;
                        }
                        else
                        {
                            width = temp;
                        }
                    }
                    break;

                case "height":
                    temp = parseIntParam(value);
                    if (temp != -1)
                    {
                        if (temp < 1)
                        {
                            height = 1;
                        }
                        else if (temp > 2048)
                        {
                            height = 2048;
                        }
                        else
                        {
                            height = temp;
                        }
                    }
                    break;

                case "alpha":
                    temp = parseIntParam(value);
                    if (temp != -1)
                    {
                        if (temp < 0)
                        {
                            alpha = 0;
                        }
                        else if (temp > 255)
                        {
                            alpha = 255;
                        }
                        else
                        {
                            alpha = temp;
                        }
                    }
                    // Allow a bitmap w/o the alpha component to be created
                    else if (value.ToLower() == "false")
                    {
                        alpha = 256;
                    }
                    break;

                case "bgcolor":
                case "bgcolour":
                    int hex = 0;
                    if (Int32.TryParse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out hex))
                    {
                        bgColor = Color.FromArgb(hex);
                    }
                    else
                    {
                        bgColor = Color.FromName(value);
                    }
                    break;

                case "altdatadelim":
                    altDataDelim = value.ToCharArray()[0];
                    break;

                case "":
                    // blank string has been passed do nothing just use defaults
                    break;

                default:      // this is all for backwards compat, all a bit ugly hopfully can be removed in future
                    // could be either set alpha or just an int
                    if (name == "setalpha")
                    {
                        alpha = 0;      // set the texture to have transparent background (maintains backwards compat)
                    }
                    else
                    {
                        // this function used to accept an int on its own that represented both
                        // width and height, this is to maintain backwards compat, could be removed
                        // but would break existing scripts
                        temp = parseIntParam(name);
                        if (temp != -1)
                        {
                            if (temp > 1024)
                            {
                                temp = 1024;
                            }

                            if (temp < 128)
                            {
                                temp = 128;
                            }

                            width  = temp;
                            height = temp;
                        }
                    }
                    break;
                }
            }

            Bitmap   bitmap    = null;
            Graphics graph     = null;
            bool     reuseable = false;

            try
            {
                // XXX: In testing, it appears that if multiple threads dispose of separate GDI+ objects simultaneously,
                // the native malloc heap can become corrupted, possibly due to a double free().  This may be due to
                // bugs in the underlying libcairo used by mono's libgdiplus.dll on Linux/OSX.  These problems were
                // seen with both libcario 1.10.2-6.1ubuntu3 and 1.8.10-2ubuntu1.  They go away if disposal is perfomed
                // under lock.
                lock (this)
                {
                    if (alpha == 256)
                    {
                        bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb);
                        graph  = Graphics.FromImage(bitmap);
                        using (SolidBrush bgFillBrush = new SolidBrush(bgColor))
                        {
                            graph.FillRectangle(bgFillBrush, 0, 0, width, height);
                        }
                    }
                    else
                    {
                        bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
                        graph  = Graphics.FromImage(bitmap);
                        Color newbg = Color.FromArgb(alpha, bgColor);
                        using (SolidBrush bgFillBrush = new SolidBrush(newbg))
                        {
                            graph.FillRectangle(bgFillBrush, 0, 0, width, height);
                        }
                    }

                    GDIDraw(data, graph, altDataDelim, out reuseable);
                }

                byte[] imageJ2000 = new byte[0];

                // This code exists for testing purposes, please do not remove.
//                if (s_flipper)
//                    imageJ2000 = s_asset1Data;
//                else
//                    imageJ2000 = s_asset2Data;
//
//                s_flipper = !s_flipper;

                try
                {
                    imageJ2000 = OpenJPEG.EncodeFromImage(bitmap, true);
                }
                catch (Exception e)
                {
                    m_log.ErrorFormat(
                        "[VECTORRENDERMODULE]: OpenJpeg Encode Failed.  Exception {0}{1}",
                        e.Message, e.StackTrace);
                }

                return(new OpenSim.Region.CoreModules.Scripting.DynamicTexture.DynamicTexture(
                           data, extraParams, imageJ2000, new Size(width, height), reuseable));
            }
            finally
            {
                // XXX: In testing, it appears that if multiple threads dispose of separate GDI+ objects simultaneously,
                // the native malloc heap can become corrupted, possibly due to a double free().  This may be due to
                // bugs in the underlying libcairo used by mono's libgdiplus.dll on Linux/OSX.  These problems were
                // seen with both libcario 1.10.2-6.1ubuntu3 and 1.8.10-2ubuntu1.  They go away if disposal is perfomed
                // under lock.
                lock (this)
                {
                    if (graph != null)
                    {
                        graph.Dispose();
                    }

                    if (bitmap != null)
                    {
                        bitmap.Dispose();
                    }
                }
            }
        }
Example #27
0
        private bool DoJ2KDecode(UUID assetID, byte[] j2kData, bool useCSJ2K)
        {
            //int DecodeTime = 0;
            //DecodeTime = Environment.TickCount;
            OpenJPEG.J2KLayerInfo[] layers;

            if (!TryLoadCacheForAsset(assetID, out layers))
            {
                if (j2kData == null || j2kData.Length == 0)
                {
                    // Layer decoding completely failed. Guess at sane defaults for the layer boundaries
                    layers = CreateDefaultLayers(j2kData.Length);
                    // Notify Interested Parties
                    lock (m_notifyList)
                    {
                        if (m_notifyList.ContainsKey(assetID))
                        {
                            foreach (DecodedCallback d in m_notifyList[assetID].Where(d => d != null))
                            {
                                d.DynamicInvoke(assetID, layers);
                            }

                            m_notifyList.Remove(assetID);
                        }
                    }
                    return(false);
                }
                if (m_useCSJ2K)
                {
                    try
                    {
                        List <int> layerStarts = J2kImage.GetLayerBoundaries(new MemoryStream(j2kData));

                        if (layerStarts != null && layerStarts.Count > 0)
                        {
                            layers = new OpenJPEG.J2KLayerInfo[layerStarts.Count];

                            for (int i = 0; i < layerStarts.Count; i++)
                            {
                                OpenJPEG.J2KLayerInfo layer = new OpenJPEG.J2KLayerInfo
                                {
                                    Start = i == 0 ? 0 : layerStarts[i]
                                };


                                if (i == layerStarts.Count - 1)
                                {
                                    layer.End = j2kData.Length;
                                }
                                else
                                {
                                    layer.End = layerStarts[i + 1] - 1;
                                }

                                layers[i] = layer;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MainConsole.Instance.Warn("[J2KDecoderModule]: CSJ2K threw an exception decoding texture " +
                                                  assetID + ": " +
                                                  ex.Message);
                    }
                }
                else
                {
                    int components;
                    if (!OpenJPEG.DecodeLayerBoundaries(j2kData, out layers, out components))
                    {
                        MainConsole.Instance.Warn("[J2KDecoderModule]: OpenJPEG failed to decode texture " + assetID);
                    }
                }

                if (layers == null || layers.Length == 0)
                {
                    if (useCSJ2K == this.m_useCSJ2K)
                    {
                        MainConsole.Instance.Warn("[J2KDecoderModule]: Failed to decode layer data with (" +
                                                  (m_useCSJ2K ? "CSJ2K" : "OpenJPEG") + ") for texture " + assetID +
                                                  ", length " +
                                                  j2kData.Length + " trying " + (!m_useCSJ2K ? "CSJ2K" : "OpenJPEG"));
                        DoJ2KDecode(assetID, j2kData, !m_useCSJ2K);
                    }
                    else
                    {
                        //Second attempt at decode with the other j2k decoder, give up
                        MainConsole.Instance.Warn("[J2KDecoderModule]: Failed to decode layer data (" +
                                                  (m_useCSJ2K ? "CSJ2K" : "OpenJPEG") + ") for texture " + assetID +
                                                  ", length " +
                                                  j2kData.Length + " guessing sane defaults");
                        // Layer decoding completely failed. Guess at sane defaults for the layer boundaries
                        layers = CreateDefaultLayers(j2kData.Length);
                        // Notify Interested Parties
                        lock (m_notifyList)
                        {
                            if (m_notifyList.ContainsKey(assetID))
                            {
                                foreach (DecodedCallback d in m_notifyList[assetID].Where(d => d != null))
                                {
                                    d.DynamicInvoke(assetID, layers);
                                }
                                m_notifyList.Remove(assetID);
                            }
                        }
                        return(false);
                    }
                }
                else //Don't save the corrupt texture!
                {
                    // Cache Decoded layers
                    SaveFileCacheForAsset(assetID, layers);
                }
            }

            // Notify Interested Parties
            lock (m_notifyList)
            {
                if (m_notifyList.ContainsKey(assetID))
                {
                    foreach (DecodedCallback d in m_notifyList[assetID].Where(d => d != null))
                    {
                        d.DynamicInvoke(assetID, layers);
                    }
                    m_notifyList.Remove(assetID);
                }
            }
            return(true);
        }
Example #28
0
        private void HttpRequestReturn(IAsyncResult result)
        {
            if (m_textureManager == null)
            {
                m_log.WarnFormat("[LOADIMAGEURLMODULE]: No texture manager. Can't function.");
                return;
            }

            RequestState state   = (RequestState)result.AsyncState;
            WebRequest   request = (WebRequest)state.Request;
            Stream       stream  = null;

            byte[]          imageJ2000 = new byte[0];
            Size            newSize    = new Size(0, 0);
            HttpWebResponse response   = null;

            try
            {
                response = (HttpWebResponse)request.EndGetResponse(result);
                if (response != null && response.StatusCode == HttpStatusCode.OK)
                {
                    stream = response.GetResponseStream();
                    if (stream != null)
                    {
                        try
                        {
                            using (Bitmap image = new Bitmap(stream))
                            {
                                // TODO: make this a bit less hard coded
                                if ((image.Height < 64) && (image.Width < 64))
                                {
                                    newSize.Width  = 32;
                                    newSize.Height = 32;
                                }
                                else if ((image.Height < 128) && (image.Width < 128))
                                {
                                    newSize.Width  = 64;
                                    newSize.Height = 64;
                                }
                                else if ((image.Height < 256) && (image.Width < 256))
                                {
                                    newSize.Width  = 128;
                                    newSize.Height = 128;
                                }
                                else if ((image.Height < 512 && image.Width < 512))
                                {
                                    newSize.Width  = 256;
                                    newSize.Height = 256;
                                }
                                else if ((image.Height < 1024 && image.Width < 1024))
                                {
                                    newSize.Width  = 512;
                                    newSize.Height = 512;
                                }
                                else
                                {
                                    newSize.Width  = 1024;
                                    newSize.Height = 1024;
                                }

                                if (newSize.Width != image.Width || newSize.Height != image.Height)
                                {
                                    using (Bitmap resize = new Bitmap(image, newSize))
                                        imageJ2000 = OpenJPEG.EncodeFromImage(resize, false);
                                }
                                else
                                {
                                    imageJ2000 = OpenJPEG.EncodeFromImage(image, false);
                                }
                            }
                        }
                        catch (Exception)
                        {
                            m_log.Error("[LOADIMAGEURLMODULE]: OpenJpeg Conversion Failed.  Empty byte data returned!");
                        }
                    }
                    else
                    {
                        m_log.WarnFormat("[LOADIMAGEURLMODULE] No data returned");
                    }
                }
            }
            catch (WebException)
            {
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[LOADIMAGEURLMODULE]: unexpected exception {0}", e.Message);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }

                if (response != null)
                {
                    if (response.StatusCode == HttpStatusCode.MovedPermanently ||
                        response.StatusCode == HttpStatusCode.Found ||
                        response.StatusCode == HttpStatusCode.SeeOther ||
                        response.StatusCode == HttpStatusCode.TemporaryRedirect)
                    {
                        string redirectedUrl = response.Headers["Location"];

                        MakeHttpRequest(redirectedUrl, state.RequestID);
                    }
                    else
                    {
                        m_log.DebugFormat("[LOADIMAGEURLMODULE]: Returning {0} bytes of image data for request {1}",
                                          imageJ2000.Length, state.RequestID);

                        m_textureManager.ReturnData(
                            state.RequestID,
                            new OpenSim.Region.CoreModules.Scripting.DynamicTexture.DynamicTexture(
                                request.RequestUri, null, imageJ2000, newSize, false));
                    }
                    response.Close();
                }
            }
        }
Example #29
0
 /// <summary>
 /// Populates the <seealso cref="AssetData"/> byte array with a JPEG2000
 /// encoded image created from the data in <seealso cref="Image"/>
 /// </summary>
 public override void Encode()
 {
     AssetData = OpenJPEG.Encode(Image);
 }
Example #30
0
 /// <summary>
 /// Decodes the begin and end byte positions for each quality layer in
 /// the image
 /// </summary>
 /// <returns></returns>
 public bool DecodeLayerBoundaries()
 {
     return(OpenJPEG.DecodeLayerBoundaries(AssetData, out LayerInfo, out Components));
 }