Coverage Report

Created: 2026-12-01 06:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/ogre/OgreMain/src/OgreRenderSystem.cpp
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
#include "OgrePrerequisites.h"
29
#include "OgreStableHeaders.h"
30
// RenderSystem implementation
31
// Note that most of this class is abstract since
32
//  we cannot know how to implement the behaviour without
33
//  being aware of the 3D API. However there are a few
34
//  simple functions which can have a base implementation
35
36
#include "OgreHardwareOcclusionQuery.h"
37
#include "OgreComponents.h"
38
39
#ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM
40
#include "OgreRTShaderConfig.h"
41
#endif
42
43
namespace Ogre {
44
45
    RenderSystem::Listener* RenderSystem::msSharedEventListener = 0;
46
47
    static const TexturePtr sNullTexPtr;
48
49
    //-----------------------------------------------------------------------
50
    RenderSystem::RenderSystem()
51
0
        : mActiveRenderTarget(0)
52
0
        , mTextureManager(0)
53
0
        , mActiveViewport(0)
54
        // This means CULL clockwise vertices, i.e. front of poly is counter-clockwise
55
        // This makes it the same as OpenGL and other right-handed systems
56
0
        , mCullingMode(CULL_CLOCKWISE)
57
0
        , mBatchCount(0)
58
0
        , mFaceCount(0)
59
0
        , mVertexCount(0)
60
0
        , mInvertVertexWinding(false)
61
0
        , mIsReverseDepthBufferEnabled(false)
62
0
        , mDisabledTexUnitsFrom(0)
63
0
        , mCurrentPassIterationCount(0)
64
0
        , mCurrentPassIterationNum(0)
65
0
        , mDerivedDepthBias(false)
66
0
        , mDerivedDepthBiasBase(0.0f)
67
0
        , mDerivedDepthBiasMultiplier(0.0f)
68
0
        , mDerivedDepthBiasSlopeScale(0.0f)
69
0
        , mClipPlanesDirty(true)
70
0
        , mRealCapabilities(0)
71
0
        , mCurrentCapabilities(0)
72
0
        , mUseCustomCapabilities(false)
73
0
        , mNativeShadingLanguageVersion(0)
74
0
        , mTexProjRelative(false)
75
0
        , mTexProjRelativeOrigin(Vector3::ZERO)
76
0
    {
77
0
        mEventNames.push_back("RenderSystemCapabilitiesCreated");
78
0
    }
79
80
    void RenderSystem::initFixedFunctionParams()
81
0
    {
82
0
        if(mFixedFunctionParams)
83
0
            return;
84
85
0
        GpuLogicalBufferStructPtr logicalBufferStruct(new GpuLogicalBufferStruct());
86
0
        mFixedFunctionParams.reset(new GpuProgramParameters);
87
0
        mFixedFunctionParams->_setLogicalIndexes(logicalBufferStruct);
88
0
        mFixedFunctionParams->setAutoConstant(0, GpuProgramParameters::ACT_WORLD_MATRIX);
89
0
        mFixedFunctionParams->setAutoConstant(4, GpuProgramParameters::ACT_VIEW_MATRIX);
90
0
        mFixedFunctionParams->setAutoConstant(8, GpuProgramParameters::ACT_PROJECTION_MATRIX);
91
0
        mFixedFunctionParams->setAutoConstant(12, GpuProgramParameters::ACT_SURFACE_AMBIENT_COLOUR);
92
0
        mFixedFunctionParams->setAutoConstant(13, GpuProgramParameters::ACT_SURFACE_DIFFUSE_COLOUR);
93
0
        mFixedFunctionParams->setAutoConstant(14, GpuProgramParameters::ACT_SURFACE_SPECULAR_COLOUR);
94
0
        mFixedFunctionParams->setAutoConstant(15, GpuProgramParameters::ACT_SURFACE_EMISSIVE_COLOUR);
95
0
        mFixedFunctionParams->setAutoConstant(16, GpuProgramParameters::ACT_SURFACE_SHININESS);
96
0
        mFixedFunctionParams->setAutoConstant(17, GpuProgramParameters::ACT_POINT_PARAMS);
97
0
        mFixedFunctionParams->setConstant(18, Vector4::ZERO); // ACT_FOG_PARAMS
98
0
        mFixedFunctionParams->setConstant(19, Vector4::ZERO); // ACT_FOG_COLOUR
99
0
        mFixedFunctionParams->setAutoConstant(20, GpuProgramParameters::ACT_AMBIENT_LIGHT_COLOUR);
100
101
        // allocate per light parameters. slots 21..69
102
0
        for(int i = 0; i < OGRE_MAX_SIMULTANEOUS_LIGHTS; i++)
103
0
        {
104
0
            size_t light_offset = 21 + i * 6;
105
0
            mFixedFunctionParams->setConstant(light_offset + 0, Vector4::ZERO); // position
106
0
            mFixedFunctionParams->setConstant(light_offset + 1, Vector4::ZERO); // direction
107
0
            mFixedFunctionParams->setConstant(light_offset + 2, Vector4::ZERO); // diffuse
108
0
            mFixedFunctionParams->setConstant(light_offset + 3, Vector4::ZERO); // specular
109
0
            mFixedFunctionParams->setConstant(light_offset + 4, Vector4::ZERO); // attenuation
110
0
            mFixedFunctionParams->setConstant(light_offset + 5, Vector4::ZERO); // spotlight
111
0
        }
112
0
    }
113
114
    void RenderSystem::setFFPLightParams(uint32 index, bool enabled)
115
0
    {
116
0
        if(!mFixedFunctionParams)
117
0
            return;
118
119
0
        size_t light_offset = 21 + 6 * index;
120
0
        if (!enabled)
121
0
        {
122
0
            mFixedFunctionParams->clearAutoConstant(light_offset + 0);
123
0
            mFixedFunctionParams->clearAutoConstant(light_offset + 1);
124
0
            mFixedFunctionParams->clearAutoConstant(light_offset + 2);
125
0
            mFixedFunctionParams->clearAutoConstant(light_offset + 3);
126
0
            mFixedFunctionParams->clearAutoConstant(light_offset + 4);
127
0
            mFixedFunctionParams->clearAutoConstant(light_offset + 5);
128
0
            return;
129
0
        }
130
0
        mFixedFunctionParams->setAutoConstant(light_offset + 0, GpuProgramParameters::ACT_LIGHT_POSITION, index);
131
0
        mFixedFunctionParams->setAutoConstant(light_offset + 1, GpuProgramParameters::ACT_LIGHT_DIRECTION, index);
132
0
        mFixedFunctionParams->setAutoConstant(light_offset + 2, GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR, index);
133
0
        mFixedFunctionParams->setAutoConstant(light_offset + 3, GpuProgramParameters::ACT_LIGHT_SPECULAR_COLOUR, index);
134
0
        mFixedFunctionParams->setAutoConstant(light_offset + 4, GpuProgramParameters::ACT_LIGHT_ATTENUATION, index);
135
0
        mFixedFunctionParams->setAutoConstant(light_offset + 5, GpuProgramParameters::ACT_SPOTLIGHT_PARAMS, index);
136
0
    }
137
138
    const HardwareBufferPtr& RenderSystem::updateDefaultUniformBuffer(GpuProgramType gptype, const ConstantList& params)
139
0
    {
140
0
        auto& ubo = mUniformBuffer[gptype];
141
0
        if (!ubo || ubo->getSizeInBytes() < params.size())
142
0
        {
143
0
            ubo = HardwareBufferManager::getSingleton().createUniformBuffer(params.size());
144
0
        }
145
146
0
        ubo->writeData(0, params.size(), params.data(), true);
147
148
0
        return ubo;
149
0
    }
150
    //-----------------------------------------------------------------------
151
    RenderSystem::~RenderSystem()
152
0
    {
153
0
        shutdown();
154
0
        OGRE_DELETE mRealCapabilities;
155
0
        mRealCapabilities = 0;
156
        // Current capabilities managed externally
157
0
        mCurrentCapabilities = 0;
158
0
    }
159
160
    RenderWindowDescription RenderSystem::getRenderWindowDescription() const
161
0
    {
162
0
        RenderWindowDescription ret;
163
0
        auto& miscParams = ret.miscParams;
164
165
0
        auto end = mOptions.end();
166
167
0
        auto opt = mOptions.find("Full Screen");
168
0
        if (opt == end)
169
0
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Can't find 'Full Screen' option");
170
171
0
        ret.useFullScreen = StringConverter::parseBool(opt->second.currentValue);
172
173
0
        opt = mOptions.find("Video Mode");
174
0
        if (opt == end)
175
0
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Can't find 'Video Mode' option");
176
177
0
        StringStream mode(opt->second.currentValue);
178
0
        String token;
179
180
0
        mode >> ret.width;
181
0
        mode >> token; // 'x' as seperator between width and height
182
0
        mode >> ret.height;
183
184
        // backend specific options. Presence determined by getConfigOptions
185
0
        mode >> token; // '@' as seperator between bpp on D3D
186
0
        if(!mode.eof())
187
0
        {
188
0
            uint32 bpp;
189
0
            mode >> bpp;
190
0
            miscParams.emplace("colourDepth", std::to_string(bpp));
191
0
        }
192
193
0
        if((opt = mOptions.find("FSAA")) != end)
194
0
        {
195
0
            StringStream fsaaMode(opt->second.currentValue);
196
0
            uint32_t fsaa;
197
0
            fsaaMode >> fsaa;
198
0
            miscParams.emplace("FSAA", std::to_string(fsaa));
199
200
            // D3D specific
201
0
            if(!fsaaMode.eof())
202
0
            {
203
0
                String hint;
204
0
                fsaaMode >> hint;
205
0
                miscParams.emplace("FSAAHint", hint);
206
0
            }
207
0
        }
208
209
0
        if((opt = mOptions.find("VSync")) != end)
210
0
            miscParams.emplace("vsync", opt->second.currentValue);
211
212
0
        if((opt = mOptions.find("sRGB Gamma Conversion")) != end)
213
0
            miscParams.emplace("gamma", opt->second.currentValue);
214
215
0
        if((opt = mOptions.find("HDR Display")) != end)
216
0
            miscParams.emplace("hdrDisplay", opt->second.currentValue);
217
218
0
        if((opt = mOptions.find("Colour Depth")) != end)
219
0
            miscParams.emplace("colourDepth", opt->second.currentValue);
220
221
0
        if((opt = mOptions.find("VSync Interval")) != end)
222
0
            miscParams.emplace("vsyncInterval", opt->second.currentValue);
223
224
0
        if((opt = mOptions.find("Display Frequency")) != end)
225
0
            miscParams.emplace("displayFrequency", opt->second.currentValue);
226
227
        // "Auto" means the window provider detects the scale of the monitor the
228
        // window is created on; there is no usable value to pass along.
229
0
        if ((opt = mOptions.find("Content Scaling Factor")) != end && opt->second.currentValue != "Auto")
230
0
            miscParams["contentScalingFactor"] = opt->second.currentValue;
231
232
0
        if((opt = mOptions.find("Rendering Device")) != end)
233
0
        {
234
            // try to parse "Monitor-NN-"
235
0
            auto start = opt->second.currentValue.find('-') + 1;
236
0
            auto len = opt->second.currentValue.find('-', start) - start;
237
0
            if(start != String::npos)
238
0
                miscParams["monitorIndex"] = opt->second.currentValue.substr(start, len);
239
0
        }
240
241
#if OGRE_NO_QUAD_BUFFER_STEREO == 0
242
        if((opt = mOptions.find("Frame Sequential Stereo")) != end)
243
            miscParams["stereoMode"] = opt->second.currentValue;
244
#endif
245
0
        return ret;
246
0
    }
247
248
    //-----------------------------------------------------------------------
249
    void RenderSystem::_initRenderTargets(void)
250
0
    {
251
252
        // Init stats
253
0
        for (auto& rt : mRenderTargets)
254
0
        {
255
0
            rt.second->resetStatistics();
256
0
        }
257
0
    }
258
    //-----------------------------------------------------------------------
259
    void RenderSystem::_updateAllRenderTargets(bool swapBuffers)
260
0
    {
261
        // Update all in order of priority
262
        // This ensures render-to-texture targets get updated before render windows
263
0
        for (auto& rt : mPrioritisedRenderTargets)
264
0
        {
265
0
            if (rt.second->isActive() && rt.second->isAutoUpdated())
266
0
                rt.second->update(swapBuffers);
267
0
        }
268
0
    }
269
    //-----------------------------------------------------------------------
270
    void RenderSystem::_swapAllRenderTargetBuffers()
271
0
    {
272
0
        OgreProfile("_swapAllRenderTargetBuffers");
273
        // Update all in order of priority
274
        // This ensures render-to-texture targets get updated before render windows
275
0
        for (auto& rt : mPrioritisedRenderTargets)
276
0
        {
277
0
            if (rt.second->isActive() && rt.second->isAutoUpdated())
278
0
                rt.second->swapBuffers();
279
0
        }
280
0
    }
281
    //-----------------------------------------------------------------------
282
    void RenderSystem::_initialise()
283
0
    {
284
        // Have I been registered by call to Root::setRenderSystem?
285
        /** Don't do this anymore, just allow via Root
286
        RenderSystem* regPtr = Root::getSingleton().getRenderSystem();
287
        if (!regPtr || regPtr != this)
288
            // Register self - library user has come to me direct
289
            Root::getSingleton().setRenderSystem(this);
290
        */
291
292
293
        // Subclasses should take it from here
294
        // They should ALL call this superclass method from
295
        //   their own initialise() implementations.
296
        
297
0
        mProgramBound.fill(false);
298
0
    }
299
300
    //---------------------------------------------------------------------------------------------
301
    void RenderSystem::useCustomRenderSystemCapabilities(RenderSystemCapabilities* capabilities)
302
0
    {
303
0
        if (mRealCapabilities)
304
0
        {
305
0
            OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR,
306
0
                        "Custom render capabilities must be set before the RenderSystem is initialised");
307
0
        }
308
309
0
        if (capabilities->getRenderSystemName() != getName())
310
0
        {
311
0
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
312
0
                        "Trying to use RenderSystemCapabilities that were created for a different RenderSystem");
313
0
        }
314
315
0
        mCurrentCapabilities = capabilities;
316
0
        mUseCustomCapabilities = true;
317
0
    }
318
319
    //---------------------------------------------------------------------------------------------
320
    RenderWindow* RenderSystem::_createRenderWindow(const String& name, unsigned int width,
321
                                                    unsigned int height, bool fullScreen,
322
                                                    const NameValuePairList* miscParams)
323
0
    {
324
0
        if (mRenderTargets.find(name) != mRenderTargets.end())
325
0
        {
326
0
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Window with name '" + name + "' already exists");
327
0
        }
328
329
        // Log a message
330
0
        StringStream ss;
331
0
        ss << "RenderSystem::_createRenderWindow \"" << name << "\", " <<
332
0
            width << "x" << height << " ";
333
0
        if (fullScreen)
334
0
            ss << "fullscreen ";
335
0
        else
336
0
            ss << "windowed ";
337
338
0
        if (miscParams)
339
0
        {
340
0
            ss << " miscParams: ";
341
0
            NameValuePairList::const_iterator it;
342
0
            for (const auto& p : *miscParams)
343
0
            {
344
0
                ss << p.first << "=" << p.second << " ";
345
0
            }
346
0
        }
347
0
        LogManager::getSingleton().logMessage(ss.str());
348
349
0
        return NULL;
350
0
    }
351
    //---------------------------------------------------------------------------------------------
352
    void RenderSystem::destroyRenderWindow(const String& name)
353
0
    {
354
0
        destroyRenderTarget(name);
355
0
    }
356
    //---------------------------------------------------------------------------------------------
357
    void RenderSystem::destroyRenderTexture(const String& name)
358
0
    {
359
0
        destroyRenderTarget(name);
360
0
    }
361
    //---------------------------------------------------------------------------------------------
362
    void RenderSystem::destroyRenderTarget(const String& name)
363
0
    {
364
0
        RenderTarget* rt = detachRenderTarget(name);
365
0
        OGRE_DELETE rt;
366
0
    }
367
    //---------------------------------------------------------------------------------------------
368
    void RenderSystem::attachRenderTarget( RenderTarget &target )
369
0
    {
370
0
        assert( target.getPriority() < OGRE_NUM_RENDERTARGET_GROUPS );
371
372
0
        mRenderTargets.emplace(target.getName(), &target);
373
0
        mPrioritisedRenderTargets.emplace(target.getPriority(), &target);
374
0
    }
375
376
    //---------------------------------------------------------------------------------------------
377
    RenderTarget * RenderSystem::getRenderTarget( const String &name )
378
0
    {
379
0
        RenderTargetMap::iterator it = mRenderTargets.find( name );
380
0
        RenderTarget *ret = NULL;
381
382
0
        if( it != mRenderTargets.end() )
383
0
        {
384
0
            ret = it->second;
385
0
        }
386
387
0
        return ret;
388
0
    }
389
390
    //---------------------------------------------------------------------------------------------
391
    RenderTarget * RenderSystem::detachRenderTarget( const String &name )
392
0
    {
393
0
        RenderTargetMap::iterator it = mRenderTargets.find( name );
394
0
        RenderTarget *ret = NULL;
395
396
0
        if( it != mRenderTargets.end() )
397
0
        {
398
0
            ret = it->second;
399
            
400
            /* Remove the render target from the priority groups. */
401
0
            RenderTargetPriorityMap::iterator itarg, itargend;
402
0
            itargend = mPrioritisedRenderTargets.end();
403
0
            for( itarg = mPrioritisedRenderTargets.begin(); itarg != itargend; ++itarg )
404
0
            {
405
0
                if( itarg->second == ret ) {
406
0
                    mPrioritisedRenderTargets.erase( itarg );
407
0
                    break;
408
0
                }
409
0
            }
410
411
0
            mRenderTargets.erase( it );
412
0
        }
413
        /// If detached render target is the active render target, reset active render target
414
0
        if(ret == mActiveRenderTarget)
415
0
            mActiveRenderTarget = 0;
416
417
0
        return ret;
418
0
    }
419
    //-----------------------------------------------------------------------
420
    Viewport* RenderSystem::_getViewport(void)
421
0
    {
422
0
        return mActiveViewport;
423
0
    }
424
    //-----------------------------------------------------------------------
425
    void RenderSystem::_setTextureUnitSettings(size_t texUnit, TextureUnitState& tl)
426
0
    {
427
0
        if(texUnit >= getCapabilities()->getNumTextureUnits())
428
0
            return;
429
430
        // This method is only ever called to set a texture unit to valid details
431
        // The method _disableTextureUnit is called to turn a unit off
432
0
        TexturePtr tex = tl._getTexturePtr();
433
0
        if(!tex || tl.isTextureLoadFailing())
434
0
            tex = mTextureManager->_getWarningTexture();
435
436
0
        if(tl.getUnorderedAccessMipLevel() > -1)
437
0
        {
438
0
            tex->createShaderAccessPoint(texUnit, TA_READ_WRITE, tl.getUnorderedAccessMipLevel());
439
0
            return;
440
0
        }
441
442
        // Bind texture (may be blank)
443
0
        _setTexture(texUnit, true, tex);
444
445
0
        _setSampler(texUnit, *tl.getSampler());
446
447
0
        if(!getCapabilities()->hasCapability(RSC_FIXED_FUNCTION))
448
0
            return;
449
450
        // Set texture coordinate set
451
0
        _setTextureCoordSet(texUnit, tl.getTextureCoordSet());
452
453
        // Set blend modes
454
        // Note, colour before alpha is important
455
0
        _setTextureBlendMode(texUnit, tl.getColourBlendMode());
456
0
        _setTextureBlendMode(texUnit, tl.getAlphaBlendMode());
457
458
0
        auto calcMode = tl._deriveTexCoordCalcMethod();
459
0
        if(calcMode == TEXCALC_PROJECTIVE_TEXTURE)
460
0
        {
461
0
            _setTextureCoordCalculation(texUnit, calcMode, tl.getProjectiveTexturingFrustum());
462
0
        }
463
0
        else
464
0
        {
465
0
            _setTextureCoordCalculation(texUnit, calcMode);
466
0
        }
467
468
        // Change tetxure matrix 
469
0
        _setTextureMatrix(texUnit, tl.getTextureTransform());
470
0
    }
471
    //-----------------------------------------------------------------------
472
    void RenderSystem::_disableTextureUnit(size_t texUnit)
473
0
    {
474
0
        _setTexture(texUnit, false, sNullTexPtr);
475
0
    }
476
    //---------------------------------------------------------------------
477
    void RenderSystem::_disableTextureUnitsFrom(size_t texUnit)
478
0
    {
479
0
        size_t disableTo = OGRE_MAX_TEXTURE_LAYERS;
480
0
        if (disableTo > mDisabledTexUnitsFrom)
481
0
            disableTo = mDisabledTexUnitsFrom;
482
0
        mDisabledTexUnitsFrom = texUnit;
483
0
        for (size_t i = texUnit; i < disableTo; ++i)
484
0
        {
485
0
            _disableTextureUnit(i);
486
0
        }
487
0
    }
488
    //---------------------------------------------------------------------
489
    void RenderSystem::_cleanupDepthBuffers( bool bCleanManualBuffers )
490
0
    {
491
0
        for (auto& m : mDepthBufferPool)
492
0
        {
493
0
            for (auto *b : m.second)
494
0
            {
495
0
                if (bCleanManualBuffers || !b->isManual())
496
0
                    delete b;
497
0
            }
498
0
            m.second.clear();
499
0
        }
500
0
        mDepthBufferPool.clear();
501
0
    }
502
    //-----------------------------------------------------------------------
503
    void RenderSystem::_beginFrame(void)
504
0
    {
505
0
        if (!mActiveViewport)
506
0
            OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Cannot begin frame - no viewport selected.");
507
0
    }
508
    //-----------------------------------------------------------------------
509
    CullingMode RenderSystem::_getCullingMode(void) const
510
0
    {
511
0
        return mCullingMode;
512
0
    }
513
    //-----------------------------------------------------------------------
514
    void RenderSystem::setDepthBufferFor( RenderTarget *renderTarget )
515
0
    {
516
0
        uint16 poolNum = renderTarget->getDepthBufferPool();
517
0
        if( poolNum == RBP_NONE )
518
0
            return; //RenderTarget explicitly requested no depth buffer
519
520
0
        uint32 poolId = HashCombine(0, poolNum);
521
0
        poolId = HashCombine(poolId, renderTarget->getFSAA());
522
523
0
        if(!getCapabilities()->hasCapability(RSC_RTT_INDEPENDENT_BUFFER_SIZE))
524
0
        {
525
            //Depth buffer must be EXACT same size as RT
526
0
            poolId = HashCombine(poolId, renderTarget->getWidth());
527
0
            poolId = HashCombine(poolId, renderTarget->getHeight());
528
0
        }
529
530
        //Find a depth buffer in the pool
531
0
        bool bAttached = false;
532
0
        for (auto& d : mDepthBufferPool[poolId]) {
533
0
            bAttached = renderTarget->attachDepthBuffer(d);
534
0
            if (bAttached) break;
535
0
        }
536
537
        //Not found yet? Create a new one!
538
0
        if( !bAttached )
539
0
        {
540
0
            DepthBuffer *newDepthBuffer = _createDepthBufferFor( renderTarget );
541
542
0
            if( newDepthBuffer )
543
0
            {
544
0
                mDepthBufferPool[poolId].push_back( newDepthBuffer );
545
546
0
                bAttached = renderTarget->attachDepthBuffer( newDepthBuffer );
547
548
0
                OgreAssert( bAttached ,"A new DepthBuffer for a RenderTarget was created, but after creation"
549
0
                                     " it says it's incompatible with that RT" );
550
0
            }
551
0
            else
552
0
                LogManager::getSingleton().logWarning( "Couldn't create a suited DepthBuffer"
553
0
                                                       "for RT: " + renderTarget->getName());
554
0
        }
555
0
    }
556
    //-----------------------------------------------------------------------
557
    bool RenderSystem::isReverseDepthBufferEnabled() const
558
0
    {
559
0
        return mIsReverseDepthBufferEnabled;
560
0
    }
561
    //-----------------------------------------------------------------------
562
    void RenderSystem::reinitialise()
563
0
    {
564
0
        shutdown();
565
0
        _initialise();
566
0
    }
567
568
    void RenderSystem::shutdown(void)
569
0
    {
570
0
        for (auto& q : mHwOcclusionQueries)
571
0
        {
572
0
            OGRE_DELETE q;
573
0
        }
574
0
        mHwOcclusionQueries.clear();
575
576
0
        _cleanupDepthBuffers();
577
578
        // Remove all the render targets. Destroy primary target last since others may depend on it.
579
        // Keep mRenderTargets valid all the time, so that render targets could receive
580
        // appropriate notifications, for example FBO based about GL context destruction.
581
0
        RenderTarget* primary = 0;
582
0
        for (RenderTargetMap::iterator it = mRenderTargets.begin(); it != mRenderTargets.end(); /* note - no increment */)
583
0
        {
584
0
            RenderTarget* current = it->second;
585
0
            if (!primary && current->isPrimary())
586
0
            {
587
0
                ++it;
588
0
                primary = current;
589
0
            }
590
0
            else
591
0
            {
592
0
                it = mRenderTargets.erase(it);
593
0
                OGRE_DELETE current;
594
0
            }
595
0
        }
596
0
        OGRE_DELETE primary;
597
0
        mRenderTargets.clear();
598
599
0
        mPrioritisedRenderTargets.clear();
600
0
    }
601
602
    void RenderSystem::_setProjectionMatrix(Matrix4 m)
603
0
    {
604
0
        if (!mFixedFunctionParams) return;
605
606
0
        if (mActiveRenderTarget->requiresTextureFlipping())
607
0
        {
608
            // Invert transformed y
609
0
            m[1][0] = -m[1][0];
610
0
            m[1][1] = -m[1][1];
611
0
            m[1][2] = -m[1][2];
612
0
            m[1][3] = -m[1][3];
613
0
        }
614
615
0
        mFixedFunctionParams->setConstant(8, m);
616
0
        applyFixedFunctionParams(mFixedFunctionParams, GPV_GLOBAL);
617
0
    }
618
    //-----------------------------------------------------------------------
619
    void RenderSystem::_beginGeometryCount(void)
620
0
    {
621
0
        mBatchCount = mFaceCount = mVertexCount = 0;
622
0
    }
623
    //-----------------------------------------------------------------------
624
    void RenderSystem::_render(const RenderOperation& op)
625
0
    {
626
        // Update stats
627
0
        size_t val;
628
629
0
        if (op.useIndexes)
630
0
            val = op.indexData->indexCount;
631
0
        else
632
0
            val = op.vertexData->vertexCount;
633
634
0
        size_t trueInstanceNum = std::max<size_t>(op.numberOfInstances,1);
635
0
        val *= trueInstanceNum;
636
637
        // account for a pass having multiple iterations
638
0
        if (mCurrentPassIterationCount > 1)
639
0
            val *= mCurrentPassIterationCount;
640
0
        mCurrentPassIterationNum = 0;
641
642
0
        switch(op.operationType)
643
0
        {
644
0
        case RenderOperation::OT_TRIANGLE_LIST:
645
0
            mFaceCount += (val / 3);
646
0
            break;
647
0
        case RenderOperation::OT_TRIANGLE_LIST_ADJ:
648
0
            mFaceCount += (val / 6);
649
0
            break;
650
0
        case RenderOperation::OT_TRIANGLE_STRIP_ADJ:
651
0
            mFaceCount += (val / 2 - 2);
652
0
            break;
653
0
        case RenderOperation::OT_TRIANGLE_STRIP:
654
0
        case RenderOperation::OT_TRIANGLE_FAN:
655
0
            mFaceCount += (val - 2);
656
0
            break;
657
0
        default:
658
0
            break;
659
0
        }
660
661
0
        mVertexCount += op.vertexData->vertexCount * trueInstanceNum;
662
0
        mBatchCount += mCurrentPassIterationCount;
663
664
        // sort out clip planes
665
        // have to do it here in case of matrix issues
666
0
        if (mClipPlanesDirty)
667
0
        {
668
0
            setClipPlanesImpl(mClipPlanes);
669
0
            mClipPlanesDirty = false;
670
0
        }
671
0
    }
672
    //-----------------------------------------------------------------------
673
    void RenderSystem::setInvertVertexWinding(bool invert)
674
0
    {
675
0
        mInvertVertexWinding = invert;
676
0
    }
677
    //-----------------------------------------------------------------------
678
    bool RenderSystem::getInvertVertexWinding(void) const
679
0
    {
680
0
        return mInvertVertexWinding;
681
0
    }
682
    //---------------------------------------------------------------------
683
    void RenderSystem::setClipPlanes(const PlaneList& clipPlanes)
684
0
    {
685
0
        if (clipPlanes != mClipPlanes)
686
0
        {
687
0
            mClipPlanes = clipPlanes;
688
0
            mClipPlanesDirty = true;
689
0
        }
690
0
    }
691
    //-----------------------------------------------------------------------
692
    void RenderSystem::_notifyCameraRemoved(const Camera* cam)
693
0
    {
694
0
        for (auto& rt : mRenderTargets)
695
0
        {
696
0
            auto target = rt.second;
697
0
            target->_notifyCameraRemoved(cam);
698
0
        }
699
0
    }
700
701
    //---------------------------------------------------------------------
702
    bool RenderSystem::updatePassIterationRenderState(void)
703
0
    {
704
0
        if (mCurrentPassIterationCount <= 1)
705
0
            return false;
706
707
0
        --mCurrentPassIterationCount;
708
0
        ++mCurrentPassIterationNum;
709
710
        // Update derived depth bias for the next iteration
711
0
        if (mDerivedDepthBias)
712
0
        {
713
0
            _setDepthBias(mDerivedDepthBiasBase + mDerivedDepthBiasMultiplier * mCurrentPassIterationNum,
714
0
                          mDerivedDepthBiasSlopeScale);
715
0
        }
716
717
0
        const uint16 mask = GPV_PASS_ITERATION_NUMBER;
718
719
0
        for (int i = 0; i < GPT_COUNT; i++)
720
0
        {
721
0
            if (!mActiveParameters[i])
722
0
                continue;
723
0
            mActiveParameters[i]->incPassIterationNumber();
724
0
            bindGpuProgramParameters(GpuProgramType(i), mActiveParameters[i], mask);
725
0
        }
726
727
0
        return true;
728
0
    }
729
730
    //-----------------------------------------------------------------------
731
    void RenderSystem::setSharedListener(Listener* listener)
732
0
    {
733
0
        assert(msSharedEventListener == NULL || listener == NULL); // you can set or reset, but for safety not directly override
734
0
        msSharedEventListener = listener;
735
0
    }
736
    //-----------------------------------------------------------------------
737
    RenderSystem::Listener* RenderSystem::getSharedListener(void)
738
0
    {
739
0
        return msSharedEventListener;
740
0
    }
741
    //-----------------------------------------------------------------------
742
    void RenderSystem::addListener(Listener* l)
743
0
    {
744
0
        mEventListeners.push_back(l);
745
0
    }
746
    //-----------------------------------------------------------------------
747
    void RenderSystem::removeListener(Listener* l)
748
0
    {
749
0
        mEventListeners.remove(l);
750
0
    }
751
    //-----------------------------------------------------------------------
752
    void RenderSystem::fireEvent(const String& name, const NameValuePairList* params)
753
0
    {
754
0
        for(auto& el : mEventListeners)
755
0
        {
756
0
            el->eventOccurred(name, params);
757
0
        }
758
759
0
        if(msSharedEventListener)
760
0
            msSharedEventListener->eventOccurred(name, params);
761
0
    }
762
    //-----------------------------------------------------------------------
763
    void RenderSystem::destroyHardwareOcclusionQuery( HardwareOcclusionQuery *hq)
764
0
    {
765
0
        auto end = mHwOcclusionQueries.end();
766
0
        auto i = std::find(mHwOcclusionQueries.begin(), end, hq);
767
0
        if (i != end)
768
0
        {
769
0
            mHwOcclusionQueries.erase(i);
770
0
            OGRE_DELETE hq;
771
0
        }
772
0
    }
773
    //-----------------------------------------------------------------------
774
    void RenderSystem::bindGpuProgram(GpuProgram* prg)
775
0
    {
776
0
        auto gptype = prg->getType();
777
        // mark clip planes dirty if changed (programmable can change space)
778
0
        if(gptype == GPT_VERTEX_PROGRAM && !mClipPlanes.empty() && !mProgramBound[gptype])
779
0
            mClipPlanesDirty = true;
780
781
0
        mProgramBound[gptype] = true;
782
0
    }
783
    //-----------------------------------------------------------------------
784
    void RenderSystem::unbindGpuProgram(GpuProgramType gptype)
785
0
    {
786
        // mark clip planes dirty if changed (programmable can change space)
787
0
        if(gptype == GPT_VERTEX_PROGRAM && !mClipPlanes.empty() && mProgramBound[gptype])
788
0
            mClipPlanesDirty = true;
789
790
0
        mProgramBound[gptype] = false;
791
0
    }
792
    //-----------------------------------------------------------------------
793
    bool RenderSystem::isGpuProgramBound(GpuProgramType gptype)
794
0
    {
795
0
        return mProgramBound[gptype];
796
0
    }
797
    //---------------------------------------------------------------------
798
    void RenderSystem::_setTextureProjectionRelativeTo(bool enabled, const Vector3& pos)
799
0
    {
800
0
        mTexProjRelative = enabled;
801
0
        mTexProjRelativeOrigin = pos;
802
803
0
    }
804
    //---------------------------------------------------------------------
805
    const String& RenderSystem::_getDefaultViewportMaterialScheme( void ) const
806
0
    {
807
0
#ifdef RTSHADER_SYSTEM_BUILD_CORE_SHADERS
808
0
        if (!getCapabilities()->hasCapability(RSC_FIXED_FUNCTION))
809
0
        {
810
0
            return MSN_SHADERGEN;
811
0
        }
812
0
#endif
813
0
        return MSN_DEFAULT;
814
0
    }
815
    //---------------------------------------------------------------------
816
    void RenderSystem::setGlobalInstanceVertexBuffer(const HardwareVertexBufferSharedPtr& val)
817
0
    {
818
0
        OgreAssert(!val || val->isInstanceData(), "not an instance buffer");
819
0
        mSchemeInstancingData[_getDefaultViewportMaterialScheme()].vertexBuffer = val;
820
0
    }
821
    void RenderSystem::enableSchemeInstancing(const String& materialScheme, const HardwareVertexBufferPtr& buffer,
822
                                              VertexDeclaration* decl, uint32 instanceCount)
823
0
    {
824
0
        OgreAssert(!buffer || buffer->isInstanceData(), "not an instance buffer");
825
0
        OgreAssert(decl, "null vertex declaration");
826
0
        OgreAssert(instanceCount > 1, "instance count must be greater than 1");
827
0
        mSchemeInstancingData.emplace(materialScheme, GlobalInstancingData{buffer, decl, instanceCount});
828
0
    }
829
830
    //---------------------------------------------------------------------
831
    void RenderSystem::getCustomAttribute(const String& name, void* pData)
832
0
    {
833
0
        OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Attribute not found.", "RenderSystem::getCustomAttribute");
834
0
    }
835
836
    void RenderSystem::initConfigOptions()
837
0
    {
838
        // FS setting possibilities
839
0
        ConfigOption optFullScreen;
840
0
        optFullScreen.name = "Full Screen";
841
0
        optFullScreen.possibleValues.push_back( "No" );
842
0
        optFullScreen.possibleValues.push_back( "Yes" );
843
0
        optFullScreen.currentValue = optFullScreen.possibleValues[0];
844
0
        optFullScreen.immutable = false;
845
0
        mOptions[optFullScreen.name] = optFullScreen;
846
847
        // Video mode possibilities, can be overwritten by actual values
848
0
        ConfigOption optVideoMode;
849
0
        optVideoMode.name = "Video Mode";
850
0
        optVideoMode.possibleValues.push_back("1920 x 1080");
851
0
        optVideoMode.possibleValues.push_back("1280 x 720");
852
0
        optVideoMode.possibleValues.push_back("800 x 600");
853
0
        optVideoMode.currentValue = optVideoMode.possibleValues.back();
854
0
        optVideoMode.immutable = false;
855
0
        mOptions[optVideoMode.name] = optVideoMode;
856
857
0
        ConfigOption optVSync;
858
0
        optVSync.name = "VSync";
859
0
        optVSync.immutable = false;
860
0
        optVSync.possibleValues.push_back("No");
861
0
        optVSync.possibleValues.push_back("Yes");
862
0
        optVSync.currentValue = optVSync.possibleValues[1];
863
0
        mOptions[optVSync.name] = optVSync;
864
865
0
        ConfigOption optVSyncInterval;
866
0
        optVSyncInterval.name = "VSync Interval";
867
0
        optVSyncInterval.immutable = false;
868
0
        optVSyncInterval.possibleValues.push_back("1");
869
0
        optVSyncInterval.possibleValues.push_back("2");
870
0
        optVSyncInterval.possibleValues.push_back("3");
871
0
        optVSyncInterval.possibleValues.push_back("4");
872
0
        optVSyncInterval.currentValue = optVSyncInterval.possibleValues[0];
873
0
        mOptions[optVSyncInterval.name] = optVSyncInterval;
874
875
0
        ConfigOption optSRGB;
876
0
        optSRGB.name = "sRGB Gamma Conversion";
877
0
        optSRGB.immutable = false;
878
0
        optSRGB.possibleValues.push_back("No");
879
0
        optSRGB.possibleValues.push_back("Yes");
880
0
        optSRGB.currentValue = optSRGB.possibleValues[0];
881
0
        mOptions[optSRGB.name] = optSRGB;
882
883
0
        ConfigOption optHDRDisplay;
884
0
        optHDRDisplay.name = "HDR Display";
885
0
        optHDRDisplay.immutable = false;
886
0
        optHDRDisplay.possibleValues.push_back("No");
887
0
        optHDRDisplay.possibleValues.push_back("Yes");
888
0
        optHDRDisplay.currentValue = optHDRDisplay.possibleValues[0];
889
0
        mOptions[optHDRDisplay.name] = optHDRDisplay;
890
891
        // Windows are sized in view points while the backbuffer is allocated in
892
        // pixels. "Auto" lets the window provider detect the scale of the monitor
893
        // the window is created on; the list is for discoverability only, the
894
        // value can be anything the backend understands.
895
0
        if (mOptions.find("Content Scaling Factor") == mOptions.end())
896
0
        {
897
0
            ConfigOption optContentScaling;
898
0
            optContentScaling.name = "Content Scaling Factor";
899
0
            optContentScaling.immutable = false;
900
0
            optContentScaling.possibleValues = {"Auto", "1.0", "1.25", "1.5", "1.75", "2.0", "3.0"};
901
0
            optContentScaling.currentValue = optContentScaling.possibleValues.front();
902
0
            mOptions[optContentScaling.name] = optContentScaling;
903
0
        }
904
905
#if OGRE_NO_QUAD_BUFFER_STEREO == 0
906
        ConfigOption optStereoMode;
907
        optStereoMode.name = "Frame Sequential Stereo";
908
        optStereoMode.possibleValues.push_back("Off");
909
        optStereoMode.possibleValues.push_back("On");
910
        optStereoMode.currentValue = optStereoMode.possibleValues[0];
911
        optStereoMode.immutable = false;
912
913
        mOptions[optStereoMode.name] = optStereoMode;
914
#endif
915
0
    }
916
917
    CompareFunction RenderSystem::reverseCompareFunction(CompareFunction func)
918
0
    {
919
0
        switch(func)
920
0
        {
921
0
        default:
922
0
            return func;
923
0
        case CMPF_LESS:
924
0
            return CMPF_GREATER;
925
0
        case CMPF_LESS_EQUAL:
926
0
            return CMPF_GREATER_EQUAL;
927
0
        case CMPF_GREATER_EQUAL:
928
0
            return CMPF_LESS_EQUAL;
929
0
        case CMPF_GREATER:
930
0
            return CMPF_LESS;
931
0
        }
932
0
    }
933
934
    bool RenderSystem::flipFrontFace() const
935
0
    {
936
0
        return mInvertVertexWinding != mActiveRenderTarget->requiresTextureFlipping();
937
0
    }
938
939
    void RenderSystem::setStencilCheckEnabled(bool enabled)
940
0
    {
941
0
        mStencilState.enabled = enabled;
942
0
        if (!enabled)
943
0
            setStencilState(mStencilState);
944
0
    }
945
    void RenderSystem::setStencilBufferParams(CompareFunction func, uint32 refValue, uint32 compareMask,
946
                                              uint32 writeMask, StencilOperation stencilFailOp,
947
                                              StencilOperation depthFailOp, StencilOperation passOp,
948
                                              bool twoSidedOperation)
949
0
    {
950
0
        mStencilState.compareOp = func;
951
0
        mStencilState.referenceValue = refValue;
952
0
        mStencilState.compareMask = compareMask;
953
0
        mStencilState.writeMask = writeMask;
954
0
        mStencilState.stencilFailOp = stencilFailOp;
955
0
        mStencilState.depthFailOp = depthFailOp;
956
0
        mStencilState.depthStencilPassOp = passOp;
957
0
        mStencilState.twoSidedOperation = twoSidedOperation;
958
0
        if(mStencilState.enabled)
959
0
            setStencilState(mStencilState);
960
0
    }
961
}
962