Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/OgreMain/include/OgreResourceManager.h @ 5

Last change on this file since 5 was 5, checked in by anonymous, 17 years ago

=hoffentlich gehts jetzt

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