1 /*
2  * Copyright (C) 2003-2010 Neverball authors
3  *
4  * NEVERBALL is  free software; you can redistribute  it and/or modify
5  * it under the  terms of the GNU General  Public License as published
6  * by the Free  Software Foundation; either version 2  of the License,
7  * or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT  ANY  WARRANTY;  without   even  the  implied  warranty  of
11  * MERCHANTABILITY or  FITNESS FOR A PARTICULAR PURPOSE.   See the GNU
12  * General Public License for more details.
13  */
14 
15 #include <stdlib.h>
16 
17 #include "game_proxy.h"
18 #include "queue.h"
19 #include "cmd.h"
20 
21 static Queue cmd_queue;
22 
23 /*
24  * Command filtering.
25  */
26 
27 static int (*filter_fn)(const union cmd *);
28 
29 #define FILTER(cmd) (filter_fn ? filter_fn(cmd) : 1)
30 
game_proxy_filter(int (* fn)(const union cmd *))31 void game_proxy_filter(int (*fn)(const union cmd *))
32 {
33     filter_fn = fn;
34 }
35 
36 /*
37  * Enqueue SRC in the game's command queue.
38  */
game_proxy_enq(const union cmd * src)39 void game_proxy_enq(const union cmd *src)
40 {
41     union cmd *dst;
42 
43     if (!FILTER(src))
44         return;
45 
46     /*
47      * Create the queue.  This is done only once during the life time
48      * of the program.  For simplicity's sake, the queue is never
49      * destroyed.
50      */
51 
52     if (!cmd_queue)
53         cmd_queue = queue_new();
54 
55     /*
56      * Add a copy of the command to the end of the queue.
57      */
58 
59     if ((dst = malloc(sizeof (*dst))))
60     {
61         *dst = *src;
62         queue_enq(cmd_queue, dst);
63     }
64 }
65 
66 /*
67  * Dequeue and return the head element in the game's command queue.
68  * The element must be freed after use.
69  */
game_proxy_deq(void)70 union cmd *game_proxy_deq(void)
71 {
72     return cmd_queue ? queue_deq(cmd_queue) : NULL;
73 }
74 
75 /*
76  * Clear the entire queue.
77  */
game_proxy_clr(void)78 void game_proxy_clr(void)
79 {
80     union cmd *cmdp;
81 
82     while ((cmdp = game_proxy_deq()))
83         cmd_free(cmdp);
84 }
85