Coverage Report

Created: 2025-07-18 07:08

/src/ogre/OgreMain/include/OgreRenderTarget.h
Line
Count
Source (jump to first uncovered line)
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
            (started using 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 Camera::setRenderTarget).
133
            @par
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 For targets that support double-buffering, if set 
138
                to true, the target will immediately
139
                swap it's buffers after update. Otherwise, the buffers are
140
                not swapped, and you have to call swapBuffers yourself sometime
141
                later. You might want to do this on some rendersystems which 
142
                pause for queued rendering commands to complete before accepting
143
                swap buffers calls - so you could do other CPU tasks whilst the 
144
                queued commands complete. Or, you might do this if you want custom
145
                control over your windows, such as for externally created windows.
146
        */
147
        void update(bool swapBuffers = true);
148
        /** Swaps the frame buffers to display the next frame.
149
150
            For targets that are double-buffered so that no
151
            'in-progress' versions of the scene are displayed
152
            during rendering. Once rendering has completed (to
153
            an off-screen version of the window) the buffers
154
            are swapped to display the new frame.
155
        */
156
0
        virtual void swapBuffers() {}
157
158
        /** Adds a viewport to the rendering target.
159
160
            A viewport is the rectangle into which rendering output is sent. This method adds
161
            a viewport to the render target, rendering from the supplied camera. The
162
            rest of the parameters are only required if you wish to add more than one viewport
163
            to a single rendering target. Note that size information passed to this method is
164
            passed as a parametric, i.e. it is relative rather than absolute. This is to allow
165
            viewports to automatically resize along with the target.
166
            @param
167
                cam The camera from which the viewport contents will be rendered (mandatory)
168
            @param
169
                ZOrder The relative order of the viewport with others on the target (allows overlapping
170
                viewports i.e. picture-in-picture). Higher Z-orders are on top of lower ones. The actual number
171
                is irrelevant, only the relative Z-order matters (you can leave gaps in the numbering)
172
            @param
173
                rect The relative position of the viewport on the target, as a value between 0 and 1.
174
        */
175
        Viewport* addViewport(Camera* cam, int ZOrder = 0, FloatRect rect = {0.0f, 0.0f, 1.0f, 1.0f});
176
177
        /// @overload
178
        Viewport* addViewport(Camera* cam, int ZOrder, float left, float top = 0.0f, float width = 1.0f,
179
                              float height = 1.0f)
180
0
        {
181
0
            return addViewport(cam, ZOrder, {left, top, left + width, top + height});
182
0
        }
183
184
        /** Returns the number of viewports attached to this target.*/
185
0
        unsigned short getNumViewports(void) const { return static_cast<unsigned short>(mViewportList.size()); }
186
187
        /** Retrieves a pointer to the viewport with the given index. */
188
        Viewport* getViewport(unsigned short index);
189
190
        /** Retrieves a pointer to the viewport with the given Z-order. 
191
            @remarks throws if not found.
192
        */
193
        Viewport* getViewportByZOrder(int ZOrder);
194
195
        /** Returns true if and only if a viewport exists at the given Z-order. */
196
        bool hasViewportWithZOrder(int ZOrder);
197
198
        /** Removes a viewport at a given Z-order.
199
        */
200
        void removeViewport(int ZOrder);
201
202
        /** Removes all viewports on this target.
203
        */
204
        void removeAllViewports(void);
205
206
        /** Retrieves details of current rendering performance. */
207
0
        const FrameStats& getStatistics(void) const {
208
0
            return mStats;
209
0
        }
210
211
        /** Resets saved frame-rate statistices.
212
        */
213
        void resetStatistics(void);
214
215
        /** Retrieve a platform or API-specific piece of information
216
217
            This method of retrieving information should only be used if you know what you're doing.
218
219
            | Name        | Description                        |
220
            |-------------|------------------------------------|
221
            | WINDOW      | The native window handle. (X11 Window XID/ HWND / NSWindow*) |
222
            | HWND        | deprecated (same as WINDOW) |
223
            | GL_FBOID | the id of the OpenGL framebuffer object |
224
            | GL_MULTISAMPLEFBOID | the id of the OpenGL framebuffer object used for multisampling |
225
            | GLFBO | id of the screen OpenGL framebuffer object on iOS |
226
            | GLCONTEXT   | deprecated, do not use |
227
            | FBO | deprecated, do not use |
228
            | TARGET | deprecated, do not use |
229
            | XDISPLAY     | The X Display connection behind that context. |
230
            | ATOM        | The X Atom used in client delete events. |
231
            | VIEW | Cocoa NSView* |
232
            | NSOPENGLCONTEXT | Cocoa NSOpenGLContext* |
233
            | NSOPENGLPIXELFORMAT | Cocoa NSOpenGLPixelFormat* |
234
            
235
            @param name The name of the attribute.
236
            @param pData Pointer to memory of the right kind of structure to receive the info.
237
        */
238
        virtual void getCustomAttribute(const String& name, void* pData);
239
240
        /** simplified API for bindings
241
         * 
242
         * @overload
243
         */
244
        uint getCustomAttribute(const String& name)
245
0
        {
246
0
            uint ret = 0;
247
0
            getCustomAttribute(name, &ret);
248
0
            return ret;
249
0
        }
250
251
        /** Add a listener to this RenderTarget which will be called back before & after rendering.
252
253
            If you want notifications before and after a target is updated by the system, use
254
            this method to register your own custom RenderTargetListener class. This is useful
255
            for potentially adding your own manual rendering commands before and after the
256
            'normal' system rendering.
257
        @par NB this should not be used for frame-based scene updates, use Root::addFrameListener for that.
258
        */
259
        void addListener(RenderTargetListener* listener);
260
        /** same as addListener, but force the position in the vector, so we can control the call order */
261
        void insertListener(RenderTargetListener* listener, const unsigned int pos = 0);
262
        /** Removes a RenderTargetListener previously registered using addListener. */
263
        void removeListener(RenderTargetListener* listener);
264
        /** Removes all listeners from this instance. */
265
        void removeAllListeners(void);
266
267
        /** Sets the priority of this render target in relation to the others. 
268
269
            This can be used in order to schedule render target updates. Lower
270
            priorities will be rendered first. Note that the priority must be set
271
            at the time the render target is attached to the render system, changes
272
            afterwards will not affect the ordering.
273
        */
274
0
        void setPriority( uchar priority ) { mPriority = priority; }
275
        /** Gets the priority of a render target. */
276
0
        uchar getPriority() const { return mPriority; }
277
278
        /** Used to retrieve or set the active state of the render target.
279
        */
280
0
        virtual bool isActive() const { return mActive; }
281
282
        /** Used to set the active state of the render target.
283
        */
284
0
        void setActive( bool state ) { mActive = state; }
285
286
        /** Sets whether this target should be automatically updated if Ogre's rendering
287
            loop or Root::_updateAllRenderTargets is being used.
288
289
            By default, if you use Ogre's own rendering loop (Root::startRendering)
290
            or call Root::_updateAllRenderTargets, all render targets are updated 
291
            automatically. This method allows you to control that behaviour, if 
292
            for example you have a render target which you only want to update periodically.
293
        @param autoupdate If true, the render target is updated during the automatic render
294
            loop or when Root::_updateAllRenderTargets is called. If false, the 
295
            target is only updated when its update() method is called explicitly.
296
        */
297
0
        void setAutoUpdated(bool autoupdate) { mAutoUpdate = autoupdate; }
298
        /** Gets whether this target is automatically updated if Ogre's rendering
299
            loop or Root::_updateAllRenderTargets is being used.
300
        */
301
0
        bool isAutoUpdated(void) const { return mAutoUpdate; }
302
303
        /** Copies the current contents of the render target to a pixelbox. 
304
        @remarks See suggestPixelFormat for a tip as to the best pixel format to
305
            extract into, although you can use whatever format you like and the 
306
            results will be converted.
307
        */
308
        virtual void copyContentsToMemory(const Box& src, const PixelBox &dst, FrameBuffer buffer = FB_AUTO) = 0;
309
310
        /** @overload
311
        @deprecated This function is deprecated as behavior for dst.size < RenderTarget.size
312
            was inconsistent in previous versions of Ogre. Sometimes the whole rect was used as a source,
313
            sometimes the rect with the size equal to the size of destination rect but located
314
            in the top left corner of the render target, sometimes the destination rect itself.
315
            Use the overload with explicitly specified source and destination boxes instead.
316
        */
317
0
        OGRE_DEPRECATED void copyContentsToMemory(const PixelBox &dst, FrameBuffer buffer = FB_AUTO) { copyContentsToMemory(Box(0, 0, mWidth, mHeight), dst, buffer); }
318
319
        /** Suggests a pixel format to use for extracting the data in this target, 
320
            when calling copyContentsToMemory.
321
        */
322
0
        virtual PixelFormat suggestPixelFormat() const { return PF_BYTE_RGBA; }
323
        
324
        /** Writes the current contents of the render target to the named file. */
325
        void writeContentsToFile(const String& filename);
326
327
        /** Writes the current contents of the render target to the (PREFIX)(time-stamp)(SUFFIX) file.
328
            @return the name of the file used.*/
329
        String writeContentsToTimestampedFile(const String& filenamePrefix, const String& filenameSuffix);
330
331
        virtual bool requiresTextureFlipping() const = 0;
332
333
        /** Utility method to notify a render target that a camera has been removed,
334
        in case it was referring to it as a viewer.
335
        */
336
        void _notifyCameraRemoved(const Camera* cam);
337
338
        /** Indicates whether this target is the primary window. The
339
            primary window is special in that it is destroyed when
340
            ogre is shut down, and cannot be destroyed directly.
341
            This is the case because it holds the context for vertex,
342
            index buffers and textures.
343
        */
344
0
        virtual bool isPrimary(void) const { return false; }
345
346
    /** Indicates whether stereo is currently enabled for this target. Default is false. */
347
0
    virtual bool isStereoEnabled(void) const { return mStereoEnabled; }
348
    
349
        /** Indicates whether on rendering, linear colour space is converted to 
350
            sRGB gamma colour space. This is the exact opposite conversion of
351
            what is indicated by Texture::isHardwareGammaEnabled, and can only
352
            be enabled on creation of the render target. For render windows, it's
353
            enabled through the 'gamma' creation misc parameter. For textures, 
354
            it is enabled through the hwGamma parameter to the create call.
355
        */
356
0
        bool isHardwareGammaEnabled() const { return mHwGamma; }
357
358
        /** Indicates whether multisampling is performed on rendering and at what level.
359
        */
360
0
        uint getFSAA() const { return mFSAA; }
361
362
        /// RenderSystem specific FSAA option. See @ref RenderSystem::_createRenderWindow for details.
363
0
        const String& getFSAAHint() const { return mFSAAHint; }
364
365
        /** Set the level of multisample AA to be used if hardware support it.
366
            This option will be ignored if the hardware does not support it 
367
            or setting can not be changed on the fly on per-target level. 
368
            @param fsaa The number of samples
369
            @param fsaaHint @copybrief getFSAAHint
370
        */
371
0
        virtual void setFSAA(uint fsaa, const String& fsaaHint) { }
372
373
        /** Method for manual management of rendering : fires 'preRenderTargetUpdate'
374
            and initialises statistics etc.
375
376
        <ul>
377
        <li>_beginUpdate resets statistics and fires 'preRenderTargetUpdate'.</li>
378
        <li>_updateViewport renders the given viewport (even if it is not autoupdated),
379
        fires preViewportUpdate and postViewportUpdate and manages statistics.</li>
380
        <li>_updateAutoUpdatedViewports renders only viewports that are auto updated,
381
        fires preViewportUpdate and postViewportUpdate and manages statistics.</li>
382
        <li>_endUpdate() ends statistics calculation and fires postRenderTargetUpdate.</li>
383
        </ul>
384
        you can use it like this for example :
385
        <pre>
386
            renderTarget->_beginUpdate();
387
            renderTarget->_updateViewport(1); // which is not auto updated
388
            renderTarget->_updateViewport(2); // which is not auto updated
389
            renderTarget->_updateAutoUpdatedViewports();
390
            renderTarget->_endUpdate();
391
            renderTarget->swapBuffers();
392
        </pre>
393
            Please note that in that case, the zorder may not work as you expect,
394
            since you are responsible for calling _updateViewport in the correct order.
395
        */
396
        virtual void _beginUpdate();
397
398
        /** Method for manual management of rendering - renders the given 
399
        viewport (even if it is not autoupdated)
400
401
        This also fires preViewportUpdate and postViewportUpdate, and manages statistics.
402
        You should call it between _beginUpdate() and _endUpdate().
403
        @see _beginUpdate for more details.
404
        @param zorder The zorder of the viewport to update.
405
        @param updateStatistics Whether you want to update statistics or not.
406
        */
407
        void _updateViewport(int zorder, bool updateStatistics = true)
408
0
        {
409
0
            _updateViewport(getViewportByZOrder(zorder), updateStatistics);
410
0
        }
411
412
        /** Method for manual management of rendering - renders the given viewport (even if it is not autoupdated)
413
414
        This also fires preViewportUpdate and postViewportUpdate, and manages statistics
415
        if needed. You should call it between _beginUpdate() and _endUpdate().
416
        @see _beginUpdate for more details.
417
        @param viewport The viewport you want to update, it must be bound to the rendertarget.
418
        @param updateStatistics Whether you want to update statistics or not.
419
        */
420
        virtual void _updateViewport(Viewport* viewport, bool updateStatistics = true);
421
422
        /** Method for manual management of rendering - renders only viewports that are auto updated
423
424
        This also fires preViewportUpdate and postViewportUpdate, and manages statistics.
425
        You should call it between _beginUpdate() and _endUpdate().
426
        See _beginUpdate for more details.
427
        @param updateStatistics Whether you want to update statistics or not.
428
        @see _beginUpdate()
429
        */
430
        void _updateAutoUpdatedViewports(bool updateStatistics = true);
431
        
432
        /** Method for manual management of rendering - finishes statistics calculation 
433
            and fires 'postRenderTargetUpdate'.
434
435
        You should call it after a _beginUpdate
436
        @see _beginUpdate for more details.
437
        */
438
        virtual void _endUpdate();
439
440
    protected:
441
        /// The name of this target.
442
        String mName;
443
        /// The priority of the render target.
444
        uchar mPriority;
445
446
        uint32 mWidth;
447
        uint32 mHeight;
448
        uint16       mDepthBufferPoolId;
449
        DepthBuffer *mDepthBuffer;
450
451
        // Stats
452
        FrameStats mStats;
453
        
454
        Timer* mTimer ;
455
        unsigned long mLastSecond;
456
        unsigned long mLastTime;
457
        size_t mFrameCount;
458
459
        bool mActive;
460
        bool mAutoUpdate;
461
        // Hardware sRGB gamma conversion done on write?
462
        bool mHwGamma;
463
        // FSAA performed?
464
        uint mFSAA;
465
        String mFSAAHint;
466
    bool mStereoEnabled;
467
468
        virtual void updateStats(void);
469
470
        typedef std::map<int, Viewport*> ViewportList;
471
        /// List of viewports, map on Z-order
472
        ViewportList mViewportList;
473
474
        typedef std::vector<RenderTargetListener*> RenderTargetListenerList;
475
        RenderTargetListenerList mListeners;
476
    
477
478
        /// internal method for firing events
479
        virtual void firePreUpdate(void);
480
        /// internal method for firing events
481
        virtual void firePostUpdate(void);
482
        /// internal method for firing events
483
        virtual void fireViewportPreUpdate(Viewport* vp);
484
        /// internal method for firing events
485
        virtual void fireViewportPostUpdate(Viewport* vp);
486
        /// internal method for firing events
487
        virtual void fireViewportAdded(Viewport* vp);
488
        /// internal method for firing events
489
        void fireViewportRemoved(Viewport* vp);
490
        
491
        /// Internal implementation of update()
492
        virtual void updateImpl();
493
    };
494
    /** @} */
495
    /** @} */
496
497
} // Namespace
498
499
#include "OgreHeaderSuffix.h"
500
501
#endif