Minimal modern efficient cross platform 2D graphics painter in C
Minimal modern efficient cross platform 2D graphics painter in C
Minimal efficient cross platform 2D graphics painter in pure C using modern graphics API through the excellent Sokol GFX library.
Sokol GP, or in short SGP, stands for Sokol Graphics Painter.
Sokol GFX is an excellent library for rendering using unfixed pipelines of modern graphics cards, but it is too complex to use for simple 2D drawing, and it's API is too generic and specialized for 3D rendering. To draw 2D stuff, the programmer usually needs to setup custom shaders when using Sokol GFX, or use its Sokol GL extra library, but Sokol GL also has an API with 3D design in mind, which incurs some costs and limitations.
This library was created to draw 2D primitives through Sokol GFX with ease, and by not considering 3D usage it is optimized for 2D rendering only, furthermore it features an automatic batch optimizer, more details of it will be described below.
When drawing the library creates a draw command queue of all primitives yet to be drawn, every time a new draw command is added the batch optimizer looks back up to the last 8 recent draw commands (this is adjustable), and try to rearrange and merge drawing commands if it finds a previous draw command that meets the following criteria:
By doing this the batch optimizer is able for example to merge textured draw calls, even if they were drawn with other intermediary different textures draws between them. The effect is more efficiency when drawing, because less draw calls will be dispatched to the GPU,
This library can avoid a lot of work of making an efficient 2D drawing batching system, by automatically merging draw calls behind the scenes at runtime, thus the programmer does not need to manage batched draw calls manually, nor he needs to sort batched texture draw calls, the library will do this seamlessly behind the scenes.
The batching algorithm is fast, but it has O(n) CPU complexity for every new draw command added,
where n is the SGP_BATCH_OPTIMIZER_DEPTH configuration.
In experiments using 8 as the default is a good default,
but you may want to try out different values depending on your case.
Using values that are too high is not recommended, because the algorithm may take too long
scanning previous draw commands, and that may consume more CPU resources.
The batch optimizer can be disabled by setting SGP_BATCH_OPTIMIZER_DEPTH to 0,
you can use that to measure its impact.
In the samples directory of this repository there is a benchmark example that tests drawing with the bath optimizer enabled/disabled. On my machine that benchmark was able to increase performance in a 2.2x factor when it is enabled. In some private game projects the gains of the batch optimizer proved to increase FPS performance above 1.5x by just replacing the graphics backend with this library, with no internal changes to the game itself.
The library has some design choices with performance in mind that will be discussed briefly here.
Like Sokol GFX, Sokol GP will never do any allocation in the draw loop, so when initializing you must configure beforehand the maximum size of the draw command queue buffer and the vertices buffer.
All the 2D space transformation (functions like sgp_rotate) are done by the CPU and not by the GPU,
this is intentionally to avoid adding extra overhead in the GPU, because typically the number
of vertices of 2D applications are not that large, and it is more efficient to perform
all the transformation with the CPU right away rather than pushing extra buffers to the GPU
that ends up using more bandwidth of the CPUGPU bus.
In contrast 3D applications usually dispatches vertex transformations to the GPU using a vertex shader,
they do this because the amount of vertices of 3D objects can be very large
and it is usually the best choice, but this is not true for 2D rendering.
Many APIs to transform the 2D space before drawing a primitive are available, such as translate, rotate and scale. They can be used as similarly as the ones available in 3D graphics APIs, but they are crafted for 2D only, for example when using 2D we don't need to use a 4x4 or 3x3 matrix to perform vertex transformation, instead the code is specialized for 2D and can use a 2x3 matrix, saving extra CPU float computations.
All pipelines always use a texture associated with it, even when drawing non textured primitives, because this minimizes graphics pipeline changes when mixing textured calls and non textured calls, improving efficiency.
The library is coded in the style of Sokol GFX headers, reusing many macros from there,
you can change some of its semantics such as custom allocator, custom log function, and some
other details, read sokol_gfx.h documentation for more on that.
Copy sokol_gp.h along with other Sokol headers to the same folder. Setup Sokol GFX
as you usually would, then add call to sgp_setup(desc) just after sg_setup(desc), and
call to sgp_shutdown() just before sg_shutdown(). Note that you should usually check if
SGP is valid after its creation with sgp_is_valid() and exit gracefully with an error if not.
In your frame draw function add sgp_begin(width, height) before calling any SGP
draw function, then draw your primitives. At the end of the frame (or framebuffer) you
should ALWAYS call sgp_flush() between a Sokol GFX begin/end render pass,
the sgp_flush() will dispatch all draw commands to Sokol GFX. Then call sgp_end() immediately
to discard the draw command queue.
An actual example of this setup will be shown below.
The following is a quick example on how to this library with Sokol GFX and Sokol APP:
…To run this example, first copy the sokol_gp.h header alongside with other Sokol headers
to the same folder, then compile with any C compiler using the proper linking flags (read sokol_gfx.h).
In folder samples you can find the following complete examples covering all APIs of the library:
sgp_begin() with frame buffers.These examples are used as the test suite for the library, you can build them by typing make.
It is possible that after many draw calls the command or vertex buffer may overflow,
in that case the library will set an error error state and will continue to operate normally,
but when flushing the drawing command queue with sgp_flush() no draw command will be dispatched.
This can happen because the library uses pre allocated buffers, in such
cases the issue can be fixed by increasing the prefixed command queue buffer and the vertices buffer
when calling sgp_setup().
Making invalid number of push/pops of sgp_push_transform() and sgp_pop_transform(),
or nesting too many sgp_begin() and sgp_end() may also lead to errors, that
is a usage mistake.
You can enable the SOKOL_DEBUG macro in such cases to debug, or handle
the error programmatically by reading sgp_get_last_error() after calling sgp_end().
It is also advised to leave SOKOL_DEBUG enabled when developing with Sokol, so you can
catch mistakes early.
The library supports the most usual blend modes used in 2D, which are the following:
SGP_BLENDMODE_NONE - No blending (dstRGBA = srcRGBA).SGP_BLENDMODE_BLEND - Alpha blending (dstRGB = (srcRGB * srcA) + (dstRGB * (1-srcA)) and dstA = srcA + (dstA * (1-srcA)))SGP_BLENDMODE_BLEND_PREMULTIPLIED - Pre-multiplied alpha blending (dstRGBA = srcRGBA + (dstRGBA * (1-srcA)))SGP_BLENDMODE_ADD - Additive blending (dstRGB = (srcRGB * srcA) + dstRGB and dstA = dstA)SGP_BLENDMODE_ADD_PREMULTIPLIED - Pre-multiplied additive blending (dstRGB = srcRGB + dstRGB and dstA = dstA)SGP_BLENDMODE_MOD - Color modulate (dstRGB = srcRGB * dstRGB and dstA = dstA)SGP_BLENDMODE_MUL - Color multiply (dstRGB = (srcRGB * dstRGB) + (dstRGB * (1-srcA)) and dstA = (srcA * dstA) + (dstA * (1-srcA)))You can change the screen area to draw by calling sgp_viewport(x, y, width, height).
You can change the coordinate system of the 2D space by calling sgp_project(left, right, top, bottom),
with it.
You can translate, rotate or scale the 2D space before a draw call, by using the transformation
functions the library provides, such as sgp_translate(x, y), sgp_rotate(theta), etc.
Check the cheat sheet or the header for more.
To save and restore the transformation state you should call sgp_push_transform() and
later sgp_pop_transform().
The library provides drawing functions for all the basic primitives, that is,
for points, lines, triangles and rectangles, such as sgp_draw_line() and sgp_draw_filled_rect().
Check the cheat sheet or the header for more.
All of them have batched variations.
To draw textured rectangles you can use sgp_set_image(0, img) and then sgp_draw_filled_rect(),
this will draw an entire texture into a rectangle.
You should later reset the image with sgp_reset_image(0) to restore the bound image to default white image,
otherwise you will have glitches when drawing a solid color.
In case you want to draw a specific source from the texture,
you should use sgp_draw_textured_rect() instead.
By default textures are drawn using a simple nearest filter sampler,
you can change the sampler with sgp_set_sampler(0, smp) before drawing a texture,
it's recommended to restore the default sampler using sgp_reset_sampler(0).
All common
No open issues yet, or sync has not completed.