Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/ogre_src_v1-9-0/OgreMain/include/OgreResource.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: 20.8 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 _Resource_H__
29#define _Resource_H__
30
31#include "OgrePrerequisites.h"
32#include "OgreString.h"
33#include "OgreSharedPtr.h"
34#include "OgreStringInterface.h"
35#include "OgreAtomicScalar.h"
36#include "Threading/OgreThreadHeaders.h"
37#include "OgreHeaderPrefix.h"
38
39namespace Ogre {
40
41    typedef unsigned long long int ResourceHandle;
42
43
44        // Forward declaration
45        class ManualResourceLoader;
46
47        /** \addtogroup Core
48        *  @{
49        */
50        /** \addtogroup Resources
51        *  @{
52        */
53        /** Abstract class representing a loadable resource (e.g. textures, sounds etc)
54        @remarks
55            Resources are data objects that must be loaded and managed throughout
56                        an application. A resource might be a mesh, a texture, or any other
57                        piece of data - the key thing is that they must be identified by
58                        a name which is unique, must be loaded only once,
59                        must be managed efficiently in terms of retrieval, and they may
60                        also be unloadable to free memory up when they have not been used for
61                        a while and the memory budget is under stress.
62                @par
63                        All Resource instances must be a member of a resource group; see
64                        ResourceGroupManager for full details.
65        @par
66            Subclasses must implement:
67                        <ol>
68                        <li>A constructor, overriding the same parameters as the constructor
69                            defined by this class. Subclasses are not allowed to define
70                                constructors with other parameters; other settings must be
71                                settable through accessor methods before loading.</li>
72            <li>The loadImpl() and unloadImpl() methods - mSize must be set
73                                after loadImpl()</li>
74                        <li>StringInterface ParamCommand and ParamDictionary setups
75                            in order to allow setting of core parameters (prior to load)
76                                through a generic interface.</li>
77                        </ol>
78    */
79        class _OgreExport Resource : public StringInterface, public ResourceAlloc
80    {
81        public:
82        OGRE_AUTO_MUTEX; // public to allow external locking
83                class Listener
84                {
85                public:
86                        Listener() {}
87                        virtual ~Listener() {}
88
89                        /** Callback to indicate that background loading has completed.
90                        @deprecated
91                                Use loadingComplete instead.
92                        */
93                        OGRE_DEPRECATED virtual void backgroundLoadingComplete(Resource*) {}
94
95                        /** Callback to indicate that background preparing has completed.
96                        @deprecated
97                                Use preparingComplete instead.
98                        */
99                        OGRE_DEPRECATED virtual void backgroundPreparingComplete(Resource*) {}
100
101                        /** Called whenever the resource finishes loading.
102                        @remarks
103                                If a Resource has been marked as background loaded (@see Resource::setBackgroundLoaded),
104                                the call does not itself occur in the thread which is doing the loading;
105                                when loading is complete a response indicator is placed with the
106                                ResourceGroupManager, which will then be sent back to the
107                                listener as part of the application's primary frame loop thread.
108                        */
109                        virtual void loadingComplete(Resource*) {}
110
111
112                        /** Called whenever the resource finishes preparing (paging into memory).
113                        @remarks
114                                If a Resource has been marked as background loaded (@see Resource::setBackgroundLoaded)
115                                the call does not itself occur in the thread which is doing the preparing;
116                                when preparing is complete a response indicator is placed with the
117                                ResourceGroupManager, which will then be sent back to the
118                                listener as part of the application's primary frame loop thread.
119                        */
120                        virtual void preparingComplete(Resource*) {}
121
122                        /** Called whenever the resource has been unloaded. */
123                        virtual void unloadingComplete(Resource*) {}
124                };
125               
126                /// Enum identifying the loading state of the resource
127                enum LoadingState
128                {
129            /// Not loaded
130            LOADSTATE_UNLOADED,
131            /// Loading is in progress
132            LOADSTATE_LOADING,
133            /// Fully loaded
134            LOADSTATE_LOADED,
135            /// Currently unloading
136            LOADSTATE_UNLOADING,
137            /// Fully prepared
138            LOADSTATE_PREPARED,
139            /// Preparing is in progress
140            LOADSTATE_PREPARING
141                };
142    protected:
143                /// Creator
144                ResourceManager* mCreator;
145                /// Unique name of the resource
146        String mName;
147                /// The name of the resource group
148                String mGroup;
149                /// Numeric handle for more efficient look up than name
150        ResourceHandle mHandle;
151                /// Is the resource currently loaded?
152        AtomicScalar<LoadingState> mLoadingState;
153                /// Is this resource going to be background loaded? Only applicable for multithreaded
154                volatile bool mIsBackgroundLoaded;
155                /// The size of the resource in bytes
156        size_t mSize;
157                /// Is this file manually loaded?
158                bool mIsManual;
159                /// Origin of this resource (e.g. script name) - optional
160                String mOrigin;
161                /// Optional manual loader; if provided, data is loaded from here instead of a file
162                ManualResourceLoader* mLoader;
163                /// State count, the number of times this resource has changed state
164                size_t mStateCount;
165
166                typedef set<Listener*>::type ListenerList;
167                ListenerList mListenerList;
168                OGRE_MUTEX(mListenerListMutex);
169
170                /** Protected unnamed constructor to prevent default construction.
171                */
172                Resource() 
173                        : mCreator(0), mHandle(0), mLoadingState(LOADSTATE_UNLOADED), 
174                        mIsBackgroundLoaded(false),     mSize(0), mIsManual(0), mLoader(0)
175                { 
176                }
177
178                /** Internal hook to perform actions before the load process, but
179                        after the resource has been marked as 'loading'.
180                @note Mutex will have already been acquired by the loading thread.
181                        Also, this call will occur even when using a ManualResourceLoader
182                        (when loadImpl is not actually called)
183                */
184                virtual void preLoadImpl(void) {}
185                /** Internal hook to perform actions after the load process, but
186                        before the resource has been marked as fully loaded.
187                @note Mutex will have already been acquired by the loading thread.
188                        Also, this call will occur even when using a ManualResourceLoader
189                        (when loadImpl is not actually called)
190                */
191                virtual void postLoadImpl(void) {}
192
193                /** Internal hook to perform actions before the unload process.
194                @note Mutex will have already been acquired by the unloading thread.
195                */
196                virtual void preUnloadImpl(void) {}
197                /** Internal hook to perform actions after the unload process, but
198                before the resource has been marked as fully unloaded.
199                @note Mutex will have already been acquired by the unloading thread.
200                */
201                virtual void postUnloadImpl(void) {}
202
203        /** Internal implementation of the meat of the 'prepare' action.
204        */
205        virtual void prepareImpl(void) {}
206        /** Internal function for undoing the 'prepare' action.  Called when
207            the load is completed, and when resources are unloaded when they
208            are prepared but not yet loaded.
209        */
210        virtual void unprepareImpl(void) {}
211                /** Internal implementation of the meat of the 'load' action, only called if this
212                        resource is not being loaded from a ManualResourceLoader.
213                */
214                virtual void loadImpl(void) = 0;
215                /** Internal implementation of the 'unload' action; called regardless of
216                        whether this resource is being loaded from a ManualResourceLoader.
217                */
218                virtual void unloadImpl(void) = 0;
219
220    public:
221                /** Standard constructor.
222                @param creator Pointer to the ResourceManager that is creating this resource
223                @param name The unique name of the resource
224                @param group The name of the resource group to which this resource belongs
225                @param isManual Is this resource manually loaded? If so, you should really
226                        populate the loader parameter in order that the load process
227                        can call the loader back when loading is required.
228                @param loader Pointer to a ManualResourceLoader implementation which will be called
229                        when the Resource wishes to load (should be supplied if you set
230                        isManual to true). You can in fact leave this parameter null
231                        if you wish, but the Resource will never be able to reload if
232                        anything ever causes it to unload. Therefore provision of a proper
233                        ManualResourceLoader instance is strongly recommended.
234                */
235                Resource(ResourceManager* creator, const String& name, ResourceHandle handle,
236                        const String& group, bool isManual = false, ManualResourceLoader* loader = 0);
237
238        /** Virtual destructor. Shouldn't need to be overloaded, as the resource
239            deallocation code should reside in unload()
240            @see
241                Resource::unload()
242        */
243        virtual ~Resource();
244
245        /** Prepares the resource for load, if it is not already.  One can call prepare()
246            before load(), but this is not required as load() will call prepare()
247            itself, if needed.  When OGRE_THREAD_SUPPORT==1 both load() and prepare()
248            are thread-safe.  When OGRE_THREAD_SUPPORT==2 however, only prepare()
249            is thread-safe.  The reason for this function is to allow a background
250            thread to do some of the loading work, without requiring the whole render
251            system to be thread-safe.  The background thread would call
252            prepare() while the main render loop would later call load().  So long as
253            prepare() remains thread-safe, subclasses can arbitrarily split the work of
254            loading a resource between load() and prepare().  It is best to try and
255            do as much work in prepare(), however, since this will leave less work for
256            the main render thread to do and thus increase FPS.
257                        @param backgroundThread Whether this is occurring in a background thread
258        */
259        virtual void prepare(bool backgroundThread = false);
260
261     /** Loads the resource, if it is not already.
262                @remarks
263                        If the resource is loaded from a file, loading is automatic. If not,
264                        if for example this resource gained it's data from procedural calls
265                        rather than loading from a file, then this resource will not reload
266                        on it's own.
267                @param backgroundThread Indicates whether the caller of this method is
268                        the background resource loading thread.
269                       
270        */
271        virtual void load(bool backgroundThread = false);
272
273                /** Reloads the resource, if it is already loaded.
274                @remarks
275                        Calls unload() and then load() again, if the resource is already
276                        loaded. If it is not loaded already, then nothing happens.
277                */
278                virtual void reload(void);
279
280        /** Returns true if the Resource is reloadable, false otherwise.
281        */
282        virtual bool isReloadable(void) const
283        {
284            return !mIsManual || mLoader;
285        }
286
287        /** Is this resource manually loaded?
288                */
289                virtual bool isManuallyLoaded(void) const
290                {
291                        return mIsManual;
292                }
293
294                /** Unloads the resource; this is not permanent, the resource can be
295                        reloaded later if required.
296        */
297                virtual void unload(void);
298
299        /** Retrieves info about the size of the resource.
300        */
301        virtual size_t getSize(void) const
302        { 
303            return mSize; 
304        }
305
306        /** 'Touches' the resource to indicate it has been used.
307        */
308        virtual void touch(void);
309
310        /** Gets resource name.
311        */
312        virtual const String& getName(void) const 
313        { 
314            return mName; 
315        }
316
317        virtual ResourceHandle getHandle(void) const
318        {
319            return mHandle;
320        }
321
322        /** Returns true if the Resource has been prepared, false otherwise.
323        */
324        virtual bool isPrepared(void) const 
325        { 
326                        // No lock required to read this state since no modify
327            return (mLoadingState.get() == LOADSTATE_PREPARED); 
328        }
329
330        /** Returns true if the Resource has been loaded, false otherwise.
331        */
332        virtual bool isLoaded(void) const 
333        { 
334                        // No lock required to read this state since no modify
335            return (mLoadingState.get() == LOADSTATE_LOADED); 
336        }
337
338                /** Returns whether the resource is currently in the process of
339                        background loading.
340                */
341                virtual bool isLoading() const
342                {
343                        return (mLoadingState.get() == LOADSTATE_LOADING);
344                }
345
346                /** Returns the current loading state.
347                */
348                virtual LoadingState getLoadingState() const
349                {
350                        return mLoadingState.get();
351                }
352
353
354
355                /** Returns whether this Resource has been earmarked for background loading.
356                @remarks
357                        This option only makes sense when you have built Ogre with
358                        thread support (OGRE_THREAD_SUPPORT). If a resource has been marked
359                        for background loading, then it won't load on demand like normal
360                        when load() is called. Instead, it will ignore request to load()
361                        except if the caller indicates it is the background loader. Any
362                        other users of this resource should check isLoaded(), and if that
363                        returns false, don't use the resource and come back later.
364                */
365                virtual bool isBackgroundLoaded(void) const { return mIsBackgroundLoaded; }
366
367                /** Tells the resource whether it is background loaded or not.
368
369         @see Resource::isBackgroundLoaded. Note that calling this only
370                        defers the normal on-demand loading behaviour of a resource, it
371                        does not actually set up a thread to make sure the resource gets
372                        loaded in the background. You should use ResourceBackgroundLoadingQueue
373                        to manage the actual loading (which will call this method itself).
374                */
375                virtual void setBackgroundLoaded(bool bl) { mIsBackgroundLoaded = bl; }
376
377                /** Escalates the loading of a background loaded resource.
378                @remarks
379                        If a resource is set to load in the background, but something needs
380                        it before it's been loaded, there could be a problem. If the user
381                        of this resource really can't wait, they can escalate the loading
382                        which basically pulls the loading into the current thread immediately.
383                        If the resource is already being loaded but just hasn't quite finished
384                        then this method will simply wait until the background load is complete.
385                */
386                virtual void escalateLoading();
387
388                /** Register a listener on this resource.
389                        @see Resource::Listener
390                */
391                virtual void addListener(Listener* lis);
392
393                /** Remove a listener on this resource.
394                        @see Resource::Listener
395                */
396                virtual void removeListener(Listener* lis);
397
398                /// Gets the group which this resource is a member of
399                virtual const String& getGroup(void) const { return mGroup; }
400
401                /** Change the resource group ownership of a Resource.
402                @remarks
403                        This method is generally reserved for internal use, although
404                        if you really know what you're doing you can use it to move
405                        this resource from one group to another.
406                @param newGroup Name of the new group
407                */
408                virtual void changeGroupOwnership(const String& newGroup);
409
410                /// Gets the manager which created this resource
411                virtual ResourceManager* getCreator(void) { return mCreator; }
412                /** Get the origin of this resource, e.g. a script file name.
413                @remarks
414                        This property will only contain something if the creator of
415                        this resource chose to populate it. Script loaders are advised
416                        to populate it.
417                */
418                virtual const String& getOrigin(void) const { return mOrigin; }
419                /// Notify this resource of it's origin
420                virtual void _notifyOrigin(const String& origin) { mOrigin = origin; }
421
422                /** Returns the number of times this resource has changed state, which
423                        generally means the number of times it has been loaded. Objects that
424                        build derived data based on the resource can check this value against
425                        a copy they kept last time they built this derived data, in order to
426                        know whether it needs rebuilding. This is a nice way of monitoring
427                        changes without having a tightly-bound callback.
428                */
429                virtual size_t getStateCount() const { return mStateCount; }
430
431                /** Manually mark the state of this resource as having been changed.
432                @remarks
433                        You only need to call this from outside if you explicitly want derived
434                        objects to think this object has changed. @see getStateCount.
435                */
436                virtual void _dirtyState();
437
438
439                /** Firing of loading complete event
440                @remarks
441                        You should call this from the thread that runs the main frame loop
442                        to avoid having to make the receivers of this event thread-safe.
443                        If you use Ogre's built in frame loop you don't need to call this
444                        yourself.
445                        @param wasBackgroundLoaded Whether this was a background loaded event
446                */
447                virtual void _fireLoadingComplete(bool wasBackgroundLoaded);
448
449                /** Firing of preparing complete event
450                @remarks
451                        You should call this from the thread that runs the main frame loop
452                        to avoid having to make the receivers of this event thread-safe.
453                        If you use Ogre's built in frame loop you don't need to call this
454                        yourself.
455                        @param wasBackgroundLoaded Whether this was a background loaded event
456                */
457                virtual void _firePreparingComplete(bool wasBackgroundLoaded);
458
459                /** Firing of unloading complete event
460                @remarks
461                You should call this from the thread that runs the main frame loop
462                to avoid having to make the receivers of this event thread-safe.
463                If you use Ogre's built in frame loop you don't need to call this
464                yourself.
465                */
466                virtual void _fireUnloadingComplete(void);
467
468                /** Calculate the size of a resource; this will only be called after 'load' */
469                virtual size_t calculateSize(void) const;
470
471    };
472
473        /** Shared pointer to a Resource.
474        @remarks
475                This shared pointer allows many references to a resource to be held, and
476                when the final reference is removed, the resource will be destroyed.
477                Note that the ResourceManager which created this Resource will be holding
478                at least one reference, so this resource will not get destroyed until
479                someone removes the resource from the manager - this at least gives you
480                strong control over when resources are freed. But the nature of the
481                shared pointer means that if anyone refers to the removed resource in the
482                meantime, the resource will remain valid.
483        @par
484                You may well see references to ResourcePtr (i.e. ResourcePtr&) being passed
485                around internally within Ogre. These are 'weak references' ie they do
486                not increment the reference count on the Resource. This is done for
487                efficiency in temporary operations that shouldn't need to incur the
488                overhead of maintaining the reference count; however we don't recommend
489                you do it yourself since these references are not guaranteed to remain valid.
490        */
491        typedef SharedPtr<Resource> ResourcePtr;
492
493        /** Interface describing a manual resource loader.
494        @remarks
495                Resources are usually loaded from files; however in some cases you
496                want to be able to set the data up manually instead. This provides
497                some problems, such as how to reload a Resource if it becomes
498                unloaded for some reason, either because of memory constraints, or
499                because a device fails and some or all of the data is lost.
500        @par
501                This interface should be implemented by all classes which wish to
502                provide manual data to a resource. They provide a pointer to themselves
503                when defining the resource (via the appropriate ResourceManager),
504                and will be called when the Resource tries to load.
505                They should implement the loadResource method such that the Resource
506                is in the end set up exactly as if it had loaded from a file,
507                although the implementations will likely differ between subclasses
508                of Resource, which is why no generic algorithm can be stated here.
509        @note
510                The loader must remain valid for the entire life of the resource,
511                so that if need be it can be called upon to re-load the resource
512                at any time.
513        */
514        class _OgreExport ManualResourceLoader
515        {
516        public:
517                ManualResourceLoader() {}
518                virtual ~ManualResourceLoader() {}
519
520        /** Called when a resource wishes to load.  Note that this could get
521         * called in a background thread even in just a semithreaded ogre
522         * (OGRE_THREAD_SUPPORT==2).  Thus, you must not access the rendersystem from
523         * this callback.  Do that stuff in loadResource.
524                @param resource The resource which wishes to load
525                */
526                virtual void prepareResource(Resource* resource)
527                { (void)resource; }
528
529                /** Called when a resource wishes to prepare.
530                @param resource The resource which wishes to prepare
531                */
532                virtual void loadResource(Resource* resource) = 0;
533        };
534        /** @} */
535        /** @} */
536}
537
538#include "OgreHeaderSuffix.h"
539
540#endif
Note: See TracBrowser for help on using the repository browser.