More to come...
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

550 lines
33KB

  1. #ifndef CHAPTER_2_SOURCE
  2. #define CHAPTER_2_SOURCE
  3. #include <stdlib.h>
  4. #include <termios.h> // Terminal input, output and configuration.
  5. #include <sys/ioctl.h> // Rest is some Linux related cancer...
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include "chapter_2.h" // We're copying function and variable declarations from this file here. This shouldn't be copied twice, more on that later...
  9. #define CURSES_FORMAT ((int) sizeof ("\033[-;3-m-\033[0m") - 1) // We'll use these three macros through-out cursed functions.
  10. #define CURSES_REVERT ((int) sizeof ("\033[H") - 1)
  11. #define CURSES_CURSOR ((int) sizeof ("\033[---;---H") - 1)
  12. /*
  13. Function 'hello_world_0' uses (rougly said) a system call instead of a function, but I don't even know what will different compilers do to that line of code. What's a system call?
  14. Well, when you're writing assembly, you have some general purpose registers, on mine and your machine, there's 16 of them, and you move some data in them, then use 'syscall'
  15. instruction, which magically does something, like open or close a file descriptor, read or write to it, but more on that later! A lot more... Important thing to know is that when
  16. you use keyword 'sizeof' on a string, it'll count null terminator, so it'll have value 14, and type 'size_t'. It's provided in <unistd.h> header file.
  17. @C
  18. write ( // mov rax 1 ; Literal of Linux write system call, defined internally.
  19. STDOUT_FILENO, // mov rdi 1 ; Literal of standard output file descriptor, defined as 'STDOUT_FILENO'.
  20. "Hello world!\n", // mov rsi X ; Address of our string.
  21. sizeof ("Hello world!\n") // mov rdx [Y] ; Literal of size of our string.
  22. ); // syscall ; Ask kernel to do some work.
  23. @
  24. We'll talk about assembly a lot in future chapters, but you should filter that out of your brain until you learn C well...
  25. */
  26. void hello_world_0 (void) {
  27. write (STDOUT_FILENO, "Hello world!\n", sizeof ("Hello world!\n"));
  28. }
  29. /*
  30. In function 'hello_world_1' we're using function 'puts' this time, which is considered unsafe because it'll fail when input string isn't null terminated. Keep in mind that it also
  31. prints line feed (new line) on the end. Why I call it line feed? Some terminals and text editors distinguish carriage return ('\r' / 13 / CR) and line feed ('\n' / 10 / LF), and
  32. some of them use both, like old teleprinters used to do, where the name 'tty' on UNIX-based operating systems comes from.
  33. */
  34. void hello_world_1 (void) {
  35. puts ("Hello world!");
  36. }
  37. /*
  38. Now, in function 'hello_world_2' and function 'hello_world_3', we're using 'printf' function, which is in my opinion important for debugging. It has many variations, so we'll have
  39. a separate chapter only about it. Know that it's a variadic function, which means that it can take more than one input argument, and later we'll learn to make our own variadic
  40. functions as well. It's also a bit unsafe, if you're not careful how you use it, but nothing drastic can happen, most compilers catch those kinds of errors.
  41. */
  42. void hello_world_2 (void) {
  43. printf ("Hello world!\n");
  44. }
  45. /*
  46. It's also worth noting that we're using it's arguments in function 'hello_world_3', function 'printf' will print characters one by one from its' format, until it encounters '%',
  47. if the next character is '%', it prints one '%', if it's 's', then it'll print a string, which we provide in the next argument. When compiler optimizations are turned on, it will
  48. change all sorts of things here, since it's obvious that we're using simple string in this example.
  49. */
  50. void hello_world_3 (void) {
  51. printf ("%s %s!\n", "Hello", "world");
  52. }
  53. /*
  54. Lastly, we have a global variable, some people like to call it that, and consider it evil. It's not evil if you know the pros and cons of using them, which causes intellectual
  55. overhead for certain sort of people. Pros, makes your code shorter and easier to refactor. Cons, it can potentially make your code less safe if you don't know what you're doing.
  56. You should use them, external variables as I like to call them, when you're working on your programs or in a small group, but they can lead to bad things if you're working with a
  57. lot of people, someone could change it in some bad place, and cause a bug that's difficult to track.
  58. We could initialize it also in any part of our code later, in some function for example, as following:
  59. @C
  60. // One by one:
  61. hello_world [0] = hello_world_0;
  62. hello_world [1] = hello_world_1;
  63. hello_world [2] = hello_world_2;
  64. hello_world [3] = hello_world_3;
  65. // Or use it for some completely unrelated function if we wanted to, as long as function "kind" is same, they both take no input and no output:
  66. static void unrelated_function (void) {
  67. puts ("I couldn't care less...");
  68. exit (EXIT_FAILURE);
  69. }
  70. hello_world [2] = unrelated_function;
  71. @
  72. Just know that an array(s) of function pointers is my favorite kind of variable for bot AI in simple games, index can be derived from bot state.
  73. */
  74. void (* hello_world [4]) (void) = {
  75. hello_world_0,
  76. hello_world_1,
  77. hello_world_2,
  78. hello_world_3
  79. };
  80. /*
  81. Now, we'll talk more about cursed functions! I broke code formatting rules for this, but it's worth it, time to learn. Function or variable with 'static' instead of 'extern'
  82. keyword before it is internal. That means it'll only be accessable in this file. That way, I can include file "chapter_2.h" in some other file, and know that I can't access or
  83. modify some internal variable within that other file. They can only be accessed or modified in this file! Lets show some formatting examples below:
  84. @C
  85. static int my_size = 0;
  86. static char * my_name = "Name";
  87. static void * my_data = NULL;
  88. @
  89. Unlike when declaring external variables (seen in previous header files), you need to initialize internal variables to some value, like you see above. You shouldn't initialize
  90. external variables, they have separate definition (initialization in this case). You can see them just below, they are initialized without 'extern' in front of them, and the same
  91. goes for functions declared in "chapter_2.h", but there's another trick to this... You can declare internal functions before defining them, so you have 2 options for them:
  92. @C
  93. // Option A:
  94. static int my_function (char * name, int size);
  95. // ...
  96. int my_function (char * name, int size) {
  97. int data = 0;
  98. // Do some work involving function arguments and modify data.
  99. return (data);
  100. }
  101. // Option B:
  102. static int my_function (char * name, int size) {
  103. int data = 0;
  104. // Do some work involving function arguments and modify data.
  105. return (data);
  106. }
  107. @
  108. Okay, external variables you see lower (without 'static') are all integers. Lets briefly see what types are the internal variables.
  109. - curses_format / curses_cursor: Array of characters (also known as string!), and their size is already known at the compile time, it's inside square braces.
  110. - curses_screen: Pointer to character, we'll allocate memory for it later, so it'll be a dynamic array of characters, its' size can change.
  111. - curses_activator: Pointer to integer, we'll also allocate memory for it, so we can't use square braces for those. Remember that for later.
  112. - curses_action: Strictly speaking, pointer to another pointer to function of signature 'void SOMETHING (void);', but ignore it for now, don't get confused.
  113. */
  114. static char curses_format [CURSES_FORMAT + 1] = "\033[-;3-m-\033[0m"; // Internal variable holding data for rendering single character, using ASCII escape sequences.
  115. static char curses_cursor [CURSES_CURSOR + 1] = "\033[---;---H"; // Internal variable holding data for rendering cursor at some position.
  116. static char * curses_screen = NULL; // We hold all terminal screen data here, you can think of it as an image, but better word is a framebuffer.
  117. static int curses_action_count = 0; // Count of defined actions, these are part of event handling system.
  118. static int * curses_activator = NULL; // Array of action signals, when they are active, action is executed.
  119. static void (* * curses_action) (void) = NULL; // Array of function pointers, we use it to set event actions, so that user can interact with the terminal.
  120. static struct termios curses_old_terminal; // This is <termios.h> magic for making terminal enter and exit the raw mode.
  121. static struct termios curses_new_terminal;
  122. // We've explained these external variables in header file already.
  123. int curses_character = 0;
  124. int curses_signal = SIGNAL_NONE;
  125. int curses_screen_width = 0;
  126. int curses_screen_height = 0;
  127. int curses_active = FALSE;
  128. /*
  129. I need to quickly explain how I'm structuring this subprogram. You can think of functions and variables starting with 'curses_*' as tiny standalone library if it's easier. They
  130. deal with terminal input and output. User only needs to call function 'curses_configure' only once, and necessary amount of 'curses_bind' functions, before doing any rendering,
  131. then make an "infinite" loop that'll stop when external variable 'curses_active' is equal to zero. In that loop, user can call any amount 'curses_render_*' functions, and at the
  132. end call function 'curses_synchronize' again, only once. So the following program structure would look something like this:
  133. @C
  134. // ...
  135. int main (int argc, char * * argv) {
  136. // ...
  137. curses_configure ();
  138. while (curses_active != 0) { // Notice the negative condition, the loop will stop then the condition is 0, so when 'curses_active' is 0.
  139. // Calling functions 'curses_render_*' and doing other work...
  140. curses_synchronize ();
  141. }
  142. // ...
  143. return (0);
  144. }
  145. @
  146. We don't need to use 'curses_initialize' and the begining of the program, or 'curses_deinitialize' at the end. Also, there are no functions like 'BeginDrawing' or 'EndDrawing',
  147. with 'Draw*' functions strictly between those two, like you would see in Raylib. We won't cover SDL2 and Raylib in this book, since I think that anyone with minimal knowledge of
  148. C can efficiently write good programs using those libraries, please don't misunderstand me, those two are good libraries. We'll simply eliminate that "begin" or "end" step in
  149. our subprogram called 'curses'.
  150. */
  151. static void curses_idle (void) { return; } // If you have a lot of short functions that are intended to be in array of function pointers, you can align them like this.
  152. static void curses_exit (void) { curses_active = 0; } // And this is our main function for quitting main loop in curses.
  153. static void curses_initialize (void) { // This function will be called when 'curses_configure' is called, automatically.
  154. struct winsize screen_dimension; // We need this ugly structure for our 'ioctl' function to get the dimensions.
  155. int screen_memory, lines; // And you can use local variables to shorten some lines of code if you want.
  156. fatal_failure (ioctl (STDOUT_FILENO, TIOCGWINSZ, & screen_dimension) == -1, // If function 'ioctl' failed, we immediately aborting the entire program.
  157. "ioctl: Failed to get terminal dimensions."); // I split those error messages, you can find your own formatting style.
  158. curses_screen_width = (int) screen_dimension.ws_col; // We get the dimensions of terminal window by calling that 'ioctl' function.
  159. curses_screen_height = (int) screen_dimension.ws_row;
  160. fatal_failure (tcgetattr (STDIN_FILENO, & curses_old_terminal) == -1, // Now we need to obtain data for current non-raw terminal to restore it later.
  161. "tcgetattr: Failed to get default terminal attributes.");
  162. curses_new_terminal = curses_old_terminal; // Here we set our raw terminal to be the same as the non-raw one.
  163. curses_new_terminal.c_cc [VMIN] = (unsigned char) 0; // Now it's time to modify it to be raw.
  164. curses_new_terminal.c_cc [VTIME] = (unsigned char) 1;
  165. curses_new_terminal.c_iflag &= (unsigned int) ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
  166. curses_new_terminal.c_oflag &= (unsigned int) ~(OPOST);
  167. curses_new_terminal.c_cflag |= (unsigned int) (CS8);
  168. curses_new_terminal.c_lflag &= (unsigned int) ~(ECHO | ICANON | IEXTEN | ISIG);
  169. fatal_failure (tcsetattr (STDIN_FILENO, TCSAFLUSH, & curses_new_terminal) == -1, // Finally, we're passing intormations to our terminal, and it becomes raw.
  170. "tcsetattr: Failed to set reverse terminal attributes.");
  171. screen_memory = CURSES_FORMAT * curses_screen_width * curses_screen_height; // This is square area of our terminal, and multiplied by 12, size of FORMAT.
  172. lines = (curses_screen_height - 1) * 2; // This is size of line feed and carriage return to avoid word-wrapping.
  173. curses_screen = allocate (CURSES_REVERT + screen_memory + lines + CURSES_CURSOR + 1); // We're requesting new memory for framebuffer.
  174. curses_bind (SIGNAL_ESCAPE, curses_exit); // Binding universal exit key (signal).
  175. string_copy (& curses_screen [0], "\033[H"); // ASCII black magic to always clear screen.
  176. for (lines = 1; lines < curses_screen_height; ++lines) { // Now it's time to put forced line breaks in raw terminal, without the last one.
  177. int skip = CURSES_REVERT + 2 * (lines - 1); // We skip first 3 bytes and previously copied amount of line breaks.
  178. int next = lines * CURSES_FORMAT * curses_screen_width; // And now we offset full width of our terminal, this makes it faster...
  179. string_copy_limit (curses_screen + skip + next, "\r\n", string_length ("\r\n")); // And lastly, we copy those line breaks at this offset into our screen buffer.
  180. } // Keep in mind that word-wrapping is slow on some terminals, hence I use this.
  181. // So, what's difference with using these two examples? Really, nothing.
  182. // string_copy (& string [offset], source);
  183. // string_copy ( string + offset , source);
  184. // Unary operator '&' references the variable, returning it's memory address (pointer of its' type).
  185. // Unary operator '*' (not multiplication!) dereferences the variable, returning value found at some memory address (with type).
  186. // Arrays in C are just pointers to the first element of that array, and since they lay next to each other in memory, we can access them by doing:
  187. // array [element] <=> * (array + sizeof (* array) * element)
  188. // So, to explain, we're adding pointer to the first element of that array with size of one element multiplied by index of wanted element, and dereferencing that.
  189. // Since referencing and then immediately dereferencing something does nothing, we can ommit that '& (* variable)' into just 'variable'.
  190. // & array [element] <=> array + sizeof (* array) * element
  191. // In the end, use whatever you like, compiler will make sure to optimize it, since this is a simple optimization process, it won't cause bugs.
  192. terminal_clear ();
  193. }
  194. static void curses_deinitialize (void) { // This function will be only called once, automatically, at the program exit.
  195. curses_screen = deallocate (curses_screen); // It's important to deallocate all previously allocated memory.
  196. curses_activator = deallocate (curses_activator);
  197. curses_action = deallocate (curses_action);
  198. curses_action_count = 0; // I just set everthing into default state, so we can use curses multiple times.
  199. curses_character = 0; // This way, it's all safe and clean, even with (de)initializing it twice.
  200. curses_signal = SIGNAL_NONE;
  201. curses_screen_width = 0;
  202. curses_screen_height = 0;
  203. curses_active = FALSE;
  204. terminal_clear (); // This only make things look prettier, we don't have mess when we exit the program.
  205. fatal_failure (tcsetattr (STDIN_FILENO, TCSAFLUSH, & curses_old_terminal) == -1, // Again, if this fails, we're doomed, we're aborting.
  206. "tcsetattr: Failed to set default terminal attributes.");
  207. }
  208. /*
  209. Next two functions are also internal, and we'll use them in our other 'curses_*' functions. The goal of extracting that piece of code into separate functions is to eliminate code
  210. repetition. Copying and pasting the same piece of code everywhere has pros and cons. Pros are that they're very good indication what should be factored out. The best example that
  211. comes from top of my head is 'echo' function from chapter zero. It'd be boring to use 'out' everywhere, since it also requires the 'size' argument, and I want to just output
  212. string literals to terminal in most cases. But that doesn't mean that 'out' is useless, as you'll see, we'll use it in 'curses_synchronize' funcion. Cons are, if you really have
  213. repeating code all over your program, if there's a bug in one of them, there's a bug in all of them. Also, if you'll use some extracted function (also refered to as refactored in
  214. some cases) only once, it's not a bad thing. We've extracted some code into 'curses_initialize' function, and we call it only once, inside 'curses_configure' function, but the
  215. intention behind what it does is clear. However, I still believe that procedural code, that's executed line by line, from top to bottom, is best. You can use 'curses_configure'
  216. and main loop with 'curses_synchronize' inside more functions, and it'll clean itself after the program exits.
  217. Now, we could also implement some error checking functions for 'curses_*' functions. Good idea, when something is wrong, like we want to render a character out of the screen, we
  218. just print an error message to terminal, right? Well, no. Remember, we're using terminal as a framebuffer (about which we'll talk about a lot more in ray tracing and rasterization
  219. chapters), so if we just print message there, it'll corrupt our framebuffer. So, we could just write them to some log file. How about binding them, whenever something is wrong,
  220. we don't just abort the program or stop rendering, but continue running it, while also writing error messages to that same file. Then, when we exit the program, it'll print all
  221. error messages (if any) normally. It could be done like something below, but since I know what I'm doing (for the most part), I'll just comment them out inside functions, and
  222. leave 'log_in' and 'log_out' unimplemented.
  223. @C
  224. // Enumeration for log type.
  225. enum {
  226. LOG_FAILURE, LOG_WARNING, LOG_SUCCESS, LOG_COUNT
  227. };
  228. static void log_in (int type, int condition, char * message);
  229. static void log_out (char * name);
  230. // Usage example:
  231. log_in (LOG_FAILURE, condition != 0, "function_name: The kind of error that occured or a general notification.");
  232. log_out ("file_name.log");
  233. @
  234. To be honest, I consider that a bad idea, because if we render something that's not supposed to be rendered (we pass wrong arguments to any of the 'curses_render_*' functions),
  235. it'll be obvious when we look at it. So, I wrote commented-out examples below of how we'd do it, but it won't be compiled into the final object file. If we pass a wrong value to
  236. those functions, they'll be fixed (modified), and give the wrong results, which will be obvious when we look at the screen. Nothing will crash or burn.
  237. */
  238. static char * curses_screen_offset (int x, int y) {
  239. // log_in (LOG_FAILURE, x <= -1, "curses_screen_offset: X position is below the lower bound.");
  240. // log_in (LOG_FAILURE, y <= -1, "curses_screen_offset: Y position is below the lower bound.");
  241. // log_in (LOG_FAILURE, x >= curses_screen_width, "curses_screen_offset: X position is above the upper bound.");
  242. // log_in (LOG_FAILURE, y >= curses_screen_height, "curses_screen_offset: Y position is above the upper bound.");
  243. limit (& x, 0, curses_screen_width - 1); // We're limiting the values of X and Y coordinates to screen dimensions.
  244. limit (& y, 0, curses_screen_height - 1); // Function 'limit' uses inclusive values for minimum and maximum.
  245. return (& curses_screen [CURSES_REVERT + 2 * y + CURSES_FORMAT * (y * curses_screen_width + x)]); // And returning the offset of the screen buffer.
  246. }
  247. static char * curses_format_character (char character, int colour, int effect) {
  248. // log_in (LOG_WARNING, character_is_invisible (character), "curses_format_character: Can not format invisible characters.");
  249. // log_in (LOG_FAILURE, colour >= COLOUR_COUNT, "curses_format_character: Colour is invalid enumeration value.");
  250. // log_in (LOG_FAILURE, effect >= EFFECT_COUNT, "curses_format_character: Effect is invalid enumeration value.");
  251. if (character_is_invisible (character) != 0) { // Since we don't want to render invisible ASCII characters, we'll just change 'character' to space.
  252. character = ' ';
  253. }
  254. colour %= COLOUR_COUNT; // Instead of breaking and burning everything, we'll just "round" it down to one of the allowed values.
  255. effect %= EFFECT_COUNT;
  256. switch (effect) { // Effects aren't enumerated nicely as colours, so here we'll use switch statement instead of nested if-else statements.
  257. case EFFECT_NORMAL: effect = 0; break; // We could break these into any combination of new lines, we'll just show one example below of how else you can do it.
  258. // case EFFECT_NORMAL:
  259. // effect = 0;
  260. // break;
  261. // case EFFECT_NORMAL: {
  262. // effect = 0;
  263. // } break;
  264. case EFFECT_BOLD: effect = 1; break;
  265. case EFFECT_ITALIC: effect = 3; break;
  266. case EFFECT_UNDERLINE: effect = 4; break;
  267. case EFFECT_BLINK: effect = 5; break;
  268. case EFFECT_REVERSE: effect = 7; break;
  269. default: effect = 0; break;
  270. }
  271. curses_format [2] = (char) effect + '0'; // Now, here comes ASCII escape sequence magic, this will format the character to have colour and effect.
  272. curses_format [5] = (char) colour + '0';
  273. curses_format [7] = character;
  274. return (curses_format); // And we return the value (pointer to character) of formatted internal variables.
  275. }
  276. /*
  277. External function definitions, those found in "chapter_2.h" header file.
  278. */
  279. void curses_configure (void) {
  280. curses_active = TRUE; // This is important part, and something I like to do in my standalone libraries.
  281. atexit (curses_deinitialize); // Deinitialization is automatically executed on exit point of the program, since we called 'atexit' function.
  282. curses_initialize (); // Initializing curses, finally, yaay.
  283. }
  284. void curses_synchronize (void) {
  285. int signal, length;
  286. curses_signal = curses_character = signal = 0; // Reassigning signals to 0.
  287. length = CURSES_REVERT + CURSES_FORMAT * curses_screen_width * curses_screen_height + 2 * (curses_screen_height - 1) + CURSES_CURSOR;
  288. out (curses_screen, length); // We output the entire framebuffer to terminal (present).
  289. in (& signal, (int) sizeof (signal)); // We're now checking for user input to modify it.
  290. curses_character = signal; // We need literal value of 'signal' for text input.
  291. if (signal == '\033') { // And then we modify the actual 'curses_signal'.
  292. curses_signal = SIGNAL_ESCAPE;
  293. } else if (character_is_digit ((char) signal) != 0) {
  294. curses_signal |= SIGNAL_0 + (int) (signal - '0');
  295. } else if (character_is_lowercase ((char) signal) != 0) {
  296. curses_signal |= SIGNAL_A + (int) (signal - 'a');
  297. } else if (character_is_uppercase ((char) signal) != 0) {
  298. curses_signal |= SIGNAL_A + (int) (signal - 'A');
  299. curses_signal |= SIGNAL_SHIFT;
  300. } else if ((signal == SIGNAL_ARROW_UP) || (signal == SIGNAL_ARROW_DOWN) || (signal == SIGNAL_ARROW_RIGHT) || (signal == SIGNAL_ARROW_LEFT)) {
  301. curses_signal = signal;
  302. } else {
  303. curses_signal = SIGNAL_NONE;
  304. }
  305. for (signal = 0; signal != curses_action_count; ++signal) { // Now, it's time to loop over bound actions.
  306. if (curses_signal == curses_activator [signal]) { // If we have a bound signal, then:
  307. curses_action [signal] (); // We execute corresponding action (function).
  308. break;
  309. }
  310. }
  311. if (curses_active == FALSE) { // Lastly, if we exited curses, we want to deinitialize.
  312. curses_deinitialize (); // It's no problem if we do it more than once...
  313. }
  314. }
  315. /*
  316. It's still to early to talk about signal binding and unbinding, so I'll skip over them as they are more complex.
  317. */
  318. void curses_bind (int signal, void (* action) (void)) {
  319. ++curses_action_count;
  320. curses_activator = reallocate (curses_activator, curses_action_count * (int) sizeof (* curses_activator));
  321. curses_action = reallocate (curses_action, curses_action_count * (int) sizeof (* curses_action));
  322. curses_activator [curses_action_count - 1] = signal;
  323. curses_action [curses_action_count - 1] = action;
  324. }
  325. void curses_unbind (int signal) {
  326. (void) signal;
  327. curses_activator [curses_action_count - 1] = SIGNAL_NONE;
  328. curses_action [curses_action_count - 1] = curses_idle;
  329. --curses_action_count;
  330. }
  331. /*
  332. Finally, we're getting to rendering, something that we can actually see on our screen. There's ASCII escape sequences involved into this, so lets explain them briefly. We
  333. mentioned in "chapter_2.h" header file about how some of them work. Now, we're extending them, with minimal amount of error checking in order to keep things more clear. Worth
  334. noting is that not all terminals support all of ASCII escape sequences, but most of them support at least a subset of them. There are many terminals such as ones provided by
  335. desktop environment (xfce4-terminal, etc.), and independent ones (st, sakura, xterm, etc.), use whatever, it'll (in 99% of cases) work as intended.
  336. If you want to know what rendering truly is, it's just copying certain value to some offset. Nothing more...
  337. */
  338. void curses_render_cursor (int x, int y) {
  339. // We're expecting that our terminal dimensions (width and height in unit of 'characters') is always less 1000. If it's not, I really don't care.
  340. // Also, there's the application of "limited" string functions, since we don't want to copy until null character ('\0') is reached.
  341. // Lastly, if you remember that 'curses_cursor' is string "\033[---;---H", we're just writing two numbers to "---" parts, from 0 to 999 inclusively.
  342. // We're adding one because ASCII uses 1 ... 1000, and we use 0 ... 999, so it doesn't causes hidden bugs, and realign them to be prefixed with '0' characters.
  343. // If we have set of values (x = 31, y = 37), then the copied string would look like "\033[031;037H". It's not complex as it may sound.
  344. // And remember our ASCII table, thing scary thing (\033) is just octal value for number 27, which is CHARACTER_ESCAPE, hence the escape sequences start with it.
  345. int offset;
  346. x %= 1000; // I don't care for terminals bigger than this...
  347. y %= 1000;
  348. string_copy_limit (curses_cursor + 2, string_realign (number_to_string (y + 1), 3, '0'), 3); // We're copying 0...999 number as string, with 0s.
  349. string_copy_limit (curses_cursor + 6, string_realign (number_to_string (x + 1), 3, '0'), 3); // Those prefix 0s must be used with this.
  350. offset = CURSES_REVERT + 2 * (curses_screen_height - 1) + CURSES_FORMAT * curses_screen_width * curses_screen_height; // We need to offset it at the end of our screen.
  351. string_copy_limit (& curses_screen [offset], curses_cursor, CURSES_CURSOR); // And only then copy cursor data into screen.
  352. }
  353. void curses_render_character (char character, int colour, int effect, int x, int y) {
  354. // Again, lets show some code formatting examples:
  355. // if ((x < 0)
  356. // || (y < 0)
  357. // || (x > curses_screen_width - 1)
  358. // || (y > curses_screen_height - 1)) {
  359. // return;
  360. // }
  361. // Or, if you don't want to subtract one from values there:
  362. // if ((x < 0) ||
  363. // (y < 0) ||
  364. // (x >= curses_screen_width) ||
  365. // (y >= curses_screen_height)) {
  366. // return;
  367. // }
  368. // Or if you really hate adding 2 more lines of code and curly braces:
  369. // if ((x < 0) || (x > curses_screen_width - 1) || (y < 0) || (y > curses_screen_height - 1)) return;
  370. if ((x < 0) || (x > curses_screen_width - 1) || (y < 0) || (y > curses_screen_height - 1)) { // If any of these are true, we don't render.
  371. return;
  372. }
  373. string_copy_limit (curses_screen_offset (x, y), curses_format_character (character, colour, effect), CURSES_FORMAT); // Again, actual rendering, copying a value to offset.
  374. }
  375. void curses_render_background (char character, int colour, int effect) {
  376. int x, y; // We declare local variables like this, I usually don't initialize them right away.
  377. for (y = 0; y != curses_screen_height; ++y) { // Iterating through rows (by height) of our framebuffer ('curses_screen').
  378. for (x = 0; x != curses_screen_width; ++x) { // Iterating through columns (by width) of our framebuffer.
  379. curses_render_character (character, colour, effect, x, y); // Now, we can use function 'curses_render_character' to simplify our life...
  380. }
  381. }
  382. }
  383. void curses_render_rectangle_fill (char character, int colour, int effect, int x, int y, int width, int height) {
  384. for (int j = 0; j < height; ++j) { // You can declare type of those iterators in for loops.
  385. for (int i = 0; i < width; ++i) { // This only works if you're not using ANSI C (C89 / C90) standard.
  386. curses_render_character (character, colour, effect, x + i, y + j); // Now, we render character by character again...
  387. }
  388. }
  389. }
  390. void curses_render_rectangle_line (char character, int colour, int effect, int x, int y, int width, int height) {
  391. for (int offset = 0; offset < width; ++offset) { // Now, we only want to render line, rectangle has 4 lines, so we need 2 loops.
  392. curses_render_character (character, colour, effect, x + offset, y); // First we're rendering horizontal lines, then vertical lines.
  393. curses_render_character (character, colour, effect, x + offset, y + height - 1); // We also need to offset X or Y, depending on rectangle width or height.
  394. }
  395. for (int offset = 0; offset < height; ++offset) { // Now, we only want to render line, rectangle has 4 lines, so we need 2 loops.
  396. curses_render_character (character, colour, effect, x, y + offset); // I prefer to use 'offset' instead of 'i' and 'j', but I have no strict rule.
  397. curses_render_character (character, colour, effect, x + width - 1, y + offset); // I'm mixing them here, so you can see what you find more readable.
  398. }
  399. }
  400. /*
  401. We've mentioned before, in chapter zero, that you can implement 'string_*' functions by 'string_*_limit', and here's an example of that. Functions below are quite self
  402. explanatory, so you can do a "homework" of reading them and trying to understand what they'll do. Since I use very verbose naming style, I hope that won't be a problem...
  403. */
  404. int curses_render_string (char * string, int colour, int effect, int x, int y) { // Keep in mind, we could reimplement this to be very similar to "limited" version.
  405. return (curses_render_string_limit (string, string_length (string), colour, effect, x, y));
  406. }
  407. int curses_render_number (int number, int colour, int effect, int x, int y) { // This is not particularly smart solution, but it's simple to understand.
  408. return (curses_render_string (number_to_string (number), colour, effect, x, y));
  409. }
  410. int curses_render_string_limit (char * string, int limit, int colour, int effect, int x, int y) { // This uses short "fix" for blank characters, but we'll align them better later.
  411. int offset;
  412. for (offset = 0; offset != limit; ++offset) {
  413. if (string [offset] == '\n') {
  414. x *= 0;
  415. y += 1;
  416. } else if (string [offset] == '\t') {
  417. x += 8;
  418. } else {
  419. curses_render_character (string [offset], colour, effect, x, y);
  420. x += 1;
  421. }
  422. }
  423. return (limit);
  424. }
  425. int curses_render_number_limit (int number, int limit, int colour, int effect, int x, int y) { // Finally, this will align the number to the right and limit it as well.
  426. return (curses_render_string_limit (number_to_string (number), limit, colour, effect, x, y));
  427. }
  428. #endif