]> git.lizzy.rs Git - dungeon_game.git/blob - plugins/game/game.c
152a5c97200e75578a3139877929e6b03277fa75
[dungeon_game.git] / plugins / game / game.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <assert.h>
5 #include <ctype.h>
6 #include <signal.h>
7 #include <termios.h>
8 #include <math.h>
9 #include <pthread.h>
10 #include <string.h>
11 #include "game.h"
12
13 /* Shared variables */
14
15 struct color black = {0};
16
17 struct material wall;
18 struct material air;
19 struct material outside;
20
21 struct node map[MAP_WIDTH][MAP_HEIGHT];
22
23 struct list *entities = & (struct list) {
24         .element = &player,
25         .next = NULL,
26 };
27
28 /* Private variables */
29
30 struct entity *entity_collision_map[MAP_WIDTH][MAP_HEIGHT] = {{NULL}};
31
32 static bool running = true;
33 static double damage_overlay = 0.0;
34 static struct color damage_overlay_color;
35
36 static struct list *air_functions = NULL;
37 static struct input_handler *input_handlers[256] = {NULL};
38 static struct entity *render_entities[LIGHT * 2 + 1][LIGHT * 2 + 1];
39 static struct list *render_components = NULL;
40 static struct list *globalsteps = NULL;
41
42 /* Helper functions */
43
44 struct color get_color(const char *str)
45 {
46         unsigned int r, g, b;
47         sscanf(str, "#%2x%2x%2x", &r, &g, &b);
48         return (struct color) {r, g, b};
49 }
50
51 void set_color(struct color color, bool bg)
52 {
53         printf("\e[%u;2;%u;%u;%um", bg ? 48 : 38, color.r, color.g, color.b);
54 }
55
56 void light_color(struct color *color, double light)
57 {
58         color->r *= light;
59         color->g *= light;
60         color->b *= light;
61 }
62
63 void mix_color(struct color *color, struct color other, double ratio)
64 {
65         double ratio_total = ratio + 1;
66
67         color->r = (color->r + other.r * ratio) / ratio_total;
68         color->g = (color->g + other.g * ratio) / ratio_total;
69         color->b = (color->b + other.b * ratio) / ratio_total;
70 }
71
72 void dir_to_xy(enum direction dir, int *x, int *y)
73 {
74         switch (dir) {
75                 case UP:
76                         (*y)--;
77                         break;
78                 case LEFT:
79                         (*x)--;
80                         break;
81                 case DOWN:
82                         (*y)++;
83                         break;
84                 case RIGHT:
85                         (*x)++;
86                         break;
87         }
88 }
89
90 struct list *add_element(struct list *list, void *element)
91 {
92         struct list **ptr;
93
94         for (ptr = &list; *ptr != NULL; ptr = &(*ptr)->next)
95                 ;
96
97         *ptr = malloc(sizeof(struct list));
98         (*ptr)->element = element;
99         (*ptr)->next = NULL;
100
101         return list;
102 }
103
104 int clamp(int v, int min, int max)
105 {
106         return v < min ? min : v > max ? max : v;
107 }
108
109 int max(int a, int b)
110 {
111         return a > b ? a : b;
112 }
113
114 int min(int a, int b)
115 {
116         return a < b ? a : b;
117 }
118
119 void *make_buffer(void *ptr, size_t size)
120 {
121         void *buf = malloc(size);
122         memcpy(buf, ptr, size);
123
124         return buf;
125 }
126
127 double calculate_dtime(struct timespec from, struct timespec to)
128 {
129         return (double) (to.tv_sec - from.tv_sec) + (double) (to.tv_nsec - from.tv_nsec) / 1000000000.0;
130 }
131
132 /* Game-related utility functions */
133
134 void quit()
135 {
136         running = false;
137 }
138
139 bool player_dead()
140 {
141         return player.health <= 0;
142 }
143
144 /* Map functions */
145
146 struct node get_node(int x, int y)
147 {
148         return is_outside(x, y) ? (struct node) {&outside} : map[x][y];
149 }
150
151 bool is_outside(int x, int y)
152 {
153         return x >= MAP_WIDTH || x < 0 || y >= MAP_HEIGHT || y < 0;
154 }
155
156 bool is_solid(int x, int y)
157 {
158         return get_node(x, y).material->solid;
159 }
160
161 /* Entity functions */
162
163 bool spawn(struct entity def, int x, int y, void *data)
164 {
165         if (is_solid(x, y))
166                 return false;
167
168         if (def.collide_with_entities && entity_collision_map[x][y])
169                 return false;
170
171         def.x = x;
172         def.y = y;
173
174         struct entity *entity = malloc(sizeof(struct entity));
175         *entity = def;
176
177         add_element(entities, entity);
178
179         if (entity->collide_with_entities)
180                 entity_collision_map[x][y] = entity;
181
182         if (entity->on_spawn)
183                 entity->on_spawn(entity, data);
184
185         return true;
186 }
187
188 bool move(struct entity *entity, int xoff, int yoff)
189 {
190         int x, y;
191
192         x = entity->x + xoff;
193         y = entity->y + yoff;
194
195         if (is_solid(x, y)) {
196                 if (entity->on_collide)
197                         entity->on_collide(entity, x, y);
198                 return false;
199         } else if (entity->collide_with_entities && entity_collision_map[x][y]) {
200                 if (entity->on_collide_with_entity)
201                         entity->on_collide_with_entity(entity, entity_collision_map[x][y]);
202                 return false;
203         } else {
204                 entity_collision_map[entity->x][entity->y] = NULL;
205                 entity->x = x;
206                 entity->y = y;
207                 entity_collision_map[entity->x][entity->y] = entity;
208                 return true;
209         }
210 }
211
212 void add_health(struct entity *entity, int health)
213 {
214         bool was_alive = entity->health > 0;
215
216         entity->health += health;
217
218         if (health < 0 && entity->on_damage)
219                 entity->on_damage(entity, -health);
220
221         if (entity->health > entity->max_health)
222                 entity->health = entity->max_health;
223         else if (entity->health <= 0 && was_alive && entity->on_death)
224                 entity->on_death(entity);
225 }
226
227 /* Register callback functions */
228
229 void register_air_function(struct generator_function func)
230 {
231         air_functions = add_element(air_functions, make_buffer(&func, sizeof(struct generator_function)));
232 }
233
234 void register_input_handler(unsigned char c, struct input_handler handler)
235 {
236         if (input_handlers[c])
237                 return;
238
239         input_handlers[c] = make_buffer(&handler, sizeof(struct input_handler));
240 }
241
242 void register_render_component(void (*callback)(struct winsize ws))
243 {
244         render_components = add_element(render_components, callback);
245 };
246
247 void register_globalstep(struct globalstep step)
248 {
249         globalsteps = add_element(globalsteps, make_buffer(&step, sizeof(struct globalstep)));
250 }
251
252 /* Player */
253
254 static void player_death(struct entity *self)
255 {
256         self->texture = "☠ ";
257 }
258
259 static void player_damage(struct entity *self, int damage)
260 {
261         damage_overlay += (double) damage * 0.5;
262 }
263
264 struct entity player = {
265         .name = "player",
266         .x = MAP_WIDTH / 2,
267         .y = MAP_HEIGHT / 2,
268         .color = {0},
269         .use_color = false,
270         .texture = "🙂",
271         .remove = false,
272         .meta = NULL,
273         .health = 10,
274         .max_health = 10,
275         .collide_with_entities = true,
276
277         .on_step = NULL,
278         .on_collide = NULL,
279         .on_collide_with_entity = NULL,
280         .on_spawn = NULL,
281         .on_remove = NULL,
282         .on_death = &player_death,
283         .on_damage = &player_damage,
284 };
285
286 /* Mapgen */
287
288 static void mapgen_set_air(int x, int y)
289 {
290         if (is_outside(x, y))
291                 return;
292
293         if (map[x][y].material == &air)
294                 return;
295
296         map[x][y] = (struct node) {&air};
297
298         for (struct list *ptr = air_functions; ptr != NULL; ptr = ptr->next) {
299                 struct generator_function *func = ptr->element;
300
301                 if (rand() % func->chance == 0)
302                         func->callback(x, y);
303         }
304 }
305
306 static void generate_room(int origin_x, int origin_y)
307 {
308         int left = 5 + rand() % 10;
309         int right = 5 + rand() % 10;
310
311         int up = 0;
312         int down = 0;
313
314         for (int x = -left; x <= right; x++) {
315                 if (x < 0) {
316                         up += rand() % 2;
317                         down += rand() % 2;
318                 } else {
319                         up -= rand() % 2;
320                         down -= rand() % 2;
321                 }
322
323                 for (int y = -up; y <= down; y++)
324                         mapgen_set_air(origin_x + x, origin_y + y);
325         }
326 }
327
328 static bool check_direction(int x, int y, enum direction dir)
329 {
330         if (dir % 2 == 0)
331                 return is_solid(x + 1, y) && is_solid(x - 1, y) && (is_solid(x, y + 1) || rand() % 3 > 1) && (is_solid(x, y - 1) || rand() % 3 > 1);
332         else
333                 return is_solid(x, y + 1) && is_solid(x, y - 1) && (is_solid(x + 1, y) || rand() % 3 > 1) && (is_solid(x - 1, y) || rand() % 3 > 1);
334 }
335
336 static void generate_corridor(int lx, int ly, enum direction ldir)
337 {
338         if (is_outside(lx, ly))
339                 return;
340
341         if (rand() % 200 == 0) {
342                 generate_room(lx, ly);
343                 return;
344         }
345
346         mapgen_set_air(lx, ly);
347
348         int x, y;
349
350         enum direction dir;
351         enum direction ret = (ldir + 2) % 4;
352
353         int limit = 50;
354
355         do {
356                 x = lx;
357                 y = ly;
358
359                 if (rand() % 3 > 1)
360                         dir = ldir;
361                 else
362                         dir = rand() % 4;
363
364                 dir_to_xy(dir, &x, &y);
365         } while (dir == ret || (! check_direction(x, y, dir) && --limit));
366
367         if (limit)
368                 generate_corridor(x, y, dir);
369
370         if (rand() % 20 == 0)
371                 generate_corridor(lx, ly, ldir);
372 }
373
374 static void generate_corridor_random(int x, int y)
375 {
376         enum direction dir = rand() % 4;
377
378         generate_corridor(x, y, dir);
379         generate_corridor(x, y, (dir + 2) % 4);
380 }
381
382 /* Rendering */
383
384 static bool render_color(struct color color, double light, bool bg, bool use_color)
385 {
386         if (light <= 0.0) {
387                 set_color(black, bg);
388                 return false;
389         } else if (use_color) {
390                 if (damage_overlay > 0.0)
391                         mix_color(&color, damage_overlay_color, damage_overlay * 2.0);
392
393                 light_color(&color, light);
394
395                 set_color(color, bg);
396                 return true;
397         } else {
398                 return true;
399         }
400 }
401
402 static void render_map(struct winsize ws)
403 {
404         int cols = ws.ws_col / 2 - LIGHT * 2;
405         int rows = ws.ws_row / 2 - LIGHT;
406
407         int cols_left = ws.ws_col - cols - (LIGHT * 2 + 1) * 2;
408         int rows_left = ws.ws_row - rows - (LIGHT * 2 + 1);
409
410         for (int i = 0; i < rows; i++)
411                 for (int i = 0; i < ws.ws_col; i++)
412                         printf(" ");
413
414         for (int y = -LIGHT; y <= LIGHT; y++) {
415                 for (int i = 0; i < cols; i++)
416                         printf(" ");
417
418                 for (int x = -LIGHT; x <= LIGHT; x++) {
419                         int map_x, map_y;
420
421                         map_x = x + player.x;
422                         map_y = y + player.y;
423
424                         struct node node = get_node(map_x, map_y);
425
426                         double dist = sqrt(x * x + y * y);
427                         double light = 1.0 - (double) dist / (double) LIGHT;
428
429                         render_color(node.material->color, light, true, true);
430
431                         struct entity *entity = render_entities[x + LIGHT][y + LIGHT];
432                         render_entities[x + LIGHT][y + LIGHT] = NULL;
433
434                         if (entity && render_color(entity->color, light, false, entity->use_color))
435                                 printf("%s", entity->texture);
436                         else
437                                 printf("  ");
438                 }
439
440                 set_color(black, true);
441
442                 for (int i = 0; i < cols_left; i++)
443                         printf(" ");
444         }
445
446         for (int i = 0; i < rows_left; i++)
447                 for (int i = 0; i < ws.ws_col; i++)
448                         printf(" ");
449 }
450
451 static void render()
452 {
453         printf("\e[2J");
454
455         struct winsize ws;
456         ioctl(STDIN_FILENO, TIOCGWINSZ, &ws);
457
458         for (struct list *ptr = render_components; ptr != NULL; ptr = ptr->next) {
459                 printf("\e[0m\e[0;0H");
460                 set_color(black, true);
461
462                 ((void (*)(struct winsize ws)) ptr->element)(ws);
463         }
464
465         fflush(stdout);
466 }
467
468 /* Input */
469
470 static void handle_interrupt(int signal)
471 {
472         (void) signal;
473
474         quit();
475 }
476
477 static void handle_input(unsigned char c)
478 {
479         struct input_handler *handler = input_handlers[c];
480
481         if (handler && (handler->run_if_dead || ! player_dead()))
482                 handler->callback();
483 }
484
485 static void *input_thread(void *unused)
486 {
487         (void) unused;
488
489         while (running)
490                 handle_input(tolower(fgetc(stdin)));
491
492         return NULL;
493 }
494
495 /* Main Game */
496
497 void game()
498 {
499         struct sigaction sa;
500         sa.sa_handler = &handle_interrupt;
501         sigaction(SIGINT, &sa, NULL);
502
503         generate_corridor_random(player.x, player.y);
504
505         for (int i = 0; i < 50; i++)
506                 generate_corridor_random(rand() % MAP_WIDTH, rand() % MAP_HEIGHT);
507
508         struct termios oldtio, newtio;
509         tcgetattr(STDIN_FILENO, &oldtio);
510         newtio = oldtio;
511         newtio.c_lflag &= ~(ICANON | ECHO);
512         tcsetattr(STDIN_FILENO, TCSANOW, &newtio);
513
514         printf("\e[?1049h\e[?25l");
515
516         pthread_t input_thread_id;
517         pthread_create(&input_thread_id, NULL, &input_thread, NULL);
518
519         struct timespec ts, ts_old;
520         clock_gettime(CLOCK_REALTIME, &ts_old);
521
522         while (running) {
523                 clock_gettime(CLOCK_REALTIME, &ts);
524                 double dtime = calculate_dtime(ts_old, ts);
525                 ts_old = ts;
526
527                 bool dead = player_dead();
528
529                 for (struct list *ptr = globalsteps; ptr != NULL; ptr = ptr->next) {
530                         struct globalstep *step = ptr->element;
531
532                         if (step->run_if_dead || ! dead)
533                                 step->callback(dtime);
534                 }
535
536                 if (! dead && damage_overlay > 0.0) {
537                         damage_overlay -= dtime;
538
539                         if (damage_overlay < 0.0)
540                                 damage_overlay = 0.0;
541                 }
542
543                 for (struct list **ptr = &entities; *ptr != NULL; ) {
544                         struct entity *entity = (*ptr)->element;
545
546                         if (entity->remove) {
547                                 assert(entity != &player);
548                                 struct list *next = (*ptr)->next;
549
550                                 if (entity->on_remove)
551                                         entity->on_remove(entity);
552
553                                 if (entity->meta)
554                                         free(entity->meta);
555
556                                 if (entity->collide_with_entities)
557                                         entity_collision_map[entity->x][entity->y] = NULL;
558
559                                 free(entity);
560                                 free(*ptr);
561
562                                 *ptr = next;
563                                 continue;
564                         }
565
566                         int dx, dy;
567
568                         dx = entity->x - player.x;
569                         dy = entity->y - player.y;
570
571                         bool visible = abs(dx) <= LIGHT && abs(dy) <= LIGHT;
572
573                         if (visible)
574                                 render_entities[dx + LIGHT][dy + LIGHT] = entity;
575
576                         if (! dead && entity->on_step)
577                                 entity->on_step(entity, (struct entity_step_data) {
578                                         .dtime = dtime,
579                                         .visible = visible,
580                                         .dx = dx,
581                                         .dy = dy,
582                                 });
583
584                         ptr = &(*ptr)->next;
585                 }
586
587                 render();
588
589                 // there is no such thing as glfwSwapBuffers, so we just wait 1 / 60 seconds to prevent artifacts
590                 usleep(1000000 / 60);
591         }
592
593         printf("\e[?1049l\e[?25h");
594         tcsetattr(STDIN_FILENO, TCSANOW, &oldtio);
595 }
596
597 /* Initializer function */
598
599 __attribute__ ((constructor)) static void init()
600 {
601         srand(time(0));
602
603         wall = (struct material) {
604                 .solid = true,
605                 .color = get_color("#5B2F00"),
606         };
607
608         air = (struct material) {
609                 .solid = false,
610                 .color = get_color("#FFE027"),
611         };
612
613         outside = (struct material) {
614                 .solid = true,
615                 .color = black,
616         };
617
618         entity_collision_map[player.x][player.y] = &player;
619
620         for (int x = 0; x < MAP_WIDTH; x++)
621                 for (int y = 0; y < MAP_HEIGHT; y++)
622                         map[x][y] = (struct node) {&wall};
623
624         register_input_handler('q', (struct input_handler) {
625                 .run_if_dead = true,
626                 .callback = &quit,
627         });
628
629         register_render_component(&render_map);
630
631         damage_overlay_color = get_color("#F20000");
632 }
633
634 /* Use later */
635
636 /*
637 get_box_char(is_solid(x, y - 1), is_solid(x, y + 1), is_solid(x - 1, y), is_solid(x + 1, y));
638
639 const char *get_box_char(bool up, bool down, bool left, bool right)
640 {
641         if (left && right && ! up && ! down)
642                 return "\u2501\u2501";
643         else if (up && down && ! right && ! left)
644                 return "\u2503 ";
645         else if (down && right && ! up && ! left)
646                 return "\u250F\u2501";
647         else if (down && left && ! up && ! right)
648                 return "\u2513 ";
649         else if (up && right && ! down && ! left)
650                 return "\u2517\u2501";
651         else if (up && left && ! down && ! right)
652                 return "\u251B ";
653         else if (up && down && right && ! left)
654                 return "\u2523\u2501";
655         else if (up && down && left && ! right)
656                 return "\u252B ";
657         else if (down && left && right && ! up)
658                 return "\u2533\u2501";
659         else if (up && left && right && ! down)
660                 return "\u253B\u2501";
661         else if (up && down && left && right)
662                 return "\u254b\u2501";
663         else if (left && ! up && ! down && ! right)
664                 return "\u2578 ";
665         else if (up && ! down && ! left && ! right)
666                 return "\u2579 ";
667         else if (right && ! up && ! down && ! left)
668                 return "\u257A\u2501";
669         else if (down && ! up && ! left && ! right)
670                 return "\u257B ";
671         else if (! up && ! down && ! left && ! right)
672                 return "\u25AA ";
673         else
674                 return "??";
675 }
676 */