home · contact · privacy
c2a3354fd8f9c63d5b689fc9b3369f0ec822ce63
[plomrogue] / src / server / io.c
1 /* src/server/io.c
2  *
3  * This file is part of PlomRogue. PlomRogue is licensed under the GPL version 3
4  * or any later version. For details on its copyright, license, and warranties,
5  * see the file NOTICE in the root directory of the PlomRogue source package.
6  */
7
8 #define _POSIX_C_SOURCE 200112L /* snrpintf() */
9 #include "io.h"
10 #include <errno.h> /* global errno */
11 #include <limits.h> /* PIPE_BUF */
12 #include <stddef.h> /* size_t, NULL */
13 #include <stdint.h> /* uint8_t, uint16_t, uint32_t, UINT8_MAX */
14 #include <stdio.h> /* defines EOF, FILE, sprintf(), fprintf() */
15 #include <stdlib.h> /* free() */
16 #include <string.h> /* strlen(), snprintf(), memcpy(), memset(), strchr() */
17 #include <sys/types.h> /* time_t */
18 #include <time.h> /* time(), nanosleep() */
19 #include "../common/readwrite.h" /* atomic_write_start(), atomic_write_finish(),
20                                   * try_fwrite(), try_fputc(), try_fgetc()
21                                   */
22 #include "../common/rexit.h" /* exit_trouble() */
23 #include "../common/try_malloc.h" /* try_malloc() */
24 #include "cleanup.h" /* set_cleanup_flag() */
25 #include "hardcoded_strings.h" /* s */
26 #include "things.h" /* Thing, ThingType, ThingInMemory, ThingAction,
27                      * get_thing_type(), get_player()
28                      */
29 #include "world.h" /* global world  */
30
31
32
33 /* Helpers to write lines of god commands to recreate thing "t". */
34 static void write_key_space(FILE * file, char * key);
35 static void write_value(FILE * file, uint32_t value);
36 static void write_string(FILE * file, char * string);
37 static void write_key_space_value(FILE * file, char * key, uint32_t value);
38 static void write_key_space_string(FILE * file, char * key, char * string);
39
40 /* Write to "file" \n-delimited line of "key" + space + "value" as string. */
41 static void write_thing(FILE * file, struct Thing * t);
42
43 /* Cut out and return first \0-terminated string from world.queue and
44  * appropriately reduce world.queue_size. Return NULL if queue is empty.
45  * Superfluous \0 bytes after the string are also cut out. Should the queue
46  * start with \0 bytes, those are cut out before returning anything after them.
47  */
48 static char * get_message_from_queue();
49
50 /* Poll input file for world.queue input. Wait a few seconds until giving up;
51  * poll only every 0.03 seconds. Translate '\n' chars in input file into '\0'.
52  */
53 static void read_file_into_queue();
54
55 /* Write world state as visible to clients to its file. Write single dot line to
56  * server output file to satisfy client ping mechanisms.
57  */
58 static void update_worldstate_file();
59
60 /* Write "value" to new \n-delimited line of "file". */
61 static void write_value_as_line(uint32_t value, FILE * file);
62
63 /* Write to "file" player's inventory, one item name per line. End in "%\n". */
64 static void write_inventory(struct Thing * player, FILE * file);
65
66 /* Return map cells sequence as visible to the "player", with invisible cells as
67  * whitespace. Super-impose over visible map cells things positioned there,
68  * with animate things overwriting inanimate things, and inanimate consumable
69  * things overwriting inanimate non-consumable things.
70  */
71 static char * build_visible_map(struct Thing * player);
72
73 /* Write to "file" game map as visible to "player" right now, as drawn by
74  * build_visible_map(), and thereafter game map as memorized by player in its
75  * .mem_map and .t_mem. Write one row per \n-delimited line.
76  */
77 static void write_map(struct Thing * player, FILE * file);
78
79
80
81 static void write_key_space(FILE * file, char * key)
82 {
83     try_fwrite(key, strlen(key), 1, file, __func__);
84     try_fputc(' ', file, __func__);
85 }
86
87
88
89 static void write_value(FILE * file, uint32_t value)
90 {
91     char * line = try_malloc(11, __func__);
92     exit_trouble(-1 == sprintf(line, "%u", value), __func__, s[S_FCN_SPRINTF]);
93     try_fwrite(line, strlen(line), 1, file, __func__);
94     free(line);
95 }
96
97
98
99 static void write_string(FILE * file, char * string)
100 {
101     uint8_t contains_space = NULL != strchr(string, ' ');
102     if (contains_space)
103     {
104         try_fputc('\'', file, __func__);
105     }
106     try_fwrite(string, strlen(string), 1, file, __func__);
107     if (contains_space)
108     {
109         try_fputc('\'', file, __func__);
110     }
111 }
112
113
114
115 static void write_key_space_value(FILE * file, char * key, uint32_t value)
116 {
117     write_key_space(file, key);
118     write_value(file, value);
119     try_fputc('\n', file, __func__);
120 }
121
122
123
124 static void write_key_space_string(FILE * file, char * key, char * string)
125 {
126     write_key_space(file, key);
127     write_string(file, string);
128     try_fputc('\n', file, __func__);
129 }
130
131
132
133 static void write_thing(FILE * file, struct Thing * t)
134 {
135     struct Thing * o;
136     for (o = t->owns; o; o = o->next)
137     {
138         write_thing(file, o);
139     }
140     write_key_space_value(file, s[S_CMD_T_ID], t->id);
141     write_key_space_value(file, s[S_CMD_T_TYPE], t->type);
142     write_key_space_value(file, s[S_CMD_T_POSY], t->pos.y);
143     write_key_space_value(file, s[S_CMD_T_POSX], t->pos.x);
144     write_key_space_value(file, s[S_CMD_T_COMMAND], t->command);
145     write_key_space_value(file, s[S_CMD_T_ARGUMENT], t->arg);
146     write_key_space_value(file, s[S_CMD_T_PROGRESS], t->progress);
147     write_key_space_value(file, s[S_CMD_T_HP], t->lifepoints);
148     for (o = t->owns; o; o = o->next)
149     {
150         write_key_space_value(file, s[S_CMD_T_CARRIES], o->id);
151     }
152     if (t->mem_map)
153     {
154         uint32_t map_size = world.map.length * world.map.length;/* snprintf() */
155         char * mem_map_copy = try_malloc(map_size + 1, __func__);/* reads one */
156         memcpy(mem_map_copy, t->mem_map, map_size);   /* byte beyond map_size */
157         mem_map_copy[map_size] = '\0';     /* if string is not \0-terminated. */
158         uint16_t y;
159         char string[UINT8_MAX + 1 + 1];
160         for (y = 0; y < world.map.length; y++)
161         {
162
163             int test = snprintf(string, world.map.length + 1, "%s",
164                                 mem_map_copy + (y * world.map.length));
165             exit_trouble(test < 0, __func__, "snprintf()");
166             write_key_space(file, s[S_CMD_T_MEMMAP]);
167             write_value(file, y);
168             try_fputc(' ', file, __func__);
169             write_string(file, string);
170             try_fputc('\n', file, __func__);
171         }
172         free(mem_map_copy);
173         struct ThingInMemory * tm = t->t_mem;
174         for (; tm; tm = tm->next)
175         {
176             write_key_space(file, s[S_CMD_T_MEMTHING]);
177             write_value(file, tm->type);
178             try_fputc(' ', file, __func__);
179             write_value(file, tm->pos.y);
180             try_fputc(' ', file, __func__);
181             write_value(file, tm->pos.x);
182             try_fputc('\n', file, __func__);
183         }
184     }
185     try_fputc('\n', file, __func__);
186 }
187
188
189
190 static char * get_message_from_queue()
191 {
192     char * message = NULL;
193     if (world.queue_size)
194     {
195         size_t cutout_len = strlen(world.queue);
196         uint8_t is_nullbyte_chunk = !cutout_len;
197         if (0 < cutout_len)
198         {
199             cutout_len++;
200             message = try_malloc(cutout_len, __func__);
201             memcpy(message, world.queue, cutout_len);
202         }
203         for (;
204              cutout_len != world.queue_size && '\0' == world.queue[cutout_len];
205              cutout_len++);
206         world.queue_size = world.queue_size - cutout_len;
207         if (0 == world.queue_size)
208         {
209             free(world.queue);   /* NULL so read_file_into_queue() may free() */
210             world.queue = NULL;  /* this every time, even when it's           */
211         }                        /* un-allocated first. */
212         else
213         {
214             char * new_queue = try_malloc(world.queue_size, __func__);
215             memcpy(new_queue, &(world.queue[cutout_len]), world.queue_size);
216             free(world.queue);
217             world.queue = new_queue;
218             if (is_nullbyte_chunk)
219             {
220                 return get_message_from_queue();
221             }
222         }
223     }
224     return message;
225 }
226
227
228
229 static void read_file_into_queue()
230 {
231     uint8_t wait_seconds = 5;
232     time_t now = time(0);
233     struct timespec dur;
234     dur.tv_sec = 0;
235     dur.tv_nsec = 33333333;
236     int test;
237     while (EOF == (test = try_fgetc(world.file_in, __func__)))
238     {
239         nanosleep(&dur, NULL);
240         if (time(0) > now + wait_seconds)
241         {
242             return;
243         }
244     }
245     do
246     {
247         char c = (char) test;
248         if ('\n' == c)
249         {
250             c = '\0';
251         }
252         char * new_queue = try_malloc(world.queue_size + 1, __func__);
253         memcpy(new_queue, world.queue, world.queue_size);
254         char * new_pos = new_queue + world.queue_size;
255         * new_pos = c;
256         world.queue_size++;
257         free(world.queue);
258         world.queue = new_queue;
259     }
260     while (EOF != (test = try_fgetc(world.file_in, __func__)));
261 }
262
263
264
265 static void update_worldstate_file()
266 {
267     char * path_tmp;
268     FILE * file = atomic_write_start(s[S_PATH_WORLDSTATE], &path_tmp);
269     struct Thing * player = get_player();
270     write_value_as_line(world.turn, file);
271     write_value_as_line(player->lifepoints, file);
272     write_inventory(player, file);
273     write_value_as_line(player->pos.y, file);
274     write_value_as_line(player->pos.x, file);
275     write_value_as_line(world.map.length, file);
276     write_map(player, file);
277     if (world.log)
278     {
279         try_fwrite(world.log, strlen(world.log), 1, file, __func__);
280     }
281     atomic_write_finish(file, s[S_PATH_WORLDSTATE], path_tmp);
282     set_cleanup_flag(CLEANUP_WORLDSTATE);
283     char * dot = ".\n";
284     try_fwrite(dot, strlen(dot), 1, world.file_out, __func__);
285     fflush(world.file_out);
286 }
287
288
289
290 static void write_value_as_line(uint32_t value, FILE * file)
291 {
292     char write_buf[12];     /* Holds 10 digits of uint32_t maximum + \n + \0. */
293     exit_trouble(sprintf(write_buf,"%u\n",value) < 0,__func__,s[S_FCN_SPRINTF]);
294     try_fwrite(write_buf, strlen(write_buf), 1, file, __func__);
295 }
296
297
298
299 static void write_inventory(struct Thing * player, FILE * file)
300 {
301     struct Thing * owned = player->owns;
302     if (!owned)
303     {
304         char * empty = "(none)\n";
305         try_fwrite(empty, strlen(empty), 1, file, __func__);
306     }
307     else
308     {
309         uint8_t q;
310         for (q = 0; owned; q++)
311         {
312             struct ThingType * tt = get_thing_type(owned->type);
313             try_fwrite(tt->name, strlen(tt->name), 1, file, __func__);
314             try_fputc('\n', file, __func__);
315             owned = owned->next;
316         }
317     }
318     try_fputc('%', file, __func__);
319     try_fputc('\n', file, __func__);
320 }
321
322
323
324 static char * build_visible_map(struct Thing * player)
325 {
326     uint32_t map_size = world.map.length * world.map.length;
327     char * visible_map = try_malloc(map_size, __func__);
328     memset(visible_map, ' ', map_size);
329     if (player->fov_map) /* May fail if player thing was created / positioned */
330     {                    /* by god command after turning off FOV building.    */
331         uint32_t pos_i;
332         for (pos_i = 0; pos_i < map_size; pos_i++)
333         {
334             if (player->fov_map[pos_i] == 'v')
335             {
336                 visible_map[pos_i] = world.map.cells[pos_i];
337             }
338         }
339         struct Thing * t;
340         char c;
341         uint8_t i;
342         for (i = 0; i < 3; i++)
343         {
344             for (t = world.things; t != 0; t = t->next)
345             {
346                 if ('v' == player->fov_map[t->pos.y*world.map.length+t->pos.x])
347                 {
348                     struct ThingType * tt = get_thing_type(t->type);
349                     if (   (0 == i && !t->lifepoints && !tt->consumable)
350                         || (1 == i && !t->lifepoints &&  tt->consumable)
351                         || (2 == i &&  t->lifepoints))
352                     {
353                         c = tt->char_on_map;
354                         visible_map[t->pos.y * world.map.length + t->pos.x] = c;
355                     }
356                 }
357             }
358         }
359     }
360     return visible_map;
361 }
362
363
364
365 static void write_map(struct Thing * player, FILE * file)
366 {
367     char * visible_map = build_visible_map(player);
368     uint16_t x, y;
369     for (y = 0; y < world.map.length; y++)
370     {
371         for (x = 0; x < world.map.length; x++)
372         {
373             try_fputc(visible_map[y * world.map.length + x], file, __func__);
374         }
375         try_fputc('\n', file, __func__);
376     }
377     free(visible_map);
378     uint32_t map_size = world.map.length * world.map.length;
379     char * mem_map = try_malloc(map_size, __func__);
380     memcpy(mem_map, player->mem_map, map_size);
381     uint8_t i;
382     struct ThingInMemory * tm;
383     for (i = 0; i < 2; i++)
384     {
385         for (tm = player->t_mem; tm; tm = tm->next)
386         {
387             if (' ' != player->mem_map[tm->pos.y*world.map.length+tm->pos.x])
388             {
389                 struct ThingType * tt = get_thing_type(tm->type);
390                 if (   (0 == i && !tt->consumable)
391                     || (1 == i &&  tt->consumable))
392                 {
393                     char c = tt->char_on_map;
394                     mem_map[tm->pos.y * world.map.length + tm->pos.x] = c;
395                 }
396             }
397         }
398     }
399     for (y = 0; y < world.map.length; y++)
400     {
401         for (x = 0; x < world.map.length; x++)
402         {
403             try_fputc(mem_map[y * world.map.length + x], file, __func__);
404         }
405         try_fputc('\n', file, __func__);
406     }
407     free(mem_map);
408 }
409
410
411
412 extern char * io_round()
413 {
414     if (0 < world.queue_size)
415     {
416         return get_message_from_queue();
417     }
418     if (world.do_update)
419     {
420         update_worldstate_file();
421         world.do_update = 0;
422     }
423     read_file_into_queue();
424     if (world.queue_size && '\0' != world.queue[world.queue_size - 1])
425     {
426         char * new_queue = try_malloc(world.queue_size + 1, __func__);
427         memcpy(new_queue, world.queue, world.queue_size);
428         new_queue[world.queue_size] = '\0';
429         world.queue_size++;
430         free(world.queue);
431         world.queue = new_queue;
432     }
433     return get_message_from_queue();
434 }
435
436
437
438 extern void save_world()
439 {
440     char * path_tmp;
441     FILE * file = atomic_write_start(s[S_PATH_SAVE], &path_tmp);
442     write_key_space_value(file, s[S_CMD_MAPLENGTH], world.map.length);
443     write_key_space_value(file, s[S_CMD_PLAYTYPE], world.player_type);
444     try_fputc('\n', file, __func__);
445     struct ThingAction * ta;
446     for (ta = world.thing_actions; ta; ta = ta->next)
447     {
448         write_key_space_value(file, s[S_CMD_TA_ID], ta->id);
449         write_key_space_value(file, s[S_CMD_TA_EFFORT], ta->effort);
450         write_key_space_string(file, s[S_CMD_TA_NAME], ta->name);
451         try_fputc('\n', file, __func__);
452     }
453     struct ThingType * tt;
454     for (tt = world.thing_types; tt; tt = tt->next)
455     {
456         write_key_space_value(file, s[S_CMD_TT_ID], tt->id);
457         write_key_space_value(file, s[S_CMD_TT_STARTN], tt->start_n);
458         write_key_space_value(file, s[S_CMD_TT_HP], tt->lifepoints);
459         int test = fprintf(file, "%s %c\n", s[S_CMD_TT_SYMB], tt->char_on_map);
460         exit_trouble(test < 0, __func__, "fprintf");
461         write_key_space_string(file, s[S_CMD_TT_NAME], tt->name);
462         write_key_space_value(file, s[S_CMD_TT_CONSUM], tt->consumable);
463         write_key_space_value(file, s[S_CMD_TT_PROL], tt->proliferate);
464         try_fputc('\n', file, __func__);
465     }
466     for (tt = world.thing_types; tt; tt = tt->next)
467     {
468         write_key_space_value(file, s[S_CMD_TT_ID], tt->id);
469         write_key_space_value(file, s[S_CMD_TT_CORPS], tt->corpse_id);
470     }
471     try_fputc('\n', file, __func__);
472     write_key_space_value(file, s[S_CMD_SEED_MAP], world.seed_map);
473     write_key_space_value(file, s[S_CMD_SEED_RAND], world.seed);
474     write_key_space_value(file, s[S_CMD_TURN], world.turn);
475     try_fputc('\n', file, __func__);
476     struct Thing * t;
477     for (t = world.things; t; t = t->next)
478     {
479         write_thing(file, t);
480     }
481     write_key_space_value(file, s[S_CMD_WORLD_ACTIVE], 1);
482     atomic_write_finish(file, s[S_PATH_SAVE], path_tmp);
483 }