Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/ogre_src_v1-9-0/OgreMain/include/OgreDataStream.h

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

Added new dependencies for ogre1.9 and cegui0.8

File size: 22.2 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 __DataStream_H__
29#define __DataStream_H__
30
31#include "OgrePrerequisites.h"
32#include "OgreString.h"
33#include "OgreSharedPtr.h"
34#include <istream>
35#include "OgreHeaderPrefix.h"
36
37namespace Ogre {
38       
39        /** Template version of cache based on static array.
40         'cacheSize' defines size of cache in bytes. */
41        template <size_t cacheSize>
42        class StaticCache
43        {
44        protected:
45                /// Static buffer
46                char mBuffer[cacheSize];
47               
48                /// Number of bytes valid in cache (written from the beginning of static buffer)
49                size_t mValidBytes;
50                /// Current read position
51                size_t mPos;
52               
53        public:
54                /// Constructor
55                StaticCache()
56                {
57                        mValidBytes = 0;
58                        mPos = 0;
59                }
60               
61                /** Cache data pointed by 'buf'. If 'count' is greater than cache size, we cache only last bytes.
62                 Returns number of bytes written to cache. */
63                size_t cacheData(const void* buf, size_t count)
64                {
65                        assert(avail() == 0 && "It is assumed that you cache data only after you have read everything.");
66                       
67                        if (count < cacheSize)
68                        {
69                                // number of bytes written is less than total size of cache
70                                if (count + mValidBytes <= cacheSize)
71                                {
72                                        // just append
73                                        memcpy(mBuffer + mValidBytes, buf, count);
74                                        mValidBytes += count;
75                                }
76                                else
77                                {
78                                        size_t begOff = count - (cacheSize - mValidBytes);
79                                        // override old cache content in the beginning
80                                        memmove(mBuffer, mBuffer + begOff, mValidBytes - begOff);
81                                        // append new data
82                                        memcpy(mBuffer + cacheSize - count, buf, count);
83                                        mValidBytes = cacheSize;
84                                }
85                                mPos = mValidBytes;
86                                return count;
87                        }
88                        else
89                        {
90                                // discard all
91                                memcpy(mBuffer, (const char*)buf + count - cacheSize, cacheSize);
92                                mValidBytes = mPos = cacheSize;
93                                return cacheSize;
94                        }
95                }
96                /** Read data from cache to 'buf' (maximum 'count' bytes). Returns number of bytes read from cache. */
97                size_t read(void* buf, size_t count)
98                {
99                        size_t rb = avail();
100                        rb = (rb < count) ? rb : count;
101                        memcpy(buf, mBuffer + mPos, rb);
102                        mPos += rb;
103                        return rb;
104                }
105               
106                /** Step back in cached stream by 'count' bytes. Returns 'true' if cache contains resulting position. */
107                bool rewind(size_t count)
108                {
109                        if (mPos < count)
110                        {
111                                clear();
112                                return false;
113                        }
114                        else
115                        {
116                                mPos -= count;
117                                return true;
118                        }
119                }
120                /** Step forward in cached stream by 'count' bytes. Returns 'true' if cache contains resulting position. */
121                bool ff(size_t count)
122                {
123                        if (avail() < count)
124                        {
125                                clear();
126                                return false;
127                        }
128                        else
129                        {
130                                mPos += count;
131                                return true;
132                        }
133                }
134               
135                /** Returns number of bytes available for reading in cache after rewinding. */
136                size_t avail() const
137                {
138                        return mValidBytes - mPos;
139                }
140               
141                /** Clear the cache */
142                void clear()
143                {
144                        mValidBytes = 0;
145                        mPos = 0;
146                }
147        };
148       
149       
150        /** \addtogroup Core
151        *  @{
152        */
153        /** \addtogroup Resources
154        *  @{
155        */
156
157        /** General purpose class used for encapsulating the reading and writing of data.
158        @remarks
159                This class performs basically the same tasks as std::basic_istream,
160                except that it does not have any formatting capabilities, and is
161                designed to be subclassed to receive data from multiple sources,
162                including libraries which have no compatibility with the STL's
163                stream interfaces. As such, this is an abstraction of a set of
164                wrapper classes which pretend to be standard stream classes but
165                can actually be implemented quite differently.
166        @par
167                Generally, if a plugin or application provides an ArchiveFactory,
168                it should also provide a DataStream subclass which will be used
169                to stream data out of that Archive implementation, unless it can
170                use one of the common implementations included.
171        @note
172                Ogre makes no guarantees about thread safety, for performance reasons.
173                If you wish to access stream data asynchronously then you should
174                organise your own mutexes to avoid race conditions.
175        */
176        class _OgreExport DataStream : public StreamAlloc
177        {
178        public:
179                enum AccessMode
180                {
181                        READ = 1, 
182                        WRITE = 2
183                };
184        protected:
185                /// The name (e.g. resource name) that can be used to identify the source for this data (optional)
186                String mName;           
187        /// Size of the data in the stream (may be 0 if size cannot be determined)
188        size_t mSize;
189                /// What type of access is allowed (AccessMode)
190                uint16 mAccess;
191
192        #define OGRE_STREAM_TEMP_SIZE 128
193        public:
194                /// Constructor for creating unnamed streams
195        DataStream(uint16 accessMode = READ) : mSize(0), mAccess(accessMode) {}
196                /// Constructor for creating named streams
197                DataStream(const String& name, uint16 accessMode = READ) 
198                        : mName(name), mSize(0), mAccess(accessMode) {}
199                /// Returns the name of the stream, if it has one.
200                const String& getName(void) { return mName; }
201                /// Gets the access mode of the stream
202                uint16 getAccessMode() const { return mAccess; }
203                /** Reports whether this stream is readable. */
204                virtual bool isReadable() const { return (mAccess & READ) != 0; }
205                /** Reports whether this stream is writeable. */
206                virtual bool isWriteable() const { return (mAccess & WRITE) != 0; }
207        virtual ~DataStream() {}
208                // Streaming operators
209        template<typename T> DataStream& operator>>(T& val);
210                /** Read the requisite number of bytes from the stream,
211                        stopping at the end of the file.
212                @param buf Reference to a buffer pointer
213                @param count Number of bytes to read
214                @return The number of bytes read
215                */
216                virtual size_t read(void* buf, size_t count) = 0;
217                /** Write the requisite number of bytes from the stream (only applicable to
218                        streams that are not read-only)
219                @param buf Pointer to a buffer containing the bytes to write
220                @param count Number of bytes to write
221                @return The number of bytes written
222                */
223                virtual size_t write(const void* buf, size_t count)
224                {
225                        (void)buf;
226                        (void)count;
227                        // default to not supported
228                        return 0;
229                }
230
231                /** Get a single line from the stream.
232                @remarks
233                        The delimiter character is not included in the data
234                        returned, and it is skipped over so the next read will occur
235                        after it. The buffer contents will include a
236                        terminating character.
237        @note
238            If you used this function, you <b>must</b> open the stream in <b>binary mode</b>,
239            otherwise, it'll produce unexpected results.
240                @param buf Reference to a buffer pointer
241                @param maxCount The maximum length of data to be read, excluding the terminating character
242                @param delim The delimiter to stop at
243                @return The number of bytes read, excluding the terminating character
244                */
245                virtual size_t readLine(char* buf, size_t maxCount, const String& delim = "\n");
246               
247            /** Returns a String containing the next line of data, optionally
248                    trimmed for whitespace.
249            @remarks
250                    This is a convenience method for text streams only, allowing you to
251                    retrieve a String object containing the next line of data. The data
252                    is read up to the next newline character and the result trimmed if
253                    required.
254        @note
255            If you used this function, you <b>must</b> open the stream in <b>binary mode</b>,
256            otherwise, it'll produce unexpected results.
257            @param
258                    trimAfter If true, the line is trimmed for whitespace (as in
259                    String.trim(true,true))
260            */
261            virtual String getLine( bool trimAfter = true );
262
263            /** Returns a String containing the entire stream.
264            @remarks
265                    This is a convenience method for text streams only, allowing you to
266                    retrieve a String object containing all the data in the stream.
267            */
268            virtual String getAsString(void);
269
270                /** Skip a single line from the stream.
271        @note
272            If you used this function, you <b>must</b> open the stream in <b>binary mode</b>,
273            otherwise, it'll produce unexpected results.
274                @param delim The delimiter(s) to stop at
275                @return The number of bytes skipped
276                */
277                virtual size_t skipLine(const String& delim = "\n");
278
279                /** Skip a defined number of bytes. This can also be a negative value, in which case
280                the file pointer rewinds a defined number of bytes. */
281                virtual void skip(long count) = 0;
282       
283                /** Repositions the read point to a specified byte.
284            */
285            virtual void seek( size_t pos ) = 0;
286               
287                /** Returns the current byte offset from beginning */
288            virtual size_t tell(void) const = 0;
289
290                /** Returns true if the stream has reached the end.
291            */
292            virtual bool eof(void) const = 0;
293
294                /** Returns the total size of the data to be read from the stream,
295                        or 0 if this is indeterminate for this stream.
296                */
297        size_t size(void) const { return mSize; }
298
299        /** Close the stream; this makes further operations invalid. */
300        virtual void close(void) = 0;
301               
302
303        };
304
305        /** Shared pointer to allow data streams to be passed around without
306                worrying about deallocation
307        */
308        typedef SharedPtr<DataStream> DataStreamPtr;
309
310        /// List of DataStream items
311        typedef list<DataStreamPtr>::type DataStreamList;
312        /// Shared pointer to list of DataStream items
313        typedef SharedPtr<DataStreamList> DataStreamListPtr;
314
315        /** Common subclass of DataStream for handling data from chunks of memory.
316        */
317        class _OgreExport MemoryDataStream : public DataStream
318        {
319        protected:
320        /// Pointer to the start of the data area
321            uchar* mData;
322        /// Pointer to the current position in the memory
323            uchar* mPos;
324        /// Pointer to the end of the memory
325            uchar* mEnd;
326        /// Do we delete the memory on close
327                bool mFreeOnClose;                     
328        public:
329               
330                /** Wrap an existing memory chunk in a stream.
331                @param pMem Pointer to the existing memory
332                @param size The size of the memory chunk in bytes
333                @param freeOnClose If true, the memory associated will be destroyed
334                        when the stream is closed. Note: it's important that if you set
335                        this option to true, that you allocated the memory using OGRE_ALLOC_T
336                        with a category of MEMCATEGORY_GENERAL to ensure the freeing of memory
337                        matches up.
338                @param readOnly Whether to make the stream on this memory read-only once created
339                */
340                MemoryDataStream(void* pMem, size_t size, bool freeOnClose = false, bool readOnly = false);
341               
342                /** Wrap an existing memory chunk in a named stream.
343                @param name The name to give the stream
344                @param pMem Pointer to the existing memory
345                @param size The size of the memory chunk in bytes
346                @param freeOnClose If true, the memory associated will be destroyed
347                        when the stream is destroyed. Note: it's important that if you set
348                        this option to true, that you allocated the memory using OGRE_ALLOC_T
349                        with a category of MEMCATEGORY_GENERAL ensure the freeing of memory
350                        matches up.
351                @param readOnly Whether to make the stream on this memory read-only once created
352                */
353                MemoryDataStream(const String& name, void* pMem, size_t size, 
354                                bool freeOnClose = false, bool readOnly = false);
355
356                /** Create a stream which pre-buffers the contents of another stream.
357                @remarks
358                        This constructor can be used to intentionally read in the entire
359                        contents of another stream, copying them to the internal buffer
360                        and thus making them available in memory as a single unit.
361                @param sourceStream Another DataStream which will provide the source
362                        of data
363                @param freeOnClose If true, the memory associated will be destroyed
364                        when the stream is destroyed.
365                @param readOnly Whether to make the stream on this memory read-only once created
366                */
367                MemoryDataStream(DataStream& sourceStream, 
368                                bool freeOnClose = true, bool readOnly = false);
369               
370                /** Create a stream which pre-buffers the contents of another stream.
371                @remarks
372                        This constructor can be used to intentionally read in the entire
373                        contents of another stream, copying them to the internal buffer
374                        and thus making them available in memory as a single unit.
375                @param sourceStream Another DataStream which will provide the source
376                        of data
377                @param freeOnClose If true, the memory associated will be destroyed
378                        when the stream is destroyed.
379                @param readOnly Whether to make the stream on this memory read-only once created
380                */
381                MemoryDataStream(DataStreamPtr& sourceStream, 
382                                bool freeOnClose = true, bool readOnly = false);
383
384                /** Create a named stream which pre-buffers the contents of
385                        another stream.
386                @remarks
387                        This constructor can be used to intentionally read in the entire
388                        contents of another stream, copying them to the internal buffer
389                        and thus making them available in memory as a single unit.
390                @param name The name to give the stream
391                @param sourceStream Another DataStream which will provide the source
392                        of data
393                @param freeOnClose If true, the memory associated will be destroyed
394                        when the stream is destroyed.
395                @param readOnly Whether to make the stream on this memory read-only once created
396                */
397                MemoryDataStream(const String& name, DataStream& sourceStream, 
398                                bool freeOnClose = true, bool readOnly = false);
399
400        /** Create a named stream which pre-buffers the contents of
401        another stream.
402        @remarks
403        This constructor can be used to intentionally read in the entire
404        contents of another stream, copying them to the internal buffer
405        and thus making them available in memory as a single unit.
406        @param name The name to give the stream
407        @param sourceStream Another DataStream which will provide the source
408        of data
409        @param freeOnClose If true, the memory associated will be destroyed
410        when the stream is destroyed.
411                @param readOnly Whether to make the stream on this memory read-only once created
412        */
413        MemoryDataStream(const String& name, const DataStreamPtr& sourceStream, 
414            bool freeOnClose = true, bool readOnly = false);
415
416        /** Create a stream with a brand new empty memory chunk.
417                @param size The size of the memory chunk to create in bytes
418                @param freeOnClose If true, the memory associated will be destroyed
419                        when the stream is destroyed.
420                @param readOnly Whether to make the stream on this memory read-only once created
421                */
422                MemoryDataStream(size_t size, bool freeOnClose = true, bool readOnly = false);
423                /** Create a named stream with a brand new empty memory chunk.
424                @param name The name to give the stream
425                @param size The size of the memory chunk to create in bytes
426                @param freeOnClose If true, the memory associated will be destroyed
427                        when the stream is destroyed.
428                @param readOnly Whether to make the stream on this memory read-only once created
429                */
430                MemoryDataStream(const String& name, size_t size, 
431                                bool freeOnClose = true, bool readOnly = false);
432
433                ~MemoryDataStream();
434
435                /** Get a pointer to the start of the memory block this stream holds. */
436                uchar* getPtr(void) { return mData; }
437               
438                /** Get a pointer to the current position in the memory block this stream holds. */
439                uchar* getCurrentPtr(void) { return mPos; }
440               
441                /** @copydoc DataStream::read
442                */
443                size_t read(void* buf, size_t count);
444
445                /** @copydoc DataStream::write
446                */
447                size_t write(const void* buf, size_t count);
448
449                /** @copydoc DataStream::readLine
450                */
451                size_t readLine(char* buf, size_t maxCount, const String& delim = "\n");
452               
453                /** @copydoc DataStream::skipLine
454                */
455                size_t skipLine(const String& delim = "\n");
456
457                /** @copydoc DataStream::skip
458                */
459                void skip(long count);
460       
461                /** @copydoc DataStream::seek
462                */
463            void seek( size_t pos );
464               
465                /** @copydoc DataStream::tell
466                */
467            size_t tell(void) const;
468
469                /** @copydoc DataStream::eof
470                */
471            bool eof(void) const;
472
473        /** @copydoc DataStream::close
474        */
475        void close(void);
476
477                /** Sets whether or not to free the encapsulated memory on close. */
478                void setFreeOnClose(bool free) { mFreeOnClose = free; }
479        };
480
481    /** Shared pointer to allow memory data streams to be passed around without
482    worrying about deallocation
483    */
484    typedef SharedPtr<MemoryDataStream> MemoryDataStreamPtr;
485
486    /** Common subclass of DataStream for handling data from
487                std::basic_istream.
488        */
489        class _OgreExport FileStreamDataStream : public DataStream
490        {
491        protected:
492                /// Reference to source stream (read)
493                std::istream* mInStream;
494                /// Reference to source file stream (read-only)
495                std::ifstream* mFStreamRO;
496                /// Reference to source file stream (read-write)
497                std::fstream* mFStream;
498        bool mFreeOnClose;     
499
500                void determineAccess();
501        public:
502                /** Construct a read-only stream from an STL stream
503        @param s Pointer to source stream
504        @param freeOnClose Whether to delete the underlying stream on
505            destruction of this class
506        */
507                FileStreamDataStream(std::ifstream* s, 
508            bool freeOnClose = true);
509                /** Construct a read-write stream from an STL stream
510                @param s Pointer to source stream
511                @param freeOnClose Whether to delete the underlying stream on
512                destruction of this class
513                */
514                FileStreamDataStream(std::fstream* s, 
515                        bool freeOnClose = true);
516
517                /** Construct named read-only stream from an STL stream
518        @param name The name to give this stream
519        @param s Pointer to source stream
520        @param freeOnClose Whether to delete the underlying stream on
521            destruction of this class
522        */
523                FileStreamDataStream(const String& name, 
524            std::ifstream* s, 
525            bool freeOnClose = true);
526
527                /** Construct named read-write stream from an STL stream
528                @param name The name to give this stream
529                @param s Pointer to source stream
530                @param freeOnClose Whether to delete the underlying stream on
531                destruction of this class
532                */
533                FileStreamDataStream(const String& name, 
534                        std::fstream* s, 
535                        bool freeOnClose = true);
536
537                /** Construct named read-only stream from an STL stream, and tell it the size
538        @remarks
539            This variant tells the class the size of the stream too, which
540            means this class does not need to seek to the end of the stream
541            to determine the size up-front. This can be beneficial if you have
542            metadata about the contents of the stream already.
543        @param name The name to give this stream
544        @param s Pointer to source stream
545        @param size Size of the stream contents in bytes
546        @param freeOnClose Whether to delete the underlying stream on
547            destruction of this class. If you specify 'true' for this you
548                        must ensure that the stream was allocated using OGRE_NEW_T with
549                        MEMCATEGRORY_GENERAL.
550        */
551                FileStreamDataStream(const String& name, 
552            std::ifstream* s, 
553            size_t size, 
554            bool freeOnClose = true);
555
556                /** Construct named read-write stream from an STL stream, and tell it the size
557                @remarks
558                This variant tells the class the size of the stream too, which
559                means this class does not need to seek to the end of the stream
560                to determine the size up-front. This can be beneficial if you have
561                metadata about the contents of the stream already.
562                @param name The name to give this stream
563                @param s Pointer to source stream
564                @param size Size of the stream contents in bytes
565                @param freeOnClose Whether to delete the underlying stream on
566                destruction of this class. If you specify 'true' for this you
567                must ensure that the stream was allocated using OGRE_NEW_T with
568                MEMCATEGRORY_GENERAL.
569                */
570                FileStreamDataStream(const String& name, 
571                        std::fstream* s, 
572                        size_t size, 
573                        bool freeOnClose = true);
574
575                ~FileStreamDataStream();
576
577                /** @copydoc DataStream::read
578                */
579                size_t read(void* buf, size_t count);
580
581                /** @copydoc DataStream::write
582                */
583                size_t write(const void* buf, size_t count);
584
585                /** @copydoc DataStream::readLine
586                */
587        size_t readLine(char* buf, size_t maxCount, const String& delim = "\n");
588               
589                /** @copydoc DataStream::skip
590                */
591                void skip(long count);
592       
593                /** @copydoc DataStream::seek
594                */
595            void seek( size_t pos );
596
597                /** @copydoc DataStream::tell
598                */
599                size_t tell(void) const;
600
601                /** @copydoc DataStream::eof
602                */
603            bool eof(void) const;
604
605        /** @copydoc DataStream::close
606        */
607        void close(void);
608               
609               
610        };
611
612        /** Common subclass of DataStream for handling data from C-style file
613                handles.
614    @remarks
615        Use of this class is generally discouraged; if you want to wrap file
616        access in a DataStream, you should definitely be using the C++ friendly
617        FileStreamDataStream. However, since there are quite a few applications
618        and libraries still wedded to the old FILE handle access, this stream
619        wrapper provides some backwards compatibility.
620        */
621        class _OgreExport FileHandleDataStream : public DataStream
622        {
623        protected:
624                FILE* mFileHandle;
625        public:
626                /// Create stream from a C file handle
627                FileHandleDataStream(FILE* handle, uint16 accessMode = READ);
628                /// Create named stream from a C file handle
629                FileHandleDataStream(const String& name, FILE* handle, uint16 accessMode = READ);
630        ~FileHandleDataStream();
631
632                /** @copydoc DataStream::read
633                */
634                size_t read(void* buf, size_t count);
635
636                /** @copydoc DataStream::write
637                */
638                size_t write(const void* buf, size_t count);
639
640                /** @copydoc DataStream::skip
641                */
642                void skip(long count);
643       
644                /** @copydoc DataStream::seek
645                */
646            void seek( size_t pos );
647
648                /** @copydoc DataStream::tell
649                */
650                size_t tell(void) const;
651
652                /** @copydoc DataStream::eof
653                */
654            bool eof(void) const;
655
656        /** @copydoc DataStream::close
657        */
658        void close(void);
659
660        };
661        /** @} */
662        /** @} */
663}
664
665#include "OgreHeaderSuffix.h"
666
667#endif
668
Note: See TracBrowser for help on using the repository browser.