about summary refs log tree commit diff
path: root/generator/pgmnoise.c
blob: f5f48ff3cdad7d76d7eff1b29303890f4dbf45c8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/*********************************************************************
   pgmnoise -  create a PGM with white noise
   Frank Neumann, October 1993
*********************************************************************/

#include <assert.h>
#include "pm_c_util.h"
#include "mallocvar.h"
#include "nstring.h"
#include "rand.h"
#include "shhopt.h"
#include "pgm.h"


struct CmdlineInfo {
    /* All the information the user supplied in the command line,
       in a form easy for the program to use.
    */
    unsigned int width;
    unsigned int height;
    unsigned int maxval;
    unsigned int randomseed;
    unsigned int randomseedSpec;
    unsigned int verbose;
};



static void
parseCommandLine(int argc,
                 const char **        const argv,
                 struct CmdlineInfo * const cmdlineP) {
/*----------------------------------------------------------------------------
   Note that the file spec array we return is stored in the storage that
   was passed to us as the argv array.
-----------------------------------------------------------------------------*/
    optEntry * option_def;
        /* Instructions to OptParseOptions3 on how to parse our options.
         */
    optStruct3 opt;
    unsigned int option_def_index;
    unsigned int maxvalSpec;

    MALLOCARRAY_NOFAIL(option_def, 100);

    option_def_index = 0;   /* incremented by OPTENT3 */
    OPTENT3(0,   "randomseed",   OPT_UINT,    &cmdlineP->randomseed,
            &cmdlineP->randomseedSpec,      0);
    OPTENT3(0,   "maxval",       OPT_UINT,    &cmdlineP->maxval,
            &maxvalSpec,                    0);
    OPTENT3(0,   "verbose",      OPT_FLAG,    NULL,
            &cmdlineP->verbose,             0);

    opt.opt_table = option_def;
    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
    opt.allowNegNum = FALSE;  /* We may have parms that are negative numbers */

    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
        /* Uses and sets argc, argv, and some of *cmdlineP and others. */
    free(option_def);

    if (maxvalSpec) {
        if (cmdlineP->maxval > PGM_OVERALLMAXVAL)
            pm_error("Maxval too large: %u.  Maximum is %u",
                     cmdlineP->maxval, PGM_OVERALLMAXVAL);
        else if (cmdlineP->maxval == 0)
            pm_error("Maxval must not be zero");
    } else
        cmdlineP->maxval = PGM_MAXMAXVAL;

    if (argc-1 != 2)
        pm_error("Wrong number of arguments: %u.  "
                 "Arguments are width and height of image, in pixels",
                 argc-1);
    else {
        const char * error; /* error message of pm_string_to_uint */
        unsigned int width, height;

        pm_string_to_uint(argv[1], &width, &error);
        if (error)
            pm_error("Width argument is not an unsigned integer.  %s",
                     error);
        else if (width == 0)
            pm_error("Width argument is zero; must be positive");
        else
            cmdlineP->width = width;

        pm_string_to_uint(argv[2], &height, &error);
        if (error)
            pm_error("Height argument is not an unsigned integer.  %s ",
                     error);
        else if (height == 0)
            pm_error("Height argument is zero; must be positive");
        else
            cmdlineP->height = height;
    }
}



static unsigned int
randPool(unsigned int       const digits,
         bool               const verbose,
         struct pm_randSt * const randStP) {
/*----------------------------------------------------------------------------
  Draw 'digits' bits from pool of random bits.  If the number of random bits
  in pool is insufficient, call pm_rand() and add N bits to it.

  N is 31 or 32.  In raw mode we set this value to 32 regardless of the
  actual number of available bits.  If insufficient, the MSB will be
  set to zero.

  'digits' must be at most 16.

  We assume that each call to pm_rand() generates 31 or 32 bits,
  or randStP->max == 2147483647 or 4294967294.

  The underlying logic is flexible and endian-free.  The above conditions
  can be relaxed.
-----------------------------------------------------------------------------*/
    static unsigned long int hold=0;  /* entropy pool */
    static unsigned int len=0;        /* number of valid bits in pool */

    unsigned int const mask = (1 << digits) - 1;
    unsigned int const randbits = (randStP->max == 2147483647) ? 31 : 32;
    unsigned int retval;

    assert(randStP->max == 2147483647 || randStP->max == 4294967294);
    assert(digits <= 16);

    retval = hold;  /* initial value */

    if (len > digits) { /* Enough bits in hold to satisfy request */
        hold >>= digits;
        len   -= digits;
    } else {            /* Load another 31 or 32 bits into hold */
        hold    = pm_rand(randStP);
        if (verbose)
            pm_message("pm_rand(): %08lX", hold);
        retval |= (hold << len);
        hold >>=  (digits - len);
        len = randbits - digits + len;
    }
    return (retval & mask);
}



static void
pgmnoise(FILE *             const ofP,
         unsigned int       const cols,
         unsigned int       const rows,
         gray               const maxval,
         bool               const verbose,
         struct pm_randSt * const randStP) {

    bool const usingPool =
      !( (randStP->max==2147483647UL || randStP->max==4294967294UL)
           && (maxval & (maxval+1)) );
    unsigned int const bitLen = pm_maxvaltobits(maxval);

    unsigned int row;
    gray * destrow;

    /* If maxval is 2^n-1, we draw exactly n bits from the pool.
       Otherwise call pm_rand() and determine gray value by modulo.

       In the latter case, there is a minuscule skew toward 0 (=black)
       because smaller numbers are produced more frequently by modulo.
       Thus we employ the pool method only when it is certain that no
       skew will ensue.

       To illustrate the point, consider converting the outcome of one
       roll of a fair, six-sided die to 5 values (0 to 4) by N % 5.  The
       probability for values 1, 2, 3, 4 is 1/6, but 0 alone is 2/6.
       Average is 10/6 or 1.6667, compared to 2.0 from an ideal
       generator which produces exactly 5 values.  With two dice
       average improves to 70/36 or 1.9444.

       The more (distinct) dice we roll, or the more binary digits we
       draw, the smaller the skew.
    */

    destrow = pgm_allocrow(cols);

    pgm_writepgminit(ofP, cols, rows, maxval, 0);

    for (row = 0; row < rows; ++row) {
        if (usingPool) {
            unsigned int col;
            for (col = 0; col < cols; ++col)
                destrow[col] = randPool(bitLen, verbose, randStP);
        } else {
            unsigned int col;
            for (col = 0; col < cols; ++col)
                destrow[col] = pm_rand(randStP) % (maxval + 1);
        }
        pgm_writepgmrow(ofP, destrow, cols, maxval, 0);
    }

    pgm_freerow(destrow);
}



int
main(int          argc,
     const char * argv[]) {

    struct CmdlineInfo cmdline;
    struct pm_randSt randSt;

    pm_proginit(&argc, argv);

    parseCommandLine(argc, argv, &cmdline);

    pm_randinit(&randSt);
    pm_srand2(&randSt, cmdline.randomseedSpec, cmdline.randomseed);

    pgmnoise(stdout, cmdline.width, cmdline.height, cmdline.maxval,
             cmdline.verbose, &randSt);

    pm_randterm(&randSt);

    return 0;
}