Browse Source

TextureTools: make distance field processing into a stateful class.

pull/297/head
Vladimír Vondruš 8 years ago
parent
commit
f0bb710cd3
  1. 6
      doc/changelog.dox
  2. 4
      src/Magnum/Text/DistanceFieldGlyphCache.cpp
  3. 5
      src/Magnum/Text/DistanceFieldGlyphCache.h
  4. 90
      src/Magnum/TextureTools/DistanceField.cpp
  5. 109
      src/Magnum/TextureTools/DistanceField.h
  6. 11
      src/Magnum/TextureTools/Test/DistanceFieldGLTest.cpp
  7. 2
      src/Magnum/TextureTools/distancefieldconverter.cpp

6
doc/changelog.dox

@ -82,6 +82,12 @@ See also:
- Fixed various broken links (see [mosra/magnum#291](https://github.com/mosra/magnum/issues/291)) - Fixed various broken links (see [mosra/magnum#291](https://github.com/mosra/magnum/issues/291))
@subsection changelog-latest-deprecated Deprecated APIs
- `TextureTools::distanceField()` is deprecated due to inefficiency of its
statelessness when doing batch processing. Use the
@ref TextureTools::DistanceField class instead.
@section changelog-2018-10 2018.10 @section changelog-2018-10 2018.10
Released 2018-10-23, tagged as Released 2018-10-23, tagged as

4
src/Magnum/Text/DistanceFieldGlyphCache.cpp

@ -46,7 +46,7 @@ DistanceFieldGlyphCache::DistanceFieldGlyphCache(const Vector2i& originalSize, c
#else #else
GlyphCache(GL::TextureFormat::RGB, originalSize, size, Vector2i(radius)), GlyphCache(GL::TextureFormat::RGB, originalSize, size, Vector2i(radius)),
#endif #endif
_scale{Vector2(size)/Vector2(originalSize)}, _radius{radius} _scale{Vector2(size)/Vector2(originalSize)}, _distanceField{radius}
{ {
#ifndef MAGNUM_TARGET_GLES #ifndef MAGNUM_TARGET_GLES
MAGNUM_ASSERT_GL_EXTENSION_SUPPORTED(GL::Extensions::ARB::texture_rg); MAGNUM_ASSERT_GL_EXTENSION_SUPPORTED(GL::Extensions::ARB::texture_rg);
@ -89,7 +89,7 @@ void DistanceFieldGlyphCache::setImage(const Vector2i& offset, const ImageView2D
#endif #endif
/* Create distance field from input texture */ /* Create distance field from input texture */
TextureTools::distanceField(input, texture(), Range2Di::fromSize(offset*_scale, image.size()*_scale), _radius, image.size()); _distanceField(input, texture(), Range2Di::fromSize(offset*_scale, image.size()*_scale), image.size());
} }
void DistanceFieldGlyphCache::setDistanceFieldImage(const Vector2i& offset, const ImageView2D& image) { void DistanceFieldGlyphCache::setDistanceFieldImage(const Vector2i& offset, const ImageView2D& image) {

5
src/Magnum/Text/DistanceFieldGlyphCache.h

@ -30,6 +30,7 @@
*/ */
#include "Magnum/Text/GlyphCache.h" #include "Magnum/Text/GlyphCache.h"
#include "Magnum/TextureTools/DistanceField.h"
namespace Magnum { namespace Text { namespace Magnum { namespace Text {
@ -85,8 +86,8 @@ class MAGNUM_TEXT_EXPORT DistanceFieldGlyphCache: public GlyphCache {
void setDistanceFieldImage(const Vector2i& offset, const ImageView2D& image); void setDistanceFieldImage(const Vector2i& offset, const ImageView2D& image);
private: private:
const Vector2 _scale; Vector2 _scale;
const UnsignedInt _radius; TextureTools::DistanceField _distanceField;
}; };
}} }}

90
src/Magnum/TextureTools/DistanceField.cpp

@ -53,7 +53,7 @@ class DistanceFieldShader: public GL::AbstractShaderProgram {
public: public:
typedef GL::Attribute<0, Vector2> Position; typedef GL::Attribute<0, Vector2> Position;
explicit DistanceFieldShader(Int radius); explicit DistanceFieldShader(UnsignedInt radius);
DistanceFieldShader& setScaling(const Vector2& scaling) { DistanceFieldShader& setScaling(const Vector2& scaling) {
setUniform(scalingUniform, scaling); setUniform(scalingUniform, scaling);
@ -79,7 +79,7 @@ class DistanceFieldShader: public GL::AbstractShaderProgram {
imageSizeInvertedUniform; imageSizeInvertedUniform;
}; };
DistanceFieldShader::DistanceFieldShader(Int radius) { DistanceFieldShader::DistanceFieldShader(const UnsignedInt radius) {
#ifdef MAGNUM_BUILD_STATIC #ifdef MAGNUM_BUILD_STATIC
/* Import resources on static build, if not already */ /* Import resources on static build, if not already */
if(!Utility::Resource::hasGroup("MagnumTextureTools")) if(!Utility::Resource::hasGroup("MagnumTextureTools"))
@ -142,36 +142,71 @@ DistanceFieldShader::DistanceFieldShader(Int radius) {
} }
} }
#ifndef MAGNUM_TARGET_GLES
void distanceField(GL::Texture2D& input, GL::Texture2D& output, const Range2Di& rectangle, const Int radius, const Vector2i&) struct DistanceField::State {
#else explicit State(UnsignedInt radius): shader{radius}, radius{radius} {}
void distanceField(GL::Texture2D& input, GL::Texture2D& output, const Range2Di& rectangle, const Int radius, const Vector2i& imageSize)
#endif DistanceFieldShader shader;
{ UnsignedInt radius;
GL::Mesh mesh;
};
DistanceField::DistanceField(const UnsignedInt radius): _state{new State{radius}} {
#ifndef MAGNUM_TARGET_GLES #ifndef MAGNUM_TARGET_GLES
MAGNUM_ASSERT_GL_EXTENSION_SUPPORTED(GL::Extensions::ARB::framebuffer_object); MAGNUM_ASSERT_GL_EXTENSION_SUPPORTED(GL::Extensions::ARB::framebuffer_object);
#endif #endif
_state->mesh.setPrimitive(GL::MeshPrimitive::Triangles)
.setCount(3);
/* Older GLSL doesn't have gl_VertexID, vertices must be supplied explicitly */
#ifndef MAGNUM_TARGET_GLES
if(!GL::Context::current().isVersionSupported(GL::Version::GL300))
#else
if(!GL::Context::current().isVersionSupported(GL::Version::GLES300))
#endif
{
constexpr Vector2 triangle[] = {
Vector2(-1.0, 1.0),
Vector2(-1.0, -3.0),
Vector2( 3.0, 1.0)
};
GL::Buffer buffer;
buffer.setData(triangle, GL::BufferUsage::StaticDraw);
_state->mesh.addVertexBuffer(std::move(buffer), 0, DistanceFieldShader::Position());
}
}
DistanceField::~DistanceField() = default;
UnsignedInt DistanceField::radius() const { return _state->radius; }
void DistanceField::operator()(GL::Texture2D& input, GL::Texture2D& output, const Range2Di& rectangle, const Vector2i&
#ifdef MAGNUM_TARGET_GLES
imageSize
#endif
) {
/** @todo Disable depth test, blending and then enable it back (if was previously) */ /** @todo Disable depth test, blending and then enable it back (if was previously) */
#ifndef MAGNUM_TARGET_GLES #ifndef MAGNUM_TARGET_GLES
Vector2i imageSize = input.imageSize(0); Vector2i imageSize = input.imageSize(0);
#endif #endif
GL::Framebuffer framebuffer(rectangle); /* Framebuffer is instantiated here so it gets correctly unbound at the end
framebuffer.attachTexture(GL::Framebuffer::ColorAttachment(0), output, 0); (and bound framebuffer reset back to the default) */
framebuffer.bind(); GL::Framebuffer framebuffer{rectangle};
framebuffer.clear(GL::FramebufferClear::Color); framebuffer.attachTexture(GL::Framebuffer::ColorAttachment(0), output, 0)
.clear(GL::FramebufferClear::Color)
.bind();
const GL::Framebuffer::Status status = framebuffer.checkStatus(GL::FramebufferTarget::Draw); const GL::Framebuffer::Status status = framebuffer.checkStatus(GL::FramebufferTarget::Draw);
if(status != GL::Framebuffer::Status::Complete) { if(status != GL::Framebuffer::Status::Complete) {
Error() << "TextureTools::distanceField(): cannot render to given output texture, unexpected framebuffer status" Error() << "TextureTools::DistanceField: cannot render to given output texture, unexpected framebuffer status"
<< status; << status;
return; return;
} }
DistanceFieldShader shader{radius}; _state->shader.setScaling(Vector2(imageSize)/Vector2(rectangle.size()))
shader.setScaling(Vector2(imageSize)/Vector2(rectangle.size()))
.bindTexture(input); .bindTexture(input);
#ifndef MAGNUM_TARGET_GLES #ifndef MAGNUM_TARGET_GLES
@ -180,32 +215,11 @@ void distanceField(GL::Texture2D& input, GL::Texture2D& output, const Range2Di&
if(!GL::Context::current().isVersionSupported(GL::Version::GLES300)) if(!GL::Context::current().isVersionSupported(GL::Version::GLES300))
#endif #endif
{ {
shader.setImageSizeInverted(1.0f/Vector2(imageSize)); _state->shader.setImageSizeInverted(1.0f/Vector2(imageSize));
}
GL::Mesh mesh;
mesh.setPrimitive(GL::MeshPrimitive::Triangles)
.setCount(3);
/* Older GLSL doesn't have gl_VertexID, vertices must be supplied explicitly */
GL::Buffer buffer;
#ifndef MAGNUM_TARGET_GLES
if(!GL::Context::current().isVersionSupported(GL::Version::GL300))
#else
if(!GL::Context::current().isVersionSupported(GL::Version::GLES300))
#endif
{
constexpr Vector2 triangle[] = {
Vector2(-1.0, 1.0),
Vector2(-1.0, -3.0),
Vector2( 3.0, 1.0)
};
buffer.setData(triangle, GL::BufferUsage::StaticDraw);
mesh.addVertexBuffer(buffer, 0, DistanceFieldShader::Position());
} }
/* Draw the mesh */ /* Draw the mesh */
mesh.draw(shader); _state->mesh.draw(_state->shader);
} }
}} }}

109
src/Magnum/TextureTools/DistanceField.h

@ -29,6 +29,8 @@
* @brief Function @ref Magnum::TextureTools::distanceField() * @brief Function @ref Magnum::TextureTools::distanceField()
*/ */
#include <memory>
#include "Magnum/configure.h" #include "Magnum/configure.h"
#ifdef MAGNUM_TARGET_GL #ifdef MAGNUM_TARGET_GL
@ -42,37 +44,29 @@
namespace Magnum { namespace TextureTools { namespace Magnum { namespace TextureTools {
/** /**
@brief Create signed distance field @brief Create a signed distance field
@param input Input texture
@param output Output texture Converts a binary black/white image (stored in the red channel of @p input) to
@param rectangle Rectangle in output texture where to render a signed distance field (stored in the red channel of @p output @p rectangle).
@param radius Max lookup radius in input texture The purpose of this function is to convert a high-resolution binary image (such
@param imageSize Input texture size. Needed only in OpenGL ES, in desktop as vector artwork or font glyphs) to a low-resolution grayscale image. The
OpenGL the information is gathered automatically using image will then occupy much less memory and can be scaled without aliasing
@ref GL::Texture2D::imageSize(). issues. Additionally it provides foundation for features like outlining, glow
or drop shadow essentially for free.
Converts binary image (stored in red channel of @p input) to signed distance
field (stored in red channel in @p rectangle of @p output). The purpose of this
function is to convert high-resolution binary image (such as vector artwork or
font glyphs) to low-resolution grayscale image. The image will then occupy much
less memory and can be scaled without aliasing issues. Additionally it provides
foundation for features like outlining, glow or drop shadow essentially for
free.
You can also use the @ref magnum-distancefieldconverter "magnum-distancefieldconverter" You can also use the @ref magnum-distancefieldconverter "magnum-distancefieldconverter"
utility to do distance field conversion on command-line. By extension, this utility to do distance field conversion on command-line. This functionality is
functionality is also provided through @ref magnum-fontconverter "magnum-fontconverter" also used inside the @ref magnum-fontconverter "magnum-fontconverter" utility.
utility.
### The algorithm @section TextureTools-DistanceField-algorithm The algorithm
For each pixel inside @p rectangle the algorithm looks at corresponding pixel in For each pixel inside the @p output sub-rectangle the algorithm looks at
@p input and tries to find nearest pixel of opposite color in area given by corresponding pixel in the input and tries to find nearest pixel of opposite
@p radius. Signed distance between the points is then saved as value of given color in an area defined @p radius. Signed distance between the points is then
pixel in @p output. Value of 1.0 means that the pixel was originally colored saved as value of given pixel in @p output. Value of 1.0 means that the pixel
white and nearest black pixel is farther than @p radius, value of 0.0 means was originally colored white and nearest black pixel is farther than @p radius,
that the pixel was originally black and nearest white pixel is farther than value of 0.0 means that the pixel was originally black and nearest white pixel
@p radius. Values around 0.5 are around edges. is farther than @p radius. Values around 0.5 are around edges.
The resulting texture can be used with bilinear filtering. It can be converted The resulting texture can be used with bilinear filtering. It can be converted
back to binary form in shader using e.g. GLSL @glsl smoothstep() @ce function back to binary form in shader using e.g. GLSL @glsl smoothstep() @ce function
@ -84,13 +78,14 @@ Based on: *Chris Green - Improved Alpha-Tested Magnification for Vector Textures
and Special Effects, SIGGRAPH 2007, and Special Effects, SIGGRAPH 2007,
http://www.valvesoftware.com/publications/2007/SIGGRAPH2007_AlphaTestedMagnification.pdf* http://www.valvesoftware.com/publications/2007/SIGGRAPH2007_AlphaTestedMagnification.pdf*
@attention This is GPU-only implementation, so it expects active context. @attention This is a GPU-only implementation, so it expects an active GL
context.
@note If internal format of @p output texture is not renderable, this function @note If internal format of @p output texture is not renderable, this function
prints message to error output and does nothing. In desktop OpenGL and prints a message to error output and does nothing. On desktop OpenGL and
OpenGL ES 3.0 it's common to render to @ref GL::TextureFormat::R8. In OpenGL ES 3.0 it's common to render to @ref GL::TextureFormat::R8. On
OpenGL ES 2.0 you can use @ref GL::TextureFormat::Red if OpenGL ES 2.0 you can use @ref GL::TextureFormat::Red if
@gl_extension{EXT,texture_rg} is available, if not, the smallest but still @gl_extension{EXT,texture_rg} is available; if not, the smallest but still
inefficient supported format is in most cases @ref GL::TextureFormat::RGB, inefficient supported format is in most cases @ref GL::TextureFormat::RGB,
rendering to @ref GL::TextureFormat::Luminance is not supported in most rendering to @ref GL::TextureFormat::Luminance is not supported in most
cases. cases.
@ -102,10 +97,54 @@ http://www.valvesoftware.com/publications/2007/SIGGRAPH2007_AlphaTestedMagnifica
@bug ES (and maybe GL < 3.20) implementation behaves slightly different @bug ES (and maybe GL < 3.20) implementation behaves slightly different
(jaggies, visible e.g. when rendering outlined fonts) (jaggies, visible e.g. when rendering outlined fonts)
*/ */
#ifndef MAGNUM_TARGET_GLES class MAGNUM_TEXTURETOOLS_EXPORT DistanceField {
void MAGNUM_TEXTURETOOLS_EXPORT distanceField(GL::Texture2D& input, GL::Texture2D& output, const Range2Di& rectangle, Int radius, const Vector2i& imageSize = Vector2i()); public:
#else /**
void MAGNUM_TEXTURETOOLS_EXPORT distanceField(GL::Texture2D& input, GL::Texture2D& output, const Range2Di& rectangle, Int radius, const Vector2i& imageSize); * @brief Constructor
* @param radius Max lookup radius in the input texture
*
* Prepares the shader and other internal state for given @p radius.
*/
explicit DistanceField(UnsignedInt radius);
~DistanceField();
/** @brief Max lookup radius */
UnsignedInt radius() const;
/**
* @brief Calculate the distance field
* @param input Input texture
* @param output Output texture
* @param rectangle Rectangle in output texture where to render
* @param imageSize Input texture size. Needed only for OpenGL ES,
* on desktop GL the information is gathered automatically using
* @ref GL::Texture2D::imageSize().
*/
void operator()(GL::Texture2D& input, GL::Texture2D& output, const Range2Di& rectangle, const Vector2i& imageSize
#ifndef MAGNUM_TARGET_GLES
= {}
#endif
);
private:
struct State;
std::unique_ptr<State> _state;
};
#ifdef MAGNUM_BUILD_DEPRECATED
/**
@brief Create a signed distance field
@deprecated Deprecated due to inefficiency of its statelessness when doing
batch processing. Use the @ref DistanceField class instead.
*/
inline CORRADE_DEPRECATED("use the DistanceField class instead") void distanceField(GL::Texture2D& input, GL::Texture2D& output, const Range2Di& rectangle, Int radius, const Vector2i& imageSize
#ifndef MAGNUM_TARGET_GLES
= Vector2i{}
#endif
) {
DistanceField{UnsignedInt(radius)}(input, output, rectangle, imageSize);
}
#endif #endif
}} }}

11
src/Magnum/TextureTools/Test/DistanceFieldGLTest.cpp

@ -132,7 +132,12 @@ void DistanceFieldGLTest::test() {
.setMagnificationFilter(GL::SamplerFilter::Nearest) .setMagnificationFilter(GL::SamplerFilter::Nearest)
.setStorage(1, outputFormat, Vector2i{64}); .setStorage(1, outputFormat, Vector2i{64});
TextureTools::distanceField(input, output, {{}, Vector2i{64}}, 32 TextureTools::DistanceField distanceField{32};
CORRADE_COMPARE(distanceField.radius(), 32);
MAGNUM_VERIFY_NO_GL_ERROR();
distanceField(input, output, {{}, Vector2i{64}}
#ifdef MAGNUM_TARGET_GLES #ifdef MAGNUM_TARGET_GLES
, inputImage->size() , inputImage->size()
#endif #endif
@ -218,13 +223,15 @@ void DistanceFieldGLTest::benchmark() {
MAGNUM_VERIFY_NO_GL_ERROR(); MAGNUM_VERIFY_NO_GL_ERROR();
TextureTools::DistanceField distanceField{32};
/* So it doesn't spam too much */ /* So it doesn't spam too much */
GL::DebugOutput::setCallback(nullptr); GL::DebugOutput::setCallback(nullptr);
CORRADE_BENCHMARK(5) { CORRADE_BENCHMARK(5) {
/* This is creating the shader from scratch every time, so no wonder /* This is creating the shader from scratch every time, so no wonder
it's so freaking slow */ it's so freaking slow */
TextureTools::distanceField(input, output, {{}, Vector2i{64}}, 32 distanceField(input, output, {{}, Vector2i{64}}
#ifdef MAGNUM_TARGET_GLES #ifdef MAGNUM_TARGET_GLES
, inputImage->size() , inputImage->size()
#endif #endif

2
src/Magnum/TextureTools/distancefieldconverter.cpp

@ -203,7 +203,7 @@ int DistanceFieldConverter::exec() {
/* Do it */ /* Do it */
Debug() << "Converting image of size" << image->size() << "to distance field..."; Debug() << "Converting image of size" << image->size() << "to distance field...";
TextureTools::distanceField(input, output, {{}, args.value<Vector2i>("output-size")}, args.value<Int>("radius"), image->size()); TextureTools::DistanceField{args.value<UnsignedInt>("radius")}(input, output, {{}, args.value<Vector2i>("output-size")}, image->size());
/* Save image */ /* Save image */
Image2D result{PixelFormat::R8Unorm}; Image2D result{PixelFormat::R8Unorm};

Loading…
Cancel
Save