From: numzero Date: Sat, 25 Mar 2023 08:11:09 +0000 (+0300) Subject: Fix line endings in the new driver X-Git-Url: https://git.lizzy.rs/?a=commitdiff_plain;h=219b7fd7d2d884fddb4c12723361c3c342fb9294;p=irrlicht.git Fix line endings in the new driver --- diff --git a/source/Irrlicht/OpenGL/Common.h b/source/Irrlicht/OpenGL/Common.h index a69bcc6..4069307 100644 --- a/source/Irrlicht/OpenGL/Common.h +++ b/source/Irrlicht/OpenGL/Common.h @@ -1,36 +1,36 @@ -// Copyright (C) 2023 Vitaliy Lobachevskiy -// Copyright (C) 2015 Patryk Nadrowski -// This file is part of the "Irrlicht Engine". -// For conditions of distribution and use, see copyright notice in irrlicht.h - -#pragma once - -#define GL_GLEXT_PROTOTYPES -#include -#include - -namespace irr -{ -namespace video -{ - - // Forward declarations. - - class COpenGLCoreFeature; - - template - class COpenGLCoreTexture; - - template - class COpenGLCoreRenderTarget; - - template - class COpenGLCoreCacheHandler; - - class COpenGL3DriverBase; - typedef COpenGLCoreTexture COpenGL3Texture; - typedef COpenGLCoreRenderTarget COpenGL3RenderTarget; - typedef COpenGLCoreCacheHandler COpenGL3CacheHandler; - -} -} +// Copyright (C) 2023 Vitaliy Lobachevskiy +// Copyright (C) 2015 Patryk Nadrowski +// This file is part of the "Irrlicht Engine". +// For conditions of distribution and use, see copyright notice in irrlicht.h + +#pragma once + +#define GL_GLEXT_PROTOTYPES +#include +#include + +namespace irr +{ +namespace video +{ + + // Forward declarations. + + class COpenGLCoreFeature; + + template + class COpenGLCoreTexture; + + template + class COpenGLCoreRenderTarget; + + template + class COpenGLCoreCacheHandler; + + class COpenGL3DriverBase; + typedef COpenGLCoreTexture COpenGL3Texture; + typedef COpenGLCoreRenderTarget COpenGL3RenderTarget; + typedef COpenGLCoreCacheHandler COpenGL3CacheHandler; + +} +} diff --git a/source/Irrlicht/OpenGL/Driver.cpp b/source/Irrlicht/OpenGL/Driver.cpp index 9baefc2..641536f 100644 --- a/source/Irrlicht/OpenGL/Driver.cpp +++ b/source/Irrlicht/OpenGL/Driver.cpp @@ -1,2389 +1,2389 @@ -// Copyright (C) 2023 Vitaliy Lobachevskiy -// Copyright (C) 2014 Patryk Nadrowski -// Copyright (C) 2009-2010 Amundis -// This file is part of the "Irrlicht Engine". -// For conditions of distribution and use, see copyright notice in Irrlicht.h - -#include "Driver.h" -#include -#include "CNullDriver.h" -#include "IContextManager.h" - -#include "COpenGLCoreTexture.h" -#include "COpenGLCoreRenderTarget.h" -#include "COpenGLCoreCacheHandler.h" - -#include "MaterialRenderer.h" -#include "FixedPipelineRenderer.h" -#include "Renderer2D.h" - -#include "EVertexAttributes.h" -#include "CImage.h" -#include "os.h" - -#ifdef _IRR_COMPILE_WITH_ANDROID_DEVICE_ -#include "android_native_app_glue.h" -#endif - -#include "mt_opengl.h" - -namespace irr -{ -namespace video -{ - struct VertexAttribute { - enum class Mode { - Regular, - Normalized, - Integral, - }; - int Index; - int ComponentCount; - GLenum ComponentType; - Mode mode; - int Offset; - }; - - struct VertexType { - int VertexSize; - int AttributeCount; - VertexAttribute Attributes[]; - - VertexType(const VertexType &) = delete; - VertexType &operator= (const VertexType &) = delete; - }; - - static const VertexAttribute *begin(const VertexType &type) - { - return type.Attributes; - } - - static const VertexAttribute *end(const VertexType &type) - { - return type.Attributes + type.AttributeCount; - } - - static constexpr VertexType vtStandard = { - sizeof(S3DVertex), 4, { - {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Pos)}, - {EVA_NORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Normal)}, - {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex, Color)}, - {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, TCoords)}, - }, - }; - -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Winvalid-offsetof" - - static constexpr VertexType vt2TCoords = { - sizeof(S3DVertex2TCoords), 5, { - {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, Pos)}, - {EVA_NORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, Normal)}, - {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex2TCoords, Color)}, - {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, TCoords)}, - {EVA_TCOORD1, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, TCoords2)}, - }, - }; - - static constexpr VertexType vtTangents = { - sizeof(S3DVertexTangents), 6, { - {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Pos)}, - {EVA_NORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Normal)}, - {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertexTangents, Color)}, - {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, TCoords)}, - {EVA_TANGENT, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Tangent)}, - {EVA_BINORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Binormal)}, - }, - }; - -#pragma GCC diagnostic pop - - static const VertexType &getVertexTypeDescription(E_VERTEX_TYPE type) - { - switch (type) { - case EVT_STANDARD: return vtStandard; - case EVT_2TCOORDS: return vt2TCoords; - case EVT_TANGENTS: return vtTangents; - default: assert(false); - } - } - - static constexpr VertexType vt2DImage = { - sizeof(S3DVertex), 3, { - {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Pos)}, - {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex, Color)}, - {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, TCoords)}, - }, - }; - - static constexpr VertexType vtPrimitive = { - sizeof(S3DVertex), 2, { - {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Pos)}, - {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex, Color)}, - }, - }; - - -void APIENTRY COpenGL3DriverBase::debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) -{ - ((COpenGL3DriverBase *)userParam)->debugCb(source, type, id, severity, length, message); -} - -void COpenGL3DriverBase::debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message) -{ - printf("%04x %04x %x %x %.*s\n", source, type, id, severity, length, message); -} - -COpenGL3DriverBase::COpenGL3DriverBase(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager) : - CNullDriver(io, params.WindowSize), COpenGL3ExtensionHandler(), CacheHandler(0), - Params(params), ResetRenderStates(true), LockRenderStateMode(false), AntiAlias(params.AntiAlias), - MaterialRenderer2DActive(0), MaterialRenderer2DTexture(0), MaterialRenderer2DNoTexture(0), - CurrentRenderMode(ERM_NONE), Transformation3DChanged(true), - OGLES2ShaderPath(params.OGLES2ShaderPath), - ColorFormat(ECF_R8G8B8), ContextManager(contextManager) -{ -#ifdef _DEBUG - setDebugName("Driver"); -#endif - - if (!ContextManager) - return; - - ContextManager->grab(); - ContextManager->generateSurface(); - ContextManager->generateContext(); - ExposedData = ContextManager->getContext(); - ContextManager->activateContext(ExposedData, false); - GL.LoadAllProcedures(ContextManager); - GL.DebugMessageCallback(debugCb, this); - initQuadsIndices(); -} - -COpenGL3DriverBase::~COpenGL3DriverBase() -{ - deleteMaterialRenders(); - - CacheHandler->getTextureCache().clear(); - - removeAllRenderTargets(); - deleteAllTextures(); - removeAllOcclusionQueries(); - removeAllHardwareBuffers(); - - delete MaterialRenderer2DTexture; - delete MaterialRenderer2DNoTexture; - delete CacheHandler; - - if (ContextManager) - { - ContextManager->destroyContext(); - ContextManager->destroySurface(); - ContextManager->terminate(); - ContextManager->drop(); - } -} - - void COpenGL3DriverBase::initQuadsIndices(int max_vertex_count) - { - int max_quad_count = max_vertex_count / 4; - QuadsIndices.reserve(6 * max_quad_count); - for (int k = 0; k < max_quad_count; k++) { - QuadsIndices.push_back(4 * k + 0); - QuadsIndices.push_back(4 * k + 1); - QuadsIndices.push_back(4 * k + 2); - QuadsIndices.push_back(4 * k + 0); - QuadsIndices.push_back(4 * k + 2); - QuadsIndices.push_back(4 * k + 3); - } - } - - bool COpenGL3DriverBase::genericDriverInit(const core::dimension2d& screenSize, bool stencilBuffer) - { - Name = glGetString(GL_VERSION); - printVersion(); - - // print renderer information - VendorName = glGetString(GL_VENDOR); - os::Printer::log(VendorName.c_str(), ELL_INFORMATION); - - // load extensions - initExtensions(); - - // reset cache handler - delete CacheHandler; - CacheHandler = new COpenGL3CacheHandler(this); - - StencilBuffer = stencilBuffer; - - DriverAttributes->setAttribute("MaxTextures", (s32)Feature.MaxTextureUnits); - DriverAttributes->setAttribute("MaxSupportedTextures", (s32)Feature.MaxTextureUnits); -// DriverAttributes->setAttribute("MaxLights", MaxLights); - DriverAttributes->setAttribute("MaxAnisotropy", MaxAnisotropy); -// DriverAttributes->setAttribute("MaxUserClipPlanes", MaxUserClipPlanes); -// DriverAttributes->setAttribute("MaxAuxBuffers", MaxAuxBuffers); -// DriverAttributes->setAttribute("MaxMultipleRenderTargets", MaxMultipleRenderTargets); - DriverAttributes->setAttribute("MaxIndices", (s32)MaxIndices); - DriverAttributes->setAttribute("MaxTextureSize", (s32)MaxTextureSize); - DriverAttributes->setAttribute("MaxTextureLODBias", MaxTextureLODBias); - DriverAttributes->setAttribute("Version", Version); - DriverAttributes->setAttribute("AntiAlias", AntiAlias); - - glPixelStorei(GL_PACK_ALIGNMENT, 1); - - UserClipPlane.reallocate(0); - - for (s32 i = 0; i < ETS_COUNT; ++i) - setTransform(static_cast(i), core::IdentityMatrix); - - setAmbientLight(SColorf(0.0f, 0.0f, 0.0f, 0.0f)); - glClearDepthf(1.0f); - - glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST); - glFrontFace(GL_CW); - - // create material renderers - createMaterialRenderers(); - - // set the renderstates - setRenderStates3DMode(); - - // set fog mode - setFog(FogColor, FogType, FogStart, FogEnd, FogDensity, PixelFog, RangeFog); - - // create matrix for flipping textures - TextureFlipMatrix.buildTextureTransform(0.0f, core::vector2df(0, 0), core::vector2df(0, 1.0f), core::vector2df(1.0f, -1.0f)); - - // We need to reset once more at the beginning of the first rendering. - // This fixes problems with intermediate changes to the material during texture load. - ResetRenderStates = true; - - testGLError(__LINE__); - - return true; - } - - void COpenGL3DriverBase::loadShaderData(const io::path& vertexShaderName, const io::path& fragmentShaderName, c8** vertexShaderData, c8** fragmentShaderData) - { - io::path vsPath(OGLES2ShaderPath); - vsPath += vertexShaderName; - - io::path fsPath(OGLES2ShaderPath); - fsPath += fragmentShaderName; - - *vertexShaderData = 0; - *fragmentShaderData = 0; - - io::IReadFile* vsFile = FileSystem->createAndOpenFile(vsPath); - if ( !vsFile ) - { - core::stringw warning(L"Warning: Missing shader files needed to simulate fixed function materials:\n"); - warning += core::stringw(vsPath) + L"\n"; - warning += L"Shaderpath can be changed in SIrrCreationParamters::OGLES2ShaderPath"; - os::Printer::log(warning.c_str(), ELL_WARNING); - return; - } - - io::IReadFile* fsFile = FileSystem->createAndOpenFile(fsPath); - if ( !fsFile ) - { - core::stringw warning(L"Warning: Missing shader files needed to simulate fixed function materials:\n"); - warning += core::stringw(fsPath) + L"\n"; - warning += L"Shaderpath can be changed in SIrrCreationParamters::OGLES2ShaderPath"; - os::Printer::log(warning.c_str(), ELL_WARNING); - return; - } - - long size = vsFile->getSize(); - if (size) - { - *vertexShaderData = new c8[size+1]; - vsFile->read(*vertexShaderData, size); - (*vertexShaderData)[size] = 0; - } - - size = fsFile->getSize(); - if (size) - { - // if both handles are the same we must reset the file - if (fsFile == vsFile) - fsFile->seek(0); - - *fragmentShaderData = new c8[size+1]; - fsFile->read(*fragmentShaderData, size); - (*fragmentShaderData)[size] = 0; - } - - vsFile->drop(); - fsFile->drop(); - } - - void COpenGL3DriverBase::createMaterialRenderers() - { - // Create callbacks. - - COpenGL3MaterialSolidCB* SolidCB = new COpenGL3MaterialSolidCB(); - COpenGL3MaterialSolid2CB* Solid2LayerCB = new COpenGL3MaterialSolid2CB(); - COpenGL3MaterialLightmapCB* LightmapCB = new COpenGL3MaterialLightmapCB(1.f); - COpenGL3MaterialLightmapCB* LightmapAddCB = new COpenGL3MaterialLightmapCB(1.f); - COpenGL3MaterialLightmapCB* LightmapM2CB = new COpenGL3MaterialLightmapCB(2.f); - COpenGL3MaterialLightmapCB* LightmapM4CB = new COpenGL3MaterialLightmapCB(4.f); - COpenGL3MaterialLightmapCB* LightmapLightingCB = new COpenGL3MaterialLightmapCB(1.f); - COpenGL3MaterialLightmapCB* LightmapLightingM2CB = new COpenGL3MaterialLightmapCB(2.f); - COpenGL3MaterialLightmapCB* LightmapLightingM4CB = new COpenGL3MaterialLightmapCB(4.f); - COpenGL3MaterialSolid2CB* DetailMapCB = new COpenGL3MaterialSolid2CB(); - COpenGL3MaterialReflectionCB* SphereMapCB = new COpenGL3MaterialReflectionCB(); - COpenGL3MaterialReflectionCB* Reflection2LayerCB = new COpenGL3MaterialReflectionCB(); - COpenGL3MaterialSolidCB* TransparentAddColorCB = new COpenGL3MaterialSolidCB(); - COpenGL3MaterialSolidCB* TransparentAlphaChannelCB = new COpenGL3MaterialSolidCB(); - COpenGL3MaterialSolidCB* TransparentAlphaChannelRefCB = new COpenGL3MaterialSolidCB(); - COpenGL3MaterialSolidCB* TransparentVertexAlphaCB = new COpenGL3MaterialSolidCB(); - COpenGL3MaterialReflectionCB* TransparentReflection2LayerCB = new COpenGL3MaterialReflectionCB(); - COpenGL3MaterialOneTextureBlendCB* OneTextureBlendCB = new COpenGL3MaterialOneTextureBlendCB(); - - // Create built-in materials. - - core::stringc VertexShader = OGLES2ShaderPath + "Solid.vsh"; - core::stringc FragmentShader = OGLES2ShaderPath + "Solid.fsh"; - - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", - EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, SolidCB, EMT_SOLID, 0); - - VertexShader = OGLES2ShaderPath + "Solid2.vsh"; - FragmentShader = OGLES2ShaderPath + "Solid2Layer.fsh"; - - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", - EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, Solid2LayerCB, EMT_SOLID, 0); - - VertexShader = OGLES2ShaderPath + "Solid2.vsh"; - FragmentShader = OGLES2ShaderPath + "LightmapModulate.fsh"; - - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", - EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, LightmapCB, EMT_SOLID, 0); - - FragmentShader = OGLES2ShaderPath + "LightmapAdd.fsh"; - - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", - EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, LightmapAddCB, EMT_SOLID, 0); - - FragmentShader = OGLES2ShaderPath + "LightmapModulate.fsh"; - - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", - EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, LightmapM2CB, EMT_SOLID, 0); - - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", - EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, LightmapM4CB, EMT_SOLID, 0); - - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", - EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, LightmapLightingCB, EMT_SOLID, 0); - - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", - EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, LightmapLightingM2CB, EMT_SOLID, 0); - - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", - EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, LightmapLightingM4CB, EMT_SOLID, 0); - - VertexShader = OGLES2ShaderPath + "Solid2.vsh"; - FragmentShader = OGLES2ShaderPath + "DetailMap.fsh"; - - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", - EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, DetailMapCB, EMT_SOLID, 0); - - VertexShader = OGLES2ShaderPath + "SphereMap.vsh"; - FragmentShader = OGLES2ShaderPath + "SphereMap.fsh"; - - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", - EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, SphereMapCB, EMT_SOLID, 0); - - VertexShader = OGLES2ShaderPath + "Reflection2Layer.vsh"; - FragmentShader = OGLES2ShaderPath + "Reflection2Layer.fsh"; - - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", - EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, Reflection2LayerCB, EMT_SOLID, 0); - - VertexShader = OGLES2ShaderPath + "Solid.vsh"; - FragmentShader = OGLES2ShaderPath + "Solid.fsh"; - - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", - EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentAddColorCB, EMT_TRANSPARENT_ADD_COLOR, 0); - - FragmentShader = OGLES2ShaderPath + "TransparentAlphaChannel.fsh"; - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", - EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentAlphaChannelCB, EMT_TRANSPARENT_ALPHA_CHANNEL, 0); - - FragmentShader = OGLES2ShaderPath + "TransparentAlphaChannelRef.fsh"; - - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", - EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentAlphaChannelRefCB, EMT_SOLID, 0); - - FragmentShader = OGLES2ShaderPath + "TransparentVertexAlpha.fsh"; - - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", - EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentVertexAlphaCB, EMT_TRANSPARENT_ALPHA_CHANNEL, 0); - - VertexShader = OGLES2ShaderPath + "Reflection2Layer.vsh"; - FragmentShader = OGLES2ShaderPath + "Reflection2Layer.fsh"; - - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", - EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentReflection2LayerCB, EMT_TRANSPARENT_ALPHA_CHANNEL, 0); - - VertexShader = OGLES2ShaderPath + "Solid.vsh"; - FragmentShader = OGLES2ShaderPath + "OneTextureBlend.fsh"; - - addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", - EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, OneTextureBlendCB, EMT_ONETEXTURE_BLEND, 0); - - // Drop callbacks. - - SolidCB->drop(); - Solid2LayerCB->drop(); - LightmapCB->drop(); - LightmapAddCB->drop(); - LightmapM2CB->drop(); - LightmapM4CB->drop(); - LightmapLightingCB->drop(); - LightmapLightingM2CB->drop(); - LightmapLightingM4CB->drop(); - DetailMapCB->drop(); - SphereMapCB->drop(); - Reflection2LayerCB->drop(); - TransparentAddColorCB->drop(); - TransparentAlphaChannelCB->drop(); - TransparentAlphaChannelRefCB->drop(); - TransparentVertexAlphaCB->drop(); - TransparentReflection2LayerCB->drop(); - OneTextureBlendCB->drop(); - - // Create 2D material renderers - - c8* vs2DData = 0; - c8* fs2DData = 0; - loadShaderData(io::path("Renderer2D.vsh"), io::path("Renderer2D.fsh"), &vs2DData, &fs2DData); - MaterialRenderer2DTexture = new COpenGL3Renderer2D(vs2DData, fs2DData, this, true); - delete[] vs2DData; - delete[] fs2DData; - vs2DData = 0; - fs2DData = 0; - - loadShaderData(io::path("Renderer2D.vsh"), io::path("Renderer2D_noTex.fsh"), &vs2DData, &fs2DData); - MaterialRenderer2DNoTexture = new COpenGL3Renderer2D(vs2DData, fs2DData, this, false); - delete[] vs2DData; - delete[] fs2DData; - } - - bool COpenGL3DriverBase::setMaterialTexture(irr::u32 layerIdx, const irr::video::ITexture* texture) - { - Material.TextureLayer[layerIdx].Texture = const_cast(texture); // function uses const-pointer for texture because all draw functions use const-pointers already - return CacheHandler->getTextureCache().set(0, texture); - } - - bool COpenGL3DriverBase::beginScene(u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil, const SExposedVideoData& videoData, core::rect* sourceRect) - { - CNullDriver::beginScene(clearFlag, clearColor, clearDepth, clearStencil, videoData, sourceRect); - - if (ContextManager) - ContextManager->activateContext(videoData, true); - - clearBuffers(clearFlag, clearColor, clearDepth, clearStencil); - - return true; - } - - bool COpenGL3DriverBase::endScene() - { - CNullDriver::endScene(); - - glFlush(); - - if (ContextManager) - return ContextManager->swapBuffers(); - - return false; - } - - - //! Returns the transformation set by setTransform - const core::matrix4& COpenGL3DriverBase::getTransform(E_TRANSFORMATION_STATE state) const - { - return Matrices[state]; - } - - - //! sets transformation - void COpenGL3DriverBase::setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat) - { - Matrices[state] = mat; - Transformation3DChanged = true; - } - - - bool COpenGL3DriverBase::updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) - { - if (!HWBuffer) - return false; - - const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer; - const void* vertices = mb->getVertices(); - const u32 vertexCount = mb->getVertexCount(); - const E_VERTEX_TYPE vType = mb->getVertexType(); - const u32 vertexSize = getVertexPitchFromType(vType); - - const void *buffer = vertices; - size_t bufferSize = vertexSize * vertexCount; - - //get or create buffer - bool newBuffer = false; - if (!HWBuffer->vbo_verticesID) - { - glGenBuffers(1, &HWBuffer->vbo_verticesID); - if (!HWBuffer->vbo_verticesID) return false; - newBuffer = true; - } - else if (HWBuffer->vbo_verticesSize < bufferSize) - { - newBuffer = true; - } - - glBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID); - - // copy data to graphics card - if (!newBuffer) - glBufferSubData(GL_ARRAY_BUFFER, 0, bufferSize, buffer); - else - { - HWBuffer->vbo_verticesSize = bufferSize; - - if (HWBuffer->Mapped_Vertex == scene::EHM_STATIC) - glBufferData(GL_ARRAY_BUFFER, bufferSize, buffer, GL_STATIC_DRAW); - else - glBufferData(GL_ARRAY_BUFFER, bufferSize, buffer, GL_DYNAMIC_DRAW); - } - - glBindBuffer(GL_ARRAY_BUFFER, 0); - - return (!testGLError(__LINE__)); - } - - - bool COpenGL3DriverBase::updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) - { - if (!HWBuffer) - return false; - - const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer; - - const void* indices = mb->getIndices(); - u32 indexCount = mb->getIndexCount(); - - GLenum indexSize; - switch (mb->getIndexType()) - { - case(EIT_16BIT): - { - indexSize = sizeof(u16); - break; - } - case(EIT_32BIT): - { - indexSize = sizeof(u32); - break; - } - default: - { - return false; - } - } - - //get or create buffer - bool newBuffer = false; - if (!HWBuffer->vbo_indicesID) - { - glGenBuffers(1, &HWBuffer->vbo_indicesID); - if (!HWBuffer->vbo_indicesID) return false; - newBuffer = true; - } - else if (HWBuffer->vbo_indicesSize < indexCount*indexSize) - { - newBuffer = true; - } - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID); - - // copy data to graphics card - if (!newBuffer) - glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, indexCount * indexSize, indices); - else - { - HWBuffer->vbo_indicesSize = indexCount * indexSize; - - if (HWBuffer->Mapped_Index == scene::EHM_STATIC) - glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, GL_STATIC_DRAW); - else - glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, GL_DYNAMIC_DRAW); - } - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - - return (!testGLError(__LINE__)); - } - - - //! updates hardware buffer if needed - bool COpenGL3DriverBase::updateHardwareBuffer(SHWBufferLink *HWBuffer) - { - if (!HWBuffer) - return false; - - if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) - { - if (HWBuffer->ChangedID_Vertex != HWBuffer->MeshBuffer->getChangedID_Vertex() - || !static_cast(HWBuffer)->vbo_verticesID) - { - - HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex(); - - if (!updateVertexHardwareBuffer(static_cast(HWBuffer))) - return false; - } - } - - if (HWBuffer->Mapped_Index != scene::EHM_NEVER) - { - if (HWBuffer->ChangedID_Index != HWBuffer->MeshBuffer->getChangedID_Index() - || !static_cast(HWBuffer)->vbo_indicesID) - { - - HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index(); - - if (!updateIndexHardwareBuffer((SHWBufferLink_opengl*)HWBuffer)) - return false; - } - } - - return true; - } - - - //! Create hardware buffer from meshbuffer - COpenGL3DriverBase::SHWBufferLink *COpenGL3DriverBase::createHardwareBuffer(const scene::IMeshBuffer* mb) - { - if (!mb || (mb->getHardwareMappingHint_Index() == scene::EHM_NEVER && mb->getHardwareMappingHint_Vertex() == scene::EHM_NEVER)) - return 0; - - SHWBufferLink_opengl *HWBuffer = new SHWBufferLink_opengl(mb); - - //add to map - HWBuffer->listPosition = HWBufferList.insert(HWBufferList.end(), HWBuffer); - - HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex(); - HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index(); - HWBuffer->Mapped_Vertex = mb->getHardwareMappingHint_Vertex(); - HWBuffer->Mapped_Index = mb->getHardwareMappingHint_Index(); - HWBuffer->vbo_verticesID = 0; - HWBuffer->vbo_indicesID = 0; - HWBuffer->vbo_verticesSize = 0; - HWBuffer->vbo_indicesSize = 0; - - if (!updateHardwareBuffer(HWBuffer)) - { - deleteHardwareBuffer(HWBuffer); - return 0; - } - - return HWBuffer; - } - - - void COpenGL3DriverBase::deleteHardwareBuffer(SHWBufferLink *_HWBuffer) - { - if (!_HWBuffer) - return; - - SHWBufferLink_opengl *HWBuffer = static_cast(_HWBuffer); - if (HWBuffer->vbo_verticesID) - { - glDeleteBuffers(1, &HWBuffer->vbo_verticesID); - HWBuffer->vbo_verticesID = 0; - } - if (HWBuffer->vbo_indicesID) - { - glDeleteBuffers(1, &HWBuffer->vbo_indicesID); - HWBuffer->vbo_indicesID = 0; - } - - CNullDriver::deleteHardwareBuffer(_HWBuffer); - } - - - //! Draw hardware buffer - void COpenGL3DriverBase::drawHardwareBuffer(SHWBufferLink *_HWBuffer) - { - if (!_HWBuffer) - return; - - SHWBufferLink_opengl *HWBuffer = static_cast(_HWBuffer); - - updateHardwareBuffer(HWBuffer); //check if update is needed - - const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer; - const void *vertices = mb->getVertices(); - const void *indexList = mb->getIndices(); - - if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) - { - glBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID); - vertices = 0; - } - - if (HWBuffer->Mapped_Index != scene::EHM_NEVER) - { - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID); - indexList = 0; - } - - - drawVertexPrimitiveList(vertices, mb->getVertexCount(), - indexList, mb->getPrimitiveCount(), - mb->getVertexType(), mb->getPrimitiveType(), - mb->getIndexType()); - - if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) - glBindBuffer(GL_ARRAY_BUFFER, 0); - - if (HWBuffer->Mapped_Index != scene::EHM_NEVER) - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - } - - - IRenderTarget* COpenGL3DriverBase::addRenderTarget() - { - COpenGL3RenderTarget* renderTarget = new COpenGL3RenderTarget(this); - RenderTargets.push_back(renderTarget); - - return renderTarget; - } - - - // small helper function to create vertex buffer object adress offsets - static inline u8* buffer_offset(const long offset) - { - return ((u8*)0 + offset); - } - - - //! draws a vertex primitive list - void COpenGL3DriverBase::drawVertexPrimitiveList(const void* vertices, u32 vertexCount, - const void* indexList, u32 primitiveCount, - E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) - { - if (!primitiveCount || !vertexCount) - return; - - if (!checkPrimitiveCount(primitiveCount)) - return; - - CNullDriver::drawVertexPrimitiveList(vertices, vertexCount, indexList, primitiveCount, vType, pType, iType); - - setRenderStates3DMode(); - - auto &vTypeDesc = getVertexTypeDescription(vType); - beginDraw(vTypeDesc, reinterpret_cast(vertices)); - GLenum indexSize = 0; - - switch (iType) - { - case(EIT_16BIT): - { - indexSize = GL_UNSIGNED_SHORT; - break; - } - case(EIT_32BIT): - { -#ifdef GL_OES_element_index_uint -#ifndef GL_UNSIGNED_INT -#define GL_UNSIGNED_INT 0x1405 -#endif - if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_element_index_uint]) - indexSize = GL_UNSIGNED_INT; - else -#endif - indexSize = GL_UNSIGNED_SHORT; - break; - } - } - - switch (pType) - { - case scene::EPT_POINTS: - case scene::EPT_POINT_SPRITES: - glDrawArrays(GL_POINTS, 0, primitiveCount); - break; - case scene::EPT_LINE_STRIP: - glDrawElements(GL_LINE_STRIP, primitiveCount + 1, indexSize, indexList); - break; - case scene::EPT_LINE_LOOP: - glDrawElements(GL_LINE_LOOP, primitiveCount, indexSize, indexList); - break; - case scene::EPT_LINES: - glDrawElements(GL_LINES, primitiveCount*2, indexSize, indexList); - break; - case scene::EPT_TRIANGLE_STRIP: - glDrawElements(GL_TRIANGLE_STRIP, primitiveCount + 2, indexSize, indexList); - break; - case scene::EPT_TRIANGLE_FAN: - glDrawElements(GL_TRIANGLE_FAN, primitiveCount + 2, indexSize, indexList); - break; - case scene::EPT_TRIANGLES: - glDrawElements((LastMaterial.Wireframe) ? GL_LINES : (LastMaterial.PointCloud) ? GL_POINTS : GL_TRIANGLES, primitiveCount*3, indexSize, indexList); - break; - default: - break; - } - - endDraw(vTypeDesc); - } - - - void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, const core::position2d& destPos, - const core::rect& sourceRect, const core::rect* clipRect, SColor color, - bool useAlphaChannelOfTexture) - { - if (!texture) - return; - - if (!sourceRect.isValid()) - return; - - SColor colors[4] = {color, color, color, color}; - draw2DImage(texture, {destPos, sourceRect.getSize()}, sourceRect, clipRect, colors, useAlphaChannelOfTexture); - } - - - void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, const core::rect& destRect, - const core::rect& sourceRect, const core::rect* clipRect, - const video::SColor* const colors, bool useAlphaChannelOfTexture) - { - if (!texture) - return; - - // texcoords need to be flipped horizontally for RTTs - const bool isRTT = texture->isRenderTarget(); - const core::dimension2du& ss = texture->getOriginalSize(); - const f32 invW = 1.f / static_cast(ss.Width); - const f32 invH = 1.f / static_cast(ss.Height); - const core::rect tcoords( - sourceRect.UpperLeftCorner.X * invW, - (isRTT ? sourceRect.LowerRightCorner.Y : sourceRect.UpperLeftCorner.Y) * invH, - sourceRect.LowerRightCorner.X * invW, - (isRTT ? sourceRect.UpperLeftCorner.Y : sourceRect.LowerRightCorner.Y) *invH); - - const video::SColor temp[4] = - { - 0xFFFFFFFF, - 0xFFFFFFFF, - 0xFFFFFFFF, - 0xFFFFFFFF - }; - - const video::SColor* const useColor = colors ? colors : temp; - - chooseMaterial2D(); - if (!setMaterialTexture(0, texture )) - return; - - setRenderStates2DMode(useColor[0].getAlpha() < 255 || useColor[1].getAlpha() < 255 || - useColor[2].getAlpha() < 255 || useColor[3].getAlpha() < 255, - true, useAlphaChannelOfTexture); - - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); - - if (clipRect) - { - if (!clipRect->isValid()) - return; - - glEnable(GL_SCISSOR_TEST); - glScissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y, - clipRect->getWidth(), clipRect->getHeight()); - } - - f32 left = (f32)destRect.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 right = (f32)destRect.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 down = 2.f - (f32)destRect.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - f32 top = 2.f - (f32)destRect.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - - S3DVertex vertices[4]; - vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, useColor[0], tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y); - vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, useColor[3], tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y); - vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, useColor[2], tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y); - vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, useColor[1], tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y); - - drawQuad(vt2DImage, vertices); - - if (clipRect) - glDisable(GL_SCISSOR_TEST); - - testGLError(__LINE__); - } - - void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, u32 layer, bool flip) - { - if (!texture) - return; - - chooseMaterial2D(); - if (!setMaterialTexture(0, texture )) - return; - - setRenderStates2DMode(false, true, true); - - S3DVertex quad2DVertices[4]; - - quad2DVertices[0].Pos = core::vector3df(-1.f, 1.f, 0.f); - quad2DVertices[1].Pos = core::vector3df(1.f, 1.f, 0.f); - quad2DVertices[2].Pos = core::vector3df(1.f, -1.f, 0.f); - quad2DVertices[3].Pos = core::vector3df(-1.f, -1.f, 0.f); - - f32 modificator = (flip) ? 1.f : 0.f; - - quad2DVertices[0].TCoords = core::vector2df(0.f, 0.f + modificator); - quad2DVertices[1].TCoords = core::vector2df(1.f, 0.f + modificator); - quad2DVertices[2].TCoords = core::vector2df(1.f, 1.f - modificator); - quad2DVertices[3].TCoords = core::vector2df(0.f, 1.f - modificator); - - quad2DVertices[0].Color = SColor(0xFFFFFFFF); - quad2DVertices[1].Color = SColor(0xFFFFFFFF); - quad2DVertices[2].Color = SColor(0xFFFFFFFF); - quad2DVertices[3].Color = SColor(0xFFFFFFFF); - - drawQuad(vt2DImage, quad2DVertices); - } - - void COpenGL3DriverBase::draw2DImageBatch(const video::ITexture* texture, - const core::array >& positions, - const core::array >& sourceRects, - const core::rect* clipRect, - SColor color, bool useAlphaChannelOfTexture) - { - if (!texture) - return; - - chooseMaterial2D(); - if (!setMaterialTexture(0, texture)) - return; - - setRenderStates2DMode(color.getAlpha() < 255, true, useAlphaChannelOfTexture); - - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); - - if (clipRect) - { - if (!clipRect->isValid()) - return; - - glEnable(GL_SCISSOR_TEST); - glScissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y, - clipRect->getWidth(), clipRect->getHeight()); - } - - const irr::u32 drawCount = core::min_(positions.size(), sourceRects.size()); - assert(6 * std::size_t(drawCount) <= QuadsIndices.size()); - - core::array vtx(drawCount * 4); - - for (u32 i = 0; i < drawCount; i++) - { - core::position2d targetPos = positions[i]; - core::position2d sourcePos = sourceRects[i].UpperLeftCorner; - // This needs to be signed as it may go negative. - core::dimension2d sourceSize(sourceRects[i].getSize()); - - // now draw it. - - core::rect tcoords; - tcoords.UpperLeftCorner.X = (((f32)sourcePos.X)) / texture->getOriginalSize().Width ; - tcoords.UpperLeftCorner.Y = (((f32)sourcePos.Y)) / texture->getOriginalSize().Height; - tcoords.LowerRightCorner.X = tcoords.UpperLeftCorner.X + ((f32)(sourceSize.Width) / texture->getOriginalSize().Width); - tcoords.LowerRightCorner.Y = tcoords.UpperLeftCorner.Y + ((f32)(sourceSize.Height) / texture->getOriginalSize().Height); - - const core::rect poss(targetPos, sourceSize); - - f32 left = (f32)poss.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 right = (f32)poss.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 down = 2.f - (f32)poss.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - f32 top = 2.f - (f32)poss.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - - vtx.push_back(S3DVertex(left, top, 0.0f, - 0.0f, 0.0f, 0.0f, color, - tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y)); - vtx.push_back(S3DVertex(right, top, 0.0f, - 0.0f, 0.0f, 0.0f, color, - tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y)); - vtx.push_back(S3DVertex(right, down, 0.0f, - 0.0f, 0.0f, 0.0f, color, - tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y)); - vtx.push_back(S3DVertex(left, down, 0.0f, - 0.0f, 0.0f, 0.0f, color, - tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y)); - } - - drawElements(GL_TRIANGLES, vt2DImage, vtx.const_pointer(), QuadsIndices.data(), 6 * drawCount); - - if (clipRect) - glDisable(GL_SCISSOR_TEST); - } - - - //! draw a 2d rectangle - void COpenGL3DriverBase::draw2DRectangle(SColor color, - const core::rect& position, - const core::rect* clip) - { - chooseMaterial2D(); - setMaterialTexture(0, 0); - - setRenderStates2DMode(color.getAlpha() < 255, false, false); - - core::rect pos = position; - - if (clip) - pos.clipAgainst(*clip); - - if (!pos.isValid()) - return; - - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); - - f32 left = (f32)pos.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 right = (f32)pos.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 down = 2.f - (f32)pos.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - f32 top = 2.f - (f32)pos.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - - S3DVertex vertices[4]; - vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, color, 0, 0); - vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, color, 0, 0); - vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, color, 0, 0); - vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, color, 0, 0); - - drawQuad(vtPrimitive, vertices); - } - - - //! draw an 2d rectangle - void COpenGL3DriverBase::draw2DRectangle(const core::rect& position, - SColor colorLeftUp, SColor colorRightUp, - SColor colorLeftDown, SColor colorRightDown, - const core::rect* clip) - { - core::rect pos = position; - - if (clip) - pos.clipAgainst(*clip); - - if (!pos.isValid()) - return; - - chooseMaterial2D(); - setMaterialTexture(0, 0); - - setRenderStates2DMode(colorLeftUp.getAlpha() < 255 || - colorRightUp.getAlpha() < 255 || - colorLeftDown.getAlpha() < 255 || - colorRightDown.getAlpha() < 255, false, false); - - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); - - f32 left = (f32)pos.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 right = (f32)pos.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 down = 2.f - (f32)pos.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - f32 top = 2.f - (f32)pos.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - - S3DVertex vertices[4]; - vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, colorLeftUp, 0, 0); - vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, colorRightUp, 0, 0); - vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, colorRightDown, 0, 0); - vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, colorLeftDown, 0, 0); - - drawQuad(vtPrimitive, vertices); - } - - - //! Draws a 2d line. - void COpenGL3DriverBase::draw2DLine(const core::position2d& start, - const core::position2d& end, SColor color) - { - if (start==end) - drawPixel(start.X, start.Y, color); - else - { - chooseMaterial2D(); - setMaterialTexture(0, 0); - - setRenderStates2DMode(color.getAlpha() < 255, false, false); - - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); - - f32 startX = (f32)start.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 endX = (f32)end.X / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 startY = 2.f - (f32)start.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - f32 endY = 2.f - (f32)end.Y / (f32)renderTargetSize.Height * 2.f - 1.f; - - S3DVertex vertices[2]; - vertices[0] = S3DVertex(startX, startY, 0, 0, 0, 1, color, 0, 0); - vertices[1] = S3DVertex(endX, endY, 0, 0, 0, 1, color, 1, 1); - - drawArrays(GL_LINES, vtPrimitive, vertices, 2); - } - } - - - //! Draws a pixel - void COpenGL3DriverBase::drawPixel(u32 x, u32 y, const SColor &color) - { - const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); - if (x > (u32)renderTargetSize.Width || y > (u32)renderTargetSize.Height) - return; - - chooseMaterial2D(); - setMaterialTexture(0, 0); - - setRenderStates2DMode(color.getAlpha() < 255, false, false); - - f32 X = (f32)x / (f32)renderTargetSize.Width * 2.f - 1.f; - f32 Y = 2.f - (f32)y / (f32)renderTargetSize.Height * 2.f - 1.f; - - S3DVertex vertices[1]; - vertices[0] = S3DVertex(X, Y, 0, 0, 0, 1, color, 0, 0); - - drawArrays(GL_POINTS, vtPrimitive, vertices, 1); - } - - void COpenGL3DriverBase::drawQuad(const VertexType &vertexType, const S3DVertex (&vertices)[4]) - { - drawArrays(GL_TRIANGLE_FAN, vertexType, vertices, 4); - } - - void COpenGL3DriverBase::drawArrays(GLenum primitiveType, const VertexType &vertexType, const void *vertices, int vertexCount) - { - beginDraw(vertexType, reinterpret_cast(vertices)); - glDrawArrays(primitiveType, 0, vertexCount); - endDraw(vertexType); - } - - void COpenGL3DriverBase::drawElements(GLenum primitiveType, const VertexType &vertexType, const void *vertices, const u16 *indices, int indexCount) - { - beginDraw(vertexType, reinterpret_cast(vertices)); - glDrawElements(primitiveType, indexCount, GL_UNSIGNED_SHORT, indices); - endDraw(vertexType); - } - - void COpenGL3DriverBase::beginDraw(const VertexType &vertexType, uintptr_t verticesBase) - { - for (auto attr: vertexType) { - glEnableVertexAttribArray(attr.Index); - switch (attr.mode) { - case VertexAttribute::Mode::Regular: glVertexAttribPointer(attr.Index, attr.ComponentCount, attr.ComponentType, GL_FALSE, vertexType.VertexSize, reinterpret_cast(verticesBase + attr.Offset)); break; - case VertexAttribute::Mode::Normalized: glVertexAttribPointer(attr.Index, attr.ComponentCount, attr.ComponentType, GL_TRUE, vertexType.VertexSize, reinterpret_cast(verticesBase + attr.Offset)); break; - case VertexAttribute::Mode::Integral: glVertexAttribIPointer(attr.Index, attr.ComponentCount, attr.ComponentType, vertexType.VertexSize, reinterpret_cast(verticesBase + attr.Offset)); break; - } - } - } - - void COpenGL3DriverBase::endDraw(const VertexType &vertexType) - { - for (auto attr: vertexType) - glDisableVertexAttribArray(attr.Index); - } - - ITexture* COpenGL3DriverBase::createDeviceDependentTexture(const io::path& name, IImage* image) - { - core::array imageArray(1); - imageArray.push_back(image); - - COpenGL3Texture* texture = new COpenGL3Texture(name, imageArray, ETT_2D, this); - - return texture; - } - - ITexture* COpenGL3DriverBase::createDeviceDependentTextureCubemap(const io::path& name, const core::array& image) - { - COpenGL3Texture* texture = new COpenGL3Texture(name, image, ETT_CUBEMAP, this); - - return texture; - } - - //! Sets a material. - void COpenGL3DriverBase::setMaterial(const SMaterial& material) - { - Material = material; - OverrideMaterial.apply(Material); - - for (u32 i = 0; i < Feature.MaxTextureUnits; ++i) - { - CacheHandler->getTextureCache().set(i, material.getTexture(i)); - setTransform((E_TRANSFORMATION_STATE)(ETS_TEXTURE_0 + i), material.getTextureMatrix(i)); - } - } - - //! prints error if an error happened. - bool COpenGL3DriverBase::testGLError(int code) - { -#ifdef _DEBUG - GLenum g = glGetError(); - switch (g) - { - case GL_NO_ERROR: - return false; - case GL_INVALID_ENUM: - os::Printer::log("GL_INVALID_ENUM", core::stringc(code).c_str(), ELL_ERROR); - break; - case GL_INVALID_VALUE: - os::Printer::log("GL_INVALID_VALUE", core::stringc(code).c_str(), ELL_ERROR); - break; - case GL_INVALID_OPERATION: - os::Printer::log("GL_INVALID_OPERATION", core::stringc(code).c_str(), ELL_ERROR); - break; - case GL_OUT_OF_MEMORY: - os::Printer::log("GL_OUT_OF_MEMORY", core::stringc(code).c_str(), ELL_ERROR); - break; - }; - return true; -#else - return false; -#endif - } - - //! prints error if an error happened. - bool COpenGL3DriverBase::testEGLError() - { -#if defined(EGL_VERSION_1_0) && defined(_DEBUG) - EGLint g = eglGetError(); - switch (g) - { - case EGL_SUCCESS: - return false; - case EGL_NOT_INITIALIZED : - os::Printer::log("Not Initialized", ELL_ERROR); - break; - case EGL_BAD_ACCESS: - os::Printer::log("Bad Access", ELL_ERROR); - break; - case EGL_BAD_ALLOC: - os::Printer::log("Bad Alloc", ELL_ERROR); - break; - case EGL_BAD_ATTRIBUTE: - os::Printer::log("Bad Attribute", ELL_ERROR); - break; - case EGL_BAD_CONTEXT: - os::Printer::log("Bad Context", ELL_ERROR); - break; - case EGL_BAD_CONFIG: - os::Printer::log("Bad Config", ELL_ERROR); - break; - case EGL_BAD_CURRENT_SURFACE: - os::Printer::log("Bad Current Surface", ELL_ERROR); - break; - case EGL_BAD_DISPLAY: - os::Printer::log("Bad Display", ELL_ERROR); - break; - case EGL_BAD_SURFACE: - os::Printer::log("Bad Surface", ELL_ERROR); - break; - case EGL_BAD_MATCH: - os::Printer::log("Bad Match", ELL_ERROR); - break; - case EGL_BAD_PARAMETER: - os::Printer::log("Bad Parameter", ELL_ERROR); - break; - case EGL_BAD_NATIVE_PIXMAP: - os::Printer::log("Bad Native Pixmap", ELL_ERROR); - break; - case EGL_BAD_NATIVE_WINDOW: - os::Printer::log("Bad Native Window", ELL_ERROR); - break; - case EGL_CONTEXT_LOST: - os::Printer::log("Context Lost", ELL_ERROR); - break; - }; - return true; -#else - return false; -#endif - } - - - void COpenGL3DriverBase::setRenderStates3DMode() - { - if ( LockRenderStateMode ) - return; - - if (CurrentRenderMode != ERM_3D) - { - // Reset Texture Stages - CacheHandler->setBlend(false); - CacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - - ResetRenderStates = true; - } - - if (ResetRenderStates || LastMaterial != Material) - { - // unset old material - - // unset last 3d material - if (CurrentRenderMode == ERM_2D && MaterialRenderer2DActive) - { - MaterialRenderer2DActive->OnUnsetMaterial(); - MaterialRenderer2DActive = 0; - } - else if (LastMaterial.MaterialType != Material.MaterialType && - static_cast(LastMaterial.MaterialType) < MaterialRenderers.size()) - MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial(); - - // set new material. - if (static_cast(Material.MaterialType) < MaterialRenderers.size()) - MaterialRenderers[Material.MaterialType].Renderer->OnSetMaterial( - Material, LastMaterial, ResetRenderStates, this); - - LastMaterial = Material; - CacheHandler->correctCacheMaterial(LastMaterial); - ResetRenderStates = false; - } - - if (static_cast(Material.MaterialType) < MaterialRenderers.size()) - MaterialRenderers[Material.MaterialType].Renderer->OnRender(this, video::EVT_STANDARD); - - CurrentRenderMode = ERM_3D; - } - - //! Can be called by an IMaterialRenderer to make its work easier. - void COpenGL3DriverBase::setBasicRenderStates(const SMaterial& material, const SMaterial& lastmaterial, bool resetAllRenderStates) - { - // ZBuffer - switch (material.ZBuffer) - { - case ECFN_DISABLED: - CacheHandler->setDepthTest(false); - break; - case ECFN_LESSEQUAL: - CacheHandler->setDepthTest(true); - CacheHandler->setDepthFunc(GL_LEQUAL); - break; - case ECFN_EQUAL: - CacheHandler->setDepthTest(true); - CacheHandler->setDepthFunc(GL_EQUAL); - break; - case ECFN_LESS: - CacheHandler->setDepthTest(true); - CacheHandler->setDepthFunc(GL_LESS); - break; - case ECFN_NOTEQUAL: - CacheHandler->setDepthTest(true); - CacheHandler->setDepthFunc(GL_NOTEQUAL); - break; - case ECFN_GREATEREQUAL: - CacheHandler->setDepthTest(true); - CacheHandler->setDepthFunc(GL_GEQUAL); - break; - case ECFN_GREATER: - CacheHandler->setDepthTest(true); - CacheHandler->setDepthFunc(GL_GREATER); - break; - case ECFN_ALWAYS: - CacheHandler->setDepthTest(true); - CacheHandler->setDepthFunc(GL_ALWAYS); - break; - case ECFN_NEVER: - CacheHandler->setDepthTest(true); - CacheHandler->setDepthFunc(GL_NEVER); - break; - default: - break; - } - - // ZWrite - if (getWriteZBuffer(material)) - { - CacheHandler->setDepthMask(true); - } - else - { - CacheHandler->setDepthMask(false); - } - - // Back face culling - if ((material.FrontfaceCulling) && (material.BackfaceCulling)) - { - CacheHandler->setCullFaceFunc(GL_FRONT_AND_BACK); - CacheHandler->setCullFace(true); - } - else if (material.BackfaceCulling) - { - CacheHandler->setCullFaceFunc(GL_BACK); - CacheHandler->setCullFace(true); - } - else if (material.FrontfaceCulling) - { - CacheHandler->setCullFaceFunc(GL_FRONT); - CacheHandler->setCullFace(true); - } - else - { - CacheHandler->setCullFace(false); - } - - // Color Mask - CacheHandler->setColorMask(material.ColorMask); - - // Blend Equation - if (material.BlendOperation == EBO_NONE) - CacheHandler->setBlend(false); - else - { - CacheHandler->setBlend(true); - - switch (material.BlendOperation) - { - case EBO_ADD: - CacheHandler->setBlendEquation(GL_FUNC_ADD); - break; - case EBO_SUBTRACT: - CacheHandler->setBlendEquation(GL_FUNC_SUBTRACT); - break; - case EBO_REVSUBTRACT: - CacheHandler->setBlendEquation(GL_FUNC_REVERSE_SUBTRACT); - break; - default: - break; - } - } - - // Blend Factor - if (IR(material.BlendFactor) & 0xFFFFFFFF // TODO: why the & 0xFFFFFFFF? - && material.MaterialType != EMT_ONETEXTURE_BLEND - ) - { - E_BLEND_FACTOR srcRGBFact = EBF_ZERO; - E_BLEND_FACTOR dstRGBFact = EBF_ZERO; - E_BLEND_FACTOR srcAlphaFact = EBF_ZERO; - E_BLEND_FACTOR dstAlphaFact = EBF_ZERO; - E_MODULATE_FUNC modulo = EMFN_MODULATE_1X; - u32 alphaSource = 0; - - unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulo, alphaSource, material.BlendFactor); - - CacheHandler->setBlendFuncSeparate(getGLBlend(srcRGBFact), getGLBlend(dstRGBFact), - getGLBlend(srcAlphaFact), getGLBlend(dstAlphaFact)); - } - - // TODO: Polygon Offset. Not sure if it was left out deliberately or if it won't work with this driver. - - if (resetAllRenderStates || lastmaterial.Thickness != material.Thickness) - glLineWidth(core::clamp(static_cast(material.Thickness), DimAliasedLine[0], DimAliasedLine[1])); - - // Anti aliasing - if (resetAllRenderStates || lastmaterial.AntiAliasing != material.AntiAliasing) - { - if (material.AntiAliasing & EAAM_ALPHA_TO_COVERAGE) - glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE); - else if (lastmaterial.AntiAliasing & EAAM_ALPHA_TO_COVERAGE) - glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); - } - - // Texture parameters - setTextureRenderStates(material, resetAllRenderStates); - } - - //! Compare in SMaterial doesn't check texture parameters, so we should call this on each OnRender call. - void COpenGL3DriverBase::setTextureRenderStates(const SMaterial& material, bool resetAllRenderstates) - { - // Set textures to TU/TIU and apply filters to them - - for (s32 i = Feature.MaxTextureUnits - 1; i >= 0; --i) - { - const COpenGL3Texture* tmpTexture = CacheHandler->getTextureCache()[i]; - - if (!tmpTexture) - continue; - - GLenum tmpTextureType = tmpTexture->getOpenGLTextureType(); - - CacheHandler->setActiveTexture(GL_TEXTURE0 + i); - - if (resetAllRenderstates) - tmpTexture->getStatesCache().IsCached = false; - - if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].BilinearFilter != tmpTexture->getStatesCache().BilinearFilter || - material.TextureLayer[i].TrilinearFilter != tmpTexture->getStatesCache().TrilinearFilter) - { - glTexParameteri(tmpTextureType, GL_TEXTURE_MAG_FILTER, - (material.TextureLayer[i].BilinearFilter || material.TextureLayer[i].TrilinearFilter) ? GL_LINEAR : GL_NEAREST); - - tmpTexture->getStatesCache().BilinearFilter = material.TextureLayer[i].BilinearFilter; - tmpTexture->getStatesCache().TrilinearFilter = material.TextureLayer[i].TrilinearFilter; - } - - if (material.UseMipMaps && tmpTexture->hasMipMaps()) - { - if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].BilinearFilter != tmpTexture->getStatesCache().BilinearFilter || - material.TextureLayer[i].TrilinearFilter != tmpTexture->getStatesCache().TrilinearFilter || !tmpTexture->getStatesCache().MipMapStatus) - { - glTexParameteri(tmpTextureType, GL_TEXTURE_MIN_FILTER, - material.TextureLayer[i].TrilinearFilter ? GL_LINEAR_MIPMAP_LINEAR : - material.TextureLayer[i].BilinearFilter ? GL_LINEAR_MIPMAP_NEAREST : - GL_NEAREST_MIPMAP_NEAREST); - - tmpTexture->getStatesCache().BilinearFilter = material.TextureLayer[i].BilinearFilter; - tmpTexture->getStatesCache().TrilinearFilter = material.TextureLayer[i].TrilinearFilter; - tmpTexture->getStatesCache().MipMapStatus = true; - } - } - else - { - if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].BilinearFilter != tmpTexture->getStatesCache().BilinearFilter || - material.TextureLayer[i].TrilinearFilter != tmpTexture->getStatesCache().TrilinearFilter || tmpTexture->getStatesCache().MipMapStatus) - { - glTexParameteri(tmpTextureType, GL_TEXTURE_MIN_FILTER, - (material.TextureLayer[i].BilinearFilter || material.TextureLayer[i].TrilinearFilter) ? GL_LINEAR : GL_NEAREST); - - tmpTexture->getStatesCache().BilinearFilter = material.TextureLayer[i].BilinearFilter; - tmpTexture->getStatesCache().TrilinearFilter = material.TextureLayer[i].TrilinearFilter; - tmpTexture->getStatesCache().MipMapStatus = false; - } - } - - #ifdef GL_EXT_texture_filter_anisotropic - if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_EXT_texture_filter_anisotropic] && - (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].AnisotropicFilter != tmpTexture->getStatesCache().AnisotropicFilter)) - { - glTexParameteri(tmpTextureType, GL_TEXTURE_MAX_ANISOTROPY_EXT, - material.TextureLayer[i].AnisotropicFilter>1 ? core::min_(MaxAnisotropy, material.TextureLayer[i].AnisotropicFilter) : 1); - - tmpTexture->getStatesCache().AnisotropicFilter = material.TextureLayer[i].AnisotropicFilter; - } - #endif - - if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].TextureWrapU != tmpTexture->getStatesCache().WrapU) - { - glTexParameteri(tmpTextureType, GL_TEXTURE_WRAP_S, getTextureWrapMode(material.TextureLayer[i].TextureWrapU)); - tmpTexture->getStatesCache().WrapU = material.TextureLayer[i].TextureWrapU; - } - - if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].TextureWrapV != tmpTexture->getStatesCache().WrapV) - { - glTexParameteri(tmpTextureType, GL_TEXTURE_WRAP_T, getTextureWrapMode(material.TextureLayer[i].TextureWrapV)); - tmpTexture->getStatesCache().WrapV = material.TextureLayer[i].TextureWrapV; - } - - tmpTexture->getStatesCache().IsCached = true; - } - } - - - // Get OpenGL ES2.0 texture wrap mode from Irrlicht wrap mode. - GLint COpenGL3DriverBase::getTextureWrapMode(u8 clamp) const - { - switch (clamp) - { - case ETC_CLAMP: - case ETC_CLAMP_TO_EDGE: - case ETC_CLAMP_TO_BORDER: - return GL_CLAMP_TO_EDGE; - case ETC_MIRROR: - return GL_REPEAT; - default: - return GL_REPEAT; - } - } - - - //! sets the needed renderstates - void COpenGL3DriverBase::setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel) - { - if ( LockRenderStateMode ) - return; - - COpenGL3Renderer2D* nextActiveRenderer = texture ? MaterialRenderer2DTexture : MaterialRenderer2DNoTexture; - - if (CurrentRenderMode != ERM_2D) - { - // unset last 3d material - if (CurrentRenderMode == ERM_3D) - { - if (static_cast(LastMaterial.MaterialType) < MaterialRenderers.size()) - MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial(); - } - - CurrentRenderMode = ERM_2D; - } - else if ( MaterialRenderer2DActive && MaterialRenderer2DActive != nextActiveRenderer) - { - MaterialRenderer2DActive->OnUnsetMaterial(); - } - - MaterialRenderer2DActive = nextActiveRenderer; - - MaterialRenderer2DActive->OnSetMaterial(Material, LastMaterial, true, 0); - LastMaterial = Material; - CacheHandler->correctCacheMaterial(LastMaterial); - - // no alphaChannel without texture - alphaChannel &= texture; - - if (alphaChannel || alpha) - { - CacheHandler->setBlend(true); - CacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - CacheHandler->setBlendEquation(GL_FUNC_ADD); - } - else - CacheHandler->setBlend(false); - - Material.setTexture(0, const_cast(CacheHandler->getTextureCache().get(0))); - setTransform(ETS_TEXTURE_0, core::IdentityMatrix); - - if (texture) - { - if (OverrideMaterial2DEnabled) - setTextureRenderStates(OverrideMaterial2D, false); - else - setTextureRenderStates(InitMaterial2D, false); - } - - MaterialRenderer2DActive->OnRender(this, video::EVT_STANDARD); - } - - - void COpenGL3DriverBase::chooseMaterial2D() - { - if (!OverrideMaterial2DEnabled) - Material = InitMaterial2D; - - if (OverrideMaterial2DEnabled) - { - OverrideMaterial2D.Lighting=false; - OverrideMaterial2D.ZWriteEnable=EZW_OFF; - OverrideMaterial2D.ZBuffer=ECFN_DISABLED; // it will be ECFN_DISABLED after merge - OverrideMaterial2D.Lighting=false; - - Material = OverrideMaterial2D; - } - } - - - //! \return Returns the name of the video driver. - const wchar_t* COpenGL3DriverBase::getName() const - { - return Name.c_str(); - } - - void COpenGL3DriverBase::setViewPort(const core::rect& area) - { - core::rect vp = area; - core::rect rendert(0, 0, getCurrentRenderTargetSize().Width, getCurrentRenderTargetSize().Height); - vp.clipAgainst(rendert); - - if (vp.getHeight() > 0 && vp.getWidth() > 0) - CacheHandler->setViewport(vp.UpperLeftCorner.X, getCurrentRenderTargetSize().Height - vp.UpperLeftCorner.Y - vp.getHeight(), vp.getWidth(), vp.getHeight()); - - ViewPort = vp; - } - - - void COpenGL3DriverBase::setViewPortRaw(u32 width, u32 height) - { - CacheHandler->setViewport(0, 0, width, height); - ViewPort = core::recti(0, 0, width, height); - } - - - //! Draws a 3d line. - void COpenGL3DriverBase::draw3DLine(const core::vector3df& start, - const core::vector3df& end, SColor color) - { - setRenderStates3DMode(); - - S3DVertex vertices[2]; - vertices[0] = S3DVertex(start.X, start.Y, start.Z, 0, 0, 1, color, 0, 0); - vertices[1] = S3DVertex(end.X, end.Y, end.Z, 0, 0, 1, color, 0, 0); - - drawArrays(GL_LINES, vtPrimitive, vertices, 2); - } - - - //! Only used by the internal engine. Used to notify the driver that - //! the window was resized. - void COpenGL3DriverBase::OnResize(const core::dimension2d& size) - { - CNullDriver::OnResize(size); - CacheHandler->setViewport(0, 0, size.Width, size.Height); - Transformation3DChanged = true; - } - - - //! Returns type of video driver - E_DRIVER_TYPE COpenGL3DriverBase::getDriverType() const - { - return EDT_OPENGL3; - } - - - //! returns color format - ECOLOR_FORMAT COpenGL3DriverBase::getColorFormat() const - { - return ColorFormat; - } - - - //! Get a vertex shader constant index. - s32 COpenGL3DriverBase::getVertexShaderConstantID(const c8* name) - { - return getPixelShaderConstantID(name); - } - - //! Get a pixel shader constant index. - s32 COpenGL3DriverBase::getPixelShaderConstantID(const c8* name) - { - os::Printer::log("Error: Please call services->getPixelShaderConstantID(), not VideoDriver->getPixelShaderConstantID()."); - return -1; - } - - //! Sets a vertex shader constant. - void COpenGL3DriverBase::setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount) - { - os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setPixelShaderConstant()."); - } - - //! Sets a pixel shader constant. - void COpenGL3DriverBase::setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount) - { - os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant()."); - } - - //! Sets a constant for the vertex shader based on an index. - bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const f32* floats, int count) - { - os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant()."); - return false; - } - - //! Int interface for the above. - bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const s32* ints, int count) - { - os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant()."); - return false; - } - - bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const u32* ints, int count) - { - os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant()."); - return false; - } - - //! Sets a constant for the pixel shader based on an index. - bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const f32* floats, int count) - { - os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant()."); - return false; - } - - //! Int interface for the above. - bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const s32* ints, int count) - { - os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant()."); - return false; - } - - bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const u32* ints, int count) - { - os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant()."); - return false; - } - - //! Adds a new material renderer to the VideoDriver, using pixel and/or - //! vertex shaders to render geometry. - s32 COpenGL3DriverBase::addShaderMaterial(const c8* vertexShaderProgram, - const c8* pixelShaderProgram, - IShaderConstantSetCallBack* callback, - E_MATERIAL_TYPE baseMaterial, s32 userData) - { - os::Printer::log("No shader support."); - return -1; - } - - - //! Adds a new material renderer to the VideoDriver, using GLSL to render geometry. - s32 COpenGL3DriverBase::addHighLevelShaderMaterial( - const c8* vertexShaderProgram, - const c8* vertexShaderEntryPointName, - E_VERTEX_SHADER_TYPE vsCompileTarget, - const c8* pixelShaderProgram, - const c8* pixelShaderEntryPointName, - E_PIXEL_SHADER_TYPE psCompileTarget, - const c8* geometryShaderProgram, - const c8* geometryShaderEntryPointName, - E_GEOMETRY_SHADER_TYPE gsCompileTarget, - scene::E_PRIMITIVE_TYPE inType, - scene::E_PRIMITIVE_TYPE outType, - u32 verticesOut, - IShaderConstantSetCallBack* callback, - E_MATERIAL_TYPE baseMaterial, - s32 userData) - { - s32 nr = -1; - COpenGL3MaterialRenderer* r = new COpenGL3MaterialRenderer( - this, nr, vertexShaderProgram, - pixelShaderProgram, - callback, baseMaterial, userData); - - r->drop(); - return nr; - } - - //! Returns a pointer to the IVideoDriver interface. (Implementation for - //! IMaterialRendererServices) - IVideoDriver* COpenGL3DriverBase::getVideoDriver() - { - return this; - } - - - //! Returns pointer to the IGPUProgrammingServices interface. - IGPUProgrammingServices* COpenGL3DriverBase::getGPUProgrammingServices() - { - return this; - } - - ITexture* COpenGL3DriverBase::addRenderTargetTexture(const core::dimension2d& size, - const io::path& name, const ECOLOR_FORMAT format) - { - //disable mip-mapping - bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS); - setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false); - - COpenGL3Texture* renderTargetTexture = new COpenGL3Texture(name, size, ETT_2D, format, this); - addTexture(renderTargetTexture); - renderTargetTexture->drop(); - - //restore mip-mapping - setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels); - - return renderTargetTexture; - } - - ITexture* COpenGL3DriverBase::addRenderTargetTextureCubemap(const irr::u32 sideLen, const io::path& name, const ECOLOR_FORMAT format) - { - //disable mip-mapping - bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS); - setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false); - - bool supportForFBO = (Feature.ColorAttachment > 0); - - const core::dimension2d size(sideLen, sideLen); - core::dimension2du destSize(size); - - if (!supportForFBO) - { - destSize = core::dimension2d(core::min_(size.Width, ScreenSize.Width), core::min_(size.Height, ScreenSize.Height)); - destSize = destSize.getOptimalSize((size == size.getOptimalSize()), false, false); - } - - COpenGL3Texture* renderTargetTexture = new COpenGL3Texture(name, destSize, ETT_CUBEMAP, format, this); - addTexture(renderTargetTexture); - renderTargetTexture->drop(); - - //restore mip-mapping - setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels); - - return renderTargetTexture; - } - - - //! Returns the maximum amount of primitives - u32 COpenGL3DriverBase::getMaximalPrimitiveCount() const - { - return 65535; - } - - bool COpenGL3DriverBase::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil) - { - if (target && target->getDriverType() != getDriverType()) - { - os::Printer::log("Fatal Error: Tried to set a render target not owned by OpenGL 3 driver.", ELL_ERROR); - return false; - } - - core::dimension2d destRenderTargetSize(0, 0); - - if (target) - { - COpenGL3RenderTarget* renderTarget = static_cast(target); - - CacheHandler->setFBO(renderTarget->getBufferID()); - renderTarget->update(); - - destRenderTargetSize = renderTarget->getSize(); - - setViewPortRaw(destRenderTargetSize.Width, destRenderTargetSize.Height); - } - else - { - CacheHandler->setFBO(0); - - destRenderTargetSize = core::dimension2d(0, 0); - - setViewPortRaw(ScreenSize.Width, ScreenSize.Height); - } - - if (CurrentRenderTargetSize != destRenderTargetSize) - { - CurrentRenderTargetSize = destRenderTargetSize; - - Transformation3DChanged = true; - } - - CurrentRenderTarget = target; - - clearBuffers(clearFlag, clearColor, clearDepth, clearStencil); - - return true; - } - - void COpenGL3DriverBase::clearBuffers(u16 flag, SColor color, f32 depth, u8 stencil) - { - GLbitfield mask = 0; - u8 colorMask = 0; - bool depthMask = false; - - CacheHandler->getColorMask(colorMask); - CacheHandler->getDepthMask(depthMask); - - if (flag & ECBF_COLOR) - { - CacheHandler->setColorMask(ECP_ALL); - - const f32 inv = 1.0f / 255.0f; - glClearColor(color.getRed() * inv, color.getGreen() * inv, - color.getBlue() * inv, color.getAlpha() * inv); - - mask |= GL_COLOR_BUFFER_BIT; - } - - if (flag & ECBF_DEPTH) - { - CacheHandler->setDepthMask(true); - glClearDepthf(depth); - mask |= GL_DEPTH_BUFFER_BIT; - } - - if (flag & ECBF_STENCIL) - { - glClearStencil(stencil); - mask |= GL_STENCIL_BUFFER_BIT; - } - - if (mask) - glClear(mask); - - CacheHandler->setColorMask(colorMask); - CacheHandler->setDepthMask(depthMask); - } - - - //! Returns an image created from the last rendered frame. - // We want to read the front buffer to get the latest render finished. - // This is not possible under ogl-es, though, so one has to call this method - // outside of the render loop only. - IImage* COpenGL3DriverBase::createScreenShot(video::ECOLOR_FORMAT format, video::E_RENDER_TARGET target) - { - if (target==video::ERT_MULTI_RENDER_TEXTURES || target==video::ERT_RENDER_TEXTURE || target==video::ERT_STEREO_BOTH_BUFFERS) - return 0; - - GLint internalformat = GL_RGBA; - GLint type = GL_UNSIGNED_BYTE; - { -// glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT, &internalformat); -// glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE, &type); - // there's a format we don't support ATM - if (GL_UNSIGNED_SHORT_4_4_4_4 == type) - { - internalformat = GL_RGBA; - type = GL_UNSIGNED_BYTE; - } - } - - IImage* newImage = 0; - if (GL_RGBA == internalformat) - { - if (GL_UNSIGNED_BYTE == type) - newImage = new CImage(ECF_A8R8G8B8, ScreenSize); - else - newImage = new CImage(ECF_A1R5G5B5, ScreenSize); - } - else - { - if (GL_UNSIGNED_BYTE == type) - newImage = new CImage(ECF_R8G8B8, ScreenSize); - else - newImage = new CImage(ECF_R5G6B5, ScreenSize); - } - - if (!newImage) - return 0; - - u8* pixels = static_cast(newImage->getData()); - if (!pixels) - { - newImage->drop(); - return 0; - } - - glReadPixels(0, 0, ScreenSize.Width, ScreenSize.Height, internalformat, type, pixels); - testGLError(__LINE__); - - // opengl images are horizontally flipped, so we have to fix that here. - const s32 pitch = newImage->getPitch(); - u8* p2 = pixels + (ScreenSize.Height - 1) * pitch; - u8* tmpBuffer = new u8[pitch]; - for (u32 i = 0; i < ScreenSize.Height; i += 2) - { - memcpy(tmpBuffer, pixels, pitch); - memcpy(pixels, p2, pitch); - memcpy(p2, tmpBuffer, pitch); - pixels += pitch; - p2 -= pitch; - } - delete [] tmpBuffer; - - // also GL_RGBA doesn't match the internal encoding of the image (which is BGRA) - if (GL_RGBA == internalformat && GL_UNSIGNED_BYTE == type) - { - pixels = static_cast(newImage->getData()); - for (u32 i = 0; i < ScreenSize.Height; i++) - { - for (u32 j = 0; j < ScreenSize.Width; j++) - { - u32 c = *(u32*) (pixels + 4 * j); - *(u32*) (pixels + 4 * j) = (c & 0xFF00FF00) | - ((c & 0x00FF0000) >> 16) | ((c & 0x000000FF) << 16); - } - pixels += pitch; - } - } - - if (testGLError(__LINE__)) - { - newImage->drop(); - return 0; - } - testGLError(__LINE__); - return newImage; - } - - void COpenGL3DriverBase::removeTexture(ITexture* texture) - { - CacheHandler->getTextureCache().remove(texture); - CNullDriver::removeTexture(texture); - } - - //! Set/unset a clipping plane. - bool COpenGL3DriverBase::setClipPlane(u32 index, const core::plane3df& plane, bool enable) - { - if (index >= UserClipPlane.size()) - UserClipPlane.push_back(SUserClipPlane()); - - UserClipPlane[index].Plane = plane; - UserClipPlane[index].Enabled = enable; - return true; - } - - //! Enable/disable a clipping plane. - void COpenGL3DriverBase::enableClipPlane(u32 index, bool enable) - { - UserClipPlane[index].Enabled = enable; - } - - //! Get the ClipPlane Count - u32 COpenGL3DriverBase::getClipPlaneCount() const - { - return UserClipPlane.size(); - } - - const core::plane3df& COpenGL3DriverBase::getClipPlane(irr::u32 index) const - { - if (index < UserClipPlane.size()) - return UserClipPlane[index].Plane; - else - { - _IRR_DEBUG_BREAK_IF(true) // invalid index - static const core::plane3df dummy; - return dummy; - } - } - - core::dimension2du COpenGL3DriverBase::getMaxTextureSize() const - { - return core::dimension2du(MaxTextureSize, MaxTextureSize); - } - - GLenum COpenGL3DriverBase::getGLBlend(E_BLEND_FACTOR factor) const - { - static GLenum const blendTable[] = - { - GL_ZERO, - GL_ONE, - GL_DST_COLOR, - GL_ONE_MINUS_DST_COLOR, - GL_SRC_COLOR, - GL_ONE_MINUS_SRC_COLOR, - GL_SRC_ALPHA, - GL_ONE_MINUS_SRC_ALPHA, - GL_DST_ALPHA, - GL_ONE_MINUS_DST_ALPHA, - GL_SRC_ALPHA_SATURATE - }; - - return blendTable[factor]; - } - - bool COpenGL3DriverBase::getColorFormatParameters(ECOLOR_FORMAT format, GLint& internalFormat, GLenum& pixelFormat, - GLenum& pixelType, void(**converter)(const void*, s32, void*)) const - { - bool supported = false; - pixelFormat = GL_RGBA; - pixelType = GL_UNSIGNED_BYTE; - *converter = 0; - - switch (format) - { - case ECF_A1R5G5B5: - supported = true; - pixelFormat = GL_RGBA; - pixelType = GL_UNSIGNED_SHORT_5_5_5_1; - *converter = CColorConverter::convert_A1R5G5B5toR5G5B5A1; - break; - case ECF_R5G6B5: - supported = true; - pixelFormat = GL_RGB; - pixelType = GL_UNSIGNED_SHORT_5_6_5; - break; - case ECF_R8G8B8: - supported = true; - pixelFormat = GL_RGB; - pixelType = GL_UNSIGNED_BYTE; - break; - case ECF_A8R8G8B8: - supported = true; - if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_IMG_texture_format_BGRA8888) || - queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_format_BGRA8888) || - queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_APPLE_texture_format_BGRA8888)) - { - pixelFormat = GL_BGRA; - } - else - { - pixelFormat = GL_RGBA; - *converter = CColorConverter::convert_A8R8G8B8toA8B8G8R8; - } - pixelType = GL_UNSIGNED_BYTE; - break; -#ifdef GL_EXT_texture_compression_s3tc - case ECF_DXT1: - supported = true; - pixelFormat = GL_RGBA; - pixelType = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; - break; - case ECF_DXT2: - case ECF_DXT3: - supported = true; - pixelFormat = GL_RGBA; - pixelType = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; - break; - case ECF_DXT4: - case ECF_DXT5: - supported = true; - pixelFormat = GL_RGBA; - pixelType = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; - break; -#endif -#ifdef GL_OES_compressed_ETC1_RGB8_texture - case ECF_ETC1: - supported = true; - pixelFormat = GL_RGB; - pixelType = GL_ETC1_RGB8_OES; - break; -#endif -#ifdef GL_ES_VERSION_3_0 // TO-DO - fix when extension name will be available - case ECF_ETC2_RGB: - supported = true; - pixelFormat = GL_RGB; - pixelType = GL_COMPRESSED_RGB8_ETC2; - break; -#endif -#ifdef GL_ES_VERSION_3_0 // TO-DO - fix when extension name will be available - case ECF_ETC2_ARGB: - supported = true; - pixelFormat = GL_RGBA; - pixelType = GL_COMPRESSED_RGBA8_ETC2_EAC; - break; -#endif - case ECF_D16: - supported = true; - pixelFormat = GL_DEPTH_COMPONENT; - pixelType = GL_UNSIGNED_SHORT; - break; - case ECF_D32: -#if defined(GL_OES_depth32) - if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_depth32)) - { - supported = true; - pixelFormat = GL_DEPTH_COMPONENT; - pixelType = GL_UNSIGNED_INT; - } -#endif - break; - case ECF_D24S8: -#ifdef GL_OES_packed_depth_stencil - if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_packed_depth_stencil)) - { - supported = true; - pixelFormat = GL_DEPTH_STENCIL_OES; - pixelType = GL_UNSIGNED_INT_24_8_OES; - } -#endif - break; - case ECF_R8: -#if defined(GL_EXT_texture_rg) - if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg)) - { - supported = true; - pixelFormat = GL_RED_EXT; - pixelType = GL_UNSIGNED_BYTE; - } -#endif - break; - case ECF_R8G8: -#if defined(GL_EXT_texture_rg) - if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg)) - { - supported = true; - pixelFormat = GL_RG_EXT; - pixelType = GL_UNSIGNED_BYTE; - } -#endif - break; - case ECF_R16: - break; - case ECF_R16G16: - break; - case ECF_R16F: -#if defined(GL_OES_texture_half_float) && defined(GL_EXT_texture_rg) - if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg) - && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float) - ) - { - supported = true; - pixelFormat = GL_RED_EXT; - pixelType = GL_HALF_FLOAT_OES ; - } -#endif - break; - case ECF_G16R16F: -#if defined(GL_OES_texture_half_float) && defined(GL_EXT_texture_rg) - if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg) - && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float) - ) - { - supported = true; - pixelFormat = GL_RG_EXT; - pixelType = GL_HALF_FLOAT_OES ; - } -#endif - break; - case ECF_A16B16G16R16F: -#if defined(GL_OES_texture_half_float) - if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float)) - { - supported = true; - pixelFormat = GL_RGBA; - pixelType = GL_HALF_FLOAT_OES ; - } -#endif - break; - case ECF_R32F: -#if defined(GL_OES_texture_float) && defined(GL_EXT_texture_rg) - if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg) - && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_float) - ) - { - supported = true; - pixelFormat = GL_RED_EXT; - pixelType = GL_FLOAT; - } -#endif - break; - case ECF_G32R32F: -#if defined(GL_OES_texture_float) && defined(GL_EXT_texture_rg) - if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg) - && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_float) - ) - { - supported = true; - pixelFormat = GL_RG_EXT; - pixelType = GL_FLOAT; - } -#endif - break; - case ECF_A32B32G32R32F: -#if defined(GL_OES_texture_float) - if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float)) - { - supported = true; - pixelFormat = GL_RGBA; - pixelType = GL_FLOAT ; - } -#endif - break; - default: - break; - } - - // ES 2.0 says internalFormat must match pixelFormat (chapter 3.7.1 in Spec). - // Doesn't mention if "match" means "equal" or some other way of matching, but - // some bug on Emscripten and browsing discussions by others lead me to believe - // it means they have to be equal. Note that this was different in OpenGL. - internalFormat = pixelFormat; - -#ifdef _IRR_IOS_PLATFORM_ - if (internalFormat == GL_BGRA) - internalFormat = GL_RGBA; -#endif - - return supported; - } - - bool COpenGL3DriverBase::queryTextureFormat(ECOLOR_FORMAT format) const - { - GLint dummyInternalFormat; - GLenum dummyPixelFormat; - GLenum dummyPixelType; - void (*dummyConverter)(const void*, s32, void*); - return getColorFormatParameters(format, dummyInternalFormat, dummyPixelFormat, dummyPixelType, &dummyConverter); - } - - bool COpenGL3DriverBase::needsTransparentRenderPass(const irr::video::SMaterial& material) const - { - return CNullDriver::needsTransparentRenderPass(material) || material.isAlphaBlendOperation(); - } - - const SMaterial& COpenGL3DriverBase::getCurrentMaterial() const - { - return Material; - } - - COpenGL3CacheHandler* COpenGL3DriverBase::getCacheHandler() const - { - return CacheHandler; - } - -} // end namespace -} // end namespace +// Copyright (C) 2023 Vitaliy Lobachevskiy +// Copyright (C) 2014 Patryk Nadrowski +// Copyright (C) 2009-2010 Amundis +// This file is part of the "Irrlicht Engine". +// For conditions of distribution and use, see copyright notice in Irrlicht.h + +#include "Driver.h" +#include +#include "CNullDriver.h" +#include "IContextManager.h" + +#include "COpenGLCoreTexture.h" +#include "COpenGLCoreRenderTarget.h" +#include "COpenGLCoreCacheHandler.h" + +#include "MaterialRenderer.h" +#include "FixedPipelineRenderer.h" +#include "Renderer2D.h" + +#include "EVertexAttributes.h" +#include "CImage.h" +#include "os.h" + +#ifdef _IRR_COMPILE_WITH_ANDROID_DEVICE_ +#include "android_native_app_glue.h" +#endif + +#include "mt_opengl.h" + +namespace irr +{ +namespace video +{ + struct VertexAttribute { + enum class Mode { + Regular, + Normalized, + Integral, + }; + int Index; + int ComponentCount; + GLenum ComponentType; + Mode mode; + int Offset; + }; + + struct VertexType { + int VertexSize; + int AttributeCount; + VertexAttribute Attributes[]; + + VertexType(const VertexType &) = delete; + VertexType &operator= (const VertexType &) = delete; + }; + + static const VertexAttribute *begin(const VertexType &type) + { + return type.Attributes; + } + + static const VertexAttribute *end(const VertexType &type) + { + return type.Attributes + type.AttributeCount; + } + + static constexpr VertexType vtStandard = { + sizeof(S3DVertex), 4, { + {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Pos)}, + {EVA_NORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Normal)}, + {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex, Color)}, + {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, TCoords)}, + }, + }; + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Winvalid-offsetof" + + static constexpr VertexType vt2TCoords = { + sizeof(S3DVertex2TCoords), 5, { + {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, Pos)}, + {EVA_NORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, Normal)}, + {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex2TCoords, Color)}, + {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, TCoords)}, + {EVA_TCOORD1, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex2TCoords, TCoords2)}, + }, + }; + + static constexpr VertexType vtTangents = { + sizeof(S3DVertexTangents), 6, { + {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Pos)}, + {EVA_NORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Normal)}, + {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertexTangents, Color)}, + {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, TCoords)}, + {EVA_TANGENT, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Tangent)}, + {EVA_BINORMAL, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertexTangents, Binormal)}, + }, + }; + +#pragma GCC diagnostic pop + + static const VertexType &getVertexTypeDescription(E_VERTEX_TYPE type) + { + switch (type) { + case EVT_STANDARD: return vtStandard; + case EVT_2TCOORDS: return vt2TCoords; + case EVT_TANGENTS: return vtTangents; + default: assert(false); + } + } + + static constexpr VertexType vt2DImage = { + sizeof(S3DVertex), 3, { + {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Pos)}, + {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex, Color)}, + {EVA_TCOORD0, 2, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, TCoords)}, + }, + }; + + static constexpr VertexType vtPrimitive = { + sizeof(S3DVertex), 2, { + {EVA_POSITION, 3, GL_FLOAT, VertexAttribute::Mode::Regular, offsetof(S3DVertex, Pos)}, + {EVA_COLOR, 4, GL_UNSIGNED_BYTE, VertexAttribute::Mode::Normalized, offsetof(S3DVertex, Color)}, + }, + }; + + +void APIENTRY COpenGL3DriverBase::debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) +{ + ((COpenGL3DriverBase *)userParam)->debugCb(source, type, id, severity, length, message); +} + +void COpenGL3DriverBase::debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message) +{ + printf("%04x %04x %x %x %.*s\n", source, type, id, severity, length, message); +} + +COpenGL3DriverBase::COpenGL3DriverBase(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager) : + CNullDriver(io, params.WindowSize), COpenGL3ExtensionHandler(), CacheHandler(0), + Params(params), ResetRenderStates(true), LockRenderStateMode(false), AntiAlias(params.AntiAlias), + MaterialRenderer2DActive(0), MaterialRenderer2DTexture(0), MaterialRenderer2DNoTexture(0), + CurrentRenderMode(ERM_NONE), Transformation3DChanged(true), + OGLES2ShaderPath(params.OGLES2ShaderPath), + ColorFormat(ECF_R8G8B8), ContextManager(contextManager) +{ +#ifdef _DEBUG + setDebugName("Driver"); +#endif + + if (!ContextManager) + return; + + ContextManager->grab(); + ContextManager->generateSurface(); + ContextManager->generateContext(); + ExposedData = ContextManager->getContext(); + ContextManager->activateContext(ExposedData, false); + GL.LoadAllProcedures(ContextManager); + GL.DebugMessageCallback(debugCb, this); + initQuadsIndices(); +} + +COpenGL3DriverBase::~COpenGL3DriverBase() +{ + deleteMaterialRenders(); + + CacheHandler->getTextureCache().clear(); + + removeAllRenderTargets(); + deleteAllTextures(); + removeAllOcclusionQueries(); + removeAllHardwareBuffers(); + + delete MaterialRenderer2DTexture; + delete MaterialRenderer2DNoTexture; + delete CacheHandler; + + if (ContextManager) + { + ContextManager->destroyContext(); + ContextManager->destroySurface(); + ContextManager->terminate(); + ContextManager->drop(); + } +} + + void COpenGL3DriverBase::initQuadsIndices(int max_vertex_count) + { + int max_quad_count = max_vertex_count / 4; + QuadsIndices.reserve(6 * max_quad_count); + for (int k = 0; k < max_quad_count; k++) { + QuadsIndices.push_back(4 * k + 0); + QuadsIndices.push_back(4 * k + 1); + QuadsIndices.push_back(4 * k + 2); + QuadsIndices.push_back(4 * k + 0); + QuadsIndices.push_back(4 * k + 2); + QuadsIndices.push_back(4 * k + 3); + } + } + + bool COpenGL3DriverBase::genericDriverInit(const core::dimension2d& screenSize, bool stencilBuffer) + { + Name = glGetString(GL_VERSION); + printVersion(); + + // print renderer information + VendorName = glGetString(GL_VENDOR); + os::Printer::log(VendorName.c_str(), ELL_INFORMATION); + + // load extensions + initExtensions(); + + // reset cache handler + delete CacheHandler; + CacheHandler = new COpenGL3CacheHandler(this); + + StencilBuffer = stencilBuffer; + + DriverAttributes->setAttribute("MaxTextures", (s32)Feature.MaxTextureUnits); + DriverAttributes->setAttribute("MaxSupportedTextures", (s32)Feature.MaxTextureUnits); +// DriverAttributes->setAttribute("MaxLights", MaxLights); + DriverAttributes->setAttribute("MaxAnisotropy", MaxAnisotropy); +// DriverAttributes->setAttribute("MaxUserClipPlanes", MaxUserClipPlanes); +// DriverAttributes->setAttribute("MaxAuxBuffers", MaxAuxBuffers); +// DriverAttributes->setAttribute("MaxMultipleRenderTargets", MaxMultipleRenderTargets); + DriverAttributes->setAttribute("MaxIndices", (s32)MaxIndices); + DriverAttributes->setAttribute("MaxTextureSize", (s32)MaxTextureSize); + DriverAttributes->setAttribute("MaxTextureLODBias", MaxTextureLODBias); + DriverAttributes->setAttribute("Version", Version); + DriverAttributes->setAttribute("AntiAlias", AntiAlias); + + glPixelStorei(GL_PACK_ALIGNMENT, 1); + + UserClipPlane.reallocate(0); + + for (s32 i = 0; i < ETS_COUNT; ++i) + setTransform(static_cast(i), core::IdentityMatrix); + + setAmbientLight(SColorf(0.0f, 0.0f, 0.0f, 0.0f)); + glClearDepthf(1.0f); + + glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST); + glFrontFace(GL_CW); + + // create material renderers + createMaterialRenderers(); + + // set the renderstates + setRenderStates3DMode(); + + // set fog mode + setFog(FogColor, FogType, FogStart, FogEnd, FogDensity, PixelFog, RangeFog); + + // create matrix for flipping textures + TextureFlipMatrix.buildTextureTransform(0.0f, core::vector2df(0, 0), core::vector2df(0, 1.0f), core::vector2df(1.0f, -1.0f)); + + // We need to reset once more at the beginning of the first rendering. + // This fixes problems with intermediate changes to the material during texture load. + ResetRenderStates = true; + + testGLError(__LINE__); + + return true; + } + + void COpenGL3DriverBase::loadShaderData(const io::path& vertexShaderName, const io::path& fragmentShaderName, c8** vertexShaderData, c8** fragmentShaderData) + { + io::path vsPath(OGLES2ShaderPath); + vsPath += vertexShaderName; + + io::path fsPath(OGLES2ShaderPath); + fsPath += fragmentShaderName; + + *vertexShaderData = 0; + *fragmentShaderData = 0; + + io::IReadFile* vsFile = FileSystem->createAndOpenFile(vsPath); + if ( !vsFile ) + { + core::stringw warning(L"Warning: Missing shader files needed to simulate fixed function materials:\n"); + warning += core::stringw(vsPath) + L"\n"; + warning += L"Shaderpath can be changed in SIrrCreationParamters::OGLES2ShaderPath"; + os::Printer::log(warning.c_str(), ELL_WARNING); + return; + } + + io::IReadFile* fsFile = FileSystem->createAndOpenFile(fsPath); + if ( !fsFile ) + { + core::stringw warning(L"Warning: Missing shader files needed to simulate fixed function materials:\n"); + warning += core::stringw(fsPath) + L"\n"; + warning += L"Shaderpath can be changed in SIrrCreationParamters::OGLES2ShaderPath"; + os::Printer::log(warning.c_str(), ELL_WARNING); + return; + } + + long size = vsFile->getSize(); + if (size) + { + *vertexShaderData = new c8[size+1]; + vsFile->read(*vertexShaderData, size); + (*vertexShaderData)[size] = 0; + } + + size = fsFile->getSize(); + if (size) + { + // if both handles are the same we must reset the file + if (fsFile == vsFile) + fsFile->seek(0); + + *fragmentShaderData = new c8[size+1]; + fsFile->read(*fragmentShaderData, size); + (*fragmentShaderData)[size] = 0; + } + + vsFile->drop(); + fsFile->drop(); + } + + void COpenGL3DriverBase::createMaterialRenderers() + { + // Create callbacks. + + COpenGL3MaterialSolidCB* SolidCB = new COpenGL3MaterialSolidCB(); + COpenGL3MaterialSolid2CB* Solid2LayerCB = new COpenGL3MaterialSolid2CB(); + COpenGL3MaterialLightmapCB* LightmapCB = new COpenGL3MaterialLightmapCB(1.f); + COpenGL3MaterialLightmapCB* LightmapAddCB = new COpenGL3MaterialLightmapCB(1.f); + COpenGL3MaterialLightmapCB* LightmapM2CB = new COpenGL3MaterialLightmapCB(2.f); + COpenGL3MaterialLightmapCB* LightmapM4CB = new COpenGL3MaterialLightmapCB(4.f); + COpenGL3MaterialLightmapCB* LightmapLightingCB = new COpenGL3MaterialLightmapCB(1.f); + COpenGL3MaterialLightmapCB* LightmapLightingM2CB = new COpenGL3MaterialLightmapCB(2.f); + COpenGL3MaterialLightmapCB* LightmapLightingM4CB = new COpenGL3MaterialLightmapCB(4.f); + COpenGL3MaterialSolid2CB* DetailMapCB = new COpenGL3MaterialSolid2CB(); + COpenGL3MaterialReflectionCB* SphereMapCB = new COpenGL3MaterialReflectionCB(); + COpenGL3MaterialReflectionCB* Reflection2LayerCB = new COpenGL3MaterialReflectionCB(); + COpenGL3MaterialSolidCB* TransparentAddColorCB = new COpenGL3MaterialSolidCB(); + COpenGL3MaterialSolidCB* TransparentAlphaChannelCB = new COpenGL3MaterialSolidCB(); + COpenGL3MaterialSolidCB* TransparentAlphaChannelRefCB = new COpenGL3MaterialSolidCB(); + COpenGL3MaterialSolidCB* TransparentVertexAlphaCB = new COpenGL3MaterialSolidCB(); + COpenGL3MaterialReflectionCB* TransparentReflection2LayerCB = new COpenGL3MaterialReflectionCB(); + COpenGL3MaterialOneTextureBlendCB* OneTextureBlendCB = new COpenGL3MaterialOneTextureBlendCB(); + + // Create built-in materials. + + core::stringc VertexShader = OGLES2ShaderPath + "Solid.vsh"; + core::stringc FragmentShader = OGLES2ShaderPath + "Solid.fsh"; + + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, SolidCB, EMT_SOLID, 0); + + VertexShader = OGLES2ShaderPath + "Solid2.vsh"; + FragmentShader = OGLES2ShaderPath + "Solid2Layer.fsh"; + + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, Solid2LayerCB, EMT_SOLID, 0); + + VertexShader = OGLES2ShaderPath + "Solid2.vsh"; + FragmentShader = OGLES2ShaderPath + "LightmapModulate.fsh"; + + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, LightmapCB, EMT_SOLID, 0); + + FragmentShader = OGLES2ShaderPath + "LightmapAdd.fsh"; + + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, LightmapAddCB, EMT_SOLID, 0); + + FragmentShader = OGLES2ShaderPath + "LightmapModulate.fsh"; + + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, LightmapM2CB, EMT_SOLID, 0); + + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, LightmapM4CB, EMT_SOLID, 0); + + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, LightmapLightingCB, EMT_SOLID, 0); + + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, LightmapLightingM2CB, EMT_SOLID, 0); + + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, LightmapLightingM4CB, EMT_SOLID, 0); + + VertexShader = OGLES2ShaderPath + "Solid2.vsh"; + FragmentShader = OGLES2ShaderPath + "DetailMap.fsh"; + + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, DetailMapCB, EMT_SOLID, 0); + + VertexShader = OGLES2ShaderPath + "SphereMap.vsh"; + FragmentShader = OGLES2ShaderPath + "SphereMap.fsh"; + + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, SphereMapCB, EMT_SOLID, 0); + + VertexShader = OGLES2ShaderPath + "Reflection2Layer.vsh"; + FragmentShader = OGLES2ShaderPath + "Reflection2Layer.fsh"; + + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, Reflection2LayerCB, EMT_SOLID, 0); + + VertexShader = OGLES2ShaderPath + "Solid.vsh"; + FragmentShader = OGLES2ShaderPath + "Solid.fsh"; + + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentAddColorCB, EMT_TRANSPARENT_ADD_COLOR, 0); + + FragmentShader = OGLES2ShaderPath + "TransparentAlphaChannel.fsh"; + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentAlphaChannelCB, EMT_TRANSPARENT_ALPHA_CHANNEL, 0); + + FragmentShader = OGLES2ShaderPath + "TransparentAlphaChannelRef.fsh"; + + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentAlphaChannelRefCB, EMT_SOLID, 0); + + FragmentShader = OGLES2ShaderPath + "TransparentVertexAlpha.fsh"; + + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentVertexAlphaCB, EMT_TRANSPARENT_ALPHA_CHANNEL, 0); + + VertexShader = OGLES2ShaderPath + "Reflection2Layer.vsh"; + FragmentShader = OGLES2ShaderPath + "Reflection2Layer.fsh"; + + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, TransparentReflection2LayerCB, EMT_TRANSPARENT_ALPHA_CHANNEL, 0); + + VertexShader = OGLES2ShaderPath + "Solid.vsh"; + FragmentShader = OGLES2ShaderPath + "OneTextureBlend.fsh"; + + addHighLevelShaderMaterialFromFiles(VertexShader, "main", EVST_VS_2_0, FragmentShader, "main", EPST_PS_2_0, "", "main", + EGST_GS_4_0, scene::EPT_TRIANGLES, scene::EPT_TRIANGLE_STRIP, 0, OneTextureBlendCB, EMT_ONETEXTURE_BLEND, 0); + + // Drop callbacks. + + SolidCB->drop(); + Solid2LayerCB->drop(); + LightmapCB->drop(); + LightmapAddCB->drop(); + LightmapM2CB->drop(); + LightmapM4CB->drop(); + LightmapLightingCB->drop(); + LightmapLightingM2CB->drop(); + LightmapLightingM4CB->drop(); + DetailMapCB->drop(); + SphereMapCB->drop(); + Reflection2LayerCB->drop(); + TransparentAddColorCB->drop(); + TransparentAlphaChannelCB->drop(); + TransparentAlphaChannelRefCB->drop(); + TransparentVertexAlphaCB->drop(); + TransparentReflection2LayerCB->drop(); + OneTextureBlendCB->drop(); + + // Create 2D material renderers + + c8* vs2DData = 0; + c8* fs2DData = 0; + loadShaderData(io::path("Renderer2D.vsh"), io::path("Renderer2D.fsh"), &vs2DData, &fs2DData); + MaterialRenderer2DTexture = new COpenGL3Renderer2D(vs2DData, fs2DData, this, true); + delete[] vs2DData; + delete[] fs2DData; + vs2DData = 0; + fs2DData = 0; + + loadShaderData(io::path("Renderer2D.vsh"), io::path("Renderer2D_noTex.fsh"), &vs2DData, &fs2DData); + MaterialRenderer2DNoTexture = new COpenGL3Renderer2D(vs2DData, fs2DData, this, false); + delete[] vs2DData; + delete[] fs2DData; + } + + bool COpenGL3DriverBase::setMaterialTexture(irr::u32 layerIdx, const irr::video::ITexture* texture) + { + Material.TextureLayer[layerIdx].Texture = const_cast(texture); // function uses const-pointer for texture because all draw functions use const-pointers already + return CacheHandler->getTextureCache().set(0, texture); + } + + bool COpenGL3DriverBase::beginScene(u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil, const SExposedVideoData& videoData, core::rect* sourceRect) + { + CNullDriver::beginScene(clearFlag, clearColor, clearDepth, clearStencil, videoData, sourceRect); + + if (ContextManager) + ContextManager->activateContext(videoData, true); + + clearBuffers(clearFlag, clearColor, clearDepth, clearStencil); + + return true; + } + + bool COpenGL3DriverBase::endScene() + { + CNullDriver::endScene(); + + glFlush(); + + if (ContextManager) + return ContextManager->swapBuffers(); + + return false; + } + + + //! Returns the transformation set by setTransform + const core::matrix4& COpenGL3DriverBase::getTransform(E_TRANSFORMATION_STATE state) const + { + return Matrices[state]; + } + + + //! sets transformation + void COpenGL3DriverBase::setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat) + { + Matrices[state] = mat; + Transformation3DChanged = true; + } + + + bool COpenGL3DriverBase::updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) + { + if (!HWBuffer) + return false; + + const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer; + const void* vertices = mb->getVertices(); + const u32 vertexCount = mb->getVertexCount(); + const E_VERTEX_TYPE vType = mb->getVertexType(); + const u32 vertexSize = getVertexPitchFromType(vType); + + const void *buffer = vertices; + size_t bufferSize = vertexSize * vertexCount; + + //get or create buffer + bool newBuffer = false; + if (!HWBuffer->vbo_verticesID) + { + glGenBuffers(1, &HWBuffer->vbo_verticesID); + if (!HWBuffer->vbo_verticesID) return false; + newBuffer = true; + } + else if (HWBuffer->vbo_verticesSize < bufferSize) + { + newBuffer = true; + } + + glBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID); + + // copy data to graphics card + if (!newBuffer) + glBufferSubData(GL_ARRAY_BUFFER, 0, bufferSize, buffer); + else + { + HWBuffer->vbo_verticesSize = bufferSize; + + if (HWBuffer->Mapped_Vertex == scene::EHM_STATIC) + glBufferData(GL_ARRAY_BUFFER, bufferSize, buffer, GL_STATIC_DRAW); + else + glBufferData(GL_ARRAY_BUFFER, bufferSize, buffer, GL_DYNAMIC_DRAW); + } + + glBindBuffer(GL_ARRAY_BUFFER, 0); + + return (!testGLError(__LINE__)); + } + + + bool COpenGL3DriverBase::updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer) + { + if (!HWBuffer) + return false; + + const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer; + + const void* indices = mb->getIndices(); + u32 indexCount = mb->getIndexCount(); + + GLenum indexSize; + switch (mb->getIndexType()) + { + case(EIT_16BIT): + { + indexSize = sizeof(u16); + break; + } + case(EIT_32BIT): + { + indexSize = sizeof(u32); + break; + } + default: + { + return false; + } + } + + //get or create buffer + bool newBuffer = false; + if (!HWBuffer->vbo_indicesID) + { + glGenBuffers(1, &HWBuffer->vbo_indicesID); + if (!HWBuffer->vbo_indicesID) return false; + newBuffer = true; + } + else if (HWBuffer->vbo_indicesSize < indexCount*indexSize) + { + newBuffer = true; + } + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID); + + // copy data to graphics card + if (!newBuffer) + glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, indexCount * indexSize, indices); + else + { + HWBuffer->vbo_indicesSize = indexCount * indexSize; + + if (HWBuffer->Mapped_Index == scene::EHM_STATIC) + glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, GL_STATIC_DRAW); + else + glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * indexSize, indices, GL_DYNAMIC_DRAW); + } + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + + return (!testGLError(__LINE__)); + } + + + //! updates hardware buffer if needed + bool COpenGL3DriverBase::updateHardwareBuffer(SHWBufferLink *HWBuffer) + { + if (!HWBuffer) + return false; + + if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) + { + if (HWBuffer->ChangedID_Vertex != HWBuffer->MeshBuffer->getChangedID_Vertex() + || !static_cast(HWBuffer)->vbo_verticesID) + { + + HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex(); + + if (!updateVertexHardwareBuffer(static_cast(HWBuffer))) + return false; + } + } + + if (HWBuffer->Mapped_Index != scene::EHM_NEVER) + { + if (HWBuffer->ChangedID_Index != HWBuffer->MeshBuffer->getChangedID_Index() + || !static_cast(HWBuffer)->vbo_indicesID) + { + + HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index(); + + if (!updateIndexHardwareBuffer((SHWBufferLink_opengl*)HWBuffer)) + return false; + } + } + + return true; + } + + + //! Create hardware buffer from meshbuffer + COpenGL3DriverBase::SHWBufferLink *COpenGL3DriverBase::createHardwareBuffer(const scene::IMeshBuffer* mb) + { + if (!mb || (mb->getHardwareMappingHint_Index() == scene::EHM_NEVER && mb->getHardwareMappingHint_Vertex() == scene::EHM_NEVER)) + return 0; + + SHWBufferLink_opengl *HWBuffer = new SHWBufferLink_opengl(mb); + + //add to map + HWBuffer->listPosition = HWBufferList.insert(HWBufferList.end(), HWBuffer); + + HWBuffer->ChangedID_Vertex = HWBuffer->MeshBuffer->getChangedID_Vertex(); + HWBuffer->ChangedID_Index = HWBuffer->MeshBuffer->getChangedID_Index(); + HWBuffer->Mapped_Vertex = mb->getHardwareMappingHint_Vertex(); + HWBuffer->Mapped_Index = mb->getHardwareMappingHint_Index(); + HWBuffer->vbo_verticesID = 0; + HWBuffer->vbo_indicesID = 0; + HWBuffer->vbo_verticesSize = 0; + HWBuffer->vbo_indicesSize = 0; + + if (!updateHardwareBuffer(HWBuffer)) + { + deleteHardwareBuffer(HWBuffer); + return 0; + } + + return HWBuffer; + } + + + void COpenGL3DriverBase::deleteHardwareBuffer(SHWBufferLink *_HWBuffer) + { + if (!_HWBuffer) + return; + + SHWBufferLink_opengl *HWBuffer = static_cast(_HWBuffer); + if (HWBuffer->vbo_verticesID) + { + glDeleteBuffers(1, &HWBuffer->vbo_verticesID); + HWBuffer->vbo_verticesID = 0; + } + if (HWBuffer->vbo_indicesID) + { + glDeleteBuffers(1, &HWBuffer->vbo_indicesID); + HWBuffer->vbo_indicesID = 0; + } + + CNullDriver::deleteHardwareBuffer(_HWBuffer); + } + + + //! Draw hardware buffer + void COpenGL3DriverBase::drawHardwareBuffer(SHWBufferLink *_HWBuffer) + { + if (!_HWBuffer) + return; + + SHWBufferLink_opengl *HWBuffer = static_cast(_HWBuffer); + + updateHardwareBuffer(HWBuffer); //check if update is needed + + const scene::IMeshBuffer* mb = HWBuffer->MeshBuffer; + const void *vertices = mb->getVertices(); + const void *indexList = mb->getIndices(); + + if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) + { + glBindBuffer(GL_ARRAY_BUFFER, HWBuffer->vbo_verticesID); + vertices = 0; + } + + if (HWBuffer->Mapped_Index != scene::EHM_NEVER) + { + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, HWBuffer->vbo_indicesID); + indexList = 0; + } + + + drawVertexPrimitiveList(vertices, mb->getVertexCount(), + indexList, mb->getPrimitiveCount(), + mb->getVertexType(), mb->getPrimitiveType(), + mb->getIndexType()); + + if (HWBuffer->Mapped_Vertex != scene::EHM_NEVER) + glBindBuffer(GL_ARRAY_BUFFER, 0); + + if (HWBuffer->Mapped_Index != scene::EHM_NEVER) + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + } + + + IRenderTarget* COpenGL3DriverBase::addRenderTarget() + { + COpenGL3RenderTarget* renderTarget = new COpenGL3RenderTarget(this); + RenderTargets.push_back(renderTarget); + + return renderTarget; + } + + + // small helper function to create vertex buffer object adress offsets + static inline u8* buffer_offset(const long offset) + { + return ((u8*)0 + offset); + } + + + //! draws a vertex primitive list + void COpenGL3DriverBase::drawVertexPrimitiveList(const void* vertices, u32 vertexCount, + const void* indexList, u32 primitiveCount, + E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) + { + if (!primitiveCount || !vertexCount) + return; + + if (!checkPrimitiveCount(primitiveCount)) + return; + + CNullDriver::drawVertexPrimitiveList(vertices, vertexCount, indexList, primitiveCount, vType, pType, iType); + + setRenderStates3DMode(); + + auto &vTypeDesc = getVertexTypeDescription(vType); + beginDraw(vTypeDesc, reinterpret_cast(vertices)); + GLenum indexSize = 0; + + switch (iType) + { + case(EIT_16BIT): + { + indexSize = GL_UNSIGNED_SHORT; + break; + } + case(EIT_32BIT): + { +#ifdef GL_OES_element_index_uint +#ifndef GL_UNSIGNED_INT +#define GL_UNSIGNED_INT 0x1405 +#endif + if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_OES_element_index_uint]) + indexSize = GL_UNSIGNED_INT; + else +#endif + indexSize = GL_UNSIGNED_SHORT; + break; + } + } + + switch (pType) + { + case scene::EPT_POINTS: + case scene::EPT_POINT_SPRITES: + glDrawArrays(GL_POINTS, 0, primitiveCount); + break; + case scene::EPT_LINE_STRIP: + glDrawElements(GL_LINE_STRIP, primitiveCount + 1, indexSize, indexList); + break; + case scene::EPT_LINE_LOOP: + glDrawElements(GL_LINE_LOOP, primitiveCount, indexSize, indexList); + break; + case scene::EPT_LINES: + glDrawElements(GL_LINES, primitiveCount*2, indexSize, indexList); + break; + case scene::EPT_TRIANGLE_STRIP: + glDrawElements(GL_TRIANGLE_STRIP, primitiveCount + 2, indexSize, indexList); + break; + case scene::EPT_TRIANGLE_FAN: + glDrawElements(GL_TRIANGLE_FAN, primitiveCount + 2, indexSize, indexList); + break; + case scene::EPT_TRIANGLES: + glDrawElements((LastMaterial.Wireframe) ? GL_LINES : (LastMaterial.PointCloud) ? GL_POINTS : GL_TRIANGLES, primitiveCount*3, indexSize, indexList); + break; + default: + break; + } + + endDraw(vTypeDesc); + } + + + void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, const core::position2d& destPos, + const core::rect& sourceRect, const core::rect* clipRect, SColor color, + bool useAlphaChannelOfTexture) + { + if (!texture) + return; + + if (!sourceRect.isValid()) + return; + + SColor colors[4] = {color, color, color, color}; + draw2DImage(texture, {destPos, sourceRect.getSize()}, sourceRect, clipRect, colors, useAlphaChannelOfTexture); + } + + + void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, const core::rect& destRect, + const core::rect& sourceRect, const core::rect* clipRect, + const video::SColor* const colors, bool useAlphaChannelOfTexture) + { + if (!texture) + return; + + // texcoords need to be flipped horizontally for RTTs + const bool isRTT = texture->isRenderTarget(); + const core::dimension2du& ss = texture->getOriginalSize(); + const f32 invW = 1.f / static_cast(ss.Width); + const f32 invH = 1.f / static_cast(ss.Height); + const core::rect tcoords( + sourceRect.UpperLeftCorner.X * invW, + (isRTT ? sourceRect.LowerRightCorner.Y : sourceRect.UpperLeftCorner.Y) * invH, + sourceRect.LowerRightCorner.X * invW, + (isRTT ? sourceRect.UpperLeftCorner.Y : sourceRect.LowerRightCorner.Y) *invH); + + const video::SColor temp[4] = + { + 0xFFFFFFFF, + 0xFFFFFFFF, + 0xFFFFFFFF, + 0xFFFFFFFF + }; + + const video::SColor* const useColor = colors ? colors : temp; + + chooseMaterial2D(); + if (!setMaterialTexture(0, texture )) + return; + + setRenderStates2DMode(useColor[0].getAlpha() < 255 || useColor[1].getAlpha() < 255 || + useColor[2].getAlpha() < 255 || useColor[3].getAlpha() < 255, + true, useAlphaChannelOfTexture); + + const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); + + if (clipRect) + { + if (!clipRect->isValid()) + return; + + glEnable(GL_SCISSOR_TEST); + glScissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y, + clipRect->getWidth(), clipRect->getHeight()); + } + + f32 left = (f32)destRect.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 right = (f32)destRect.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 down = 2.f - (f32)destRect.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; + f32 top = 2.f - (f32)destRect.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; + + S3DVertex vertices[4]; + vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, useColor[0], tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y); + vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, useColor[3], tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y); + vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, useColor[2], tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y); + vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, useColor[1], tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y); + + drawQuad(vt2DImage, vertices); + + if (clipRect) + glDisable(GL_SCISSOR_TEST); + + testGLError(__LINE__); + } + + void COpenGL3DriverBase::draw2DImage(const video::ITexture* texture, u32 layer, bool flip) + { + if (!texture) + return; + + chooseMaterial2D(); + if (!setMaterialTexture(0, texture )) + return; + + setRenderStates2DMode(false, true, true); + + S3DVertex quad2DVertices[4]; + + quad2DVertices[0].Pos = core::vector3df(-1.f, 1.f, 0.f); + quad2DVertices[1].Pos = core::vector3df(1.f, 1.f, 0.f); + quad2DVertices[2].Pos = core::vector3df(1.f, -1.f, 0.f); + quad2DVertices[3].Pos = core::vector3df(-1.f, -1.f, 0.f); + + f32 modificator = (flip) ? 1.f : 0.f; + + quad2DVertices[0].TCoords = core::vector2df(0.f, 0.f + modificator); + quad2DVertices[1].TCoords = core::vector2df(1.f, 0.f + modificator); + quad2DVertices[2].TCoords = core::vector2df(1.f, 1.f - modificator); + quad2DVertices[3].TCoords = core::vector2df(0.f, 1.f - modificator); + + quad2DVertices[0].Color = SColor(0xFFFFFFFF); + quad2DVertices[1].Color = SColor(0xFFFFFFFF); + quad2DVertices[2].Color = SColor(0xFFFFFFFF); + quad2DVertices[3].Color = SColor(0xFFFFFFFF); + + drawQuad(vt2DImage, quad2DVertices); + } + + void COpenGL3DriverBase::draw2DImageBatch(const video::ITexture* texture, + const core::array >& positions, + const core::array >& sourceRects, + const core::rect* clipRect, + SColor color, bool useAlphaChannelOfTexture) + { + if (!texture) + return; + + chooseMaterial2D(); + if (!setMaterialTexture(0, texture)) + return; + + setRenderStates2DMode(color.getAlpha() < 255, true, useAlphaChannelOfTexture); + + const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); + + if (clipRect) + { + if (!clipRect->isValid()) + return; + + glEnable(GL_SCISSOR_TEST); + glScissor(clipRect->UpperLeftCorner.X, renderTargetSize.Height - clipRect->LowerRightCorner.Y, + clipRect->getWidth(), clipRect->getHeight()); + } + + const irr::u32 drawCount = core::min_(positions.size(), sourceRects.size()); + assert(6 * std::size_t(drawCount) <= QuadsIndices.size()); + + core::array vtx(drawCount * 4); + + for (u32 i = 0; i < drawCount; i++) + { + core::position2d targetPos = positions[i]; + core::position2d sourcePos = sourceRects[i].UpperLeftCorner; + // This needs to be signed as it may go negative. + core::dimension2d sourceSize(sourceRects[i].getSize()); + + // now draw it. + + core::rect tcoords; + tcoords.UpperLeftCorner.X = (((f32)sourcePos.X)) / texture->getOriginalSize().Width ; + tcoords.UpperLeftCorner.Y = (((f32)sourcePos.Y)) / texture->getOriginalSize().Height; + tcoords.LowerRightCorner.X = tcoords.UpperLeftCorner.X + ((f32)(sourceSize.Width) / texture->getOriginalSize().Width); + tcoords.LowerRightCorner.Y = tcoords.UpperLeftCorner.Y + ((f32)(sourceSize.Height) / texture->getOriginalSize().Height); + + const core::rect poss(targetPos, sourceSize); + + f32 left = (f32)poss.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 right = (f32)poss.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 down = 2.f - (f32)poss.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; + f32 top = 2.f - (f32)poss.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; + + vtx.push_back(S3DVertex(left, top, 0.0f, + 0.0f, 0.0f, 0.0f, color, + tcoords.UpperLeftCorner.X, tcoords.UpperLeftCorner.Y)); + vtx.push_back(S3DVertex(right, top, 0.0f, + 0.0f, 0.0f, 0.0f, color, + tcoords.LowerRightCorner.X, tcoords.UpperLeftCorner.Y)); + vtx.push_back(S3DVertex(right, down, 0.0f, + 0.0f, 0.0f, 0.0f, color, + tcoords.LowerRightCorner.X, tcoords.LowerRightCorner.Y)); + vtx.push_back(S3DVertex(left, down, 0.0f, + 0.0f, 0.0f, 0.0f, color, + tcoords.UpperLeftCorner.X, tcoords.LowerRightCorner.Y)); + } + + drawElements(GL_TRIANGLES, vt2DImage, vtx.const_pointer(), QuadsIndices.data(), 6 * drawCount); + + if (clipRect) + glDisable(GL_SCISSOR_TEST); + } + + + //! draw a 2d rectangle + void COpenGL3DriverBase::draw2DRectangle(SColor color, + const core::rect& position, + const core::rect* clip) + { + chooseMaterial2D(); + setMaterialTexture(0, 0); + + setRenderStates2DMode(color.getAlpha() < 255, false, false); + + core::rect pos = position; + + if (clip) + pos.clipAgainst(*clip); + + if (!pos.isValid()) + return; + + const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); + + f32 left = (f32)pos.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 right = (f32)pos.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 down = 2.f - (f32)pos.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; + f32 top = 2.f - (f32)pos.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; + + S3DVertex vertices[4]; + vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, color, 0, 0); + vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, color, 0, 0); + vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, color, 0, 0); + vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, color, 0, 0); + + drawQuad(vtPrimitive, vertices); + } + + + //! draw an 2d rectangle + void COpenGL3DriverBase::draw2DRectangle(const core::rect& position, + SColor colorLeftUp, SColor colorRightUp, + SColor colorLeftDown, SColor colorRightDown, + const core::rect* clip) + { + core::rect pos = position; + + if (clip) + pos.clipAgainst(*clip); + + if (!pos.isValid()) + return; + + chooseMaterial2D(); + setMaterialTexture(0, 0); + + setRenderStates2DMode(colorLeftUp.getAlpha() < 255 || + colorRightUp.getAlpha() < 255 || + colorLeftDown.getAlpha() < 255 || + colorRightDown.getAlpha() < 255, false, false); + + const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); + + f32 left = (f32)pos.UpperLeftCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 right = (f32)pos.LowerRightCorner.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 down = 2.f - (f32)pos.LowerRightCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; + f32 top = 2.f - (f32)pos.UpperLeftCorner.Y / (f32)renderTargetSize.Height * 2.f - 1.f; + + S3DVertex vertices[4]; + vertices[0] = S3DVertex(left, top, 0, 0, 0, 1, colorLeftUp, 0, 0); + vertices[1] = S3DVertex(right, top, 0, 0, 0, 1, colorRightUp, 0, 0); + vertices[2] = S3DVertex(right, down, 0, 0, 0, 1, colorRightDown, 0, 0); + vertices[3] = S3DVertex(left, down, 0, 0, 0, 1, colorLeftDown, 0, 0); + + drawQuad(vtPrimitive, vertices); + } + + + //! Draws a 2d line. + void COpenGL3DriverBase::draw2DLine(const core::position2d& start, + const core::position2d& end, SColor color) + { + if (start==end) + drawPixel(start.X, start.Y, color); + else + { + chooseMaterial2D(); + setMaterialTexture(0, 0); + + setRenderStates2DMode(color.getAlpha() < 255, false, false); + + const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); + + f32 startX = (f32)start.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 endX = (f32)end.X / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 startY = 2.f - (f32)start.Y / (f32)renderTargetSize.Height * 2.f - 1.f; + f32 endY = 2.f - (f32)end.Y / (f32)renderTargetSize.Height * 2.f - 1.f; + + S3DVertex vertices[2]; + vertices[0] = S3DVertex(startX, startY, 0, 0, 0, 1, color, 0, 0); + vertices[1] = S3DVertex(endX, endY, 0, 0, 0, 1, color, 1, 1); + + drawArrays(GL_LINES, vtPrimitive, vertices, 2); + } + } + + + //! Draws a pixel + void COpenGL3DriverBase::drawPixel(u32 x, u32 y, const SColor &color) + { + const core::dimension2d& renderTargetSize = getCurrentRenderTargetSize(); + if (x > (u32)renderTargetSize.Width || y > (u32)renderTargetSize.Height) + return; + + chooseMaterial2D(); + setMaterialTexture(0, 0); + + setRenderStates2DMode(color.getAlpha() < 255, false, false); + + f32 X = (f32)x / (f32)renderTargetSize.Width * 2.f - 1.f; + f32 Y = 2.f - (f32)y / (f32)renderTargetSize.Height * 2.f - 1.f; + + S3DVertex vertices[1]; + vertices[0] = S3DVertex(X, Y, 0, 0, 0, 1, color, 0, 0); + + drawArrays(GL_POINTS, vtPrimitive, vertices, 1); + } + + void COpenGL3DriverBase::drawQuad(const VertexType &vertexType, const S3DVertex (&vertices)[4]) + { + drawArrays(GL_TRIANGLE_FAN, vertexType, vertices, 4); + } + + void COpenGL3DriverBase::drawArrays(GLenum primitiveType, const VertexType &vertexType, const void *vertices, int vertexCount) + { + beginDraw(vertexType, reinterpret_cast(vertices)); + glDrawArrays(primitiveType, 0, vertexCount); + endDraw(vertexType); + } + + void COpenGL3DriverBase::drawElements(GLenum primitiveType, const VertexType &vertexType, const void *vertices, const u16 *indices, int indexCount) + { + beginDraw(vertexType, reinterpret_cast(vertices)); + glDrawElements(primitiveType, indexCount, GL_UNSIGNED_SHORT, indices); + endDraw(vertexType); + } + + void COpenGL3DriverBase::beginDraw(const VertexType &vertexType, uintptr_t verticesBase) + { + for (auto attr: vertexType) { + glEnableVertexAttribArray(attr.Index); + switch (attr.mode) { + case VertexAttribute::Mode::Regular: glVertexAttribPointer(attr.Index, attr.ComponentCount, attr.ComponentType, GL_FALSE, vertexType.VertexSize, reinterpret_cast(verticesBase + attr.Offset)); break; + case VertexAttribute::Mode::Normalized: glVertexAttribPointer(attr.Index, attr.ComponentCount, attr.ComponentType, GL_TRUE, vertexType.VertexSize, reinterpret_cast(verticesBase + attr.Offset)); break; + case VertexAttribute::Mode::Integral: glVertexAttribIPointer(attr.Index, attr.ComponentCount, attr.ComponentType, vertexType.VertexSize, reinterpret_cast(verticesBase + attr.Offset)); break; + } + } + } + + void COpenGL3DriverBase::endDraw(const VertexType &vertexType) + { + for (auto attr: vertexType) + glDisableVertexAttribArray(attr.Index); + } + + ITexture* COpenGL3DriverBase::createDeviceDependentTexture(const io::path& name, IImage* image) + { + core::array imageArray(1); + imageArray.push_back(image); + + COpenGL3Texture* texture = new COpenGL3Texture(name, imageArray, ETT_2D, this); + + return texture; + } + + ITexture* COpenGL3DriverBase::createDeviceDependentTextureCubemap(const io::path& name, const core::array& image) + { + COpenGL3Texture* texture = new COpenGL3Texture(name, image, ETT_CUBEMAP, this); + + return texture; + } + + //! Sets a material. + void COpenGL3DriverBase::setMaterial(const SMaterial& material) + { + Material = material; + OverrideMaterial.apply(Material); + + for (u32 i = 0; i < Feature.MaxTextureUnits; ++i) + { + CacheHandler->getTextureCache().set(i, material.getTexture(i)); + setTransform((E_TRANSFORMATION_STATE)(ETS_TEXTURE_0 + i), material.getTextureMatrix(i)); + } + } + + //! prints error if an error happened. + bool COpenGL3DriverBase::testGLError(int code) + { +#ifdef _DEBUG + GLenum g = glGetError(); + switch (g) + { + case GL_NO_ERROR: + return false; + case GL_INVALID_ENUM: + os::Printer::log("GL_INVALID_ENUM", core::stringc(code).c_str(), ELL_ERROR); + break; + case GL_INVALID_VALUE: + os::Printer::log("GL_INVALID_VALUE", core::stringc(code).c_str(), ELL_ERROR); + break; + case GL_INVALID_OPERATION: + os::Printer::log("GL_INVALID_OPERATION", core::stringc(code).c_str(), ELL_ERROR); + break; + case GL_OUT_OF_MEMORY: + os::Printer::log("GL_OUT_OF_MEMORY", core::stringc(code).c_str(), ELL_ERROR); + break; + }; + return true; +#else + return false; +#endif + } + + //! prints error if an error happened. + bool COpenGL3DriverBase::testEGLError() + { +#if defined(EGL_VERSION_1_0) && defined(_DEBUG) + EGLint g = eglGetError(); + switch (g) + { + case EGL_SUCCESS: + return false; + case EGL_NOT_INITIALIZED : + os::Printer::log("Not Initialized", ELL_ERROR); + break; + case EGL_BAD_ACCESS: + os::Printer::log("Bad Access", ELL_ERROR); + break; + case EGL_BAD_ALLOC: + os::Printer::log("Bad Alloc", ELL_ERROR); + break; + case EGL_BAD_ATTRIBUTE: + os::Printer::log("Bad Attribute", ELL_ERROR); + break; + case EGL_BAD_CONTEXT: + os::Printer::log("Bad Context", ELL_ERROR); + break; + case EGL_BAD_CONFIG: + os::Printer::log("Bad Config", ELL_ERROR); + break; + case EGL_BAD_CURRENT_SURFACE: + os::Printer::log("Bad Current Surface", ELL_ERROR); + break; + case EGL_BAD_DISPLAY: + os::Printer::log("Bad Display", ELL_ERROR); + break; + case EGL_BAD_SURFACE: + os::Printer::log("Bad Surface", ELL_ERROR); + break; + case EGL_BAD_MATCH: + os::Printer::log("Bad Match", ELL_ERROR); + break; + case EGL_BAD_PARAMETER: + os::Printer::log("Bad Parameter", ELL_ERROR); + break; + case EGL_BAD_NATIVE_PIXMAP: + os::Printer::log("Bad Native Pixmap", ELL_ERROR); + break; + case EGL_BAD_NATIVE_WINDOW: + os::Printer::log("Bad Native Window", ELL_ERROR); + break; + case EGL_CONTEXT_LOST: + os::Printer::log("Context Lost", ELL_ERROR); + break; + }; + return true; +#else + return false; +#endif + } + + + void COpenGL3DriverBase::setRenderStates3DMode() + { + if ( LockRenderStateMode ) + return; + + if (CurrentRenderMode != ERM_3D) + { + // Reset Texture Stages + CacheHandler->setBlend(false); + CacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + ResetRenderStates = true; + } + + if (ResetRenderStates || LastMaterial != Material) + { + // unset old material + + // unset last 3d material + if (CurrentRenderMode == ERM_2D && MaterialRenderer2DActive) + { + MaterialRenderer2DActive->OnUnsetMaterial(); + MaterialRenderer2DActive = 0; + } + else if (LastMaterial.MaterialType != Material.MaterialType && + static_cast(LastMaterial.MaterialType) < MaterialRenderers.size()) + MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial(); + + // set new material. + if (static_cast(Material.MaterialType) < MaterialRenderers.size()) + MaterialRenderers[Material.MaterialType].Renderer->OnSetMaterial( + Material, LastMaterial, ResetRenderStates, this); + + LastMaterial = Material; + CacheHandler->correctCacheMaterial(LastMaterial); + ResetRenderStates = false; + } + + if (static_cast(Material.MaterialType) < MaterialRenderers.size()) + MaterialRenderers[Material.MaterialType].Renderer->OnRender(this, video::EVT_STANDARD); + + CurrentRenderMode = ERM_3D; + } + + //! Can be called by an IMaterialRenderer to make its work easier. + void COpenGL3DriverBase::setBasicRenderStates(const SMaterial& material, const SMaterial& lastmaterial, bool resetAllRenderStates) + { + // ZBuffer + switch (material.ZBuffer) + { + case ECFN_DISABLED: + CacheHandler->setDepthTest(false); + break; + case ECFN_LESSEQUAL: + CacheHandler->setDepthTest(true); + CacheHandler->setDepthFunc(GL_LEQUAL); + break; + case ECFN_EQUAL: + CacheHandler->setDepthTest(true); + CacheHandler->setDepthFunc(GL_EQUAL); + break; + case ECFN_LESS: + CacheHandler->setDepthTest(true); + CacheHandler->setDepthFunc(GL_LESS); + break; + case ECFN_NOTEQUAL: + CacheHandler->setDepthTest(true); + CacheHandler->setDepthFunc(GL_NOTEQUAL); + break; + case ECFN_GREATEREQUAL: + CacheHandler->setDepthTest(true); + CacheHandler->setDepthFunc(GL_GEQUAL); + break; + case ECFN_GREATER: + CacheHandler->setDepthTest(true); + CacheHandler->setDepthFunc(GL_GREATER); + break; + case ECFN_ALWAYS: + CacheHandler->setDepthTest(true); + CacheHandler->setDepthFunc(GL_ALWAYS); + break; + case ECFN_NEVER: + CacheHandler->setDepthTest(true); + CacheHandler->setDepthFunc(GL_NEVER); + break; + default: + break; + } + + // ZWrite + if (getWriteZBuffer(material)) + { + CacheHandler->setDepthMask(true); + } + else + { + CacheHandler->setDepthMask(false); + } + + // Back face culling + if ((material.FrontfaceCulling) && (material.BackfaceCulling)) + { + CacheHandler->setCullFaceFunc(GL_FRONT_AND_BACK); + CacheHandler->setCullFace(true); + } + else if (material.BackfaceCulling) + { + CacheHandler->setCullFaceFunc(GL_BACK); + CacheHandler->setCullFace(true); + } + else if (material.FrontfaceCulling) + { + CacheHandler->setCullFaceFunc(GL_FRONT); + CacheHandler->setCullFace(true); + } + else + { + CacheHandler->setCullFace(false); + } + + // Color Mask + CacheHandler->setColorMask(material.ColorMask); + + // Blend Equation + if (material.BlendOperation == EBO_NONE) + CacheHandler->setBlend(false); + else + { + CacheHandler->setBlend(true); + + switch (material.BlendOperation) + { + case EBO_ADD: + CacheHandler->setBlendEquation(GL_FUNC_ADD); + break; + case EBO_SUBTRACT: + CacheHandler->setBlendEquation(GL_FUNC_SUBTRACT); + break; + case EBO_REVSUBTRACT: + CacheHandler->setBlendEquation(GL_FUNC_REVERSE_SUBTRACT); + break; + default: + break; + } + } + + // Blend Factor + if (IR(material.BlendFactor) & 0xFFFFFFFF // TODO: why the & 0xFFFFFFFF? + && material.MaterialType != EMT_ONETEXTURE_BLEND + ) + { + E_BLEND_FACTOR srcRGBFact = EBF_ZERO; + E_BLEND_FACTOR dstRGBFact = EBF_ZERO; + E_BLEND_FACTOR srcAlphaFact = EBF_ZERO; + E_BLEND_FACTOR dstAlphaFact = EBF_ZERO; + E_MODULATE_FUNC modulo = EMFN_MODULATE_1X; + u32 alphaSource = 0; + + unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulo, alphaSource, material.BlendFactor); + + CacheHandler->setBlendFuncSeparate(getGLBlend(srcRGBFact), getGLBlend(dstRGBFact), + getGLBlend(srcAlphaFact), getGLBlend(dstAlphaFact)); + } + + // TODO: Polygon Offset. Not sure if it was left out deliberately or if it won't work with this driver. + + if (resetAllRenderStates || lastmaterial.Thickness != material.Thickness) + glLineWidth(core::clamp(static_cast(material.Thickness), DimAliasedLine[0], DimAliasedLine[1])); + + // Anti aliasing + if (resetAllRenderStates || lastmaterial.AntiAliasing != material.AntiAliasing) + { + if (material.AntiAliasing & EAAM_ALPHA_TO_COVERAGE) + glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE); + else if (lastmaterial.AntiAliasing & EAAM_ALPHA_TO_COVERAGE) + glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE); + } + + // Texture parameters + setTextureRenderStates(material, resetAllRenderStates); + } + + //! Compare in SMaterial doesn't check texture parameters, so we should call this on each OnRender call. + void COpenGL3DriverBase::setTextureRenderStates(const SMaterial& material, bool resetAllRenderstates) + { + // Set textures to TU/TIU and apply filters to them + + for (s32 i = Feature.MaxTextureUnits - 1; i >= 0; --i) + { + const COpenGL3Texture* tmpTexture = CacheHandler->getTextureCache()[i]; + + if (!tmpTexture) + continue; + + GLenum tmpTextureType = tmpTexture->getOpenGLTextureType(); + + CacheHandler->setActiveTexture(GL_TEXTURE0 + i); + + if (resetAllRenderstates) + tmpTexture->getStatesCache().IsCached = false; + + if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].BilinearFilter != tmpTexture->getStatesCache().BilinearFilter || + material.TextureLayer[i].TrilinearFilter != tmpTexture->getStatesCache().TrilinearFilter) + { + glTexParameteri(tmpTextureType, GL_TEXTURE_MAG_FILTER, + (material.TextureLayer[i].BilinearFilter || material.TextureLayer[i].TrilinearFilter) ? GL_LINEAR : GL_NEAREST); + + tmpTexture->getStatesCache().BilinearFilter = material.TextureLayer[i].BilinearFilter; + tmpTexture->getStatesCache().TrilinearFilter = material.TextureLayer[i].TrilinearFilter; + } + + if (material.UseMipMaps && tmpTexture->hasMipMaps()) + { + if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].BilinearFilter != tmpTexture->getStatesCache().BilinearFilter || + material.TextureLayer[i].TrilinearFilter != tmpTexture->getStatesCache().TrilinearFilter || !tmpTexture->getStatesCache().MipMapStatus) + { + glTexParameteri(tmpTextureType, GL_TEXTURE_MIN_FILTER, + material.TextureLayer[i].TrilinearFilter ? GL_LINEAR_MIPMAP_LINEAR : + material.TextureLayer[i].BilinearFilter ? GL_LINEAR_MIPMAP_NEAREST : + GL_NEAREST_MIPMAP_NEAREST); + + tmpTexture->getStatesCache().BilinearFilter = material.TextureLayer[i].BilinearFilter; + tmpTexture->getStatesCache().TrilinearFilter = material.TextureLayer[i].TrilinearFilter; + tmpTexture->getStatesCache().MipMapStatus = true; + } + } + else + { + if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].BilinearFilter != tmpTexture->getStatesCache().BilinearFilter || + material.TextureLayer[i].TrilinearFilter != tmpTexture->getStatesCache().TrilinearFilter || tmpTexture->getStatesCache().MipMapStatus) + { + glTexParameteri(tmpTextureType, GL_TEXTURE_MIN_FILTER, + (material.TextureLayer[i].BilinearFilter || material.TextureLayer[i].TrilinearFilter) ? GL_LINEAR : GL_NEAREST); + + tmpTexture->getStatesCache().BilinearFilter = material.TextureLayer[i].BilinearFilter; + tmpTexture->getStatesCache().TrilinearFilter = material.TextureLayer[i].TrilinearFilter; + tmpTexture->getStatesCache().MipMapStatus = false; + } + } + + #ifdef GL_EXT_texture_filter_anisotropic + if (FeatureAvailable[COGLESCoreExtensionHandler::IRR_GL_EXT_texture_filter_anisotropic] && + (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].AnisotropicFilter != tmpTexture->getStatesCache().AnisotropicFilter)) + { + glTexParameteri(tmpTextureType, GL_TEXTURE_MAX_ANISOTROPY_EXT, + material.TextureLayer[i].AnisotropicFilter>1 ? core::min_(MaxAnisotropy, material.TextureLayer[i].AnisotropicFilter) : 1); + + tmpTexture->getStatesCache().AnisotropicFilter = material.TextureLayer[i].AnisotropicFilter; + } + #endif + + if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].TextureWrapU != tmpTexture->getStatesCache().WrapU) + { + glTexParameteri(tmpTextureType, GL_TEXTURE_WRAP_S, getTextureWrapMode(material.TextureLayer[i].TextureWrapU)); + tmpTexture->getStatesCache().WrapU = material.TextureLayer[i].TextureWrapU; + } + + if (!tmpTexture->getStatesCache().IsCached || material.TextureLayer[i].TextureWrapV != tmpTexture->getStatesCache().WrapV) + { + glTexParameteri(tmpTextureType, GL_TEXTURE_WRAP_T, getTextureWrapMode(material.TextureLayer[i].TextureWrapV)); + tmpTexture->getStatesCache().WrapV = material.TextureLayer[i].TextureWrapV; + } + + tmpTexture->getStatesCache().IsCached = true; + } + } + + + // Get OpenGL ES2.0 texture wrap mode from Irrlicht wrap mode. + GLint COpenGL3DriverBase::getTextureWrapMode(u8 clamp) const + { + switch (clamp) + { + case ETC_CLAMP: + case ETC_CLAMP_TO_EDGE: + case ETC_CLAMP_TO_BORDER: + return GL_CLAMP_TO_EDGE; + case ETC_MIRROR: + return GL_REPEAT; + default: + return GL_REPEAT; + } + } + + + //! sets the needed renderstates + void COpenGL3DriverBase::setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel) + { + if ( LockRenderStateMode ) + return; + + COpenGL3Renderer2D* nextActiveRenderer = texture ? MaterialRenderer2DTexture : MaterialRenderer2DNoTexture; + + if (CurrentRenderMode != ERM_2D) + { + // unset last 3d material + if (CurrentRenderMode == ERM_3D) + { + if (static_cast(LastMaterial.MaterialType) < MaterialRenderers.size()) + MaterialRenderers[LastMaterial.MaterialType].Renderer->OnUnsetMaterial(); + } + + CurrentRenderMode = ERM_2D; + } + else if ( MaterialRenderer2DActive && MaterialRenderer2DActive != nextActiveRenderer) + { + MaterialRenderer2DActive->OnUnsetMaterial(); + } + + MaterialRenderer2DActive = nextActiveRenderer; + + MaterialRenderer2DActive->OnSetMaterial(Material, LastMaterial, true, 0); + LastMaterial = Material; + CacheHandler->correctCacheMaterial(LastMaterial); + + // no alphaChannel without texture + alphaChannel &= texture; + + if (alphaChannel || alpha) + { + CacheHandler->setBlend(true); + CacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + CacheHandler->setBlendEquation(GL_FUNC_ADD); + } + else + CacheHandler->setBlend(false); + + Material.setTexture(0, const_cast(CacheHandler->getTextureCache().get(0))); + setTransform(ETS_TEXTURE_0, core::IdentityMatrix); + + if (texture) + { + if (OverrideMaterial2DEnabled) + setTextureRenderStates(OverrideMaterial2D, false); + else + setTextureRenderStates(InitMaterial2D, false); + } + + MaterialRenderer2DActive->OnRender(this, video::EVT_STANDARD); + } + + + void COpenGL3DriverBase::chooseMaterial2D() + { + if (!OverrideMaterial2DEnabled) + Material = InitMaterial2D; + + if (OverrideMaterial2DEnabled) + { + OverrideMaterial2D.Lighting=false; + OverrideMaterial2D.ZWriteEnable=EZW_OFF; + OverrideMaterial2D.ZBuffer=ECFN_DISABLED; // it will be ECFN_DISABLED after merge + OverrideMaterial2D.Lighting=false; + + Material = OverrideMaterial2D; + } + } + + + //! \return Returns the name of the video driver. + const wchar_t* COpenGL3DriverBase::getName() const + { + return Name.c_str(); + } + + void COpenGL3DriverBase::setViewPort(const core::rect& area) + { + core::rect vp = area; + core::rect rendert(0, 0, getCurrentRenderTargetSize().Width, getCurrentRenderTargetSize().Height); + vp.clipAgainst(rendert); + + if (vp.getHeight() > 0 && vp.getWidth() > 0) + CacheHandler->setViewport(vp.UpperLeftCorner.X, getCurrentRenderTargetSize().Height - vp.UpperLeftCorner.Y - vp.getHeight(), vp.getWidth(), vp.getHeight()); + + ViewPort = vp; + } + + + void COpenGL3DriverBase::setViewPortRaw(u32 width, u32 height) + { + CacheHandler->setViewport(0, 0, width, height); + ViewPort = core::recti(0, 0, width, height); + } + + + //! Draws a 3d line. + void COpenGL3DriverBase::draw3DLine(const core::vector3df& start, + const core::vector3df& end, SColor color) + { + setRenderStates3DMode(); + + S3DVertex vertices[2]; + vertices[0] = S3DVertex(start.X, start.Y, start.Z, 0, 0, 1, color, 0, 0); + vertices[1] = S3DVertex(end.X, end.Y, end.Z, 0, 0, 1, color, 0, 0); + + drawArrays(GL_LINES, vtPrimitive, vertices, 2); + } + + + //! Only used by the internal engine. Used to notify the driver that + //! the window was resized. + void COpenGL3DriverBase::OnResize(const core::dimension2d& size) + { + CNullDriver::OnResize(size); + CacheHandler->setViewport(0, 0, size.Width, size.Height); + Transformation3DChanged = true; + } + + + //! Returns type of video driver + E_DRIVER_TYPE COpenGL3DriverBase::getDriverType() const + { + return EDT_OPENGL3; + } + + + //! returns color format + ECOLOR_FORMAT COpenGL3DriverBase::getColorFormat() const + { + return ColorFormat; + } + + + //! Get a vertex shader constant index. + s32 COpenGL3DriverBase::getVertexShaderConstantID(const c8* name) + { + return getPixelShaderConstantID(name); + } + + //! Get a pixel shader constant index. + s32 COpenGL3DriverBase::getPixelShaderConstantID(const c8* name) + { + os::Printer::log("Error: Please call services->getPixelShaderConstantID(), not VideoDriver->getPixelShaderConstantID()."); + return -1; + } + + //! Sets a vertex shader constant. + void COpenGL3DriverBase::setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount) + { + os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setPixelShaderConstant()."); + } + + //! Sets a pixel shader constant. + void COpenGL3DriverBase::setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount) + { + os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant()."); + } + + //! Sets a constant for the vertex shader based on an index. + bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const f32* floats, int count) + { + os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant()."); + return false; + } + + //! Int interface for the above. + bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const s32* ints, int count) + { + os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant()."); + return false; + } + + bool COpenGL3DriverBase::setVertexShaderConstant(s32 index, const u32* ints, int count) + { + os::Printer::log("Error: Please call services->setVertexShaderConstant(), not VideoDriver->setVertexShaderConstant()."); + return false; + } + + //! Sets a constant for the pixel shader based on an index. + bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const f32* floats, int count) + { + os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant()."); + return false; + } + + //! Int interface for the above. + bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const s32* ints, int count) + { + os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant()."); + return false; + } + + bool COpenGL3DriverBase::setPixelShaderConstant(s32 index, const u32* ints, int count) + { + os::Printer::log("Error: Please call services->setPixelShaderConstant(), not VideoDriver->setPixelShaderConstant()."); + return false; + } + + //! Adds a new material renderer to the VideoDriver, using pixel and/or + //! vertex shaders to render geometry. + s32 COpenGL3DriverBase::addShaderMaterial(const c8* vertexShaderProgram, + const c8* pixelShaderProgram, + IShaderConstantSetCallBack* callback, + E_MATERIAL_TYPE baseMaterial, s32 userData) + { + os::Printer::log("No shader support."); + return -1; + } + + + //! Adds a new material renderer to the VideoDriver, using GLSL to render geometry. + s32 COpenGL3DriverBase::addHighLevelShaderMaterial( + const c8* vertexShaderProgram, + const c8* vertexShaderEntryPointName, + E_VERTEX_SHADER_TYPE vsCompileTarget, + const c8* pixelShaderProgram, + const c8* pixelShaderEntryPointName, + E_PIXEL_SHADER_TYPE psCompileTarget, + const c8* geometryShaderProgram, + const c8* geometryShaderEntryPointName, + E_GEOMETRY_SHADER_TYPE gsCompileTarget, + scene::E_PRIMITIVE_TYPE inType, + scene::E_PRIMITIVE_TYPE outType, + u32 verticesOut, + IShaderConstantSetCallBack* callback, + E_MATERIAL_TYPE baseMaterial, + s32 userData) + { + s32 nr = -1; + COpenGL3MaterialRenderer* r = new COpenGL3MaterialRenderer( + this, nr, vertexShaderProgram, + pixelShaderProgram, + callback, baseMaterial, userData); + + r->drop(); + return nr; + } + + //! Returns a pointer to the IVideoDriver interface. (Implementation for + //! IMaterialRendererServices) + IVideoDriver* COpenGL3DriverBase::getVideoDriver() + { + return this; + } + + + //! Returns pointer to the IGPUProgrammingServices interface. + IGPUProgrammingServices* COpenGL3DriverBase::getGPUProgrammingServices() + { + return this; + } + + ITexture* COpenGL3DriverBase::addRenderTargetTexture(const core::dimension2d& size, + const io::path& name, const ECOLOR_FORMAT format) + { + //disable mip-mapping + bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS); + setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false); + + COpenGL3Texture* renderTargetTexture = new COpenGL3Texture(name, size, ETT_2D, format, this); + addTexture(renderTargetTexture); + renderTargetTexture->drop(); + + //restore mip-mapping + setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels); + + return renderTargetTexture; + } + + ITexture* COpenGL3DriverBase::addRenderTargetTextureCubemap(const irr::u32 sideLen, const io::path& name, const ECOLOR_FORMAT format) + { + //disable mip-mapping + bool generateMipLevels = getTextureCreationFlag(ETCF_CREATE_MIP_MAPS); + setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, false); + + bool supportForFBO = (Feature.ColorAttachment > 0); + + const core::dimension2d size(sideLen, sideLen); + core::dimension2du destSize(size); + + if (!supportForFBO) + { + destSize = core::dimension2d(core::min_(size.Width, ScreenSize.Width), core::min_(size.Height, ScreenSize.Height)); + destSize = destSize.getOptimalSize((size == size.getOptimalSize()), false, false); + } + + COpenGL3Texture* renderTargetTexture = new COpenGL3Texture(name, destSize, ETT_CUBEMAP, format, this); + addTexture(renderTargetTexture); + renderTargetTexture->drop(); + + //restore mip-mapping + setTextureCreationFlag(ETCF_CREATE_MIP_MAPS, generateMipLevels); + + return renderTargetTexture; + } + + + //! Returns the maximum amount of primitives + u32 COpenGL3DriverBase::getMaximalPrimitiveCount() const + { + return 65535; + } + + bool COpenGL3DriverBase::setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SColor clearColor, f32 clearDepth, u8 clearStencil) + { + if (target && target->getDriverType() != getDriverType()) + { + os::Printer::log("Fatal Error: Tried to set a render target not owned by OpenGL 3 driver.", ELL_ERROR); + return false; + } + + core::dimension2d destRenderTargetSize(0, 0); + + if (target) + { + COpenGL3RenderTarget* renderTarget = static_cast(target); + + CacheHandler->setFBO(renderTarget->getBufferID()); + renderTarget->update(); + + destRenderTargetSize = renderTarget->getSize(); + + setViewPortRaw(destRenderTargetSize.Width, destRenderTargetSize.Height); + } + else + { + CacheHandler->setFBO(0); + + destRenderTargetSize = core::dimension2d(0, 0); + + setViewPortRaw(ScreenSize.Width, ScreenSize.Height); + } + + if (CurrentRenderTargetSize != destRenderTargetSize) + { + CurrentRenderTargetSize = destRenderTargetSize; + + Transformation3DChanged = true; + } + + CurrentRenderTarget = target; + + clearBuffers(clearFlag, clearColor, clearDepth, clearStencil); + + return true; + } + + void COpenGL3DriverBase::clearBuffers(u16 flag, SColor color, f32 depth, u8 stencil) + { + GLbitfield mask = 0; + u8 colorMask = 0; + bool depthMask = false; + + CacheHandler->getColorMask(colorMask); + CacheHandler->getDepthMask(depthMask); + + if (flag & ECBF_COLOR) + { + CacheHandler->setColorMask(ECP_ALL); + + const f32 inv = 1.0f / 255.0f; + glClearColor(color.getRed() * inv, color.getGreen() * inv, + color.getBlue() * inv, color.getAlpha() * inv); + + mask |= GL_COLOR_BUFFER_BIT; + } + + if (flag & ECBF_DEPTH) + { + CacheHandler->setDepthMask(true); + glClearDepthf(depth); + mask |= GL_DEPTH_BUFFER_BIT; + } + + if (flag & ECBF_STENCIL) + { + glClearStencil(stencil); + mask |= GL_STENCIL_BUFFER_BIT; + } + + if (mask) + glClear(mask); + + CacheHandler->setColorMask(colorMask); + CacheHandler->setDepthMask(depthMask); + } + + + //! Returns an image created from the last rendered frame. + // We want to read the front buffer to get the latest render finished. + // This is not possible under ogl-es, though, so one has to call this method + // outside of the render loop only. + IImage* COpenGL3DriverBase::createScreenShot(video::ECOLOR_FORMAT format, video::E_RENDER_TARGET target) + { + if (target==video::ERT_MULTI_RENDER_TEXTURES || target==video::ERT_RENDER_TEXTURE || target==video::ERT_STEREO_BOTH_BUFFERS) + return 0; + + GLint internalformat = GL_RGBA; + GLint type = GL_UNSIGNED_BYTE; + { +// glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT, &internalformat); +// glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE, &type); + // there's a format we don't support ATM + if (GL_UNSIGNED_SHORT_4_4_4_4 == type) + { + internalformat = GL_RGBA; + type = GL_UNSIGNED_BYTE; + } + } + + IImage* newImage = 0; + if (GL_RGBA == internalformat) + { + if (GL_UNSIGNED_BYTE == type) + newImage = new CImage(ECF_A8R8G8B8, ScreenSize); + else + newImage = new CImage(ECF_A1R5G5B5, ScreenSize); + } + else + { + if (GL_UNSIGNED_BYTE == type) + newImage = new CImage(ECF_R8G8B8, ScreenSize); + else + newImage = new CImage(ECF_R5G6B5, ScreenSize); + } + + if (!newImage) + return 0; + + u8* pixels = static_cast(newImage->getData()); + if (!pixels) + { + newImage->drop(); + return 0; + } + + glReadPixels(0, 0, ScreenSize.Width, ScreenSize.Height, internalformat, type, pixels); + testGLError(__LINE__); + + // opengl images are horizontally flipped, so we have to fix that here. + const s32 pitch = newImage->getPitch(); + u8* p2 = pixels + (ScreenSize.Height - 1) * pitch; + u8* tmpBuffer = new u8[pitch]; + for (u32 i = 0; i < ScreenSize.Height; i += 2) + { + memcpy(tmpBuffer, pixels, pitch); + memcpy(pixels, p2, pitch); + memcpy(p2, tmpBuffer, pitch); + pixels += pitch; + p2 -= pitch; + } + delete [] tmpBuffer; + + // also GL_RGBA doesn't match the internal encoding of the image (which is BGRA) + if (GL_RGBA == internalformat && GL_UNSIGNED_BYTE == type) + { + pixels = static_cast(newImage->getData()); + for (u32 i = 0; i < ScreenSize.Height; i++) + { + for (u32 j = 0; j < ScreenSize.Width; j++) + { + u32 c = *(u32*) (pixels + 4 * j); + *(u32*) (pixels + 4 * j) = (c & 0xFF00FF00) | + ((c & 0x00FF0000) >> 16) | ((c & 0x000000FF) << 16); + } + pixels += pitch; + } + } + + if (testGLError(__LINE__)) + { + newImage->drop(); + return 0; + } + testGLError(__LINE__); + return newImage; + } + + void COpenGL3DriverBase::removeTexture(ITexture* texture) + { + CacheHandler->getTextureCache().remove(texture); + CNullDriver::removeTexture(texture); + } + + //! Set/unset a clipping plane. + bool COpenGL3DriverBase::setClipPlane(u32 index, const core::plane3df& plane, bool enable) + { + if (index >= UserClipPlane.size()) + UserClipPlane.push_back(SUserClipPlane()); + + UserClipPlane[index].Plane = plane; + UserClipPlane[index].Enabled = enable; + return true; + } + + //! Enable/disable a clipping plane. + void COpenGL3DriverBase::enableClipPlane(u32 index, bool enable) + { + UserClipPlane[index].Enabled = enable; + } + + //! Get the ClipPlane Count + u32 COpenGL3DriverBase::getClipPlaneCount() const + { + return UserClipPlane.size(); + } + + const core::plane3df& COpenGL3DriverBase::getClipPlane(irr::u32 index) const + { + if (index < UserClipPlane.size()) + return UserClipPlane[index].Plane; + else + { + _IRR_DEBUG_BREAK_IF(true) // invalid index + static const core::plane3df dummy; + return dummy; + } + } + + core::dimension2du COpenGL3DriverBase::getMaxTextureSize() const + { + return core::dimension2du(MaxTextureSize, MaxTextureSize); + } + + GLenum COpenGL3DriverBase::getGLBlend(E_BLEND_FACTOR factor) const + { + static GLenum const blendTable[] = + { + GL_ZERO, + GL_ONE, + GL_DST_COLOR, + GL_ONE_MINUS_DST_COLOR, + GL_SRC_COLOR, + GL_ONE_MINUS_SRC_COLOR, + GL_SRC_ALPHA, + GL_ONE_MINUS_SRC_ALPHA, + GL_DST_ALPHA, + GL_ONE_MINUS_DST_ALPHA, + GL_SRC_ALPHA_SATURATE + }; + + return blendTable[factor]; + } + + bool COpenGL3DriverBase::getColorFormatParameters(ECOLOR_FORMAT format, GLint& internalFormat, GLenum& pixelFormat, + GLenum& pixelType, void(**converter)(const void*, s32, void*)) const + { + bool supported = false; + pixelFormat = GL_RGBA; + pixelType = GL_UNSIGNED_BYTE; + *converter = 0; + + switch (format) + { + case ECF_A1R5G5B5: + supported = true; + pixelFormat = GL_RGBA; + pixelType = GL_UNSIGNED_SHORT_5_5_5_1; + *converter = CColorConverter::convert_A1R5G5B5toR5G5B5A1; + break; + case ECF_R5G6B5: + supported = true; + pixelFormat = GL_RGB; + pixelType = GL_UNSIGNED_SHORT_5_6_5; + break; + case ECF_R8G8B8: + supported = true; + pixelFormat = GL_RGB; + pixelType = GL_UNSIGNED_BYTE; + break; + case ECF_A8R8G8B8: + supported = true; + if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_IMG_texture_format_BGRA8888) || + queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_format_BGRA8888) || + queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_APPLE_texture_format_BGRA8888)) + { + pixelFormat = GL_BGRA; + } + else + { + pixelFormat = GL_RGBA; + *converter = CColorConverter::convert_A8R8G8B8toA8B8G8R8; + } + pixelType = GL_UNSIGNED_BYTE; + break; +#ifdef GL_EXT_texture_compression_s3tc + case ECF_DXT1: + supported = true; + pixelFormat = GL_RGBA; + pixelType = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; + break; + case ECF_DXT2: + case ECF_DXT3: + supported = true; + pixelFormat = GL_RGBA; + pixelType = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; + break; + case ECF_DXT4: + case ECF_DXT5: + supported = true; + pixelFormat = GL_RGBA; + pixelType = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; + break; +#endif +#ifdef GL_OES_compressed_ETC1_RGB8_texture + case ECF_ETC1: + supported = true; + pixelFormat = GL_RGB; + pixelType = GL_ETC1_RGB8_OES; + break; +#endif +#ifdef GL_ES_VERSION_3_0 // TO-DO - fix when extension name will be available + case ECF_ETC2_RGB: + supported = true; + pixelFormat = GL_RGB; + pixelType = GL_COMPRESSED_RGB8_ETC2; + break; +#endif +#ifdef GL_ES_VERSION_3_0 // TO-DO - fix when extension name will be available + case ECF_ETC2_ARGB: + supported = true; + pixelFormat = GL_RGBA; + pixelType = GL_COMPRESSED_RGBA8_ETC2_EAC; + break; +#endif + case ECF_D16: + supported = true; + pixelFormat = GL_DEPTH_COMPONENT; + pixelType = GL_UNSIGNED_SHORT; + break; + case ECF_D32: +#if defined(GL_OES_depth32) + if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_depth32)) + { + supported = true; + pixelFormat = GL_DEPTH_COMPONENT; + pixelType = GL_UNSIGNED_INT; + } +#endif + break; + case ECF_D24S8: +#ifdef GL_OES_packed_depth_stencil + if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_packed_depth_stencil)) + { + supported = true; + pixelFormat = GL_DEPTH_STENCIL_OES; + pixelType = GL_UNSIGNED_INT_24_8_OES; + } +#endif + break; + case ECF_R8: +#if defined(GL_EXT_texture_rg) + if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg)) + { + supported = true; + pixelFormat = GL_RED_EXT; + pixelType = GL_UNSIGNED_BYTE; + } +#endif + break; + case ECF_R8G8: +#if defined(GL_EXT_texture_rg) + if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg)) + { + supported = true; + pixelFormat = GL_RG_EXT; + pixelType = GL_UNSIGNED_BYTE; + } +#endif + break; + case ECF_R16: + break; + case ECF_R16G16: + break; + case ECF_R16F: +#if defined(GL_OES_texture_half_float) && defined(GL_EXT_texture_rg) + if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg) + && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float) + ) + { + supported = true; + pixelFormat = GL_RED_EXT; + pixelType = GL_HALF_FLOAT_OES ; + } +#endif + break; + case ECF_G16R16F: +#if defined(GL_OES_texture_half_float) && defined(GL_EXT_texture_rg) + if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg) + && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float) + ) + { + supported = true; + pixelFormat = GL_RG_EXT; + pixelType = GL_HALF_FLOAT_OES ; + } +#endif + break; + case ECF_A16B16G16R16F: +#if defined(GL_OES_texture_half_float) + if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float)) + { + supported = true; + pixelFormat = GL_RGBA; + pixelType = GL_HALF_FLOAT_OES ; + } +#endif + break; + case ECF_R32F: +#if defined(GL_OES_texture_float) && defined(GL_EXT_texture_rg) + if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg) + && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_float) + ) + { + supported = true; + pixelFormat = GL_RED_EXT; + pixelType = GL_FLOAT; + } +#endif + break; + case ECF_G32R32F: +#if defined(GL_OES_texture_float) && defined(GL_EXT_texture_rg) + if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_EXT_texture_rg) + && queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_float) + ) + { + supported = true; + pixelFormat = GL_RG_EXT; + pixelType = GL_FLOAT; + } +#endif + break; + case ECF_A32B32G32R32F: +#if defined(GL_OES_texture_float) + if (queryGLESFeature(COGLESCoreExtensionHandler::IRR_GL_OES_texture_half_float)) + { + supported = true; + pixelFormat = GL_RGBA; + pixelType = GL_FLOAT ; + } +#endif + break; + default: + break; + } + + // ES 2.0 says internalFormat must match pixelFormat (chapter 3.7.1 in Spec). + // Doesn't mention if "match" means "equal" or some other way of matching, but + // some bug on Emscripten and browsing discussions by others lead me to believe + // it means they have to be equal. Note that this was different in OpenGL. + internalFormat = pixelFormat; + +#ifdef _IRR_IOS_PLATFORM_ + if (internalFormat == GL_BGRA) + internalFormat = GL_RGBA; +#endif + + return supported; + } + + bool COpenGL3DriverBase::queryTextureFormat(ECOLOR_FORMAT format) const + { + GLint dummyInternalFormat; + GLenum dummyPixelFormat; + GLenum dummyPixelType; + void (*dummyConverter)(const void*, s32, void*); + return getColorFormatParameters(format, dummyInternalFormat, dummyPixelFormat, dummyPixelType, &dummyConverter); + } + + bool COpenGL3DriverBase::needsTransparentRenderPass(const irr::video::SMaterial& material) const + { + return CNullDriver::needsTransparentRenderPass(material) || material.isAlphaBlendOperation(); + } + + const SMaterial& COpenGL3DriverBase::getCurrentMaterial() const + { + return Material; + } + + COpenGL3CacheHandler* COpenGL3DriverBase::getCacheHandler() const + { + return CacheHandler; + } + +} // end namespace +} // end namespace diff --git a/source/Irrlicht/OpenGL/Driver.h b/source/Irrlicht/OpenGL/Driver.h index e95a633..06907b7 100644 --- a/source/Irrlicht/OpenGL/Driver.h +++ b/source/Irrlicht/OpenGL/Driver.h @@ -1,395 +1,395 @@ -// Copyright (C) 2023 Vitaliy Lobachevskiy -// Copyright (C) 2014 Patryk Nadrowski -// Copyright (C) 2009-2010 Amundis -// This file is part of the "Irrlicht Engine". -// For conditions of distribution and use, see copyright notice in Irrlicht.h - -#pragma once - -#include "SIrrCreationParameters.h" - -#include "Common.h" -#include "CNullDriver.h" -#include "IMaterialRendererServices.h" -#include "EDriverFeatures.h" -#include "fast_atof.h" -#include "ExtensionHandler.h" -#include "IContextManager.h" - -namespace irr -{ -namespace video -{ - struct VertexType; - - class COpenGL3FixedPipelineRenderer; - class COpenGL3Renderer2D; - - class COpenGL3DriverBase : public CNullDriver, public IMaterialRendererServices, public COpenGL3ExtensionHandler - { - friend class COpenGLCoreTexture; - - protected: - //! constructor (use createOpenGL3Driver instead) - COpenGL3DriverBase(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager); - - public: - - //! destructor - virtual ~COpenGL3DriverBase(); - - virtual bool beginScene(u16 clearFlag, SColor clearColor = SColor(255, 0, 0, 0), f32 clearDepth = 1.f, u8 clearStencil = 0, - const SExposedVideoData& videoData = SExposedVideoData(), core::rect* sourceRect = 0) override; - - bool endScene() override; - - //! sets transformation - void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat) override; - - struct SHWBufferLink_opengl : public SHWBufferLink - { - SHWBufferLink_opengl(const scene::IMeshBuffer *meshBuffer) - : SHWBufferLink(meshBuffer), vbo_verticesID(0), vbo_indicesID(0) - , vbo_verticesSize(0), vbo_indicesSize(0) - {} - - u32 vbo_verticesID; //tmp - u32 vbo_indicesID; //tmp - - u32 vbo_verticesSize; //tmp - u32 vbo_indicesSize; //tmp - }; - - bool updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); - bool updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); - - //! updates hardware buffer if needed - bool updateHardwareBuffer(SHWBufferLink *HWBuffer) override; - - //! Create hardware buffer from mesh - SHWBufferLink *createHardwareBuffer(const scene::IMeshBuffer* mb) override; - - //! Delete hardware buffer (only some drivers can) - void deleteHardwareBuffer(SHWBufferLink *HWBuffer) override; - - //! Draw hardware buffer - void drawHardwareBuffer(SHWBufferLink *HWBuffer) override; - - IRenderTarget* addRenderTarget() override; - - //! draws a vertex primitive list - virtual void drawVertexPrimitiveList(const void* vertices, u32 vertexCount, - const void* indexList, u32 primitiveCount, - E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) override; - - //! queries the features of the driver, returns true if feature is available - bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const override - { - return FeatureEnabled[feature] && COpenGL3ExtensionHandler::queryFeature(feature); - } - - //! Sets a material. - void setMaterial(const SMaterial& material) override; - - virtual void draw2DImage(const video::ITexture* texture, - const core::position2d& destPos, - const core::rect& sourceRect, const core::rect* clipRect = 0, - SColor color = SColor(255, 255, 255, 255), bool useAlphaChannelOfTexture = false) override; - - virtual void draw2DImage(const video::ITexture* texture, const core::rect& destRect, - const core::rect& sourceRect, const core::rect* clipRect = 0, - const video::SColor* const colors = 0, bool useAlphaChannelOfTexture = false) override; - - // internally used - virtual void draw2DImage(const video::ITexture* texture, u32 layer, bool flip); - - void draw2DImageBatch(const video::ITexture* texture, - const core::array >& positions, - const core::array >& sourceRects, - const core::rect* clipRect, - SColor color, - bool useAlphaChannelOfTexture) override; - - //! draw an 2d rectangle - virtual void draw2DRectangle(SColor color, const core::rect& pos, - const core::rect* clip = 0) override; - - //!Draws an 2d rectangle with a gradient. - virtual void draw2DRectangle(const core::rect& pos, - SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown, - const core::rect* clip = 0) override; - - //! Draws a 2d line. - virtual void draw2DLine(const core::position2d& start, - const core::position2d& end, - SColor color = SColor(255, 255, 255, 255)) override; - - //! Draws a single pixel - void drawPixel(u32 x, u32 y, const SColor & color) override; - - //! Draws a 3d line. - virtual void draw3DLine(const core::vector3df& start, - const core::vector3df& end, - SColor color = SColor(255, 255, 255, 255)) override; - - //! Draws a pixel -// virtual void drawPixel(u32 x, u32 y, const SColor & color); - - //! Returns the name of the video driver. - const wchar_t* getName() const override; - - //! Returns the maximum texture size supported. - core::dimension2du getMaxTextureSize() const override; - - //! sets a viewport - void setViewPort(const core::rect& area) override; - - //! Only used internally by the engine - void OnResize(const core::dimension2d& size) override; - - //! Returns type of video driver - E_DRIVER_TYPE getDriverType() const override; - - //! get color format of the current color buffer - ECOLOR_FORMAT getColorFormat() const override; - - //! Returns the transformation set by setTransform - const core::matrix4& getTransform(E_TRANSFORMATION_STATE state) const override; - - //! Can be called by an IMaterialRenderer to make its work easier. - void setBasicRenderStates(const SMaterial& material, const SMaterial& lastmaterial, bool resetAllRenderstates) override; - - //! Compare in SMaterial doesn't check texture parameters, so we should call this on each OnRender call. - void setTextureRenderStates(const SMaterial& material, bool resetAllRenderstates); - - //! Get a vertex shader constant index. - s32 getVertexShaderConstantID(const c8* name) override; - - //! Get a pixel shader constant index. - s32 getPixelShaderConstantID(const c8* name) override; - - //! Sets a vertex shader constant. - void setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount = 1) override; - - //! Sets a pixel shader constant. - void setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount = 1) override; - - //! Sets a constant for the vertex shader based on an index. - bool setVertexShaderConstant(s32 index, const f32* floats, int count) override; - - //! Int interface for the above. - bool setVertexShaderConstant(s32 index, const s32* ints, int count) override; - - //! Uint interface for the above. - bool setVertexShaderConstant(s32 index, const u32* ints, int count) override; - - //! Sets a constant for the pixel shader based on an index. - bool setPixelShaderConstant(s32 index, const f32* floats, int count) override; - - //! Int interface for the above. - bool setPixelShaderConstant(s32 index, const s32* ints, int count) override; - - //! Uint interface for the above. - bool setPixelShaderConstant(s32 index, const u32* ints, int count) override; - - //! Adds a new material renderer to the VideoDriver - virtual s32 addShaderMaterial(const c8* vertexShaderProgram, const c8* pixelShaderProgram, - IShaderConstantSetCallBack* callback, E_MATERIAL_TYPE baseMaterial, s32 userData) override; - - //! Adds a new material renderer to the VideoDriver - virtual s32 addHighLevelShaderMaterial( - const c8* vertexShaderProgram, - const c8* vertexShaderEntryPointName = 0, - E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1, - const c8* pixelShaderProgram = 0, - const c8* pixelShaderEntryPointName = 0, - E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1, - const c8* geometryShaderProgram = 0, - const c8* geometryShaderEntryPointName = "main", - E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, - scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, - scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, - u32 verticesOut = 0, - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, - s32 userData=0) override; - - //! Returns pointer to the IGPUProgrammingServices interface. - IGPUProgrammingServices* getGPUProgrammingServices() override; - - //! Returns a pointer to the IVideoDriver interface. - IVideoDriver* getVideoDriver() override; - - //! Returns the maximum amount of primitives - u32 getMaximalPrimitiveCount() const override; - - virtual ITexture* addRenderTargetTexture(const core::dimension2d& size, - const io::path& name, const ECOLOR_FORMAT format = ECF_UNKNOWN) override; - - //! Creates a render target texture for a cubemap - ITexture* addRenderTargetTextureCubemap(const irr::u32 sideLen, - const io::path& name, const ECOLOR_FORMAT format) override; - - virtual bool setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SColor clearColor = SColor(255, 0, 0, 0), - f32 clearDepth = 1.f, u8 clearStencil = 0) override; - - void clearBuffers(u16 flag, SColor color = SColor(255, 0, 0, 0), f32 depth = 1.f, u8 stencil = 0) override; - - //! Returns an image created from the last rendered frame. - IImage* createScreenShot(video::ECOLOR_FORMAT format=video::ECF_UNKNOWN, video::E_RENDER_TARGET target=video::ERT_FRAME_BUFFER) override; - - //! checks if an OpenGL error has happened and prints it (+ some internal code which is usually the line number) - bool testGLError(int code=0); - - //! checks if an OGLES1 error has happened and prints it - bool testEGLError(); - - //! Set/unset a clipping plane. - bool setClipPlane(u32 index, const core::plane3df& plane, bool enable = false) override; - - //! returns the current amount of user clip planes set. - u32 getClipPlaneCount() const; - - //! returns the 0 indexed Plane - const core::plane3df& getClipPlane(u32 index) const; - - //! Enable/disable a clipping plane. - void enableClipPlane(u32 index, bool enable) override; - - //! Returns the graphics card vendor name. - core::stringc getVendorInfo() override - { - return VendorName; - }; - - void removeTexture(ITexture* texture) override; - - //! Check if the driver supports creating textures with the given color format - bool queryTextureFormat(ECOLOR_FORMAT format) const override; - - //! Used by some SceneNodes to check if a material should be rendered in the transparent render pass - bool needsTransparentRenderPass(const irr::video::SMaterial& material) const override; - - //! Convert E_BLEND_FACTOR to OpenGL equivalent - GLenum getGLBlend(E_BLEND_FACTOR factor) const; - - virtual bool getColorFormatParameters(ECOLOR_FORMAT format, GLint& internalFormat, GLenum& pixelFormat, - GLenum& pixelType, void(**converter)(const void*, s32, void*)) const; - - //! Get current material. - const SMaterial& getCurrentMaterial() const; - - COpenGL3CacheHandler* getCacheHandler() const; - - protected: - //! inits the opengl-es driver - virtual bool genericDriverInit(const core::dimension2d& screenSize, bool stencilBuffer); - - void chooseMaterial2D(); - - ITexture* createDeviceDependentTexture(const io::path& name, IImage* image) override; - - ITexture* createDeviceDependentTextureCubemap(const io::path& name, const core::array& image) override; - - //! Map Irrlicht wrap mode to OpenGL enum - GLint getTextureWrapMode(u8 clamp) const; - - //! sets the needed renderstates - void setRenderStates3DMode(); - - //! sets the needed renderstates - void setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel); - - //! Prevent setRenderStateMode calls to do anything. - // hack to allow drawing meshbuffers in 2D mode. - // Better solution would be passing this flag through meshbuffers, - // but the way this is currently implemented in Irrlicht makes this tricky to implement - void lockRenderStateMode() - { - LockRenderStateMode = true; - } - - //! Allow setRenderStateMode calls to work again - void unlockRenderStateMode() - { - LockRenderStateMode = false; - } - - void draw2D3DVertexPrimitiveList(const void* vertices, - u32 vertexCount, const void* indexList, u32 primitiveCount, - E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, - E_INDEX_TYPE iType, bool is3D); - - void createMaterialRenderers(); - - void loadShaderData(const io::path& vertexShaderName, const io::path& fragmentShaderName, c8** vertexShaderData, c8** fragmentShaderData); - - bool setMaterialTexture(irr::u32 layerIdx, const irr::video::ITexture* texture); - - //! Same as `CacheHandler->setViewport`, but also sets `ViewPort` - virtual void setViewPortRaw(u32 width, u32 height); - - void drawQuad(const VertexType &vertexType, const S3DVertex (&vertices)[4]); - void drawArrays(GLenum primitiveType, const VertexType &vertexType, const void *vertices, int vertexCount); - void drawElements(GLenum primitiveType, const VertexType &vertexType, const void *vertices, const u16 *indices, int indexCount); - void drawElements(GLenum primitiveType, const VertexType &vertexType, uintptr_t vertices, uintptr_t indices, int indexCount); - - void beginDraw(const VertexType &vertexType, uintptr_t verticesBase); - void endDraw(const VertexType &vertexType); - - COpenGL3CacheHandler* CacheHandler; - core::stringw Name; - core::stringc VendorName; - SIrrlichtCreationParameters Params; - - //! bool to make all renderstates reset if set to true. - bool ResetRenderStates; - bool LockRenderStateMode; - u8 AntiAlias; - - struct SUserClipPlane - { - core::plane3df Plane; - bool Enabled; - }; - - core::array UserClipPlane; - - core::matrix4 TextureFlipMatrix; - -private: - - COpenGL3Renderer2D* MaterialRenderer2DActive; - COpenGL3Renderer2D* MaterialRenderer2DTexture; - COpenGL3Renderer2D* MaterialRenderer2DNoTexture; - - core::matrix4 Matrices[ETS_COUNT]; - - //! enumeration for rendering modes such as 2d and 3d for minimizing the switching of renderStates. - enum E_RENDER_MODE - { - ERM_NONE = 0, // no render state has been set yet. - ERM_2D, // 2d drawing rendermode - ERM_3D // 3d rendering mode - }; - - E_RENDER_MODE CurrentRenderMode; - bool Transformation3DChanged; - irr::io::path OGLES2ShaderPath; - - SMaterial Material, LastMaterial; - - //! Color buffer format - ECOLOR_FORMAT ColorFormat; - - IContextManager* ContextManager; - - std::vector QuadsIndices; - void initQuadsIndices(int max_vertex_count = 65536); - - void debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message); - static void APIENTRY debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam); - }; - -} // end namespace video -} // end namespace irr +// Copyright (C) 2023 Vitaliy Lobachevskiy +// Copyright (C) 2014 Patryk Nadrowski +// Copyright (C) 2009-2010 Amundis +// This file is part of the "Irrlicht Engine". +// For conditions of distribution and use, see copyright notice in Irrlicht.h + +#pragma once + +#include "SIrrCreationParameters.h" + +#include "Common.h" +#include "CNullDriver.h" +#include "IMaterialRendererServices.h" +#include "EDriverFeatures.h" +#include "fast_atof.h" +#include "ExtensionHandler.h" +#include "IContextManager.h" + +namespace irr +{ +namespace video +{ + struct VertexType; + + class COpenGL3FixedPipelineRenderer; + class COpenGL3Renderer2D; + + class COpenGL3DriverBase : public CNullDriver, public IMaterialRendererServices, public COpenGL3ExtensionHandler + { + friend class COpenGLCoreTexture; + + protected: + //! constructor (use createOpenGL3Driver instead) + COpenGL3DriverBase(const SIrrlichtCreationParameters& params, io::IFileSystem* io, IContextManager* contextManager); + + public: + + //! destructor + virtual ~COpenGL3DriverBase(); + + virtual bool beginScene(u16 clearFlag, SColor clearColor = SColor(255, 0, 0, 0), f32 clearDepth = 1.f, u8 clearStencil = 0, + const SExposedVideoData& videoData = SExposedVideoData(), core::rect* sourceRect = 0) override; + + bool endScene() override; + + //! sets transformation + void setTransform(E_TRANSFORMATION_STATE state, const core::matrix4& mat) override; + + struct SHWBufferLink_opengl : public SHWBufferLink + { + SHWBufferLink_opengl(const scene::IMeshBuffer *meshBuffer) + : SHWBufferLink(meshBuffer), vbo_verticesID(0), vbo_indicesID(0) + , vbo_verticesSize(0), vbo_indicesSize(0) + {} + + u32 vbo_verticesID; //tmp + u32 vbo_indicesID; //tmp + + u32 vbo_verticesSize; //tmp + u32 vbo_indicesSize; //tmp + }; + + bool updateVertexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); + bool updateIndexHardwareBuffer(SHWBufferLink_opengl *HWBuffer); + + //! updates hardware buffer if needed + bool updateHardwareBuffer(SHWBufferLink *HWBuffer) override; + + //! Create hardware buffer from mesh + SHWBufferLink *createHardwareBuffer(const scene::IMeshBuffer* mb) override; + + //! Delete hardware buffer (only some drivers can) + void deleteHardwareBuffer(SHWBufferLink *HWBuffer) override; + + //! Draw hardware buffer + void drawHardwareBuffer(SHWBufferLink *HWBuffer) override; + + IRenderTarget* addRenderTarget() override; + + //! draws a vertex primitive list + virtual void drawVertexPrimitiveList(const void* vertices, u32 vertexCount, + const void* indexList, u32 primitiveCount, + E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, E_INDEX_TYPE iType) override; + + //! queries the features of the driver, returns true if feature is available + bool queryFeature(E_VIDEO_DRIVER_FEATURE feature) const override + { + return FeatureEnabled[feature] && COpenGL3ExtensionHandler::queryFeature(feature); + } + + //! Sets a material. + void setMaterial(const SMaterial& material) override; + + virtual void draw2DImage(const video::ITexture* texture, + const core::position2d& destPos, + const core::rect& sourceRect, const core::rect* clipRect = 0, + SColor color = SColor(255, 255, 255, 255), bool useAlphaChannelOfTexture = false) override; + + virtual void draw2DImage(const video::ITexture* texture, const core::rect& destRect, + const core::rect& sourceRect, const core::rect* clipRect = 0, + const video::SColor* const colors = 0, bool useAlphaChannelOfTexture = false) override; + + // internally used + virtual void draw2DImage(const video::ITexture* texture, u32 layer, bool flip); + + void draw2DImageBatch(const video::ITexture* texture, + const core::array >& positions, + const core::array >& sourceRects, + const core::rect* clipRect, + SColor color, + bool useAlphaChannelOfTexture) override; + + //! draw an 2d rectangle + virtual void draw2DRectangle(SColor color, const core::rect& pos, + const core::rect* clip = 0) override; + + //!Draws an 2d rectangle with a gradient. + virtual void draw2DRectangle(const core::rect& pos, + SColor colorLeftUp, SColor colorRightUp, SColor colorLeftDown, SColor colorRightDown, + const core::rect* clip = 0) override; + + //! Draws a 2d line. + virtual void draw2DLine(const core::position2d& start, + const core::position2d& end, + SColor color = SColor(255, 255, 255, 255)) override; + + //! Draws a single pixel + void drawPixel(u32 x, u32 y, const SColor & color) override; + + //! Draws a 3d line. + virtual void draw3DLine(const core::vector3df& start, + const core::vector3df& end, + SColor color = SColor(255, 255, 255, 255)) override; + + //! Draws a pixel +// virtual void drawPixel(u32 x, u32 y, const SColor & color); + + //! Returns the name of the video driver. + const wchar_t* getName() const override; + + //! Returns the maximum texture size supported. + core::dimension2du getMaxTextureSize() const override; + + //! sets a viewport + void setViewPort(const core::rect& area) override; + + //! Only used internally by the engine + void OnResize(const core::dimension2d& size) override; + + //! Returns type of video driver + E_DRIVER_TYPE getDriverType() const override; + + //! get color format of the current color buffer + ECOLOR_FORMAT getColorFormat() const override; + + //! Returns the transformation set by setTransform + const core::matrix4& getTransform(E_TRANSFORMATION_STATE state) const override; + + //! Can be called by an IMaterialRenderer to make its work easier. + void setBasicRenderStates(const SMaterial& material, const SMaterial& lastmaterial, bool resetAllRenderstates) override; + + //! Compare in SMaterial doesn't check texture parameters, so we should call this on each OnRender call. + void setTextureRenderStates(const SMaterial& material, bool resetAllRenderstates); + + //! Get a vertex shader constant index. + s32 getVertexShaderConstantID(const c8* name) override; + + //! Get a pixel shader constant index. + s32 getPixelShaderConstantID(const c8* name) override; + + //! Sets a vertex shader constant. + void setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount = 1) override; + + //! Sets a pixel shader constant. + void setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount = 1) override; + + //! Sets a constant for the vertex shader based on an index. + bool setVertexShaderConstant(s32 index, const f32* floats, int count) override; + + //! Int interface for the above. + bool setVertexShaderConstant(s32 index, const s32* ints, int count) override; + + //! Uint interface for the above. + bool setVertexShaderConstant(s32 index, const u32* ints, int count) override; + + //! Sets a constant for the pixel shader based on an index. + bool setPixelShaderConstant(s32 index, const f32* floats, int count) override; + + //! Int interface for the above. + bool setPixelShaderConstant(s32 index, const s32* ints, int count) override; + + //! Uint interface for the above. + bool setPixelShaderConstant(s32 index, const u32* ints, int count) override; + + //! Adds a new material renderer to the VideoDriver + virtual s32 addShaderMaterial(const c8* vertexShaderProgram, const c8* pixelShaderProgram, + IShaderConstantSetCallBack* callback, E_MATERIAL_TYPE baseMaterial, s32 userData) override; + + //! Adds a new material renderer to the VideoDriver + virtual s32 addHighLevelShaderMaterial( + const c8* vertexShaderProgram, + const c8* vertexShaderEntryPointName = 0, + E_VERTEX_SHADER_TYPE vsCompileTarget = EVST_VS_1_1, + const c8* pixelShaderProgram = 0, + const c8* pixelShaderEntryPointName = 0, + E_PIXEL_SHADER_TYPE psCompileTarget = EPST_PS_1_1, + const c8* geometryShaderProgram = 0, + const c8* geometryShaderEntryPointName = "main", + E_GEOMETRY_SHADER_TYPE gsCompileTarget = EGST_GS_4_0, + scene::E_PRIMITIVE_TYPE inType = scene::EPT_TRIANGLES, + scene::E_PRIMITIVE_TYPE outType = scene::EPT_TRIANGLE_STRIP, + u32 verticesOut = 0, + IShaderConstantSetCallBack* callback = 0, + E_MATERIAL_TYPE baseMaterial = video::EMT_SOLID, + s32 userData=0) override; + + //! Returns pointer to the IGPUProgrammingServices interface. + IGPUProgrammingServices* getGPUProgrammingServices() override; + + //! Returns a pointer to the IVideoDriver interface. + IVideoDriver* getVideoDriver() override; + + //! Returns the maximum amount of primitives + u32 getMaximalPrimitiveCount() const override; + + virtual ITexture* addRenderTargetTexture(const core::dimension2d& size, + const io::path& name, const ECOLOR_FORMAT format = ECF_UNKNOWN) override; + + //! Creates a render target texture for a cubemap + ITexture* addRenderTargetTextureCubemap(const irr::u32 sideLen, + const io::path& name, const ECOLOR_FORMAT format) override; + + virtual bool setRenderTargetEx(IRenderTarget* target, u16 clearFlag, SColor clearColor = SColor(255, 0, 0, 0), + f32 clearDepth = 1.f, u8 clearStencil = 0) override; + + void clearBuffers(u16 flag, SColor color = SColor(255, 0, 0, 0), f32 depth = 1.f, u8 stencil = 0) override; + + //! Returns an image created from the last rendered frame. + IImage* createScreenShot(video::ECOLOR_FORMAT format=video::ECF_UNKNOWN, video::E_RENDER_TARGET target=video::ERT_FRAME_BUFFER) override; + + //! checks if an OpenGL error has happened and prints it (+ some internal code which is usually the line number) + bool testGLError(int code=0); + + //! checks if an OGLES1 error has happened and prints it + bool testEGLError(); + + //! Set/unset a clipping plane. + bool setClipPlane(u32 index, const core::plane3df& plane, bool enable = false) override; + + //! returns the current amount of user clip planes set. + u32 getClipPlaneCount() const; + + //! returns the 0 indexed Plane + const core::plane3df& getClipPlane(u32 index) const; + + //! Enable/disable a clipping plane. + void enableClipPlane(u32 index, bool enable) override; + + //! Returns the graphics card vendor name. + core::stringc getVendorInfo() override + { + return VendorName; + }; + + void removeTexture(ITexture* texture) override; + + //! Check if the driver supports creating textures with the given color format + bool queryTextureFormat(ECOLOR_FORMAT format) const override; + + //! Used by some SceneNodes to check if a material should be rendered in the transparent render pass + bool needsTransparentRenderPass(const irr::video::SMaterial& material) const override; + + //! Convert E_BLEND_FACTOR to OpenGL equivalent + GLenum getGLBlend(E_BLEND_FACTOR factor) const; + + virtual bool getColorFormatParameters(ECOLOR_FORMAT format, GLint& internalFormat, GLenum& pixelFormat, + GLenum& pixelType, void(**converter)(const void*, s32, void*)) const; + + //! Get current material. + const SMaterial& getCurrentMaterial() const; + + COpenGL3CacheHandler* getCacheHandler() const; + + protected: + //! inits the opengl-es driver + virtual bool genericDriverInit(const core::dimension2d& screenSize, bool stencilBuffer); + + void chooseMaterial2D(); + + ITexture* createDeviceDependentTexture(const io::path& name, IImage* image) override; + + ITexture* createDeviceDependentTextureCubemap(const io::path& name, const core::array& image) override; + + //! Map Irrlicht wrap mode to OpenGL enum + GLint getTextureWrapMode(u8 clamp) const; + + //! sets the needed renderstates + void setRenderStates3DMode(); + + //! sets the needed renderstates + void setRenderStates2DMode(bool alpha, bool texture, bool alphaChannel); + + //! Prevent setRenderStateMode calls to do anything. + // hack to allow drawing meshbuffers in 2D mode. + // Better solution would be passing this flag through meshbuffers, + // but the way this is currently implemented in Irrlicht makes this tricky to implement + void lockRenderStateMode() + { + LockRenderStateMode = true; + } + + //! Allow setRenderStateMode calls to work again + void unlockRenderStateMode() + { + LockRenderStateMode = false; + } + + void draw2D3DVertexPrimitiveList(const void* vertices, + u32 vertexCount, const void* indexList, u32 primitiveCount, + E_VERTEX_TYPE vType, scene::E_PRIMITIVE_TYPE pType, + E_INDEX_TYPE iType, bool is3D); + + void createMaterialRenderers(); + + void loadShaderData(const io::path& vertexShaderName, const io::path& fragmentShaderName, c8** vertexShaderData, c8** fragmentShaderData); + + bool setMaterialTexture(irr::u32 layerIdx, const irr::video::ITexture* texture); + + //! Same as `CacheHandler->setViewport`, but also sets `ViewPort` + virtual void setViewPortRaw(u32 width, u32 height); + + void drawQuad(const VertexType &vertexType, const S3DVertex (&vertices)[4]); + void drawArrays(GLenum primitiveType, const VertexType &vertexType, const void *vertices, int vertexCount); + void drawElements(GLenum primitiveType, const VertexType &vertexType, const void *vertices, const u16 *indices, int indexCount); + void drawElements(GLenum primitiveType, const VertexType &vertexType, uintptr_t vertices, uintptr_t indices, int indexCount); + + void beginDraw(const VertexType &vertexType, uintptr_t verticesBase); + void endDraw(const VertexType &vertexType); + + COpenGL3CacheHandler* CacheHandler; + core::stringw Name; + core::stringc VendorName; + SIrrlichtCreationParameters Params; + + //! bool to make all renderstates reset if set to true. + bool ResetRenderStates; + bool LockRenderStateMode; + u8 AntiAlias; + + struct SUserClipPlane + { + core::plane3df Plane; + bool Enabled; + }; + + core::array UserClipPlane; + + core::matrix4 TextureFlipMatrix; + +private: + + COpenGL3Renderer2D* MaterialRenderer2DActive; + COpenGL3Renderer2D* MaterialRenderer2DTexture; + COpenGL3Renderer2D* MaterialRenderer2DNoTexture; + + core::matrix4 Matrices[ETS_COUNT]; + + //! enumeration for rendering modes such as 2d and 3d for minimizing the switching of renderStates. + enum E_RENDER_MODE + { + ERM_NONE = 0, // no render state has been set yet. + ERM_2D, // 2d drawing rendermode + ERM_3D // 3d rendering mode + }; + + E_RENDER_MODE CurrentRenderMode; + bool Transformation3DChanged; + irr::io::path OGLES2ShaderPath; + + SMaterial Material, LastMaterial; + + //! Color buffer format + ECOLOR_FORMAT ColorFormat; + + IContextManager* ContextManager; + + std::vector QuadsIndices; + void initQuadsIndices(int max_vertex_count = 65536); + + void debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message); + static void APIENTRY debugCb(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam); + }; + +} // end namespace video +} // end namespace irr diff --git a/source/Irrlicht/OpenGL/ExtensionHandler.cpp b/source/Irrlicht/OpenGL/ExtensionHandler.cpp index 055738b..b9cb75a 100644 --- a/source/Irrlicht/OpenGL/ExtensionHandler.cpp +++ b/source/Irrlicht/OpenGL/ExtensionHandler.cpp @@ -1,66 +1,66 @@ -// Copyright (C) 2015 Patryk Nadrowski -// Copyright (C) 2009-2010 Amundis -// 2017 modified by Michael Zeilfelder (unifying extension handlers) -// This file is part of the "Irrlicht Engine". -// For conditions of distribution and use, see copyright notice in Irrlicht.h - -#include "ExtensionHandler.h" - -#include "irrString.h" -#include "SMaterial.h" -#include "fast_atof.h" -#include - -namespace irr -{ -namespace video -{ - void COpenGL3ExtensionHandler::initExtensions() - { - GLint major, minor; - glGetIntegerv(GL_MAJOR_VERSION, &major); - glGetIntegerv(GL_MINOR_VERSION, &minor); - Version = 100 * major + 10 * minor; - - GLint ext_count = 0; - GL.GetIntegerv(GL_NUM_EXTENSIONS, &ext_count); - for (int k = 0; k < ext_count; k++) { - auto ext_name = (char *)GL.GetStringi(GL_EXTENSIONS, k); - for (size_t j=0; j(val); - - #ifdef GL_EXT_texture_filter_anisotropic - if (FeatureAvailable[IRR_GL_EXT_texture_filter_anisotropic]) - { - glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &val); - MaxAnisotropy = static_cast(val); - } - #endif - #ifdef GL_MAX_ELEMENTS_INDICES - glGetIntegerv(GL_MAX_ELEMENTS_INDICES, &val); - MaxIndices=val; - #endif - glGetIntegerv(GL_MAX_TEXTURE_SIZE, &val); - MaxTextureSize=static_cast(val); - #ifdef GL_EXT_texture_lod_bias - if (FeatureAvailable[IRR_GL_EXT_texture_lod_bias]) - glGetFloatv(GL_MAX_TEXTURE_LOD_BIAS_EXT, &MaxTextureLODBias); - #endif - glGetFloatv(GL_ALIASED_LINE_WIDTH_RANGE, DimAliasedLine); - glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, DimAliasedPoint); - - Feature.MaxTextureUnits = core::min_(Feature.MaxTextureUnits, static_cast(MATERIAL_MAX_TEXTURES)); - Feature.ColorAttachment = 1; - } - -} // end namespace video -} // end namespace irr +// Copyright (C) 2015 Patryk Nadrowski +// Copyright (C) 2009-2010 Amundis +// 2017 modified by Michael Zeilfelder (unifying extension handlers) +// This file is part of the "Irrlicht Engine". +// For conditions of distribution and use, see copyright notice in Irrlicht.h + +#include "ExtensionHandler.h" + +#include "irrString.h" +#include "SMaterial.h" +#include "fast_atof.h" +#include + +namespace irr +{ +namespace video +{ + void COpenGL3ExtensionHandler::initExtensions() + { + GLint major, minor; + glGetIntegerv(GL_MAJOR_VERSION, &major); + glGetIntegerv(GL_MINOR_VERSION, &minor); + Version = 100 * major + 10 * minor; + + GLint ext_count = 0; + GL.GetIntegerv(GL_NUM_EXTENSIONS, &ext_count); + for (int k = 0; k < ext_count; k++) { + auto ext_name = (char *)GL.GetStringi(GL_EXTENSIONS, k); + for (size_t j=0; j(val); + + #ifdef GL_EXT_texture_filter_anisotropic + if (FeatureAvailable[IRR_GL_EXT_texture_filter_anisotropic]) + { + glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &val); + MaxAnisotropy = static_cast(val); + } + #endif + #ifdef GL_MAX_ELEMENTS_INDICES + glGetIntegerv(GL_MAX_ELEMENTS_INDICES, &val); + MaxIndices=val; + #endif + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &val); + MaxTextureSize=static_cast(val); + #ifdef GL_EXT_texture_lod_bias + if (FeatureAvailable[IRR_GL_EXT_texture_lod_bias]) + glGetFloatv(GL_MAX_TEXTURE_LOD_BIAS_EXT, &MaxTextureLODBias); + #endif + glGetFloatv(GL_ALIASED_LINE_WIDTH_RANGE, DimAliasedLine); + glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, DimAliasedPoint); + + Feature.MaxTextureUnits = core::min_(Feature.MaxTextureUnits, static_cast(MATERIAL_MAX_TEXTURES)); + Feature.ColorAttachment = 1; + } + +} // end namespace video +} // end namespace irr diff --git a/source/Irrlicht/OpenGL/ExtensionHandler.h b/source/Irrlicht/OpenGL/ExtensionHandler.h index 1e6bd7f..6fb47b8 100644 --- a/source/Irrlicht/OpenGL/ExtensionHandler.h +++ b/source/Irrlicht/OpenGL/ExtensionHandler.h @@ -1,187 +1,187 @@ -// Copyright (C) 2023 Vitaliy Lobachevskiy -// Copyright (C) 2015 Patryk Nadrowski -// Copyright (C) 2009-2010 Amundis -// This file is part of the "Irrlicht Engine". -// For conditions of distribution and use, see copyright notice in Irrlicht.h - -#pragma once - -#include "EDriverFeatures.h" -#include "irrTypes.h" -#include "os.h" - -#include "Common.h" - -#include "COGLESCoreExtensionHandler.h" - -namespace irr -{ -namespace video -{ - - class COpenGL3ExtensionHandler : public COGLESCoreExtensionHandler - { - public: - COpenGL3ExtensionHandler() : COGLESCoreExtensionHandler() {} - - void initExtensions(); - - bool queryFeature(video::E_VIDEO_DRIVER_FEATURE feature) const - { - switch (feature) - { - case EVDF_RENDER_TO_TARGET: - case EVDF_HARDWARE_TL: - case EVDF_MULTITEXTURE: - case EVDF_BILINEAR_FILTER: - case EVDF_MIP_MAP: - case EVDF_MIP_MAP_AUTO_UPDATE: - case EVDF_VERTEX_SHADER_1_1: - case EVDF_PIXEL_SHADER_1_1: - case EVDF_PIXEL_SHADER_1_2: - case EVDF_PIXEL_SHADER_2_0: - case EVDF_VERTEX_SHADER_2_0: - case EVDF_ARB_GLSL: - case EVDF_TEXTURE_NSQUARE: - case EVDF_TEXTURE_NPOT: - case EVDF_FRAMEBUFFER_OBJECT: - case EVDF_VERTEX_BUFFER_OBJECT: - case EVDF_COLOR_MASK: - case EVDF_ALPHA_TO_COVERAGE: - case EVDF_POLYGON_OFFSET: - case EVDF_BLEND_OPERATIONS: - case EVDF_BLEND_SEPARATE: - case EVDF_TEXTURE_MATRIX: - case EVDF_TEXTURE_CUBEMAP: - return true; - case EVDF_ARB_VERTEX_PROGRAM_1: - case EVDF_ARB_FRAGMENT_PROGRAM_1: - case EVDF_GEOMETRY_SHADER: - case EVDF_MULTIPLE_RENDER_TARGETS: - case EVDF_MRT_BLEND: - case EVDF_MRT_COLOR_MASK: - case EVDF_MRT_BLEND_FUNC: - case EVDF_OCCLUSION_QUERY: - return false; - case EVDF_TEXTURE_COMPRESSED_DXT: - return false; // NV Tegra need improvements here - case EVDF_TEXTURE_COMPRESSED_PVRTC: - return FeatureAvailable[IRR_GL_IMG_texture_compression_pvrtc]; - case EVDF_TEXTURE_COMPRESSED_PVRTC2: - return FeatureAvailable[IRR_GL_IMG_texture_compression_pvrtc2]; - case EVDF_TEXTURE_COMPRESSED_ETC1: - return FeatureAvailable[IRR_GL_OES_compressed_ETC1_RGB8_texture]; - case EVDF_TEXTURE_COMPRESSED_ETC2: - return false; - case EVDF_STENCIL_BUFFER: - return StencilBuffer; - default: - return false; - }; - } - - inline void irrGlActiveTexture(GLenum texture) - { - glActiveTexture(texture); - } - - inline void irrGlCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, - GLsizei imageSize, const void* data) - { - glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); - } - - inline void irrGlCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, - GLenum format, GLsizei imageSize, const void* data) - { - glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); - } - - inline void irrGlUseProgram(GLuint prog) - { - glUseProgram(prog); - } - - inline void irrGlBindFramebuffer(GLenum target, GLuint framebuffer) - { - glBindFramebuffer(target, framebuffer); - } - - inline void irrGlDeleteFramebuffers(GLsizei n, const GLuint *framebuffers) - { - glDeleteFramebuffers(n, framebuffers); - } - - inline void irrGlGenFramebuffers(GLsizei n, GLuint *framebuffers) - { - glGenFramebuffers(n, framebuffers); - } - - inline GLenum irrGlCheckFramebufferStatus(GLenum target) - { - return glCheckFramebufferStatus(target); - } - - inline void irrGlFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) - { - glFramebufferTexture2D(target, attachment, textarget, texture, level); - } - - inline void irrGlGenerateMipmap(GLenum target) - { - glGenerateMipmap(target); - } - - inline void irrGlActiveStencilFace(GLenum face) - { - } - - inline void irrGlDrawBuffer(GLenum mode) - { - } - - inline void irrGlDrawBuffers(GLsizei n, const GLenum *bufs) - { - } - - inline void irrGlBlendFuncSeparate(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha) - { - glBlendFuncSeparate(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha); - } - - inline void irrGlBlendEquation(GLenum mode) - { - glBlendEquation(mode); - } - - inline void irrGlEnableIndexed(GLenum target, GLuint index) - { - } - - inline void irrGlDisableIndexed(GLenum target, GLuint index) - { - } - - inline void irrGlColorMaskIndexed(GLuint buf, GLboolean r, GLboolean g, GLboolean b, GLboolean a) - { - } - - inline void irrGlBlendFuncIndexed(GLuint buf, GLenum src, GLenum dst) - { - } - - inline void irrGlBlendFuncSeparateIndexed(GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha) - { - } - - inline void irrGlBlendEquationIndexed(GLuint buf, GLenum mode) - { - } - - inline void irrGlBlendEquationSeparateIndexed(GLuint buf, GLenum modeRGB, GLenum modeAlpha) - { - } - }; - -} -} +// Copyright (C) 2023 Vitaliy Lobachevskiy +// Copyright (C) 2015 Patryk Nadrowski +// Copyright (C) 2009-2010 Amundis +// This file is part of the "Irrlicht Engine". +// For conditions of distribution and use, see copyright notice in Irrlicht.h + +#pragma once + +#include "EDriverFeatures.h" +#include "irrTypes.h" +#include "os.h" + +#include "Common.h" + +#include "COGLESCoreExtensionHandler.h" + +namespace irr +{ +namespace video +{ + + class COpenGL3ExtensionHandler : public COGLESCoreExtensionHandler + { + public: + COpenGL3ExtensionHandler() : COGLESCoreExtensionHandler() {} + + void initExtensions(); + + bool queryFeature(video::E_VIDEO_DRIVER_FEATURE feature) const + { + switch (feature) + { + case EVDF_RENDER_TO_TARGET: + case EVDF_HARDWARE_TL: + case EVDF_MULTITEXTURE: + case EVDF_BILINEAR_FILTER: + case EVDF_MIP_MAP: + case EVDF_MIP_MAP_AUTO_UPDATE: + case EVDF_VERTEX_SHADER_1_1: + case EVDF_PIXEL_SHADER_1_1: + case EVDF_PIXEL_SHADER_1_2: + case EVDF_PIXEL_SHADER_2_0: + case EVDF_VERTEX_SHADER_2_0: + case EVDF_ARB_GLSL: + case EVDF_TEXTURE_NSQUARE: + case EVDF_TEXTURE_NPOT: + case EVDF_FRAMEBUFFER_OBJECT: + case EVDF_VERTEX_BUFFER_OBJECT: + case EVDF_COLOR_MASK: + case EVDF_ALPHA_TO_COVERAGE: + case EVDF_POLYGON_OFFSET: + case EVDF_BLEND_OPERATIONS: + case EVDF_BLEND_SEPARATE: + case EVDF_TEXTURE_MATRIX: + case EVDF_TEXTURE_CUBEMAP: + return true; + case EVDF_ARB_VERTEX_PROGRAM_1: + case EVDF_ARB_FRAGMENT_PROGRAM_1: + case EVDF_GEOMETRY_SHADER: + case EVDF_MULTIPLE_RENDER_TARGETS: + case EVDF_MRT_BLEND: + case EVDF_MRT_COLOR_MASK: + case EVDF_MRT_BLEND_FUNC: + case EVDF_OCCLUSION_QUERY: + return false; + case EVDF_TEXTURE_COMPRESSED_DXT: + return false; // NV Tegra need improvements here + case EVDF_TEXTURE_COMPRESSED_PVRTC: + return FeatureAvailable[IRR_GL_IMG_texture_compression_pvrtc]; + case EVDF_TEXTURE_COMPRESSED_PVRTC2: + return FeatureAvailable[IRR_GL_IMG_texture_compression_pvrtc2]; + case EVDF_TEXTURE_COMPRESSED_ETC1: + return FeatureAvailable[IRR_GL_OES_compressed_ETC1_RGB8_texture]; + case EVDF_TEXTURE_COMPRESSED_ETC2: + return false; + case EVDF_STENCIL_BUFFER: + return StencilBuffer; + default: + return false; + }; + } + + inline void irrGlActiveTexture(GLenum texture) + { + glActiveTexture(texture); + } + + inline void irrGlCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, + GLsizei imageSize, const void* data) + { + glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); + } + + inline void irrGlCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, + GLenum format, GLsizei imageSize, const void* data) + { + glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); + } + + inline void irrGlUseProgram(GLuint prog) + { + glUseProgram(prog); + } + + inline void irrGlBindFramebuffer(GLenum target, GLuint framebuffer) + { + glBindFramebuffer(target, framebuffer); + } + + inline void irrGlDeleteFramebuffers(GLsizei n, const GLuint *framebuffers) + { + glDeleteFramebuffers(n, framebuffers); + } + + inline void irrGlGenFramebuffers(GLsizei n, GLuint *framebuffers) + { + glGenFramebuffers(n, framebuffers); + } + + inline GLenum irrGlCheckFramebufferStatus(GLenum target) + { + return glCheckFramebufferStatus(target); + } + + inline void irrGlFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) + { + glFramebufferTexture2D(target, attachment, textarget, texture, level); + } + + inline void irrGlGenerateMipmap(GLenum target) + { + glGenerateMipmap(target); + } + + inline void irrGlActiveStencilFace(GLenum face) + { + } + + inline void irrGlDrawBuffer(GLenum mode) + { + } + + inline void irrGlDrawBuffers(GLsizei n, const GLenum *bufs) + { + } + + inline void irrGlBlendFuncSeparate(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha) + { + glBlendFuncSeparate(sfactorRGB, dfactorRGB, sfactorAlpha, dfactorAlpha); + } + + inline void irrGlBlendEquation(GLenum mode) + { + glBlendEquation(mode); + } + + inline void irrGlEnableIndexed(GLenum target, GLuint index) + { + } + + inline void irrGlDisableIndexed(GLenum target, GLuint index) + { + } + + inline void irrGlColorMaskIndexed(GLuint buf, GLboolean r, GLboolean g, GLboolean b, GLboolean a) + { + } + + inline void irrGlBlendFuncIndexed(GLuint buf, GLenum src, GLenum dst) + { + } + + inline void irrGlBlendFuncSeparateIndexed(GLuint buf, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha) + { + } + + inline void irrGlBlendEquationIndexed(GLuint buf, GLenum mode) + { + } + + inline void irrGlBlendEquationSeparateIndexed(GLuint buf, GLenum modeRGB, GLenum modeAlpha) + { + } + }; + +} +} diff --git a/source/Irrlicht/OpenGL/FixedPipelineRenderer.cpp b/source/Irrlicht/OpenGL/FixedPipelineRenderer.cpp index bcf99ac..2922470 100644 --- a/source/Irrlicht/OpenGL/FixedPipelineRenderer.cpp +++ b/source/Irrlicht/OpenGL/FixedPipelineRenderer.cpp @@ -1,334 +1,334 @@ -// Copyright (C) 2014 Patryk Nadrowski -// This file is part of the "Irrlicht Engine". -// For conditions of distribution and use, see copyright notice in Irrlicht.h - -#include "FixedPipelineRenderer.h" - -#include "IVideoDriver.h" - -namespace irr -{ -namespace video -{ - -// Base callback - -COpenGL3MaterialBaseCB::COpenGL3MaterialBaseCB() : - FirstUpdateBase(true), WVPMatrixID(-1), WVMatrixID(-1), NMatrixID(-1), GlobalAmbientID(-1), MaterialAmbientID(-1), MaterialDiffuseID(-1), MaterialEmissiveID(-1), MaterialSpecularID(-1), MaterialShininessID(-1), - FogEnableID(-1), FogTypeID(-1), FogColorID(-1), FogStartID(-1), - FogEndID(-1), FogDensityID(-1), ThicknessID(-1), LightEnable(false), MaterialAmbient(SColorf(0.f, 0.f, 0.f)), MaterialDiffuse(SColorf(0.f, 0.f, 0.f)), MaterialEmissive(SColorf(0.f, 0.f, 0.f)), MaterialSpecular(SColorf(0.f, 0.f, 0.f)), - MaterialShininess(0.f), FogEnable(0), FogType(1), FogColor(SColorf(0.f, 0.f, 0.f, 1.f)), FogStart(0.f), FogEnd(0.f), FogDensity(0.f), Thickness(1.f) -{ -} - -void COpenGL3MaterialBaseCB::OnSetMaterial(const SMaterial& material) -{ - LightEnable = material.Lighting; - MaterialAmbient = SColorf(material.AmbientColor); - MaterialDiffuse = SColorf(material.DiffuseColor); - MaterialEmissive = SColorf(material.EmissiveColor); - MaterialSpecular = SColorf(material.SpecularColor); - MaterialShininess = material.Shininess; - - FogEnable = material.FogEnable ? 1 : 0; - - Thickness = (material.Thickness > 0.f) ? material.Thickness : 1.f; -} - -void COpenGL3MaterialBaseCB::OnSetConstants(IMaterialRendererServices* services, s32 userData) -{ - IVideoDriver* driver = services->getVideoDriver(); - - if (FirstUpdateBase) - { - WVPMatrixID = services->getVertexShaderConstantID("uWVPMatrix"); - WVMatrixID = services->getVertexShaderConstantID("uWVMatrix"); - NMatrixID = services->getVertexShaderConstantID("uNMatrix"); - GlobalAmbientID = services->getVertexShaderConstantID("uGlobalAmbient"); - MaterialAmbientID = services->getVertexShaderConstantID("uMaterialAmbient"); - MaterialDiffuseID = services->getVertexShaderConstantID("uMaterialDiffuse"); - MaterialEmissiveID = services->getVertexShaderConstantID("uMaterialEmissive"); - MaterialSpecularID = services->getVertexShaderConstantID("uMaterialSpecular"); - MaterialShininessID = services->getVertexShaderConstantID("uMaterialShininess"); - FogEnableID = services->getVertexShaderConstantID("uFogEnable"); - FogTypeID = services->getVertexShaderConstantID("uFogType"); - FogColorID = services->getVertexShaderConstantID("uFogColor"); - FogStartID = services->getVertexShaderConstantID("uFogStart"); - FogEndID = services->getVertexShaderConstantID("uFogEnd"); - FogDensityID = services->getVertexShaderConstantID("uFogDensity"); - ThicknessID = services->getVertexShaderConstantID("uThickness"); - - FirstUpdateBase = false; - } - - const core::matrix4 W = driver->getTransform(ETS_WORLD); - const core::matrix4 V = driver->getTransform(ETS_VIEW); - const core::matrix4 P = driver->getTransform(ETS_PROJECTION); - - core::matrix4 Matrix = P * V * W; - services->setPixelShaderConstant(WVPMatrixID, Matrix.pointer(), 16); - - Matrix = V * W; - services->setPixelShaderConstant(WVMatrixID, Matrix.pointer(), 16); - - Matrix.makeInverse(); - services->setPixelShaderConstant(NMatrixID, Matrix.getTransposed().pointer(), 16); - - services->setPixelShaderConstant(FogEnableID, &FogEnable, 1); - - if (FogEnable) - { - SColor TempColor(0); - E_FOG_TYPE TempType = EFT_FOG_LINEAR; - bool TempPerFragment = false; - bool TempRange = false; - - driver->getFog(TempColor, TempType, FogStart, FogEnd, FogDensity, TempPerFragment, TempRange); - - FogType = (s32)TempType; - FogColor = SColorf(TempColor); - - services->setPixelShaderConstant(FogTypeID, &FogType, 1); - services->setPixelShaderConstant(FogColorID, reinterpret_cast(&FogColor), 4); - services->setPixelShaderConstant(FogStartID, &FogStart, 1); - services->setPixelShaderConstant(FogEndID, &FogEnd, 1); - services->setPixelShaderConstant(FogDensityID, &FogDensity, 1); - } - - services->setPixelShaderConstant(ThicknessID, &Thickness, 1); -} - -// EMT_SOLID + EMT_TRANSPARENT_ADD_COLOR + EMT_TRANSPARENT_ALPHA_CHANNEL + EMT_TRANSPARENT_VERTEX_ALPHA - -COpenGL3MaterialSolidCB::COpenGL3MaterialSolidCB() : - FirstUpdate(true), TMatrix0ID(-1), AlphaRefID(-1), TextureUsage0ID(-1), TextureUnit0ID(-1), AlphaRef(0.5f), TextureUsage0(0), TextureUnit0(0) -{ -} - -void COpenGL3MaterialSolidCB::OnSetMaterial(const SMaterial& material) -{ - COpenGL3MaterialBaseCB::OnSetMaterial(material); - - AlphaRef = material.MaterialTypeParam; - TextureUsage0 = (material.TextureLayer[0].Texture) ? 1 : 0; -} - -void COpenGL3MaterialSolidCB::OnSetConstants(IMaterialRendererServices* services, s32 userData) -{ - COpenGL3MaterialBaseCB::OnSetConstants(services, userData); - - IVideoDriver* driver = services->getVideoDriver(); - - if (FirstUpdate) - { - TMatrix0ID = services->getVertexShaderConstantID("uTMatrix0"); - AlphaRefID = services->getVertexShaderConstantID("uAlphaRef"); - TextureUsage0ID = services->getVertexShaderConstantID("uTextureUsage0"); - TextureUnit0ID = services->getVertexShaderConstantID("uTextureUnit0"); - - FirstUpdate = false; - } - - core::matrix4 Matrix = driver->getTransform(ETS_TEXTURE_0); - services->setPixelShaderConstant(TMatrix0ID, Matrix.pointer(), 16); - - services->setPixelShaderConstant(AlphaRefID, &AlphaRef, 1); - services->setPixelShaderConstant(TextureUsage0ID, &TextureUsage0, 1); - services->setPixelShaderConstant(TextureUnit0ID, &TextureUnit0, 1); -} - -// EMT_SOLID_2_LAYER + EMT_DETAIL_MAP - -COpenGL3MaterialSolid2CB::COpenGL3MaterialSolid2CB() : - FirstUpdate(true), TMatrix0ID(-1), TMatrix1ID(-1), TextureUsage0ID(-1), TextureUsage1ID(-1), TextureUnit0ID(-1), TextureUnit1ID(-1), - TextureUsage0(0), TextureUsage1(0), TextureUnit0(0), TextureUnit1(1) -{ -} - -void COpenGL3MaterialSolid2CB::OnSetMaterial(const SMaterial& material) -{ - COpenGL3MaterialBaseCB::OnSetMaterial(material); - - TextureUsage0 = (material.TextureLayer[0].Texture) ? 1 : 0; - TextureUsage1 = (material.TextureLayer[1].Texture) ? 1 : 0; -} - -void COpenGL3MaterialSolid2CB::OnSetConstants(IMaterialRendererServices* services, s32 userData) -{ - COpenGL3MaterialBaseCB::OnSetConstants(services, userData); - - IVideoDriver* driver = services->getVideoDriver(); - - if (FirstUpdate) - { - TMatrix0ID = services->getVertexShaderConstantID("uTMatrix0"); - TMatrix1ID = services->getVertexShaderConstantID("uTMatrix1"); - TextureUsage0ID = services->getVertexShaderConstantID("uTextureUsage0"); - TextureUsage1ID = services->getVertexShaderConstantID("uTextureUsage1"); - TextureUnit0ID = services->getVertexShaderConstantID("uTextureUnit0"); - TextureUnit1ID = services->getVertexShaderConstantID("uTextureUnit1"); - - FirstUpdate = false; - } - - core::matrix4 Matrix = driver->getTransform(ETS_TEXTURE_0); - services->setPixelShaderConstant(TMatrix0ID, Matrix.pointer(), 16); - - Matrix = driver->getTransform(E_TRANSFORMATION_STATE(ETS_TEXTURE_0 + 1)); - services->setPixelShaderConstant(TMatrix1ID, Matrix.pointer(), 16); - - services->setPixelShaderConstant(TextureUsage0ID, &TextureUsage0, 1); - services->setPixelShaderConstant(TextureUsage1ID, &TextureUsage1, 1); - services->setPixelShaderConstant(TextureUnit0ID, &TextureUnit0, 1); - services->setPixelShaderConstant(TextureUnit1ID, &TextureUnit1, 1); -} - -// EMT_LIGHTMAP + EMT_LIGHTMAP_ADD + EMT_LIGHTMAP_M2 + EMT_LIGHTMAP_M4 - -COpenGL3MaterialLightmapCB::COpenGL3MaterialLightmapCB(float modulate) : - FirstUpdate(true), TMatrix0ID(-1), TMatrix1ID(-1), ModulateID(-1), TextureUsage0ID(-1), TextureUsage1ID(-1), TextureUnit0ID(-1), TextureUnit1ID(-1), - Modulate(modulate), TextureUsage0(0), TextureUsage1(0), TextureUnit0(0), TextureUnit1(1) -{ -} - -void COpenGL3MaterialLightmapCB::OnSetMaterial(const SMaterial& material) -{ - COpenGL3MaterialBaseCB::OnSetMaterial(material); - - TextureUsage0 = (material.TextureLayer[0].Texture) ? 1 : 0; - TextureUsage1 = (material.TextureLayer[1].Texture) ? 1 : 0; -} - -void COpenGL3MaterialLightmapCB::OnSetConstants(IMaterialRendererServices* services, s32 userData) -{ - COpenGL3MaterialBaseCB::OnSetConstants(services, userData); - - IVideoDriver* driver = services->getVideoDriver(); - - if (FirstUpdate) - { - TMatrix0ID = services->getVertexShaderConstantID("uTMatrix0"); - TMatrix1ID = services->getVertexShaderConstantID("uTMatrix1"); - ModulateID = services->getVertexShaderConstantID("uModulate"); - TextureUsage0ID = services->getVertexShaderConstantID("uTextureUsage0"); - TextureUsage1ID = services->getVertexShaderConstantID("uTextureUsage1"); - TextureUnit0ID = services->getVertexShaderConstantID("uTextureUnit0"); - TextureUnit1ID = services->getVertexShaderConstantID("uTextureUnit1"); - - FirstUpdate = false; - } - - core::matrix4 Matrix = driver->getTransform(ETS_TEXTURE_0); - services->setPixelShaderConstant(TMatrix0ID, Matrix.pointer(), 16); - - Matrix = driver->getTransform(E_TRANSFORMATION_STATE(ETS_TEXTURE_0 + 1)); - services->setPixelShaderConstant(TMatrix1ID, Matrix.pointer(), 16); - - services->setPixelShaderConstant(ModulateID, &Modulate, 1); - services->setPixelShaderConstant(TextureUsage0ID, &TextureUsage0, 1); - services->setPixelShaderConstant(TextureUsage1ID, &TextureUsage1, 1); - services->setPixelShaderConstant(TextureUnit0ID, &TextureUnit0, 1); - services->setPixelShaderConstant(TextureUnit1ID, &TextureUnit1, 1); -} - -// EMT_SPHERE_MAP + EMT_REFLECTION_2_LAYER + EMT_TRANSPARENT_REFLECTION_2_LAYER - -COpenGL3MaterialReflectionCB::COpenGL3MaterialReflectionCB() : - FirstUpdate(true), TMatrix0ID(-1), TextureUsage0ID(-1), TextureUsage1ID(-1), TextureUnit0ID(-1), TextureUnit1ID(-1), - TextureUsage0(0), TextureUsage1(0), TextureUnit0(0), TextureUnit1(1) -{ -} - -void COpenGL3MaterialReflectionCB::OnSetMaterial(const SMaterial& material) -{ - COpenGL3MaterialBaseCB::OnSetMaterial(material); - - TextureUsage0 = (material.TextureLayer[0].Texture) ? 1 : 0; - TextureUsage1 = (material.TextureLayer[1].Texture) ? 1 : 0; -} - -void COpenGL3MaterialReflectionCB::OnSetConstants(IMaterialRendererServices* services, s32 userData) -{ - COpenGL3MaterialBaseCB::OnSetConstants(services, userData); - - IVideoDriver* driver = services->getVideoDriver(); - - if (FirstUpdate) - { - TMatrix0ID = services->getVertexShaderConstantID("uTMatrix0"); - TextureUsage0ID = services->getVertexShaderConstantID("uTextureUsage0"); - TextureUsage1ID = services->getVertexShaderConstantID("uTextureUsage1"); - TextureUnit0ID = services->getVertexShaderConstantID("uTextureUnit0"); - TextureUnit1ID = services->getVertexShaderConstantID("uTextureUnit1"); - - FirstUpdate = false; - } - - core::matrix4 Matrix = driver->getTransform(ETS_TEXTURE_0); - services->setPixelShaderConstant(TMatrix0ID, Matrix.pointer(), 16); - - services->setPixelShaderConstant(TextureUsage0ID, &TextureUsage0, 1); - services->setPixelShaderConstant(TextureUsage1ID, &TextureUsage1, 1); - services->setPixelShaderConstant(TextureUnit0ID, &TextureUnit0, 1); - services->setPixelShaderConstant(TextureUnit1ID, &TextureUnit1, 1); -} - -// EMT_ONETEXTURE_BLEND - -COpenGL3MaterialOneTextureBlendCB::COpenGL3MaterialOneTextureBlendCB() : - FirstUpdate(true), TMatrix0ID(-1), BlendTypeID(-1), TextureUsage0ID(-1), TextureUnit0ID(-1), BlendType(0), TextureUsage0(0), TextureUnit0(0) -{ -} - -void COpenGL3MaterialOneTextureBlendCB::OnSetMaterial(const SMaterial& material) -{ - COpenGL3MaterialBaseCB::OnSetMaterial(material); - - BlendType = 0; - - E_BLEND_FACTOR srcRGBFact,dstRGBFact,srcAlphaFact,dstAlphaFact; - E_MODULATE_FUNC modulate; - u32 alphaSource; - unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulate, alphaSource, material.MaterialTypeParam); - - if (textureBlendFunc_hasAlpha(srcRGBFact) || textureBlendFunc_hasAlpha(dstRGBFact) || textureBlendFunc_hasAlpha(srcAlphaFact) || textureBlendFunc_hasAlpha(dstAlphaFact)) - { - if (alphaSource == EAS_VERTEX_COLOR) - { - BlendType = 1; - } - else if (alphaSource == EAS_TEXTURE) - { - BlendType = 2; - } - } - - TextureUsage0 = (material.TextureLayer[0].Texture) ? 1 : 0; -} - -void COpenGL3MaterialOneTextureBlendCB::OnSetConstants(IMaterialRendererServices* services, s32 userData) -{ - COpenGL3MaterialBaseCB::OnSetConstants(services, userData); - - IVideoDriver* driver = services->getVideoDriver(); - - if (FirstUpdate) - { - TMatrix0ID = services->getVertexShaderConstantID("uTMatrix0"); - BlendTypeID = services->getVertexShaderConstantID("uBlendType"); - TextureUsage0ID = services->getVertexShaderConstantID("uTextureUsage0"); - TextureUnit0ID = services->getVertexShaderConstantID("uTextureUnit0"); - - FirstUpdate = false; - } - - core::matrix4 Matrix = driver->getTransform(ETS_TEXTURE_0); - services->setPixelShaderConstant(TMatrix0ID, Matrix.pointer(), 16); - - services->setPixelShaderConstant(BlendTypeID, &BlendType, 1); - services->setPixelShaderConstant(TextureUsage0ID, &TextureUsage0, 1); - services->setPixelShaderConstant(TextureUnit0ID, &TextureUnit0, 1); -} - -} -} +// Copyright (C) 2014 Patryk Nadrowski +// This file is part of the "Irrlicht Engine". +// For conditions of distribution and use, see copyright notice in Irrlicht.h + +#include "FixedPipelineRenderer.h" + +#include "IVideoDriver.h" + +namespace irr +{ +namespace video +{ + +// Base callback + +COpenGL3MaterialBaseCB::COpenGL3MaterialBaseCB() : + FirstUpdateBase(true), WVPMatrixID(-1), WVMatrixID(-1), NMatrixID(-1), GlobalAmbientID(-1), MaterialAmbientID(-1), MaterialDiffuseID(-1), MaterialEmissiveID(-1), MaterialSpecularID(-1), MaterialShininessID(-1), + FogEnableID(-1), FogTypeID(-1), FogColorID(-1), FogStartID(-1), + FogEndID(-1), FogDensityID(-1), ThicknessID(-1), LightEnable(false), MaterialAmbient(SColorf(0.f, 0.f, 0.f)), MaterialDiffuse(SColorf(0.f, 0.f, 0.f)), MaterialEmissive(SColorf(0.f, 0.f, 0.f)), MaterialSpecular(SColorf(0.f, 0.f, 0.f)), + MaterialShininess(0.f), FogEnable(0), FogType(1), FogColor(SColorf(0.f, 0.f, 0.f, 1.f)), FogStart(0.f), FogEnd(0.f), FogDensity(0.f), Thickness(1.f) +{ +} + +void COpenGL3MaterialBaseCB::OnSetMaterial(const SMaterial& material) +{ + LightEnable = material.Lighting; + MaterialAmbient = SColorf(material.AmbientColor); + MaterialDiffuse = SColorf(material.DiffuseColor); + MaterialEmissive = SColorf(material.EmissiveColor); + MaterialSpecular = SColorf(material.SpecularColor); + MaterialShininess = material.Shininess; + + FogEnable = material.FogEnable ? 1 : 0; + + Thickness = (material.Thickness > 0.f) ? material.Thickness : 1.f; +} + +void COpenGL3MaterialBaseCB::OnSetConstants(IMaterialRendererServices* services, s32 userData) +{ + IVideoDriver* driver = services->getVideoDriver(); + + if (FirstUpdateBase) + { + WVPMatrixID = services->getVertexShaderConstantID("uWVPMatrix"); + WVMatrixID = services->getVertexShaderConstantID("uWVMatrix"); + NMatrixID = services->getVertexShaderConstantID("uNMatrix"); + GlobalAmbientID = services->getVertexShaderConstantID("uGlobalAmbient"); + MaterialAmbientID = services->getVertexShaderConstantID("uMaterialAmbient"); + MaterialDiffuseID = services->getVertexShaderConstantID("uMaterialDiffuse"); + MaterialEmissiveID = services->getVertexShaderConstantID("uMaterialEmissive"); + MaterialSpecularID = services->getVertexShaderConstantID("uMaterialSpecular"); + MaterialShininessID = services->getVertexShaderConstantID("uMaterialShininess"); + FogEnableID = services->getVertexShaderConstantID("uFogEnable"); + FogTypeID = services->getVertexShaderConstantID("uFogType"); + FogColorID = services->getVertexShaderConstantID("uFogColor"); + FogStartID = services->getVertexShaderConstantID("uFogStart"); + FogEndID = services->getVertexShaderConstantID("uFogEnd"); + FogDensityID = services->getVertexShaderConstantID("uFogDensity"); + ThicknessID = services->getVertexShaderConstantID("uThickness"); + + FirstUpdateBase = false; + } + + const core::matrix4 W = driver->getTransform(ETS_WORLD); + const core::matrix4 V = driver->getTransform(ETS_VIEW); + const core::matrix4 P = driver->getTransform(ETS_PROJECTION); + + core::matrix4 Matrix = P * V * W; + services->setPixelShaderConstant(WVPMatrixID, Matrix.pointer(), 16); + + Matrix = V * W; + services->setPixelShaderConstant(WVMatrixID, Matrix.pointer(), 16); + + Matrix.makeInverse(); + services->setPixelShaderConstant(NMatrixID, Matrix.getTransposed().pointer(), 16); + + services->setPixelShaderConstant(FogEnableID, &FogEnable, 1); + + if (FogEnable) + { + SColor TempColor(0); + E_FOG_TYPE TempType = EFT_FOG_LINEAR; + bool TempPerFragment = false; + bool TempRange = false; + + driver->getFog(TempColor, TempType, FogStart, FogEnd, FogDensity, TempPerFragment, TempRange); + + FogType = (s32)TempType; + FogColor = SColorf(TempColor); + + services->setPixelShaderConstant(FogTypeID, &FogType, 1); + services->setPixelShaderConstant(FogColorID, reinterpret_cast(&FogColor), 4); + services->setPixelShaderConstant(FogStartID, &FogStart, 1); + services->setPixelShaderConstant(FogEndID, &FogEnd, 1); + services->setPixelShaderConstant(FogDensityID, &FogDensity, 1); + } + + services->setPixelShaderConstant(ThicknessID, &Thickness, 1); +} + +// EMT_SOLID + EMT_TRANSPARENT_ADD_COLOR + EMT_TRANSPARENT_ALPHA_CHANNEL + EMT_TRANSPARENT_VERTEX_ALPHA + +COpenGL3MaterialSolidCB::COpenGL3MaterialSolidCB() : + FirstUpdate(true), TMatrix0ID(-1), AlphaRefID(-1), TextureUsage0ID(-1), TextureUnit0ID(-1), AlphaRef(0.5f), TextureUsage0(0), TextureUnit0(0) +{ +} + +void COpenGL3MaterialSolidCB::OnSetMaterial(const SMaterial& material) +{ + COpenGL3MaterialBaseCB::OnSetMaterial(material); + + AlphaRef = material.MaterialTypeParam; + TextureUsage0 = (material.TextureLayer[0].Texture) ? 1 : 0; +} + +void COpenGL3MaterialSolidCB::OnSetConstants(IMaterialRendererServices* services, s32 userData) +{ + COpenGL3MaterialBaseCB::OnSetConstants(services, userData); + + IVideoDriver* driver = services->getVideoDriver(); + + if (FirstUpdate) + { + TMatrix0ID = services->getVertexShaderConstantID("uTMatrix0"); + AlphaRefID = services->getVertexShaderConstantID("uAlphaRef"); + TextureUsage0ID = services->getVertexShaderConstantID("uTextureUsage0"); + TextureUnit0ID = services->getVertexShaderConstantID("uTextureUnit0"); + + FirstUpdate = false; + } + + core::matrix4 Matrix = driver->getTransform(ETS_TEXTURE_0); + services->setPixelShaderConstant(TMatrix0ID, Matrix.pointer(), 16); + + services->setPixelShaderConstant(AlphaRefID, &AlphaRef, 1); + services->setPixelShaderConstant(TextureUsage0ID, &TextureUsage0, 1); + services->setPixelShaderConstant(TextureUnit0ID, &TextureUnit0, 1); +} + +// EMT_SOLID_2_LAYER + EMT_DETAIL_MAP + +COpenGL3MaterialSolid2CB::COpenGL3MaterialSolid2CB() : + FirstUpdate(true), TMatrix0ID(-1), TMatrix1ID(-1), TextureUsage0ID(-1), TextureUsage1ID(-1), TextureUnit0ID(-1), TextureUnit1ID(-1), + TextureUsage0(0), TextureUsage1(0), TextureUnit0(0), TextureUnit1(1) +{ +} + +void COpenGL3MaterialSolid2CB::OnSetMaterial(const SMaterial& material) +{ + COpenGL3MaterialBaseCB::OnSetMaterial(material); + + TextureUsage0 = (material.TextureLayer[0].Texture) ? 1 : 0; + TextureUsage1 = (material.TextureLayer[1].Texture) ? 1 : 0; +} + +void COpenGL3MaterialSolid2CB::OnSetConstants(IMaterialRendererServices* services, s32 userData) +{ + COpenGL3MaterialBaseCB::OnSetConstants(services, userData); + + IVideoDriver* driver = services->getVideoDriver(); + + if (FirstUpdate) + { + TMatrix0ID = services->getVertexShaderConstantID("uTMatrix0"); + TMatrix1ID = services->getVertexShaderConstantID("uTMatrix1"); + TextureUsage0ID = services->getVertexShaderConstantID("uTextureUsage0"); + TextureUsage1ID = services->getVertexShaderConstantID("uTextureUsage1"); + TextureUnit0ID = services->getVertexShaderConstantID("uTextureUnit0"); + TextureUnit1ID = services->getVertexShaderConstantID("uTextureUnit1"); + + FirstUpdate = false; + } + + core::matrix4 Matrix = driver->getTransform(ETS_TEXTURE_0); + services->setPixelShaderConstant(TMatrix0ID, Matrix.pointer(), 16); + + Matrix = driver->getTransform(E_TRANSFORMATION_STATE(ETS_TEXTURE_0 + 1)); + services->setPixelShaderConstant(TMatrix1ID, Matrix.pointer(), 16); + + services->setPixelShaderConstant(TextureUsage0ID, &TextureUsage0, 1); + services->setPixelShaderConstant(TextureUsage1ID, &TextureUsage1, 1); + services->setPixelShaderConstant(TextureUnit0ID, &TextureUnit0, 1); + services->setPixelShaderConstant(TextureUnit1ID, &TextureUnit1, 1); +} + +// EMT_LIGHTMAP + EMT_LIGHTMAP_ADD + EMT_LIGHTMAP_M2 + EMT_LIGHTMAP_M4 + +COpenGL3MaterialLightmapCB::COpenGL3MaterialLightmapCB(float modulate) : + FirstUpdate(true), TMatrix0ID(-1), TMatrix1ID(-1), ModulateID(-1), TextureUsage0ID(-1), TextureUsage1ID(-1), TextureUnit0ID(-1), TextureUnit1ID(-1), + Modulate(modulate), TextureUsage0(0), TextureUsage1(0), TextureUnit0(0), TextureUnit1(1) +{ +} + +void COpenGL3MaterialLightmapCB::OnSetMaterial(const SMaterial& material) +{ + COpenGL3MaterialBaseCB::OnSetMaterial(material); + + TextureUsage0 = (material.TextureLayer[0].Texture) ? 1 : 0; + TextureUsage1 = (material.TextureLayer[1].Texture) ? 1 : 0; +} + +void COpenGL3MaterialLightmapCB::OnSetConstants(IMaterialRendererServices* services, s32 userData) +{ + COpenGL3MaterialBaseCB::OnSetConstants(services, userData); + + IVideoDriver* driver = services->getVideoDriver(); + + if (FirstUpdate) + { + TMatrix0ID = services->getVertexShaderConstantID("uTMatrix0"); + TMatrix1ID = services->getVertexShaderConstantID("uTMatrix1"); + ModulateID = services->getVertexShaderConstantID("uModulate"); + TextureUsage0ID = services->getVertexShaderConstantID("uTextureUsage0"); + TextureUsage1ID = services->getVertexShaderConstantID("uTextureUsage1"); + TextureUnit0ID = services->getVertexShaderConstantID("uTextureUnit0"); + TextureUnit1ID = services->getVertexShaderConstantID("uTextureUnit1"); + + FirstUpdate = false; + } + + core::matrix4 Matrix = driver->getTransform(ETS_TEXTURE_0); + services->setPixelShaderConstant(TMatrix0ID, Matrix.pointer(), 16); + + Matrix = driver->getTransform(E_TRANSFORMATION_STATE(ETS_TEXTURE_0 + 1)); + services->setPixelShaderConstant(TMatrix1ID, Matrix.pointer(), 16); + + services->setPixelShaderConstant(ModulateID, &Modulate, 1); + services->setPixelShaderConstant(TextureUsage0ID, &TextureUsage0, 1); + services->setPixelShaderConstant(TextureUsage1ID, &TextureUsage1, 1); + services->setPixelShaderConstant(TextureUnit0ID, &TextureUnit0, 1); + services->setPixelShaderConstant(TextureUnit1ID, &TextureUnit1, 1); +} + +// EMT_SPHERE_MAP + EMT_REFLECTION_2_LAYER + EMT_TRANSPARENT_REFLECTION_2_LAYER + +COpenGL3MaterialReflectionCB::COpenGL3MaterialReflectionCB() : + FirstUpdate(true), TMatrix0ID(-1), TextureUsage0ID(-1), TextureUsage1ID(-1), TextureUnit0ID(-1), TextureUnit1ID(-1), + TextureUsage0(0), TextureUsage1(0), TextureUnit0(0), TextureUnit1(1) +{ +} + +void COpenGL3MaterialReflectionCB::OnSetMaterial(const SMaterial& material) +{ + COpenGL3MaterialBaseCB::OnSetMaterial(material); + + TextureUsage0 = (material.TextureLayer[0].Texture) ? 1 : 0; + TextureUsage1 = (material.TextureLayer[1].Texture) ? 1 : 0; +} + +void COpenGL3MaterialReflectionCB::OnSetConstants(IMaterialRendererServices* services, s32 userData) +{ + COpenGL3MaterialBaseCB::OnSetConstants(services, userData); + + IVideoDriver* driver = services->getVideoDriver(); + + if (FirstUpdate) + { + TMatrix0ID = services->getVertexShaderConstantID("uTMatrix0"); + TextureUsage0ID = services->getVertexShaderConstantID("uTextureUsage0"); + TextureUsage1ID = services->getVertexShaderConstantID("uTextureUsage1"); + TextureUnit0ID = services->getVertexShaderConstantID("uTextureUnit0"); + TextureUnit1ID = services->getVertexShaderConstantID("uTextureUnit1"); + + FirstUpdate = false; + } + + core::matrix4 Matrix = driver->getTransform(ETS_TEXTURE_0); + services->setPixelShaderConstant(TMatrix0ID, Matrix.pointer(), 16); + + services->setPixelShaderConstant(TextureUsage0ID, &TextureUsage0, 1); + services->setPixelShaderConstant(TextureUsage1ID, &TextureUsage1, 1); + services->setPixelShaderConstant(TextureUnit0ID, &TextureUnit0, 1); + services->setPixelShaderConstant(TextureUnit1ID, &TextureUnit1, 1); +} + +// EMT_ONETEXTURE_BLEND + +COpenGL3MaterialOneTextureBlendCB::COpenGL3MaterialOneTextureBlendCB() : + FirstUpdate(true), TMatrix0ID(-1), BlendTypeID(-1), TextureUsage0ID(-1), TextureUnit0ID(-1), BlendType(0), TextureUsage0(0), TextureUnit0(0) +{ +} + +void COpenGL3MaterialOneTextureBlendCB::OnSetMaterial(const SMaterial& material) +{ + COpenGL3MaterialBaseCB::OnSetMaterial(material); + + BlendType = 0; + + E_BLEND_FACTOR srcRGBFact,dstRGBFact,srcAlphaFact,dstAlphaFact; + E_MODULATE_FUNC modulate; + u32 alphaSource; + unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulate, alphaSource, material.MaterialTypeParam); + + if (textureBlendFunc_hasAlpha(srcRGBFact) || textureBlendFunc_hasAlpha(dstRGBFact) || textureBlendFunc_hasAlpha(srcAlphaFact) || textureBlendFunc_hasAlpha(dstAlphaFact)) + { + if (alphaSource == EAS_VERTEX_COLOR) + { + BlendType = 1; + } + else if (alphaSource == EAS_TEXTURE) + { + BlendType = 2; + } + } + + TextureUsage0 = (material.TextureLayer[0].Texture) ? 1 : 0; +} + +void COpenGL3MaterialOneTextureBlendCB::OnSetConstants(IMaterialRendererServices* services, s32 userData) +{ + COpenGL3MaterialBaseCB::OnSetConstants(services, userData); + + IVideoDriver* driver = services->getVideoDriver(); + + if (FirstUpdate) + { + TMatrix0ID = services->getVertexShaderConstantID("uTMatrix0"); + BlendTypeID = services->getVertexShaderConstantID("uBlendType"); + TextureUsage0ID = services->getVertexShaderConstantID("uTextureUsage0"); + TextureUnit0ID = services->getVertexShaderConstantID("uTextureUnit0"); + + FirstUpdate = false; + } + + core::matrix4 Matrix = driver->getTransform(ETS_TEXTURE_0); + services->setPixelShaderConstant(TMatrix0ID, Matrix.pointer(), 16); + + services->setPixelShaderConstant(BlendTypeID, &BlendType, 1); + services->setPixelShaderConstant(TextureUsage0ID, &TextureUsage0, 1); + services->setPixelShaderConstant(TextureUnit0ID, &TextureUnit0, 1); +} + +} +} diff --git a/source/Irrlicht/OpenGL/FixedPipelineRenderer.h b/source/Irrlicht/OpenGL/FixedPipelineRenderer.h index 4a9bb95..aea935f 100644 --- a/source/Irrlicht/OpenGL/FixedPipelineRenderer.h +++ b/source/Irrlicht/OpenGL/FixedPipelineRenderer.h @@ -1,180 +1,180 @@ -// Copyright (C) 2014 Patryk Nadrowski -// This file is part of the "Irrlicht Engine". -// For conditions of distribution and use, see copyright notice in Irrlicht.h - -#pragma once - -#include "IShaderConstantSetCallBack.h" -#include "IMaterialRendererServices.h" - -namespace irr -{ -namespace video -{ - -class COpenGL3MaterialBaseCB : public IShaderConstantSetCallBack -{ -public: - COpenGL3MaterialBaseCB(); - - virtual void OnSetMaterial(const SMaterial& material); - virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData); - -protected: - bool FirstUpdateBase; - - s32 WVPMatrixID; - s32 WVMatrixID; - s32 NMatrixID; - - s32 GlobalAmbientID; - s32 MaterialAmbientID; - s32 MaterialDiffuseID; - s32 MaterialEmissiveID; - s32 MaterialSpecularID; - s32 MaterialShininessID; - - s32 FogEnableID; - s32 FogTypeID; - s32 FogColorID; - s32 FogStartID; - s32 FogEndID; - s32 FogDensityID; - - s32 ThicknessID; - - bool LightEnable; - SColorf GlobalAmbient; - SColorf MaterialAmbient; - SColorf MaterialDiffuse; - SColorf MaterialEmissive; - SColorf MaterialSpecular; - f32 MaterialShininess; - - s32 FogEnable; - s32 FogType; - SColorf FogColor; - f32 FogStart; - f32 FogEnd; - f32 FogDensity; - - f32 Thickness; -}; - -class COpenGL3MaterialSolidCB : public COpenGL3MaterialBaseCB -{ -public: - COpenGL3MaterialSolidCB(); - - virtual void OnSetMaterial(const SMaterial& material); - virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData); - -protected: - bool FirstUpdate; - - s32 TMatrix0ID; - s32 AlphaRefID; - s32 TextureUsage0ID; - s32 TextureUnit0ID; - - f32 AlphaRef; - s32 TextureUsage0; - s32 TextureUnit0; -}; - -class COpenGL3MaterialSolid2CB : public COpenGL3MaterialBaseCB -{ -public: - COpenGL3MaterialSolid2CB(); - - virtual void OnSetMaterial(const SMaterial& material); - virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData); - -protected: - bool FirstUpdate; - - s32 TMatrix0ID; - s32 TMatrix1ID; - s32 TextureUsage0ID; - s32 TextureUsage1ID; - s32 TextureUnit0ID; - s32 TextureUnit1ID; - - s32 TextureUsage0; - s32 TextureUsage1; - s32 TextureUnit0; - s32 TextureUnit1; -}; - -class COpenGL3MaterialLightmapCB : public COpenGL3MaterialBaseCB -{ -public: - COpenGL3MaterialLightmapCB(float modulate); - - virtual void OnSetMaterial(const SMaterial& material); - virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData); - -protected: - bool FirstUpdate; - - s32 TMatrix0ID; - s32 TMatrix1ID; - s32 ModulateID; - s32 TextureUsage0ID; - s32 TextureUsage1ID; - s32 TextureUnit0ID; - s32 TextureUnit1ID; - - f32 Modulate; - s32 TextureUsage0; - s32 TextureUsage1; - s32 TextureUnit0; - s32 TextureUnit1; -}; - -class COpenGL3MaterialReflectionCB : public COpenGL3MaterialBaseCB -{ -public: - COpenGL3MaterialReflectionCB(); - - virtual void OnSetMaterial(const SMaterial& material); - virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData); - -protected: - bool FirstUpdate; - - s32 TMatrix0ID; - s32 TextureUsage0ID; - s32 TextureUsage1ID; - s32 TextureUnit0ID; - s32 TextureUnit1ID; - - s32 TextureUsage0; - s32 TextureUsage1; - s32 TextureUnit0; - s32 TextureUnit1; -}; - -class COpenGL3MaterialOneTextureBlendCB : public COpenGL3MaterialBaseCB -{ -public: - COpenGL3MaterialOneTextureBlendCB(); - - virtual void OnSetMaterial(const SMaterial& material); - virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData); - -protected: - bool FirstUpdate; - - s32 TMatrix0ID; - s32 BlendTypeID; - s32 TextureUsage0ID; - s32 TextureUnit0ID; - - s32 BlendType; - s32 TextureUsage0; - s32 TextureUnit0; -}; - -} -} +// Copyright (C) 2014 Patryk Nadrowski +// This file is part of the "Irrlicht Engine". +// For conditions of distribution and use, see copyright notice in Irrlicht.h + +#pragma once + +#include "IShaderConstantSetCallBack.h" +#include "IMaterialRendererServices.h" + +namespace irr +{ +namespace video +{ + +class COpenGL3MaterialBaseCB : public IShaderConstantSetCallBack +{ +public: + COpenGL3MaterialBaseCB(); + + virtual void OnSetMaterial(const SMaterial& material); + virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData); + +protected: + bool FirstUpdateBase; + + s32 WVPMatrixID; + s32 WVMatrixID; + s32 NMatrixID; + + s32 GlobalAmbientID; + s32 MaterialAmbientID; + s32 MaterialDiffuseID; + s32 MaterialEmissiveID; + s32 MaterialSpecularID; + s32 MaterialShininessID; + + s32 FogEnableID; + s32 FogTypeID; + s32 FogColorID; + s32 FogStartID; + s32 FogEndID; + s32 FogDensityID; + + s32 ThicknessID; + + bool LightEnable; + SColorf GlobalAmbient; + SColorf MaterialAmbient; + SColorf MaterialDiffuse; + SColorf MaterialEmissive; + SColorf MaterialSpecular; + f32 MaterialShininess; + + s32 FogEnable; + s32 FogType; + SColorf FogColor; + f32 FogStart; + f32 FogEnd; + f32 FogDensity; + + f32 Thickness; +}; + +class COpenGL3MaterialSolidCB : public COpenGL3MaterialBaseCB +{ +public: + COpenGL3MaterialSolidCB(); + + virtual void OnSetMaterial(const SMaterial& material); + virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData); + +protected: + bool FirstUpdate; + + s32 TMatrix0ID; + s32 AlphaRefID; + s32 TextureUsage0ID; + s32 TextureUnit0ID; + + f32 AlphaRef; + s32 TextureUsage0; + s32 TextureUnit0; +}; + +class COpenGL3MaterialSolid2CB : public COpenGL3MaterialBaseCB +{ +public: + COpenGL3MaterialSolid2CB(); + + virtual void OnSetMaterial(const SMaterial& material); + virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData); + +protected: + bool FirstUpdate; + + s32 TMatrix0ID; + s32 TMatrix1ID; + s32 TextureUsage0ID; + s32 TextureUsage1ID; + s32 TextureUnit0ID; + s32 TextureUnit1ID; + + s32 TextureUsage0; + s32 TextureUsage1; + s32 TextureUnit0; + s32 TextureUnit1; +}; + +class COpenGL3MaterialLightmapCB : public COpenGL3MaterialBaseCB +{ +public: + COpenGL3MaterialLightmapCB(float modulate); + + virtual void OnSetMaterial(const SMaterial& material); + virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData); + +protected: + bool FirstUpdate; + + s32 TMatrix0ID; + s32 TMatrix1ID; + s32 ModulateID; + s32 TextureUsage0ID; + s32 TextureUsage1ID; + s32 TextureUnit0ID; + s32 TextureUnit1ID; + + f32 Modulate; + s32 TextureUsage0; + s32 TextureUsage1; + s32 TextureUnit0; + s32 TextureUnit1; +}; + +class COpenGL3MaterialReflectionCB : public COpenGL3MaterialBaseCB +{ +public: + COpenGL3MaterialReflectionCB(); + + virtual void OnSetMaterial(const SMaterial& material); + virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData); + +protected: + bool FirstUpdate; + + s32 TMatrix0ID; + s32 TextureUsage0ID; + s32 TextureUsage1ID; + s32 TextureUnit0ID; + s32 TextureUnit1ID; + + s32 TextureUsage0; + s32 TextureUsage1; + s32 TextureUnit0; + s32 TextureUnit1; +}; + +class COpenGL3MaterialOneTextureBlendCB : public COpenGL3MaterialBaseCB +{ +public: + COpenGL3MaterialOneTextureBlendCB(); + + virtual void OnSetMaterial(const SMaterial& material); + virtual void OnSetConstants(IMaterialRendererServices* services, s32 userData); + +protected: + bool FirstUpdate; + + s32 TMatrix0ID; + s32 BlendTypeID; + s32 TextureUsage0ID; + s32 TextureUnit0ID; + + s32 BlendType; + s32 TextureUsage0; + s32 TextureUnit0; +}; + +} +} diff --git a/source/Irrlicht/OpenGL/MaterialRenderer.cpp b/source/Irrlicht/OpenGL/MaterialRenderer.cpp index 20d684c..d7aa483 100644 --- a/source/Irrlicht/OpenGL/MaterialRenderer.cpp +++ b/source/Irrlicht/OpenGL/MaterialRenderer.cpp @@ -1,481 +1,481 @@ -// Copyright (C) 2014 Patryk Nadrowski -// This file is part of the "Irrlicht Engine". -// For conditions of distribution and use, see copyright notice in irrlicht.h - -#include "MaterialRenderer.h" - -#include "EVertexAttributes.h" -#include "IGPUProgrammingServices.h" -#include "IShaderConstantSetCallBack.h" -#include "IVideoDriver.h" -#include "os.h" - -#include "Driver.h" - -#include "COpenGLCoreTexture.h" -#include "COpenGLCoreCacheHandler.h" - -namespace irr -{ -namespace video -{ - - -COpenGL3MaterialRenderer::COpenGL3MaterialRenderer(COpenGL3DriverBase* driver, - s32& outMaterialTypeNr, - const c8* vertexShaderProgram, - const c8* pixelShaderProgram, - IShaderConstantSetCallBack* callback, - E_MATERIAL_TYPE baseMaterial, - s32 userData) - : Driver(driver), CallBack(callback), Alpha(false), Blending(false), FixedBlending(false), Program(0), UserData(userData) -{ -#ifdef _DEBUG - setDebugName("MaterialRenderer"); -#endif - - switch (baseMaterial) - { - case EMT_TRANSPARENT_VERTEX_ALPHA: - case EMT_TRANSPARENT_ALPHA_CHANNEL: - Alpha = true; - break; - case EMT_TRANSPARENT_ADD_COLOR: - FixedBlending = true; - break; - case EMT_ONETEXTURE_BLEND: - Blending = true; - break; - default: - break; - } - - if (CallBack) - CallBack->grab(); - - init(outMaterialTypeNr, vertexShaderProgram, pixelShaderProgram); -} - - -COpenGL3MaterialRenderer::COpenGL3MaterialRenderer(COpenGL3DriverBase* driver, - IShaderConstantSetCallBack* callback, - E_MATERIAL_TYPE baseMaterial, s32 userData) -: Driver(driver), CallBack(callback), Alpha(false), Blending(false), FixedBlending(false), Program(0), UserData(userData) -{ - switch (baseMaterial) - { - case EMT_TRANSPARENT_VERTEX_ALPHA: - case EMT_TRANSPARENT_ALPHA_CHANNEL: - Alpha = true; - break; - case EMT_TRANSPARENT_ADD_COLOR: - FixedBlending = true; - break; - case EMT_ONETEXTURE_BLEND: - Blending = true; - break; - default: - break; - } - - if (CallBack) - CallBack->grab(); -} - - -COpenGL3MaterialRenderer::~COpenGL3MaterialRenderer() -{ - if (CallBack) - CallBack->drop(); - - if (Program) - { - GLuint shaders[8]; - GLint count; - glGetAttachedShaders(Program, 8, &count, shaders); - - count=core::min_(count,8); - for (GLint i=0; iaddMaterialRenderer(this); -} - - -bool COpenGL3MaterialRenderer::OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype) -{ - if (CallBack && Program) - CallBack->OnSetConstants(this, UserData); - - return true; -} - - -void COpenGL3MaterialRenderer::OnSetMaterial(const video::SMaterial& material, - const video::SMaterial& lastMaterial, - bool resetAllRenderstates, - video::IMaterialRendererServices* services) -{ - COpenGL3CacheHandler* cacheHandler = Driver->getCacheHandler(); - - cacheHandler->setProgram(Program); - - Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); - - if (Alpha) - { - cacheHandler->setBlend(true); - cacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - } - else if (FixedBlending) - { - cacheHandler->setBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR); - cacheHandler->setBlend(true); - } - else if (Blending) - { - E_BLEND_FACTOR srcRGBFact,dstRGBFact,srcAlphaFact,dstAlphaFact; - E_MODULATE_FUNC modulate; - u32 alphaSource; - unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulate, alphaSource, material.MaterialTypeParam); - - cacheHandler->setBlendFuncSeparate(Driver->getGLBlend(srcRGBFact), Driver->getGLBlend(dstRGBFact), - Driver->getGLBlend(srcAlphaFact), Driver->getGLBlend(dstAlphaFact)); - - cacheHandler->setBlend(true); - } - - if (CallBack) - CallBack->OnSetMaterial(material); -} - - -void COpenGL3MaterialRenderer::OnUnsetMaterial() -{ -} - - -bool COpenGL3MaterialRenderer::isTransparent() const -{ - return (Alpha || Blending || FixedBlending); -} - - -s32 COpenGL3MaterialRenderer::getRenderCapability() const -{ - return 0; -} - - -bool COpenGL3MaterialRenderer::createShader(GLenum shaderType, const char* shader) -{ - if (Program) - { - GLuint shaderHandle = glCreateShader(shaderType); - glShaderSource(shaderHandle, 1, &shader, NULL); - glCompileShader(shaderHandle); - - GLint status = 0; - - glGetShaderiv(shaderHandle, GL_COMPILE_STATUS, &status); - - if (status != GL_TRUE) - { - os::Printer::log("GLSL shader failed to compile", ELL_ERROR); - - GLint maxLength=0; - GLint length; - - glGetShaderiv(shaderHandle, GL_INFO_LOG_LENGTH, - &maxLength); - - if (maxLength) - { - GLchar *infoLog = new GLchar[maxLength]; - glGetShaderInfoLog(shaderHandle, maxLength, &length, infoLog); - os::Printer::log(reinterpret_cast(infoLog), ELL_ERROR); - delete [] infoLog; - } - - return false; - } - - glAttachShader(Program, shaderHandle); - } - - return true; -} - - -bool COpenGL3MaterialRenderer::linkProgram() -{ - if (Program) - { - glLinkProgram(Program); - - GLint status = 0; - - glGetProgramiv(Program, GL_LINK_STATUS, &status); - - if (!status) - { - os::Printer::log("GLSL shader program failed to link", ELL_ERROR); - - GLint maxLength=0; - GLsizei length; - - glGetProgramiv(Program, GL_INFO_LOG_LENGTH, &maxLength); - - if (maxLength) - { - GLchar *infoLog = new GLchar[maxLength]; - glGetProgramInfoLog(Program, maxLength, &length, infoLog); - os::Printer::log(reinterpret_cast(infoLog), ELL_ERROR); - delete [] infoLog; - } - - return false; - } - - GLint num = 0; - - glGetProgramiv(Program, GL_ACTIVE_UNIFORMS, &num); - - if (num == 0) - return true; - - GLint maxlen = 0; - - glGetProgramiv(Program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxlen); - - if (maxlen == 0) - { - os::Printer::log("GLSL: failed to retrieve uniform information", ELL_ERROR); - return false; - } - - // seems that some implementations use an extra null terminator. - ++maxlen; - c8 *buf = new c8[maxlen]; - - UniformInfo.clear(); - UniformInfo.reallocate(num); - - for (GLint i=0; i < num; ++i) - { - SUniformInfo ui; - memset(buf, 0, maxlen); - - GLint size; - glGetActiveUniform(Program, i, maxlen, 0, &size, &ui.type, reinterpret_cast(buf)); - - core::stringc name = ""; - - // array support, workaround for some bugged drivers. - for (s32 i = 0; i < maxlen; ++i) - { - if (buf[i] == '[' || buf[i] == '\0') - break; - - name += buf[i]; - } - - ui.name = name; - ui.location = glGetUniformLocation(Program, buf); - - UniformInfo.push_back(ui); - } - - delete [] buf; - } - - return true; -} - - -void COpenGL3MaterialRenderer::setBasicRenderStates(const SMaterial& material, - const SMaterial& lastMaterial, - bool resetAllRenderstates) -{ - Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); -} - -s32 COpenGL3MaterialRenderer::getVertexShaderConstantID(const c8* name) -{ - return getPixelShaderConstantID(name); -} - -s32 COpenGL3MaterialRenderer::getPixelShaderConstantID(const c8* name) -{ - for (u32 i = 0; i < UniformInfo.size(); ++i) - { - if (UniformInfo[i].name == name) - return i; - } - - return -1; -} - -void COpenGL3MaterialRenderer::setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount) -{ - os::Printer::log("Cannot set constant, please use high level shader call instead.", ELL_WARNING); -} - -void COpenGL3MaterialRenderer::setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount) -{ - os::Printer::log("Cannot set constant, use high level shader call.", ELL_WARNING); -} - -bool COpenGL3MaterialRenderer::setVertexShaderConstant(s32 index, const f32* floats, int count) -{ - return setPixelShaderConstant(index, floats, count); -} - -bool COpenGL3MaterialRenderer::setVertexShaderConstant(s32 index, const s32* ints, int count) -{ - return setPixelShaderConstant(index, ints, count); -} - -bool COpenGL3MaterialRenderer::setVertexShaderConstant(s32 index, const u32* ints, int count) -{ - return setPixelShaderConstant(index, ints, count); -} - -bool COpenGL3MaterialRenderer::setPixelShaderConstant(s32 index, const f32* floats, int count) -{ - if(index < 0 || UniformInfo[index].location < 0) - return false; - - bool status = true; - - switch (UniformInfo[index].type) - { - case GL_FLOAT: - glUniform1fv(UniformInfo[index].location, count, floats); - break; - case GL_FLOAT_VEC2: - glUniform2fv(UniformInfo[index].location, count/2, floats); - break; - case GL_FLOAT_VEC3: - glUniform3fv(UniformInfo[index].location, count/3, floats); - break; - case GL_FLOAT_VEC4: - glUniform4fv(UniformInfo[index].location, count/4, floats); - break; - case GL_FLOAT_MAT2: - glUniformMatrix2fv(UniformInfo[index].location, count/4, false, floats); - break; - case GL_FLOAT_MAT3: - glUniformMatrix3fv(UniformInfo[index].location, count/9, false, floats); - break; - case GL_FLOAT_MAT4: - glUniformMatrix4fv(UniformInfo[index].location, count/16, false, floats); - break; - case GL_SAMPLER_2D: - case GL_SAMPLER_CUBE: - { - if(floats) - { - const GLint id = (GLint)(*floats); - glUniform1iv(UniformInfo[index].location, 1, &id); - } - else - status = false; - } - break; - default: - status = false; - break; - } - - return status; -} - -bool COpenGL3MaterialRenderer::setPixelShaderConstant(s32 index, const s32* ints, int count) -{ - if(index < 0 || UniformInfo[index].location < 0) - return false; - - bool status = true; - - switch (UniformInfo[index].type) - { - case GL_INT: - case GL_BOOL: - glUniform1iv(UniformInfo[index].location, count, ints); - break; - case GL_INT_VEC2: - case GL_BOOL_VEC2: - glUniform2iv(UniformInfo[index].location, count/2, ints); - break; - case GL_INT_VEC3: - case GL_BOOL_VEC3: - glUniform3iv(UniformInfo[index].location, count/3, ints); - break; - case GL_INT_VEC4: - case GL_BOOL_VEC4: - glUniform4iv(UniformInfo[index].location, count/4, ints); - break; - case GL_SAMPLER_2D: - case GL_SAMPLER_CUBE: - glUniform1iv(UniformInfo[index].location, 1, ints); - break; - default: - status = false; - break; - } - - return status; -} - -bool COpenGL3MaterialRenderer::setPixelShaderConstant(s32 index, const u32* ints, int count) -{ - os::Printer::log("Unsigned int support needs at least GLES 3.0", ELL_WARNING); - return false; -} - -IVideoDriver* COpenGL3MaterialRenderer::getVideoDriver() -{ - return Driver; -} - -} -} +// Copyright (C) 2014 Patryk Nadrowski +// This file is part of the "Irrlicht Engine". +// For conditions of distribution and use, see copyright notice in irrlicht.h + +#include "MaterialRenderer.h" + +#include "EVertexAttributes.h" +#include "IGPUProgrammingServices.h" +#include "IShaderConstantSetCallBack.h" +#include "IVideoDriver.h" +#include "os.h" + +#include "Driver.h" + +#include "COpenGLCoreTexture.h" +#include "COpenGLCoreCacheHandler.h" + +namespace irr +{ +namespace video +{ + + +COpenGL3MaterialRenderer::COpenGL3MaterialRenderer(COpenGL3DriverBase* driver, + s32& outMaterialTypeNr, + const c8* vertexShaderProgram, + const c8* pixelShaderProgram, + IShaderConstantSetCallBack* callback, + E_MATERIAL_TYPE baseMaterial, + s32 userData) + : Driver(driver), CallBack(callback), Alpha(false), Blending(false), FixedBlending(false), Program(0), UserData(userData) +{ +#ifdef _DEBUG + setDebugName("MaterialRenderer"); +#endif + + switch (baseMaterial) + { + case EMT_TRANSPARENT_VERTEX_ALPHA: + case EMT_TRANSPARENT_ALPHA_CHANNEL: + Alpha = true; + break; + case EMT_TRANSPARENT_ADD_COLOR: + FixedBlending = true; + break; + case EMT_ONETEXTURE_BLEND: + Blending = true; + break; + default: + break; + } + + if (CallBack) + CallBack->grab(); + + init(outMaterialTypeNr, vertexShaderProgram, pixelShaderProgram); +} + + +COpenGL3MaterialRenderer::COpenGL3MaterialRenderer(COpenGL3DriverBase* driver, + IShaderConstantSetCallBack* callback, + E_MATERIAL_TYPE baseMaterial, s32 userData) +: Driver(driver), CallBack(callback), Alpha(false), Blending(false), FixedBlending(false), Program(0), UserData(userData) +{ + switch (baseMaterial) + { + case EMT_TRANSPARENT_VERTEX_ALPHA: + case EMT_TRANSPARENT_ALPHA_CHANNEL: + Alpha = true; + break; + case EMT_TRANSPARENT_ADD_COLOR: + FixedBlending = true; + break; + case EMT_ONETEXTURE_BLEND: + Blending = true; + break; + default: + break; + } + + if (CallBack) + CallBack->grab(); +} + + +COpenGL3MaterialRenderer::~COpenGL3MaterialRenderer() +{ + if (CallBack) + CallBack->drop(); + + if (Program) + { + GLuint shaders[8]; + GLint count; + glGetAttachedShaders(Program, 8, &count, shaders); + + count=core::min_(count,8); + for (GLint i=0; iaddMaterialRenderer(this); +} + + +bool COpenGL3MaterialRenderer::OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype) +{ + if (CallBack && Program) + CallBack->OnSetConstants(this, UserData); + + return true; +} + + +void COpenGL3MaterialRenderer::OnSetMaterial(const video::SMaterial& material, + const video::SMaterial& lastMaterial, + bool resetAllRenderstates, + video::IMaterialRendererServices* services) +{ + COpenGL3CacheHandler* cacheHandler = Driver->getCacheHandler(); + + cacheHandler->setProgram(Program); + + Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); + + if (Alpha) + { + cacheHandler->setBlend(true); + cacheHandler->setBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + } + else if (FixedBlending) + { + cacheHandler->setBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR); + cacheHandler->setBlend(true); + } + else if (Blending) + { + E_BLEND_FACTOR srcRGBFact,dstRGBFact,srcAlphaFact,dstAlphaFact; + E_MODULATE_FUNC modulate; + u32 alphaSource; + unpack_textureBlendFuncSeparate(srcRGBFact, dstRGBFact, srcAlphaFact, dstAlphaFact, modulate, alphaSource, material.MaterialTypeParam); + + cacheHandler->setBlendFuncSeparate(Driver->getGLBlend(srcRGBFact), Driver->getGLBlend(dstRGBFact), + Driver->getGLBlend(srcAlphaFact), Driver->getGLBlend(dstAlphaFact)); + + cacheHandler->setBlend(true); + } + + if (CallBack) + CallBack->OnSetMaterial(material); +} + + +void COpenGL3MaterialRenderer::OnUnsetMaterial() +{ +} + + +bool COpenGL3MaterialRenderer::isTransparent() const +{ + return (Alpha || Blending || FixedBlending); +} + + +s32 COpenGL3MaterialRenderer::getRenderCapability() const +{ + return 0; +} + + +bool COpenGL3MaterialRenderer::createShader(GLenum shaderType, const char* shader) +{ + if (Program) + { + GLuint shaderHandle = glCreateShader(shaderType); + glShaderSource(shaderHandle, 1, &shader, NULL); + glCompileShader(shaderHandle); + + GLint status = 0; + + glGetShaderiv(shaderHandle, GL_COMPILE_STATUS, &status); + + if (status != GL_TRUE) + { + os::Printer::log("GLSL shader failed to compile", ELL_ERROR); + + GLint maxLength=0; + GLint length; + + glGetShaderiv(shaderHandle, GL_INFO_LOG_LENGTH, + &maxLength); + + if (maxLength) + { + GLchar *infoLog = new GLchar[maxLength]; + glGetShaderInfoLog(shaderHandle, maxLength, &length, infoLog); + os::Printer::log(reinterpret_cast(infoLog), ELL_ERROR); + delete [] infoLog; + } + + return false; + } + + glAttachShader(Program, shaderHandle); + } + + return true; +} + + +bool COpenGL3MaterialRenderer::linkProgram() +{ + if (Program) + { + glLinkProgram(Program); + + GLint status = 0; + + glGetProgramiv(Program, GL_LINK_STATUS, &status); + + if (!status) + { + os::Printer::log("GLSL shader program failed to link", ELL_ERROR); + + GLint maxLength=0; + GLsizei length; + + glGetProgramiv(Program, GL_INFO_LOG_LENGTH, &maxLength); + + if (maxLength) + { + GLchar *infoLog = new GLchar[maxLength]; + glGetProgramInfoLog(Program, maxLength, &length, infoLog); + os::Printer::log(reinterpret_cast(infoLog), ELL_ERROR); + delete [] infoLog; + } + + return false; + } + + GLint num = 0; + + glGetProgramiv(Program, GL_ACTIVE_UNIFORMS, &num); + + if (num == 0) + return true; + + GLint maxlen = 0; + + glGetProgramiv(Program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxlen); + + if (maxlen == 0) + { + os::Printer::log("GLSL: failed to retrieve uniform information", ELL_ERROR); + return false; + } + + // seems that some implementations use an extra null terminator. + ++maxlen; + c8 *buf = new c8[maxlen]; + + UniformInfo.clear(); + UniformInfo.reallocate(num); + + for (GLint i=0; i < num; ++i) + { + SUniformInfo ui; + memset(buf, 0, maxlen); + + GLint size; + glGetActiveUniform(Program, i, maxlen, 0, &size, &ui.type, reinterpret_cast(buf)); + + core::stringc name = ""; + + // array support, workaround for some bugged drivers. + for (s32 i = 0; i < maxlen; ++i) + { + if (buf[i] == '[' || buf[i] == '\0') + break; + + name += buf[i]; + } + + ui.name = name; + ui.location = glGetUniformLocation(Program, buf); + + UniformInfo.push_back(ui); + } + + delete [] buf; + } + + return true; +} + + +void COpenGL3MaterialRenderer::setBasicRenderStates(const SMaterial& material, + const SMaterial& lastMaterial, + bool resetAllRenderstates) +{ + Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); +} + +s32 COpenGL3MaterialRenderer::getVertexShaderConstantID(const c8* name) +{ + return getPixelShaderConstantID(name); +} + +s32 COpenGL3MaterialRenderer::getPixelShaderConstantID(const c8* name) +{ + for (u32 i = 0; i < UniformInfo.size(); ++i) + { + if (UniformInfo[i].name == name) + return i; + } + + return -1; +} + +void COpenGL3MaterialRenderer::setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount) +{ + os::Printer::log("Cannot set constant, please use high level shader call instead.", ELL_WARNING); +} + +void COpenGL3MaterialRenderer::setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount) +{ + os::Printer::log("Cannot set constant, use high level shader call.", ELL_WARNING); +} + +bool COpenGL3MaterialRenderer::setVertexShaderConstant(s32 index, const f32* floats, int count) +{ + return setPixelShaderConstant(index, floats, count); +} + +bool COpenGL3MaterialRenderer::setVertexShaderConstant(s32 index, const s32* ints, int count) +{ + return setPixelShaderConstant(index, ints, count); +} + +bool COpenGL3MaterialRenderer::setVertexShaderConstant(s32 index, const u32* ints, int count) +{ + return setPixelShaderConstant(index, ints, count); +} + +bool COpenGL3MaterialRenderer::setPixelShaderConstant(s32 index, const f32* floats, int count) +{ + if(index < 0 || UniformInfo[index].location < 0) + return false; + + bool status = true; + + switch (UniformInfo[index].type) + { + case GL_FLOAT: + glUniform1fv(UniformInfo[index].location, count, floats); + break; + case GL_FLOAT_VEC2: + glUniform2fv(UniformInfo[index].location, count/2, floats); + break; + case GL_FLOAT_VEC3: + glUniform3fv(UniformInfo[index].location, count/3, floats); + break; + case GL_FLOAT_VEC4: + glUniform4fv(UniformInfo[index].location, count/4, floats); + break; + case GL_FLOAT_MAT2: + glUniformMatrix2fv(UniformInfo[index].location, count/4, false, floats); + break; + case GL_FLOAT_MAT3: + glUniformMatrix3fv(UniformInfo[index].location, count/9, false, floats); + break; + case GL_FLOAT_MAT4: + glUniformMatrix4fv(UniformInfo[index].location, count/16, false, floats); + break; + case GL_SAMPLER_2D: + case GL_SAMPLER_CUBE: + { + if(floats) + { + const GLint id = (GLint)(*floats); + glUniform1iv(UniformInfo[index].location, 1, &id); + } + else + status = false; + } + break; + default: + status = false; + break; + } + + return status; +} + +bool COpenGL3MaterialRenderer::setPixelShaderConstant(s32 index, const s32* ints, int count) +{ + if(index < 0 || UniformInfo[index].location < 0) + return false; + + bool status = true; + + switch (UniformInfo[index].type) + { + case GL_INT: + case GL_BOOL: + glUniform1iv(UniformInfo[index].location, count, ints); + break; + case GL_INT_VEC2: + case GL_BOOL_VEC2: + glUniform2iv(UniformInfo[index].location, count/2, ints); + break; + case GL_INT_VEC3: + case GL_BOOL_VEC3: + glUniform3iv(UniformInfo[index].location, count/3, ints); + break; + case GL_INT_VEC4: + case GL_BOOL_VEC4: + glUniform4iv(UniformInfo[index].location, count/4, ints); + break; + case GL_SAMPLER_2D: + case GL_SAMPLER_CUBE: + glUniform1iv(UniformInfo[index].location, 1, ints); + break; + default: + status = false; + break; + } + + return status; +} + +bool COpenGL3MaterialRenderer::setPixelShaderConstant(s32 index, const u32* ints, int count) +{ + os::Printer::log("Unsigned int support needs at least GLES 3.0", ELL_WARNING); + return false; +} + +IVideoDriver* COpenGL3MaterialRenderer::getVideoDriver() +{ + return Driver; +} + +} +} diff --git a/source/Irrlicht/OpenGL/MaterialRenderer.h b/source/Irrlicht/OpenGL/MaterialRenderer.h index dbac6cf..f9282cc 100644 --- a/source/Irrlicht/OpenGL/MaterialRenderer.h +++ b/source/Irrlicht/OpenGL/MaterialRenderer.h @@ -1,99 +1,99 @@ -// Copyright (C) 2014 Patryk Nadrowski -// This file is part of the "Irrlicht Engine". -// For conditions of distribution and use, see copyright notice in irrlicht.h - -#pragma once - -#include "EMaterialTypes.h" -#include "IMaterialRenderer.h" -#include "IMaterialRendererServices.h" -#include "IGPUProgrammingServices.h" -#include "irrArray.h" -#include "irrString.h" - -#include "Common.h" - -namespace irr -{ -namespace video -{ - -class COpenGL3DriverBase; - -class COpenGL3MaterialRenderer : public IMaterialRenderer, public IMaterialRendererServices -{ -public: - - COpenGL3MaterialRenderer( - COpenGL3DriverBase* driver, - s32& outMaterialTypeNr, - const c8* vertexShaderProgram = 0, - const c8* pixelShaderProgram = 0, - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = EMT_SOLID, - s32 userData = 0); - - virtual ~COpenGL3MaterialRenderer(); - - GLuint getProgram() const; - - virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, - bool resetAllRenderstates, IMaterialRendererServices* services); - - virtual bool OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype); - - virtual void OnUnsetMaterial(); - - virtual bool isTransparent() const; - - virtual s32 getRenderCapability() const; - - void setBasicRenderStates(const SMaterial& material, const SMaterial& lastMaterial, bool resetAllRenderstates) override; - - s32 getVertexShaderConstantID(const c8* name) override; - s32 getPixelShaderConstantID(const c8* name) override; - void setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount=1) override; - void setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount=1) override; - bool setVertexShaderConstant(s32 index, const f32* floats, int count) override; - bool setVertexShaderConstant(s32 index, const s32* ints, int count) override; - bool setVertexShaderConstant(s32 index, const u32* ints, int count) override; - bool setPixelShaderConstant(s32 index, const f32* floats, int count) override; - bool setPixelShaderConstant(s32 index, const s32* ints, int count) override; - bool setPixelShaderConstant(s32 index, const u32* ints, int count) override; - - IVideoDriver* getVideoDriver() override; - -protected: - - COpenGL3MaterialRenderer(COpenGL3DriverBase* driver, - IShaderConstantSetCallBack* callback = 0, - E_MATERIAL_TYPE baseMaterial = EMT_SOLID, - s32 userData = 0); - - void init(s32& outMaterialTypeNr, const c8* vertexShaderProgram, const c8* pixelShaderProgram, bool addMaterial = true); - - bool createShader(GLenum shaderType, const char* shader); - bool linkProgram(); - - COpenGL3DriverBase* Driver; - IShaderConstantSetCallBack* CallBack; - - bool Alpha; - bool Blending; - bool FixedBlending; - - struct SUniformInfo - { - core::stringc name; - GLenum type; - GLint location; - }; - - GLuint Program; - core::array UniformInfo; - s32 UserData; -}; - - -} -} +// Copyright (C) 2014 Patryk Nadrowski +// This file is part of the "Irrlicht Engine". +// For conditions of distribution and use, see copyright notice in irrlicht.h + +#pragma once + +#include "EMaterialTypes.h" +#include "IMaterialRenderer.h" +#include "IMaterialRendererServices.h" +#include "IGPUProgrammingServices.h" +#include "irrArray.h" +#include "irrString.h" + +#include "Common.h" + +namespace irr +{ +namespace video +{ + +class COpenGL3DriverBase; + +class COpenGL3MaterialRenderer : public IMaterialRenderer, public IMaterialRendererServices +{ +public: + + COpenGL3MaterialRenderer( + COpenGL3DriverBase* driver, + s32& outMaterialTypeNr, + const c8* vertexShaderProgram = 0, + const c8* pixelShaderProgram = 0, + IShaderConstantSetCallBack* callback = 0, + E_MATERIAL_TYPE baseMaterial = EMT_SOLID, + s32 userData = 0); + + virtual ~COpenGL3MaterialRenderer(); + + GLuint getProgram() const; + + virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, + bool resetAllRenderstates, IMaterialRendererServices* services); + + virtual bool OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype); + + virtual void OnUnsetMaterial(); + + virtual bool isTransparent() const; + + virtual s32 getRenderCapability() const; + + void setBasicRenderStates(const SMaterial& material, const SMaterial& lastMaterial, bool resetAllRenderstates) override; + + s32 getVertexShaderConstantID(const c8* name) override; + s32 getPixelShaderConstantID(const c8* name) override; + void setVertexShaderConstant(const f32* data, s32 startRegister, s32 constantAmount=1) override; + void setPixelShaderConstant(const f32* data, s32 startRegister, s32 constantAmount=1) override; + bool setVertexShaderConstant(s32 index, const f32* floats, int count) override; + bool setVertexShaderConstant(s32 index, const s32* ints, int count) override; + bool setVertexShaderConstant(s32 index, const u32* ints, int count) override; + bool setPixelShaderConstant(s32 index, const f32* floats, int count) override; + bool setPixelShaderConstant(s32 index, const s32* ints, int count) override; + bool setPixelShaderConstant(s32 index, const u32* ints, int count) override; + + IVideoDriver* getVideoDriver() override; + +protected: + + COpenGL3MaterialRenderer(COpenGL3DriverBase* driver, + IShaderConstantSetCallBack* callback = 0, + E_MATERIAL_TYPE baseMaterial = EMT_SOLID, + s32 userData = 0); + + void init(s32& outMaterialTypeNr, const c8* vertexShaderProgram, const c8* pixelShaderProgram, bool addMaterial = true); + + bool createShader(GLenum shaderType, const char* shader); + bool linkProgram(); + + COpenGL3DriverBase* Driver; + IShaderConstantSetCallBack* CallBack; + + bool Alpha; + bool Blending; + bool FixedBlending; + + struct SUniformInfo + { + core::stringc name; + GLenum type; + GLint location; + }; + + GLuint Program; + core::array UniformInfo; + s32 UserData; +}; + + +} +} diff --git a/source/Irrlicht/OpenGL/Renderer2D.cpp b/source/Irrlicht/OpenGL/Renderer2D.cpp index 8bedb17..96bdbda 100644 --- a/source/Irrlicht/OpenGL/Renderer2D.cpp +++ b/source/Irrlicht/OpenGL/Renderer2D.cpp @@ -1,83 +1,83 @@ -// Copyright (C) 2014 Patryk Nadrowski -// This file is part of the "Irrlicht Engine". -// For conditions of distribution and use, see copyright notice in Irrlicht.h - -#include "Renderer2D.h" - -#include "IGPUProgrammingServices.h" -#include "os.h" - -#include "Driver.h" - -#include "COpenGLCoreFeature.h" -#include "COpenGLCoreTexture.h" -#include "COpenGLCoreCacheHandler.h" - -namespace irr -{ -namespace video -{ - -COpenGL3Renderer2D::COpenGL3Renderer2D(const c8* vertexShaderProgram, const c8* pixelShaderProgram, COpenGL3DriverBase* driver, bool withTexture) : - COpenGL3MaterialRenderer(driver, 0, EMT_SOLID), - WithTexture(withTexture) -{ -#ifdef _DEBUG - setDebugName("Renderer2D"); -#endif - - int Temp = 0; - - init(Temp, vertexShaderProgram, pixelShaderProgram, false); - - COpenGL3CacheHandler* cacheHandler = Driver->getCacheHandler(); - - cacheHandler->setProgram(Program); - - // These states don't change later. - - ThicknessID = getPixelShaderConstantID("uThickness"); - if ( WithTexture ) - { - TextureUsageID = getPixelShaderConstantID("uTextureUsage"); - s32 TextureUnitID = getPixelShaderConstantID("uTextureUnit"); - - s32 TextureUnit = 0; - setPixelShaderConstant(TextureUnitID, &TextureUnit, 1); - - s32 TextureUsage = 0; - setPixelShaderConstant(TextureUsageID, &TextureUsage, 1); - } - - cacheHandler->setProgram(0); -} - -COpenGL3Renderer2D::~COpenGL3Renderer2D() -{ -} - -void COpenGL3Renderer2D::OnSetMaterial(const video::SMaterial& material, - const video::SMaterial& lastMaterial, - bool resetAllRenderstates, - video::IMaterialRendererServices* services) -{ - Driver->getCacheHandler()->setProgram(Program); - Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); - - f32 Thickness = (material.Thickness > 0.f) ? material.Thickness : 1.f; - setPixelShaderConstant(ThicknessID, &Thickness, 1); - - if ( WithTexture ) - { - s32 TextureUsage = material.TextureLayer[0].Texture ? 1 : 0; - setPixelShaderConstant(TextureUsageID, &TextureUsage, 1); - } -} - -bool COpenGL3Renderer2D::OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype) -{ - return true; -} - -} -} +// Copyright (C) 2014 Patryk Nadrowski +// This file is part of the "Irrlicht Engine". +// For conditions of distribution and use, see copyright notice in Irrlicht.h + +#include "Renderer2D.h" + +#include "IGPUProgrammingServices.h" +#include "os.h" + +#include "Driver.h" + +#include "COpenGLCoreFeature.h" +#include "COpenGLCoreTexture.h" +#include "COpenGLCoreCacheHandler.h" + +namespace irr +{ +namespace video +{ + +COpenGL3Renderer2D::COpenGL3Renderer2D(const c8* vertexShaderProgram, const c8* pixelShaderProgram, COpenGL3DriverBase* driver, bool withTexture) : + COpenGL3MaterialRenderer(driver, 0, EMT_SOLID), + WithTexture(withTexture) +{ +#ifdef _DEBUG + setDebugName("Renderer2D"); +#endif + + int Temp = 0; + + init(Temp, vertexShaderProgram, pixelShaderProgram, false); + + COpenGL3CacheHandler* cacheHandler = Driver->getCacheHandler(); + + cacheHandler->setProgram(Program); + + // These states don't change later. + + ThicknessID = getPixelShaderConstantID("uThickness"); + if ( WithTexture ) + { + TextureUsageID = getPixelShaderConstantID("uTextureUsage"); + s32 TextureUnitID = getPixelShaderConstantID("uTextureUnit"); + + s32 TextureUnit = 0; + setPixelShaderConstant(TextureUnitID, &TextureUnit, 1); + + s32 TextureUsage = 0; + setPixelShaderConstant(TextureUsageID, &TextureUsage, 1); + } + + cacheHandler->setProgram(0); +} + +COpenGL3Renderer2D::~COpenGL3Renderer2D() +{ +} + +void COpenGL3Renderer2D::OnSetMaterial(const video::SMaterial& material, + const video::SMaterial& lastMaterial, + bool resetAllRenderstates, + video::IMaterialRendererServices* services) +{ + Driver->getCacheHandler()->setProgram(Program); + Driver->setBasicRenderStates(material, lastMaterial, resetAllRenderstates); + + f32 Thickness = (material.Thickness > 0.f) ? material.Thickness : 1.f; + setPixelShaderConstant(ThicknessID, &Thickness, 1); + + if ( WithTexture ) + { + s32 TextureUsage = material.TextureLayer[0].Texture ? 1 : 0; + setPixelShaderConstant(TextureUsageID, &TextureUsage, 1); + } +} + +bool COpenGL3Renderer2D::OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype) +{ + return true; +} + +} +} diff --git a/source/Irrlicht/OpenGL/Renderer2D.h b/source/Irrlicht/OpenGL/Renderer2D.h index 806d1e7..426a8b7 100644 --- a/source/Irrlicht/OpenGL/Renderer2D.h +++ b/source/Irrlicht/OpenGL/Renderer2D.h @@ -1,33 +1,33 @@ -// Copyright (C) 2014 Patryk Nadrowski -// This file is part of the "Irrlicht Engine". -// For conditions of distribution and use, see copyright notice in Irrlicht.h - -#pragma once - -#include "MaterialRenderer.h" - -namespace irr -{ -namespace video -{ - -class COpenGL3Renderer2D : public COpenGL3MaterialRenderer -{ -public: - COpenGL3Renderer2D(const c8* vertexShaderProgram, const c8* pixelShaderProgram, COpenGL3DriverBase* driver, bool withTexture); - ~COpenGL3Renderer2D(); - - virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, - bool resetAllRenderstates, IMaterialRendererServices* services); - - virtual bool OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype); - -protected: - bool WithTexture; - s32 ThicknessID; - s32 TextureUsageID; -}; - - -} -} +// Copyright (C) 2014 Patryk Nadrowski +// This file is part of the "Irrlicht Engine". +// For conditions of distribution and use, see copyright notice in Irrlicht.h + +#pragma once + +#include "MaterialRenderer.h" + +namespace irr +{ +namespace video +{ + +class COpenGL3Renderer2D : public COpenGL3MaterialRenderer +{ +public: + COpenGL3Renderer2D(const c8* vertexShaderProgram, const c8* pixelShaderProgram, COpenGL3DriverBase* driver, bool withTexture); + ~COpenGL3Renderer2D(); + + virtual void OnSetMaterial(const SMaterial& material, const SMaterial& lastMaterial, + bool resetAllRenderstates, IMaterialRendererServices* services); + + virtual bool OnRender(IMaterialRendererServices* service, E_VERTEX_TYPE vtxtype); + +protected: + bool WithTexture; + s32 ThicknessID; + s32 TextureUsageID; +}; + + +} +}