| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839 |
- //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
- //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
- #include "BsGLRenderAPI.h"
- #include "RenderAPI/BsRenderAPI.h"
- #include "BsGLTextureManager.h"
- #include "BsGLIndexBuffer.h"
- #include "BsGLUtil.h"
- #include "GLSL/BsGLSLGpuProgram.h"
- #include "Error/BsException.h"
- #include "BsGLContext.h"
- #include "BsGLSupport.h"
- #include "RenderAPI/BsBlendState.h"
- #include "RenderAPI/BsRasterizerState.h"
- #include "RenderAPI/BsDepthStencilState.h"
- #include "BsGLRenderTexture.h"
- #include "BsGLRenderWindowManager.h"
- #include "GLSL/BsGLSLProgramPipelineManager.h"
- #include "BsGLVertexArrayObjectManager.h"
- #include "Managers/BsRenderStateManager.h"
- #include "RenderAPI/BsGpuParams.h"
- #include "BsGLGpuParamBlockBuffer.h"
- #include "CoreThread/BsCoreThread.h"
- #include "BsGLQueryManager.h"
- #include "Debug/BsDebug.h"
- #include "Profiling/BsRenderStats.h"
- #include "RenderAPI/BsGpuParamDesc.h"
- #include "BsGLGpuBuffer.h"
- #include "BsGLCommandBuffer.h"
- #include "BsGLCommandBufferManager.h"
- #include "BsGLTextureView.h"
- namespace bs { namespace ct
- {
- const char* MODULE_NAME = "BansheeGLRenderAPI.dll";
- const char* bs_get_gl_error_string(GLenum errorCode)
- {
- switch (errorCode)
- {
- case GL_INVALID_OPERATION: return "INVALID_OPERATION";
- case GL_INVALID_ENUM: return "INVALID_ENUM";
- case GL_INVALID_VALUE: return "INVALID_VALUE";
- case GL_OUT_OF_MEMORY: return "OUT_OF_MEMORY";
- case GL_INVALID_FRAMEBUFFER_OPERATION: return "INVALID_FRAMEBUFFER_OPERATION";
- }
- return nullptr;
- }
- void bs_check_gl_error(const char* function, const char* file, INT32 line)
- {
- GLenum errorCode = glGetError();
- if (errorCode != GL_NO_ERROR)
- {
- StringStream errorOutput;
- errorOutput << "OpenGL error in " << function << " [" << file << ":" << toString(line) << "]:\n";
- while (errorCode != GL_NO_ERROR)
- {
- const char* errorString = bs_get_gl_error_string(errorCode);
- if (errorString)
- errorOutput << "\t - " << errorString;
- errorCode = glGetError();
- }
- gDebug().logWarning(errorOutput.str());
- }
- }
- #if BS_OPENGL_4_3 || BS_OPENGLES_3_2
- void openGlErrorCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar
- *message, GLvoid *userParam);
- #endif
- /************************************************************************/
- /* PUBLIC INTERFACE */
- /************************************************************************/
- GLRenderAPI::GLRenderAPI()
- : mViewportNorm(0.0f, 0.0f, 1.0f, 1.0f)
- , mScissorTop(0), mScissorBottom(720), mScissorLeft(0), mScissorRight(1280)
- , mViewportLeft(0), mViewportTop(0), mViewportWidth(0), mViewportHeight(0)
- , mScissorEnabled(false)
- , mStencilReadMask(0xFFFFFFFF)
- , mStencilWriteMask(0xFFFFFFFF)
- , mStencilRefValue(0)
- , mStencilCompareFront(CMPF_ALWAYS_PASS)
- , mStencilCompareBack(CMPF_ALWAYS_PASS)
- , mNumTextureUnits(0)
- , mTextureInfos(nullptr)
- , mDepthWrite(true)
- , mGLSLProgramFactory(nullptr)
- , mProgramPipelineManager(nullptr)
- , mActivePipeline(nullptr)
- , mCurrentDrawOperation(DOT_TRIANGLE_LIST)
- , mDrawCallInProgress(false)
- , mActiveTextureUnit(-1)
- {
- // Get our GLSupport
- mGLSupport = ct::getGLSupport();
- mColorWrite[0] = mColorWrite[1] = mColorWrite[2] = mColorWrite[3] = true;
- mCurrentContext = 0;
- mMainContext = 0;
- mGLInitialised = false;
- mMinFilter = FO_LINEAR;
- mMipFilter = FO_POINT;
- mProgramPipelineManager = bs_new<GLSLProgramPipelineManager>();
- }
- GLRenderAPI::~GLRenderAPI()
- {
- }
- const StringID& GLRenderAPI::getName() const
- {
- static StringID strName("GLRenderAPI");
- return strName;
- }
- const String& GLRenderAPI::getShadingLanguageName() const
- {
- static String strName("glsl");
- return strName;
- }
- void GLRenderAPI::initialize()
- {
- THROW_IF_NOT_CORE_THREAD;
- mGLSupport->start();
- mVideoModeInfo = mGLSupport->getVideoModeInfo();
- CommandBufferManager::startUp<GLCommandBufferManager>();
- bs::RenderWindowManager::startUp<bs::GLRenderWindowManager>(this);
- RenderWindowManager::startUp<GLRenderWindowManager>(this);
- RenderStateManager::startUp();
- QueryManager::startUp<GLQueryManager>();
- RenderAPI::initialize();
- }
- void GLRenderAPI::initializeWithWindow(const SPtr<RenderWindow>& primaryWindow)
- {
- // Get the context from the window and finish initialization
- SPtr<GLContext> context;
- primaryWindow->getCustomAttribute("GLCONTEXT", &context);
- // Set main and current context
- mMainContext = context;
- mCurrentContext = mMainContext;
- // Set primary context as active
- if (mCurrentContext)
- mCurrentContext->setCurrent(*primaryWindow);
- // Setup GLSupport
- mGLSupport->initializeExtensions();
- mNumDevices = 1;
- mCurrentCapabilities = bs_newN<RenderAPICapabilities>(mNumDevices);
- initCapabilities(mCurrentCapabilities[0]);
- initFromCaps(mCurrentCapabilities);
- GLVertexArrayObjectManager::startUp();
- glFrontFace(GL_CW);
- BS_CHECK_GL_ERROR();
- // Ensure cubemaps are filtered across seams
- glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
- BS_CHECK_GL_ERROR();
- GPUInfo gpuInfo;
- gpuInfo.numGPUs = 1;
- const char* vendor = (const char*)glGetString(GL_VENDOR);
- BS_CHECK_GL_ERROR();
- const char* renderer = (const char*)glGetString(GL_RENDERER);
- BS_CHECK_GL_ERROR();
- gpuInfo.names[0] = String(vendor) + " " + String(renderer);
- PlatformUtility::_setGPUInfo(gpuInfo);
- mGLInitialised = true;
- RenderAPI::initializeWithWindow(primaryWindow);
- }
- void GLRenderAPI::destroyCore()
- {
- RenderAPI::destroyCore();
- // Deleting the GLSL program factory
- if (mGLSLProgramFactory)
- {
- // Remove from manager safely
- GpuProgramManager::instance().removeFactory(mGLSLProgramFactory);
- bs_delete(mGLSLProgramFactory);
- mGLSLProgramFactory = nullptr;
- }
- // Deleting the hardware buffer manager. Has to be done before the mGLSupport->stop().
- HardwareBufferManager::shutDown();
- bs::HardwareBufferManager::shutDown();
- GLRTTManager::shutDown();
- for (UINT32 i = 0; i < MAX_VB_COUNT; i++)
- mBoundVertexBuffers[i] = nullptr;
- mBoundVertexDeclaration = nullptr;
- mBoundIndexBuffer = nullptr;
- mCurrentVertexProgram = nullptr;
- mCurrentFragmentProgram = nullptr;
- mCurrentGeometryProgram = nullptr;
- mCurrentHullProgram = nullptr;
- mCurrentDomainProgram = nullptr;
- mCurrentComputeProgram = nullptr;
- mGLSupport->stop();
- TextureManager::shutDown();
- bs::TextureManager::shutDown();
- QueryManager::shutDown();
- RenderWindowManager::shutDown();
- bs::RenderWindowManager::shutDown();
- RenderStateManager::shutDown();
- GLVertexArrayObjectManager::shutDown(); // Note: Needs to be after QueryManager shutdown as some resources might be waiting for queries to complete
- CommandBufferManager::shutDown();
- mGLInitialised = false;
- if(mProgramPipelineManager != nullptr)
- bs_delete(mProgramPipelineManager);
- if(mCurrentContext)
- mCurrentContext->endCurrent();
- mCurrentContext = nullptr;
- mMainContext = nullptr;
- if(mGLSupport)
- bs_delete(mGLSupport);
- if (mTextureInfos != nullptr)
- bs_deleteN(mTextureInfos, mNumTextureUnits);
- }
- void GLRenderAPI::setGraphicsPipeline(const SPtr<GraphicsPipelineState>& pipelineState,
- const SPtr<CommandBuffer>& commandBuffer)
- {
- auto executeRef = [&](const SPtr<GraphicsPipelineState>& pipelineState)
- {
- THROW_IF_NOT_CORE_THREAD;
- BlendState* blendState;
- RasterizerState* rasterizerState;
- DepthStencilState* depthStencilState;
- if (pipelineState != nullptr)
- {
- mCurrentVertexProgram = std::static_pointer_cast<GLSLGpuProgram>(pipelineState->getVertexProgram());
- mCurrentFragmentProgram = std::static_pointer_cast<GLSLGpuProgram>(pipelineState->getFragmentProgram());
- mCurrentGeometryProgram = std::static_pointer_cast<GLSLGpuProgram>(pipelineState->getGeometryProgram());
- mCurrentDomainProgram = std::static_pointer_cast<GLSLGpuProgram>(pipelineState->getDomainProgram());
- mCurrentHullProgram = std::static_pointer_cast<GLSLGpuProgram>(pipelineState->getHullProgram());
- blendState = pipelineState->getBlendState().get();
- rasterizerState = pipelineState->getRasterizerState().get();
- depthStencilState = pipelineState->getDepthStencilState().get();
- if (blendState == nullptr)
- blendState = BlendState::getDefault().get();
- if (rasterizerState == nullptr)
- rasterizerState = RasterizerState::getDefault().get();
- if(depthStencilState == nullptr)
- depthStencilState = DepthStencilState::getDefault().get();
- }
- else
- {
- mCurrentVertexProgram = nullptr;
- mCurrentFragmentProgram = nullptr;
- mCurrentGeometryProgram = nullptr;
- mCurrentDomainProgram = nullptr;
- mCurrentHullProgram = nullptr;
- blendState = BlendState::getDefault().get();
- rasterizerState = RasterizerState::getDefault().get();
- depthStencilState = DepthStencilState::getDefault().get();
- }
- // Blend state
- {
- const BlendProperties& stateProps = blendState->getProperties();
- // Alpha to coverage
- setAlphaToCoverage(stateProps.getAlphaToCoverageEnabled());
- // Blend states
- // OpenGL doesn't allow us to specify blend state per render target, so we just use the first one.
- if (stateProps.getBlendEnabled(0))
- {
- setSceneBlending(stateProps.getSrcBlend(0), stateProps.getDstBlend(0), stateProps.getAlphaSrcBlend(0),
- stateProps.getAlphaDstBlend(0), stateProps.getBlendOperation(0), stateProps.getAlphaBlendOperation(0));
- }
- else
- {
- setSceneBlending(BF_ONE, BF_ZERO, BO_ADD);
- }
- // Color write mask
- UINT8 writeMask = stateProps.getRenderTargetWriteMask(0);
- setColorBufferWriteEnabled((writeMask & 0x1) != 0, (writeMask & 0x2) != 0, (writeMask & 0x4) != 0, (writeMask & 0x8) != 0);
- }
- // Rasterizer state
- {
- const RasterizerProperties& stateProps = rasterizerState->getProperties();
- setDepthBias(stateProps.getDepthBias(), stateProps.getSlopeScaledDepthBias());
- setCullingMode(stateProps.getCullMode());
- setPolygonMode(stateProps.getPolygonMode());
- setScissorTestEnable(stateProps.getScissorEnable());
- setMultisamplingEnable(stateProps.getMultisampleEnable());
- setDepthClipEnable(stateProps.getDepthClipEnable());
- setAntialiasedLineEnable(stateProps.getAntialiasedLineEnable());
- }
- // Depth stencil state
- {
- const DepthStencilProperties& stateProps = depthStencilState->getProperties();
- // Set stencil buffer options
- setStencilCheckEnabled(stateProps.getStencilEnable());
- setStencilBufferOperations(stateProps.getStencilFrontFailOp(), stateProps.getStencilFrontZFailOp(), stateProps.getStencilFrontPassOp(), true);
- setStencilBufferFunc(stateProps.getStencilFrontCompFunc(), stateProps.getStencilReadMask(), true);
- setStencilBufferOperations(stateProps.getStencilBackFailOp(), stateProps.getStencilBackZFailOp(), stateProps.getStencilBackPassOp(), false);
- setStencilBufferFunc(stateProps.getStencilBackCompFunc(), stateProps.getStencilReadMask(), false);
- setStencilBufferWriteMask(stateProps.getStencilWriteMask());
- // Set depth buffer options
- setDepthBufferCheckEnabled(stateProps.getDepthReadEnable());
- setDepthBufferWriteEnabled(stateProps.getDepthWriteEnable());
- setDepthBufferFunction(stateProps.getDepthComparisonFunc());
- }
- };
- if (commandBuffer == nullptr)
- executeRef(pipelineState);
- else
- {
- auto execute = [=]() { executeRef(pipelineState); };
- SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
- cb->queueCommand(execute);
- }
- BS_INC_RENDER_STAT(NumPipelineStateChanges);
- }
- void GLRenderAPI::setComputePipeline(const SPtr<ComputePipelineState>& pipelineState,
- const SPtr<CommandBuffer>& commandBuffer)
- {
- auto executeRef = [&](const SPtr<ComputePipelineState>& pipelineState)
- {
- THROW_IF_NOT_CORE_THREAD;
- SPtr<GpuProgram> program;
- if (pipelineState != nullptr)
- program = pipelineState->getProgram();
- if (program != nullptr && program->getProperties().getType() == GPT_COMPUTE_PROGRAM)
- mCurrentComputeProgram = std::static_pointer_cast<GLSLGpuProgram>(program);
- else
- mCurrentComputeProgram = nullptr;
- };
- if (commandBuffer == nullptr)
- executeRef(pipelineState);
- else
- {
- auto execute = [=]() { executeRef(pipelineState); };
- SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
- cb->queueCommand(execute);
- }
- BS_INC_RENDER_STAT(NumPipelineStateChanges);
- }
- void GLRenderAPI::setGpuParams(const SPtr<GpuParams>& gpuParams, const SPtr<CommandBuffer>& commandBuffer)
- {
- auto executeRef = [&](const SPtr<GpuParams>& gpuParams)
- {
- THROW_IF_NOT_CORE_THREAD;
- #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
- for (UINT32 i = 0; i < 8; i++)
- {
- glBindImageTexture(i, 0, 0, false, 0, GL_READ_WRITE, GL_R32F);
- BS_CHECK_GL_ERROR();
- }
- #endif
- bs_frame_mark();
- {
- UINT32 textureUnitCount = 0;
- FrameVector<UINT32> textureUnits(12);
- auto getTexUnit = [&](UINT32 binding)
- {
- for(UINT32 i = 0; i < (UINT32)textureUnits.size(); i++)
- {
- if (textureUnits[i] == binding)
- return i;
- }
- UINT32 unit = textureUnitCount++;
- textureUnits.push_back(binding);
- return unit;
- };
- UINT32 imageUnitCount = 0;
- FrameVector<UINT32> imageUnits(6);
- auto getImageUnit = [&](UINT32 binding)
- {
- for (UINT32 i = 0; i < (UINT32)imageUnits.size(); i++)
- {
- if (imageUnits[i] == binding)
- return i;
- }
- UINT32 unit = imageUnitCount++;
- imageUnits.push_back(binding);
- return unit;
- };
- UINT32 uniformUnitCount = 0;
- FrameVector<UINT32> uniformUnits(6);
- auto getUniformUnit = [&](UINT32 binding)
- {
- for (UINT32 i = 0; i < (UINT32)uniformUnits.size(); i++)
- {
- if (uniformUnits[i] == binding)
- return i;
- }
- UINT32 unit = uniformUnitCount++;
- uniformUnits.push_back(binding);
- return unit;
- };
- UINT32 sharedStorageUnitCount = 0;
- FrameVector<UINT32> sharedStorageUnits(6);
- auto getSharedStorageUnit = [&](UINT32 binding)
- {
- for (UINT32 i = 0; i < (UINT32)sharedStorageUnits.size(); i++)
- {
- if (sharedStorageUnits[i] == binding)
- return i;
- }
- UINT32 unit = sharedStorageUnitCount++;
- sharedStorageUnits.push_back(binding);
- return unit;
- };
- const UINT32 numStages = 6;
- for(UINT32 i = 0; i < numStages; i++)
- {
- textureUnits.clear();
- imageUnits.clear();
- uniformUnits.clear();
- sharedStorageUnits.clear();
- GpuProgramType type = (GpuProgramType)i;
- SPtr<GpuParamDesc> paramDesc = gpuParams->getParamDesc(type);
- if (paramDesc == nullptr)
- continue;
- for (auto& entry : paramDesc->textures)
- {
- UINT32 binding = entry.second.slot;
- SPtr<Texture> texture = gpuParams->getTexture(entry.second.set, binding);
- const TextureSurface& surface = gpuParams->getTextureSurface(entry.second.set, binding);
- UINT32 unit = getTexUnit(binding);
- if (!activateGLTextureUnit(unit))
- continue;
- GLTexture* glTex = static_cast<GLTexture*>(texture.get());
- if (glTex != nullptr)
- {
- #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
- SPtr<TextureView> texView = glTex->requestView(
- surface.mipLevel,
- surface.numMipLevels,
- surface.face,
- surface.numFaces,
- GVU_DEFAULT);
- GLTextureView* glTexView = static_cast<GLTextureView*>(texView.get());
- GLenum newTextureType = glTexView->getGLTextureTarget();
- GLuint texId = glTexView->getGLID();
- #else
- // Texture views are not supported, so if user requested a part of the texture surface report
- // a warning
- auto& props = texture->getProperties();
- if (surface.mipLevel != 0 || surface.face != 0 ||
- (surface.numMipLevels != 0 && surface.numMipLevels != props.getNumMipmaps()) ||
- (surface.numFaces != 0 && surface.numFaces != props.getNumFaces()))
- {
- LOGWRN("Attempting to bind only a part of a texture, but texture views are not supported. "
- "Entire texture will be bound instead.");
- }
- GLenum newTextureType = glTex->getGLTextureTarget();
- GLuint texId = glTex->getGLID();
- #endif
- if (mTextureInfos[unit].type != newTextureType)
- {
- glBindTexture(mTextureInfos[unit].type, 0);
- BS_CHECK_GL_ERROR();
- }
- glBindTexture(newTextureType, texId);
- BS_CHECK_GL_ERROR();
- mTextureInfos[unit].type = newTextureType;
- SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
- if (activeProgram != nullptr)
- {
- GLuint glProgram = activeProgram->getGLHandle();
- glProgramUniform1i(glProgram, binding, unit);
- BS_CHECK_GL_ERROR();
- }
- }
- else
- {
- glBindTexture(mTextureInfos[unit].type, 0);
- BS_CHECK_GL_ERROR();
- }
- }
- for(auto& entry : paramDesc->samplers)
- {
- UINT32 binding = entry.second.slot;
- SPtr<SamplerState> samplerState = gpuParams->getSamplerState(entry.second.set, binding);
- if (samplerState == nullptr)
- samplerState = SamplerState::getDefault();
- UINT32 unit = getTexUnit(binding);
- if (!activateGLTextureUnit(unit))
- continue;
- bool isMultisample = mTextureInfos[unit].type == GL_TEXTURE_2D_MULTISAMPLE ||
- mTextureInfos[unit].type == GL_TEXTURE_2D_MULTISAMPLE_ARRAY;
- // No sampler options for multisampled textures
- if (!isMultisample)
- {
- const SamplerProperties& stateProps = samplerState->getProperties();
- setTextureFiltering(unit, FT_MIN, stateProps.getTextureFiltering(FT_MIN));
- setTextureFiltering(unit, FT_MAG, stateProps.getTextureFiltering(FT_MAG));
- setTextureFiltering(unit, FT_MIP, stateProps.getTextureFiltering(FT_MIP));
- setTextureAnisotropy(unit, stateProps.getTextureAnisotropy());
- setTextureCompareMode(unit, stateProps.getComparisonFunction());
- setTextureMipmapBias(unit, stateProps.getTextureMipmapBias());
- setTextureMipmapRange(unit, stateProps.getMinimumMip(), stateProps.getMaximumMip());
- const UVWAddressingMode& uvw = stateProps.getTextureAddressingMode();
- setTextureAddressingMode(unit, uvw);
- setTextureBorderColor(unit, stateProps.getBorderColor());
- }
- }
- for(auto& entry : paramDesc->buffers)
- {
- UINT32 binding = entry.second.slot;
- SPtr<GpuBuffer> buffer = gpuParams->getBuffer(entry.second.set, binding);
- GLGpuBuffer* glBuffer = static_cast<GLGpuBuffer*>(buffer.get());
- switch(entry.second.type)
- {
- case GPOT_BYTE_BUFFER: // Texture buffer (read-only, unstructured)
- {
- UINT32 unit = getTexUnit(binding);
- if (!activateGLTextureUnit(unit))
- continue;
- if (glBuffer != nullptr)
- {
- if (mTextureInfos[unit].type != GL_TEXTURE_BUFFER)
- {
- glBindTexture(mTextureInfos[unit].type, 0);
- BS_CHECK_GL_ERROR();
- }
- mTextureInfos[unit].type = GL_TEXTURE_BUFFER;
- glBindTexture(GL_TEXTURE_BUFFER, glBuffer->getGLTextureId());
- BS_CHECK_GL_ERROR();
- SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
- if (activeProgram != nullptr)
- {
- GLuint glProgram = activeProgram->getGLHandle();
- glProgramUniform1i(glProgram, binding, unit);
- BS_CHECK_GL_ERROR();
- }
- }
- else
- {
- glBindTexture(mTextureInfos[unit].type, 0);
- BS_CHECK_GL_ERROR();
- }
- }
- break;
- #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
- case GPOT_RWBYTE_BUFFER: // Storage buffer (read/write, unstructured)
- {
- UINT32 unit = getImageUnit(binding);
- if (glBuffer != nullptr)
- {
- glBindImageTexture(
- unit,
- glBuffer->getGLTextureId(),
- 0,
- false,
- 0,
- GL_READ_WRITE,
- glBuffer->getGLFormat());
- BS_CHECK_GL_ERROR();
- SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
- if (activeProgram != nullptr)
- {
- GLuint glProgram = activeProgram->getGLHandle();
- glProgramUniform1i(glProgram, binding, unit);
- BS_CHECK_GL_ERROR();
- }
- }
- else
- {
- glBindImageTexture(unit, 0, 0, false, 0, GL_READ_WRITE, GL_R32F);
- BS_CHECK_GL_ERROR();
- }
- }
- break;
- #endif
- #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
- case GPOT_RWSTRUCTURED_BUFFER: // Shared storage block (read/write, structured)
- {
- UINT32 unit = getSharedStorageUnit(binding);
- if (glBuffer != nullptr)
- {
- glBindBufferBase(GL_SHADER_STORAGE_BUFFER, unit, glBuffer->getGLBufferId());
- BS_CHECK_GL_ERROR();
-
- SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
- if (activeProgram != nullptr)
- {
- GLuint glProgram = activeProgram->getGLHandle();
- glShaderStorageBlockBinding(glProgram, binding, unit);
- BS_CHECK_GL_ERROR();
- }
- }
- else
- {
- glBindBufferBase(GL_SHADER_STORAGE_BUFFER, unit, 0);
- BS_CHECK_GL_ERROR();
- }
- }
- break;
- #endif
- default:
- break;
- }
- }
- #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
- for(auto& entry : paramDesc->loadStoreTextures)
- {
- UINT32 binding = entry.second.slot;
- SPtr<Texture> texture = gpuParams->getLoadStoreTexture(entry.second.set, binding);
- const TextureSurface& surface = gpuParams->getLoadStoreSurface(entry.second.set, binding);
- UINT32 unit = getImageUnit(binding);
- if (texture != nullptr)
- {
- GLTexture* tex = static_cast<GLTexture*>(texture.get());
- glBindImageTexture(
- unit,
- tex->getGLID(),
- surface.mipLevel,
- surface.numFaces > 1,
- surface.face,
- GL_READ_WRITE,
- tex->getGLFormat());
- BS_CHECK_GL_ERROR();
- SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
- if (activeProgram != nullptr)
- {
- GLuint glProgram = activeProgram->getGLHandle();
- glProgramUniform1i(glProgram, binding, unit);
- BS_CHECK_GL_ERROR();
- }
- }
- else
- {
- glBindImageTexture(unit, 0, 0, false, 0, GL_READ_WRITE, GL_R32F);
- BS_CHECK_GL_ERROR();
- }
- }
- #endif
- for (auto& entry : paramDesc->paramBlocks)
- {
- UINT32 binding = entry.second.slot;
- SPtr<GpuParamBlockBuffer> buffer = gpuParams->getParamBlockBuffer(entry.second.set, binding);
-
- if (buffer == nullptr)
- continue;
- buffer->flushToGPU();
- SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
- GLuint glProgram = activeProgram->getGLHandle();
- // 0 means uniforms are not in block, in which case we handle it specially
- if (binding == 0)
- {
- UINT8* uniformBufferData = (UINT8*)bs_stack_alloc(buffer->getSize());
- buffer->read(0, uniformBufferData, buffer->getSize());
- for (auto iter = paramDesc->params.begin(); iter != paramDesc->params.end(); ++iter)
- {
- const GpuParamDataDesc& param = iter->second;
- if (param.paramBlockSlot != 0) // 0 means uniforms are not in a block
- continue;
- const UINT8* ptrData = uniformBufferData + param.cpuMemOffset * sizeof(UINT32);
- // Note: We don't transpose matrices here even though we don't use column major format
- // because they are assumed to be pre-transposed in the GpuParams buffer
- switch (param.type)
- {
- case GPDT_FLOAT1:
- glProgramUniform1fv(glProgram, param.gpuMemOffset, param.arraySize, (GLfloat*)ptrData);
- BS_CHECK_GL_ERROR();
- break;
- case GPDT_FLOAT2:
- glProgramUniform2fv(glProgram, param.gpuMemOffset, param.arraySize, (GLfloat*)ptrData);
- BS_CHECK_GL_ERROR();
- break;
- case GPDT_FLOAT3:
- glProgramUniform3fv(glProgram, param.gpuMemOffset, param.arraySize, (GLfloat*)ptrData);
- BS_CHECK_GL_ERROR();
- break;
- case GPDT_FLOAT4:
- glProgramUniform4fv(glProgram, param.gpuMemOffset, param.arraySize, (GLfloat*)ptrData);
- BS_CHECK_GL_ERROR();
- break;
- case GPDT_MATRIX_2X2:
- glProgramUniformMatrix2fv(
- glProgram,
- param.gpuMemOffset,
- param.arraySize,
- GL_FALSE,
- (GLfloat*)ptrData);
- BS_CHECK_GL_ERROR();
- break;
- case GPDT_MATRIX_2X3:
- glProgramUniformMatrix3x2fv(
- glProgram,
- param.gpuMemOffset,
- param.arraySize,
- GL_FALSE,
- (GLfloat*)ptrData);
- BS_CHECK_GL_ERROR();
- break;
- case GPDT_MATRIX_2X4:
- glProgramUniformMatrix4x2fv(
- glProgram,
- param.gpuMemOffset,
- param.arraySize,
- GL_FALSE,
- (GLfloat*)ptrData);
- BS_CHECK_GL_ERROR();
- break;
- case GPDT_MATRIX_3X2:
- glProgramUniformMatrix2x3fv(
- glProgram,
- param.gpuMemOffset,
- param.arraySize,
- GL_FALSE,
- (GLfloat*)ptrData);
- BS_CHECK_GL_ERROR();
- break;
- case GPDT_MATRIX_3X3:
- glProgramUniformMatrix3fv(
- glProgram,
- param.gpuMemOffset,
- param.arraySize,
- GL_FALSE,
- (GLfloat*)ptrData);
- BS_CHECK_GL_ERROR();
- break;
- case GPDT_MATRIX_3X4:
- glProgramUniformMatrix4x3fv(
- glProgram,
- param.gpuMemOffset,
- param.arraySize,
- GL_FALSE,
- (GLfloat*)ptrData);
- BS_CHECK_GL_ERROR();
- break;
- case GPDT_MATRIX_4X2:
- glProgramUniformMatrix2x4fv(
- glProgram,
- param.gpuMemOffset,
- param.arraySize,
- GL_FALSE,
- (GLfloat*)ptrData);
- BS_CHECK_GL_ERROR();
- break;
- case GPDT_MATRIX_4X3:
- glProgramUniformMatrix3x4fv(
- glProgram,
- param.gpuMemOffset,
- param.arraySize,
- GL_FALSE,
- (GLfloat*)ptrData);
- BS_CHECK_GL_ERROR();
- break;
- case GPDT_MATRIX_4X4:
- glProgramUniformMatrix4fv(
- glProgram,
- param.gpuMemOffset,
- param.arraySize,
- GL_FALSE,
- (GLfloat*)ptrData);
- BS_CHECK_GL_ERROR();
- break;
- case GPDT_INT1:
- glProgramUniform1iv(glProgram, param.gpuMemOffset, param.arraySize, (GLint*)ptrData);
- BS_CHECK_GL_ERROR();
- break;
- case GPDT_INT2:
- glProgramUniform2iv(glProgram, param.gpuMemOffset, param.arraySize, (GLint*)ptrData);
- BS_CHECK_GL_ERROR();
- break;
- case GPDT_INT3:
- glProgramUniform3iv(glProgram, param.gpuMemOffset, param.arraySize, (GLint*)ptrData);
- BS_CHECK_GL_ERROR();
- break;
- case GPDT_INT4:
- glProgramUniform4iv(glProgram, param.gpuMemOffset, param.arraySize, (GLint*)ptrData);
- BS_CHECK_GL_ERROR();
- break;
- case GPDT_BOOL:
- glProgramUniform1uiv(glProgram, param.gpuMemOffset, param.arraySize, (GLuint*)ptrData);
- BS_CHECK_GL_ERROR();
- break;
- default:
- case GPDT_UNKNOWN:
- break;
- }
- }
- if (uniformBufferData != nullptr)
- bs_stack_free(uniformBufferData);
- }
- else
- {
- const GLGpuParamBlockBuffer* glParamBlockBuffer = static_cast<const GLGpuParamBlockBuffer*>(buffer.get());
- UINT32 unit = getUniformUnit(binding - 1);
- glUniformBlockBinding(glProgram, binding - 1, unit);
- BS_CHECK_GL_ERROR();
- glBindBufferBase(GL_UNIFORM_BUFFER, unit, glParamBlockBuffer->getGLHandle());
- BS_CHECK_GL_ERROR();
- }
- }
- }
- }
- bs_frame_clear();
- activateGLTextureUnit(0);
- };
- if (commandBuffer == nullptr)
- executeRef(gpuParams);
- else
- {
- auto execute = [=]() { executeRef(gpuParams); };
- SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
- cb->queueCommand(execute);
- }
- BS_INC_RENDER_STAT(NumGpuParamBinds);
- }
- void GLRenderAPI::setStencilRef(UINT32 stencilRefValue, const SPtr<CommandBuffer>& commandBuffer)
- {
- auto executeRef = [&](UINT32 stencilRefValue)
- {
- THROW_IF_NOT_CORE_THREAD;
- setStencilRefValue(stencilRefValue);
- };
- if (commandBuffer == nullptr)
- executeRef(stencilRefValue);
- else
- {
- auto execute = [=]() { executeRef(stencilRefValue); };
- SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
- cb->queueCommand(execute);
- }
- }
- void GLRenderAPI::setViewport(const Rect2& area,
- const SPtr<CommandBuffer>& commandBuffer)
- {
- auto executeRef = [&](const Rect2& area)
- {
- THROW_IF_NOT_CORE_THREAD;
- mViewportNorm = area;
- applyViewport();
- };
- if (commandBuffer == nullptr)
- executeRef(area);
- else
- {
- auto execute = [=]() { executeRef(area); };
- SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
- cb->queueCommand(execute);
- }
- }
- void GLRenderAPI::setRenderTarget(const SPtr<RenderTarget>& target, UINT32 readOnlyFlags,
- RenderSurfaceMask loadMask, const SPtr<CommandBuffer>& commandBuffer)
- {
- auto executeRef = [&](const SPtr<RenderTarget>& target, UINT32 readOnlyFlags)
- {
- THROW_IF_NOT_CORE_THREAD;
- // Switch context if different from current one
- if (target != nullptr && target->getProperties().isWindow)
- {
- RenderWindow* window = static_cast<RenderWindow*>(target.get());
- SPtr<GLContext> newContext;
- target->getCustomAttribute("GLCONTEXT", &newContext);
- if (newContext && mCurrentContext != newContext)
- switchContext(newContext, *window);
- else
- mCurrentContext->setCurrent(*window);
- }
- // This must happen after context switch to ensure previous context is still alive
- mActiveRenderTarget = target;
- GLFrameBufferObject* fbo = nullptr;
- if (target != nullptr)
- target->getCustomAttribute("FBO", &fbo);
- if (fbo != nullptr)
- {
- fbo->bind();
- // Enable / disable sRGB states
- if (target->getProperties().hwGamma)
- {
- glEnable(GL_FRAMEBUFFER_SRGB);
- BS_CHECK_GL_ERROR();
- }
- else
- {
- glDisable(GL_FRAMEBUFFER_SRGB);
- BS_CHECK_GL_ERROR();
- }
- }
- else
- {
- glBindFramebuffer(GL_FRAMEBUFFER, 0);
- BS_CHECK_GL_ERROR();
- }
- applyViewport();
- };
- if (commandBuffer == nullptr)
- executeRef(target, readOnlyFlags);
- else
- {
- auto execute = [=]() { executeRef(target, readOnlyFlags); };
- SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
- cb->queueCommand(execute);
- }
- BS_INC_RENDER_STAT(NumRenderTargetChanges);
- }
- void GLRenderAPI::setVertexBuffers(UINT32 index, SPtr<VertexBuffer>* buffers, UINT32 numBuffers,
- const SPtr<CommandBuffer>& commandBuffer)
- {
- #if BS_DEBUG_MODE
- UINT32 lastIdx = index + numBuffers;
- if(lastIdx > MAX_VB_COUNT)
- {
- LOGERR("Provided vertex buffer slot range is invalid: " + toString(index) + " to " +
- toString(index + numBuffers) + ".");
- return;
- }
- #endif
- auto executeRef = [&](UINT32 index, SPtr<VertexBuffer>* buffers, UINT32 numBuffers)
- {
- THROW_IF_NOT_CORE_THREAD;
- std::array<SPtr<VertexBuffer>, MAX_VB_COUNT> boundBuffers;
- for (UINT32 i = 0; i < numBuffers; i++)
- boundBuffers[index + i] = buffers[i];
- for (UINT32 i = 0; i < numBuffers; i++)
- mBoundVertexBuffers[index + i] = boundBuffers[index + i];
- };
- if (commandBuffer == nullptr)
- executeRef(index, buffers, numBuffers);
- else
- {
- auto execute = [=]() { executeRef(index, buffers, numBuffers); };
- SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
- cb->queueCommand(execute);
- }
- }
- void GLRenderAPI::setVertexDeclaration(const SPtr<VertexDeclaration>& vertexDeclaration,
- const SPtr<CommandBuffer>& commandBuffer)
- {
- auto executeRef = [&](const SPtr<VertexDeclaration>& vertexDeclaration)
- {
- THROW_IF_NOT_CORE_THREAD;
- mBoundVertexDeclaration = vertexDeclaration;
- };
- if (commandBuffer == nullptr)
- executeRef(vertexDeclaration);
- else
- {
- auto execute = [=]() { executeRef(vertexDeclaration); };
- SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
- cb->queueCommand(execute);
- }
- }
- void GLRenderAPI::setDrawOperation(DrawOperationType op, const SPtr<CommandBuffer>& commandBuffer)
- {
- auto executeRef = [&](DrawOperationType op)
- {
- THROW_IF_NOT_CORE_THREAD;
- mCurrentDrawOperation = op;
- };
- if (commandBuffer == nullptr)
- executeRef(op);
- else
- {
- auto execute = [=]() { executeRef(op); };
- SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
- cb->queueCommand(execute);
- cb->mCurrentDrawOperation = op;
- }
- }
- void GLRenderAPI::setIndexBuffer(const SPtr<IndexBuffer>& buffer, const SPtr<CommandBuffer>& commandBuffer)
- {
- auto executeRef = [&](const SPtr<IndexBuffer>& buffer)
- {
- THROW_IF_NOT_CORE_THREAD;
- mBoundIndexBuffer = buffer;
- };
- if (commandBuffer == nullptr)
- executeRef(buffer);
- else
- {
- auto execute = [=]() { executeRef(buffer); };
- SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
- cb->queueCommand(execute);
- }
- }
- void GLRenderAPI::draw(UINT32 vertexOffset, UINT32 vertexCount, UINT32 instanceCount,
- const SPtr<CommandBuffer>& commandBuffer)
- {
- auto executeRef = [&](UINT32 vertexOffset, UINT32 vertexCount, UINT32 instanceCount)
- {
- THROW_IF_NOT_CORE_THREAD;
- // Find the correct type to render
- GLint primType = getGLDrawMode();
- beginDraw();
- if (instanceCount <= 1)
- {
- glDrawArrays(primType, vertexOffset, vertexCount);
- BS_CHECK_GL_ERROR();
- }
- else
- {
- glDrawArraysInstanced(primType, vertexOffset, vertexCount, instanceCount);
- BS_CHECK_GL_ERROR();
- }
- endDraw();
- };
- UINT32 primCount;
- if (commandBuffer == nullptr)
- {
- executeRef(vertexOffset, vertexCount, instanceCount);
- primCount = vertexCountToPrimCount(mCurrentDrawOperation, vertexCount);
- }
- else
- {
- auto execute = [=]() { executeRef(vertexOffset, vertexCount, instanceCount); };
- SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
- cb->queueCommand(execute);
- primCount = vertexCountToPrimCount(cb->mCurrentDrawOperation, vertexCount);
- }
- BS_INC_RENDER_STAT(NumDrawCalls);
- BS_ADD_RENDER_STAT(NumVertices, vertexCount);
- BS_ADD_RENDER_STAT(NumPrimitives, primCount);
- }
- void GLRenderAPI::drawIndexed(UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount,
- UINT32 instanceCount, const SPtr<CommandBuffer>& commandBuffer)
- {
- auto executeRef = [&](UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount,
- UINT32 instanceCount)
- {
- THROW_IF_NOT_CORE_THREAD;
- if (mBoundIndexBuffer == nullptr)
- {
- LOGWRN("Cannot draw indexed because index buffer is not set.");
- return;
- }
- // Find the correct type to render
- GLint primType = getGLDrawMode();
- beginDraw();
- SPtr<GLIndexBuffer> indexBuffer = std::static_pointer_cast<GLIndexBuffer>(mBoundIndexBuffer);
- const IndexBufferProperties& ibProps = indexBuffer->getProperties();
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer->getGLBufferId());
- BS_CHECK_GL_ERROR();
- GLenum indexType = (ibProps.getType() == IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
- if (instanceCount <= 1)
- {
- glDrawElementsBaseVertex(
- primType,
- indexCount,
- indexType,
- (GLvoid*)(UINT64)(ibProps.getIndexSize() * startIndex),
- vertexOffset);
- BS_CHECK_GL_ERROR();
- }
- else
- {
- glDrawElementsInstancedBaseVertex(
- primType,
- indexCount,
- indexType,
- (GLvoid*)(UINT64)(ibProps.getIndexSize() * startIndex),
- instanceCount,
- vertexOffset);
- BS_CHECK_GL_ERROR();
- }
- endDraw();
- };
- UINT32 primCount;
- if (commandBuffer == nullptr)
- {
- executeRef(startIndex, indexCount, vertexOffset, vertexCount, instanceCount);
- primCount = vertexCountToPrimCount(mCurrentDrawOperation, vertexCount);
- }
- else
- {
- auto execute = [=]() { executeRef(startIndex, indexCount, vertexOffset, vertexCount, instanceCount); };
- SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
- cb->queueCommand(execute);
- primCount = vertexCountToPrimCount(cb->mCurrentDrawOperation, vertexCount);
- }
- BS_INC_RENDER_STAT(NumDrawCalls);
- BS_ADD_RENDER_STAT(NumVertices, vertexCount);
- BS_ADD_RENDER_STAT(NumPrimitives, primCount);
- BS_INC_RENDER_STAT(NumIndexBufferBinds);
- }
- void GLRenderAPI::dispatchCompute(UINT32 numGroupsX, UINT32 numGroupsY, UINT32 numGroupsZ,
- const SPtr<CommandBuffer>& commandBuffer)
- {
- auto executeRef = [&](UINT32 numGroupsX, UINT32 numGroupsY, UINT32 numGroupsZ)
- {
- THROW_IF_NOT_CORE_THREAD;
- if (mCurrentComputeProgram == nullptr)
- {
- LOGWRN("Cannot dispatch compute without a set compute program.");
- return;
- }
- #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
- glUseProgram(mCurrentComputeProgram->getGLHandle());
- BS_CHECK_GL_ERROR();
- glDispatchCompute(numGroupsX, numGroupsY, numGroupsZ);
- BS_CHECK_GL_ERROR();
- #else
- LOGWRN("Compute shaders not supported on current OpenGL version.");
- #endif
- };
- if (commandBuffer == nullptr)
- executeRef(numGroupsX, numGroupsY, numGroupsZ);
- else
- {
- auto execute = [=]() { executeRef(numGroupsX, numGroupsY, numGroupsZ); };
- SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
- cb->queueCommand(execute);
- }
- BS_INC_RENDER_STAT(NumComputeCalls);
- }
- void GLRenderAPI::setScissorRect(UINT32 left, UINT32 top, UINT32 right, UINT32 bottom,
- const SPtr<CommandBuffer>& commandBuffer)
- {
- auto executeRef = [&](UINT32 left, UINT32 top, UINT32 right, UINT32 bottom)
- {
- THROW_IF_NOT_CORE_THREAD;
- mScissorTop = top;
- mScissorBottom = bottom;
- mScissorLeft = left;
- mScissorRight = right;
- };
- if (commandBuffer == nullptr)
- executeRef(left, top, right, bottom);
- else
- {
- auto execute = [=]() { executeRef(left, top, right, bottom); };
- SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
- cb->queueCommand(execute);
- }
- }
- void GLRenderAPI::clearRenderTarget(UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask,
- const SPtr<CommandBuffer>& commandBuffer)
- {
- auto executeRef = [&](UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask)
- {
- if (mActiveRenderTarget == nullptr)
- return;
- const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
- Rect2I clearRect(0, 0, rtProps.width, rtProps.height);
- clearArea(buffers, color, depth, stencil, clearRect, targetMask);
- };
- if (commandBuffer == nullptr)
- executeRef(buffers, color, depth, stencil, targetMask);
- else
- {
- auto execute = [=]() { executeRef(buffers, color, depth, stencil, targetMask); };
- SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
- cb->queueCommand(execute);
- }
- }
- void GLRenderAPI::clearViewport(UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask,
- const SPtr<CommandBuffer>& commandBuffer)
- {
- auto executeRef = [&](UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask)
- {
- Rect2I clearRect(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
- clearArea(buffers, color, depth, stencil, clearRect, targetMask);
- };
- if (commandBuffer == nullptr)
- executeRef(buffers, color, depth, stencil, targetMask);
- else
- {
- auto execute = [=]() { executeRef(buffers, color, depth, stencil, targetMask); };
- SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
- cb->queueCommand(execute);
- }
- }
- void GLRenderAPI::swapBuffers(const SPtr<RenderTarget>& target, UINT32 syncMask)
- {
- THROW_IF_NOT_CORE_THREAD;
- // Switch context if different from current one
- if(!target->getProperties().isWindow)
- return;
- RenderWindow* window = static_cast<RenderWindow*>(target.get());
- SPtr<GLContext> newContext;
- target->getCustomAttribute("GLCONTEXT", &newContext);
- if (newContext && mCurrentContext != newContext)
- switchContext(newContext, *window);
- else
- mCurrentContext->setCurrent(*window);
- target->swapBuffers();
-
- BS_INC_RENDER_STAT(NumPresents);
- }
- void GLRenderAPI::addCommands(const SPtr<CommandBuffer>& commandBuffer, const SPtr<CommandBuffer>& secondary)
- {
- SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
- SPtr<GLCommandBuffer> secondaryCb = std::static_pointer_cast<GLCommandBuffer>(secondary);
- cb->appendSecondary(secondaryCb);
- }
- void GLRenderAPI::submitCommandBuffer(const SPtr<CommandBuffer>& commandBuffer, UINT32 syncMask)
- {
- SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
- if (cb == nullptr)
- return;
- cb->executeCommands();
- cb->clear();
- }
- void GLRenderAPI::clearArea(UINT32 buffers, const Color& color, float depth, UINT16 stencil, const Rect2I& clearRect,
- UINT8 targetMask)
- {
- THROW_IF_NOT_CORE_THREAD;
- if(mActiveRenderTarget == nullptr)
- return;
- bool colorMask = !mColorWrite[0] || !mColorWrite[1] || !mColorWrite[2] || !mColorWrite[3];
- // Disable scissor test as we want to clear the entire render surface
- GLboolean scissorTestEnabled = glIsEnabled(GL_SCISSOR_TEST);
- UINT32 oldScissorTop = mScissorTop;
- UINT32 oldScissorBottom = mScissorBottom;
- UINT32 oldScissorLeft = mScissorLeft;
- UINT32 oldScissorRight = mScissorRight;
- if (scissorTestEnabled)
- {
- glDisable(GL_SCISSOR_TEST);
- BS_CHECK_GL_ERROR();
- }
- const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
- bool clearEntireTarget = clearRect.width == 0 || clearRect.height == 0;
- clearEntireTarget |= (clearRect.x == 0 && clearRect.y == 0 && clearRect.width == rtProps.width && clearRect.height == rtProps.height);
- if (!clearEntireTarget)
- {
- setScissorRect(clearRect.x, clearRect.y, clearRect.x + clearRect.width, clearRect.y + clearRect.height);
- setScissorTestEnable(true);
- }
- if (buffers & FBT_COLOR)
- {
- // Enable buffer for writing if it isn't
- if (colorMask)
- {
- glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
- BS_CHECK_GL_ERROR();
- }
- }
- if (buffers & FBT_DEPTH)
- {
- // Enable buffer for writing if it isn't
- if (!mDepthWrite)
- {
- glDepthMask(GL_TRUE);
- BS_CHECK_GL_ERROR();
- }
- }
- if (buffers & FBT_STENCIL)
- {
- // Enable buffer for writing if it isn't
- glStencilMask(0xFFFFFFFF);
- BS_CHECK_GL_ERROR();
- }
- if (targetMask == 0xFF)
- {
- GLbitfield flags = 0;
- if (buffers & FBT_COLOR)
- {
- flags |= GL_COLOR_BUFFER_BIT;
- glClearColor(color.r, color.g, color.b, color.a);
- BS_CHECK_GL_ERROR();
- }
- if (buffers & FBT_DEPTH)
- {
- flags |= GL_DEPTH_BUFFER_BIT;
- glClearDepth(depth);
- BS_CHECK_GL_ERROR();
- }
- if (buffers & FBT_STENCIL)
- {
- flags |= GL_STENCIL_BUFFER_BIT;
- glClearStencil(stencil);
- BS_CHECK_GL_ERROR();
- }
- // Clear buffers
- glClear(flags);
- BS_CHECK_GL_ERROR();
- }
- else
- {
- GLFrameBufferObject* fbo = nullptr;
- mActiveRenderTarget->getCustomAttribute("FBO", &fbo);
- if (buffers & FBT_COLOR)
- {
- for (UINT32 i = 0; i < BS_MAX_MULTIPLE_RENDER_TARGETS; i++)
- {
- if (fbo->hasColorBuffer(i) && ((1 << i) & targetMask) != 0)
- {
- glClearBufferfv(GL_COLOR, i, (GLfloat*)&color);
- BS_CHECK_GL_ERROR();
- }
- }
- }
- if (buffers & FBT_DEPTH)
- {
- if (buffers & FBT_STENCIL)
- {
- glClearBufferfi(GL_DEPTH_STENCIL, 0, depth, stencil);
- BS_CHECK_GL_ERROR();
- }
- else
- {
- glClearBufferfv(GL_DEPTH, 0, &depth);
- BS_CHECK_GL_ERROR();
- }
- }
- else if (buffers & FBT_STENCIL)
- {
- INT32 stencilClear = (INT32)stencil;
- glClearBufferiv(GL_STENCIL, 0, &stencilClear);
- BS_CHECK_GL_ERROR();
- }
- }
- if (!clearEntireTarget)
- {
- setScissorTestEnable(false);
- }
- // Restore scissor test
- if (scissorTestEnabled)
- {
- glEnable(GL_SCISSOR_TEST);
- BS_CHECK_GL_ERROR();
- mScissorTop = oldScissorTop;
- mScissorBottom = oldScissorBottom;
- mScissorLeft = oldScissorLeft;
- mScissorRight = oldScissorRight;
- }
- // Reset buffer write state
- if (!mDepthWrite && (buffers & FBT_DEPTH))
- {
- glDepthMask(GL_FALSE);
- BS_CHECK_GL_ERROR();
- }
- if (colorMask && (buffers & FBT_COLOR))
- {
- glColorMask(mColorWrite[0], mColorWrite[1], mColorWrite[2], mColorWrite[3]);
- BS_CHECK_GL_ERROR();
- }
- if (buffers & FBT_STENCIL)
- {
- glStencilMask(mStencilWriteMask);
- BS_CHECK_GL_ERROR();
- }
- BS_INC_RENDER_STAT(NumClears);
- }
- /************************************************************************/
- /* PRIVATE */
- /************************************************************************/
- void GLRenderAPI::setTextureAddressingMode(UINT16 unit, const UVWAddressingMode& uvw)
- {
- glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_WRAP_S, getTextureAddressingMode(uvw.u));
- BS_CHECK_GL_ERROR();
- glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_WRAP_T, getTextureAddressingMode(uvw.v));
- BS_CHECK_GL_ERROR();
- glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_WRAP_R, getTextureAddressingMode(uvw.w));
- BS_CHECK_GL_ERROR();
- }
- void GLRenderAPI::setTextureBorderColor(UINT16 unit, const Color& color)
- {
- GLfloat border[4] = { color.r, color.g, color.b, color.a };
- glTexParameterfv(mTextureInfos[unit].type, GL_TEXTURE_BORDER_COLOR, border);
- BS_CHECK_GL_ERROR();
- }
- void GLRenderAPI::setTextureMipmapBias(UINT16 unit, float bias)
- {
- glTexParameterf(mTextureInfos[unit].type, GL_TEXTURE_LOD_BIAS, bias);
- BS_CHECK_GL_ERROR();
- }
- void GLRenderAPI::setTextureMipmapRange(UINT16 unit, float min, float max)
- {
- glTexParameterf(mTextureInfos[unit].type, GL_TEXTURE_MIN_LOD, min);
- BS_CHECK_GL_ERROR();
- glTexParameterf(mTextureInfos[unit].type, GL_TEXTURE_MAX_LOD, max);
- BS_CHECK_GL_ERROR();
- }
- void GLRenderAPI::setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor, BlendOperation op)
- {
- GLint sourceBlend = getBlendMode(sourceFactor);
- GLint destBlend = getBlendMode(destFactor);
- if(sourceFactor == BF_ONE && destFactor == BF_ZERO)
- {
- glDisable(GL_BLEND);
- BS_CHECK_GL_ERROR();
- }
- else
- {
- glEnable(GL_BLEND);
- BS_CHECK_GL_ERROR();
- glBlendFunc(sourceBlend, destBlend);
- BS_CHECK_GL_ERROR();
- }
- GLint func = GL_FUNC_ADD;
- switch(op)
- {
- case BO_ADD:
- func = GL_FUNC_ADD;
- break;
- case BO_SUBTRACT:
- func = GL_FUNC_SUBTRACT;
- break;
- case BO_REVERSE_SUBTRACT:
- func = GL_FUNC_REVERSE_SUBTRACT;
- break;
- case BO_MIN:
- func = GL_MIN;
- break;
- case BO_MAX:
- func = GL_MAX;
- break;
- }
- if(GLEW_VERSION_1_4 || GLEW_ARB_imaging)
- {
- glBlendEquation(func);
- BS_CHECK_GL_ERROR();
- }
- else if(GLEW_EXT_blend_minmax && (func == GL_MIN || func == GL_MAX))
- {
- glBlendEquationEXT(func);
- BS_CHECK_GL_ERROR();
- }
- }
- void GLRenderAPI::setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor,
- BlendFactor sourceFactorAlpha, BlendFactor destFactorAlpha, BlendOperation op, BlendOperation alphaOp)
- {
- GLint sourceBlend = getBlendMode(sourceFactor);
- GLint destBlend = getBlendMode(destFactor);
- GLint sourceBlendAlpha = getBlendMode(sourceFactorAlpha);
- GLint destBlendAlpha = getBlendMode(destFactorAlpha);
- if(sourceFactor == BF_ONE && destFactor == BF_ZERO && sourceFactorAlpha == BF_ONE && destFactorAlpha == BF_ZERO)
- {
- glDisable(GL_BLEND);
- BS_CHECK_GL_ERROR();
- }
- else
- {
- glEnable(GL_BLEND);
- BS_CHECK_GL_ERROR();
- glBlendFuncSeparate(sourceBlend, destBlend, sourceBlendAlpha, destBlendAlpha);
- BS_CHECK_GL_ERROR();
- }
- GLint func = GL_FUNC_ADD, alphaFunc = GL_FUNC_ADD;
- switch(op)
- {
- case BO_ADD:
- func = GL_FUNC_ADD;
- break;
- case BO_SUBTRACT:
- func = GL_FUNC_SUBTRACT;
- break;
- case BO_REVERSE_SUBTRACT:
- func = GL_FUNC_REVERSE_SUBTRACT;
- break;
- case BO_MIN:
- func = GL_MIN;
- break;
- case BO_MAX:
- func = GL_MAX;
- break;
- }
- switch(alphaOp)
- {
- case BO_ADD:
- alphaFunc = GL_FUNC_ADD;
- break;
- case BO_SUBTRACT:
- alphaFunc = GL_FUNC_SUBTRACT;
- break;
- case BO_REVERSE_SUBTRACT:
- alphaFunc = GL_FUNC_REVERSE_SUBTRACT;
- break;
- case BO_MIN:
- alphaFunc = GL_MIN;
- break;
- case BO_MAX:
- alphaFunc = GL_MAX;
- break;
- }
- glBlendEquationSeparate(func, alphaFunc);
- BS_CHECK_GL_ERROR();
- }
- void GLRenderAPI::setAlphaTest(CompareFunction func, unsigned char value)
- {
- if(func == CMPF_ALWAYS_PASS)
- {
- glDisable(GL_ALPHA_TEST);
- BS_CHECK_GL_ERROR();
- }
- else
- {
- glEnable(GL_ALPHA_TEST);
- BS_CHECK_GL_ERROR();
- glAlphaFunc(convertCompareFunction(func), value / 255.0f);
- BS_CHECK_GL_ERROR();
- }
- }
- void GLRenderAPI::setAlphaToCoverage(bool enable)
- {
- static bool lasta2c = false;
- if (enable != lasta2c)
- {
- if (enable)
- {
- glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
- BS_CHECK_GL_ERROR();
- }
- else
- {
- glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
- BS_CHECK_GL_ERROR();
- }
- lasta2c = enable;
- }
- }
- void GLRenderAPI::setScissorTestEnable(bool enable)
- {
- if (mActiveRenderTarget == nullptr)
- return;
- // Calculate the "lower-left" corner of the viewport
- GLsizei x = 0, y = 0, w = 0, h = 0;
- if (enable)
- {
- glEnable(GL_SCISSOR_TEST);
- BS_CHECK_GL_ERROR();
- x = mScissorLeft;
- y = mScissorTop;
- w = mScissorRight - mScissorLeft;
- h = mScissorBottom - mScissorTop;
- glScissor(x, y, w, h);
- BS_CHECK_GL_ERROR();
- }
- else
- {
- glDisable(GL_SCISSOR_TEST);
- BS_CHECK_GL_ERROR();
- // GL requires you to reset the scissor when disabling
- w = mViewportWidth;
- h = mViewportHeight;
- x = mViewportLeft;
- y = mViewportTop;
- glScissor(x, y, w, h);
- BS_CHECK_GL_ERROR();
- }
- mScissorEnabled = enable;
- }
- void GLRenderAPI::setMultisamplingEnable(bool enable)
- {
- if (enable)
- {
- glEnable(GL_MULTISAMPLE);
- BS_CHECK_GL_ERROR();
- }
- else
- {
- glDisable(GL_MULTISAMPLE);
- BS_CHECK_GL_ERROR();
- }
- }
- void GLRenderAPI::setDepthClipEnable(bool enable)
- {
- if (enable)
- {
- glEnable(GL_DEPTH_CLAMP);
- BS_CHECK_GL_ERROR();
- }
- else
- {
- glDisable(GL_DEPTH_CLAMP);
- BS_CHECK_GL_ERROR();
- }
- }
- void GLRenderAPI::setAntialiasedLineEnable(bool enable)
- {
- if (enable)
- {
- glEnable(GL_LINE_SMOOTH);
- BS_CHECK_GL_ERROR();
- }
- else
- {
- glDisable(GL_LINE_SMOOTH);
- BS_CHECK_GL_ERROR();
- }
- }
- void GLRenderAPI::setCullingMode(CullingMode mode)
- {
- GLenum cullMode;
- switch( mode )
- {
- case CULL_NONE:
- glDisable(GL_CULL_FACE);
- BS_CHECK_GL_ERROR();
- return;
- default:
- case CULL_CLOCKWISE:
- cullMode = GL_FRONT;
- break;
- case CULL_COUNTERCLOCKWISE:
- cullMode = GL_BACK;
- break;
- }
- glEnable(GL_CULL_FACE);
- BS_CHECK_GL_ERROR();
- glCullFace(cullMode);
- BS_CHECK_GL_ERROR();
- }
- void GLRenderAPI::setDepthBufferCheckEnabled(bool enabled)
- {
- if (enabled)
- {
- glClearDepth(1.0f);
- BS_CHECK_GL_ERROR();
- glEnable(GL_DEPTH_TEST);
- BS_CHECK_GL_ERROR();
- }
- else
- {
- glDisable(GL_DEPTH_TEST);
- BS_CHECK_GL_ERROR();
- }
- }
- void GLRenderAPI::setDepthBufferWriteEnabled(bool enabled)
- {
- GLboolean flag = enabled ? GL_TRUE : GL_FALSE;
- glDepthMask(flag);
- BS_CHECK_GL_ERROR();
- mDepthWrite = enabled;
- }
- void GLRenderAPI::setDepthBufferFunction(CompareFunction func)
- {
- glDepthFunc(convertCompareFunction(func));
- BS_CHECK_GL_ERROR();
- }
- void GLRenderAPI::setDepthBias(float constantBias, float slopeScaleBias)
- {
- if (constantBias != 0 || slopeScaleBias != 0)
- {
- glEnable(GL_POLYGON_OFFSET_FILL);
- BS_CHECK_GL_ERROR();
- glEnable(GL_POLYGON_OFFSET_POINT);
- BS_CHECK_GL_ERROR();
- glEnable(GL_POLYGON_OFFSET_LINE);
- BS_CHECK_GL_ERROR();
- float scaledConstantBias = -constantBias * float((1 << 24) - 1); // Note: Assumes 24-bit depth buffer
- glPolygonOffset(slopeScaleBias, scaledConstantBias);
- BS_CHECK_GL_ERROR();
- }
- else
- {
- glDisable(GL_POLYGON_OFFSET_FILL);
- BS_CHECK_GL_ERROR();
- glDisable(GL_POLYGON_OFFSET_POINT);
- BS_CHECK_GL_ERROR();
- glDisable(GL_POLYGON_OFFSET_LINE);
- BS_CHECK_GL_ERROR();
- }
- }
- void GLRenderAPI::setColorBufferWriteEnabled(bool red, bool green, bool blue, bool alpha)
- {
- glColorMask(red, green, blue, alpha);
- BS_CHECK_GL_ERROR();
- mColorWrite[0] = red;
- mColorWrite[1] = blue;
- mColorWrite[2] = green;
- mColorWrite[3] = alpha;
- }
- void GLRenderAPI::setPolygonMode(PolygonMode level)
- {
- GLenum glmode;
- switch(level)
- {
- case PM_WIREFRAME:
- glmode = GL_LINE;
- break;
- default:
- case PM_SOLID:
- glmode = GL_FILL;
- break;
- }
- glPolygonMode(GL_FRONT_AND_BACK, glmode);
- BS_CHECK_GL_ERROR();
- }
- void GLRenderAPI::setStencilCheckEnabled(bool enabled)
- {
- if (enabled)
- {
- glEnable(GL_STENCIL_TEST);
- BS_CHECK_GL_ERROR();
- }
- else
- {
- glDisable(GL_STENCIL_TEST);
- BS_CHECK_GL_ERROR();
- }
- }
- void GLRenderAPI::setStencilBufferOperations(StencilOperation stencilFailOp,
- StencilOperation depthFailOp, StencilOperation passOp, bool front)
- {
- if (front)
- {
- glStencilOpSeparate(
- GL_FRONT,
- convertStencilOp(stencilFailOp),
- convertStencilOp(depthFailOp),
- convertStencilOp(passOp));
- BS_CHECK_GL_ERROR();
- }
- else
- {
- glStencilOpSeparate(
- GL_BACK,
- convertStencilOp(stencilFailOp, true),
- convertStencilOp(depthFailOp, true),
- convertStencilOp(passOp, true));
- BS_CHECK_GL_ERROR();
- }
- }
- void GLRenderAPI::setStencilBufferFunc(CompareFunction func, UINT32 mask, bool front)
- {
- mStencilReadMask = mask;
- if(front)
- {
- mStencilCompareFront = func;
- glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
- BS_CHECK_GL_ERROR();
- }
- else
- {
- mStencilCompareBack = func;
- glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
- BS_CHECK_GL_ERROR();
- }
- }
- void GLRenderAPI::setStencilBufferWriteMask(UINT32 mask)
- {
- mStencilWriteMask = mask;
- glStencilMask(mask);
- BS_CHECK_GL_ERROR();
- }
- void GLRenderAPI::setStencilRefValue(UINT32 refValue)
- {
- THROW_IF_NOT_CORE_THREAD;
- mStencilRefValue = refValue;
- glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
- BS_CHECK_GL_ERROR();
- glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
- BS_CHECK_GL_ERROR();
- }
- void GLRenderAPI::setTextureFiltering(UINT16 unit, FilterType ftype, FilterOptions fo)
- {
- switch(ftype)
- {
- case FT_MIN:
- mMinFilter = fo;
- // Combine with existing mip filter
- glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_MIN_FILTER, getCombinedMinMipFilter());
- BS_CHECK_GL_ERROR();
- break;
- case FT_MAG:
- switch (fo)
- {
- case FO_ANISOTROPIC: // GL treats linear and aniso the same
- case FO_LINEAR:
- glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
- BS_CHECK_GL_ERROR();
- break;
- case FO_POINT:
- case FO_NONE:
- glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
- BS_CHECK_GL_ERROR();
- break;
- default:
- break;
- }
- break;
- case FT_MIP:
- mMipFilter = fo;
- // Combine with existing min filter
- glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_MIN_FILTER, getCombinedMinMipFilter());
- BS_CHECK_GL_ERROR();
- break;
- }
- }
- void GLRenderAPI::setTextureAnisotropy(UINT16 unit, UINT32 maxAnisotropy)
- {
- GLfloat maxSupportAnisotropy = 0;
- glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maxSupportAnisotropy);
- BS_CHECK_GL_ERROR();
- if (maxAnisotropy > maxSupportAnisotropy)
- maxAnisotropy = maxSupportAnisotropy ? static_cast<UINT32>(maxSupportAnisotropy) : 1;
- if(maxAnisotropy < 1)
- maxAnisotropy = 1;
- if (getCurrentAnisotropy(unit) != maxAnisotropy)
- {
- glTexParameterf(mTextureInfos[unit].type, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)maxAnisotropy);
- BS_CHECK_GL_ERROR();
- }
- }
- void GLRenderAPI::setTextureCompareMode(UINT16 unit, CompareFunction compare)
- {
- if (compare == CMPF_ALWAYS_PASS)
- {
- glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_COMPARE_MODE, GL_NONE);
- BS_CHECK_GL_ERROR();
- }
- else
- {
- glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
- BS_CHECK_GL_ERROR();
- glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_COMPARE_FUNC, convertCompareFunction(compare));
- BS_CHECK_GL_ERROR();
- }
- }
- bool GLRenderAPI::activateGLTextureUnit(UINT16 unit)
- {
- if (mActiveTextureUnit != unit)
- {
- if (unit < getCapabilities(0).getNumCombinedTextureUnits())
- {
- glActiveTexture(GL_TEXTURE0 + unit);
- BS_CHECK_GL_ERROR();
- mActiveTextureUnit = unit;
- return true;
- }
- else if (!unit)
- {
- // Always ok to use the first unit
- return true;
- }
- else
- {
- LOGWRN("Provided texture unit index is higher than OpenGL supports. Provided: " + toString(unit) +
- ". Supported range: 0 .. " + toString(getCapabilities(0).getNumCombinedTextureUnits() - 1));
- return false;
- }
- }
- else
- {
- return true;
- }
- }
- void GLRenderAPI::beginDraw()
- {
- if(mDrawCallInProgress)
- BS_EXCEPT(InternalErrorException, "Calling beginDraw without finishing previous draw call. Please call endDraw().");
- mDrawCallInProgress = true;
- if(mCurrentVertexProgram == nullptr)
- {
- LOGWRN("Cannot render without a set vertex shader.");
- return;
- }
- if(mBoundVertexDeclaration == nullptr)
- {
- LOGWRN("Cannot render without a set vertex declaration.");
- return;
- }
- const GLSLProgramPipeline* pipeline = mProgramPipelineManager->getPipeline(mCurrentVertexProgram.get(),
- mCurrentFragmentProgram.get(), mCurrentGeometryProgram.get(), mCurrentHullProgram.get(), mCurrentDomainProgram.get());
- glUseProgram(0);
- BS_CHECK_GL_ERROR();
- if(mActivePipeline != pipeline)
- {
- glBindProgramPipeline(pipeline->glHandle);
- BS_CHECK_GL_ERROR();
- mActivePipeline = pipeline;
- }
- const GLVertexArrayObject& vao = GLVertexArrayObjectManager::instance().getVAO(
- mCurrentVertexProgram,
- mBoundVertexDeclaration,
- mBoundVertexBuffers);
- glBindVertexArray(vao.getGLHandle());
- BS_CHECK_GL_ERROR();
- BS_INC_RENDER_STAT(NumVertexBufferBinds);
- }
- void GLRenderAPI::endDraw()
- {
- if(!mDrawCallInProgress)
- return;
- mDrawCallInProgress = false;
- }
- GLfloat GLRenderAPI::getCurrentAnisotropy(UINT16 unit)
- {
- GLfloat curAniso = 0;
- glGetTexParameterfv(mTextureInfos[unit].type, GL_TEXTURE_MAX_ANISOTROPY_EXT, &curAniso);
- BS_CHECK_GL_ERROR();
- return curAniso ? curAniso : 1;
- }
- GLint GLRenderAPI::convertStencilOp(StencilOperation op, bool invert) const
- {
- switch (op)
- {
- case SOP_KEEP:
- return GL_KEEP;
- case SOP_ZERO:
- return GL_ZERO;
- case SOP_REPLACE:
- return GL_REPLACE;
- case SOP_INCREMENT:
- return invert ? GL_DECR : GL_INCR;
- case SOP_DECREMENT:
- return invert ? GL_INCR : GL_DECR;
- case SOP_INCREMENT_WRAP:
- return invert ? GL_DECR_WRAP_EXT : GL_INCR_WRAP_EXT;
- case SOP_DECREMENT_WRAP:
- return invert ? GL_INCR_WRAP_EXT : GL_DECR_WRAP_EXT;
- case SOP_INVERT:
- return GL_INVERT;
- };
- // to keep compiler happy
- return SOP_KEEP;
- }
- GLint GLRenderAPI::convertCompareFunction(CompareFunction func) const
- {
- switch (func)
- {
- case CMPF_ALWAYS_FAIL:
- return GL_NEVER;
- case CMPF_ALWAYS_PASS:
- return GL_ALWAYS;
- case CMPF_LESS:
- return GL_LESS;
- case CMPF_LESS_EQUAL:
- return GL_LEQUAL;
- case CMPF_EQUAL:
- return GL_EQUAL;
- case CMPF_NOT_EQUAL:
- return GL_NOTEQUAL;
- case CMPF_GREATER_EQUAL:
- return GL_GEQUAL;
- case CMPF_GREATER:
- return GL_GREATER;
- };
- return GL_ALWAYS;
- }
- GLuint GLRenderAPI::getCombinedMinMipFilter() const
- {
- switch (mMinFilter)
- {
- case FO_ANISOTROPIC:
- case FO_LINEAR:
- switch (mMipFilter)
- {
- case FO_ANISOTROPIC:
- case FO_LINEAR:
- // Linear min, linear mip
- return GL_LINEAR_MIPMAP_LINEAR;
- case FO_POINT:
- // Linear min, point mip
- return GL_LINEAR_MIPMAP_NEAREST;
- case FO_NONE:
- // Linear min, no mip
- return GL_LINEAR;
- default:
- break;
- }
- break;
- case FO_POINT:
- case FO_NONE:
- switch (mMipFilter)
- {
- case FO_ANISOTROPIC:
- case FO_LINEAR:
- // Nearest min, linear mip
- return GL_NEAREST_MIPMAP_LINEAR;
- case FO_POINT:
- // Nearest min, point mip
- return GL_NEAREST_MIPMAP_NEAREST;
- case FO_NONE:
- // Nearest min, no mip
- return GL_NEAREST;
- default:
- break;
- }
- break;
- default:
- break;
- }
- // Should never get here
- return 0;
- }
- GLint GLRenderAPI::getBlendMode(BlendFactor blendMode) const
- {
- switch (blendMode)
- {
- case BF_ONE:
- return GL_ONE;
- case BF_ZERO:
- return GL_ZERO;
- case BF_DEST_COLOR:
- return GL_DST_COLOR;
- case BF_SOURCE_COLOR:
- return GL_SRC_COLOR;
- case BF_INV_DEST_COLOR:
- return GL_ONE_MINUS_DST_COLOR;
- case BF_INV_SOURCE_COLOR:
- return GL_ONE_MINUS_SRC_COLOR;
- case BF_DEST_ALPHA:
- return GL_DST_ALPHA;
- case BF_SOURCE_ALPHA:
- return GL_SRC_ALPHA;
- case BF_INV_DEST_ALPHA:
- return GL_ONE_MINUS_DST_ALPHA;
- case BF_INV_SOURCE_ALPHA:
- return GL_ONE_MINUS_SRC_ALPHA;
- };
- return GL_ONE;
- }
- GLint GLRenderAPI::getTextureAddressingMode(TextureAddressingMode tam) const
- {
- switch (tam)
- {
- default:
- case TAM_WRAP:
- return GL_REPEAT;
- case TAM_MIRROR:
- return GL_MIRRORED_REPEAT;
- case TAM_CLAMP:
- return GL_CLAMP_TO_EDGE;
- case TAM_BORDER:
- return GL_CLAMP_TO_BORDER;
- }
- }
- GLint GLRenderAPI::getGLDrawMode() const
- {
- GLint primType;
- // Use adjacency if there is a geometry program and it requested adjacency info
- bool useAdjacency = (mCurrentGeometryProgram != nullptr && mCurrentGeometryProgram->isAdjacencyInfoRequired());
- switch (mCurrentDrawOperation)
- {
- case DOT_POINT_LIST:
- primType = GL_POINTS;
- break;
- case DOT_LINE_LIST:
- primType = useAdjacency ? GL_LINES_ADJACENCY_EXT : GL_LINES;
- break;
- case DOT_LINE_STRIP:
- primType = useAdjacency ? GL_LINE_STRIP_ADJACENCY_EXT : GL_LINE_STRIP;
- break;
- default:
- case DOT_TRIANGLE_LIST:
- primType = useAdjacency ? GL_TRIANGLES_ADJACENCY_EXT : GL_TRIANGLES;
- break;
- case DOT_TRIANGLE_STRIP:
- primType = useAdjacency ? GL_TRIANGLE_STRIP_ADJACENCY_EXT : GL_TRIANGLE_STRIP;
- break;
- case DOT_TRIANGLE_FAN:
- primType = GL_TRIANGLE_FAN;
- break;
- }
- return primType;
- }
- SPtr<GLSLGpuProgram> GLRenderAPI::getActiveProgram(GpuProgramType gptype) const
- {
- switch (gptype)
- {
- case GPT_VERTEX_PROGRAM:
- return mCurrentVertexProgram;
- case GPT_FRAGMENT_PROGRAM:
- return mCurrentFragmentProgram;
- case GPT_GEOMETRY_PROGRAM:
- return mCurrentGeometryProgram;
- case GPT_DOMAIN_PROGRAM:
- return mCurrentDomainProgram;
- case GPT_HULL_PROGRAM:
- return mCurrentHullProgram;
- case GPT_COMPUTE_PROGRAM:
- return mCurrentComputeProgram;
- default:
- BS_EXCEPT(InvalidParametersException, "Unsupported gpu program type: " + toString(gptype));
- }
- return nullptr;
- }
- void GLRenderAPI::initFromCaps(RenderAPICapabilities* caps)
- {
- if(caps->getRenderAPIName() != getName())
- {
- BS_EXCEPT(InvalidParametersException,
- "Trying to initialize GLRenderAPI from RenderSystemCapabilities that do not support OpenGL");
- }
- #if BS_DEBUG_MODE && (BS_OPENGL_4_3 || BS_OPENGLES_3_2)
- if (mGLSupport->checkExtension("GL_ARB_debug_output"))
- {
- glDebugMessageCallback(&openGlErrorCallback, 0);
- glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
- }
- #endif
- bs::HardwareBufferManager::startUp();
- HardwareBufferManager::startUp<GLHardwareBufferManager>();
- // GPU Program Manager setup
- if(caps->isShaderProfileSupported("glsl"))
- {
- mGLSLProgramFactory = bs_new<GLSLProgramFactory>();
- GpuProgramManager::instance().addFactory(mGLSLProgramFactory);
- }
- GLRTTManager::startUp<GLRTTManager>();
- UINT32 curTexUnitOffset = 0;
- for (UINT32 i = 0; i < 6; i++)
- curTexUnitOffset += caps->getNumTextureUnits((GpuProgramType)i);
- UINT32 totalNumTexUnits = curTexUnitOffset;
- UINT16 numCombinedTexUnits = caps->getNumCombinedTextureUnits();
- if (totalNumTexUnits > numCombinedTexUnits)
- BS_EXCEPT(InternalErrorException, "Number of combined texture units less than the number of individual units!?");
- mNumTextureUnits = numCombinedTexUnits;
- mTextureInfos = bs_newN<TextureInfo>(mNumTextureUnits);
- for (UINT16 i = 0; i < mNumTextureUnits; i++)
- mTextureInfos[i].type = GL_TEXTURE_2D;
-
- bs::TextureManager::startUp<bs::GLTextureManager>(std::ref(*mGLSupport));
- TextureManager::startUp<GLTextureManager>(std::ref(*mGLSupport));
- }
- void GLRenderAPI::switchContext(const SPtr<GLContext>& context, const RenderWindow& window)
- {
- // Unbind GPU programs and rebind to new context later, because
- // scene manager treat render system as ONE 'context' ONLY, and it
- // cached the GPU programs using state.
- setGraphicsPipeline(nullptr);
- // It's ready for switching
- if (mCurrentContext)
- mCurrentContext->endCurrent();
- mCurrentContext = context;
- mCurrentContext->setCurrent(window);
- // Must reset depth/colour write mask to according with user desired, otherwise,
- // clearFrameBuffer would be wrong because the value we recorded may be
- // different from the real state stored in GL context.
- glDepthMask(mDepthWrite);
- BS_CHECK_GL_ERROR();
- glColorMask(mColorWrite[0], mColorWrite[1], mColorWrite[2], mColorWrite[3]);
- BS_CHECK_GL_ERROR();
- glStencilMask(mStencilWriteMask);
- BS_CHECK_GL_ERROR();
- }
- void GLRenderAPI::initCapabilities(RenderAPICapabilities& caps) const
- {
- Vector<String> tokens = StringUtil::split(mGLSupport->getGLVersion(), ".");
- DriverVersion driverVersion;
- if (!tokens.empty())
- {
- driverVersion.major = parseINT32(tokens[0]);
- if (tokens.size() > 1)
- driverVersion.minor = parseINT32(tokens[1]);
- if (tokens.size() > 2)
- driverVersion.release = parseINT32(tokens[2]);
- }
- driverVersion.build = 0;
- caps.setDriverVersion(driverVersion);
- const char* deviceName = (const char*)glGetString(GL_RENDERER);
- const char* vendorName = (const char*)glGetString(GL_VENDOR);
- caps.setDeviceName(deviceName);
- caps.setRenderAPIName(getName());
- // determine vendor
- if (strstr(vendorName, "NVIDIA"))
- caps.setVendor(GPU_NVIDIA);
- else if (strstr(vendorName, "ATI"))
- caps.setVendor(GPU_AMD);
- else if (strstr(vendorName, "AMD"))
- caps.setVendor(GPU_AMD);
- else if (strstr(vendorName, "Intel"))
- caps.setVendor(GPU_INTEL);
- else
- caps.setVendor(GPU_UNKNOWN);
- caps.addShaderProfile("glsl");
- caps.setCapability(RSC_TEXTURE_COMPRESSION_BC);
- // Check if geometry shaders are supported
- if (getGLSupport()->checkExtension("GL_EXT_geometry_shader4"))
- {
- #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
- caps.setCapability(RSC_GEOMETRY_PROGRAM);
- #endif
- GLint maxOutputVertices;
- #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
- glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT,&maxOutputVertices);
- BS_CHECK_GL_ERROR();
- #else
- maxOutputVertices = 0;
- #endif
- caps.setGeometryProgramNumOutputVertices(maxOutputVertices);
- }
- // Max number of fragment shader textures
- GLint units;
- glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &units);
- BS_CHECK_GL_ERROR();
- caps.setNumTextureUnits(GPT_FRAGMENT_PROGRAM, static_cast<UINT16>(units));
- // Max number of vertex shader textures
- GLint vUnits;
- glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &vUnits);
- BS_CHECK_GL_ERROR();
- caps.setNumTextureUnits(GPT_VERTEX_PROGRAM, static_cast<UINT16>(vUnits));
- GLint numUniformBlocks;
- glGetIntegerv(GL_MAX_VERTEX_UNIFORM_BLOCKS, &numUniformBlocks);
- BS_CHECK_GL_ERROR();
- caps.setNumGpuParamBlockBuffers(GPT_VERTEX_PROGRAM, numUniformBlocks);
- glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_BLOCKS, &numUniformBlocks);
- BS_CHECK_GL_ERROR();
- caps.setNumGpuParamBlockBuffers(GPT_FRAGMENT_PROGRAM, numUniformBlocks);
- if (mGLSupport->checkExtension("GL_ARB_geometry_shader4"))
- {
- GLint geomUnits;
- #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
- glGetIntegerv(GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS, &geomUnits);
- BS_CHECK_GL_ERROR();
- #else
- geomUnits = 0;
- #endif
- caps.setNumTextureUnits(GPT_GEOMETRY_PROGRAM, static_cast<UINT16>(geomUnits));
- #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
- glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_BLOCKS, &numUniformBlocks);
- BS_CHECK_GL_ERROR();
- #else
- numUniformBlocks = 0;
- #endif
- caps.setNumGpuParamBlockBuffers(GPT_GEOMETRY_PROGRAM, numUniformBlocks);
- }
- if (mGLSupport->checkExtension("GL_ARB_tessellation_shader"))
- {
- #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
- caps.setCapability(RSC_TESSELLATION_PROGRAM);
- #endif
- #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
- glGetIntegerv(GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS, &numUniformBlocks);
- BS_CHECK_GL_ERROR();
- #else
- numUniformBlocks = 0;
- #endif
- caps.setNumGpuParamBlockBuffers(GPT_HULL_PROGRAM, numUniformBlocks);
- #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
- glGetIntegerv(GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS, &numUniformBlocks);
- BS_CHECK_GL_ERROR();
- #else
- numUniformBlocks = 0;
- #endif
- caps.setNumGpuParamBlockBuffers(GPT_DOMAIN_PROGRAM, numUniformBlocks);
- }
- if (mGLSupport->checkExtension("GL_ARB_compute_shader"))
- {
- #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
- caps.setCapability(RSC_COMPUTE_PROGRAM);
- #endif
- GLint computeUnits;
- #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
- glGetIntegerv(GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS, &computeUnits);
- BS_CHECK_GL_ERROR();
- #else
- computeUnits = 0;
- #endif
- caps.setNumTextureUnits(GPT_COMPUTE_PROGRAM, static_cast<UINT16>(computeUnits));
- #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
- glGetIntegerv(GL_MAX_COMPUTE_UNIFORM_BLOCKS, &numUniformBlocks);
- BS_CHECK_GL_ERROR();
- #else
- numUniformBlocks = 0;
- #endif
- caps.setNumGpuParamBlockBuffers(GPT_COMPUTE_PROGRAM, numUniformBlocks);
- // Max number of load-store textures
- GLint lsfUnits;
- #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
- glGetIntegerv(GL_MAX_FRAGMENT_IMAGE_UNIFORMS, &lsfUnits);
- BS_CHECK_GL_ERROR();
- #else
- lsfUnits = 0;
- #endif
- caps.setNumLoadStoreTextureUnits(GPT_FRAGMENT_PROGRAM, static_cast<UINT16>(lsfUnits));
- GLint lscUnits;
- #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
- glGetIntegerv(GL_MAX_COMPUTE_IMAGE_UNIFORMS, &lscUnits);
- BS_CHECK_GL_ERROR();
- #else
- lscUnits = 0;
- #endif
- caps.setNumLoadStoreTextureUnits(GPT_COMPUTE_PROGRAM, static_cast<UINT16>(lscUnits));
- GLint combinedLoadStoreTextureUnits;
- #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
- glGetIntegerv(GL_MAX_IMAGE_UNITS, &combinedLoadStoreTextureUnits);
- BS_CHECK_GL_ERROR();
- #else
- combinedLoadStoreTextureUnits = 0;
- #endif
- caps.setNumCombinedLoadStoreTextureUnits(static_cast<UINT16>(combinedLoadStoreTextureUnits));
- }
- GLint combinedTexUnits;
- glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &combinedTexUnits);
- BS_CHECK_GL_ERROR();
- caps.setNumCombinedTextureUnits(static_cast<UINT16>(combinedTexUnits));
- GLint combinedUniformBlockUnits;
- glGetIntegerv(GL_MAX_COMBINED_UNIFORM_BLOCKS, &combinedUniformBlockUnits);
- BS_CHECK_GL_ERROR();
- caps.setNumCombinedGpuParamBlockBuffers(static_cast<UINT16>(combinedUniformBlockUnits));
- caps.setNumMultiRenderTargets(8);
- }
- void GLRenderAPI::makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m)
- {
- UINT32 x = 0;
- for (UINT32 i = 0; i < 4; i++)
- {
- for (UINT32 j = 0; j < 4; j++)
- {
- gl_matrix[x] = m[j][i];
- x++;
- }
- }
- }
- void GLRenderAPI::applyViewport()
- {
- if (mActiveRenderTarget == nullptr)
- return;
- const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
- // Calculate the "lower-left" corner of the viewport
- mViewportLeft = (UINT32)(rtProps.width * mViewportNorm.x);
- mViewportTop = (UINT32)(rtProps.height * mViewportNorm.y);
- mViewportWidth = (UINT32)(rtProps.width * mViewportNorm.width);
- mViewportHeight = (UINT32)(rtProps.height * mViewportNorm.height);
- glViewport(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
- BS_CHECK_GL_ERROR();
- // Configure the viewport clipping
- if (!mScissorEnabled)
- {
- glEnable(GL_SCISSOR_TEST);
- BS_CHECK_GL_ERROR();
- glScissor(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
- BS_CHECK_GL_ERROR();
- }
- }
- /************************************************************************/
- /* UTILITY */
- /************************************************************************/
- void GLRenderAPI::convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest)
- {
- dest = matrix;
- }
- const RenderAPIInfo& GLRenderAPI::getAPIInfo() const
- {
- RenderAPIFeatures featureFlags =
- RenderAPIFeatureFlag::UVYAxisUp |
- RenderAPIFeatureFlag::ColumnMajorMatrices |
- RenderAPIFeatureFlag::MSAAImageStores;
- #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
- featureFlags |= RenderAPIFeatureFlag::TextureViews;
- featureFlags |= RenderAPIFeatureFlag::Compute;
- #endif
- #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
- featureFlags |= RenderAPIFeatureFlag::LoadStore;
- #endif
- static RenderAPIInfo info(0.0f, 0.0f, -1.0f, 1.0f, VET_COLOR_ABGR, featureFlags);
-
- return info;
- }
- GpuParamBlockDesc GLRenderAPI::generateParamBlockDesc(const String& name, Vector<GpuParamDataDesc>& params)
- {
- GpuParamBlockDesc block;
- block.blockSize = 0;
- block.isShareable = true;
- block.name = name;
- block.slot = 0;
- block.set = 0;
- for (auto& param : params)
- {
- const GpuParamDataTypeInfo& typeInfo = bs::GpuParams::PARAM_SIZES.lookup[param.type];
- UINT32 size = typeInfo.size / 4;
- UINT32 alignment = typeInfo.alignment / 4;
- // Fix alignment if needed
- UINT32 alignOffset = block.blockSize % alignment;
- if (alignOffset != 0)
- {
- UINT32 padding = (alignment - alignOffset);
- block.blockSize += padding;
- }
- if (param.arraySize > 1)
- {
- // Array elements are always padded and aligned to vec4
- alignOffset = size % typeInfo.baseTypeSize;
- if (alignOffset != 0)
- {
- UINT32 padding = (typeInfo.baseTypeSize - alignOffset);
- size += padding;
- }
- alignOffset = block.blockSize % typeInfo.baseTypeSize;
- if (alignOffset != 0)
- {
- UINT32 padding = (typeInfo.baseTypeSize - alignOffset);
- block.blockSize += padding;
- }
- param.elementSize = size;
- param.arrayElementStride = size;
- param.cpuMemOffset = block.blockSize;
- param.gpuMemOffset = 0;
-
- block.blockSize += size * param.arraySize;
- }
- else
- {
- param.elementSize = size;
- param.arrayElementStride = size;
- param.cpuMemOffset = block.blockSize;
- param.gpuMemOffset = 0;
- block.blockSize += size;
- }
- param.paramBlockSlot = 0;
- param.paramBlockSet = 0;
- }
- // Constant buffer size must always be a multiple of 16
- if (block.blockSize % 4 != 0)
- block.blockSize += (4 - (block.blockSize % 4));
- return block;
- }
- #if BS_OPENGL_4_3 || BS_OPENGLES_3_2
- void openGlErrorCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length,
- const GLchar *message, GLvoid *userParam)
- {
- if (type != GL_DEBUG_TYPE_PERFORMANCE && type != GL_DEBUG_TYPE_OTHER)
- {
- BS_EXCEPT(RenderingAPIException, "OpenGL error: " + String(message));
- }
- }
- #endif
- }}
|