Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/ogre_src_v1-9-0/OgreMain/include/OgreResourceManager.h @ 148

Last change on this file since 148 was 148, checked in by patricwi, 6 years ago

Added new dependencies for ogre1.9 and cegui0.8

File size: 25.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-2013 Torus Knot Software Ltd
8
9Permission is hereby granted, free of charge, to any person obtaining a copy
10of this software and associated documentation files (the "Software"), to deal
11in the Software without restriction, including without limitation the rights
12to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13copies of the Software, and to permit persons to whom the Software is
14furnished to do so, subject to the following conditions:
15
16The above copyright notice and this permission notice shall be included in
17all copies or substantial portions of the Software.
18
19THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25THE SOFTWARE.
26-----------------------------------------------------------------------------
27*/
28#ifndef _ResourceManager_H__
29#define _ResourceManager_H__
30
31#include "OgrePrerequisites.h"
32
33#include "OgreResource.h"
34#include "OgreResourceGroupManager.h"
35#include "OgreIteratorWrappers.h"
36#include "OgreCommon.h"
37#include "OgreDataStream.h"
38#include "OgreStringVector.h"
39#include "OgreScriptLoader.h"
40#include "OgreHeaderPrefix.h"
41
42namespace Ogre {
43
44    /** Template class describing a simple pool of items.
45     */
46        template <typename T>
47        class Pool
48        {
49        protected:
50                typedef typename list<T>::type ItemList;
51                ItemList mItems;
52                OGRE_AUTO_MUTEX;
53        public:
54                Pool() {}
55                virtual ~Pool() {}
56
57                /** Get the next item from the pool.
58         @return pair indicating whether there was a free item, and the item if so
59         */
60                virtual std::pair<bool, T> removeItem()
61                {
62            OGRE_LOCK_AUTO_MUTEX;
63                        std::pair<bool, T> ret;
64                        if (mItems.empty())
65                        {
66                                ret.first = false;
67                        }
68                        else
69                        {
70                                ret.first = true;
71                                ret.second = mItems.front();
72                                mItems.pop_front();
73                        }
74                        return ret;
75                }
76
77                /** Add a new item to the pool.
78         */
79                virtual void addItem(const T& i)
80                {
81            OGRE_LOCK_AUTO_MUTEX;
82                        mItems.push_front(i);
83                }
84                /// Clear the pool
85                virtual void clear()
86                {
87            OGRE_LOCK_AUTO_MUTEX;
88                        mItems.clear();
89                }
90        };
91
92        /** \addtogroup Core
93        *  @{
94        */
95        /** \addtogroup Resources
96        *  @{
97        */
98        /** Defines a generic resource handler.
99    @remarks
100        A resource manager is responsible for managing a pool of
101        resources of a particular type. It must index them, look
102        them up, load and destroy them. It may also need to stay within
103        a defined memory budget, and temporarily unload some resources
104        if it needs to to stay within this budget.
105    @par
106        Resource managers use a priority system to determine what can
107        be unloaded, and a Least Recently Used (LRU) policy within
108        resources of the same priority.
109        @par
110                Resources can be loaded using the generalised load interface,
111                and they can be unloaded and removed. In addition, each
112                subclass of ResourceManager will likely define custom 'load' methods
113                which take explicit parameters depending on the kind of resource
114                being created.
115        @note
116                Resources can be loaded and unloaded through the Resource class,
117                but they can only be removed (and thus eventually destroyed) using
118                their parent ResourceManager.
119    @note
120        If OGRE_THREAD_SUPPORT is 1, this class is thread-safe.
121    */
122        class _OgreExport ResourceManager : public ScriptLoader, public ResourceAlloc
123    {
124    public:
125        OGRE_AUTO_MUTEX; // public to allow external locking
126        ResourceManager();
127        virtual ~ResourceManager();
128
129        /** Creates a new blank resource, but does not immediately load it.
130        @remarks
131            Resource managers handle disparate types of resources, so if you want
132                        to get at the detailed interface of this resource, you'll have to
133                        cast the result to the subclass you know you're creating.
134                @param name The unique name of the resource
135                @param group The name of the resource group to attach this new resource to
136                @param isManual Is this resource manually loaded? If so, you should really
137                        populate the loader parameter in order that the load process
138                        can call the loader back when loading is required.
139                @param loader Pointer to a ManualLoader implementation which will be called
140                        when the Resource wishes to load (should be supplied if you set
141                        isManual to true). You can in fact leave this parameter null
142                        if you wish, but the Resource will never be able to reload if
143                        anything ever causes it to unload. Therefore provision of a proper
144                        ManualLoader instance is strongly recommended.
145        @param createParams If any parameters are required to create an instance,
146            they should be supplied here as name / value pairs
147        */
148        virtual ResourcePtr createResource(const String& name, const String& group,
149            bool isManual = false, ManualResourceLoader* loader = 0, 
150            const NameValuePairList* createParams = 0);
151
152                typedef std::pair<ResourcePtr, bool> ResourceCreateOrRetrieveResult;
153                /** Create a new resource, or retrieve an existing one with the same
154                        name if it already exists.
155                @remarks
156                        This method performs the same task as calling getByName() followed
157                        by create() if that returns null. The advantage is that it does it
158                        in one call so there are no race conditions if using multiple
159                        threads that could cause getByName() to return null, but create() to
160                        fail because another thread created a resource in between.
161                @see ResourceManager::createResource
162                @see ResourceManager::getResourceByName
163                @return A pair, the first element being the pointer, and the second being
164                        an indicator specifying whether the resource was newly created.
165                */
166                virtual ResourceCreateOrRetrieveResult createOrRetrieve(const String& name, 
167                        const String& group, bool isManual = false, 
168                        ManualResourceLoader* loader = 0, 
169                        const NameValuePairList* createParams = 0);
170               
171        /** Set a limit on the amount of memory this resource handler may use.
172            @remarks
173                If, when asked to load a new resource, the manager believes it will exceed this memory
174                budget, it will temporarily unload a resource to make room for the new one. This unloading
175                is not permanent and the Resource is not destroyed; it simply needs to be reloaded when
176                next used.
177        */
178        virtual void setMemoryBudget(size_t bytes);
179
180        /** Get the limit on the amount of memory this resource handler may use.
181        */
182        virtual size_t getMemoryBudget(void) const;
183
184                /** Gets the current memory usage, in bytes. */
185                virtual size_t getMemoryUsage(void) const { return mMemoryUsage.get(); }
186
187                /** Unloads a single resource by name.
188                @remarks
189                        Unloaded resources are not removed, they simply free up their memory
190                        as much as they can and wait to be reloaded.
191                        @see ResourceGroupManager for unloading of resource groups.
192                */
193                virtual void unload(const String& name);
194               
195                /** Unloads a single resource by handle.
196                @remarks
197                        Unloaded resources are not removed, they simply free up their memory
198                        as much as they can and wait to be reloaded.
199                        @see ResourceGroupManager for unloading of resource groups.
200                */
201                virtual void unload(ResourceHandle handle);
202
203                /** Unloads all resources.
204                @remarks
205                        Unloaded resources are not removed, they simply free up their memory
206                        as much as they can and wait to be reloaded.
207                        @see ResourceGroupManager for unloading of resource groups.
208                @param reloadableOnly If true (the default), only unload the resource that
209            is reloadable. Because some resources isn't reloadable, they will be
210                        unloaded but can't load them later. Thus, you might not want to them
211                        unloaded. Or, you might unload all of them, and then populate them
212                        manually later.
213                        @see Resource::isReloadable for resource is reloadable.
214                */
215                virtual void unloadAll(bool reloadableOnly = true);
216
217                /** Caused all currently loaded resources to be reloaded.
218                @remarks
219                        All resources currently being held in this manager which are also
220                        marked as currently loaded will be unloaded, then loaded again.
221                @param reloadableOnly If true (the default), only reload the resource that
222            is reloadable. Because some resources isn't reloadable, they will be
223                        unloaded but can't loaded again. Thus, you might not want to them
224                        unloaded. Or, you might unload all of them, and then populate them
225                        manually later.
226                        @see Resource::isReloadable for resource is reloadable.
227                */
228                virtual void reloadAll(bool reloadableOnly = true);
229
230                /** Unload all resources which are not referenced by any other object.
231                @remarks
232                        This method behaves like unloadAll, except that it only unloads resources
233            which are not in use, ie not referenced by other objects. This allows you
234            to free up some memory selectively whilst still keeping the group around
235            (and the resources present, just not using much memory).
236        @par
237            Some referenced resource may exists 'weak' pointer to their sub-components
238            (e.g. Entity held pointer to SubMesh), in this case, unload or reload that
239            resource will cause dangerous pointer access. Use this function instead of
240            unloadAll allows you avoid fail in those situations.
241                @param reloadableOnly If true (the default), only unloads resources
242                        which can be subsequently automatically reloaded.
243                */
244                virtual void unloadUnreferencedResources(bool reloadableOnly = true);
245
246                /** Caused all currently loaded but not referenced by any other object
247            resources to be reloaded.
248                @remarks
249                        This method behaves like reloadAll, except that it only reloads resources
250            which are not in use, i.e. not referenced by other objects.
251        @par
252            Some referenced resource may exists 'weak' pointer to their sub-components
253            (e.g. Entity held pointer to SubMesh), in this case, unload or reload that
254            resource will cause dangerous pointer access. Use this function instead of
255            reloadAll allows you avoid fail in those situations.
256                @param reloadableOnly If true (the default), only reloads resources
257                        which can be subsequently automatically reloaded.
258                */
259                virtual void reloadUnreferencedResources(bool reloadableOnly = true);
260
261                /** Remove a single resource.
262                @remarks
263                        Removes a single resource, meaning it will be removed from the list
264                        of valid resources in this manager, also causing it to be unloaded.
265                @note
266                        The word 'Destroy' is not used here, since
267                        if any other pointers are referring to this resource, it will persist
268                        until they have finished with it; however to all intents and purposes
269                        it no longer exists and will likely get destroyed imminently.
270        @note
271            If you do have shared pointers to resources hanging around after the
272            ResourceManager is destroyed, you may get problems on destruction of
273            these resources if they were relying on the manager (especially if
274            it is a plugin). If you find you get problems on shutdown in the
275            destruction of resources, try making sure you release all your
276            shared pointers before you shutdown OGRE.
277                */
278                virtual void remove(ResourcePtr& r);
279
280        /** Remove a single resource by name.
281                @remarks
282                        Removes a single resource, meaning it will be removed from the list
283                        of valid resources in this manager, also causing it to be unloaded.
284                @note
285                        The word 'Destroy' is not used here, since
286                        if any other pointers are referring to this resource, it will persist
287                        until they have finished with it; however to all intents and purposes
288                        it no longer exists and will likely get destroyed imminently.
289        @note
290            If you do have shared pointers to resources hanging around after the
291            ResourceManager is destroyed, you may get problems on destruction of
292            these resources if they were relying on the manager (especially if
293            it is a plugin). If you find you get problems on shutdown in the
294            destruction of resources, try making sure you release all your
295            shared pointers before you shutdown OGRE.
296                */
297                virtual void remove(const String& name);
298               
299                /** Remove a single resource by handle.
300                @remarks
301                        Removes a single resource, meaning it will be removed from the list
302                        of valid resources in this manager, also causing it to be unloaded.
303                @note
304                        The word 'Destroy' is not used here, since
305                        if any other pointers are referring to this resource, it will persist
306                        until they have finished with it; however to all intents and purposes
307                        it no longer exists and will likely get destroyed imminently.
308        @note
309            If you do have shared pointers to resources hanging around after the
310            ResourceManager is destroyed, you may get problems on destruction of
311            these resources if they were relying on the manager (especially if
312            it is a plugin). If you find you get problems on shutdown in the
313            destruction of resources, try making sure you release all your
314            shared pointers before you shutdown OGRE.
315                */
316                virtual void remove(ResourceHandle handle);
317                /** Removes all resources.
318                @note
319                        The word 'Destroy' is not used here, since
320                        if any other pointers are referring to these resources, they will persist
321                        until they have been finished with; however to all intents and purposes
322                        the resources no longer exist and will get destroyed imminently.
323        @note
324            If you do have shared pointers to resources hanging around after the
325            ResourceManager is destroyed, you may get problems on destruction of
326            these resources if they were relying on the manager (especially if
327            it is a plugin). If you find you get problems on shutdown in the
328            destruction of resources, try making sure you release all your
329            shared pointers before you shutdown OGRE.
330        */
331        virtual void removeAll(void);
332
333                /** Remove all resources which are not referenced by any other object.
334                @remarks
335                        This method behaves like removeAll, except that it only removes resources
336            which are not in use, ie not referenced by other objects. This allows you
337            to free up some memory selectively whilst still keeping the group around
338            (and the resources present, just not using much memory).
339        @par
340            Some referenced resource may exists 'weak' pointer to their sub-components
341            (e.g. Entity held pointer to SubMesh), in this case, remove or reload that
342            resource will cause dangerous pointer access. Use this function instead of
343            removeAll allows you avoid fail in those situations.
344                @param reloadableOnly If true (the default), only removes resources
345                        which can be subsequently automatically reloaded.
346                */
347                virtual void removeUnreferencedResources(bool reloadableOnly = true);
348
349        /** Retrieves a pointer to a resource by name, or null if the resource does not exist.
350        */
351        virtual ResourcePtr getResourceByName(const String& name, const String& groupName = ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME);
352        /** Retrieves a pointer to a resource by handle, or null if the resource does not exist.
353        */
354        virtual ResourcePtr getByHandle(ResourceHandle handle);
355               
356                /// Returns whether the named resource exists in this manager
357                virtual bool resourceExists(const String& name)
358                {
359                        return !getResourceByName(name).isNull();
360                }
361                /// Returns whether a resource with the given handle exists in this manager
362                virtual bool resourceExists(ResourceHandle handle)
363                {
364                        return !getByHandle(handle).isNull();
365                }
366
367                /** Notify this manager that a resource which it manages has been
368                        'touched', i.e. used.
369                */
370                virtual void _notifyResourceTouched(Resource* res);
371
372                /** Notify this manager that a resource which it manages has been
373                        loaded.
374                */
375                virtual void _notifyResourceLoaded(Resource* res);
376
377                /** Notify this manager that a resource which it manages has been
378                        unloaded.
379                */
380                virtual void _notifyResourceUnloaded(Resource* res);
381
382                /** Generic prepare method, used to create a Resource specific to this
383                        ResourceManager without using one of the specialised 'prepare' methods
384                        (containing per-Resource-type parameters).
385                @param name The name of the Resource
386                @param group The resource group to which this resource will belong
387                @param isManual Is the resource to be manually loaded? If so, you should
388                        provide a value for the loader parameter
389                @param loader The manual loader which is to perform the required actions
390                        when this resource is loaded; only applicable when you specify true
391                        for the previous parameter
392        @param loadParams Optional pointer to a list of name/value pairs
393            containing loading parameters for this type of resource.
394                @param backgroundThread Optional boolean which lets the load routine know if it
395                        is being run on the background resource loading thread
396                */
397                virtual ResourcePtr prepare(const String& name, 
398            const String& group, bool isManual = false, 
399                        ManualResourceLoader* loader = 0, const NameValuePairList* loadParams = 0,
400                        bool backgroundThread = false);
401
402                /** Generic load method, used to create a Resource specific to this
403                        ResourceManager without using one of the specialised 'load' methods
404                        (containing per-Resource-type parameters).
405                @param name The name of the Resource
406                @param group The resource group to which this resource will belong
407                @param isManual Is the resource to be manually loaded? If so, you should
408                        provide a value for the loader parameter
409                @param loader The manual loader which is to perform the required actions
410                        when this resource is loaded; only applicable when you specify true
411                        for the previous parameter
412        @param loadParams Optional pointer to a list of name/value pairs
413            containing loading parameters for this type of resource.
414                @param backgroundThread Optional boolean which lets the load routine know if it
415                        is being run on the background resource loading thread
416                */
417                virtual ResourcePtr load(const String& name, 
418            const String& group, bool isManual = false, 
419                        ManualResourceLoader* loader = 0, const NameValuePairList* loadParams = 0,
420                        bool backgroundThread = false);
421
422                /** Gets the file patterns which should be used to find scripts for this
423                        ResourceManager.
424                @remarks
425                        Some resource managers can read script files in order to define
426                        resources ahead of time. These resources are added to the available
427                        list inside the manager, but none are loaded initially. This allows
428                        you to load the items that are used on demand, or to load them all
429                        as a group if you wish (through ResourceGroupManager).
430                @par
431                        This method lets you determine the file pattern which will be used
432                        to identify scripts intended for this manager.
433                @return
434                        A list of file patterns, in the order they should be searched in.
435                @see isScriptingSupported, parseScript
436                */
437                virtual const StringVector& getScriptPatterns(void) const { return mScriptPatterns; }
438
439                /** Parse the definition of a set of resources from a script file.
440                @remarks
441                        Some resource managers can read script files in order to define
442                        resources ahead of time. These resources are added to the available
443                        list inside the manager, but none are loaded initially. This allows
444                        you to load the items that are used on demand, or to load them all
445                        as a group if you wish (through ResourceGroupManager).
446                @param stream Weak reference to a data stream which is the source of the script
447                @param groupName The name of the resource group that resources which are
448                        parsed are to become a member of. If this group is loaded or unloaded,
449                        then the resources discovered in this script will be loaded / unloaded
450                        with it.
451                */
452                virtual void parseScript(DataStreamPtr& stream, const String& groupName)
453                { (void)stream; (void)groupName; }
454
455                /** Gets the relative loading order of resources of this type.
456                @remarks
457                        There are dependencies between some kinds of resource in terms of loading
458                        order, and this value enumerates that. Higher values load later during
459                        bulk loading tasks.
460                */
461                virtual Real getLoadingOrder(void) const { return mLoadOrder; }
462
463                /** Gets a string identifying the type of resource this manager handles. */
464                const String& getResourceType(void) const { return mResourceType; }
465
466        /** Sets whether this manager and its resources habitually produce log output */
467        virtual void setVerbose(bool v) { mVerbose = v; }
468
469        /** Gets whether this manager and its resources habitually produce log output */
470        virtual bool getVerbose(void) { return mVerbose; }
471
472                /** Definition of a pool of resources, which users can use to reuse similar
473                        resources many times without destroying and recreating them.
474                @remarks
475                        This is a simple utility class which allows the reuse of resources
476                        between code which has a changing need for them. For example,
477                */
478                class _OgreExport ResourcePool : public Pool<ResourcePtr>, public ResourceAlloc
479                {
480                protected:
481                        String mName;
482                public:
483                        ResourcePool(const String& name);
484                        ~ResourcePool();
485                        /// Get the name of the pool
486                        const String& getName() const;
487                        void clear();
488                };
489               
490                /// Create a resource pool, or reuse one that already exists
491                ResourcePool* getResourcePool(const String& name);
492                /// Destroy a resource pool
493                void destroyResourcePool(ResourcePool* pool);
494                /// Destroy a resource pool
495                void destroyResourcePool(const String& name);
496                /// destroy all pools
497                void destroyAllResourcePools();
498
499
500
501
502    protected:
503
504        /** Allocates the next handle. */
505        ResourceHandle getNextHandle(void);
506
507                /** Create a new resource instance compatible with this manager (no custom
508                        parameters are populated at this point).
509                @remarks
510                        Subclasses must override this method and create a subclass of Resource.
511                @param name The unique name of the resource
512                @param group The name of the resource group to attach this new resource to
513                @param isManual Is this resource manually loaded? If so, you should really
514                        populate the loader parameter in order that the load process
515                        can call the loader back when loading is required.
516                @param loader Pointer to a ManualLoader implementation which will be called
517                        when the Resource wishes to load (should be supplied if you set
518                        isManual to true). You can in fact leave this parameter null
519                        if you wish, but the Resource will never be able to reload if
520                        anything ever causes it to unload. Therefore provision of a proper
521                        ManualLoader instance is strongly recommended.
522        @param createParams If any parameters are required to create an instance,
523            they should be supplied here as name / value pairs. These do not need
524            to be set on the instance (handled elsewhere), just used if required
525            to differentiate which concrete class is created.
526
527                */
528                virtual Resource* createImpl(const String& name, ResourceHandle handle, 
529                        const String& group, bool isManual, ManualResourceLoader* loader, 
530            const NameValuePairList* createParams) = 0;
531                /** Add a newly created resource to the manager (note weak reference) */
532                virtual void addImpl( ResourcePtr& res );
533                /** Remove a resource from this manager; remove it from the lists. */
534                virtual void removeImpl( ResourcePtr& res );
535                /** Checks memory usage and pages out if required. This is automatically done after a new resource is loaded.
536                */
537                virtual void checkUsage(void);
538
539
540    public:
541                typedef HashMap< String, ResourcePtr > ResourceMap;
542                typedef HashMap< String, ResourceMap > ResourceWithGroupMap;
543                typedef map<ResourceHandle, ResourcePtr>::type ResourceHandleMap;
544    protected:
545        ResourceHandleMap mResourcesByHandle;
546        ResourceMap mResources;
547                ResourceWithGroupMap mResourcesWithGroup;
548        size_t mMemoryBudget; /// In bytes
549        AtomicScalar<ResourceHandle> mNextHandle;
550        AtomicScalar<size_t> mMemoryUsage; /// In bytes
551
552        bool mVerbose;
553
554                // IMPORTANT - all subclasses must populate the fields below
555
556                /// Patterns to use to look for scripts if supported (e.g. *.overlay)
557                StringVector mScriptPatterns; 
558                /// Loading order relative to other managers, higher is later
559                Real mLoadOrder; 
560                /// String identifying the resource type this manager handles
561                String mResourceType; 
562
563    public:
564        typedef MapIterator<ResourceHandleMap> ResourceMapIterator;
565        /** Returns an iterator over all resources in this manager.
566        @note
567            Use of this iterator is NOT thread safe!
568        */
569        ResourceMapIterator getResourceIterator(void) 
570        {
571            return ResourceMapIterator(mResourcesByHandle.begin(), mResourcesByHandle.end());
572        }
573
574        protected:
575                typedef map<String, ResourcePool*>::type ResourcePoolMap;
576                ResourcePoolMap mResourcePoolMap;
577    };
578
579        /** @} */
580        /** @} */
581
582}
583
584#include "OgreHeaderSuffix.h"
585
586#endif
Note: See TracBrowser for help on using the repository browser.