Skip to content

Instantly share code, notes, and snippets.

@lemon32767
Last active April 4, 2020 11:02
Show Gist options
  • Save lemon32767/5a5f10a12b2685c6aba8ae819ecc5f5f to your computer and use it in GitHub Desktop.
Save lemon32767/5a5f10a12b2685c6aba8ae819ecc5f5f to your computer and use it in GitHub Desktop.
scanline based rendering with SDL2
#include <SDL2/SDL.h>
#include<math.h>
enum {FALSE ,TRUE};
enum {W=600,H=400};
int _SCROLLX = 0;
int _SCROLLY = 0;
SDL_Surface* screen;
float t = 0;
SDL_Surface* myimg = NULL;
void _HBLANK(int sc) {
_SCROLLX = -t*70 + 0.1*cos(t)*sc + sin(tan(t-sc*30))*-4 + cos(t/2+(float)sc/4.0)*3+1.5;
_SCROLLY = t*100 + sin(-t*4+(float)sc/16.0)*20;
}
void _VBLANK(void) {
SDL_BlitSurface(myimg, NULL, screen, NULL);
t += 0.01;
}
void _INIT(void) {
myimg = SDL_LoadBMP("myimg.bmp");
if (!myimg) {
printf("give me some bitmap file @ myimg.bmp\n");
exit(1234);
}
}
int imod(int x, int y) {
int m = x % y;
return m < 0 ? y+m : m;
}
int main() {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* win;
SDL_Renderer* ren;
SDL_SetHint(SDL_HINT_RENDER_VSYNC, "1");
SDL_CreateWindowAndRenderer(W,H,0,&win,&ren);
screen = SDL_CreateRGBSurfaceWithFormat(0,W,H,8*4, SDL_PIXELFORMAT_RGBA32);
SDL_Texture* tex = SDL_CreateTexture(ren, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STREAMING, W, H);
_INIT();
int quit = FALSE;
while (!quit) {
SDL_Event ev;
while (SDL_PollEvent(&ev)) {
if (ev.type == SDL_QUIT||(ev.type==SDL_KEYDOWN&&ev.key.keysym.sym==SDLK_ESCAPE)) quit = TRUE;
}
/////////////
_VBLANK();
SDL_SetRenderDrawColor(ren, 255, 0, 0, 255);
SDL_RenderClear(ren);
/*void* pix; int pitch;
SDL_LockTexture(tex, NULL, &pix, &pitch);
memset(pix, 0, pitch*H);
SDL_UnlockTexture(tex);*/
for (int i = 0; i < H; i++) {
int scrx = imod(-_SCROLLX, W), scry = imod(-_SCROLLY, H);
void* pix = screen->pixels;
SDL_Rect dstrc = {0, i, W, 1};
int y = (i+scry) % H;
if (scrx == 0 && scry == 0) {
SDL_UpdateTexture(tex, &dstrc, screen->pixels + y*screen->pitch, screen->pitch);
} else {
int w0 = W-scrx;
dstrc.w = w0;
SDL_UpdateTexture(tex, &dstrc, screen->pixels + y*screen->pitch + scrx*4, screen->pitch);
dstrc.x = w0;
int w1 = W-w0;
dstrc.w = w1;
SDL_UpdateTexture(tex, &dstrc, screen->pixels + y*screen->pitch, screen->pitch);
}
_HBLANK(i);
}
SDL_RenderCopy(ren, tex, NULL,NULL);
SDL_RenderPresent(ren);
}
SDL_Quit();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment