]> ncurses.scripts.mit.edu Git - ncurses.git/blob - test/rain.c
ncurses 6.3 - patch 20221126
[ncurses.git] / test / rain.c
1 /****************************************************************************
2  * Copyright 2018-2020,2022 Thomas E. Dickey                                *
3  * Copyright 1998-2014,2017 Free Software Foundation, Inc.                  *
4  *                                                                          *
5  * Permission is hereby granted, free of charge, to any person obtaining a  *
6  * copy of this software and associated documentation files (the            *
7  * "Software"), to deal in the Software without restriction, including      *
8  * without limitation the rights to use, copy, modify, merge, publish,      *
9  * distribute, distribute with modifications, sublicense, and/or sell       *
10  * copies of the Software, and to permit persons to whom the Software is    *
11  * furnished to do so, subject to the following conditions:                 *
12  *                                                                          *
13  * The above copyright notice and this permission notice shall be included  *
14  * in all copies or substantial portions of the Software.                   *
15  *                                                                          *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
19  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
20  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
21  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
23  *                                                                          *
24  * Except as contained in this notice, the name(s) of the above copyright   *
25  * holders shall not be used in advertising or otherwise to promote the     *
26  * sale, use or other dealings in this Software without prior written       *
27  * authorization.                                                           *
28  ****************************************************************************/
29 /*
30  * $Id: rain.c,v 1.54 2022/07/23 22:47:38 tom Exp $
31  */
32 #include <test.priv.h>
33 #include <popup_msg.h>
34
35 /* rain 11/3/1980 EPS/CITHEP */
36
37 #ifdef USE_PTHREADS
38 #include <pthread.h>
39 #endif
40
41 WANT_USE_WINDOW();
42
43 #define MAX_THREADS     10
44 #define MAX_DROP        5
45
46 struct DATA;
47
48 typedef void (*DrawPart) (struct DATA *);
49
50 typedef struct DATA {
51     int y, x;
52 #ifdef USE_PTHREADS
53     DrawPart func;
54     int state;
55 #endif
56 } DATA;
57
58 #ifdef USE_PTHREADS
59 pthread_cond_t cond_next_drop;
60 pthread_mutex_t mutex_drop_data;
61 pthread_mutex_t mutex_next_drop;
62 static int used_threads;
63
64 typedef struct {
65     pthread_t myself;
66     long counter;
67 } STATS;
68
69 static STATS drop_threads[MAX_THREADS];
70 #endif
71
72 #if HAVE_USE_WINDOW
73 static int
74 safe_wgetch(WINDOW *w, void *data GCC_UNUSED)
75 {
76     return wgetch(w);
77 }
78 #endif
79
80 static void
81 onsig(int n GCC_UNUSED)
82 {
83     stop_curses();
84     ExitProgram(EXIT_FAILURE);
85 }
86
87 static double
88 ranf(void)
89 {
90     long r = (rand() & 077777);
91     return ((double) r / 32768.);
92 }
93
94 static int
95 random_x(void)
96 {
97     return (int) (((double) (COLS - 4) * ranf()) + 2);
98 }
99
100 static int
101 random_y(void)
102 {
103     return (int) (((double) (LINES - 4) * ranf()) + 2);
104 }
105
106 static int
107 next_j(int j)
108 {
109     if (j == 0)
110         j = MAX_DROP - 1;
111     else
112         --j;
113     if (has_colors()) {
114         int z = (int) (3 * ranf());
115         (void) attrset(AttrArg(COLOR_PAIR(z), (z ? A_BOLD : A_NORMAL)));
116     }
117     return j;
118 }
119
120 static void
121 part1(DATA * drop)
122 {
123     MvAddCh(drop->y, drop->x, '.');
124 }
125
126 static void
127 part2(DATA * drop)
128 {
129     MvAddCh(drop->y, drop->x, 'o');
130 }
131
132 static void
133 part3(DATA * drop)
134 {
135     MvAddCh(drop->y, drop->x, 'O');
136 }
137
138 static void
139 part4(DATA * drop)
140 {
141     MvAddCh(drop->y - 1, drop->x, '-');
142     MvAddStr(drop->y, drop->x - 1, "|.|");
143     MvAddCh(drop->y + 1, drop->x, '-');
144 }
145
146 static void
147 part5(DATA * drop)
148 {
149     MvAddCh(drop->y - 2, drop->x, '-');
150     MvAddStr(drop->y - 1, drop->x - 1, "/ \\");
151     MvAddStr(drop->y, drop->x - 2, "| O |");
152     MvAddStr(drop->y + 1, drop->x - 1, "\\ /");
153     MvAddCh(drop->y + 2, drop->x, '-');
154 }
155
156 static void
157 part6(DATA * drop)
158 {
159     MvAddCh(drop->y - 2, drop->x, ' ');
160     MvAddStr(drop->y - 1, drop->x - 1, "   ");
161     MvAddStr(drop->y, drop->x - 2, "     ");
162     MvAddStr(drop->y + 1, drop->x - 1, "   ");
163     MvAddCh(drop->y + 2, drop->x, ' ');
164 }
165
166 #ifdef USE_PTHREADS
167 static void
168 napsome(void)
169 {
170     napms(60);
171 }
172
173 /*
174  * This runs inside the use_window() mutex.
175  */
176 static int
177 really_draw(WINDOW *win, void *arg)
178 {
179     DATA *data = (DATA *) arg;
180
181     (void) win;
182     next_j(data->state);
183     data->func(data);
184     refresh();
185     return OK;
186 }
187
188 static void
189 draw_part(void (*func) (DATA *), int state, DATA * data)
190 {
191     data->func = func;
192     data->state = state;
193     use_window(stdscr, really_draw, (void *) data);
194     napsome();
195 }
196
197 /*
198  * Tell the threads that one of them can start work on a new raindrop.
199  * They may all be busy if we're sending requests too rapidly.
200  */
201 static int
202 put_next_drop(void)
203 {
204     pthread_cond_broadcast(&cond_next_drop);
205     pthread_mutex_unlock(&mutex_next_drop);
206
207     return 0;
208 }
209
210 /*
211  * Wait until we're assigned the task of drawing a new raindrop.
212  */
213 static int
214 get_next_drop(void)
215 {
216     pthread_mutex_lock(&mutex_next_drop);
217     pthread_cond_wait(&cond_next_drop, &mutex_next_drop);
218
219     return TRUE;
220 }
221
222 static void *
223 draw_drop(void *arg)
224 {
225     DATA mydata;
226     int mystats;
227
228     /*
229      * Find myself in the list of threads so we can count the number of loops.
230      */
231     for (mystats = 0; mystats < MAX_THREADS; ++mystats) {
232 #if defined(_NC_WINDOWS) && !defined(__WINPTHREADS_VERSION)
233         if (drop_threads[mystats].myself.p == pthread_self().p)
234 #else
235         if (drop_threads[mystats].myself == pthread_self())
236 #endif
237             break;
238     }
239
240     do {
241         if (mystats < MAX_THREADS)
242             drop_threads[mystats].counter++;
243
244         /*
245          * Make a copy of caller's data.  We're cheating for the cases after
246          * the first loop since we still have a pointer into the main thread
247          * to the data which it uses for setting up this thread (but it has
248          * been modified to use different coordinates).
249          */
250         pthread_mutex_lock(&mutex_drop_data);
251         mydata = *(DATA *) arg;
252         pthread_mutex_unlock(&mutex_drop_data);
253
254         draw_part(part1, 0, &mydata);
255         draw_part(part2, 1, &mydata);
256         draw_part(part3, 2, &mydata);
257         draw_part(part4, 3, &mydata);
258         draw_part(part5, 4, &mydata);
259         draw_part(part6, 0, &mydata);
260
261     } while (get_next_drop());
262
263     return NULL;
264 }
265
266 /*
267  * The description of pthread_create() is misleading, since it implies that
268  * threads will exit cleanly after their function returns.
269  *
270  * Since they do not (and the number of threads is limited by system
271  * resources), make a limited number of threads, and signal any that are
272  * waiting when we want a thread past that limit.
273  */
274 static int
275 start_drop(DATA * data)
276 {
277     int rc;
278
279     if (!used_threads) {
280         /* mutex and condition for signalling thread */
281         pthread_mutex_init(&mutex_next_drop, NULL);
282         pthread_cond_init(&cond_next_drop, NULL);
283     }
284
285     if (used_threads < MAX_THREADS) {
286         rc = pthread_create(&(drop_threads[used_threads].myself),
287                             NULL,
288                             draw_drop,
289                             data);
290         ++used_threads;
291     } else {
292         rc = put_next_drop();
293     }
294     return rc;
295 }
296 #endif
297
298 static int
299 get_input(void)
300 {
301     return USING_WINDOW1(stdscr, wgetch, safe_wgetch);
302 }
303
304 static void
305 usage(void)
306 {
307     static const char *msg[] =
308     {
309         "Usage: rain [options]"
310         ,""
311         ,"Options:"
312 #if HAVE_USE_DEFAULT_COLORS
313         ," -d       invoke use_default_colors"
314 #endif
315     };
316     size_t n;
317
318     for (n = 0; n < SIZEOF(msg); n++)
319         fprintf(stderr, "%s\n", msg[n]);
320
321     ExitProgram(EXIT_FAILURE);
322 }
323
324 int
325 main(int argc, char *argv[])
326 {
327     static const char *help[] =
328     {
329         "Commands:",
330         " q/Q        exit the program",
331         " s          do single-step",
332         " <space>    undo single-step",
333         "",
334         0
335     };
336
337     bool done = FALSE;
338     DATA drop;
339 #ifndef USE_PTHREADS
340     DATA last[MAX_DROP];
341 #endif
342     int j = 0;
343     int ch;
344 #if HAVE_USE_DEFAULT_COLORS
345     bool d_option = FALSE;
346 #endif
347
348     while ((ch = getopt(argc, argv, "d")) != -1) {
349         switch (ch) {
350 #if HAVE_USE_DEFAULT_COLORS
351         case 'd':
352             d_option = TRUE;
353             break;
354 #endif
355         default:
356             usage();
357             /* NOTREACHED */
358         }
359     }
360     if (optind < argc)
361         usage();
362
363     setlocale(LC_ALL, "");
364
365     InitAndCatch(initscr(), onsig);
366     if (has_colors()) {
367         int bg = COLOR_BLACK;
368         start_color();
369 #if HAVE_USE_DEFAULT_COLORS
370         if (d_option && (use_default_colors() == OK))
371             bg = -1;
372 #endif
373         init_pair(1, COLOR_BLUE, (short) bg);
374         init_pair(2, COLOR_CYAN, (short) bg);
375     }
376     nl();
377     noecho();
378     curs_set(0);
379     timeout(0);
380
381 #ifdef USE_PTHREADS
382     pthread_mutex_init(&mutex_drop_data, NULL);
383 #else /* !USE_PTHREADS */
384     for (j = MAX_DROP; --j >= 0;) {
385         last[j].x = random_x();
386         last[j].y = random_y();
387     }
388     j = 0;
389 #endif
390
391     while (!done) {
392 #ifdef USE_PTHREADS
393         pthread_mutex_lock(&mutex_drop_data);
394
395         drop.x = random_x();
396         drop.y = random_y();
397
398         if (start_drop(&drop) != 0) {
399             beep();
400         }
401
402         pthread_mutex_unlock(&mutex_drop_data);
403 #else
404         drop.x = random_x();
405         drop.y = random_y();
406
407         /*
408          * The non-threaded code draws parts of each drop on each loop.
409          */
410         part1(&drop);
411
412         part2(&last[j]);
413
414         j = next_j(j);
415         part3(&last[j]);
416
417         j = next_j(j);
418         part4(&last[j]);
419
420         j = next_j(j);
421         part5(&last[j]);
422
423         j = next_j(j);
424         part6(&last[j]);
425
426         last[j] = drop;
427 #endif
428
429         switch (get_input()) {
430         case ('q'):
431         case ('Q'):
432             done = TRUE;
433             break;
434         case 's':
435             nodelay(stdscr, FALSE);
436             break;
437         case ' ':
438             nodelay(stdscr, TRUE);
439             break;
440 #ifdef KEY_RESIZE
441         case (KEY_RESIZE):
442             break;
443 #endif
444         case HELP_KEY_1:
445             popup_msg(stdscr, help);
446             break;
447         case ERR:
448             break;
449         default:
450             beep();
451         }
452         napms(50);
453     }
454     stop_curses();
455 #ifdef USE_PTHREADS
456     printf("Counts per thread:\n");
457     for (j = 0; j < MAX_THREADS; ++j)
458         printf("  %d:%ld\n", j, drop_threads[j].counter);
459 #endif
460     ExitProgram(EXIT_SUCCESS);
461 }