Merge branch '12.0' into metal

This commit is contained in:
Alex Szpakowski
2020-02-15 14:18:35 -04:00
53 changed files with 3120 additions and 3687 deletions
-626
View File
@@ -1,626 +0,0 @@
/**
* Copyright (c) 2006-2020 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "Canvas.h"
#include "graphics/Graphics.h"
#include "Graphics.h"
#include <algorithm> // For min/max
namespace love
{
namespace graphics
{
namespace opengl
{
static GLenum createFBO(GLuint &framebuffer, TextureType texType, PixelFormat format, GLuint texture, int layers, int nb_mips)
{
// get currently bound fbo to reset to it later
GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
glGenFramebuffers(1, &framebuffer);
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, framebuffer);
if (texture != 0)
{
if (isPixelFormatDepthStencil(format) && (GLAD_ES_VERSION_3_0 || !GLAD_ES_VERSION_2_0))
{
// glDrawBuffers is an ext in GL2. glDrawBuffer doesn't exist in ES3.
GLenum none = GL_NONE;
if (GLAD_ES_VERSION_3_0)
glDrawBuffers(1, &none);
else
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
}
bool unusedSRGB = false;
OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(format, false, unusedSRGB);
int faces = texType == TEXTURE_CUBE ? 6 : 1;
// Make sure all faces and layers of the texture are initialized to
// transparent black. This is unfortunately probably pretty slow for
// 2D-array and 3D textures with a lot of layers...
for (int mip = nb_mips - 1; mip >= 0; mip--)
{
int nlayers = layers;
if (texType == TEXTURE_VOLUME)
nlayers = std::max(layers >> mip, 1);
for (int layer = nlayers - 1; layer >= 0; layer--)
{
for (int face = faces - 1; face >= 0; face--)
{
for (GLenum attachment : fmt.framebufferAttachments)
{
if (attachment == GL_NONE)
continue;
gl.framebufferTexture(attachment, texType, texture, mip, layer, face);
}
if (isPixelFormatDepthStencil(format))
{
bool hadDepthWrites = gl.hasDepthWrites();
if (!hadDepthWrites) // glDepthMask also affects glClear.
gl.setDepthWrites(true);
gl.clearDepth(1.0);
glClearStencil(0);
glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
if (!hadDepthWrites)
gl.setDepthWrites(hadDepthWrites);
}
else
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
}
}
}
}
}
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
return status;
}
static bool createRenderbuffer(int width, int height, int &samples, PixelFormat pixelformat, GLuint &buffer)
{
int reqsamples = samples;
bool unusedSRGB = false;
OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(pixelformat, true, unusedSRGB);
GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
// Temporary FBO used to clear the renderbuffer.
GLuint fbo = 0;
glGenFramebuffers(1, &fbo);
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
if (isPixelFormatDepthStencil(pixelformat) && (GLAD_ES_VERSION_3_0 || !GLAD_ES_VERSION_2_0))
{
// glDrawBuffers is an ext in GL2. glDrawBuffer doesn't exist in ES3.
GLenum none = GL_NONE;
if (GLAD_ES_VERSION_3_0)
glDrawBuffers(1, &none);
else
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
}
glGenRenderbuffers(1, &buffer);
glBindRenderbuffer(GL_RENDERBUFFER, buffer);
if (samples > 1)
glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, fmt.internalformat, width, height);
else
glRenderbufferStorage(GL_RENDERBUFFER, fmt.internalformat, width, height);
for (GLenum attachment : fmt.framebufferAttachments)
{
if (attachment != GL_NONE)
glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, buffer);
}
if (samples > 1)
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
else
samples = 0;
glBindRenderbuffer(GL_RENDERBUFFER, 0);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status == GL_FRAMEBUFFER_COMPLETE && (reqsamples <= 1 || samples > 1))
{
if (isPixelFormatDepthStencil(pixelformat))
{
bool hadDepthWrites = gl.hasDepthWrites();
if (!hadDepthWrites) // glDepthMask also affects glClear.
gl.setDepthWrites(true);
gl.clearDepth(1.0);
glClearStencil(0);
glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
if (!hadDepthWrites)
gl.setDepthWrites(hadDepthWrites);
}
else
{
// Initialize the buffer to transparent black.
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
}
}
else
{
glDeleteRenderbuffers(1, &buffer);
buffer = 0;
samples = 0;
}
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
gl.deleteFramebuffer(fbo);
return status == GL_FRAMEBUFFER_COMPLETE;
}
Canvas::Canvas(const Settings &settings)
: love::graphics::Canvas(settings)
, fbo(0)
, texture(0)
, renderbuffer(0)
, actualSamples(0)
{
format = getSizedFormat(format);
initQuad();
loadVolatile();
if (status != GL_FRAMEBUFFER_COMPLETE)
throw love::Exception("Cannot create Canvas: %s", OpenGL::framebufferStatusString(status));
}
Canvas::~Canvas()
{
unloadVolatile();
}
bool Canvas::loadVolatile()
{
if (texture != 0)
return true;
OpenGL::TempDebugGroup debuggroup("Canvas load");
fbo = texture = 0;
renderbuffer = 0;
status = GL_FRAMEBUFFER_COMPLETE;
// getMaxRenderbufferSamples will be 0 on systems that don't support
// multisampled renderbuffers / don't export FBO multisample extensions.
actualSamples = std::min(getRequestedMSAA(), gl.getMaxRenderbufferSamples());
actualSamples = std::max(actualSamples, 0);
actualSamples = actualSamples == 1 ? 0 : actualSamples;
if (isReadable())
{
glGenTextures(1, &texture);
gl.bindTextureToUnit(this, 0, false);
GLenum gltype = OpenGL::getGLTextureType(texType);
if (GLAD_ANGLE_texture_usage)
glTexParameteri(gltype, GL_TEXTURE_USAGE_ANGLE, GL_FRAMEBUFFER_ATTACHMENT_ANGLE);
setFilter(filter);
setWrap(wrap);
setMipmapSharpness(mipmapSharpness);
setDepthSampleMode(depthCompareMode);
while (glGetError() != GL_NO_ERROR)
/* Clear the error buffer. */;
bool isSRGB = format == PIXELFORMAT_sRGBA8_UNORM;
if (!gl.rawTexStorage(texType, mipmapCount, format, isSRGB, pixelWidth, pixelHeight, texType == TEXTURE_VOLUME ? depth : layers))
{
status = GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
return false;
}
if (glGetError() != GL_NO_ERROR)
{
gl.deleteTexture(texture);
texture = 0;
status = GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
return false;
}
// Create a canvas-local FBO used for glReadPixels as well as MSAA blitting.
status = createFBO(fbo, texType, format, texture, texType == TEXTURE_VOLUME ? depth : layers, mipmapCount);
if (status != GL_FRAMEBUFFER_COMPLETE)
{
if (fbo != 0)
{
gl.deleteFramebuffer(fbo);
fbo = 0;
}
return false;
}
}
if (!isReadable() || actualSamples > 0)
createRenderbuffer(pixelWidth, pixelHeight, actualSamples, format, renderbuffer);
int64 memsize = getPixelFormatSize(format) * pixelWidth * pixelHeight;
if (getMipmapCount() > 1)
memsize *= 1.33334;
if (actualSamples > 1 && isReadable())
memsize += getPixelFormatSize(format) * pixelWidth * pixelHeight * actualSamples;
else if (actualSamples > 1)
memsize *= actualSamples;
setGraphicsMemorySize(memsize);
return true;
}
void Canvas::unloadVolatile()
{
if (fbo != 0 || renderbuffer != 0 || texture != 0)
{
// This is a bit ugly, but we need some way to destroy the cached FBO
// when this Canvas' texture is destroyed.
auto gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
if (gfx != nullptr)
gfx->cleanupCanvas(this);
}
if (fbo != 0)
gl.deleteFramebuffer(fbo);
if (renderbuffer != 0)
glDeleteRenderbuffers(1, &renderbuffer);
if (texture != 0)
gl.deleteTexture(texture);
fbo = 0;
renderbuffer = 0;
texture = 0;
setGraphicsMemorySize(0);
}
void Canvas::setFilter(const Texture::Filter &f)
{
Texture::setFilter(f);
if (!OpenGL::hasTextureFilteringSupport(getPixelFormat()))
{
filter.mag = filter.min = FILTER_NEAREST;
if (filter.mipmap == FILTER_LINEAR)
filter.mipmap = FILTER_NEAREST;
}
gl.bindTextureToUnit(this, 0, false);
gl.setTextureFilter(texType, filter);
}
bool Canvas::setWrap(const Texture::Wrap &w)
{
Graphics::flushStreamDrawsGlobal();
bool success = true;
bool forceclamp = texType == TEXTURE_CUBE;
wrap = w;
// If we only have limited NPOT support then the wrap mode must be CLAMP.
if ((GLAD_ES_VERSION_2_0 && !(GLAD_ES_VERSION_3_0 || GLAD_OES_texture_npot))
&& (pixelWidth != nextP2(pixelWidth) || pixelHeight != nextP2(pixelHeight) || depth != nextP2(depth)))
{
forceclamp = true;
}
if (forceclamp)
{
if (wrap.s != WRAP_CLAMP || wrap.t != WRAP_CLAMP || wrap.r != WRAP_CLAMP)
success = false;
wrap.s = wrap.t = wrap.r = WRAP_CLAMP;
}
if (!gl.isClampZeroOneTextureWrapSupported())
{
if (isClampZeroOrOne(wrap.s)) wrap.s = WRAP_CLAMP;
if (isClampZeroOrOne(wrap.t)) wrap.t = WRAP_CLAMP;
if (isClampZeroOrOne(wrap.r)) wrap.r = WRAP_CLAMP;
}
gl.bindTextureToUnit(this, 0, false);
gl.setTextureWrap(texType, wrap);
return success;
}
bool Canvas::setMipmapSharpness(float sharpness)
{
if (!gl.isSamplerLODBiasSupported())
return false;
Graphics::flushStreamDrawsGlobal();
float maxbias = gl.getMaxLODBias();
if (maxbias > 0.01f)
maxbias -= 0.0f;
mipmapSharpness = std::min(std::max(sharpness, -maxbias), maxbias);
gl.bindTextureToUnit(this, 0, false);
// negative bias is sharper
glTexParameterf(gl.getGLTextureType(texType), GL_TEXTURE_LOD_BIAS, -mipmapSharpness);
return true;
}
void Canvas::setDepthSampleMode(Optional<CompareMode> mode)
{
Texture::setDepthSampleMode(mode);
bool supported = gl.isDepthCompareSampleSupported();
if (mode.hasValue)
{
if (!supported)
throw love::Exception("Depth comparison sampling in shaders is not supported on this system.");
Graphics::flushStreamDrawsGlobal();
gl.bindTextureToUnit(texType, texture, 0, false);
GLenum gltextype = OpenGL::getGLTextureType(texType);
// See the comment in renderstate.h
GLenum glmode = OpenGL::getGLCompareMode(getReversedCompareMode(mode.value));
glTexParameteri(gltextype, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
glTexParameteri(gltextype, GL_TEXTURE_COMPARE_FUNC, glmode);
}
else if (isPixelFormatDepth(format) && supported)
{
Graphics::flushStreamDrawsGlobal();
gl.bindTextureToUnit(texType, texture, 0, false);
GLenum gltextype = OpenGL::getGLTextureType(texType);
glTexParameteri(gltextype, GL_TEXTURE_COMPARE_MODE, GL_NONE);
}
depthCompareMode = mode;
}
ptrdiff_t Canvas::getHandle() const
{
return texture;
}
love::image::ImageData *Canvas::newImageData(love::image::Image *module, int slice, int mipmap, const Rect &r)
{
love::image::ImageData *data = love::graphics::Canvas::newImageData(module, slice, mipmap, r);
bool isSRGB = false;
OpenGL::TextureFormat fmt = gl.convertPixelFormat(data->getFormat(), false, isSRGB);
GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, getFBO());
if (slice > 0 || mipmap > 0)
{
int layer = texType == TEXTURE_CUBE ? 0 : slice;
int face = texType == TEXTURE_CUBE ? slice : 0;
gl.framebufferTexture(GL_COLOR_ATTACHMENT0, texType, texture, mipmap, layer, face);
}
glReadPixels(r.x, r.y, r.w, r.h, fmt.externalformat, fmt.type, data->getData());
if (slice > 0 || mipmap > 0)
gl.framebufferTexture(GL_COLOR_ATTACHMENT0, texType, texture, 0, 0, 0);
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
return data;
}
void Canvas::generateMipmaps()
{
if (getMipmapCount() == 1 || getMipmapMode() == MIPMAPS_NONE)
throw love::Exception("generateMipmaps can only be called on a Canvas which was created with mipmaps enabled.");
gl.bindTextureToUnit(this, 0, false);
GLenum gltextype = OpenGL::getGLTextureType(texType);
if (gl.bugs.generateMipmapsRequiresTexture2DEnable)
glEnable(gltextype);
glGenerateMipmap(gltextype);
}
PixelFormat Canvas::getSizedFormat(PixelFormat format)
{
switch (format)
{
case PIXELFORMAT_NORMAL:
if (isGammaCorrect())
return PIXELFORMAT_sRGBA8_UNORM;
else if (!OpenGL::isPixelFormatSupported(PIXELFORMAT_RGBA8_UNORM, true, true, false))
// 32-bit render targets don't have guaranteed support on GLES2.
return PIXELFORMAT_RGBA4_UNORM;
else
return PIXELFORMAT_RGBA8_UNORM;
case PIXELFORMAT_HDR:
return PIXELFORMAT_RGBA16_FLOAT;
default:
return format;
}
}
bool Canvas::isSupported()
{
return GLAD_ES_VERSION_2_0 || GLAD_VERSION_3_0 || GLAD_ARB_framebuffer_object || GLAD_EXT_framebuffer_object;
}
bool Canvas::isMultiFormatMultiCanvasSupported()
{
return gl.getMaxRenderTargets() > 1 && (GLAD_ES_VERSION_3_0 || GLAD_VERSION_3_0 || GLAD_ARB_framebuffer_object);
}
Canvas::SupportedFormat Canvas::supportedFormats[] = {};
Canvas::SupportedFormat Canvas::checkedFormats[] = {};
bool Canvas::isFormatSupported(PixelFormat format)
{
return isFormatSupported(format, !isPixelFormatDepthStencil(format));
}
bool Canvas::isFormatSupported(PixelFormat format, bool readable)
{
if (!isSupported())
return false;
const char *fstr = "?";
love::getConstant(format, fstr);
bool supported = true;
format = getSizedFormat(format);
if (!OpenGL::isPixelFormatSupported(format, true, readable, false))
return false;
if (checkedFormats[format].get(readable))
return supportedFormats[format].get(readable);
// Even though we might have the necessary OpenGL version or extension,
// drivers are still allowed to throw FRAMEBUFFER_UNSUPPORTED when attaching
// a texture to a FBO whose format the driver doesn't like. So we should
// test with an actual FBO.
GLuint texture = 0;
GLuint renderbuffer = 0;
// Avoid the test for depth/stencil formats - not every GL version
// guarantees support for depth/stencil-only render targets (which we would
// need for the test below to work), and we already do some finagling in
// convertPixelFormat to try to use the best-supported internal
// depth/stencil format for a particular driver.
if (isPixelFormatDepthStencil(format))
{
checkedFormats[format].set(readable, true);
supportedFormats[format].set(readable, true);
return true;
}
bool unusedSRGB = false;
OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(format, readable, unusedSRGB);
GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
GLuint fbo = 0;
glGenFramebuffers(1, &fbo);
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
// Make sure at least something is bound to a color attachment. I believe
// this is required on ES2 but I'm not positive.
if (isPixelFormatDepthStencil(format))
gl.framebufferTexture(GL_COLOR_ATTACHMENT0, TEXTURE_2D, gl.getDefaultTexture(TEXTURE_2D), 0, 0, 0);
if (readable)
{
glGenTextures(1, &texture);
gl.bindTextureToUnit(TEXTURE_2D, texture, 0, false);
Texture::Filter f;
f.min = f.mag = Texture::FILTER_NEAREST;
gl.setTextureFilter(TEXTURE_2D, f);
Texture::Wrap w;
gl.setTextureWrap(TEXTURE_2D, w);
unusedSRGB = false;
gl.rawTexStorage(TEXTURE_2D, 1, format, unusedSRGB, 1, 1);
}
else
{
glGenRenderbuffers(1, &renderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
glRenderbufferStorage(GL_RENDERBUFFER, fmt.internalformat, 1, 1);
}
for (GLenum attachment : fmt.framebufferAttachments)
{
if (attachment == GL_NONE)
continue;
if (readable)
gl.framebufferTexture(attachment, TEXTURE_2D, texture, 0, 0, 0);
else
glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, renderbuffer);
}
supported = glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
gl.deleteFramebuffer(fbo);
if (texture != 0)
gl.deleteTexture(texture);
if (renderbuffer != 0)
glDeleteRenderbuffers(1, &renderbuffer);
// Cache the result so we don't do this for every isFormatSupported call.
checkedFormats[format].set(readable, true);
supportedFormats[format].set(readable, supported);
return supported;
}
void Canvas::resetFormatSupport()
{
for (int i = 0; i < (int)PIXELFORMAT_MAX_ENUM; i++)
{
checkedFormats[i].readable = false;
checkedFormats[i].nonreadable = false;
}
}
} // opengl
} // graphics
} // love
-120
View File
@@ -1,120 +0,0 @@
/**
* Copyright (c) 2006-2020 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#ifndef LOVE_GRAPHICS_OPENGL_CANVAS_H
#define LOVE_GRAPHICS_OPENGL_CANVAS_H
#include "common/config.h"
#include "common/Color.h"
#include "common/int.h"
#include "graphics/Canvas.h"
#include "graphics/Volatile.h"
#include "OpenGL.h"
namespace love
{
namespace graphics
{
namespace opengl
{
class Canvas final : public love::graphics::Canvas, public Volatile
{
public:
Canvas(const Settings &settings);
virtual ~Canvas();
// Implements Volatile.
bool loadVolatile() override;
void unloadVolatile() override;
// Implements Texture.
void setFilter(const Texture::Filter &f) override;
bool setWrap(const Texture::Wrap &w) override;
bool setMipmapSharpness(float sharpness) override;
void setDepthSampleMode(Optional<CompareMode> mode) override;
ptrdiff_t getHandle() const override;
love::image::ImageData *newImageData(love::image::Image *module, int slice, int mipmap, const Rect &rect) override;
void generateMipmaps() override;
int getMSAA() const override
{
return actualSamples;
}
ptrdiff_t getRenderTargetHandle() const override
{
return renderbuffer != 0 ? renderbuffer : texture;
}
inline GLuint getFBO() const
{
return fbo;
}
static PixelFormat getSizedFormat(PixelFormat format);
static bool isSupported();
static bool isMultiFormatMultiCanvasSupported();
static bool isFormatSupported(PixelFormat format, bool readable);
static bool isFormatSupported(PixelFormat format);
static void resetFormatSupport();
private:
struct SupportedFormat
{
bool readable = false;
bool nonreadable = false;
bool get(bool getreadable)
{
return getreadable ? readable : nonreadable;
}
void set(bool setreadable, bool val)
{
if (setreadable)
readable = val;
else
nonreadable = val;
}
};
GLuint fbo;
GLuint texture;
GLuint renderbuffer;
GLenum status;
int actualSamples;
static SupportedFormat supportedFormats[PIXELFORMAT_MAX_ENUM];
static SupportedFormat checkedFormats[PIXELFORMAT_MAX_ENUM];
}; // Canvas
} // opengl
} // graphics
} // love
#endif // LOVE_GRAPHICS_OPENGL_CANVAS_H
+185 -87
View File
@@ -107,9 +107,9 @@ love::graphics::Graphics *createInstance()
Graphics::Graphics()
: windowHasStencil(false)
, mainVAO(0)
, supportedFormats()
{
gl = OpenGL();
Canvas::resetFormatSupport();
auto window = getInstance<love::window::Window>(M_WINDOW);
@@ -146,19 +146,9 @@ love::graphics::StreamBuffer *Graphics::newStreamBuffer(BufferType type, size_t
return CreateStreamBuffer(type, size);
}
love::graphics::Image *Graphics::newImage(const Image::Slices &data, const Image::Settings &settings)
love::graphics::Texture *Graphics::newTexture(const Texture::Settings &settings, const Texture::Slices *data)
{
return new Image(data, settings);
}
love::graphics::Image *Graphics::newImage(TextureType textype, PixelFormat format, int width, int height, int slices, const Image::Settings &settings)
{
return new Image(textype, format, width, height, slices, settings);
}
love::graphics::Canvas *Graphics::newCanvas(const Canvas::Settings &settings)
{
return new Canvas(settings);
return new Texture(settings, data);
}
love::graphics::ShaderStage *Graphics::newShaderStageInternal(ShaderStage::StageType stage, const std::string &cachekey, const std::string &source, bool gles)
@@ -183,7 +173,7 @@ void Graphics::setViewportSize(int width, int height, int pixelwidth, int pixelh
this->pixelWidth = pixelwidth;
this->pixelHeight = pixelheight;
if (!isCanvasActive())
if (!isRenderTargetActive())
{
// Set the viewport to top-left corner.
gl.setViewport({0, 0, pixelwidth, pixelheight});
@@ -250,7 +240,7 @@ bool Graphics::setMode(int width, int height, int pixelwidth, int pixelheight, b
// Set whether drawing converts input from linear -> sRGB colorspace.
if (GLAD_VERSION_3_0 || GLAD_ARB_framebuffer_sRGB || GLAD_EXT_framebuffer_sRGB
|| GLAD_ES_VERSION_3_0 || GLAD_EXT_sRGB)
|| GLAD_ES_VERSION_3_0)
{
if (GLAD_VERSION_1_0 || GLAD_EXT_sRGB_write_control)
gl.setEnableState(OpenGL::ENABLE_FRAMEBUFFER_SRGB, isGammaCorrect());
@@ -328,11 +318,11 @@ void Graphics::unSetMode()
for (const auto &pair : framebufferObjects)
gl.deleteFramebuffer(pair.second);
for (auto temp : temporaryCanvases)
temp.canvas->release();
for (auto temp : temporaryTextures)
temp.texture->release();
framebufferObjects.clear();
temporaryCanvases.clear();
temporaryTextures.clear();
if (mainVAO != 0)
{
@@ -525,24 +515,24 @@ void Graphics::setDebug(bool enable)
::printf("OpenGL debug output enabled (LOVE_GRAPHICS_DEBUG=1)\n");
}
void Graphics::setCanvasInternal(const RenderTargets &rts, int w, int h, int pixelw, int pixelh, bool hasSRGBcanvas)
void Graphics::setRenderTargetsInternal(const RenderTargets &rts, int w, int h, int pixelw, int pixelh, bool hasSRGBtexture)
{
const DisplayState &state = states.back();
OpenGL::TempDebugGroup debuggroup("setCanvas");
OpenGL::TempDebugGroup debuggroup("setRenderTargets");
flushStreamDraws();
endPass();
bool iswindow = rts.getFirstTarget().canvas == nullptr;
bool iswindow = rts.getFirstTarget().texture == nullptr;
vertex::Winding vertexwinding = state.winding;
if (iswindow)
{
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, gl.getDefaultFBO());
// The projection matrix is flipped compared to rendering to a canvas, due
// to OpenGL considering (0,0) bottom-left instead of top-left.
// The projection matrix is flipped compared to rendering to a texture,
// due to OpenGL considering (0,0) bottom-left instead of top-left.
projectionMatrix = Matrix4::ortho(0.0, (float) w, (float) h, 0.0, -10.0f, 10.0f);
}
else
@@ -551,7 +541,7 @@ void Graphics::setCanvasInternal(const RenderTargets &rts, int w, int h, int pix
projectionMatrix = Matrix4::ortho(0.0, (float) w, 0.0, (float) h, -10.0f, 10.0f);
// Flip front face winding when rendering to a canvas, since our
// Flip front face winding when rendering to a texture, since our
// projection matrix is flipped.
vertexwinding = vertexwinding == vertex::WINDING_CW ? vertex::WINDING_CCW : vertex::WINDING_CW;
}
@@ -565,18 +555,18 @@ void Graphics::setCanvasInternal(const RenderTargets &rts, int w, int h, int pix
if (state.scissor)
setScissor(state.scissorRect);
// Make sure the correct sRGB setting is used when drawing to the canvases.
// Make sure the correct sRGB setting is used when drawing to the textures.
if (GLAD_VERSION_1_0 || GLAD_EXT_sRGB_write_control)
{
if (hasSRGBcanvas != gl.isStateEnabled(OpenGL::ENABLE_FRAMEBUFFER_SRGB))
gl.setEnableState(OpenGL::ENABLE_FRAMEBUFFER_SRGB, hasSRGBcanvas);
if (hasSRGBtexture != gl.isStateEnabled(OpenGL::ENABLE_FRAMEBUFFER_SRGB))
gl.setEnableState(OpenGL::ENABLE_FRAMEBUFFER_SRGB, hasSRGBtexture);
}
}
void Graphics::endPass()
{
auto &rts = states.back().renderTargets;
love::graphics::Canvas *depthstencil = rts.depthStencil.canvas.get();
love::graphics::Texture *depthstencil = rts.depthStencil.texture.get();
// Discard the depth/stencil buffer if we're using an internal cached one.
if (depthstencil == nullptr && (rts.temporaryRTFlags & (TEMPORARY_RT_DEPTH | TEMPORARY_RT_STENCIL)) != 0)
@@ -584,15 +574,15 @@ void Graphics::endPass()
// Resolve MSAA buffers. MSAA is only supported for 2D render targets so we
// don't have to worry about resolving to slices.
if (rts.colors.size() > 0 && rts.colors[0].canvas->getMSAA() > 1)
if (rts.colors.size() > 0 && rts.colors[0].texture->getMSAA() > 1)
{
int mip = rts.colors[0].mipmap;
int w = rts.colors[0].canvas->getPixelWidth(mip);
int h = rts.colors[0].canvas->getPixelHeight(mip);
int w = rts.colors[0].texture->getPixelWidth(mip);
int h = rts.colors[0].texture->getPixelHeight(mip);
for (int i = 0; i < (int) rts.colors.size(); i++)
{
Canvas *c = (Canvas *) rts.colors[i].canvas.get();
Texture *c = (Texture *) rts.colors[i].texture.get();
if (!c->isReadable())
continue;
@@ -610,7 +600,7 @@ void Graphics::endPass()
if (depthstencil != nullptr && depthstencil->getMSAA() > 1 && depthstencil->isReadable())
{
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_DRAW, ((Canvas *) depthstencil)->getFBO());
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_DRAW, ((Texture *) depthstencil)->getFBO());
if (GLAD_APPLE_framebuffer_multisample)
glResolveMultisampleFramebufferAPPLE();
@@ -635,12 +625,12 @@ void Graphics::endPass()
for (const auto &rt : rts.colors)
{
if (rt.canvas->getMipmapMode() == Canvas::MIPMAPS_AUTO && rt.mipmap == 0)
rt.canvas->generateMipmaps();
if (rt.texture->getMipmapsMode() == Texture::MIPMAPS_AUTO && rt.mipmap == 0)
rt.texture->generateMipmaps();
}
int dsmipmap = rts.depthStencil.mipmap;
if (depthstencil != nullptr && depthstencil->getMipmapMode() == Canvas::MIPMAPS_AUTO && dsmipmap == 0)
if (depthstencil != nullptr && depthstencil->getMipmapsMode() == Texture::MIPMAPS_AUTO && dsmipmap == 0)
depthstencil->generateMipmaps();
}
@@ -695,10 +685,10 @@ void Graphics::clear(const std::vector<OptionalColorf> &colors, OptionalInt sten
if (colors.size() == 0 && !stencil.hasValue && !depth.hasValue)
return;
int ncolorcanvases = (int) states.back().renderTargets.colors.size();
int ncolorRTs = (int) states.back().renderTargets.colors.size();
int ncolors = (int) colors.size();
if (ncolors <= 1 && ncolorcanvases <= 1)
if (ncolors <= 1 && ncolorRTs <= 1)
{
clear(ncolors > 0 ? colors[0] : OptionalColorf(), stencil, depth);
return;
@@ -707,7 +697,7 @@ void Graphics::clear(const std::vector<OptionalColorf> &colors, OptionalInt sten
flushStreamDraws();
bool drawbuffersmodified = false;
ncolors = std::min(ncolors, ncolorcanvases);
ncolors = std::min(ncolors, ncolorRTs);
for (int i = 0; i < ncolors; i++)
{
@@ -738,10 +728,10 @@ void Graphics::clear(const std::vector<OptionalColorf> &colors, OptionalInt sten
{
GLenum bufs[MAX_COLOR_RENDER_TARGETS];
for (int i = 0; i < ncolorcanvases; i++)
for (int i = 0; i < ncolorRTs; i++)
bufs[i] = GL_COLOR_ATTACHMENT0 + i;
glDrawBuffers(ncolorcanvases, bufs);
glDrawBuffers(ncolorRTs, bufs);
}
GLbitfield flags = 0;
@@ -799,7 +789,7 @@ void Graphics::discard(OpenGL::FramebufferTarget target, const std::vector<bool>
attachments.reserve(colorbuffers.size());
// glDiscardFramebuffer uses different attachment enums for the default FBO.
if (!isCanvasActive() && gl.getDefaultFBO() == 0)
if (!isRenderTargetActive() && gl.getDefaultFBO() == 0)
{
if (colorbuffers.size() > 0 && colorbuffers[0])
attachments.push_back(GL_COLOR);
@@ -834,25 +824,28 @@ void Graphics::discard(OpenGL::FramebufferTarget target, const std::vector<bool>
glDiscardFramebufferEXT(gltarget, (GLint) attachments.size(), &attachments[0]);
}
void Graphics::cleanupCanvas(Canvas *canvas)
void Graphics::cleanupRenderTexture(love::graphics::Texture *texture)
{
if (!texture->isRenderTarget())
return;
for (auto it = framebufferObjects.begin(); it != framebufferObjects.end(); /**/)
{
bool hascanvas = false;
bool hastexture = false;
const auto &rts = it->first;
for (const RenderTarget &rt : rts.colors)
{
if (rt.canvas == canvas)
if (rt.texture == texture)
{
hascanvas = true;
hastexture = true;
break;
}
}
hascanvas = hascanvas || rts.depthStencil.canvas == canvas;
hastexture = hastexture || rts.depthStencil.texture == texture;
if (hascanvas)
if (hastexture)
{
if (isCreated())
gl.deleteFramebuffer(it->second);
@@ -873,8 +866,8 @@ void Graphics::bindCachedFBO(const RenderTargets &targets)
}
else
{
int msaa = targets.getFirstTarget().canvas->getMSAA();
bool hasDS = targets.depthStencil.canvas != nullptr;
int msaa = targets.getFirstTarget().texture->getMSAA();
bool hasDS = targets.depthStencil.texture != nullptr;
glGenFramebuffers(1, &fbo);
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
@@ -882,11 +875,11 @@ void Graphics::bindCachedFBO(const RenderTargets &targets)
int ncolortargets = 0;
GLenum drawbuffers[MAX_COLOR_RENDER_TARGETS];
auto attachCanvas = [&](const RenderTarget &rt)
auto attachRT = [&](const RenderTarget &rt)
{
bool renderbuffer = msaa > 1 || !rt.canvas->isReadable();
bool renderbuffer = msaa > 1 || !rt.texture->isReadable();
bool srgb = false;
OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(rt.canvas->getPixelFormat(), renderbuffer, srgb);
OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(rt.texture->getPixelFormat(), renderbuffer, srgb);
if (fmt.framebufferAttachments[0] == GL_COLOR_ATTACHMENT0)
{
@@ -895,7 +888,7 @@ void Graphics::bindCachedFBO(const RenderTargets &targets)
ncolortargets++;
}
GLuint handle = (GLuint) rt.canvas->getRenderTargetHandle();
GLuint handle = (GLuint) rt.texture->getRenderTargetHandle();
for (GLenum attachment : fmt.framebufferAttachments)
{
@@ -905,7 +898,7 @@ void Graphics::bindCachedFBO(const RenderTargets &targets)
glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, handle);
else
{
TextureType textype = rt.canvas->getTextureType();
TextureType textype = rt.texture->getTextureType();
int layer = textype == TEXTURE_CUBE ? 0 : rt.slice;
int face = textype == TEXTURE_CUBE ? rt.slice : 0;
@@ -917,10 +910,10 @@ void Graphics::bindCachedFBO(const RenderTargets &targets)
};
for (const auto &rt : targets.colors)
attachCanvas(rt);
attachRT(rt);
if (hasDS)
attachCanvas(targets.depthStencil);
attachRT(targets.depthStencil);
if (ncolortargets > 1)
glDrawBuffers(ncolortargets, drawbuffers);
@@ -953,8 +946,8 @@ void Graphics::present(void *screenshotCallbackData)
if (!isActive())
return;
if (isCanvasActive())
throw love::Exception("present cannot be called while a Canvas is active.");
if (isRenderTargetActive())
throw love::Exception("present cannot be called while a render target is active.");
deprecations.draw(this);
@@ -1072,20 +1065,20 @@ void Graphics::present(void *screenshotCallbackData)
// Reset the per-frame stat counts.
drawCalls = 0;
gl.stats.shaderSwitches = 0;
canvasSwitchCount = 0;
renderTargetSwitchCount = 0;
drawCallsBatched = 0;
// This assumes temporary canvases will only be used within a render pass.
for (int i = (int) temporaryCanvases.size() - 1; i >= 0; i--)
// This assumes temporary textures will only be used within a render pass.
for (int i = (int) temporaryTextures.size() - 1; i >= 0; i--)
{
if (temporaryCanvases[i].framesSinceUse >= MAX_TEMPORARY_CANVAS_UNUSED_FRAMES)
if (temporaryTextures[i].framesSinceUse >= MAX_TEMPORARY_TEXTURE_UNUSED_FRAMES)
{
temporaryCanvases[i].canvas->release();
temporaryCanvases[i] = temporaryCanvases.back();
temporaryCanvases.pop_back();
temporaryTextures[i].texture->release();
temporaryTextures[i] = temporaryTextures.back();
temporaryTextures.pop_back();
}
else
temporaryCanvases[i].framesSinceUse++;
temporaryTextures[i].framesSinceUse++;
}
}
@@ -1107,7 +1100,7 @@ void Graphics::setScissor(const Rect &rect)
glrect.h = (int) (rect.h * dpiscale);
// OpenGL's reversed y-coordinate is compensated for in OpenGL::setScissor.
gl.setScissor(glrect, isCanvasActive());
gl.setScissor(glrect, isRenderTargetActive());
state.scissor = true;
state.scissorRect = rect;
@@ -1127,12 +1120,12 @@ void Graphics::setScissor()
void Graphics::drawToStencilBuffer(StencilAction action, int value)
{
const auto &rts = states.back().renderTargets;
love::graphics::Canvas *dscanvas = rts.depthStencil.canvas.get();
love::graphics::Texture *dstexture = rts.depthStencil.texture.get();
if (!isCanvasActive() && !windowHasStencil)
if (!isRenderTargetActive() && !windowHasStencil)
throw love::Exception("The window must have stenciling enabled to draw to the main screen's stencil buffer.");
else if (isCanvasActive() && (rts.temporaryRTFlags & TEMPORARY_RT_STENCIL) == 0 && (dscanvas == nullptr || !isPixelFormatStencil(dscanvas->getPixelFormat())))
throw love::Exception("Drawing to the stencil buffer with a Canvas active requires either stencil=true or a custom stencil-type Canvas to be used, in setCanvas.");
else if (isRenderTargetActive() && (rts.temporaryRTFlags & TEMPORARY_RT_STENCIL) == 0 && (dstexture == nullptr || !isPixelFormatStencil(dstexture->getPixelFormat())))
throw love::Exception("Drawing to the stencil buffer with a render target active requires either stencil=true or a custom stencil-type texture to be used, in setRenderTarget.");
flushStreamDraws();
@@ -1260,7 +1253,7 @@ void Graphics::setFrontFaceWinding(vertex::Winding winding)
state.winding = winding;
if (isCanvasActive())
if (isRenderTargetActive())
winding = winding == vertex::WINDING_CW ? vertex::WINDING_CCW : vertex::WINDING_CW;
glFrontFace(winding == vertex::WINDING_CW ? GL_CW : GL_CCW);
@@ -1292,7 +1285,7 @@ void Graphics::setBlendState(const BlendState &blend)
if (blend.operationRGB == BLENDOP_MAX || blend.operationA == BLENDOP_MAX
|| blend.operationRGB == BLENDOP_MIN || blend.operationA == BLENDOP_MIN)
{
if (!capabilities.features[FEATURE_BLENDMINMAX])
if (!capabilities.features[FEATURE_BLEND_MINMAX])
throw love::Exception("The 'min' and 'max' blend operations are not supported on this system.");
}
@@ -1383,10 +1376,10 @@ void Graphics::getAPIStats(int &shaderswitches) const
void Graphics::initCapabilities()
{
capabilities.features[FEATURE_MULTI_CANVAS_FORMATS] = Canvas::isMultiFormatMultiCanvasSupported();
capabilities.features[FEATURE_MULTI_RENDER_TARGET_FORMATS] = gl.isMultiFormatMRTSupported();
capabilities.features[FEATURE_CLAMP_ZERO] = gl.isClampZeroOneTextureWrapSupported();
capabilities.features[FEATURE_BLENDMINMAX] = GLAD_VERSION_1_4 || GLAD_ES_VERSION_3_0 || GLAD_EXT_blend_minmax;
capabilities.features[FEATURE_LIGHTEN] = capabilities.features[FEATURE_BLENDMINMAX];
capabilities.features[FEATURE_BLEND_MINMAX] = GLAD_VERSION_1_4 || GLAD_ES_VERSION_3_0 || GLAD_EXT_blend_minmax;
capabilities.features[FEATURE_LIGHTEN] = capabilities.features[FEATURE_BLEND_MINMAX];
capabilities.features[FEATURE_FULL_NPOT] = GLAD_VERSION_2_0 || GLAD_ES_VERSION_3_0 || GLAD_OES_texture_npot;
capabilities.features[FEATURE_PIXEL_SHADER_HIGHP] = gl.isPixelShaderHighpSupported();
capabilities.features[FEATURE_SHADER_DERIVATIVES] = GLAD_VERSION_2_0 || GLAD_ES_VERSION_3_0 || GLAD_OES_standard_derivatives;
@@ -1400,8 +1393,8 @@ void Graphics::initCapabilities()
capabilities.limits[LIMIT_TEXTURE_LAYERS] = gl.getMaxTextureLayers();
capabilities.limits[LIMIT_VOLUME_TEXTURE_SIZE] = gl.getMax3DTextureSize();
capabilities.limits[LIMIT_CUBE_TEXTURE_SIZE] = gl.getMaxCubeTextureSize();
capabilities.limits[LIMIT_MULTI_CANVAS] = gl.getMaxRenderTargets();
capabilities.limits[LIMIT_CANVAS_MSAA] = gl.getMaxRenderbufferSamples();
capabilities.limits[LIMIT_RENDER_TARGETS] = gl.getMaxRenderTargets();
capabilities.limits[LIMIT_TEXTURE_MSAA] = gl.getMaxSamples();
capabilities.limits[LIMIT_ANISOTROPY] = gl.getMaxAnisotropy();
static_assert(LIMIT_MAX_ENUM == 8, "Graphics::initCapabilities must be updated when adding a new system limit!");
@@ -1409,19 +1402,124 @@ void Graphics::initCapabilities()
capabilities.textureTypes[i] = gl.isTextureTypeSupported((TextureType) i);
}
bool Graphics::isCanvasFormatSupported(PixelFormat format) const
PixelFormat Graphics::getSizedFormat(PixelFormat format, bool rendertarget, bool readable, bool sRGB) const
{
return Canvas::isFormatSupported(format);
switch (format)
{
case PIXELFORMAT_NORMAL:
if (isGammaCorrect())
return PIXELFORMAT_sRGBA8_UNORM;
else if (!OpenGL::isPixelFormatSupported(PIXELFORMAT_RGBA8_UNORM, rendertarget, readable, sRGB))
// 32-bit render targets don't have guaranteed support on GLES2.
return PIXELFORMAT_RGBA4_UNORM;
else
return PIXELFORMAT_RGBA8_UNORM;
case PIXELFORMAT_HDR:
return PIXELFORMAT_RGBA16_FLOAT;
default:
return format;
}
}
bool Graphics::isCanvasFormatSupported(PixelFormat format, bool readable) const
bool Graphics::isPixelFormatSupported(PixelFormat format, bool rendertarget, bool readable, bool sRGB)
{
return Canvas::isFormatSupported(format, readable);
}
if (sRGB && format == PIXELFORMAT_RGBA8_UNORM)
{
format = PIXELFORMAT_sRGBA8_UNORM;
sRGB = false;
}
bool Graphics::isImageFormatSupported(PixelFormat format, bool sRGB) const
{
return Image::isFormatSupported(format, sRGB);
format = getSizedFormat(format, rendertarget, readable, sRGB);
OptionalBool &supported = supportedFormats[format][rendertarget ? 1 : 0][readable ? 1 : 0][sRGB ? 1 : 0];
if (supported.hasValue)
return supported.value;
if (!OpenGL::isPixelFormatSupported(format, rendertarget, readable, sRGB))
{
supported.set(false);
return supported.value;
}
if (!rendertarget)
{
supported.set(true);
return supported.value;
}
// Even though we might have the necessary OpenGL version or extension,
// drivers are still allowed to throw FRAMEBUFFER_UNSUPPORTED when attaching
// a texture to a FBO whose format the driver doesn't like. So we should
// test with an actual FBO.
GLuint texture = 0;
GLuint renderbuffer = 0;
// Avoid the test for depth/stencil formats - not every GL version
// guarantees support for depth/stencil-only render targets (which we would
// need for the test below to work), and we already do some finagling in
// convertPixelFormat to try to use the best-supported internal
// depth/stencil format for a particular driver.
if (isPixelFormatDepthStencil(format))
{
supported.set(true);
return true;
}
OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(format, readable, sRGB);
GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
GLuint fbo = 0;
glGenFramebuffers(1, &fbo);
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
// Make sure at least something is bound to a color attachment. I believe
// this is required on ES2 but I'm not positive.
if (isPixelFormatDepthStencil(format))
gl.framebufferTexture(GL_COLOR_ATTACHMENT0, TEXTURE_2D, gl.getDefaultTexture(TEXTURE_2D), 0, 0, 0);
if (readable)
{
glGenTextures(1, &texture);
gl.bindTextureToUnit(TEXTURE_2D, texture, 0, false);
SamplerState s;
s.minFilter = s.magFilter = SamplerState::FILTER_NEAREST;
gl.setSamplerState(TEXTURE_2D, s);
gl.rawTexStorage(TEXTURE_2D, 1, format, sRGB, 1, 1);
}
else
{
glGenRenderbuffers(1, &renderbuffer);
glBindRenderbuffer(GL_RENDERBUFFER, renderbuffer);
glRenderbufferStorage(GL_RENDERBUFFER, fmt.internalformat, 1, 1);
}
for (GLenum attachment : fmt.framebufferAttachments)
{
if (attachment == GL_NONE)
continue;
if (readable)
gl.framebufferTexture(attachment, TEXTURE_2D, texture, 0, 0, 0);
else
glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, renderbuffer);
}
supported.set(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
gl.deleteFramebuffer(fbo);
if (texture != 0)
gl.deleteTexture(texture);
if (renderbuffer != 0)
glDeleteRenderbuffers(1, &renderbuffer);
return supported.value;
}
Shader::Language Graphics::getShaderLanguageTarget() const
+11 -12
View File
@@ -36,8 +36,7 @@
#include "image/Image.h"
#include "image/ImageData.h"
#include "Image.h"
#include "Canvas.h"
#include "Texture.h"
#include "Shader.h"
#include "libraries/xxHash/xxhash.h"
@@ -60,9 +59,7 @@ public:
// Implements Module.
const char *getName() const override;
love::graphics::Image *newImage(const Image::Slices &data, const Image::Settings &settings) override;
love::graphics::Image *newImage(TextureType textype, PixelFormat format, int width, int height, int slices, const Image::Settings &settings) override;
love::graphics::Canvas *newCanvas(const Canvas::Settings &settings) override;
love::graphics::Texture *newTexture(const Texture::Settings &settings, const Texture::Slices *data = nullptr) override;
love::graphics::Buffer *newBuffer(size_t size, const void *data, BufferType type, vertex::Usage usage, uint32 mapflags) override;
void setViewportSize(int width, int height, int pixelwidth, int pixelheight) override;
@@ -73,7 +70,7 @@ public:
void draw(const DrawCommand &cmd) override;
void draw(const DrawIndexedCommand &cmd) override;
void drawQuads(int start, int count, const vertex::Attributes &attributes, const vertex::BufferBindings &buffers, Texture *texture) override;
void drawQuads(int start, int count, const vertex::Attributes &attributes, const vertex::BufferBindings &buffers, love::graphics::Texture *texture) override;
void clear(OptionalColorf color, OptionalInt stencil, OptionalDouble depth) override;
void clear(const std::vector<OptionalColorf> &colors, OptionalInt stencil, OptionalDouble depth) override;
@@ -104,9 +101,8 @@ public:
void setWireframe(bool enable) override;
bool isCanvasFormatSupported(PixelFormat format) const override;
bool isCanvasFormatSupported(PixelFormat format, bool readable) const override;
bool isImageFormatSupported(PixelFormat format, bool sRGB) const override;
PixelFormat getSizedFormat(PixelFormat format, bool rendertarget, bool readable, bool sRGB) const override;
bool isPixelFormatSupported(PixelFormat format, bool rendertarget, bool readable, bool sRGB = false) override;
Renderer getRenderer() const override;
bool usesGLSLES() const override;
RendererInfo getRendererInfo() const override;
@@ -114,7 +110,7 @@ public:
Shader::Language getShaderLanguageTarget() const override;
// Internal use.
void cleanupCanvas(Canvas *canvas);
void cleanupRenderTexture(love::graphics::Texture *texture);
private:
@@ -128,7 +124,7 @@ private:
for (size_t i = 0; i < rts.colors.size(); i++)
hashtargets[hashcount++] = rts.colors[i];
if (rts.depthStencil.canvas != nullptr)
if (rts.depthStencil.texture != nullptr)
hashtargets[hashcount++] = rts.depthStencil;
else if (rts.temporaryRTFlags != 0)
hashtargets[hashcount++] = RenderTarget(nullptr, -1, rts.temporaryRTFlags);
@@ -140,7 +136,7 @@ private:
love::graphics::ShaderStage *newShaderStageInternal(ShaderStage::StageType stage, const std::string &cachekey, const std::string &source, bool gles) override;
love::graphics::Shader *newShaderInternal(love::graphics::ShaderStage *vertex, love::graphics::ShaderStage *pixel) override;
love::graphics::StreamBuffer *newStreamBuffer(BufferType type, size_t size) override;
void setCanvasInternal(const RenderTargets &rts, int w, int h, int pixelw, int pixelh, bool hasSRGBcanvas) override;
void setRenderTargetsInternal(const RenderTargets &rts, int w, int h, int pixelw, int pixelh, bool hasSRGBtexture) override;
void initCapabilities() override;
void getAPIStats(int &shaderswitches) const override;
@@ -154,6 +150,9 @@ private:
bool windowHasStencil;
GLuint mainVAO;
// [rendertarget][readable][srgb]
OptionalBool supportedFormats[PIXELFORMAT_MAX_ENUM][2][2][2];
}; // Graphics
} // opengl
-361
View File
@@ -1,361 +0,0 @@
/**
* Copyright (c) 2006-2020 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "Image.h"
#include "graphics/Graphics.h"
#include "common/int.h"
// STD
#include <algorithm> // for min/max
namespace love
{
namespace graphics
{
namespace opengl
{
Image::Image(TextureType textype, PixelFormat format, int width, int height, int slices, const Settings &settings)
: love::graphics::Image(textype, format, width, height, slices, settings)
, texture(0)
{
loadVolatile();
}
Image::Image(const Slices &slices, const Settings &settings)
: love::graphics::Image(slices, settings)
, texture(0)
{
loadVolatile();
}
Image::~Image()
{
unloadVolatile();
}
void Image::generateMipmaps()
{
if (getMipmapCount() > 1 && !isCompressed() &&
(GLAD_ES_VERSION_2_0 || GLAD_VERSION_3_0 || GLAD_ARB_framebuffer_object || GLAD_EXT_framebuffer_object))
{
gl.bindTextureToUnit(this, 0, false);
GLenum gltextype = OpenGL::getGLTextureType(texType);
if (gl.bugs.generateMipmapsRequiresTexture2DEnable)
glEnable(gltextype);
glGenerateMipmap(gltextype);
}
}
void Image::loadDefaultTexture()
{
usingDefaultTexture = true;
gl.bindTextureToUnit(this, 0, false);
setFilter(filter);
bool isSRGB = false;
gl.rawTexStorage(texType, 1, PIXELFORMAT_RGBA8_UNORM, isSRGB, 2, 2, 1);
// A nice friendly checkerboard to signify invalid textures...
GLubyte px[] = {0xFF,0xFF,0xFF,0xFF, 0xFF,0xA0,0xA0,0xFF,
0xFF,0xA0,0xA0,0xFF, 0xFF,0xFF,0xFF,0xFF};
int slices = texType == TEXTURE_CUBE ? 6 : 1;
Rect rect = {0, 0, 2, 2};
for (int slice = 0; slice < slices; slice++)
uploadByteData(PIXELFORMAT_RGBA8_UNORM, px, sizeof(px), 0, slice, rect);
}
void Image::loadData()
{
int mipcount = getMipmapCount();
int slicecount = 1;
if (texType == TEXTURE_VOLUME)
slicecount = getDepth();
else if (texType == TEXTURE_2D_ARRAY)
slicecount = getLayerCount();
else if (texType == TEXTURE_CUBE)
slicecount = 6;
if (!isCompressed())
gl.rawTexStorage(texType, mipcount, format, sRGB, pixelWidth, pixelHeight, texType == TEXTURE_VOLUME ? depth : layers);
if (mipmapsType == MIPMAPS_GENERATED)
mipcount = 1;
int w = pixelWidth;
int h = pixelHeight;
int d = depth;
OpenGL::TextureFormat fmt = gl.convertPixelFormat(format, false, sRGB);
for (int mip = 0; mip < mipcount; mip++)
{
if (isCompressed() && (texType == TEXTURE_2D_ARRAY || texType == TEXTURE_VOLUME))
{
size_t mipsize = 0;
if (texType == TEXTURE_2D_ARRAY || texType == TEXTURE_VOLUME)
{
for (int slice = 0; slice < data.getSliceCount(mip); slice++)
mipsize += data.get(slice, mip)->getSize();
}
GLenum gltarget = OpenGL::getGLTextureType(texType);
glCompressedTexImage3D(gltarget, mip, fmt.internalformat, w, h, d, 0, mipsize, nullptr);
}
for (int slice = 0; slice < slicecount; slice++)
{
love::image::ImageDataBase *id = data.get(slice, mip);
if (id != nullptr)
uploadImageData(id, mip, slice, 0, 0);
}
w = std::max(w / 2, 1);
h = std::max(h / 2, 1);
if (texType == TEXTURE_VOLUME)
d = std::max(d / 2, 1);
}
if (mipmapsType == MIPMAPS_GENERATED)
generateMipmaps();
}
void Image::uploadByteData(PixelFormat pixelformat, const void *data, size_t size, int level, int slice, const Rect &r)
{
OpenGL::TempDebugGroup debuggroup("Image data upload");
gl.bindTextureToUnit(this, 0, false);
OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(pixelformat, false, sRGB);
GLenum gltarget = OpenGL::getGLTextureType(texType);
if (texType == TEXTURE_CUBE)
gltarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + slice;
if (isPixelFormatCompressed(pixelformat))
{
if (r.x != 0 || r.y != 0)
throw love::Exception("x and y parameters must be 0 for compressed images.");
if (texType == TEXTURE_2D || texType == TEXTURE_CUBE)
glCompressedTexImage2D(gltarget, level, fmt.internalformat, r.w, r.h, 0, size, data);
else if (texType == TEXTURE_2D_ARRAY || texType == TEXTURE_VOLUME)
glCompressedTexSubImage3D(gltarget, level, 0, 0, slice, r.w, r.h, 1, fmt.internalformat, size, data);
}
else
{
if (texType == TEXTURE_2D || texType == TEXTURE_CUBE)
glTexSubImage2D(gltarget, level, r.x, r.y, r.w, r.h, fmt.externalformat, fmt.type, data);
else if (texType == TEXTURE_2D_ARRAY || texType == TEXTURE_VOLUME)
glTexSubImage3D(gltarget, level, r.x, r.y, slice, r.w, r.h, 1, fmt.externalformat, fmt.type, data);
}
}
bool Image::loadVolatile()
{
if (texture != 0)
return true;
OpenGL::TempDebugGroup debuggroup("Image load");
if (!isCompressed())
{
// GL_EXT_sRGB doesn't support glGenerateMipmap for sRGB textures.
if (sRGB && (GLAD_ES_VERSION_2_0 && GLAD_EXT_sRGB && !GLAD_ES_VERSION_3_0)
&& mipmapsType != MIPMAPS_DATA)
{
mipmapsType = MIPMAPS_NONE;
filter.mipmap = FILTER_NONE;
}
}
// NPOT textures don't support mipmapping without full NPOT support.
if ((GLAD_ES_VERSION_2_0 && !(GLAD_ES_VERSION_3_0 || GLAD_OES_texture_npot))
&& (pixelWidth != nextP2(pixelWidth) || pixelHeight != nextP2(pixelHeight)))
{
mipmapsType = MIPMAPS_NONE;
filter.mipmap = FILTER_NONE;
}
glGenTextures(1, &texture);
gl.bindTextureToUnit(this, 0, false);
// Use a default texture if the size is too big for the system.
if (!validateDimensions(false))
{
loadDefaultTexture();
return true;
}
setFilter(filter);
setWrap(wrap);
setMipmapSharpness(mipmapSharpness);
GLenum gltextype = OpenGL::getGLTextureType(texType);
if (mipmapsType == MIPMAPS_NONE && (GLAD_ES_VERSION_3_0 || GLAD_VERSION_1_0))
glTexParameteri(gltextype, GL_TEXTURE_MAX_LEVEL, 0);
while (glGetError() != GL_NO_ERROR); // Clear errors.
try
{
loadData();
GLenum glerr = glGetError();
if (glerr != GL_NO_ERROR)
throw love::Exception("Cannot create image (OpenGL error: %s)", OpenGL::errorString(glerr));
}
catch (love::Exception &)
{
gl.deleteTexture(texture);
texture = 0;
throw;
}
int64 memsize = 0;
for (int slice = 0; slice < data.getSliceCount(0); slice++)
memsize += data.get(slice, 0)->getSize();
if (getMipmapCount() > 1)
memsize *= 1.33334;
setGraphicsMemorySize(memsize);
usingDefaultTexture = false;
return true;
}
void Image::unloadVolatile()
{
if (texture == 0)
return;
gl.deleteTexture(texture);
texture = 0;
setGraphicsMemorySize(0);
}
ptrdiff_t Image::getHandle() const
{
return texture;
}
void Image::setFilter(const Texture::Filter &f)
{
Texture::setFilter(f);
if (!OpenGL::hasTextureFilteringSupport(getPixelFormat()))
{
filter.mag = filter.min = FILTER_NEAREST;
if (filter.mipmap == FILTER_LINEAR)
filter.mipmap = FILTER_NEAREST;
}
// We don't want filtering or (attempted) mipmaps on the default texture.
if (usingDefaultTexture)
{
filter.mipmap = FILTER_NONE;
filter.min = filter.mag = FILTER_NEAREST;
}
gl.bindTextureToUnit(this, 0, false);
gl.setTextureFilter(texType, filter);
}
bool Image::setWrap(const Texture::Wrap &w)
{
Graphics::flushStreamDrawsGlobal();
bool success = true;
bool forceclamp = texType == TEXTURE_CUBE;
wrap = w;
// If we only have limited NPOT support then the wrap mode must be CLAMP.
if ((GLAD_ES_VERSION_2_0 && !(GLAD_ES_VERSION_3_0 || GLAD_OES_texture_npot))
&& (pixelWidth != nextP2(pixelWidth) || pixelHeight != nextP2(pixelHeight) || depth != nextP2(depth)))
{
forceclamp = true;
}
if (forceclamp)
{
if (wrap.s != WRAP_CLAMP || wrap.t != WRAP_CLAMP || wrap.r != WRAP_CLAMP)
success = false;
wrap.s = wrap.t = wrap.r = WRAP_CLAMP;
}
if (!gl.isClampZeroOneTextureWrapSupported())
{
if (isClampZeroOrOne(wrap.s)) wrap.s = WRAP_CLAMP;
if (isClampZeroOrOne(wrap.t)) wrap.t = WRAP_CLAMP;
if (isClampZeroOrOne(wrap.r)) wrap.r = WRAP_CLAMP;
}
gl.bindTextureToUnit(this, 0, false);
gl.setTextureWrap(texType, wrap);
return success;
}
bool Image::setMipmapSharpness(float sharpness)
{
if (!gl.isSamplerLODBiasSupported())
return false;
Graphics::flushStreamDrawsGlobal();
float maxbias = gl.getMaxLODBias();
if (maxbias > 0.01f)
maxbias -= 0.01f;
mipmapSharpness = std::min(std::max(sharpness, -maxbias), maxbias);
gl.bindTextureToUnit(this, 0, false);
// negative bias is sharper
glTexParameterf(gl.getGLTextureType(texType), GL_TEXTURE_LOD_BIAS, -mipmapSharpness);
return true;
}
bool Image::isFormatSupported(PixelFormat pixelformat, bool sRGB)
{
return OpenGL::isPixelFormatSupported(pixelformat, false, true, sRGB);
}
} // opengl
} // graphics
} // love
+124 -73
View File
@@ -23,7 +23,6 @@
#include "OpenGL.h"
#include "Shader.h"
#include "Canvas.h"
#include "common/Exception.h"
#include "graphics/Graphics.h"
@@ -103,7 +102,7 @@ OpenGL::OpenGL()
, maxCubeTextureSize(0)
, maxTextureArrayLayers(0)
, maxRenderTargets(1)
, maxRenderbufferSamples(0)
, maxSamples(1)
, maxTextureUnits(1)
, maxPointSize(1)
, coreProfile(false)
@@ -260,8 +259,9 @@ void OpenGL::setupContext()
#ifdef LOVE_ANDROID
// This can't be done in initContext with the rest of the bug checks because
// Canvas::isFormatSupported relies on state initialized here / after init.
if (GLAD_ES_VERSION_3_0 && !Canvas::isFormatSupported(PIXELFORMAT_R8))
// isPixelFormatSupported relies on state initialized here / after init.
auto gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
if (GLAD_ES_VERSION_3_0 && gfx != nullptr && !gfx->isPixelFormatSupported(PIXELFORMAT_R8_UNORM, true, true))
bugs.brokenR8PixelFormat = true;
#endif
}
@@ -474,10 +474,10 @@ void OpenGL::initMaxValues()
|| GLAD_EXT_framebuffer_multisample || GLAD_APPLE_framebuffer_multisample
|| GLAD_ANGLE_framebuffer_multisample)
{
glGetIntegerv(GL_MAX_SAMPLES, &maxRenderbufferSamples);
glGetIntegerv(GL_MAX_SAMPLES, &maxSamples);
}
else
maxRenderbufferSamples = 0;
maxSamples = 1;
glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &maxTextureUnits);
@@ -502,11 +502,9 @@ void OpenGL::createDefaultTexture()
// untextured primitives vs images.
const GLubyte pix[] = {255, 255, 255, 255};
Texture::Filter filter;
filter.min = filter.mag = Texture::FILTER_NEAREST;
Texture::Wrap wrap;
wrap.s = wrap.t = wrap.r = Texture::WRAP_CLAMP;
SamplerState s;
s.minFilter = s.magFilter = SamplerState::FILTER_NEAREST;
s.wrapU = s.wrapV = s.wrapW = SamplerState::WRAP_CLAMP;
for (int i = 0; i < TEXTURE_MAX_ENUM; i++)
{
@@ -522,8 +520,7 @@ void OpenGL::createDefaultTexture()
glGenTextures(1, &state.defaultTexture[type]);
bindTextureToUnit(type, state.defaultTexture[type], 0, false);
setTextureWrap(type, wrap);
setTextureFilter(type, filter);
setSamplerState(type, s);
bool isSRGB = false;
rawTexStorage(type, 1, PIXELFORMAT_RGBA8_UNORM, isSRGB, 1, 1);
@@ -808,13 +805,13 @@ Rect OpenGL::getViewport() const
return state.viewport;
}
void OpenGL::setScissor(const Rect &v, bool canvasActive)
void OpenGL::setScissor(const Rect &v, bool rtActive)
{
if (canvasActive)
if (rtActive)
glScissor(v.x, v.y, v.w, v.h);
else
{
// With no Canvas active, we need to compensate for glScissor starting
// With no RT active, we need to compensate for glScissor starting
// from the lower left of the viewport instead of the top left.
glScissor(v.x, state.viewport.h - (v.y + v.h), v.w, v.h);
}
@@ -1050,52 +1047,19 @@ void OpenGL::deleteTexture(GLuint texture)
glDeleteTextures(1, &texture);
}
void OpenGL::setTextureFilter(TextureType target, graphics::Texture::Filter &f)
{
GLint gmin = f.min == Texture::FILTER_NEAREST ? GL_NEAREST : GL_LINEAR;
GLint gmag = f.mag == Texture::FILTER_NEAREST ? GL_NEAREST : GL_LINEAR;
if (f.mipmap != Texture::FILTER_NONE)
{
if (f.min == Texture::FILTER_NEAREST && f.mipmap == Texture::FILTER_NEAREST)
gmin = GL_NEAREST_MIPMAP_NEAREST;
else if (f.min == Texture::FILTER_NEAREST && f.mipmap == Texture::FILTER_LINEAR)
gmin = GL_NEAREST_MIPMAP_LINEAR;
else if (f.min == Texture::FILTER_LINEAR && f.mipmap == Texture::FILTER_NEAREST)
gmin = GL_LINEAR_MIPMAP_NEAREST;
else if (f.min == Texture::FILTER_LINEAR && f.mipmap == Texture::FILTER_LINEAR)
gmin = GL_LINEAR_MIPMAP_LINEAR;
else
gmin = GL_LINEAR;
}
GLenum gltarget = getGLTextureType(target);
glTexParameteri(gltarget, GL_TEXTURE_MIN_FILTER, gmin);
glTexParameteri(gltarget, GL_TEXTURE_MAG_FILTER, gmag);
if (GLAD_EXT_texture_filter_anisotropic)
{
f.anisotropy = std::min(std::max(f.anisotropy, 1.0f), maxAnisotropy);
glTexParameterf(gltarget, GL_TEXTURE_MAX_ANISOTROPY_EXT, f.anisotropy);
}
else
f.anisotropy = 1.0f;
}
GLint OpenGL::getGLWrapMode(Texture::WrapMode wmode)
GLint OpenGL::getGLWrapMode(SamplerState::WrapMode wmode)
{
switch (wmode)
{
case Texture::WRAP_CLAMP:
case SamplerState::WRAP_CLAMP:
default:
return GL_CLAMP_TO_EDGE;
case Texture::WRAP_CLAMP_ZERO:
case Texture::WRAP_CLAMP_ONE:
case SamplerState::WRAP_CLAMP_ZERO:
case SamplerState::WRAP_CLAMP_ONE:
return GL_CLAMP_TO_BORDER;
case Texture::WRAP_REPEAT:
case SamplerState::WRAP_REPEAT:
return GL_REPEAT;
case Texture::WRAP_MIRRORED_REPEAT:
case SamplerState::WRAP_MIRRORED_REPEAT:
return GL_MIRRORED_REPEAT;
}
}
@@ -1125,29 +1089,111 @@ GLint OpenGL::getGLCompareMode(CompareMode mode)
}
}
static bool isClampOne(Texture::WrapMode mode)
static bool isClampOne(SamplerState::WrapMode mode)
{
return mode == Texture::WRAP_CLAMP_ONE;
return mode == SamplerState::WRAP_CLAMP_ONE;
}
void OpenGL::setTextureWrap(TextureType target, const graphics::Texture::Wrap &w)
void OpenGL::setSamplerState(TextureType target, SamplerState &s)
{
GLenum textype = getGLTextureType(target);
GLenum gltarget = getGLTextureType(target);
if (Texture::isClampZeroOrOne(w.s) || Texture::isClampZeroOrOne(w.t) || Texture::isClampZeroOrOne(w.r))
GLint gmin = s.minFilter == SamplerState::FILTER_NEAREST ? GL_NEAREST : GL_LINEAR;
GLint gmag = s.magFilter == SamplerState::FILTER_NEAREST ? GL_NEAREST : GL_LINEAR;
if (s.mipmapFilter != SamplerState::MIPMAP_FILTER_NONE)
{
GLfloat c[] = {0.0f, 0.0f, 0.0f, 0.0f};
if (isClampOne(w.s) || isClampOne(w.t) || isClampOne(w.r))
c[0] = c[1] = c[2] = c[3] = 1.0f;
glTexParameterfv(textype, GL_TEXTURE_BORDER_COLOR, c);
if (s.minFilter == SamplerState::FILTER_NEAREST && s.mipmapFilter == SamplerState::MIPMAP_FILTER_NEAREST)
gmin = GL_NEAREST_MIPMAP_NEAREST;
else if (s.minFilter == SamplerState::FILTER_NEAREST && s.mipmapFilter == SamplerState::MIPMAP_FILTER_LINEAR)
gmin = GL_NEAREST_MIPMAP_LINEAR;
else if (s.minFilter == SamplerState::FILTER_LINEAR && s.mipmapFilter == SamplerState::MIPMAP_FILTER_NEAREST)
gmin = GL_LINEAR_MIPMAP_NEAREST;
else if (s.minFilter == SamplerState::FILTER_LINEAR && s.mipmapFilter == SamplerState::MIPMAP_FILTER_LINEAR)
gmin = GL_LINEAR_MIPMAP_LINEAR;
}
glTexParameteri(textype, GL_TEXTURE_WRAP_S, getGLWrapMode(w.s));
glTexParameteri(textype, GL_TEXTURE_WRAP_T, getGLWrapMode(w.t));
glTexParameteri(gltarget, GL_TEXTURE_MIN_FILTER, gmin);
glTexParameteri(gltarget, GL_TEXTURE_MAG_FILTER, gmag);
if (!isClampZeroOneTextureWrapSupported())
{
if (SamplerState::isClampZeroOrOne(s.wrapU)) s.wrapU = SamplerState::WRAP_CLAMP;
if (SamplerState::isClampZeroOrOne(s.wrapV)) s.wrapV = SamplerState::WRAP_CLAMP;
if (SamplerState::isClampZeroOrOne(s.wrapW)) s.wrapW = SamplerState::WRAP_CLAMP;
}
if (SamplerState::isClampZeroOrOne(s.wrapU) || SamplerState::isClampZeroOrOne(s.wrapV) || SamplerState::isClampZeroOrOne(s.wrapW))
{
GLfloat c[] = {0.0f, 0.0f, 0.0f, 0.0f};
if (isClampOne(s.wrapU) || isClampOne(s.wrapU) || isClampOne(s.wrapV))
c[0] = c[1] = c[2] = c[3] = 1.0f;
glTexParameterfv(gltarget, GL_TEXTURE_BORDER_COLOR, c);
}
glTexParameteri(gltarget, GL_TEXTURE_WRAP_S, getGLWrapMode(s.wrapU));
glTexParameteri(gltarget, GL_TEXTURE_WRAP_T, getGLWrapMode(s.wrapV));
if (target == TEXTURE_VOLUME)
glTexParameteri(textype, GL_TEXTURE_WRAP_R, getGLWrapMode(w.r));
glTexParameteri(gltarget, GL_TEXTURE_WRAP_R, getGLWrapMode(s.wrapW));
if (isSamplerLODBiasSupported())
{
float maxbias = getMaxLODBias();
if (maxbias > 0.01f)
maxbias -= 0.01f;
s.lodBias = std::min(std::max(s.lodBias, -maxbias), maxbias);
glTexParameterf(gltarget, GL_TEXTURE_LOD_BIAS, s.lodBias);
}
else
{
s.lodBias = 0.0f;
}
if (GLAD_EXT_texture_filter_anisotropic)
{
uint8 maxAniso = (uint8) std::min(maxAnisotropy, (float)LOVE_UINT8_MAX);
s.maxAnisotropy = std::min(std::max(s.maxAnisotropy, (uint8)1), maxAniso);
glTexParameteri(gltarget, GL_TEXTURE_MAX_ANISOTROPY_EXT, s.maxAnisotropy);
}
else
{
s.maxAnisotropy = 1;
}
if (GLAD_ES_VERSION_3_0 || GLAD_VERSION_1_0)
{
glTexParameterf(gltarget, GL_TEXTURE_MIN_LOD, (float)s.minLod);
glTexParameterf(gltarget, GL_TEXTURE_MAX_LOD, (float)s.maxLod);
}
else
{
s.minLod = 0;
s.maxLod = LOVE_UINT8_MAX;
}
if (isDepthCompareSampleSupported())
{
if (s.depthSampleMode.hasValue)
{
// See the comment in renderstate.h
GLenum glmode = getGLCompareMode(getReversedCompareMode(s.depthSampleMode.value));
glTexParameteri(gltarget, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
glTexParameteri(gltarget, GL_TEXTURE_COMPARE_FUNC, glmode);
}
else
{
glTexParameteri(gltarget, GL_TEXTURE_COMPARE_MODE, GL_NONE);
}
}
else
{
s.depthSampleMode.hasValue = false;
}
}
bool OpenGL::rawTexStorage(TextureType target, int levels, PixelFormat pixelformat, bool &isSRGB, int width, int height, int depth)
@@ -1282,6 +1328,11 @@ bool OpenGL::isBaseVertexSupported() const
return baseVertexSupported;
}
bool OpenGL::isMultiFormatMRTSupported() const
{
return getMaxRenderTargets() > 1 && (GLAD_ES_VERSION_3_0 || GLAD_VERSION_3_0 || GLAD_ARB_framebuffer_object);
}
int OpenGL::getMax2DTextureSize() const
{
return std::max(max2DTextureSize, 1);
@@ -1307,9 +1358,9 @@ int OpenGL::getMaxRenderTargets() const
return std::min(maxRenderTargets, MAX_COLOR_RENDER_TARGETS);
}
int OpenGL::getMaxRenderbufferSamples() const
int OpenGL::getMaxSamples() const
{
return maxRenderbufferSamples;
return maxSamples;
}
int OpenGL::getMaxTextureUnits() const
@@ -1743,10 +1794,10 @@ bool OpenGL::isPixelFormatSupported(PixelFormat pixelformat, bool rendertarget,
&& (GLAD_VERSION_2_1 || GLAD_EXT_texture_sRGB));
}
else
return GLAD_ES_VERSION_3_0 || GLAD_EXT_sRGB;
return GLAD_ES_VERSION_3_0;
}
else
return GLAD_ES_VERSION_3_0 || GLAD_EXT_sRGB || GLAD_VERSION_2_1 || GLAD_EXT_texture_sRGB;
return GLAD_ES_VERSION_3_0 || GLAD_VERSION_2_1 || GLAD_EXT_texture_sRGB;
case PIXELFORMAT_R16_UNORM:
case PIXELFORMAT_RG16_UNORM:
return GLAD_VERSION_3_0
@@ -1946,7 +1997,7 @@ const char *OpenGL::framebufferStatusString(GLenum status)
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:
return "Error in graphics driver (incomplete read buffer)";
case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE:
return "Canvas with the specified MSAA count cannot be rendered to on this system.";
return "Texture with the specified MSAA count cannot be rendered to on this system.";
case GL_FRAMEBUFFER_UNSUPPORTED:
return "Renderable textures are unsupported";
default:
+8 -14
View File
@@ -261,7 +261,7 @@ public:
* Sets the scissor box to the specified rectangle.
* The y-coordinate starts at the top and is flipped internally.
**/
void setScissor(const Rect &v, bool canvasActive);
void setScissor(const Rect &v, bool rtActive);
/**
* Sets the global point size.
@@ -329,16 +329,9 @@ public:
void deleteTexture(GLuint texture);
/**
* Sets the texture filter mode for the currently bound texture.
* The anisotropy parameter of the argument is set to the actual amount of
* anisotropy that was used.
* Sets sampler state parameters for the currently bound texture.
**/
void setTextureFilter(TextureType target, graphics::Texture::Filter &f);
/**
* Sets the texture wrap mode for the currently bound texture.
**/
void setTextureWrap(TextureType target, const graphics::Texture::Wrap &w);
void setSamplerState(TextureType target, SamplerState &s);
/**
* Equivalent to glTexStorage2D/3D on platforms that support it. Equivalent
@@ -354,6 +347,7 @@ public:
bool isDepthCompareSampleSupported() const;
bool isSamplerLODBiasSupported() const;
bool isBaseVertexSupported() const;
bool isMultiFormatMRTSupported() const;
/**
* Returns the maximum supported width or height of a texture.
@@ -369,9 +363,9 @@ public:
int getMaxRenderTargets() const;
/**
* Returns the maximum supported number of MSAA samples for renderbuffers.
* Returns the maximum supported number of MSAA sampless.
**/
int getMaxRenderbufferSamples() const;
int getMaxSamples() const;
/**
* Returns the maximum number of accessible texture units.
@@ -407,7 +401,7 @@ public:
static GLenum getGLVertexDataType(vertex::DataType type, GLboolean &normalized, bool &intformat);
static GLenum getGLBufferUsage(vertex::Usage usage);
static GLenum getGLTextureType(TextureType type);
static GLint getGLWrapMode(Texture::WrapMode wmode);
static GLint getGLWrapMode(SamplerState::WrapMode wmode);
static GLint getGLCompareMode(CompareMode mode);
static TextureFormat convertPixelFormat(PixelFormat pixelformat, bool renderbuffer, bool &isSRGB);
@@ -442,7 +436,7 @@ private:
int maxCubeTextureSize;
int maxTextureArrayLayers;
int maxRenderTargets;
int maxRenderbufferSamples;
int maxSamples;
int maxTextureUnits;
float maxPointSize;
+10 -9
View File
@@ -196,7 +196,7 @@ void Shader::mapActiveUniforms()
glUniform1iv(u.location, u.count, u.ints);
u.textures = new Texture*[u.count];
u.textures = new love::graphics::Texture*[u.count];
memset(u.textures, 0, sizeof(Texture *) * u.count);
}
}
@@ -565,12 +565,12 @@ void Shader::updateUniform(const UniformInfo *info, int count, bool internalupda
}
}
void Shader::sendTextures(const UniformInfo *info, Texture **textures, int count)
void Shader::sendTextures(const UniformInfo *info, love::graphics::Texture **textures, int count)
{
Shader::sendTextures(info, textures, count, false);
}
void Shader::sendTextures(const UniformInfo *info, Texture **textures, int count, bool internalUpdate)
void Shader::sendTextures(const UniformInfo *info, love::graphics::Texture **textures, int count, bool internalUpdate)
{
if (info->baseType != UNIFORM_SAMPLER)
return;
@@ -585,10 +585,11 @@ void Shader::sendTextures(const UniformInfo *info, Texture **textures, int count
// Bind the textures to the texture units.
for (int i = 0; i < count; i++)
{
Texture *tex = textures[i];
love::graphics::Texture *tex = textures[i];
if (tex != nullptr)
{
const SamplerState &sampler = tex->getSamplerState();
if (!tex->isReadable())
{
if (internalUpdate)
@@ -596,7 +597,7 @@ void Shader::sendTextures(const UniformInfo *info, Texture **textures, int count
else
throw love::Exception("Textures with non-readable formats cannot be sampled from in a shader.");
}
else if (info->isDepthSampler != tex->getDepthSampleMode().hasValue)
else if (info->isDepthSampler != sampler.depthSampleMode.hasValue)
{
if (internalUpdate)
continue;
@@ -671,7 +672,7 @@ int Shader::getVertexAttributeIndex(const std::string &name)
return location;
}
void Shader::setVideoTextures(Texture *ytexture, Texture *cbtexture, Texture *crtexture)
void Shader::setVideoTextures(love::graphics::Texture *ytexture, love::graphics::Texture *cbtexture, love::graphics::Texture *crtexture)
{
const BuiltinUniform builtins[3] = {
BUILTIN_TEXTURE_VIDEO_Y,
@@ -679,7 +680,7 @@ void Shader::setVideoTextures(Texture *ytexture, Texture *cbtexture, Texture *cr
BUILTIN_TEXTURE_VIDEO_CR,
};
Texture *textures[3] = {ytexture, cbtexture, crtexture};
love::graphics::Texture *textures[3] = {ytexture, cbtexture, crtexture};
for (int i = 0; i < 3; i++)
{
@@ -734,8 +735,8 @@ void Shader::updateBuiltinUniforms(love::graphics::Graphics *gfx, int viewportW,
// The shader does pixcoord.y = gl_FragCoord.y * params.z + params.w.
// This lets us flip pixcoord.y when needed, to be consistent (drawing
// with no Canvas active makes the pixel coordinates y-flipped.)
if (gfx->isCanvasActive())
// with no RT active makes the pixel coordinates y-flipped.)
if (gfx->isRenderTargetActive())
{
// No flipping: pixcoord.y = gl_FragCoord.y * 1.0 + 0.0.
data.screenSizeParams.z = 1.0f;
+4 -4
View File
@@ -61,10 +61,10 @@ public:
const UniformInfo *getUniformInfo(const std::string &name) const override;
const UniformInfo *getUniformInfo(BuiltinUniform builtin) const override;
void updateUniform(const UniformInfo *info, int count) override;
void sendTextures(const UniformInfo *info, Texture **textures, int count) override;
void sendTextures(const UniformInfo *info, love::graphics::Texture **textures, int count) override;
bool hasUniform(const std::string &name) const override;
ptrdiff_t getHandle() const override;
void setVideoTextures(Texture *ytexture, Texture *cbtexture, Texture *crtexture) override;
void setVideoTextures(love::graphics::Texture *ytexture, love::graphics::Texture *cbtexture, love::graphics::Texture *crtexture) override;
void updatePointSize(float size);
void updateBuiltinUniforms(love::graphics::Graphics *gfx, int viewportW, int viewportH);
@@ -82,7 +82,7 @@ private:
void mapActiveUniforms();
void updateUniform(const UniformInfo *info, int count, bool internalupdate);
void sendTextures(const UniformInfo *info, Texture **textures, int count, bool internalupdate);
void sendTextures(const UniformInfo *info, love::graphics::Texture **textures, int count, bool internalupdate);
int getUniformTypeComponents(GLenum type) const;
MatrixSize getMatrixSize(GLenum type) const;
@@ -110,7 +110,7 @@ private:
// Uniform location buffer map
std::map<std::string, UniformInfo> uniforms;
// Texture unit pool for setting images
// Texture unit pool for setting textures
std::vector<TextureUnit> textureUnits;
std::vector<std::pair<const UniformInfo *, int>> pendingUniformUpdates;
+32 -3
View File
@@ -406,7 +406,12 @@ public:
if (!alignedMalloc((void **) &data, alignedSize, alignment))
throw love::Exception("Out of memory.");
loadVolatile();
if (!loadVolatile())
{
ptrdiff_t pointer = (ptrdiff_t) data;
alignedFree(data);
throw love::Exception("AMD Pinned Memory StreamBuffer implementation failed to create buffer (address: %p, alignment: %ld, aiigned size: %ld)", pointer, alignment, alignedSize);
}
}
~StreamBufferPinnedMemory()
@@ -441,9 +446,19 @@ public:
glGenBuffers(1, &vbo);
while (glGetError() != GL_NO_ERROR)
/* Clear errors. */;
glBindBuffer(GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD, vbo);
glBufferData(GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD, alignedSize, data, GL_STREAM_DRAW);
if (glGetError() != GL_NO_ERROR)
{
gl.deleteBuffer(vbo);
vbo = 0;
return false;
}
frameGPUReadOffset = 0;
frameIndex = 0;
@@ -485,8 +500,22 @@ love::graphics::StreamBuffer *CreateStreamBuffer(BufferType mode, size_t size)
// AMD's pinned memory seems to be faster than persistent mapping,
// on AMD GPUs.
if (GLAD_AMD_pinned_memory)
return new StreamBufferPinnedMemory(mode, size);
else if (GLAD_VERSION_4_4 || GLAD_ARB_buffer_storage)
{
try
{
return new StreamBufferPinnedMemory(mode, size);
}
catch (love::Exception &)
{
// According to the spec, pinned memory can fail if the RAM
// allocation can't be mapped to the GPU's address space.
// This seems to happen in practice on Mesa + amdgpu:
// https://bitbucket.org/rude/love/issues/1540
// Fall through to other implementations when that happens.
}
}
if (GLAD_VERSION_4_4 || GLAD_ARB_buffer_storage)
return new StreamBufferPersistentMapSync(mode, size);
// Most modern drivers have a separate internal thread which queues
+568
View File
@@ -0,0 +1,568 @@
/**
* Copyright (c) 2006-2020 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#include "Texture.h"
#include "graphics/Graphics.h"
#include "Graphics.h"
#include "common/int.h"
// STD
#include <algorithm> // for min/max
namespace love
{
namespace graphics
{
namespace opengl
{
static GLenum createFBO(GLuint &framebuffer, TextureType texType, PixelFormat format, GLuint texture, int layers, bool clear)
{
// get currently bound fbo to reset to it later
GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
glGenFramebuffers(1, &framebuffer);
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, framebuffer);
if (texture != 0)
{
if (isPixelFormatDepthStencil(format) && (GLAD_ES_VERSION_3_0 || !GLAD_ES_VERSION_2_0))
{
// glDrawBuffers is an ext in GL2. glDrawBuffer doesn't exist in ES3.
GLenum none = GL_NONE;
if (GLAD_ES_VERSION_3_0)
glDrawBuffers(1, &none);
else
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
}
bool unusedSRGB = false;
OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(format, false, unusedSRGB);
int faces = texType == TEXTURE_CUBE ? 6 : 1;
// Make sure all faces and layers of the texture are initialized to
// transparent black. This is unfortunately probably pretty slow for
// 2D-array and 3D textures with a lot of layers...
for (int layer = layers - 1; layer >= 0; layer--)
{
for (int face = faces - 1; face >= 0; face--)
{
for (GLenum attachment : fmt.framebufferAttachments)
{
if (attachment == GL_NONE)
continue;
gl.framebufferTexture(attachment, texType, texture, 0, layer, face);
}
if (clear)
{
if (isPixelFormatDepthStencil(format))
{
bool hadDepthWrites = gl.hasDepthWrites();
if (!hadDepthWrites) // glDepthMask also affects glClear.
gl.setDepthWrites(true);
gl.clearDepth(1.0);
glClearStencil(0);
glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
if (!hadDepthWrites)
gl.setDepthWrites(hadDepthWrites);
}
else
{
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
}
}
}
}
}
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
return status;
}
static GLenum newRenderbuffer(int width, int height, int &samples, PixelFormat pixelformat, GLuint &buffer)
{
bool unusedSRGB = false;
OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(pixelformat, true, unusedSRGB);
GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
// Temporary FBO used to clear the renderbuffer.
GLuint fbo = 0;
glGenFramebuffers(1, &fbo);
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, fbo);
if (isPixelFormatDepthStencil(pixelformat) && (GLAD_ES_VERSION_3_0 || !GLAD_ES_VERSION_2_0))
{
// glDrawBuffers is an ext in GL2. glDrawBuffer doesn't exist in ES3.
GLenum none = GL_NONE;
if (GLAD_ES_VERSION_3_0)
glDrawBuffers(1, &none);
else
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
}
glGenRenderbuffers(1, &buffer);
glBindRenderbuffer(GL_RENDERBUFFER, buffer);
if (samples > 1)
glRenderbufferStorageMultisample(GL_RENDERBUFFER, samples, fmt.internalformat, width, height);
else
glRenderbufferStorage(GL_RENDERBUFFER, fmt.internalformat, width, height);
for (GLenum attachment : fmt.framebufferAttachments)
{
if (attachment != GL_NONE)
glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, buffer);
}
if (samples > 1)
{
glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_SAMPLES, &samples);
samples = std::max(1, samples);
}
glBindRenderbuffer(GL_RENDERBUFFER, 0);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status == GL_FRAMEBUFFER_COMPLETE)
{
if (isPixelFormatDepthStencil(pixelformat))
{
bool hadDepthWrites = gl.hasDepthWrites();
if (!hadDepthWrites) // glDepthMask also affects glClear.
gl.setDepthWrites(true);
gl.clearDepth(1.0);
glClearStencil(0);
glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
if (!hadDepthWrites)
gl.setDepthWrites(hadDepthWrites);
}
else
{
// Initialize the buffer to transparent black.
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
}
}
else
{
glDeleteRenderbuffers(1, &buffer);
buffer = 0;
samples = 1;
}
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
gl.deleteFramebuffer(fbo);
return status;
}
Texture::Texture(const Settings &settings, const Slices *data)
: love::graphics::Texture(settings, data)
, slices(settings.type)
, fbo(0)
, texture(0)
, renderbuffer(0)
, framebufferStatus(GL_FRAMEBUFFER_COMPLETE)
, textureGLError(GL_NO_ERROR)
, actualSamples(1)
{
if (data != nullptr)
slices = *data;
if (!loadVolatile())
{
if (framebufferStatus != GL_FRAMEBUFFER_COMPLETE)
throw love::Exception("Cannot create Texture (OpenGL framebuffer error: %s)", OpenGL::framebufferStatusString(framebufferStatus));
if (textureGLError != GL_NO_ERROR)
throw love::Exception("Cannot create Texture (OpenGL error: %s)", OpenGL::errorString(textureGLError));
}
}
Texture::~Texture()
{
unloadVolatile();
}
void Texture::createTexture()
{
// The base class handles some validation. For example, if ImageData is
// given then it must exist for all mip levels, a render target can't use
// a compressed format, etc.
glGenTextures(1, &texture);
gl.bindTextureToUnit(this, 0, false);
// Use a default texture if the size is too big for the system.
// validateDimensions is also called in the base class for RTs and
// non-readable textures.
if (!renderTarget && !validateDimensions(false))
{
usingDefaultTexture = true;
setSamplerState(samplerState);
bool isSRGB = false;
gl.rawTexStorage(texType, 1, PIXELFORMAT_RGBA8_UNORM, isSRGB, 2, 2, 1);
// A nice friendly checkerboard to signify invalid textures...
GLubyte px[] = {0xFF,0xFF,0xFF,0xFF, 0xFF,0xA0,0xA0,0xFF,
0xFF,0xA0,0xA0,0xFF, 0xFF,0xFF,0xFF,0xFF};
int slices = texType == TEXTURE_CUBE ? 6 : 1;
Rect rect = {0, 0, 2, 2};
for (int slice = 0; slice < slices; slice++)
uploadByteData(PIXELFORMAT_RGBA8_UNORM, px, sizeof(px), 0, slice, rect, nullptr);
return;
}
GLenum gltype = OpenGL::getGLTextureType(texType);
if (renderTarget && GLAD_ANGLE_texture_usage)
glTexParameteri(gltype, GL_TEXTURE_USAGE_ANGLE, GL_FRAMEBUFFER_ATTACHMENT_ANGLE);
setSamplerState(samplerState);
int mipcount = getMipmapCount();
int slicecount = 1;
if (texType == TEXTURE_VOLUME)
slicecount = getDepth();
else if (texType == TEXTURE_2D_ARRAY)
slicecount = getLayerCount();
else if (texType == TEXTURE_CUBE)
slicecount = 6;
// For a couple flimsy reasons, we don't initialize the texture here if it's
// compressed. I need to verify that getPixelFormatSliceSize will return the
// correct value for all compressed texture formats, and I also vaguely
// remember some driver issues on some old Android systems, maybe...
// For now, the base class enforces data on init for compressed textures.
if (!isCompressed())
gl.rawTexStorage(texType, mipcount, format, sRGB, pixelWidth, pixelHeight, texType == TEXTURE_VOLUME ? depth : layers);
int w = pixelWidth;
int h = pixelHeight;
int d = depth;
OpenGL::TextureFormat fmt = gl.convertPixelFormat(format, false, sRGB);
for (int mip = 0; mip < mipcount; mip++)
{
if (isCompressed() && (texType == TEXTURE_2D_ARRAY || texType == TEXTURE_VOLUME))
{
size_t mipsize = 0;
if (texType == TEXTURE_2D_ARRAY || texType == TEXTURE_VOLUME)
{
for (int slice = 0; slice < slices.getSliceCount(mip); slice++)
{
auto id = slices.get(slice, mip);
if (id != nullptr)
mipsize += id->getSize();
}
}
if (mipsize > 0)
glCompressedTexImage3D(gltype, mip, fmt.internalformat, w, h, d, 0, mipsize, nullptr);
}
for (int slice = 0; slice < slicecount; slice++)
{
love::image::ImageDataBase *id = slices.get(slice, mip);
if (id != nullptr)
uploadImageData(id, mip, slice, 0, 0);
}
w = std::max(w / 2, 1);
h = std::max(h / 2, 1);
if (texType == TEXTURE_VOLUME)
d = std::max(d / 2, 1);
}
bool hasdata = slices.get(0, 0) != nullptr;
// Create a local FBO used for glReadPixels as well as MSAA blitting.
if (isRenderTarget())
{
bool clear = !hasdata;
int slices = texType == TEXTURE_VOLUME ? depth : layers;
framebufferStatus = createFBO(fbo, texType, format, texture, slices, clear);
}
else if (!hasdata)
{
// Initialize all slices to transparent black.
std::vector<uint8> emptydata(getPixelFormatSliceSize(format, w, h));
Rect r = {0, 0, w, h};
int slices = texType == TEXTURE_VOLUME ? depth : layers;
slices = texType == TEXTURE_CUBE ? 6 : slices;
for (int i = 0; i < slices; i++)
uploadByteData(format, emptydata.data(), emptydata.size(), 0, i, r);
}
// Non-readable textures can't have mipmaps (enforced in the base class),
// so generateMipmaps here is fine - when they aren't already initialized.
if (getMipmapCount() > 1 && slices.getMipmapCount() <= 1)
generateMipmaps();
}
bool Texture::loadVolatile()
{
if (texture != 0 || renderbuffer != 0)
return true;
OpenGL::TempDebugGroup debuggroup("Texture load");
// NPOT textures don't support mipmapping without full NPOT support.
if ((GLAD_ES_VERSION_2_0 && !(GLAD_ES_VERSION_3_0 || GLAD_OES_texture_npot))
&& (pixelWidth != nextP2(pixelWidth) || pixelHeight != nextP2(pixelHeight)))
{
mipmapCount = 1;
samplerState.mipmapFilter = SamplerState::MIPMAP_FILTER_NONE;
}
actualSamples = std::max(1, std::min(getRequestedMSAA(), gl.getMaxSamples()));
while (glGetError() != GL_NO_ERROR); // Clear errors.
framebufferStatus = GL_FRAMEBUFFER_COMPLETE;
textureGLError = GL_NO_ERROR;
if (isReadable())
createTexture();
if (!usingDefaultTexture && framebufferStatus == GL_FRAMEBUFFER_COMPLETE
&& (!isReadable() || actualSamples > 1))
{
framebufferStatus = newRenderbuffer(pixelWidth, pixelHeight, actualSamples, format, renderbuffer);
}
textureGLError = glGetError();
if (framebufferStatus != GL_FRAMEBUFFER_COMPLETE || textureGLError != GL_NO_ERROR)
{
unloadVolatile();
return false;
}
int64 memsize = 0;
for (int mip = 0; mip < getMipmapCount(); mip++)
{
int w = getPixelWidth(mip);
int h = getPixelHeight(mip);
int slices = getDepth(mip) * layers * (texType == TEXTURE_CUBE ? 6 : 1);
memsize += getPixelFormatSliceSize(format, w, h) * slices;
}
if (actualSamples > 1 && isReadable())
{
int slices = depth * layers * (texType == TEXTURE_CUBE ? 6 : 1);
memsize += getPixelFormatSliceSize(format, pixelWidth, pixelHeight) * slices * actualSamples;
}
else if (actualSamples > 1)
memsize *= actualSamples;
setGraphicsMemorySize(memsize);
usingDefaultTexture = false;
return true;
}
void Texture::unloadVolatile()
{
if (isRenderTarget() && (fbo != 0 || renderbuffer != 0 || texture != 0))
{
// This is a bit ugly, but we need some way to destroy the cached FBO
// when this texture's GL object is destroyed.
auto gfx = Module::getInstance<Graphics>(Module::M_GRAPHICS);
if (gfx != nullptr)
gfx->cleanupRenderTexture(this);
}
if (fbo != 0)
gl.deleteFramebuffer(fbo);
if (renderbuffer != 0)
glDeleteRenderbuffers(1, &renderbuffer);
if (texture != 0)
gl.deleteTexture(texture);
fbo = 0;
renderbuffer = 0;
texture = 0;
setGraphicsMemorySize(0);
}
void Texture::uploadByteData(PixelFormat pixelformat, const void *data, size_t size, int level, int slice, const Rect &r, love::image::ImageDataBase *imgd)
{
love::image::ImageDataBase *oldd = slices.get(slice, level);
// We can only replace the internal Data (used when reloading due to setMode)
// if the dimensions match.
if (imgd != nullptr && oldd != nullptr && oldd->getWidth() == imgd->getWidth()
&& oldd->getHeight() == imgd->getHeight())
{
slices.set(slice, level, imgd);
}
OpenGL::TempDebugGroup debuggroup("Texture data upload");
gl.bindTextureToUnit(this, 0, false);
OpenGL::TextureFormat fmt = OpenGL::convertPixelFormat(pixelformat, false, sRGB);
GLenum gltarget = OpenGL::getGLTextureType(texType);
if (texType == TEXTURE_CUBE)
gltarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X + slice;
if (isPixelFormatCompressed(pixelformat))
{
if (r.x != 0 || r.y != 0)
throw love::Exception("x and y parameters must be 0 for compressed textures.");
if (texType == TEXTURE_2D || texType == TEXTURE_CUBE)
glCompressedTexImage2D(gltarget, level, fmt.internalformat, r.w, r.h, 0, size, data);
else if (texType == TEXTURE_2D_ARRAY || texType == TEXTURE_VOLUME)
glCompressedTexSubImage3D(gltarget, level, 0, 0, slice, r.w, r.h, 1, fmt.internalformat, size, data);
}
else
{
if (texType == TEXTURE_2D || texType == TEXTURE_CUBE)
glTexSubImage2D(gltarget, level, r.x, r.y, r.w, r.h, fmt.externalformat, fmt.type, data);
else if (texType == TEXTURE_2D_ARRAY || texType == TEXTURE_VOLUME)
glTexSubImage3D(gltarget, level, r.x, r.y, slice, r.w, r.h, 1, fmt.externalformat, fmt.type, data);
}
}
void Texture::generateMipmaps()
{
if (getMipmapCount() == 1 || getMipmapsMode() == MIPMAPS_NONE)
throw love::Exception("generateMipmaps can only be called on a Texture which was created with mipmaps enabled.");
if (isPixelFormatCompressed(format))
throw love::Exception("generateMipmaps cannot be called on a compressed Texture.");
gl.bindTextureToUnit(this, 0, false);
GLenum gltextype = OpenGL::getGLTextureType(texType);
if (gl.bugs.generateMipmapsRequiresTexture2DEnable)
glEnable(gltextype);
glGenerateMipmap(gltextype);
}
love::image::ImageData *Texture::newImageData(love::image::Image *module, int slice, int mipmap, const Rect &r)
{
// Base class does validation (only RTs allowed, etc) and creates ImageData.
love::image::ImageData *data = love::graphics::Texture::newImageData(module, slice, mipmap, r);
if (fbo == 0) // Should never be reached.
return data;
bool isSRGB = false;
OpenGL::TextureFormat fmt = gl.convertPixelFormat(data->getFormat(), false, isSRGB);
GLuint current_fbo = gl.getFramebuffer(OpenGL::FRAMEBUFFER_ALL);
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, getFBO());
if (slice > 0 || mipmap > 0)
{
int layer = texType == TEXTURE_CUBE ? 0 : slice;
int face = texType == TEXTURE_CUBE ? slice : 0;
gl.framebufferTexture(GL_COLOR_ATTACHMENT0, texType, texture, mipmap, layer, face);
}
glReadPixels(r.x, r.y, r.w, r.h, fmt.externalformat, fmt.type, data->getData());
if (slice > 0 || mipmap > 0)
gl.framebufferTexture(GL_COLOR_ATTACHMENT0, texType, texture, 0, 0, 0);
gl.bindFramebuffer(OpenGL::FRAMEBUFFER_ALL, current_fbo);
return data;
}
void Texture::setSamplerState(const SamplerState &s)
{
if (s.depthSampleMode.hasValue && !gl.isDepthCompareSampleSupported())
throw love::Exception("Depth comparison sampling in shaders is not supported on this system.");
// Base class does common validation and assigns samplerState.
love::graphics::Texture::setSamplerState(s);
if (!OpenGL::hasTextureFilteringSupport(getPixelFormat()))
{
samplerState.magFilter = samplerState.minFilter = SamplerState::FILTER_NEAREST;
if (samplerState.mipmapFilter == SamplerState::MIPMAP_FILTER_LINEAR)
samplerState.mipmapFilter = SamplerState::MIPMAP_FILTER_NEAREST;
}
// We don't want filtering or (attempted) mipmaps on the default texture.
if (usingDefaultTexture)
{
samplerState.mipmapFilter = SamplerState::MIPMAP_FILTER_NONE;
samplerState.minFilter = samplerState.magFilter = SamplerState::FILTER_NEAREST;
}
// If we only have limited NPOT support then the wrap mode must be CLAMP.
if ((GLAD_ES_VERSION_2_0 && !(GLAD_ES_VERSION_3_0 || GLAD_OES_texture_npot))
&& (pixelWidth != nextP2(pixelWidth) || pixelHeight != nextP2(pixelHeight) || depth != nextP2(depth)))
{
samplerState.wrapU = samplerState.wrapV = samplerState.wrapW = SamplerState::WRAP_CLAMP;
}
gl.bindTextureToUnit(this, 0, false);
gl.setSamplerState(texType, samplerState);
}
ptrdiff_t Texture::getHandle() const
{
return texture;
}
ptrdiff_t Texture::getRenderTargetHandle() const
{
return renderTarget ? (renderbuffer != 0 ? renderbuffer : texture) : 0;
}
} // opengl
} // graphics
} // love
@@ -21,7 +21,7 @@
#pragma once
// LOVE
#include "graphics/Image.h"
#include "graphics/Texture.h"
#include "graphics/Volatile.h"
// OpenGL
@@ -34,40 +34,47 @@ namespace graphics
namespace opengl
{
class Image final : public love::graphics::Image, public Volatile
class Texture final : public love::graphics::Texture, public Volatile
{
public:
Image(const Slices &data, const Settings &settings);
Image(TextureType textype, PixelFormat format, int width, int height, int slices, const Settings &settings);
Texture(const Settings &settings, const Slices *data);
virtual ~Image();
virtual ~Texture();
// Implements Volatile.
bool loadVolatile() override;
void unloadVolatile() override;
void generateMipmaps() override;
love::image::ImageData *newImageData(love::image::Image *module, int slice, int mipmap, const Rect &rect) override;
void setSamplerState(const SamplerState &s) override;
ptrdiff_t getHandle() const override;
ptrdiff_t getRenderTargetHandle() const override;
int getMSAA() const override { return actualSamples; }
void setFilter(const Texture::Filter &f) override;
bool setWrap(const Texture::Wrap &w) override;
bool setMipmapSharpness(float sharpness) override;
static bool isFormatSupported(PixelFormat pixelformat, bool sRGB);
inline GLuint getFBO() const { return fbo; }
private:
void uploadByteData(PixelFormat pixelformat, const void *data, size_t size, int level, int slice, const Rect &r) override;
void generateMipmaps() override;
void createTexture();
void loadDefaultTexture();
void loadData();
void uploadByteData(PixelFormat pixelformat, const void *data, size_t size, int level, int slice, const Rect &r, love::image::ImageDataBase *imgd = nullptr) override;
Slices slices;
GLuint fbo;
// OpenGL texture identifier.
GLuint texture;
GLuint renderbuffer;
}; // Image
GLenum framebufferStatus;
GLenum textureGLError;
int actualSamples;
}; // Texture
} // opengl
} // graphics