TeX/src/platform/sdl2.c

143 lines
2.7 KiB
C

//---
// SDL interface: for rendering tests on computer
//---
#ifdef TEX_PLATFORM_SDL
#include <SDL2/SDL.h>
#include <stdlib.h>
#include <TeX/TeX.h>
#include <TeX/parser.h>
/* Rendering window and renderer */
static SDL_Window *w = NULL;
static SDL_Renderer *r = NULL;
//---
// Interface functions
//---
/* intf_pixel() - Set a single pixel */
void intf_pixel(int x, int y, int color)
{
int R = color >> 16;
int G = (color >> 8) & 0xff;
int B = color & 0xff;
SDL_SetRenderDrawColor(r, R, G, B, 255);
SDL_RenderDrawPoint(r, x, y);
}
/* intf_line() - Draw a line */
void intf_line(int x1, int y1, int x2, int y2, int color)
{
int R = color >> 16;
int G = (color >> 8) & 0xff;
int B = color & 0xff;
SDL_SetRenderDrawColor(r, R, G, B, 255);
SDL_RenderDrawLine(r, x1, y1, x2, y2);
}
/* intf_size() - Get the dimensions of a string */
void intf_size(char const *str, int *width, int *height)
{
*width = 6 * strlen(str) - 1;
*height = 7;
}
/* intf_text() - Draw variable-width text */
void intf_text(char const *str, int x, int y, int color)
{
int R = color >> 16;
int G = (color >> 8) & 0xff;
int B = color & 0xff;
SDL_SetRenderDrawColor(r, R, G, B, 255);
SDL_Rect rect = { .x = x, .y = y };
intf_size(str, &rect.w, &rect.h);
SDL_RenderDrawRect(r, &rect);
}
//---
// Initialization and finalization
//---
__attribute__((constructor))
static void init(void)
{
if(SDL_Init(SDL_INIT_VIDEO) < 0)
{
fprintf(stderr, "error: cannot initialize SDL backend: %s\n",
SDL_GetError());
exit(1);
}
int c = SDL_WINDOWPOS_CENTERED;
w = SDL_CreateWindow("2D rendering", c, c, 256, 128, 0);
if(!w)
{
fprintf(stderr, "error: cannot create SDL window: %s\n",
SDL_GetError());
exit(1);
}
r = SDL_CreateRenderer(w, -1, SDL_RENDERER_ACCELERATED);
if(!r)
{
fprintf(stderr, "error: cannot create SDL renderer: %s\n",
SDL_GetError());
exit(1);
}
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0");
/* Make the window visible */
SDL_RenderPresent(r);
/* Set interface functions */
TeX_intf_pixel(intf_pixel);
TeX_intf_line(intf_line);
TeX_intf_size(intf_size);
TeX_intf_text(intf_text);
}
__attribute__((destructor))
static void fini(void)
{
if(w) SDL_DestroyWindow(w);
SDL_Quit();
}
//---
// Backend example
//---
int main(void)
{
char const * formula = "\\frac{x_7}{"
"\\left\\{\\frac{\\frac{2}{3}}{27}\\right\\}^2"
"}";
struct TeX_Flow *flow = TeX_parse(formula);
if(!flow) { puts("parsing error!"); return 1; }
TeX_debug_flow(flow, 0);
SDL_SetRenderDrawColor(r, 0xff, 0xff, 0xff, 0xff);
SDL_RenderClear(r);
TeX_draw(flow, 10, 10, 0x000000);
SDL_RenderPresent(r);
SDL_Event e;
while(1)
{
SDL_WaitEvent(&e);
if(e.type == SDL_QUIT) break;
}
TeX_free(flow);
return 0;
}
#endif /* TEX_PLATFORM_SDL */