Пример #1
0
        private void Assets_OnImageReceived(ImageDownload image, AssetTexture asset)
        {
            Image = image;
            Asset = asset;

            DownloadHandle.Set();
        }
        public override string Execute(string[] args, UUID fromAgentID)
        {
            if (args.Length != 1 && args.Length != 2)
                return "Usage: downloadtexture [texture-uuid] [discardlevel]";

            TextureID = UUID.Zero;
            DownloadHandle.Reset();
            Image = null;
            Asset = null;

            if (UUID.TryParse(args[0], out TextureID))
            {
                int discardLevel = 0;

                if (args.Length > 1)
                {
                    if (!Int32.TryParse(args[1], out discardLevel))
                        return "Usage: downloadtexture [texture-uuid] [discardlevel]";
                }

                Client.Assets.RequestImage(TextureID, ImageType.Normal, 1000000.0f, discardLevel, 0);

                if (DownloadHandle.WaitOne(120 * 1000, false))
                {
                    if (Image != null && Image.Success)
                    {
                        if (Asset != null && Asset.Decode())
                        {
                            try { File.WriteAllBytes(Image.ID.ToString() + ".jp2", Asset.AssetData); }
                            catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client, ex); }

                            return String.Format("Saved {0}.jp2 ({1}x{2})", Image.ID, Asset.Image.Width, Asset.Image.Height);
                        }
                        else
                        {
                            return "Failed to decode texture " + TextureID.ToString();
                        }
                    }
                    else if (Image != null && Image.NotFound)
                    {
                        return "Simulator reported texture not found: " + TextureID.ToString();
                    }
                    else
                    {
                        return "Download failed for texture " + TextureID.ToString();
                    }
                }
                else
                {
                    return "Timed out waiting for texture download";
                }
            }
            else
            {
                return "Usage: downloadtexture [texture-uuid]";
            }
        }
Пример #3
0
 private void Assets_OnImageReceived(ImageDownload image, AssetTexture asset)
 {
     if (enabled && alreadyRequested.ContainsKey(image.ID))
     {
         if (image.Success)
             Logger.DebugLog(String.Format("Finished downloading texture {0} ({1} bytes)", image.ID, image.Size));
         else
             Logger.Log("Failed to download texture " + image.ID.ToString(), Helpers.LogLevel.Warning);
     }
 }
Пример #4
0
        void Assets_OnImageReceived(ImageDownload image, AssetTexture assetTexture)
        {
            ManagedImage imgData;
            Image bitmap;

            if (image.Success)
            {
                OpenJPEG.DecodeToImage(image.AssetData, out imgData, out bitmap);
                picInsignia.Image = bitmap;
            }
        }
Пример #5
0
        void RequestImageHandler(Packet packet, Agent agent)
        {
            RequestImagePacket request = (RequestImagePacket)packet;

            for (int i = 0; i < request.RequestImage.Length; i++)
            {
                RequestImagePacket.RequestImageBlock block = request.RequestImage[i];

                ImageDownload download;
                bool downloadFound = currentDownloads.TryGetValue(block.Image, out download);

                if (downloadFound)
                {
                    lock (download)
                    {
                        if (block.DiscardLevel == -1 && block.DownloadPriority == 0.0f)
                            Logger.DebugLog(String.Format("Image download {0} is aborting", block.Image));

                        // Update download
                        download.Update(block.DiscardLevel, block.DownloadPriority, (int)block.Packet);
                    }
                }
                else if (block.DiscardLevel == -1 && block.DownloadPriority == 0.0f)
                {
                    // Aborting a download we are not tracking, this may be in the pipeline
                    Pipeline.AbortDownload(block.Image);
                }
                else
                {
                    //bool bake = ((ImageType)block.Type == ImageType.Baked);

                    // New download, check if we have this image
                    Asset asset;
                    if (scene.Server.Assets.TryGetAsset(block.Image, out asset) && asset is AssetTexture)
                    {
                        SendTexture(agent, (AssetTexture)asset, block.DiscardLevel, (int)block.Packet, block.DownloadPriority);
                    }
                    else
                    {
                        // We don't have this texture, add it to the download queue and see if the bot can get it for us
                        download = new ImageDownload(null, agent, block.DiscardLevel, block.DownloadPriority, (int)block.Packet);
                        lock (currentDownloads)
                            currentDownloads[block.Image] = download;

                        Pipeline.RequestTexture(block.Image, (ImageType)block.Type);
                    }
                }
            }
        }
Пример #6
0
        private void AssetImageFactory(ImageDownload image, AssetTexture asset)
        {
            string extension = "tga";
            byte[] data = asset.AssetData;
            switch (asset.AssetType)
            {
                case AssetType.ImageJPEG:
                    extension = "jpg";
                    break;
                case AssetType.Texture:
                    if (asset.Decode())
                        data = asset.Image.ExportTGA();
                    else
                        data = null;
                    break;
            }

            if (data == null)
                return;

            Ox.IO.Save(string.Format("{0}.{1}", asset.AssetID.ToString(), extension), data);
        }
Пример #7
0
        private void Assets_OnImageReceived(ImageDownload image, Asset asset)
        {
            int requestNbr;
            bool found;

            lock (syncObject)
                found = currentRequests.TryGetValue(image.ID, out requestNbr);

            if (asset != null && found)
            {
                Logger.DebugLog(String.Format("Worker {0} Downloaded texture {1}", requestNbr, image.ID));

                // Free up this slot in the ThreadPool
                lock (syncObject)
                    currentRequests.Remove(image.ID);

                resetEvents[requestNbr].Set();

                if (image.Success)
                {
                    // Add to the completed texture dictionary
                    lock (syncObject)
                        completedDownloads[image.ID] = image;
                }
                else
                {
                   // Logger.Log(String.Format("Download of texture {0} failed. NotFound={1}", image.ID, image.NotFound),
                     //   Helpers.LogLevel.Warning);
                }

                // Let any subscribers know about it
                if (OnDownloadFinished != null)
                    OnDownloadFinished(image.ID, image.Success);
            }
        }
Пример #8
0
        public void SetAsset(ImageDownload download)
        {
            bool xferFailed = !download.Success;
            PullServerAsset = xferFailed;
            NeedsRequest = xferFailed;
            if (download.Success)
            {
                AssetType = download.AssetType;
                AssetData = download.AssetData;
                AssetID = UUIDNonZero(AssetID, 
#if COGBOT_LIBOMV
                    download.AssetID, 
#endif
                    
                    download.ID);
            }
        }
Пример #9
0
        /// <summary>
        /// Fetach avatar texture on a grid capable of server side baking
        /// </summary>
        /// <param name="avatarID">ID of the avatar</param>
        /// <param name="textureID">ID of the texture</param>
        /// <param name="bakeName">Name of the part of the avatar texture applies to</param>
        /// <param name="callback">Callback invoked on operation completion</param>
        public void RequestServerBakedImage(UUID avatarID, UUID textureID, string bakeName, TextureDownloadCallback callback)
        {
            if (avatarID == UUID.Zero || textureID == UUID.Zero || callback == null)
                return;

            if (string.IsNullOrEmpty(Client.Network.AgentAppearanceServiceURL))
            {
                callback(TextureRequestState.NotFound, null);
                return;
            }

            byte[] assetData;
            // Do we have this image in the cache?
            if (Client.Assets.Cache.HasAsset(textureID)
                && (assetData = Client.Assets.Cache.GetCachedAssetBytes(textureID)) != null)
            {
                ImageDownload image = new ImageDownload();
                image.ID = textureID;
                image.AssetData = assetData;
                image.Size = image.AssetData.Length;
                image.Transferred = image.AssetData.Length;
                image.ImageType = ImageType.ServerBaked;
                image.AssetType = AssetType.Texture;
                image.Success = true;

                callback(TextureRequestState.Finished, new AssetTexture(image.ID, image.AssetData));
                FireImageProgressEvent(image.ID, image.Transferred, image.Size);
                return;
            }

            CapsBase.DownloadProgressEventHandler progressHandler = null;

            Uri url = new Uri(string.Format("{0}texture/{1}/{2}/{3}", Client.Network.AgentAppearanceServiceURL, avatarID, bakeName, textureID));

            DownloadRequest req = new DownloadRequest(
                url,
                Client.Settings.CAPS_TIMEOUT,
                "image/x-j2c",
                progressHandler,
                (HttpWebRequest request, HttpWebResponse response, byte[] responseData, Exception error) =>
                {
                    if (error == null && responseData != null) // success
                    {
                        ImageDownload image = new ImageDownload();
                        image.ID = textureID;
                        image.AssetData = responseData;
                        image.Size = image.AssetData.Length;
                        image.Transferred = image.AssetData.Length;
                        image.ImageType = ImageType.ServerBaked;
                        image.AssetType = AssetType.Texture;
                        image.Success = true;

                        callback(TextureRequestState.Finished, new AssetTexture(image.ID, image.AssetData));

                        Client.Assets.Cache.SaveAssetToCache(textureID, responseData);
                    }
                    else // download failed
                    {
                        Logger.Log(
                            string.Format("Failed to fetch server bake {0}: {1}",
                                textureID,
                                (error == null) ? "" : error.Message
                            ),
                            Helpers.LogLevel.Warning, Client);

                        callback(TextureRequestState.Timeout, null);
                    }
                }
            );

            HttpDownloads.QueueDownload(req);
        }
Пример #10
0
        /// <summary>
        /// Request a texture asset from the simulator using the <see cref="TexturePipeline"/> system to 
        /// manage the requests and re-assemble the image from the packets received from the simulator
        /// </summary>
        /// <param name="textureID">The <see cref="UUID"/> of the texture asset to download</param>
        /// <param name="imageType">The <see cref="ImageType"/> of the texture asset. 
        /// Use <see cref="ImageType.Normal"/> for most textures, or <see cref="ImageType.Baked"/> for baked layer texture assets</param>
        /// <param name="priority">A float indicating the requested priority for the transfer. Higher priority values tell the simulator
        /// to prioritize the request before lower valued requests. An image already being transferred using the <see cref="TexturePipeline"/> can have
        /// its priority changed by resending the request with the new priority value</param>
        /// <param name="discardLevel">Number of quality layers to discard.
        /// This controls the end marker of the data sent</param>
        /// <param name="packetStart">The packet number to begin the request at. A value of 0 begins the request
        /// from the start of the asset texture</param>
        /// <param name="callback">The <see cref="TextureDownloadCallback"/> callback to fire when the image is retrieved. The callback
        /// will contain the result of the request and the texture asset data</param>
        /// <param name="progressive">If true, the callback will be fired for each chunk of the downloaded image. 
        /// The callback asset parameter will contain all previously received chunks of the texture asset starting 
        /// from the beginning of the request</param>
        public void RequestTexture(UUID textureID, ImageType imageType, float priority, int discardLevel, uint packetStart, TextureDownloadCallback callback, bool progressive)
        {
            if (textureID == UUID.Zero)
                return;

            if (callback != null)
            {
                if (_Client.Assets.Cache.HasAsset(textureID))
                {
                    ImageDownload image = new ImageDownload();
                    image.ID = textureID;
                    image.AssetData = _Client.Assets.Cache.GetCachedAssetBytes(textureID);
                    image.Size = image.AssetData.Length;
                    image.Transferred = image.AssetData.Length;
                    image.ImageType = imageType;
                    image.AssetType = AssetType.Texture;
                    image.Success = true;

                    callback(TextureRequestState.Finished, new AssetTexture(image.ID, image.AssetData));

                    _Client.Assets.FireImageProgressEvent(image.ID, image.Transferred, image.Size);
                }
                else
                {
                    lock (_Transfers)
                    {
                        TaskInfo request;

                        if (_Transfers.TryGetValue(textureID, out request))
                        {
                            request.Callbacks.Add(callback);
                        }
                        else
                        {
                            request = new TaskInfo();
                            request.State = TextureRequestState.Pending;
                            request.RequestID = textureID;
                            request.ReportProgress = progressive;
                            request.RequestSlot = -1;
                            request.Type = imageType;

                            request.Callbacks = new List<TextureDownloadCallback>();
                            request.Callbacks.Add(callback);

                            ImageDownload downloadParams = new ImageDownload();
                            downloadParams.ID = textureID;
                            downloadParams.Priority = priority;
                            downloadParams.ImageType = imageType;
                            downloadParams.DiscardLevel = discardLevel;

                            request.Transfer = downloadParams;
#if DEBUG_TIMING
                            request.StartTime = DateTime.UtcNow;
#endif
                            _Transfers.Add(textureID, request);
                        }
                    }
                }
            }
        }
Пример #11
0
        /// <summary>
        /// Requests multiple Images
        /// </summary>
        /// <param name="Images">List of requested images</param>
        public void RequestImages(List<ImageRequest> Images)
        {
            for (int iri = 0; iri < Images.Count; iri++)
            {
                if (Transfers.ContainsKey(Images[iri].ImageID))
                {
                    Images.RemoveAt(iri);
                }

                if (Cache.HasImage(Images[iri].ImageID))
                {
                    ImageDownload transfer = Cache.GetCachedImage(Images[iri].ImageID);
                    if (null != transfer)
                    {
                        if (null != OnImageReceived)
                        {
                            AssetTexture asset = new AssetTexture(transfer.ID, transfer.AssetData);

                            try { OnImageReceived(transfer, asset); }
                            catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
                        }

                        Images.RemoveAt(iri);
                    }
                }
            }

            if (Images.Count > 0)
            {
                // Build and send the request packet
                RequestImagePacket request = new RequestImagePacket();
                request.AgentData.AgentID = Client.Self.AgentID;
                request.AgentData.SessionID = Client.Self.SessionID;
                request.RequestImage = new RequestImagePacket.RequestImageBlock[Images.Count];

                for (int iru = 0; iru < Images.Count; ++iru)
                {
                    ImageDownload transfer = new ImageDownload();
                    //transfer.AssetType = AssetType.Texture // Handled in ImageDataHandler.
                    transfer.ID = Images[iru].ImageID;
                    transfer.Simulator = Client.Network.CurrentSim;
                    transfer.ImageType = Images[iru].Type;
                    transfer.DiscardLevel = Images[iru].DiscardLevel;
                    transfer.Priority = Images[iru].Priority;

                    // Add this transfer to the dictionary
                    lock (Transfers) Transfers[transfer.ID] = transfer;
                    request.RequestImage[iru] = new RequestImagePacket.RequestImageBlock();
                    request.RequestImage[iru].DiscardLevel = (sbyte)Images[iru].DiscardLevel;
                    request.RequestImage[iru].DownloadPriority = Images[iru].Priority;
                    request.RequestImage[iru].Packet = 0;
                    request.RequestImage[iru].Image = Images[iru].ImageID;
                    request.RequestImage[iru].Type = (byte)Images[iru].Type;
                }

                Client.Network.SendPacket(request, Client.Network.CurrentSim);
            }
            else
            {
                Logger.Log("RequestImages() called for an image(s) we are already downloading or an empty list, ignoring",
                    Helpers.LogLevel.Info, Client);
            }
        }
Пример #12
0
 void Assets_OnImageReceived(ImageDownload image, AssetTexture asset)
 {
     lock (processQueue) processQueue.Enqueue(new QueueBase(new AssetManager.ImageReceivedCallback(ProcessImageReceived), image, asset));
 }
Пример #13
0
        /*
        On-Image-Received
             image: "{OpenMetaverse.ImageDownload,PacketCount=33,Codec=J2C,NotFound=False,Simulator=OpenSim Test (71.197.210.170:9000),PacketsSeen=System.Collections.Generic.SortedList`2[System.UInt16,System.UInt16],ImageType=Normal,DiscardLevel=-1,Priority=1013000,ID=728dd7fa-a688-432d-a4f7-4263b1f97395,Size=33345,AssetData=System.Byte[],Transferred=33345,Success=True,AssetType=Texture}"
             asset: "{OpenMetaverse.AssetTexture,Image=,LayerInfo=,Components=0,AssetData=System.Byte[],Temporary=False}"
         */

        public override void Assets_OnImageReceived(ImageDownload image, AssetTexture asset)
        {
            OnAssetDownloaded(asset.AssetID, asset);
            RegisterUUIDMaybe(image.ID, image);
        }
Пример #14
0
 public virtual void Assets_OnImageReceived(ImageDownload image, AssetTexture asset) { OnEvent("On-Image-Received", paramNamesOnImageReceived, paramTypesOnImageReceived, image, asset); }
Пример #15
0
 private void ProcessImageReceived(ImageDownload image, AssetTexture asset)
 {
     if (image.Success)
         AssetFactoryEnqueue(new QueueAsset(image, asset));
 }
Пример #16
0
        /// <summary>
        /// Initiate an image download. This is an asynchronous function
        /// </summary>
        /// <param name="imageID">The image to download</param>
        /// <param name="type">Type of the image to download, either a baked
        /// avatar texture or a normal texture</param>
        /// <param name="priority">Priority level of the download. Default is
        /// <c>1,013,000.0f</c></param>
        /// <param name="discardLevel">Number of quality layers to discard.
        /// This controls the end marker of the data sent</param>
        /// <param name="packetNum">Packet number to start the download at.
        /// This controls the start marker of the data sent</param>
        /// <remarks>Sending a priority of 0 and a discardlevel of -1 aborts
        /// download</remarks>
        public void RequestImage(UUID imageID, ImageType type, float priority, int discardLevel, uint packetNum)
        {
            if (Cache.HasImage(imageID))
            {
                ImageDownload transfer = Cache.GetCachedImage(imageID);
                transfer.ImageType = type;

                if (null != transfer)
                {
                    if (null != OnImageReceived)
                    {
                        AssetTexture asset = new AssetTexture(transfer.ID, transfer.AssetData);

                        try { OnImageReceived(transfer, asset); }
                        catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
                    }
                    return;
                }
            }

            // Priority == 0 && DiscardLevel == -1 means cancel the transfer
            if (priority.Equals(0) && discardLevel.Equals(-1))
            {
                if (Transfers.ContainsKey(imageID))
                    Transfers.Remove(imageID);

                RequestImagePacket cancel = new RequestImagePacket();
                cancel.AgentData.AgentID = Client.Self.AgentID;
                cancel.AgentData.SessionID = Client.Self.SessionID;
                cancel.RequestImage = new RequestImagePacket.RequestImageBlock[1];
                cancel.RequestImage[0] = new RequestImagePacket.RequestImageBlock();
                cancel.RequestImage[0].DiscardLevel = -1;
                cancel.RequestImage[0].DownloadPriority = 0;
                cancel.RequestImage[0].Packet = 0;
                cancel.RequestImage[0].Image = imageID;
                cancel.RequestImage[0].Type = 0;
            }
            else
            {
                Simulator currentSim = Client.Network.CurrentSim;

                if (!Transfers.ContainsKey(imageID))
                {
                    // New download
                    ImageDownload transfer = new ImageDownload();
                    transfer.ID = imageID;
                    transfer.Simulator = currentSim;
                    transfer.ImageType = type;
                    transfer.DiscardLevel = discardLevel;
                    transfer.Priority = priority;

                    // Add this transfer to the dictionary
                    lock (Transfers) Transfers[transfer.ID] = transfer;

                    Logger.DebugLog("Adding image " + imageID.ToString() + " to the download queue");
                }
                else
                {
                    // Already downloading, just updating the priority
                    Transfer transfer = Transfers[imageID];
                    float percentComplete = ((float)transfer.Transferred / (float)transfer.Size) * 100f;
                    if (Single.IsNaN(percentComplete))
                        percentComplete = 0f;

                    Logger.DebugLog(String.Format("Updating priority on image transfer {0}, {1}% complete",
                        imageID, Math.Round(percentComplete, 2)));
                }

                // Build and send the request packet
                RequestImagePacket request = new RequestImagePacket();
                request.AgentData.AgentID = Client.Self.AgentID;
                request.AgentData.SessionID = Client.Self.SessionID;
                request.RequestImage = new RequestImagePacket.RequestImageBlock[1];
                request.RequestImage[0] = new RequestImagePacket.RequestImageBlock();
                request.RequestImage[0].DiscardLevel = (sbyte)discardLevel;
                request.RequestImage[0].DownloadPriority = priority;
                request.RequestImage[0].Packet = packetNum;
                request.RequestImage[0].Image = imageID;
                request.RequestImage[0].Type = (byte)type;

                Client.Network.SendPacket(request, currentSim);
            }
        }
Пример #17
0
        private void Assets_OnImageReceived(ImageDownload image, AssetTexture asset)
        {
            if (Textures.Contains(image.ID))
            {
                lock (Textures)
                    Textures.Remove(image.ID);

                if (image.Success)
                {
                    try { File.WriteAllBytes(image.ID.ToString() + ".jp2", asset.AssetData); }
                    catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client); }

                    if (asset.Decode())
                    {
                        try { File.WriteAllBytes(image.ID.ToString() + ".tga", asset.Image.ExportTGA()); }
                        catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client); }
                    }
                    else
                    {
                        Logger.Log("Failed to decode image " + image.ID.ToString(), Helpers.LogLevel.Error, Client);
                    }

                    Logger.Log("Finished downloading image " + image.ID.ToString(), Helpers.LogLevel.Info, Client);
                }
                else
                {
                    Logger.Log("Failed to download image " + image.ID.ToString(), Helpers.LogLevel.Warning, Client);
                }
            }
        }
        void SendTexture(Agent agent, AssetTexture texture, int discardLevel, int packet, float priority)
        {
            ImageDownload download = new ImageDownload(texture, agent, discardLevel, priority, packet);

            Logger.DebugLog(String.Format(
                "[Periscope] Starting new texture transfer for {0}, DiscardLevel: {1}, Priority: {2}, Start: {3}, End: {4}, Total: {5}",
                texture.AssetID, discardLevel, priority, download.CurrentPacket, download.StopPacket, download.TexturePacketCount()));

            // Send initial data
            ImageDataPacket data = new ImageDataPacket();
            data.ImageID.Codec = (byte)ImageCodec.J2C;
            data.ImageID.ID = download.Texture.AssetID;
            data.ImageID.Packets = (ushort)download.TexturePacketCount();
            data.ImageID.Size = (uint)download.Texture.AssetData.Length;

            // The first bytes of the image are always sent in the ImageData packet
            data.ImageData = new ImageDataPacket.ImageDataBlock();
            int imageDataSize = (download.Texture.AssetData.Length >= ImageDownload.FIRST_IMAGE_PACKET_SIZE) ?
                ImageDownload.FIRST_IMAGE_PACKET_SIZE : download.Texture.AssetData.Length;
            try
            {
                data.ImageData.Data = new byte[imageDataSize];
                Buffer.BlockCopy(download.Texture.AssetData, 0, data.ImageData.Data, 0, imageDataSize);
            }
            catch (Exception ex)
            {
                Logger.Log(String.Format("{0}: imageDataSize={1}", ex.Message, imageDataSize),
                    Helpers.LogLevel.Error);
            }

            server.UDP.SendPacket(agent.Avatar.ID, data, PacketCategory.Texture);

            // Check if ImagePacket packets need to be sent to complete this transfer
            if (download.CurrentPacket <= download.StopPacket)
            {
                // Insert this download into the dictionary
                lock (currentDownloads)
                    currentDownloads[texture.AssetID] = download;

                // Send all of the remaining packets
                ThreadPool.QueueUserWorkItem(
                    delegate(object obj)
                    {
                        while (download.CurrentPacket <= download.StopPacket)
                        {
                            if (download.Priority == 0.0f && download.DiscardLevel == -1)
                                break;

                            lock (download)
                            {
                                int imagePacketSize = (download.CurrentPacket == download.TexturePacketCount() - 1) ?
                                    download.LastPacketSize() : ImageDownload.IMAGE_PACKET_SIZE;

                                ImagePacketPacket transfer = new ImagePacketPacket();
                                transfer.ImageID.ID = texture.AssetID;
                                transfer.ImageID.Packet = (ushort)download.CurrentPacket;
                                transfer.ImageData.Data = new byte[imagePacketSize];

                                try
                                {
                                    Buffer.BlockCopy(download.Texture.AssetData, download.CurrentBytePosition(),
                                        transfer.ImageData.Data, 0, imagePacketSize);
                                }
                                catch (Exception ex)
                                {
                                    Logger.Log(String.Format(
                                        "{0}: CurrentBytePosition()={1}, AssetData.Length={2} imagePacketSize={3}",
                                        ex.Message, download.CurrentBytePosition(), download.Texture.AssetData.Length,
                                        imagePacketSize), Helpers.LogLevel.Error);
                                }

                                server.UDP.SendPacket(agent.Avatar.ID, transfer, PacketCategory.Texture);

                                ++download.CurrentPacket;
                            }
                        }

                        Logger.DebugLog("Completed image transfer for " + texture.AssetID.ToString());

                        // Transfer is complete, remove the reference
                        lock (currentDownloads)
                            currentDownloads.Remove(texture.AssetID);
                    }
                );
            }
        }
Пример #19
0
 /// <summary>
 /// retrieve texture information from dictionary
 /// </summary>
 /// <param name="textureID">Texture ID</param>
 /// <returns>ImageDownload object</returns>
 public ImageDownload GetTextureToRender(UUID textureID)
 {
     ImageDownload renderable = new ImageDownload();
     lock (RenderReady)
     {
         if (RenderReady.ContainsKey(textureID))
         {
             renderable = RenderReady[textureID];
         }
         else
         {
             Logger.Log("Requested texture data for texture that does not exist in dictionary", Helpers.LogLevel.Warning);
         }
         return renderable;
     }
 }
Пример #20
0
        // Helper method for downloading textures via GetTexture cap
        // Same signature as the UDP variant since we need all the params to
        // pass to the UDP TexturePipeline in case we need to fall back to it
        // (Linden servers currently (1.42) don't support bakes downloads via HTTP)
        private void HttpRequestTexture(UUID textureID, ImageType imageType, float priority, int discardLevel,
            uint packetStart, TextureDownloadCallback callback, bool progress)
        {
            if (textureID == UUID.Zero || callback == null)
                return;

            byte[] assetData;
            // Do we have this image in the cache?
            if (Client.Assets.Cache.HasAsset(textureID)
                && (assetData = Client.Assets.Cache.GetCachedAssetBytes(textureID)) != null)
            {
                ImageDownload image = new ImageDownload();
                image.ID = textureID;
                image.AssetData = assetData;
                image.Size = image.AssetData.Length;
                image.Transferred = image.AssetData.Length;
                image.ImageType = imageType;
                image.AssetType = AssetType.Texture;
                image.Success = true;

                callback(TextureRequestState.Finished, new AssetTexture(image.ID, image.AssetData));
                FireImageProgressEvent(image.ID, image.Transferred, image.Size);
                return;
            }

            CapsBase.DownloadProgressEventHandler progressHandler = null;

            if (progress)
            {
                progressHandler = (HttpWebRequest request, HttpWebResponse response, int bytesReceived, int totalBytesToReceive) =>
                    {
                        FireImageProgressEvent(textureID, bytesReceived, totalBytesToReceive);
                    };
            }

            Uri url = Client.Network.CurrentSim.Caps.CapabilityURI("GetTexture");

            DownloadRequest req = new DownloadRequest(
                new Uri(string.Format("{0}/?texture_id={1}", url.ToString(), textureID.ToString())),
                Client.Settings.CAPS_TIMEOUT,
                "image/x-j2c",
                progressHandler,
                (HttpWebRequest request, HttpWebResponse response, byte[] responseData, Exception error) =>
                {
                    if (error == null && responseData != null) // success
                    {
                        ImageDownload image = new ImageDownload();
                        image.ID = textureID;
                        image.AssetData = responseData;
                        image.Size = image.AssetData.Length;
                        image.Transferred = image.AssetData.Length;
                        image.ImageType = imageType;
                        image.AssetType = AssetType.Texture;
                        image.Success = true;

                        callback(TextureRequestState.Finished, new AssetTexture(image.ID, image.AssetData));
                        FireImageProgressEvent(image.ID, image.Transferred, image.Size);

                        Client.Assets.Cache.SaveAssetToCache(textureID, responseData);
                    }
                    else // download failed
                    {
                        Logger.Log(
                            string.Format("Failed to fetch texture {0} over HTTP, falling back to UDP: {1}",
                                textureID,
                                (error == null) ? "" : error.Message
                            ),
                            Helpers.LogLevel.Warning, Client);

                        Texture.RequestTexture(textureID, imageType, priority, discardLevel, packetStart, callback, progress);
                    }
                }
            );

            HttpDownloads.QueueDownload(req);
        }
Пример #21
0
        private void Assets_OnImageReceived(ImageDownload image, AssetTexture asset)
        {
            // Free up this slot in the ThreadPool
            lock (CurrentRequests)
            {
                int requestNbr;
                if (asset != null && CurrentRequests.TryGetValue(image.ID, out requestNbr))
                {
                    Logger.DebugLog(String.Format("Worker {0} Downloaded texture {1}", requestNbr, image.ID));
                    resetEvents[requestNbr].Set();
                    CurrentRequests.Remove(image.ID);
                }
            }

            if (image.Success)
            {
                lock (RenderReady)
                {
                    if (!RenderReady.ContainsKey(image.ID))
                    {
                        // Add to rendering dictionary
                        RenderReady.Add(image.ID, image);
                    }
                }
            }
            else
            {
                Console.WriteLine(String.Format("Download of texture {0} failed. NotFound={1}", image.ID, image.NotFound));
            }

            // Let any subscribers know about it
            if (OnDownloadFinished != null)
            {
                OnDownloadFinished(image.ID, image.Success);
            }
        }
Пример #22
0
        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;
                }
            }
        }
Пример #23
0
        private void Assets_OnImageReceived(ImageDownload image, AssetTexture assetTexture)
        {
            lock (ImageDownloads)
            {
                if (ImageDownloads.ContainsKey(image.ID))
                {
                    ImageDownloads.Remove(image.ID);

                    // NOTE: This image may occupy more than one TextureIndex! We must finish this loop
                    for (int at = 0; at < AgentTextures.Length; at++)
                    {
                        if (AgentTextures[at] == image.ID)
                        {
                            TextureIndex index = (TextureIndex)at;
                            BakeType type = Baker.BakeTypeFor(index);

                            //BinaryWriter writer = new BinaryWriter(File.Create("wearable_" + index.ToString() + "_" + image.ID.ToString() + ".jp2"));
                            //writer.Write(image.AssetData);
                            //writer.Close();

                            bool baked = false;
                            AgentAssets[at]=assetTexture; //Cache this asset for rebaking, todo this could be better rather than dropping in this list.

                            if (PendingBakes.ContainsKey(type))
                            {
                                if (image.Success)
                                {
                                    Logger.DebugLog("Finished downloading texture for " + index.ToString(), Client);
                                    OpenJPEG.DecodeToImage(image.AssetData, out assetTexture.Image);
                                    baked = PendingBakes[type].AddTexture(index, assetTexture, false);
                                }
                                else
                                {
                                    Logger.Log("Texture for " + index.ToString() + " failed to download, " +
                                        "bake will be incomplete", Helpers.LogLevel.Warning, Client);
                                    baked = PendingBakes[type].MissingTexture(index);
                                }
                            }

                            if (baked)
                            {
                                UploadBake(PendingBakes[type]);
                                PendingBakes.Remove(type);
                            }

                            if (ImageDownloads.Count == 0 && PendingUploads.Count == 0)
                            {
                                // This is a failsafe catch, as the upload completed callback should normally 
                                // be triggering the event
                                Logger.DebugLog("No pending downloads or uploads detected in OnImageReceived", Client);
                                CachedResponseEvent.Set();
                            }
                            else
                            {
                                Logger.DebugLog("Pending uploads: " + PendingUploads.Count + ", pending downloads: " +
                                    ImageDownloads.Count, Client);
                            }

                        }
                    }
                }
                else
                {
                    Logger.Log("Received an image download callback for an image we did not request " + image.ID.ToString(),
                        Helpers.LogLevel.Warning, Client);
                }
            }
        }
Пример #24
0
 private void imageReceivedCallback(ImageDownload image, AssetTexture asset)
 {
     if (OnImageReceived != null)
     {
         OnImageReceived(asset);
     }
 }
 private void OnImageReceived(OMV.ImageDownload cntl, OMV.Assets.AssetTexture textureID)
 {
 }