source: GTP/trunk/Lib/Geom/OgreStuff/include/OgreResourceManager.h @ 1809

Revision 1809, 19.3 KB checked in by gumbau, 18 years ago (diff)
RevLine 
[1809]1/*
2-----------------------------------------------------------------------------
3This source file is part of OGRE
4    (Object-oriented Graphics Rendering Engine)
5For the latest info, see http://www.ogre3d.org/
6
7Copyright (c) 2000-2005 The OGRE Team
8Also see acknowledgements in Readme.html
9
10This program is free software; you can redistribute it and/or modify it under
11the terms of the GNU Lesser General Public License as published by the Free Software
12Foundation; either version 2 of the License, or (at your option) any later
13version.
14
15This program is distributed in the hope that it will be useful, but WITHOUT
16ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
18
19You should have received a copy of the GNU Lesser General Public License along with
20this program; if not, write to the Free Software Foundation, Inc., 59 Temple
21Place - Suite 330, Boston, MA 02111-1307, USA, or go to
22http://www.gnu.org/copyleft/lesser.txt.
23-----------------------------------------------------------------------------
24*/
25#ifndef _ResourceManager_H__
26#define _ResourceManager_H__
27
28#include "OgrePrerequisites.h"
29
30#include "OgreResource.h"
31#include "OgreResourceGroupManager.h"
32#include "OgreIteratorWrappers.h"
33#include "OgreCommon.h"
34#include "OgreDataStream.h"
35#include "OgreStringVector.h"
36#include "OgreScriptLoader.h"
37
38namespace Ogre {
39
40    /** Defines a generic resource handler.
41    @remarks
42        A resource manager is responsible for managing a pool of
43        resources of a particular type. It must index them, look
44        them up, load and destroy them. It may also need to stay within
45        a defined memory budget, and temporaily unload some resources
46        if it needs to to stay within this budget.
47    @par
48        Resource managers use a priority system to determine what can
49        be unloaded, and a Least Recently Used (LRU) policy within
50        resources of the same priority.
51        @par
52                Resources can be loaded using the generalised load interface,
53                and they can be unloaded and removed. In addition, each
54                subclass of ResourceManager will likely define custom 'load' methods
55                which take explicit parameters depending on the kind of resource
56                being created.
57        @note
58                Resources can be loaded and unloaded through the Resource class,
59                but they can only be removed (and thus eventually destroyed) using
60                their parent ResourceManager.
61    @note
62        If OGRE_THREAD_SUPPORT is 1, this class is thread-safe.
63    */
64        class _OgreExport ResourceManager : public ScriptLoader
65    {
66    public:
67                OGRE_AUTO_MUTEX // public to allow external locking
68        ResourceManager();
69        virtual ~ResourceManager();
70
71        /** Creates a new blank resource, but does not immediately load it.
72        @remarks
73            Resource managers handle disparate types of resources, so if you want
74                        to get at the detailed interface of this resource, you'll have to
75                        cast the result to the subclass you know you're creating.
76                @param name The unique name of the resource
77                @param group The name of the resource group to attach this new resource to
78                @param isManual Is this resource manually loaded? If so, you should really
79                        populate the loader parameter in order that the load process
80                        can call the loader back when loading is required.
81                @param loader Pointer to a ManualLoader implementation which will be called
82                        when the Resource wishes to load (should be supplied if you set
83                        isManual to true). You can in fact leave this parameter null
84                        if you wish, but the Resource will never be able to reload if
85                        anything ever causes it to unload. Therefore provision of a proper
86                        ManualLoader instance is strongly recommended.
87        @param createParams If any parameters are required to create an instance,
88            they should be supplied here as name / value pairs
89        */
90        virtual ResourcePtr create(const String& name, const String& group,
91            bool isManual = false, ManualResourceLoader* loader = 0,
92            const NameValuePairList* createParams = 0);
93        /** Set a limit on the amount of memory this resource handler may use.
94            @remarks
95                If, when asked to load a new resource, the manager believes it will exceed this memory
96                budget, it will temporarily unload a resource to make room for the new one. This unloading
97                is not permanent and the Resource is not destroyed; it simply needs to be reloaded when
98                next used.
99        */
100        virtual void setMemoryBudget( size_t bytes);
101
102        /** Get the limit on the amount of memory this resource handler may use.
103        */
104        virtual size_t getMemoryBudget(void) const;
105
106                /** Unloads a single resource by name.
107                @remarks
108                        Unloaded resources are not removed, they simply free up their memory
109                        as much as they can and wait to be reloaded.
110                        @see ResourceGroupManager for unloading of resource groups.
111                */
112                virtual void unload(const String& name);
113               
114                /** Unloads a single resource by handle.
115                @remarks
116                        Unloaded resources are not removed, they simply free up their memory
117                        as much as they can and wait to be reloaded.
118                        @see ResourceGroupManager for unloading of resource groups.
119                */
120                virtual void unload(ResourceHandle handle);
121
122                /** Unloads all resources.
123                @remarks
124                        Unloaded resources are not removed, they simply free up their memory
125                        as much as they can and wait to be reloaded.
126                        @see ResourceGroupManager for unloading of resource groups.
127                @param reloadableOnly If true (the default), only unload the resource that
128            is reloadable. Because some resources isn't reloadable, they will be
129                        unloaded but can't load them later. Thus, you might not want to them
130                        unloaded. Or, you might unload all of them, and then populate them
131                        manually later.
132                        @see Resource::isReloadable for resource is reloadable.
133                */
134                virtual void unloadAll(bool reloadableOnly = true);
135
136                /** Caused all currently loaded resources to be reloaded.
137                @remarks
138                        All resources currently being held in this manager which are also
139                        marked as currently loaded will be unloaded, then loaded again.
140                @param reloadableOnly If true (the default), only reload the resource that
141            is reloadable. Because some resources isn't reloadable, they will be
142                        unloaded but can't loaded again. Thus, you might not want to them
143                        unloaded. Or, you might unload all of them, and then populate them
144                        manually later.
145                        @see Resource::isReloadable for resource is reloadable.
146                */
147                virtual void reloadAll(bool reloadableOnly = true);
148
149                /** Unload all resources which are not referenced by any other object.
150                @remarks
151                        This method behaves like unloadAll, except that it only unloads resources
152            which are not in use, ie not referenced by other objects. This allows you
153            to free up some memory selectively whilst still keeping the group around
154            (and the resources present, just not using much memory).
155        @par
156            Some referenced resource may exists 'weak' pointer to their sub-components
157            (e.g. Entity held pointer to SubMesh), in this case, unload or reload that
158            resource will cause dangerous pointer access. Use this function instead of
159            unloadAll allows you avoid fail in those situations.
160                @param reloadableOnly If true (the default), only unloads resources
161                        which can be subsequently automatically reloaded.
162                */
163                virtual void unloadUnreferencedResources(bool reloadableOnly = true);
164
165                /** Caused all currently loaded but not referenced by any other object
166            resources to be reloaded.
167                @remarks
168                        This method behaves like reloadAll, except that it only reloads resources
169            which are not in use, ie not referenced by other objects.
170        @par
171            Some referenced resource may exists 'weak' pointer to their sub-components
172            (e.g. Entity held pointer to SubMesh), in this case, unload or reload that
173            resource will cause dangerous pointer access. Use this function instead of
174            reloadAll allows you avoid fail in those situations.
175                @param reloadableOnly If true (the default), only reloads resources
176                        which can be subsequently automatically reloaded.
177                */
178                virtual void reloadUnreferencedResources(bool reloadableOnly = true);
179
180                /** Remove a single resource.
181                @remarks
182                        Removes a single resource, meaning it will be removed from the list
183                        of valid resources in this manager, also causing it to be unloaded.
184                @note
185                        The word 'Destroy' is not used here, since
186                        if any other pointers are referring to this resource, it will persist
187                        until they have finished with it; however to all intents and purposes
188                        it no longer exists and will likely get destroyed imminently.
189        @note
190            If you do have shared pointers to resources hanging around after the
191            ResourceManager is destroyed, you may get problems on destruction of
192            these resources if they were relying on the manager (especially if
193            it is a plugin). If you find you get problems on shutdown in the
194            destruction of resources, try making sure you release all your
195            shared pointers before you shutdown OGRE.
196                */
197                virtual void remove(ResourcePtr& r);
198
199        /** Remove a single resource by name.
200                @remarks
201                        Removes a single resource, meaning it will be removed from the list
202                        of valid resources in this manager, also causing it to be unloaded.
203                @note
204                        The word 'Destroy' is not used here, since
205                        if any other pointers are referring to this resource, it will persist
206                        until they have finished with it; however to all intents and purposes
207                        it no longer exists and will likely get destroyed imminently.
208        @note
209            If you do have shared pointers to resources hanging around after the
210            ResourceManager is destroyed, you may get problems on destruction of
211            these resources if they were relying on the manager (especially if
212            it is a plugin). If you find you get problems on shutdown in the
213            destruction of resources, try making sure you release all your
214            shared pointers before you shutdown OGRE.
215                */
216                virtual void remove(const String& name);
217               
218                /** Remove a single resource by handle.
219                @remarks
220                        Removes a single resource, meaning it will be removed from the list
221                        of valid resources in this manager, also causing it to be unloaded.
222                @note
223                        The word 'Destroy' is not used here, since
224                        if any other pointers are referring to this resource, it will persist
225                        until they have finished with it; however to all intents and purposes
226                        it no longer exists and will likely get destroyed imminently.
227        @note
228            If you do have shared pointers to resources hanging around after the
229            ResourceManager is destroyed, you may get problems on destruction of
230            these resources if they were relying on the manager (especially if
231            it is a plugin). If you find you get problems on shutdown in the
232            destruction of resources, try making sure you release all your
233            shared pointers before you shutdown OGRE.
234                */
235                virtual void remove(ResourceHandle handle);
236                /** Removes all resources.
237                @note
238                        The word 'Destroy' is not used here, since
239                        if any other pointers are referring to these resources, they will persist
240                        until they have been finished with; however to all intents and purposes
241                        the resources no longer exist and will get destroyed imminently.
242        @note
243            If you do have shared pointers to resources hanging around after the
244            ResourceManager is destroyed, you may get problems on destruction of
245            these resources if they were relying on the manager (especially if
246            it is a plugin). If you find you get problems on shutdown in the
247            destruction of resources, try making sure you release all your
248            shared pointers before you shutdown OGRE.
249        */
250        virtual void removeAll(void);
251
252        /** Retrieves a pointer to a resource by name, or null if the resource does not exist.
253        */
254        virtual ResourcePtr getByName(const String& name);
255        /** Retrieves a pointer to a resource by handle, or null if the resource does not exist.
256        */
257        virtual ResourcePtr getByHandle(ResourceHandle handle);
258               
259                /// Returns whether the named resource exists in this manager
260                virtual bool resourceExists(const String& name)
261                {
262                        return !getByName(name).isNull();
263                }
264                /// Returns whether a resource with the given handle exists in this manager
265                virtual bool resourceExists(ResourceHandle handle)
266                {
267                        return !getByHandle(handle).isNull();
268                }
269
270                /** Notify this manager that a resource which it manages has been
271                        'touched', ie used.
272                */
273                virtual void _notifyResourceTouched(Resource* res);
274
275                /** Notify this manager that a resource which it manages has been
276                        loaded.
277                */
278                virtual void _notifyResourceLoaded(Resource* res);
279
280                /** Notify this manager that a resource which it manages has been
281                        unloaded.
282                */
283                virtual void _notifyResourceUnloaded(Resource* res);
284
285                /** Generic load method, used to create a Resource specific to this
286                        ResourceManager without using one of the specialised 'load' methods
287                        (containing per-Resource-type parameters).
288                @param name The name of the Resource
289                @param group The resource group to which this resource will belong
290                @param isManual Is the resource to be manually loaded? If so, you should
291                        provide a value for the loader parameter
292                @param loader The manual loader which is to perform the required actions
293                        when this resource is loaded; only applicable when you specify true
294                        for the previous parameter
295        @param loadParams Optional pointer to a list of name/value pairs
296            containing loading parameters for this type of resource.
297                */
298                virtual ResourcePtr load(const String& name,
299            const String& group, bool isManual = false,
300                        ManualResourceLoader* loader = 0, const NameValuePairList* loadParams = 0);
301
302                /** Gets the file patterns which should be used to find scripts for this
303                        ResourceManager.
304                @remarks
305                        Some resource managers can read script files in order to define
306                        resources ahead of time. These resources are added to the available
307                        list inside the manager, but none are loaded initially. This allows
308                        you to load the items that are used on demand, or to load them all
309                        as a group if you wish (through ResourceGroupManager).
310                @par
311                        This method lets you determine the file pattern which will be used
312                        to identify scripts intended for this manager.
313                @returns
314                        A list of file patterns, in the order they should be searched in.
315                @see isScriptingSupported, parseScript
316                */
317                virtual const StringVector& getScriptPatterns(void) const { return mScriptPatterns; }
318
319                /** Parse the definition of a set of resources from a script file.
320                @remarks
321                        Some resource managers can read script files in order to define
322                        resources ahead of time. These resources are added to the available
323                        list inside the manager, but none are loaded initially. This allows
324                        you to load the items that are used on demand, or to load them all
325                        as a group if you wish (through ResourceGroupManager).
326                @param stream Weak reference to a data stream which is the source of the script
327                @param groupName The name of the resource group that resources which are
328                        parsed are to become a member of. If this group is loaded or unloaded,
329                        then the resources discovered in this script will be loaded / unloaded
330                        with it.
331                */
332                virtual void parseScript(DataStreamPtr& stream, const String& groupName) {}
333
334                /** Gets the relative loading order of resources of this type.
335                @remarks
336                        There are dependencies between some kinds of resource in terms of loading
337                        order, and this value enumerates that. Higher values load later during
338                        bulk loading tasks.
339                */
340                virtual Real getLoadingOrder(void) const { return mLoadOrder; }
341
342                /** Gets a string identifying the type of resource this manager handles. */
343                const String& getResourceType(void) const { return mResourceType; }
344
345    protected:
346
347        /** Allocates the next handle. */
348        ResourceHandle getNextHandle(void);
349
350                /** Create a new resource instance compatible with this manager (no custom
351                        parameters are populated at this point).
352                @remarks
353                        Subclasses must override this method and create a subclass of Resource.
354                @param name The unique name of the resource
355                @param group The name of the resource group to attach this new resource to
356                @param isManual Is this resource manually loaded? If so, you should really
357                        populate the loader parameter in order that the load process
358                        can call the loader back when loading is required.
359                @param loader Pointer to a ManualLoader implementation which will be called
360                        when the Resource wishes to load (should be supplied if you set
361                        isManual to true). You can in fact leave this parameter null
362                        if you wish, but the Resource will never be able to reload if
363                        anything ever causes it to unload. Therefore provision of a proper
364                        ManualLoader instance is strongly recommended.
365        @param createParams If any parameters are required to create an instance,
366            they should be supplied here as name / value pairs. These do not need
367            to be set on the instance (handled elsewhere), just used if required
368            to differentiate which concrete class is created.
369
370                */
371                virtual Resource* createImpl(const String& name, ResourceHandle handle,
372                        const String& group, bool isManual, ManualResourceLoader* loader,
373            const NameValuePairList* createParams) = 0;
374                /** Add a newly created resource to the manager (note weak reference) */
375                virtual void addImpl( ResourcePtr& res );
376                /** Remove a resource from this manager; remove it from the lists. */
377                virtual void removeImpl( ResourcePtr& res );
378                /** Checks memory usage and pages out if required.
379                */
380                virtual void checkUsage(void);
381                /** Gets the current memory usage, in bytes. */
382                virtual size_t getMemoryUsage(void) const { return mMemoryUsage; }
383
384
385    public:
386                typedef HashMap< String, ResourcePtr > ResourceMap;
387                typedef std::map<ResourceHandle, ResourcePtr> ResourceHandleMap;
388    protected:
389        ResourceHandleMap mResourcesByHandle;
390        ResourceMap mResources;
391        ResourceHandle mNextHandle;
392        size_t mMemoryBudget; // In bytes
393        size_t mMemoryUsage; // In bytes
394
395                // IMPORTANT - all subclasses must populate the fields below
396
397                /// Patterns to use to look for scripts if supported (e.g. *.overlay)
398                StringVector mScriptPatterns;
399                /// Loading order relative to other managers, higher is later
400                Real mLoadOrder;
401                /// String identifying the resource type this manager handles
402                String mResourceType;
403
404    public:
405        typedef MapIterator<ResourceHandleMap> ResourceMapIterator;
406        /** Returns an iterator over all resources in this manager.
407        @note
408            Use of this iterator is NOT thread safe!
409        */
410        ResourceMapIterator getResourceIterator(void)
411        {
412            return ResourceMapIterator(mResourcesByHandle.begin(), mResourcesByHandle.end());
413        }
414
415   
416
417    };
418
419}
420
421#endif
Note: See TracBrowser for help on using the repository browser.