experiment #1: writing some pixels in the framebuffer device and cls
[winnie] / src / gfx.cc
1 #include <errno.h>
2 #include <limits.h>
3 #include <stdio.h>
4 #include <string.h>
5
6 #include <fcntl.h>
7 #include <sys/ioctl.h>
8 #include <sys/mman.h>
9 #include <unistd.h>
10
11 #include <linux/fb.h>
12
13 #include "gfx.h"
14
15 #define FRAMEBUFFER_SIZE(xsz, ysz, bpp) ((xsz) * (ysz) * (bpp) / CHAR_BIT)
16
17 static unsigned char* framebuffer;
18 static int dev_fd = -1;
19
20 static Rect screen_rect;
21 static int color_depth; //bits per pixel
22
23 bool init_gfx()
24 {
25         if((dev_fd = open("/dev/fb0", O_RDWR)) == -1) {
26                 fprintf(stderr, "Cannot open /dev/fb0 : %s\n", strerror(errno));
27                 return false;
28         }
29
30         fb_var_screeninfo sinfo;
31         if(ioctl(dev_fd, FBIOGET_VSCREENINFO, &sinfo) == -1) {
32                 close(dev_fd);
33                 dev_fd = -1;
34                 fprintf(stderr, "Unable to get screen info : %s\n", strerror(errno));
35                 return false;
36         }
37
38         printf("width : %d height : %d\n : bpp : %d\n", sinfo.xres, sinfo.yres, sinfo.bits_per_pixel);
39         printf("virtual w: %d virtual h: %d\n", sinfo.xres_virtual, sinfo.yres_virtual);
40
41         screen_rect.x = screen_rect.y = 0;
42         screen_rect.width = sinfo.xres_virtual;
43         screen_rect.height = sinfo.yres_virtual;
44         color_depth = sinfo.bits_per_pixel;
45
46         int sz = FRAMEBUFFER_SIZE(screen_rect.width, screen_rect.height, color_depth);
47         framebuffer = (unsigned char*)mmap(0, sz, PROT_READ | PROT_WRITE, MAP_SHARED, dev_fd, 0);
48
49         if(framebuffer == (void*)-1) {
50                 close(dev_fd);
51                 dev_fd = -1;
52                 fprintf(stderr, "Cannot map the framebuffer to memory : %s\n", strerror(errno));
53                 return false;
54         }
55
56         return true;
57 }
58
59 void destroy_gfx()
60 {
61         close(dev_fd);
62         dev_fd = -1;
63
64         munmap(framebuffer, FRAMEBUFFER_SIZE(screen_rect.width, screen_rect.height, color_depth));
65         framebuffer = 0;
66 }
67
68 unsigned char* get_framebuffer()
69 {
70         return framebuffer;
71 }
72
73 Rect get_screen_size()
74 {
75         return screen_rect;
76 }
77
78 int get_color_depth()
79 {
80         return color_depth;
81 }
82
83 void clear_screen(int r, int g, int b)
84 {
85         unsigned char* fb = framebuffer;
86         for(int i=0; i<screen_rect.width * screen_rect.height; i++) {
87                 *fb++ = r;
88                 *fb++ = g;
89                 *fb++ = b;
90                 fb++;
91         }
92 }
93
94 void set_cursor_visibility(bool visible)
95 {
96         fb_cursor curs;
97         curs.enable = visible ? 1 : 0;
98
99         if(ioctl(dev_fd, FBIO_CURSOR, &curs) == -1) {
100                 fprintf(stderr, "Cannot toggle cursor visibility : %s\n", strerror(errno));
101         }
102 }