-
Notifications
You must be signed in to change notification settings - Fork 0
/
pbm.c
72 lines (70 loc) · 1.26 KB
/
pbm.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "pbm.h"
#include <stdbool.h>
SDL_Surface *pbm_string(string s)
{
if(!s.buf) return(NULL);
if(s.i<3) return(NULL);
if(strncmp(s.buf, "P4\n", 3)) return(NULL);
unsigned int w, h;
unsigned int i=3,j;
if(i==s.i) return(NULL);
while(s.buf[i]=='#')
{
unsigned int l=strcspn(s.buf+i, "\n");
if(i+l>=s.i) return(NULL);
i+=l;
}
j=i;
while(i<s.i)
{
if(s.buf[i]==' ') break;
i++;
}
s.buf[i++]=0;
sscanf(s.buf+j, "%u", &w);
j=i;
while(i<s.i)
{
if(s.buf[i]=='\n') break;
i++;
}
s.buf[i++]=0;
sscanf(s.buf+j, "%u", &h);
SDL_Surface *rv=SDL_CreateRGBSurface(SDL_HWSURFACE, w, h, 32, 0xFF0000, 0xFF00, 0xFF, 0xFF000000);
if(!rv) return(NULL);
for(unsigned int y=0;y<h;y++)
{
if(i<s.i)
{
for(unsigned int x=0;x<w;x++)
{
if(x&&!(x&7))
{
if(++i>=s.i)
{
SDL_FreeSurface(rv);
return(NULL);
}
}
bool px=s.buf[i]&(1<<(7-(x&7)));
if(px) SDL_FillRect(rv, &(SDL_Rect){x, y, 1, 1}, SDL_MapRGB(rv->format, 0, 0, 0));
}
}
else
{
SDL_FreeSurface(rv);
return(NULL);
}
i++;
}
return(rv);
}
int pbm_putheader(FILE *f, unsigned int w, unsigned int h)
{
if(!f) return(0);
int bytes=0;
fprintf(f, "P1\n%u %n%u", w, &bytes, h);
if(!h) fprintf(f, " ");
fprintf(f, "\n");
return(bytes);
}