Coverage Report

Created: 2026-02-14 06:32

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ogre/OgreMain/include/OgreRenderTarget.h
Line
Count
Source
1
/*
2
-----------------------------------------------------------------------------
3
This source file is part of OGRE
4
    (Object-oriented Graphics Rendering Engine)
5
For the latest info, see http://www.ogre3d.org/
6
7
Copyright (c) 2000-2014 Torus Knot Software Ltd
8
9
Permission is hereby granted, free of charge, to any person obtaining a copy
10
of this software and associated documentation files (the "Software"), to deal
11
in the Software without restriction, including without limitation the rights
12
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
copies of the Software, and to permit persons to whom the Software is
14
furnished to do so, subject to the following conditions:
15
16
The above copyright notice and this permission notice shall be included in
17
all copies or substantial portions of the Software.
18
19
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25
THE SOFTWARE.
26
-----------------------------------------------------------------------------
27
*/
28
#ifndef __RenderTarget_H__
29
#define __RenderTarget_H__
30
31
#include "OgrePrerequisites.h"
32
33
#include "OgrePixelFormat.h"
34
#include "OgreHeaderPrefix.h"
35
36
/* Define the number of priority groups for the render system's render targets. */
37
#ifndef OGRE_NUM_RENDERTARGET_GROUPS
38
    #define OGRE_NUM_RENDERTARGET_GROUPS 10
39
    #define OGRE_DEFAULT_RT_GROUP 4
40
    #define OGRE_REND_TO_TEX_RT_GROUP 2
41
#endif
42
43
namespace Ogre {
44
45
    /** \addtogroup Core
46
    *  @{
47
    */
48
    /** \addtogroup RenderSystem
49
    *  @{
50
    */
51
    /** A 'canvas' which can receive the results of a rendering
52
        operation.
53
54
        This abstract class defines a common root to all targets of rendering operations. A
55
        render target could be a window on a screen, or another
56
        offscreen surface like a texture or bump map etc.
57
        @author
58
            Steven Streeting
59
     */
60
    class _OgreExport RenderTarget : public RenderSysAlloc
61
    {
62
    public:
63
        struct FrameStats
64
        {
65
            /// frames per second (FPS) based on the frames rendered in the last second
66
            float lastFPS;
67
            /// average frames per second (FPS) since call to Root::startRendering
68
            float avgFPS;
69
            /// best frames per second (FPS) since call to Root::startRendering
70
            float bestFPS;
71
            /// worst frames per second (FPS) since call to Root::startRendering
72
            float worstFPS;
73
            unsigned long bestFrameTime;
74
            unsigned long worstFrameTime;
75
            /// number of triangles rendered in the last update() call.
76
            size_t triangleCount;
77
            /// number of batches rendered in the last update() call.
78
            size_t batchCount;
79
            int vBlankMissCount; // -1 means that the value is not applicable
80
        };
81
82
        enum FrameBuffer
83
        {
84
            FB_FRONT,
85
            FB_BACK,
86
            FB_AUTO
87
        };
88
89
        RenderTarget();
90
        virtual ~RenderTarget();
91
92
        /// Retrieve target's name.
93
0
        const String& getName(void) const { return mName; }
94
95
        /// Retrieve information about the render target.
96
        void getMetrics(unsigned int& width, unsigned int& height);
97
98
0
        uint32 getWidth(void) const { return mWidth; }
99
0
        uint32 getHeight(void) const { return mHeight; }
100
101
        /**
102
         * Sets the pool ID this RenderTarget should query from. Default value is POOL_DEFAULT.
103
         * Set to POOL_NO_DEPTH to avoid using a DepthBuffer (or manually controlling it) @see DepthBuffer
104
         *      Changing the pool Id will cause the current depth buffer to be detached unless the old
105
         *      id and the new one are the same
106
         */
107
        void setDepthBufferPool( uint16 poolId );
108
109
        //Returns the pool ID this RenderTarget should query from. @see DepthBuffer
110
0
        uint16 getDepthBufferPool() const { return mDepthBufferPoolId; }
111
112
0
        DepthBuffer* getDepthBuffer() const { return mDepthBuffer; }
113
114
        //Returns false if couldn't attach
115
        virtual bool attachDepthBuffer( DepthBuffer *depthBuffer );
116
117
        void detachDepthBuffer();
118
119
        /** Detaches DepthBuffer without notifying it from the detach.
120
            Useful when called from the DepthBuffer while it iterates through attached
121
            RenderTargets (@see DepthBuffer::_setPoolId())
122
        */
123
0
        virtual void _detachDepthBuffer() { mDepthBuffer = 0; }
124
125
        /** Tells the target to update it's contents.
126
127
            If OGRE is not running in an automatic rendering loop
128
            (via @ref Root::startRendering),
129
            the user of the library is responsible for asking each render
130
            target to refresh. This is the method used to do this. It automatically
131
            re-renders the contents of the target using whatever cameras have been
132
            pointed at it (using @ref addViewport).
133
134
            This allows OGRE to be used in multi-windowed utilities
135
            and for contents to be refreshed only when required, rather than
136
            constantly as with the automatic rendering loop.
137
            @param swapBuffers If set to true, the target will immediately call
138
            @ref swapBuffers() after the update. See @ref swapBuffers() for why you
139
            might want to set this to false.
140
        */
141
        void update(bool swapBuffers = true);
142
        /** Finalizes the frame by performing buffer swaps and MSAA resolves
143
144
            This method handles the end-of-frame operations required to display the
145
            rendered content. Depending on the target configuration, this includes:
146
            - Swapping the front and back buffers (if double-buffering is enabled).
147
            - Resolving the MSAA (Multisample Anti-Aliasing) surface to the
148
            displayable surface (if MSAA is enabled).
149
150
            @attention After this method returns, the contents of the multisample buffers
151
            are invalidated/discarded. You cannot rely on their contents for
152
            subsequent operations without re-rendering.
153
        */
154
0
        virtual void swapBuffers() {}
155
156
        /** Adds a viewport to the rendering target.
157
158
            A viewport is the rectangle into which rendering output is sent. This method adds
159
            a viewport to the render target, rendering from the supplied camera. The
160
            rest of the parameters are only required if you wish to add more than one viewport
161
            to a single rendering target. Note that size information passed to this method is
162
            passed as a parametric, i.e. it is relative rather than absolute. This is to allow
163
            viewports to automatically resize along with the target.
164
            @param
165
                cam The camera from which the viewport contents will be rendered (mandatory)
166
            @param
167
                ZOrder The relative order of the viewport with others on the target (allows overlapping
168
                viewports i.e. picture-in-picture). Higher Z-orders are on top of lower ones. The actual number
169
                is irrelevant, only the relative Z-order matters (you can leave gaps in the numbering)
170
            @param
171
                rect The relative position of the viewport on the target, as a value between 0 and 1.
172
        */
173
        Viewport* addViewport(Camera* cam, int ZOrder = 0, FloatRect rect = {0.0f, 0.0f, 1.0f, 1.0f});
174
175
        /// @overload
176
        Viewport* addViewport(Camera* cam, int ZOrder, float left, float top = 0.0f, float width = 1.0f,
177
                              float height = 1.0f)
178
0
        {
179
0
            return addViewport(cam, ZOrder, {left, top, left + width, top + height});
180
0
        }
181
182
        /** Returns the number of viewports attached to this target.*/
183
0
        unsigned short getNumViewports(void) const { return static_cast<unsigned short>(mViewportList.size()); }
184
185
        /** Retrieves a pointer to the viewport with the given index. */
186
        Viewport* getViewport(unsigned short index);
187
188
        /** Retrieves a pointer to the viewport with the given Z-order. 
189
            @remarks throws if not found.
190
        */
191
        Viewport* getViewportByZOrder(int ZOrder);
192
193
        /** Returns true if and only if a viewport exists at the given Z-order. */
194
        bool hasViewportWithZOrder(int ZOrder);
195
196
        /** Removes a viewport at a given Z-order.
197
        */
198
        void removeViewport(int ZOrder);
199
200
        /** Removes all viewports on this target.
201
        */
202
        void removeAllViewports(void);
203
204
        /** Retrieves details of current rendering performance. */
205
0
        const FrameStats& getStatistics(void) const {
206
0
            return mStats;
207
0
        }
208
209
        /** Resets saved frame-rate statistices.
210
        */
211
        void resetStatistics(void);
212
213
        /** Retrieve a platform or API-specific piece of information
214
215
            This method of retrieving information should only be used if you know what you're doing.
216
217
            | Name        | Description                        |
218
            |-------------|------------------------------------|
219
            | WINDOW      | The native window handle. (X11 Window XID/ HWND / NSWindow*) |
220
            | HWND        | deprecated (same as WINDOW) |
221
            | GL_FBOID | the id of the OpenGL framebuffer object |
222
            | GL_MULTISAMPLEFBOID | the id of the OpenGL framebuffer object used for multisampling |
223
            | GLFBO | id of the screen OpenGL framebuffer object on iOS |
224
            | GLCONTEXT   | deprecated, do not use |
225
            | FBO | deprecated, do not use |
226
            | TARGET | deprecated, do not use |
227
            | XDISPLAY     | The X Display connection behind that context. |
228
            | ATOM        | The X Atom used in client delete events. |
229
            | VIEW | Cocoa NSView* |
230
            | NSOPENGLCONTEXT | Cocoa NSOpenGLContext* |
231
            | NSOPENGLPIXELFORMAT | Cocoa NSOpenGLPixelFormat* |
232
            
233
            @param name The name of the attribute.
234
            @param pData Pointer to memory of the right kind of structure to receive the info.
235
        */
236
        virtual void getCustomAttribute(const String& name, void* pData);
237
238
        /** simplified API for bindings
239
         * 
240
         * @overload
241
         */
242
        uint getCustomAttribute(const String& name)
243
0
        {
244
0
            uint ret = 0;
245
0
            getCustomAttribute(name, &ret);
246
0
            return ret;
247
0
        }
248
249
        /** Add a listener to this RenderTarget which will be called back before & after rendering.
250
251
            If you want notifications before and after a target is updated by the system, use
252
            this method to register your own custom RenderTargetListener class. This is useful
253
            for potentially adding your own manual rendering commands before and after the
254
            'normal' system rendering.
255
        @par NB this should not be used for frame-based scene updates, use Root::addFrameListener for that.
256
        */
257
        void addListener(RenderTargetListener* listener);
258
        /** same as addListener, but force the position in the vector, so we can control the call order */
259
        void insertListener(RenderTargetListener* listener, const unsigned int pos = 0);
260
        /** Removes a RenderTargetListener previously registered using addListener. */
261
        void removeListener(RenderTargetListener* listener);
262
        /** Removes all listeners from this instance. */
263
        void removeAllListeners(void);
264
265
        /** Sets the priority of this render target in relation to the others. 
266
267
            This can be used in order to schedule render target updates. Lower
268
            priorities will be rendered first. Note that the priority must be set
269
            at the time the render target is attached to the render system, changes
270
            afterwards will not affect the ordering.
271
        */
272
0
        void setPriority( uchar priority ) { mPriority = priority; }
273
        /** Gets the priority of a render target. */
274
0
        uchar getPriority() const { return mPriority; }
275
276
        /** Used to retrieve or set the active state of the render target.
277
        */
278
0
        virtual bool isActive() const { return mActive; }
279
280
        /** Used to set the active state of the render target.
281
        */
282
0
        void setActive( bool state ) { mActive = state; }
283
284
        /** Sets whether this target should be automatically updated if Ogre's rendering
285
            loop or Root::_updateAllRenderTargets is being used.
286
287
            By default, if you use Ogre's own rendering loop (Root::startRendering)
288
            or call Root::_updateAllRenderTargets, all render targets are updated 
289
            automatically. This method allows you to control that behaviour, if 
290
            for example you have a render target which you only want to update periodically.
291
        @param autoupdate If true, the render target is updated during the automatic render
292
            loop or when Root::_updateAllRenderTargets is called. If false, the 
293
            target is only updated when its update() method is called explicitly.
294
        */
295
0
        void setAutoUpdated(bool autoupdate) { mAutoUpdate = autoupdate; }
296
        /** Gets whether this target is automatically updated if Ogre's rendering
297
            loop or Root::_updateAllRenderTargets is being used.
298
        */
299
0
        bool isAutoUpdated(void) const { return mAutoUpdate; }
300
301
        /** Copies the current contents of the render target to a pixelbox. 
302
        @remarks See suggestPixelFormat for a tip as to the best pixel format to
303
            extract into, although you can use whatever format you like and the 
304
            results will be converted.
305
        */
306
        virtual void copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer = FB_AUTO) = 0;
307
308
        /** @overload
309
        @deprecated This function is deprecated as behavior for dst.size < RenderTarget.size
310
            was inconsistent in previous versions of Ogre. Sometimes the whole rect was used as a source,
311
            sometimes the rect with the size equal to the size of destination rect but located
312
            in the top left corner of the render target, sometimes the destination rect itself.
313
            Use the overload with explicitly specified source and destination boxes instead.
314
        */
315
0
        OGRE_DEPRECATED void copyContentsToMemory(const PixelBox &dst, FrameBuffer buffer = FB_AUTO) { copyContentsToMemory(Box(0, 0, mWidth, mHeight), dst, buffer); }
316
317
        /** Suggests a pixel format to use for extracting the data in this target, 
318
            when calling copyContentsToMemory.
319
        */
320
0
        virtual PixelFormat suggestPixelFormat() const { return PF_BYTE_RGBA; }
321
        
322
        /** Writes the current contents of the render target to the named file. */
323
        void writeContentsToFile(const String& filename);
324
325
        /** Writes the current contents of the render target to the (PREFIX)(time-stamp)(SUFFIX) file.
326
            @return the name of the file used.*/
327
        String writeContentsToTimestampedFile(const String& filenamePrefix, const String& filenameSuffix);
328
329
        virtual bool requiresTextureFlipping() const = 0;
330
331
        /** Utility method to notify a render target that a camera has been removed,
332
        in case it was referring to it as a viewer.
333
        */
334
        void _notifyCameraRemoved(const Camera* cam);
335
336
        /** Indicates whether this target is the primary window. The
337
            primary window is special in that it is destroyed when
338
            ogre is shut down, and cannot be destroyed directly.
339
            This is the case because it holds the context for vertex,
340
            index buffers and textures.
341
        */
342
0
        virtual bool isPrimary(void) const { return false; }
343
344
    /** Indicates whether stereo is currently enabled for this target. Default is false. */
345
0
    virtual bool isStereoEnabled(void) const { return mStereoEnabled; }
346
    
347
        /** Indicates whether on rendering, linear colour space is converted to 
348
            sRGB gamma colour space. This is the exact opposite conversion of
349
            what is indicated by Texture::isHardwareGammaEnabled, and can only
350
            be enabled on creation of the render target. For render windows, it's
351
            enabled through the 'gamma' creation misc parameter. For textures, 
352
            it is enabled through the hwGamma parameter to the create call.
353
        */
354
0
        bool isHardwareGammaEnabled() const { return mHwGamma; }
355
356
        /** Indicates whether multisampling is performed on rendering and at what level.
357
        */
358
0
        uint getFSAA() const { return mFSAA; }
359
360
        /// RenderSystem specific FSAA option. See @ref RenderSystem::_createRenderWindow for details.
361
0
        const String& getFSAAHint() const { return mFSAAHint; }
362
363
        /** Set the level of multisample AA to be used if hardware support it.
364
            This option will be ignored if the hardware does not support it 
365
            or setting can not be changed on the fly on per-target level. 
366
            @param fsaa The number of samples
367
            @param fsaaHint @copybrief getFSAAHint
368
        */
369
0
        virtual void setFSAA(uint fsaa, const String& fsaaHint) { }
370
371
        /** Method for manual management of rendering : fires 'preRenderTargetUpdate'
372
            and initialises statistics etc.
373
374
        <ul>
375
        <li>_beginUpdate resets statistics and fires 'preRenderTargetUpdate'.</li>
376
        <li>_updateViewport renders the given viewport (even if it is not autoupdated),
377
        fires preViewportUpdate and postViewportUpdate and manages statistics.</li>
378
        <li>_updateAutoUpdatedViewports renders only viewports that are auto updated,
379
        fires preViewportUpdate and postViewportUpdate and manages statistics.</li>
380
        <li>_endUpdate() ends statistics calculation and fires postRenderTargetUpdate.</li>
381
        </ul>
382
        you can use it like this for example :
383
        <pre>
384
            renderTarget->_beginUpdate();
385
            renderTarget->_updateViewport(1); // which is not auto updated
386
            renderTarget->_updateViewport(2); // which is not auto updated
387
            renderTarget->_updateAutoUpdatedViewports();
388
            renderTarget->_endUpdate();
389
            renderTarget->swapBuffers();
390
        </pre>
391
            Please note that in that case, the zorder may not work as you expect,
392
            since you are responsible for calling _updateViewport in the correct order.
393
        */
394
        virtual void _beginUpdate();
395
396
        /** Method for manual management of rendering - renders the given 
397
        viewport (even if it is not autoupdated)
398
399
        This also fires preViewportUpdate and postViewportUpdate, and manages statistics.
400
        You should call it between _beginUpdate() and _endUpdate().
401
        @see _beginUpdate for more details.
402
        @param zorder The zorder of the viewport to update.
403
        @param updateStatistics Whether you want to update statistics or not.
404
        */
405
        void _updateViewport(int zorder, bool updateStatistics = true)
406
0
        {
407
0
            _updateViewport(getViewportByZOrder(zorder), updateStatistics);
408
0
        }
409
410
        /** Method for manual management of rendering - renders the given viewport (even if it is not autoupdated)
411
412
        This also fires preViewportUpdate and postViewportUpdate, and manages statistics
413
        if needed. You should call it between _beginUpdate() and _endUpdate().
414
        @see _beginUpdate for more details.
415
        @param viewport The viewport you want to update, it must be bound to the rendertarget.
416
        @param updateStatistics Whether you want to update statistics or not.
417
        */
418
        virtual void _updateViewport(Viewport* viewport, bool updateStatistics = true);
419
420
        /** Method for manual management of rendering - renders only viewports that are auto updated
421
422
        This also fires preViewportUpdate and postViewportUpdate, and manages statistics.
423
        You should call it between _beginUpdate() and _endUpdate().
424
        See _beginUpdate for more details.
425
        @param updateStatistics Whether you want to update statistics or not.
426
        @see _beginUpdate()
427
        */
428
        void _updateAutoUpdatedViewports(bool updateStatistics = true);
429
        
430
        /** Method for manual management of rendering - finishes statistics calculation 
431
            and fires 'postRenderTargetUpdate'.
432
433
        You should call it after a _beginUpdate
434
        @see _beginUpdate for more details.
435
        */
436
        virtual void _endUpdate();
437
438
    protected:
439
        /// The name of this target.
440
        String mName;
441
        /// The priority of the render target.
442
        uchar mPriority;
443
444
        uint32 mWidth;
445
        uint32 mHeight;
446
        uint16       mDepthBufferPoolId;
447
        DepthBuffer *mDepthBuffer;
448
449
        // Stats
450
        FrameStats mStats;
451
        
452
        Timer* mTimer ;
453
        unsigned long mLastSecond;
454
        unsigned long mLastTime;
455
        size_t mFrameCount;
456
457
        bool mActive;
458
        bool mAutoUpdate;
459
        // Hardware sRGB gamma conversion done on write?
460
        bool mHwGamma;
461
        // FSAA performed?
462
        uint mFSAA;
463
        String mFSAAHint;
464
    bool mStereoEnabled;
465
466
        virtual void updateStats(void);
467
468
        typedef std::map<int, Viewport*> ViewportList;
469
        /// List of viewports, map on Z-order
470
        ViewportList mViewportList;
471
472
        typedef std::vector<RenderTargetListener*> RenderTargetListenerList;
473
        RenderTargetListenerList mListeners;
474
    
475
476
        /// internal method for firing events
477
        virtual void firePreUpdate(void);
478
        /// internal method for firing events
479
        virtual void firePostUpdate(void);
480
        /// internal method for firing events
481
        virtual void fireViewportPreUpdate(Viewport* vp);
482
        /// internal method for firing events
483
        virtual void fireViewportPostUpdate(Viewport* vp);
484
        /// internal method for firing events
485
        virtual void fireViewportAdded(Viewport* vp);
486
        /// internal method for firing events
487
        void fireViewportRemoved(Viewport* vp);
488
        
489
        /// Internal implementation of update()
490
        virtual void updateImpl();
491
    };
492
    /** @} */
493
    /** @} */
494
495
} // Namespace
496
497
#include "OgreHeaderSuffix.h"
498
499
#endif