Created
April 4, 2019 06:04
-
-
Save haxpor/e17bfa955c0650cb6ea17c41d8dff626 to your computer and use it in GitHub Desktop.
Using recursive function (divide and conquer) to render ruler with SDL2. Compile with `gcc divide_and_conquer.c -lSDL2`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <SDL2/SDL.h> | |
#include <stdio.h> | |
#define SCREEN_WIDTH 640 | |
#define SCREEN_HEIGHT 480 | |
#define RULER_HEIGHT_FACTOR 5 | |
static const int base_line = SCREEN_HEIGHT / 2; | |
SDL_Window *window = NULL; | |
SDL_Renderer *renderer = NULL; | |
static void render_ruler(SDL_Renderer* renderer, int l, int r, int h); | |
static void render_mark(SDL_Renderer* renderer, int x, int h); | |
void render_ruler(SDL_Renderer* renderer, int l, int r, int h) | |
{ | |
int m = (l+r)/2; | |
if (h > 0) | |
{ | |
render_mark(renderer, m, h); | |
render_ruler(renderer, l, m, h-1); | |
render_ruler(renderer, m, r, h-1); | |
} | |
} | |
void render_mark(SDL_Renderer* renderer, int x, int h) | |
{ | |
SDL_RenderDrawLine(renderer, x, base_line, x, base_line - h*RULER_HEIGHT_FACTOR); | |
} | |
int main(int argc, char* argv[]) | |
{ | |
if (SDL_Init(SDL_INIT_VIDEO) < 0) { | |
SDL_Log("failed to init: %s", SDL_GetError()); | |
return -1; | |
} | |
window = SDL_CreateWindow( | |
"Ruler - Divide and Conquer", 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, | |
SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | |
); | |
if (window == NULL) { | |
SDL_Log("Failed to create window: %s", SDL_GetError()); | |
return -1; | |
} | |
renderer = SDL_CreateRenderer(window, -1, 0); | |
if (renderer == NULL) | |
{ | |
SDL_Log("Failed to create renderer: %s", SDL_GetError()); | |
return -1; | |
} | |
SDL_bool quit = SDL_FALSE; | |
while (!quit) | |
{ | |
SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); | |
SDL_RenderClear(renderer); | |
SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE); | |
render_ruler(renderer, 5, SCREEN_WIDTH-5, 5); | |
SDL_RenderPresent(renderer); | |
SDL_Event e; | |
// we need to call SDL_PollEvent to let window rendered, otherwise | |
// no window will be shown | |
while (SDL_PollEvent(&e) != 0) | |
{ | |
if (e.type == SDL_QUIT) | |
{ | |
quit = SDL_TRUE; | |
} | |
} | |
} | |
// free | |
if (renderer != NULL) | |
{ | |
SDL_DestroyRenderer(renderer); | |
renderer = NULL; | |
} | |
if (window != NULL) | |
{ | |
SDL_DestroyWindow(window); | |
window = NULL; | |
} | |
SDL_Quit(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment