Пример #1
0
 //Faux destructor
 public void Close()
 {
     m_shuttingdown    = true;
     m_j2kDecodeModule = null;
     m_assetCache      = null;
     m_client          = null;
 }
Пример #2
0
        public LLImageManager(IClientAPI client, IAssetService pAssetCache, IJ2KDecoder pJ2kDecodeModule)
        {
            Client       = client;
            m_assetCache = pAssetCache;

            m_j2kDecodeModule = pJ2kDecodeModule;
        }
Пример #3
0
 public BakedTextureUploader(Caps caps, string path, IAssetCache assetCache, IJ2KDecoder layerDecoder)
 {
     m_uploaderPath = path;
     m_Caps         = caps;
     m_assetCache   = assetCache;
     m_layerDecoder = layerDecoder;
 }
        private warp_Texture GetTexture(UUID id)
        {
            warp_Texture ret = null;

            byte[] asset = m_scene.AssetService.GetData(id.ToString());

            if (asset != null)
            {
                IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface <IJ2KDecoder>();

                try
                {
                    using (Bitmap img = (Bitmap)imgDecoder.DecodeToImage(asset))
                    {
                        ret = new warp_Texture(img);
                        img.Dispose();
                    }
                }
                catch (Exception e)
                {
                    m_log.Warn(string.Format("[WARP 3D IMAGE MODULE]: Failed to decode asset {0}, exception  ", id), e);
                }
            }

            return(ret);
        }
Пример #5
0
 public void Initialise(IScene scene, IConfigSource config)
 {
     m_scene      = scene;
     m_imgDecoder = m_scene.RequestModuleInterface <IJ2KDecoder>();
     m_config     = config;
     ReadCacheMap();
 }
        bool m_renderMeshes = true;     // true if to render meshes rather than just bounding boxes

        #region IMapTileTerrainRenderer Members

        public void Initialise (IScene scene, IConfigSource config)
        {
            m_scene = scene;
            m_imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder> ();
            m_config = config;
            m_assetCacheDir = m_config.Configs ["AssetCache"].GetString ("CacheDirectory", m_assetCacheDir);
            if (m_assetCacheDir == "") {
                var defpath = scene.RequestModuleInterface<ISimulationBase> ().DefaultDataPath;
                m_assetCacheDir = System.IO.Path.Combine (defpath, Constants.DEFAULT_ASSETCACHE_DIR);
            }

            List<string> renderers = RenderingLoader.ListRenderers (Util.ExecutingDirectory ());
            if (renderers.Count > 0) {
                m_primMesher = RenderingLoader.LoadRenderer (renderers [0]);
                MainConsole.Instance.Debug ("[WarpTile generator]: Loaded prim mesher " + m_primMesher);
            } else {
                MainConsole.Instance.Info ("[WarpTile generator]: No prim mesher loaded, prim rendering will be disabled");
            }

            var mapConfig = m_config.Configs ["MapModule"];
            if (mapConfig != null) {
                m_texturePrimSize = mapConfig.GetFloat ("TexturePrimSize", m_texturePrimSize);
                m_renderMeshes = mapConfig.GetBoolean ("RenderMeshes", m_renderMeshes);
            }


            ReadCacheMap ();
        }
        bool m_renderMeshes     = true; // true if to render meshes rather than just bounding boxes

        #region IMapTileTerrainRenderer Members

        public void Initialize(IScene scene, IConfigSource config)
        {
            m_scene         = scene;
            m_imgDecoder    = m_scene.RequestModuleInterface <IJ2KDecoder> ();
            m_config        = config;
            m_assetCacheDir = m_config.Configs ["AssetCache"].GetString("CacheDirectory", m_assetCacheDir);
            if (m_assetCacheDir == "")
            {
                var defpath = scene.RequestModuleInterface <ISimulationBase> ().DefaultDataPath;
                m_assetCacheDir = System.IO.Path.Combine(defpath, Constants.DEFAULT_ASSETCACHE_DIR);
            }

            List <string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());

            if (renderers.Count > 0)
            {
                m_primMesher = RenderingLoader.LoadRenderer(renderers [0]);
                MainConsole.Instance.Debug("[WarpTile generator]: Loaded prim mesher " + m_primMesher);
            }
            else
            {
                MainConsole.Instance.Info("[WarpTile generator]: No prim mesher loaded, prim rendering will be disabled");
            }

            var mapConfig = m_config.Configs ["MapModule"];

            if (mapConfig != null)
            {
                m_texturePrimSize = mapConfig.GetFloat("TexturePrimSize", m_texturePrimSize);
                m_renderMeshes    = mapConfig.GetBoolean("RenderMeshes", m_renderMeshes);
            }


            ReadCacheMap();
        }
Пример #8
0
 public void Initialise(IScene scene, IConfigSource config)
 {
     m_scene = scene;
     m_imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>();
     m_config = config;
     ReadCacheMap();
 }
        bool m_renderMeshes     = true; // true if to render meshes rather than just bounding boxes

        #region IMapTileTerrainRenderer Members

        public void Initialise(IScene scene, IConfigSource config)
        {
            m_scene         = scene;
            m_imgDecoder    = m_scene.RequestModuleInterface <IJ2KDecoder>();
            m_config        = config;
            m_assetCacheDir = m_config.Configs ["AssetCache"].GetString("CacheDirectory", m_assetCacheDir);

            List <string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());

            if (renderers.Count > 0)
            {
                m_primMesher = RenderingLoader.LoadRenderer(renderers[0]);
                MainConsole.Instance.Debug("[MAPTILE]: Loaded prim mesher " + m_primMesher);
            }
            else
            {
                MainConsole.Instance.Info("[MAPTILE]: No prim mesher loaded, prim rendering will be disabled");
            }

            var mapConfig = m_config.Configs ["MapModule"];

            if (mapConfig != null)
            {
                m_texturePrimSize = mapConfig.GetFloat("TexturePrimSize", m_texturePrimSize);
                m_renderMeshes    = mapConfig.GetBoolean("RenderMeshes", m_renderMeshes);
            }


            ReadCacheMap();
        }
        warp_Texture GetTexture(UUID id)
        {
            warp_Texture ret = null;

            if (id == UUID.Zero)
            {
                id = (UUID)Constants.MISSING_TEXTURE_ID;
            }

            byte [] assetData = m_scene.AssetService.GetData(id.ToString(), false);         // suppress warnings here
            if (assetData == null || assetData.Length == 0)
            {
                assetData = m_scene.AssetService.GetData(Constants.MISSING_TEXTURE_ID);     // not found, replace with something identifable
            }
            if (assetData != null && assetData.Length > 0)
            {
                IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface <IJ2KDecoder> ();
                Bitmap      img        = (Bitmap)imgDecoder.DecodeToImage(assetData);

                if (img != null)
                {
                    ret = new warp_Texture(img);
                    img.Dispose();
                    return(ret);
                }
            }
            MainConsole.Instance.Debug("[WarpTile generator]: Gettexture returning null, asset id: " + id);
            return(ret);
        }
Пример #11
0
        public void RegionLoaded(Scene scene)
        {
            if (!m_Enabled)
            {
                return;
            }

            m_imgDecoder = m_scene.RequestModuleInterface <IJ2KDecoder>();
        }
Пример #12
0
 public Abuse(IAssetService assetService, IJ2KDecoder j2k)
 {
     InitializeComponent();
     m_decoder             = j2k;
     m_assetService        = assetService;
     AbuseReportsConnector = DataManager.DataManager.RequestPlugin <IAbuseReportsConnector>();
     Password = "";
     Utilities.InputBox("Password Input Required", "Password for abuse reports database", ref Password);
 }
Пример #13
0
 public Abuse(IAssetService assetService, IJ2KDecoder j2k)
 {
     InitializeComponent();
     m_decoder = j2k;
     m_assetService = assetService;
     AbuseReportsConnector = DataManager.DataManager.RequestPlugin<IAbuseReportsConnector>();
     Password = "";
     Utilities.InputBox("Password Input Required", "Password for abuse reports database", ref Password);
 }
Пример #14
0
 public void Start(IConfigSource config, IRegistryCore registry)
 {
     if (!m_enabled)
     {
         return;
     }
     m_assetService = m_registry.RequestModuleInterface <IAssetService>();
     m_gridService  = m_registry.RequestModuleInterface <IGridService>();
     m_j2kDecoder   = m_registry.RequestModuleInterface <IJ2KDecoder>();
 }
        void HandleDecode(string module, string[] args)
        {
            if (args.Length < 3)
            {
                MainConsole.Instance.Output("Usage is j2k decode <ID>");
                return;
            }

            UUID   assetId;
            string rawAssetId = args[2];

            if (!UUID.TryParse(rawAssetId, out assetId))
            {
                MainConsole.Instance.OutputFormat("ERROR: {0} is not a valid ID format", rawAssetId);
                return;
            }

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

            if (asset == null)
            {
                MainConsole.Instance.OutputFormat("ERROR: No asset found with ID {0}", assetId);
                return;
            }

            if (asset.Type != (sbyte)AssetType.Texture)
            {
                MainConsole.Instance.OutputFormat("ERROR: Asset {0} is not a texture type", assetId);
                return;
            }

            IJ2KDecoder decoder = m_scene.RequestModuleInterface <IJ2KDecoder>();

            if (decoder == null)
            {
                MainConsole.Instance.OutputFormat("ERROR: No IJ2KDecoder module available");
                return;
            }

            OpenJPEG.J2KLayerInfo[] layers;
            int components;

            if (decoder.Decode(assetId, asset.Data, out layers, out components))
            {
                MainConsole.Instance.OutputFormat(
                    "Successfully decoded asset {0} with {1} layers and {2} components",
                    assetId, layers.Length, components);
            }
            else
            {
                MainConsole.Instance.OutputFormat("Decode of asset {0} failed", assetId);
            }
        }
Пример #16
0
        public LLImageManager(LLClientView client, IAssetCache pAssetCache,
                              IJ2KDecoder pJ2kDecodeModule)
        {
            m_client     = client;
            m_assetCache = pAssetCache;

            /*if (pAssetCache != null)
             *  m_missingImage = pAssetCache.GetAsset(UUID.Parse("5748decc-f629-461c-9a36-a35a221fe21f"), AssetRequestInfo.InternalRequest());
             *
             * if (m_missingImage == null)
             *  m_log.Error("[ClientView] - Couldn't set missing image asset, falling back to missing image packet. This is known to crash the client");
             */
            m_j2kDecodeModule = pJ2kDecodeModule;
        }
Пример #17
0
 //Constructor
 public LLImageManager(LLClientView client, IAssetService pAssetCache, IJ2KDecoder pJ2kDecodeModule)
 {
     
     m_imagestore = new Dictionary<UUID,J2KImage>();
     m_priorities = new SortedList<double,UUID>();
     m_priorityresolver = new Dictionary<int, int>();
     m_client = client;
     m_assetCache = pAssetCache;
     if (pAssetCache != null)
         m_missingsubstitute = pAssetCache.Get("5748decc-f629-461c-9a36-a35a221fe21f");
     else
         m_log.Error("[ClientView] - couldn't set missing image, all manner of things will probably break");
     m_j2kDecodeModule = pJ2kDecodeModule;
 }
Пример #18
0
        public LLImageManager(LLClientView client, IAssetService pAssetCache, IJ2KDecoder pJ2kDecodeModule)
        {
            m_client = client;
            m_assetCache = pAssetCache;

            if (pAssetCache != null && m_missingImage == null)
                m_missingImage = pAssetCache.Get("5748decc-f629-461c-9a36-a35a221fe21f");

            if (m_missingImage == null)
                MainConsole.Instance.Error(
                    "[ClientView] - Couldn't set missing image asset, falling back to missing image packet. This is known to crash the client");

            m_j2kDecodeModule = pJ2kDecodeModule;
        }
Пример #19
0
        public void IncomingCapsRequest(UUID agentID, Aurora.Framework.Services.GridRegion region, ISimulationBase simbase, ref OSDMap capURLs)
        {
            m_AgentID      = agentID;
            m_assetService = simbase.ApplicationRegistry.RequestModuleInterface <IAssetService>();
            m_j2kDecoder   = simbase.ApplicationRegistry.RequestModuleInterface <IJ2KDecoder>();

            m_getTextureURI       = "/CAPS/GetTexture/" + UUID.Random() + "/";
            capURLs["GetTexture"] = MainServer.Instance.ServerURI + m_getTextureURI;
            MainServer.Instance.AddStreamHandler(new GenericStreamHandler("GET", m_getTextureURI, ProcessGetTexture));
            m_bakedTextureURI             = "/CAPS/UploadBakedTexture/" + UUID.Random() + "/";
            capURLs["UploadBakedTexture"] = MainServer.Instance.ServerURI + m_bakedTextureURI;
            MainServer.Instance.AddStreamHandler(new GenericStreamHandler("POST", m_bakedTextureURI, UploadBakedTexture));
            m_getMeshURI       = "/CAPS/GetMesh/" + UUID.Random() + "/";
            capURLs["GetMesh"] = MainServer.Instance.ServerURI + m_getMeshURI;
            MainServer.Instance.AddStreamHandler(new GenericStreamHandler("GET", m_getMeshURI, ProcessGetMesh));
        }
Пример #20
0
        private warp_Texture GetTexture(UUID id)
        {
            warp_Texture ret = null;

            byte[] asset = m_scene.AssetService.GetData(id.ToString());
            if (asset != null)
            {
                IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface <IJ2KDecoder>();
                Bitmap      img        = (Bitmap)imgDecoder.DecodeToImage(asset);
                if (img != null)
                {
                    return(new warp_Texture(img));
                }
            }
            return(ret);
        }
Пример #21
0
 //Constructor
 public LLImageManager(LLClientView client, IAssetCache pAssetCache, IJ2KDecoder pJ2kDecodeModule)
 {
     m_imagestore       = new Dictionary <UUID, J2KImage>();
     m_priorities       = new SortedList <double, UUID>();
     m_priorityresolver = new Dictionary <int, int>();
     m_client           = client;
     m_assetCache       = pAssetCache;
     if (pAssetCache != null)
     {
         m_missingsubstitute = pAssetCache.GetAsset(UUID.Parse("5748decc-f629-461c-9a36-a35a221fe21f"), true);
     }
     else
     {
         m_log.Error("[ClientView] - couldn't set missing image, all manner of things will probably break");
     }
     m_j2kDecodeModule = pJ2kDecodeModule;
 }
Пример #22
0
        public LLImageManager(LLClientView client, IAssetService pAssetCache, IJ2KDecoder pJ2kDecodeModule)
        {
            m_client     = client;
            m_assetCache = pAssetCache;

            if (pAssetCache != null && m_missingImage == null)
            {
                //m_missingImage = pAssetCache.Get("5748decc-f629-461c-9a36-a35a221fe21f"); // this is just a blank texture. Not very useful -greythane-
                m_missingImage = pAssetCache.Get(Constants.MISSING_TEXTURE_ID);
            }
            if (m_missingImage == null)
            {
                MainConsole.Instance.Error(
                    "[ClientView] - Couldn't set missing image asset, falling back to missing image packet. This is known to crash the client");
            }

            m_j2kDecodeModule = pJ2kDecodeModule;
        }
        private warp_Texture GetTexture(UUID id)
        {
            warp_Texture ret   = null;
            AssetBase    asset = m_scene.AssetService.Get(id.ToString());

            if (asset != null)
            {
                IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface <IJ2KDecoder>();
                Bitmap      img        = (Bitmap)imgDecoder.DecodeToImage(asset.Data);
                if (img != null)
                {
                    ret = new warp_Texture(img);
                    img.Dispose();
                }
                asset.Dispose();
            }
            return(ret);
        }
Пример #24
0
        public void IncomingCapsRequest (UUID agentID, Framework.Services.GridRegion region, ISimulationBase simbase, ref OSDMap capURLs)
        {
            m_AgentID = agentID;
            m_assetService = simbase.ApplicationRegistry.RequestModuleInterface<IAssetService> ();
            m_j2kDecoder = simbase.ApplicationRegistry.RequestModuleInterface<IJ2KDecoder> ();

            m_getTextureURI = "/CAPS/GetTexture/" + UUID.Random () + "/";
            capURLs ["GetTexture"] = MainServer.Instance.ServerURI + m_getTextureURI;
            MainServer.Instance.AddStreamHandler (new GenericStreamHandler ("GET", m_getTextureURI, ProcessGetTexture));

            m_bakedTextureURI = "/CAPS/UploadBakedTexture/" + UUID.Random () + "/";
            capURLs ["UploadBakedTexture"] = MainServer.Instance.ServerURI + m_bakedTextureURI;
            MainServer.Instance.AddStreamHandler (new GenericStreamHandler ("POST", m_bakedTextureURI, UploadBakedTexture));

            m_getMeshURI = "/CAPS/GetMesh/" + UUID.Random () + "/";
            capURLs ["GetMesh"] = MainServer.Instance.ServerURI + m_getMeshURI;
            MainServer.Instance.AddStreamHandler (new GenericStreamHandler ("GET", m_getMeshURI, ProcessGetMesh));
        }
Пример #25
0
        public Meshmerizer(IConfigSource config, IRegistryCore registry)
        {
            IConfig start_config = config.Configs ["Meshing"];

            decodedSculptMapPath = start_config.GetString("DecodedSculptMapPath", "j2kDecodeCache");
            cacheSculptMaps      = start_config.GetBoolean("CacheSculptMaps", cacheSculptMaps);
            UseMeshesPhysicsMesh = start_config.GetBoolean("UseMeshesPhysicsMesh", UseMeshesPhysicsMesh);

            cacheSculptAlphaMaps = Environment.OSVersion.Platform != PlatformID.Unix && cacheSculptMaps;
            m_j2kDecoder         = registry.RequestModuleInterface <IJ2KDecoder> ();
            try {
                if (!Directory.Exists(decodedSculptMapPath))
                {
                    Directory.CreateDirectory(decodedSculptMapPath);
                }
            } catch (Exception e) {
                MainConsole.Instance.WarnFormat("[Sculpt]: Unable to create {0} directory: ", decodedSculptMapPath,
                                                e.ToString());
            }
        }
Пример #26
0
            /// <summary>
            /// Handle a request from the client for a Uri to upload a baked texture.
            /// </summary>
            /// <param name="request"></param>
            /// <param name="path"></param>
            /// <param name="param"></param>
            /// <param name="httpRequest"></param>
            /// <param name="httpResponse"></param>
            /// <returns>The upload response if the request is successful, null otherwise.</returns>
            public string UploadBakedTexture(
                string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
            {
                try
                {
                    IAssetCache          assetCache   = m_Scene.CommsManager.AssetCache;
                    IJ2KDecoder          layerDecoder = m_Scene.RequestModuleInterface <IJ2KDecoder>();
                    String               uploaderPath = m_Caps.CapsBase + "/" + UUID.Random();
                    BakedTextureUploader uploader     = new BakedTextureUploader(m_Caps, uploaderPath, assetCache, layerDecoder);
                    m_Caps.HttpListener.AddStreamHandler(new BinaryStreamHandler("POST", uploaderPath, uploader.BakedTextureUploaded));

                    string uploaderURL = m_Caps.HttpListener.ServerURI + uploaderPath;
                    LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
                    uploadResponse.uploader = uploaderURL;
                    uploadResponse.state    = "upload";
                    return(LLSDHelpers.SerializeLLSDReply(uploadResponse));
                }
                catch (Exception e)
                {
                    m_log.ErrorFormat("[UPLOAD BAKED TEXTURE HANDLER]: {0}{1}", e.Message, e.StackTrace);
                }

                return(null);
            }
Пример #27
0
        public void Initialise(IScene scene, IConfigSource config)
        {
            m_scene = scene;
            m_imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>();
            m_config = config;
            m_assetCacheDir = m_config.Configs ["AssetCache"].GetString ("CacheDirectory",m_assetCacheDir);

            ReadCacheMap();
        }
Пример #28
0
 public BakedTextureUploader(Caps caps, string path, IAssetCache assetCache, IJ2KDecoder layerDecoder)
 {
     m_uploaderPath = path;
     m_Caps = caps;
     m_assetCache = assetCache;
     m_layerDecoder = layerDecoder;
 }
            /// <summary>
            ///     Called once new texture data has been received for this updater.
            /// </summary>
            public void DataReceived(byte [] data, IScene scene)
            {
                ISceneChildEntity part = scene.GetSceneObjectPart(PrimID);

                if (part == null || data == null || data.Length <= 1)
                {
                    IChatModule chatModule = scene.RequestModuleInterface <IChatModule> ();
                    if (chatModule != null)
                    {
                        string msg =
                            string.Format("DynamicTextureModule: Error preparing image using URL {0}", Url);
                        if (part != null)
                        {
                            chatModule.SimChat(msg, ChatTypeEnum.Say, 0,
                                               part.ParentEntity.AbsolutePosition, part.Name, part.UUID, false, scene);
                        }
                        else
                        {
                            chatModule.SimChat(msg, ChatTypeEnum.Say, 0,
                                               new Vector3(), "Unknown", UUID.Zero, false, scene);
                        }
                    }
                    return;
                }

                byte []   assetData = null;
                AssetBase oldAsset  = null;

                if (BlendWithOldTexture)
                {
                    Primitive.TextureEntryFace defaultFace = part.Shape.Textures.DefaultTexture;
                    if (defaultFace != null)
                    {
                        oldAsset = scene.AssetService.Get(defaultFace.TextureID.ToString());

                        if (oldAsset != null)
                        {
                            assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha, scene);
                        }
                    }
                }

                if (assetData == null)
                {
                    assetData = new byte [data.Length];
                    Array.Copy(data, assetData, data.Length);
                }

                AssetBase asset = null;

                if (LastAssetID != UUID.Zero)
                {
                    asset = scene.AssetService.Get(LastAssetID.ToString());
                    if (asset != null)
                    {
                        asset.Description = string.Format("URL image : {0}", Url);
                        asset.Data        = assetData;
                        if ((asset.Flags & AssetFlags.Local) == AssetFlags.Local)
                        {
                            asset.Flags = asset.Flags & ~AssetFlags.Local;
                        }
                        if (((asset.Flags & AssetFlags.Temporary) == AssetFlags.Temporary) != ((Disp & DISP_TEMP) != 0))
                        {
                            if ((Disp & DISP_TEMP) != 0)
                            {
                                asset.Flags |= AssetFlags.Temporary;
                            }
                            else
                            {
                                asset.Flags = asset.Flags & ~AssetFlags.Temporary;
                            }
                        }
                        asset.ID = scene.AssetService.Store(asset);
                    }
                }

                // either we have no LastAssetID or the above failed to retrieve the asset...so...
                if (asset == null)
                {
                    // Create a new asset for user
                    asset = new AssetBase(UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000),
                                          AssetType.Texture,
                                          scene.RegionInfo.RegionID)
                    {
                        Data = assetData, Description = string.Format("URL image : {0}", Url)
                    };
                    if ((Disp & DISP_TEMP) != 0)
                    {
                        asset.Flags = AssetFlags.Temporary;
                    }
                    asset.ID = scene.AssetService.Store(asset);
                }

                IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface <IJ2KDecoder> ();

                if (cacheLayerDecode != null)
                {
                    cacheLayerDecode.Decode(asset.ID, asset.Data);
                    cacheLayerDecode = null;
                    LastAssetID      = asset.ID;
                }

                UUID oldID = UUID.Zero;

                lock (part) {
                    // mostly keep the values from before
                    Primitive.TextureEntry tmptex = part.Shape.Textures;

                    // remove the old asset from the cache
                    oldID = tmptex.DefaultTexture.TextureID;

                    if (Face == ALL_SIDES)
                    {
                        tmptex.DefaultTexture.TextureID = asset.ID;
                    }
                    else
                    {
                        try {
                            Primitive.TextureEntryFace texface = tmptex.CreateFace((uint)Face);
                            texface.TextureID          = asset.ID;
                            tmptex.FaceTextures [Face] = texface;
                        } catch (Exception) {
                            tmptex.DefaultTexture.TextureID = asset.ID;
                        }
                    }

                    // I'm pretty sure we always want to force this to true
                    // I'm pretty sure no one wants to set fullbright true if it wasn't true before.
                    // tmptex.DefaultTexture.Fullbright = true;

                    part.UpdateTexture(tmptex, true);
                }

                if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0))
                {
                    if (oldAsset == null)
                    {
                        oldAsset = scene.AssetService.Get(oldID.ToString());
                    }
                    if (oldAsset != null)
                    {
                        if ((oldAsset.Flags & AssetFlags.Temporary) == AssetFlags.Temporary)
                        {
                            scene.AssetService.Delete(oldID);
                        }
                    }
                }

                if (oldAsset != null)
                {
                    oldAsset.Dispose();
                }
                asset.Dispose();
            }
Пример #30
0
 public void Start(IConfigSource config, IRegistryCore registry)
 {
     if (!m_enabled) return;
     m_assetService = m_registry.RequestModuleInterface<IAssetService>();
     m_gridService = m_registry.RequestModuleInterface<IGridService>();
     m_j2kDecoder = m_registry.RequestModuleInterface<IJ2KDecoder>();
 }
Пример #31
0
            /// <summary>
            /// Called once new texture data has been received for this updater.
            /// </summary>
            /// <param name="data"></param>
            /// <param name="scene"></param>
            /// <param name="isReuseable">True if the data given is reuseable.</param>
            /// <returns>The asset UUID given to the incoming data.</returns>
            public UUID DataReceived(byte[] data, Scene scene)
            {
                SceneObjectPart part = scene.GetSceneObjectPart(PrimID);

                if (part == null || data == null || data.Length <= 1)
                {
                    string msg =
                        String.Format("DynamicTextureModule: Error preparing image using URL {0}", Url);
                    scene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say,
                                  0, part.ParentGroup.RootPart.AbsolutePosition, part.Name, part.UUID, false);

                    return(UUID.Zero);
                }

                byte[]    assetData = null;
                AssetBase oldAsset  = null;

                if (BlendWithOldTexture)
                {
                    Primitive.TextureEntryFace curFace;
                    if (Face == ALL_SIDES)
                    {
                        curFace = part.Shape.Textures.DefaultTexture;
                    }
                    else
                    {
                        try
                        {
                            curFace = part.Shape.Textures.GetFace((uint)Face);
                        }
                        catch
                        {
                            curFace = null;
                        }
                    }
                    if (curFace != null)
                    {
                        oldAsset = scene.AssetService.Get(curFace.TextureID.ToString());

                        if (oldAsset != null)
                        {
                            assetData = BlendTextures(data, oldAsset.Data, FrontAlpha);
                        }
                    }
                }
                else if (FrontAlpha < 255)
                {
                    assetData = BlendTextures(data, null, FrontAlpha);
                }


                if (assetData == null)
                {
                    assetData = new byte[data.Length];
                    Array.Copy(data, assetData, data.Length);
                }

                // Create a new asset for user
                AssetBase asset
                    = new AssetBase(
                          UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000), (sbyte)AssetType.Texture,
                          scene.RegionInfo.RegionID.ToString());

                asset.Data        = assetData;
                asset.Description = String.Format("URL image : {0}", Url);
                if (asset.Description.Length > 128)
                {
                    asset.Description = asset.Description.Substring(0, 128);
                }
                asset.Local     = true;          // dynamic images aren't saved in the assets server
                asset.Temporary = ((Disp & DISP_TEMP) != 0);
                scene.AssetService.Store(asset); // this will only save the asset in the local asset cache

                IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface <IJ2KDecoder>();

                if (cacheLayerDecode != null)
                {
                    if (!cacheLayerDecode.Decode(asset.FullID, asset.Data))
                    {
                        m_log.WarnFormat(
                            "[DYNAMIC TEXTURE MODULE]: Decoding of dynamically generated asset {0} for {1} in {2} failed",
                            asset.ID, part.Name, part.ParentGroup.Scene.Name);
                    }
                }

                UUID oldID = UpdatePart(part, asset.FullID);

                if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0))
                {
                    if (oldAsset == null)
                    {
                        oldAsset = scene.AssetService.Get(oldID.ToString());
                    }

                    if (oldAsset != null)
                    {
                        if (oldAsset.Temporary)
                        {
                            scene.AssetService.Delete(oldID.ToString());
                        }
                    }
                }

                return(asset.FullID);
            }
Пример #32
0
 //Faux destructor
 public void Close()
 {
     
     m_shuttingdown = true;
     m_j2kDecodeModule = null;
     m_assetCache = null;
     m_client = null;
 }
Пример #33
0
        /// <summary>
        /// Builds a composited terrain texture given the region texture
        /// and heightmap settings
        /// </summary>
        /// <param name="terrain">Terrain heightmap</param>
        /// <param name="regionInfo">Region information including terrain texture parameters</param>
        /// <returns>A 256x256 square RGB texture ready for rendering</returns>
        /// <remarks>Based on the algorithm described at http://opensimulator.org/wiki/Terrain_Splatting
        /// Note we create a 256x256 dimension texture even if the actual terrain is larger.
        /// </remarks>

        public static Bitmap Splat(ITerrainChannel terrain, UUID[] textureIDs,
                                   float[] startHeights, float[] heightRanges,
                                   uint regionPositionX, uint regionPositionY,
                                   IAssetService assetService, IJ2KDecoder decoder,
                                   bool textureTerrain, bool averagetextureTerrain,
                                   int twidth, int theight)
        {
            Debug.Assert(textureIDs.Length == 4);
            Debug.Assert(startHeights.Length == 4);
            Debug.Assert(heightRanges.Length == 4);

            Bitmap[] detailTexture = new Bitmap[4];

            byte[] mapColorsRed   = new byte[4];
            byte[] mapColorsGreen = new byte[4];
            byte[] mapColorsBlue  = new byte[4];

            bool usecolors = false;

            if (textureTerrain)
            {
                // Swap empty terrain textureIDs with default IDs
                for (int i = 0; i < textureIDs.Length; i++)
                {
                    if (textureIDs[i] == UUID.Zero)
                    {
                        textureIDs[i] = DEFAULT_TERRAIN_DETAIL[i];
                    }
                }

                #region Texture Fetching

                if (assetService != null)
                {
                    for (int i = 0; i < 4; i++)
                    {
                        AssetBase asset = null;

                        // asset cache indexes are strings
                        string cacheName = "MAP" + textureIDs[i].ToString();

                        // Try to fetch a cached copy of the decoded/resized version of this texture
                        asset = assetService.GetCached(cacheName);
                        if (asset != null)
                        {
                            try
                            {
                                using (System.IO.MemoryStream stream = new System.IO.MemoryStream(asset.Data))
                                    detailTexture[i] = (Bitmap)Image.FromStream(stream);

                                if (detailTexture[i].PixelFormat != PixelFormat.Format24bppRgb ||
                                    detailTexture[i].Width != 16 || detailTexture[i].Height != 16)
                                {
                                    detailTexture[i].Dispose();
                                    detailTexture[i] = null;
                                }
                            }
                            catch (Exception ex)
                            {
                                m_log.Warn("Failed to decode cached terrain patch texture" + textureIDs[i] + "): " + ex.Message);
                            }
                        }

                        if (detailTexture[i] == null)
                        {
                            // Try to fetch the original JPEG2000 texture, resize if needed, and cache as PNG
                            asset = assetService.Get(textureIDs[i].ToString());
                            if (asset != null)
                            {
                                try
                                {
                                    detailTexture[i] = (Bitmap)decoder.DecodeToImage(asset.Data);
                                }
                                catch (Exception ex)
                                {
                                    m_log.Warn("Failed to decode terrain texture " + asset.ID + ": " + ex.Message);
                                }
                            }

                            if (detailTexture[i] != null)
                            {
                                if (detailTexture[i].PixelFormat != PixelFormat.Format24bppRgb ||
                                    detailTexture[i].Width != 16 || detailTexture[i].Height != 16)
                                {
                                    using (Bitmap origBitmap = detailTexture[i])
                                        detailTexture[i] = Util.ResizeImageSolid(origBitmap, 16, 16);
                                }

                                // Save the decoded and resized texture to the cache
                                byte[] data;
                                using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                                {
                                    detailTexture[i].Save(stream, ImageFormat.Png);
                                    data = stream.ToArray();
                                }

                                // Cache a PNG copy of this terrain texture
                                AssetBase newAsset = new AssetBase
                                {
                                    Data        = data,
                                    Description = "PNG",
                                    Flags       = AssetFlags.Collectable,
                                    FullID      = UUID.Zero,
                                    ID          = cacheName,
                                    Local       = true,
                                    Name        = String.Empty,
                                    Temporary   = true,
                                    Type        = (sbyte)AssetType.Unknown
                                };
                                newAsset.Metadata.ContentType = "image/png";
                                assetService.Store(newAsset);
                            }
                        }
                    }
                }

                #endregion Texture Fetching
                if (averagetextureTerrain)
                {
                    for (int t = 0; t < 4; t++)
                    {
                        usecolors = true;
                        if (detailTexture[t] == null)
                        {
                            mapColorsRed[t]   = DEFAULT_TERRAIN_COLOR[t].R;
                            mapColorsGreen[t] = DEFAULT_TERRAIN_COLOR[t].G;
                            mapColorsBlue[t]  = DEFAULT_TERRAIN_COLOR[t].B;
                            continue;
                        }

                        int npixeis = 0;
                        int cR      = 0;
                        int cG      = 0;
                        int cB      = 0;

                        BitmapData bmdata = detailTexture[t].LockBits(new Rectangle(0, 0, 16, 16),
                                                                      ImageLockMode.ReadOnly, detailTexture[t].PixelFormat);

                        npixeis = bmdata.Height * bmdata.Width;
                        int ylen = bmdata.Height * bmdata.Stride;

                        unsafe
                        {
                            for (int y = 0; y < ylen; y += bmdata.Stride)
                            {
                                byte *ptrc = (byte *)bmdata.Scan0 + y;
                                for (int x = 0; x < bmdata.Width; ++x)
                                {
                                    cR += *(ptrc++);
                                    cG += *(ptrc++);
                                    cB += *(ptrc++);
                                }
                            }
                        }
                        detailTexture[t].UnlockBits(bmdata);
                        detailTexture[t].Dispose();

                        mapColorsRed[t]   = (byte)Util.Clamp(cR / npixeis, 0, 255);
                        mapColorsGreen[t] = (byte)Util.Clamp(cG / npixeis, 0, 255);
                        mapColorsBlue[t]  = (byte)Util.Clamp(cB / npixeis, 0, 255);
                    }
                }
                else
                {
                    // Fill in any missing textures with a solid color
                    for (int i = 0; i < 4; i++)
                    {
                        if (detailTexture[i] == null)
                        {
                            m_log.DebugFormat("{0} Missing terrain texture for layer {1}. Filling with solid default color", LogHeader, i);

                            // Create a solid color texture for this layer
                            detailTexture[i] = new Bitmap(16, 16, PixelFormat.Format24bppRgb);
                            using (Graphics gfx = Graphics.FromImage(detailTexture[i]))
                            {
                                using (SolidBrush brush = new SolidBrush(DEFAULT_TERRAIN_COLOR[i]))
                                    gfx.FillRectangle(brush, 0, 0, 16, 16);
                            }
                        }
                        else
                        {
                            if (detailTexture[i].Width != 16 || detailTexture[i].Height != 16)
                            {
                                using (Bitmap origBitmap = detailTexture[i])
                                    detailTexture[i] = Util.ResizeImageSolid(origBitmap, 16, 16);
                            }
                        }
                    }
                }
            }
            else
            {
                usecolors = true;
                for (int t = 0; t < 4; t++)
                {
                    mapColorsRed[t]   = DEFAULT_TERRAIN_COLOR[t].R;
                    mapColorsGreen[t] = DEFAULT_TERRAIN_COLOR[t].G;
                    mapColorsBlue[t]  = DEFAULT_TERRAIN_COLOR[t].B;
                }
            }

            #region Layer Map

            float xFactor = terrain.Width / twidth;
            float yFactor = terrain.Height / theight;

            #endregion Layer Map

            #region Texture Compositing

            Bitmap     output     = new Bitmap(twidth, theight, PixelFormat.Format24bppRgb);
            BitmapData outputData = output.LockBits(new Rectangle(0, 0, twidth, theight), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);

            // Unsafe work as we lock down the source textures for quicker access and access the
            //    pixel data directly
            float invtwitdthMinus1 = 1.0f / (twidth - 1);
            float invtheightMinus1 = 1.0f / (theight - 1);
            int   ty;
            int   tx;
            float pctx;
            float pcty;
            float height;
            float layer;
            float layerDiff;
            int   l0;
            int   l1;
            uint  yglobalpos;

            if (usecolors)
            {
                float a;
                float b;
                unsafe
                {
                    byte *ptrO;
                    for (int y = 0; y < theight; ++y)
                    {
                        pcty       = y * invtheightMinus1;
                        ptrO       = (byte *)outputData.Scan0 + y * outputData.Stride;
                        ty         = (int)(y * yFactor);
                        yglobalpos = (uint)ty + regionPositionY;

                        for (int x = 0; x < twidth; ++x)
                        {
                            tx     = (int)(x * xFactor);
                            pctx   = x * invtwitdthMinus1;
                            height = (float)terrain[tx, ty];
                            layer  = getLayerTex(height, pctx, pcty,
                                                 (uint)tx + regionPositionX, yglobalpos,
                                                 startHeights, heightRanges);

                            // Select two textures
                            l0 = (int)layer;
                            l1 = Math.Min(l0 + 1, 3);

                            layerDiff = layer - l0;

                            a         = mapColorsRed[l0];
                            b         = mapColorsRed[l1];
                            *(ptrO++) = (byte)(a + layerDiff * (b - a));

                            a         = mapColorsGreen[l0];
                            b         = mapColorsGreen[l1];
                            *(ptrO++) = (byte)(a + layerDiff * (b - a));

                            a         = mapColorsBlue[l0];
                            b         = mapColorsBlue[l1];
                            *(ptrO++) = (byte)(a + layerDiff * (b - a));
                        }
                    }
                }
            }
            else
            {
                float aB;
                float aG;
                float aR;
                float bB;
                float bG;
                float bR;

                unsafe
                {
                    // Get handles to all of the texture data arrays
                    BitmapData[] datas = new BitmapData[]
                    {
                        detailTexture[0].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[0].PixelFormat),
                        detailTexture[1].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[1].PixelFormat),
                        detailTexture[2].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[2].PixelFormat),
                        detailTexture[3].LockBits(new Rectangle(0, 0, 16, 16), ImageLockMode.ReadOnly, detailTexture[3].PixelFormat)
                    };

                    byte *ptr;
                    byte *ptrO;
                    for (int y = 0; y < theight; y++)
                    {
                        pcty = y * invtheightMinus1;
                        int ypatch = ((int)(y * yFactor) & 0x0f) * datas[0].Stride;
                        ptrO       = (byte *)outputData.Scan0 + y * outputData.Stride;
                        ty         = (int)(y * yFactor);
                        yglobalpos = (uint)ty + regionPositionY;

                        for (int x = 0; x < twidth; x++)
                        {
                            tx     = (int)(x * xFactor);
                            pctx   = x * invtwitdthMinus1;
                            height = (float)terrain[tx, ty];
                            layer  = getLayerTex(height, pctx, pcty,
                                                 (uint)tx + regionPositionX, yglobalpos,
                                                 startHeights, heightRanges);

                            // Select two textures
                            l0        = (int)layer;
                            layerDiff = layer - l0;

                            int patchOffset = (tx & 0x0f) * 3 + ypatch;

                            ptr = (byte *)datas[l0].Scan0 + patchOffset;
                            aB  = *(ptr++);
                            aG  = *(ptr++);
                            aR  = *(ptr);

                            l1  = Math.Min(l0 + 1, 3);
                            ptr = (byte *)datas[l1].Scan0 + patchOffset;
                            bB  = *(ptr++);
                            bG  = *(ptr++);
                            bR  = *(ptr);


                            // Interpolate between the two selected textures
                            *(ptrO++) = (byte)(aB + layerDiff * (bB - aB));
                            *(ptrO++) = (byte)(aG + layerDiff * (bG - aG));
                            *(ptrO++) = (byte)(aR + layerDiff * (bR - aR));
                        }
                    }

                    for (int i = 0; i < detailTexture.Length; i++)
                    {
                        detailTexture[i].UnlockBits(datas[i]);
                    }
                }

                for (int i = 0; i < detailTexture.Length; i++)
                {
                    if (detailTexture[i] != null)
                    {
                        detailTexture[i].Dispose();
                    }
                }
            }

            output.UnlockBits(outputData);

//output.Save("terr.png",ImageFormat.Png);

            #endregion Texture Compositing

            return(output);
        }
        public static Color4 GetAverageColor(UUID textureID, byte [] j2kData, IScene scene)
        {
            ulong  r      = 0;
            ulong  g      = 0;
            ulong  b      = 0;
            ulong  a      = 0;
            Bitmap bitmap = null;

            try {
                if (j2kData.Length == 0)
                {
                    return(new Color4(1.0f, 0.0f, 1.0f, 1.0f));
                }

                IJ2KDecoder decoder = scene.RequestModuleInterface <IJ2KDecoder> ();
                bitmap = (Bitmap)decoder.DecodeToImage(j2kData);
                if (bitmap == null)
                {
                    return(new Color4(1.0f, 0.0f, 0.5f, 1.0f));
                }

                j2kData = null;
                int width  = bitmap.Width;
                int height = bitmap.Height;

                BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly,
                                                        bitmap.PixelFormat);
                int  pixelBytes = (bitmap.PixelFormat == PixelFormat.Format24bppRgb) ? 3 : 4;
                bool hasAlpha   = (pixelBytes == 4);

                // Sum up the individual channels
                unsafe
                {
                    for (int y = 0; y < height; y++)
                    {
                        byte *row = (byte *)bitmapData.Scan0 + (y * bitmapData.Stride);

                        for (int x = 0; x < width; x++)
                        {
                            b += row [x * pixelBytes + 0];
                            g += row [x * pixelBytes + 1];
                            r += row [x * pixelBytes + 2];
                            if (hasAlpha)
                            {
                                a += row [x * pixelBytes + 3];
                            }
                        }
                    }
                }

                // Get the averages for each channel
                const decimal OO_255      = 1m / 255m;
                decimal       totalPixels = (width * height);

                decimal rm = (r / totalPixels) * OO_255;
                decimal gm = (g / totalPixels) * OO_255;
                decimal bm = (b / totalPixels) * OO_255;
                decimal am;
                if (hasAlpha)
                {
                    am = (a / totalPixels) * OO_255;
                }
                else
                {
                    am = 1m;
                }

                return(new Color4((float)rm, (float)gm, (float)bm, (float)am));
            } catch (Exception ex) {
                MainConsole.Instance.WarnFormat("[WarpTile generator]: Error decoding JPEG2000 texture {0} ({1} bytes): {2}",
                                                textureID,
                                                j2kData.Length, ex.Message);
                return(new Color4(0.5f, 0.5f, 0.5f, 1.0f));
            } finally {
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }
            }
        }
        public void Initialise(IScene scene, IConfigSource config)
        {
            m_scene = scene;
            m_imgDecoder = m_scene.RequestModuleInterface<IJ2KDecoder>();
            m_config = config;
            m_assetCacheDir = m_config.Configs ["AssetCache"].GetString ("CacheDirectory",m_assetCacheDir);

            List<string> renderers = RenderingLoader.ListRenderers(Util.ExecutingDirectory());
            if (renderers.Count > 0)
            {
                m_primMesher = RenderingLoader.LoadRenderer(renderers[0]);
                MainConsole.Instance.Debug("[MAPTILE]: Loaded prim mesher " + m_primMesher);
            }
            else
            {
                MainConsole.Instance.Info("[MAPTILE]: No prim mesher loaded, prim rendering will be disabled");
            }

            var mapConfig = m_config.Configs ["MapModule"];
            if (mapConfig != null)
            {
                m_texturePrimSize = mapConfig.GetFloat ("TexturePrimSize", m_texturePrimSize);
                m_renderMeshes = mapConfig.GetBoolean ("RenderMeshes", m_renderMeshes);
            }

            ReadCacheMap();
        }
Пример #36
0
        private void CreatePrim(WarpRenderer renderer, SceneObjectPart prim,
                                bool useTextures)
        {
            const float MIN_SIZE_SQUARE = 4f;

            if ((PCode)prim.Shape.PCode != PCode.Prim)
            {
                return;
            }
            float primScaleLenSquared = prim.Scale.LengthSquared();

            if (primScaleLenSquared < MIN_SIZE_SQUARE)
            {
                return;
            }

            FacetedMesh renderMesh = null;
            Primitive   omvPrim    = prim.Shape.ToOmvPrimitive(prim.OffsetPosition, prim.RotationOffset);

            if (m_renderMeshes)
            {
                if (omvPrim.Sculpt != null && omvPrim.Sculpt.SculptTexture != UUID.Zero)
                {
                    // Try fetchinng the asset
                    byte[] sculptAsset = m_scene.AssetService.GetData(omvPrim.Sculpt.SculptTexture.ToString());
                    if (sculptAsset != null)
                    {
                        // Is it a mesh?
                        if (omvPrim.Sculpt.Type == SculptType.Mesh)
                        {
                            AssetMesh meshAsset = new AssetMesh(omvPrim.Sculpt.SculptTexture, sculptAsset);
                            FacetedMesh.TryDecodeFromAsset(omvPrim, meshAsset, DetailLevel.Highest, out renderMesh);
                            meshAsset = null;
                        }
                        else // It's sculptie
                        {
                            IJ2KDecoder imgDecoder = m_scene.RequestModuleInterface <IJ2KDecoder>();
                            if (imgDecoder != null)
                            {
                                Image sculpt = imgDecoder.DecodeToImage(sculptAsset);
                                if (sculpt != null)
                                {
                                    renderMesh = m_primMesher.GenerateFacetedSculptMesh(omvPrim, (Bitmap)sculpt,
                                                                                        DetailLevel.Medium);
                                    sculpt.Dispose();
                                }
                            }
                        }
                    }
                }
            }

            // If not a mesh or sculptie, try the regular mesher
            if (renderMesh == null)
            {
                renderMesh = m_primMesher.GenerateFacetedMesh(omvPrim, DetailLevel.Medium);
            }

            if (renderMesh == null)
            {
                return;
            }

            string primID = prim.UUID.ToString();

            // Create the prim faces
            // TODO: Implement the useTextures flag behavior
            for (int i = 0; i < renderMesh.Faces.Count; i++)
            {
                Face   face     = renderMesh.Faces[i];
                string meshName = primID + i.ToString();

                // Avoid adding duplicate meshes to the scene
                if (renderer.Scene.objectData.ContainsKey(meshName))
                {
                    continue;
                }

                warp_Object faceObj = new warp_Object();
                for (int j = 0; j < face.Vertices.Count; j++)
                {
                    Vertex      v    = face.Vertices[j];
                    warp_Vector pos  = ConvertVector(v.Position);
                    warp_Vertex vert = new warp_Vertex(pos, v.TexCoord.X, v.TexCoord.Y);
                    faceObj.addVertex(vert);
                }

                for (int j = 0; j < face.Indices.Count; j += 3)
                {
                    faceObj.addTriangle(
                        face.Indices[j + 0],
                        face.Indices[j + 1],
                        face.Indices[j + 2]);
                }

                Primitive.TextureEntryFace teFace = prim.Shape.Textures.GetFace((uint)i);
                Color4 faceColor    = GetFaceColor(teFace);
                string materialName = String.Empty;
                if (m_texturePrims && primScaleLenSquared > m_texturePrimSize * m_texturePrimSize)
                {
                    materialName = GetOrCreateMaterial(renderer, faceColor, teFace.TextureID);
                }
                else
                {
                    materialName = GetOrCreateMaterial(renderer, faceColor);
                }

                warp_Vector     primPos = ConvertVector(prim.GetWorldPosition());
                warp_Quaternion primRot = ConvertQuaternion(prim.GetWorldRotation());
                warp_Matrix     m       = warp_Matrix.quaternionMatrix(primRot);
                faceObj.transform(m);
                faceObj.setPos(primPos);
                faceObj.scaleSelf(prim.Scale.X, prim.Scale.Z, prim.Scale.Y);

                renderer.Scene.addObject(meshName, faceObj);
                renderer.SetObjectMaterial(meshName, materialName);
            }
        }
Пример #37
0
        Bitmap BuildMapTile(int regionX, int regionY, List <GridRegion> regions)
        {
            if (regions == null)
            {
                int maxRegionSize = m_gridService.GetMaxRegionSize();
                if (maxRegionSize == 0)
                {
                    maxRegionSize = Constants.MaxRegionSize;
                }
                regions = m_gridService.GetRegionRange(
                    null,
                    (regionX * Constants.RegionSize) - maxRegionSize,
                    (regionX * Constants.RegionSize) + maxRegionSize,
                    (regionY * Constants.RegionSize) - maxRegionSize,
                    (regionY * Constants.RegionSize) + maxRegionSize);
            }

            List <Image>      bitImages  = new List <Image>();
            List <GridRegion> badRegions = new List <GridRegion>();
            Rectangle         mapRect    = new Rectangle(regionX * Constants.RegionSize, regionY * Constants.RegionSize, Constants.RegionSize, Constants.RegionSize);

            foreach (GridRegion r in regions)
            {
                Rectangle regionRect = new Rectangle(r.RegionLocX, r.RegionLocY, r.RegionSizeX, r.RegionSizeY);
                if (!mapRect.IntersectsWith(regionRect))
                {
                    badRegions.Add(r);
                }
            }
            foreach (GridRegion r in badRegions)
            {
                regions.Remove(r);
            }
            badRegions.Clear();
            IJ2KDecoder decoder = m_registry.RequestModuleInterface <IJ2KDecoder>();

            foreach (GridRegion r in regions)
            {
                byte[] texAsset = null;
                if (m_assetService.GetExists(r.TerrainMapImage.ToString()))
                {
                    texAsset = m_assetService.GetData(r.TerrainMapImage.ToString());
                }

                if (texAsset != null)
                {
                    Image image = decoder.DecodeToImage(texAsset);
                    if (image != null)
                    {
                        bitImages.Add(image);
                    }
                    else
                    {
                        badRegions.Add(r);
                    }
                }
                else
                {
                    badRegions.Add(r);
                }
            }
            foreach (GridRegion r in badRegions)
            {
                regions.Remove(r);
            }

            if (regions.Count == 0)
            {
                lock (m_blankTiles.BlankTiles)
                    m_blankTiles.BlankTiles.Add(Util.IntsToUlong(regionX, regionY));
                return(m_blankRegionTile);
            }

            const int SizeOfImage = Constants.RegionSize;           // 256

            Bitmap mapTexture = new Bitmap(SizeOfImage, SizeOfImage);

            using (Graphics g = Graphics.FromImage(mapTexture))
            {
                SolidBrush sea = new SolidBrush(Color.FromArgb(29, 71, 95));
                g.FillRectangle(sea, 0, 0, SizeOfImage, SizeOfImage);

                for (int i = 0; i < regions.Count; i++)
                {
                    //Find the offsets first
                    float x = (regions[i].RegionLocX - (regionX * (float)Constants.RegionSize)) /
                              Constants.RegionSize;
                    float y = (regions[i].RegionLocY - (regionY * (float)Constants.RegionSize)) /
                              Constants.RegionSize;
                    y += (regions[i].RegionSizeY - Constants.RegionSize) / Constants.RegionSize;
                    float xx = (x * (SizeOfImage));
                    float yy = SizeOfImage - (y * (SizeOfImage) + (SizeOfImage));
                    g.DrawImage(bitImages[i], xx, yy,
                                (int)(SizeOfImage * ((float)regions[i].RegionSizeX / Constants.RegionSize)),
                                (int)(SizeOfImage * (regions[i].RegionSizeY / (float)Constants.RegionSize))); // y origin is top
                }
            }

            foreach (var bmp in bitImages)
            {
                bmp.Dispose();
            }

            CacheMapTexture(1, regionX, regionY, mapTexture);
            //mapTexture = ResizeBitmap(mapTexture, 128, 128);
            return(mapTexture);
        }
Пример #38
0
        // prims with all dimensions smaller than this will have a bounding box mesh
        public Meshmerizer(IConfigSource config, IRegistryCore registry)
        {
            IConfig start_config = config.Configs["Meshing"];

            decodedSculptMapPath = start_config.GetString("DecodedSculptMapPath", "j2kDecodeCache");
            cacheSculptMaps = start_config.GetBoolean("CacheSculptMaps", cacheSculptMaps);
            UseMeshesPhysicsMesh = start_config.GetBoolean("UseMeshesPhysicsMesh", UseMeshesPhysicsMesh);

            cacheSculptAlphaMaps = Environment.OSVersion.Platform != PlatformID.Unix && cacheSculptMaps;
            m_j2kDecoder = registry.RequestModuleInterface<IJ2KDecoder>();
            try
            {
                if (!Directory.Exists(decodedSculptMapPath))
                    Directory.CreateDirectory(decodedSculptMapPath);
            }
            catch (Exception e)
            {
                MainConsole.Instance.WarnFormat("[SCULPT]: Unable to create {0} directory: ", decodedSculptMapPath,
                                                e.ToString());
            }
        }
Пример #39
0
        public void CacheJ2kDecode(int threads)
        {
            if (threads < 1)
            {
                threads = 1;
            }

            IJ2KDecoder m_decoder = m_localScenes[0].RequestModuleInterface <IJ2KDecoder>();

            List <UUID> assetRequestList = new List <UUID>();

            #region AssetGathering!
            foreach (Scene scene in m_localScenes)
            {
                List <EntityBase> entitles = scene.GetEntities();
                foreach (EntityBase entity in entitles)
                {
                    if (entity is SceneObjectGroup)
                    {
                        SceneObjectGroup sog = (SceneObjectGroup)entity;
                        foreach (SceneObjectPart part in sog.Children.Values)
                        {
                            if (part.Shape != null)
                            {
                                OpenMetaverse.Primitive.TextureEntry te = part.Shape.Textures;
                                if (te.DefaultTexture != null) // this has been null for some reason...
                                {
                                    if (te.DefaultTexture.TextureID != UUID.Zero)
                                    {
                                        assetRequestList.Add(te.DefaultTexture.TextureID);
                                    }
                                }
                                for (int i = 0; i < te.FaceTextures.Length; i++)
                                {
                                    if (te.FaceTextures[i] != null)
                                    {
                                        if (te.FaceTextures[i].TextureID != UUID.Zero)
                                        {
                                            assetRequestList.Add(te.FaceTextures[i].TextureID);
                                        }
                                    }
                                }
                                if (part.Shape.SculptTexture != UUID.Zero)
                                {
                                    assetRequestList.Add(part.Shape.SculptTexture);
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            int entries_per_thread = (assetRequestList.Count / threads) + 1;

            UUID[] arrAssetRequestList = assetRequestList.ToArray();

            List <UUID[]> arrvalus = new List <UUID[]>();

            //split into separate arrays
            for (int j = 0; j < threads; j++)
            {
                List <UUID> val = new List <UUID>();

                for (int k = j * entries_per_thread; k < ((j + 1) * entries_per_thread); k++)
                {
                    if (k < arrAssetRequestList.Length)
                    {
                        val.Add(arrAssetRequestList[k]);
                    }
                }
                arrvalus.Add(val.ToArray());
            }

            for (int l = 0; l < arrvalus.Count; l++)
            {
                DecodeThreadContents threadworkItem = new DecodeThreadContents();
                threadworkItem.sn        = m_localScenes[0];
                threadworkItem.j2kdecode = m_decoder;
                threadworkItem.arrassets = arrvalus[l];

                System.Threading.Thread decodethread =
                    new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(threadworkItem.run));

                threadworkItem.SetThread(decodethread);

                decodethread.Priority = System.Threading.ThreadPriority.Lowest;
                decodethread.Name     = "J2kCacheDecodeThread_" + l + 1;
                ThreadTracker.Add(decodethread);
                decodethread.Start();
            }
        }
Пример #40
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);
                            }
                        }
                    }
                }
            }
        }
            /// <summary>
            /// Called once new texture data has been received for this updater.
            /// </summary>
            public void DataReceived(byte[] data, Scene scene)
            {
                SceneObjectPart part = scene.GetSceneObjectPart(PrimID);

                if (part == null || data == null || data.Length <= 1)
                {
                    string msg =
                        String.Format("DynamicTextureModule: Error preparing image using URL {0}", Url);
                    scene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say,
                                  0, part.ParentGroup.RootPart.AbsolutePosition, part.Name, part.UUID, false);
                    return;
                }

                byte[]    assetData = null;
                AssetBase oldAsset  = null;

                if (BlendWithOldTexture)
                {
                    Primitive.TextureEntryFace defaultFace = part.Shape.Textures.DefaultTexture;
                    if (defaultFace != null)
                    {
                        oldAsset = scene.AssetService.Get(defaultFace.TextureID.ToString());

                        if (oldAsset != null)
                        {
                            assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha);
                        }
                    }
                }

                if (assetData == null)
                {
                    assetData = new byte[data.Length];
                    Array.Copy(data, assetData, data.Length);
                }

                // Create a new asset for user
                AssetBase asset = new AssetBase(UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000), (sbyte)AssetType.Texture,
                                                scene.RegionInfo.RegionID.ToString());

                asset.Data        = assetData;
                asset.Description = String.Format("URL image : {0}", Url);
                asset.Local       = false;
                asset.Temporary   = ((Disp & DISP_TEMP) != 0);
                scene.AssetService.Store(asset);
//                scene.CommsManager.AssetCache.AddAsset(asset);

                IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface <IJ2KDecoder>();

                if (cacheLayerDecode != null)
                {
                    cacheLayerDecode.Decode(asset.FullID, asset.Data);
                    cacheLayerDecode = null;
                    LastAssetID      = asset.FullID;
                }

                UUID oldID = UUID.Zero;

                lock (part)
                {
                    // mostly keep the values from before
                    Primitive.TextureEntry tmptex = part.Shape.Textures;

                    // remove the old asset from the cache
                    oldID = tmptex.DefaultTexture.TextureID;

                    if (Face == ALL_SIDES)
                    {
                        tmptex.DefaultTexture.TextureID = asset.FullID;
                    }
                    else
                    {
                        try
                        {
                            Primitive.TextureEntryFace texface = tmptex.CreateFace((uint)Face);
                            texface.TextureID         = asset.FullID;
                            tmptex.FaceTextures[Face] = texface;
                        }
                        catch (Exception)
                        {
                            tmptex.DefaultTexture.TextureID = asset.FullID;
                        }
                    }

                    // I'm pretty sure we always want to force this to true
                    // I'm pretty sure noone whats to set fullbright true if it wasn't true before.
                    // tmptex.DefaultTexture.Fullbright = true;

                    part.UpdateTexture(tmptex);
                }

                if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0))
                {
                    if (oldAsset == null)
                    {
                        oldAsset = scene.AssetService.Get(oldID.ToString());
                    }
                    if (oldAsset != null)
                    {
                        if (oldAsset.Temporary == true)
                        {
                            scene.AssetService.Delete(oldID.ToString());
                        }
                    }
                }
            }