chiark / gitweb /
8fabe1887b9063b12715843046afe9ef72556110
[ypp-sc-tools.db-test.git] / pctb / structure.c
1 /*
2  * Parsing of the structure of the YPP client's displayed image
3  */
4 /*
5  *  This is part of ypp-sc-tools, a set of third-party tools for assisting
6  *  players of Yohoho Puzzle Pirates.
7  * 
8  *  Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
9  * 
10  *  This program is free software: you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation, either version 3 of the License, or
13  *  (at your option) any later version.
14  * 
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  * 
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  * 
23  *  Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
24  *  are used without permission.  This program is not endorsed or
25  *  sponsored by Three Rings.
26  */
27
28 #include "structure.h"
29
30 static CanonImage *cim;
31
32 static inline char get(int x, int y) { return cim->d[y * cim->w + x]; }
33 static inline char get_p(Point p) { return get(p.x,p.y); }
34
35 #define START_MAIN {200,200}
36 #define MIN_COLUMNS         6
37 #define INTERESTING_COLUMNS 7
38 #define TEXT_COLUMNS        2
39 #define MAX_COLUMNS         7
40
41 static Rect mainr = { START_MAIN,START_MAIN };
42 static int commbasey, comminty;
43 static int colrightx[INTERESTING_COLUMNS];
44 static int text_h=-1, columns=-1;
45 static OcrReader *rd;
46
47 const CanonColourInfo canoncolourinfos[]= {
48   { 0x475A5E, '*' }, /* edge */
49   { 0x2C5F7A, '*' }, /* edge just under box heading shadow */
50   { 0xC5C7Ae, '*' }, /* blank area of partial commodities list */
51   { 0x7D9094, '+' }, /* interbox */
52
53   { 0xBDC5BF, ' ' }, /* background - pale  Sugar cane, etc. */
54   { 0xADB5AF, ' ' }, /* background - dark                   */
55   { 0xC7E1C3, ' ' }, /* background - pale  Swill, etc.      */
56   { 0xB5CFB1, ' ' }, /* background - dark                   */
57   { 0xD6CEB0, ' ' }, /* background - pale  Madder, etc.     */
58   { 0xC8C0A2, ' ' }, /* background - dark                   */
59   { 0xE0E1D3, ' ' }, /* background - pale  Lorandite, etc.  */
60   { 0xD0D1C3, ' ' }, /* background - dark                   */
61   { 0xE5E6C1, ' ' }, /* background - pale  Cloth            */
62   { 0xD7D8B3, ' ' }, /* background - dark                   */
63   { 0xEDDED9, ' ' }, /* background - pale  Dye              */
64   { 0xDACBC6, ' ' }, /* background - dark                   */
65   { 0xD3DEDF, ' ' }, /* background - pale  Paint            */
66   { 0xC5D0D1, ' ' }, /* background - dark                   */
67   { 0xDCD1CF, ' ' }, /* background - pale  Enamel           */
68   { 0xCEC3C1, ' ' }, /* background - dark                   */
69   { 0xF3F6F5, ' ' }, /* background - pale  fruit            */
70   { 0xE2E7E5, ' ' }, /* background - dark                   */
71
72   { 0x000000, 'o' }, /* foreground */
73   { 0xD4B356, ' ' }, /* background (cursor) */
74   { 0xFFFFFF, 'o' }, /* foreground (cursor) */
75
76   { 0x5B93BF, '_' }, /* selector dropdown background */
77   { 0xD7C94F, 'X' }, /* selector dropdown foreground */
78   { 0,0 }
79 };
80
81
82 static void mustfail1(const char *file, int line, const char *what) {
83   fprintf(stderr,
84           "\n\n"
85           "Unable to figure out contents YPP client display.\n"
86           " Check that your client is logged in has the correct display.\n"
87           " If that isn't the problem, please report this as a fault.\n\n"
88           "Technical details:"
89           " %s:%d: requirement failed: %s\n",
90           file, line, what);
91 }
92 static void mustfail2(void) NORET;
93 static void mustfail2(void) {
94   fprintf(stderr, "\n\nGiving up.\n");
95   exit(8);
96 }
97
98 #define MUST(x, ifnot) do{                      \
99     if (!(x)) {                                 \
100       mustfail1(__FILE__,__LINE__,#x);          \
101       ifnot;                                    \
102       mustfail2();                              \
103     }                                           \
104   }while(0)
105
106 #define MP(v) fprintf(stderr," %s=%d,%d",#v,(v).x,(v).y)
107 #define MI(v) fprintf(stderr," %s=%d",   #v,(v))
108 #define MC(v) fprintf(stderr," %s='%c'", #v,(v))
109 #define MS(v) fprintf(stderr," %s=\"%s\"", #v,(v))
110 #define MSB(v) fprintf(stderr," %s", (v))
111 #define MR(v) fprintf(stderr," %s=%d,%d..%d,%d",\
112                       #v,(v).tl.x,(v).tl.y,(v).br.x,(v).br.y)
113
114
115 #define REQUIRE_RECTANGLE(tlx,tly,brx,bry,ok) \
116  require_rectangle(tlx, tly, brx, bry, ok, __LINE__);
117
118 static void require_rectangle(int tlx, int tly, int brx, int bry,
119                               const char *ok, int lineno) {
120   Point p;
121   for (p.x=tlx; p.x<=brx; p.x++)
122     for (p.y=tly; p.y<=bry; p.y++) {
123       int c= get_p(p);
124       MUST( strchr(ok,c), ({
125              Rect rm={{tlx,tly},{brx,bry}};
126              MI(lineno),MR(rm);MP(p);MS(ok);
127       }));
128     }
129 }
130 static void require_rectangle_r(Rect rr, const char *ok, int lineno) {
131   require_rectangle(rr.tl.x,rr.tl.y, rr.br.x,rr.br.y, ok, lineno);
132 }
133
134 static void debug_rect(const char *what, int whati, Rect rr) {
135   if (!DEBUGP(rect)) return;
136   int y,w;
137   fprintf(debug, "%s %d: %d,%d..%d,%d:\n", what, whati,
138           rr.tl.x,rr.tl.y, rr.br.x,rr.br.y);
139   w= rr.br.x - rr.tl.x + 1;
140   for (y=rr.tl.y; y<=rr.br.y; y++) {
141     fprintf(debug, "%4d%*s|", y, rr.tl.x,"");
142     fwrite(cim->d + y*cim->w + rr.tl.x, 1, w, debug);
143     fputc('|',debug);
144     fputc('\n',debug);
145   }
146   debug_flush();
147 }
148
149 #define WALK_UNTIL(point,coord,increm,last,edge)                        \
150   for (;;) {                                                            \
151     if ((point).coord == (last)+(increm)) break;                        \
152     if (get_p((point)) == (edge)) { (point).coord -= (increm); break; } \
153     (point).coord += (increm);                                          \
154   }
155
156 #define WALK_UNTIL_MUST(point,coord,increm,last,edge)   \
157   do {                                                  \
158     WALK_UNTIL(point,coord,increm,last,edge);           \
159     MUST( (point).coord != (last)+(increm),             \
160           MP(point); MI(increm); MI(last); MC(edge);    \
161           );                                            \
162   }while(0)
163
164 void find_structure(CanonImage *im, int *max_relevant_y_r) {
165   cim= im;
166   
167   Rect whole = { {0,0}, {cim->w-1,cim->h-1} };
168
169   WALK_UNTIL_MUST(mainr.tl, x,-1, whole.tl.x, '*');
170   WALK_UNTIL_MUST(mainr.tl, y,-1, whole.tl.y, '*');
171   WALK_UNTIL_MUST(mainr.br, x,+1, whole.br.x, '*');
172   WALK_UNTIL_MUST(mainr.br, y,+1, whole.br.y, '*');
173
174   REQUIRE_RECTANGLE(mainr.tl.x-1, mainr.tl.y, mainr.tl.x-1, mainr.br.y, "*");
175   REQUIRE_RECTANGLE(mainr.br.x+1, mainr.tl.y, mainr.br.x+1, mainr.br.y, "*");
176   REQUIRE_RECTANGLE(mainr.tl.x, mainr.tl.y-1, mainr.br.x, mainr.tl.y-1, "*");
177   REQUIRE_RECTANGLE(mainr.tl.x, mainr.br.y+1, mainr.br.x, mainr.br.y+1, "*");
178
179 #define CHECK_STRIP_BORDER(tlbr,xy,increm)              \
180   do {                                                  \
181     Point csb_p;                                        \
182     Rect csb_r;                                         \
183     csb_p= mainr.tl;                                    \
184     csb_p.xy= mainr.tlbr.xy;                            \
185     if (get_p(csb_p)=='+') {                            \
186       csb_r= mainr;                                     \
187       csb_r.tl.xy= csb_p.xy;                            \
188       csb_r.br.xy= csb_p.xy;                            \
189       require_rectangle_r(csb_r, "+", __LINE__);        \
190       mainr.tlbr.xy += increm;                          \
191     }                                                   \
192   } while(0)
193
194   debug_rect("mainr",0, mainr);
195
196   CHECK_STRIP_BORDER(tl,x,+1);
197   CHECK_STRIP_BORDER(tl,y,+1);
198   CHECK_STRIP_BORDER(br,x,-1);
199   CHECK_STRIP_BORDER(br,y,-1);
200
201   debug_rect("mainr",1, mainr);
202
203   Point up = START_MAIN;
204   WALK_UNTIL_MUST(up, y,-1, mainr.tl.y, '+');
205
206   Point down = START_MAIN;
207   down.y++;
208   WALK_UNTIL_MUST(down, y,+1, mainr.br.y, '+');
209
210   if (DEBUGP(rect)) {
211     int xscaleunit, y,x;
212     for (y=0, xscaleunit=1; y<4; y++, xscaleunit*=10) {
213       fprintf(debug,"     ");
214       for (x=0; x<=cim->w; x++) {
215         if (x % xscaleunit) fputc(' ',debug);
216         else fprintf(debug,"%d",(x / xscaleunit)%10);
217       }
218       fputc('\n',debug);
219     }
220   }
221
222   commbasey= up.y;
223   comminty= down.y - up.y + 2;
224
225   Point across= { mainr.tl.x, commbasey };
226   int colno=0;
227   for (;;) {
228     MUST( get_p(across) != '+', MI(colno);MP(across);MR(mainr);MI(commbasey) );
229     WALK_UNTIL(across, x,+1, mainr.br.x, '+');
230     MUST( colno < MAX_COLUMNS, MP(across);MR(mainr);MI(commbasey); );
231     int colrx= across.x;
232     if (colrx > mainr.br.x) colrx= mainr.br.x;
233     if (colno < INTERESTING_COLUMNS)
234       colrightx[colno]= colrx;
235       
236     colno++;
237     
238     if (across.x >= mainr.br.x-1)
239       break;
240
241     across.x++;
242     REQUIRE_RECTANGLE(across.x,mainr.tl.y, across.x,mainr.br.y, "+");
243     across.x++;
244   }
245   MUST( colno >= MIN_COLUMNS, MI(colno);MR(mainr);MP(across); );
246
247 #define SET_ONCE(var,val) do{                                           \
248     int v= (val);                                                       \
249     if ((var)==-1) (var)= v;                                            \
250     else MUST( (var) == v, MSB(#var);MI((var));MI(v);MR(mainr); );      \
251   }while(0)
252
253   SET_ONCE(columns, colno);
254   SET_ONCE(text_h, comminty - 1);
255   if (max_relevant_y_r)
256     SET_ONCE(*max_relevant_y_r, mainr.br.y + 10);
257 }                   
258
259 CanonImage *alloc_canon_image(int w, int h) {
260   CanonImage *im= mmalloc(sizeof(CanonImage) + w*h);
261   im->w= w;
262   im->h= h;
263   memset(im->d,'?',w*h);
264   return im;
265 }
266
267 static void file_read_image_ppm(FILE *f) {
268   struct pam inpam;
269   unsigned char rgb_buf[3];
270   CanonImage *im;
271
272   pnm_readpaminit(f, &inpam, sizeof(inpam));
273   if (!(inpam.maxval == 255 &&
274         inpam.bytes_per_sample == 1 &&
275         inpam.format == RPPM_FORMAT))
276     fatal("PNM screenshot(s) file must be 8bpp 1 byte per sample RGB");
277
278   CANONICALISE_IMAGE(im, inpam.width, inpam.height, {
279     int r= fread(&rgb_buf,1,3,f);
280     sysassert(!ferror(f));
281     if (r!=3) fatal("PNM screenshot(s) file ends unexpectedly");
282
283     rgb=
284         ((unsigned long)rgb_buf[0]<<16) |
285         ((unsigned long)rgb_buf[1]<<8) |
286                        (rgb_buf[2]);
287   });
288
289   sysassert(!ferror(screenshot_file));
290
291   if (!(npages < MAX_PAGES))
292     fatal("Too many images in screenshots file; max is %d.\n", MAX_PAGES);
293
294   page_images[npages++]= im;
295 }
296
297 void read_one_screenshot(void) {
298   progress("reading screenshot...");
299   file_read_image_ppm(screenshot_file);
300   progress_log("read screenshot.");
301 }
302
303 void read_screenshots(void) {
304   struct stat stab;
305   
306   sysassert(! fstat(fileno(screenshot_file), &stab) );
307   
308   for (;;) {
309     if (S_ISREG(stab.st_mode)) {
310       long pos= ftell(screenshot_file);
311       if (pos == stab.st_size) break;
312     } else {
313       int c= fgetc(screenshot_file);
314       if (c==EOF) break;
315       ungetc(c, screenshot_file);
316     }
317     progress("reading screenshot %d...",npages);
318     file_read_image_ppm(screenshot_file);
319   }
320   sysassert(!ferror(screenshot_file));
321   progress_log("read %d screenshots.",npages);
322 }
323
324 static void find_commodity(int offset, Rect *rr) {
325   /* rr->tl.x==-1 if offset out of range */
326   rr->tl.y= commbasey - offset*comminty;
327   rr->br.y= rr->tl.y + comminty-2;
328   if (rr->tl.y < mainr.tl.y || rr->br.y > mainr.br.y) { rr->tl.x=-1; return; }
329   
330   rr->tl.x= mainr.tl.x;
331   rr->br.x= mainr.br.x;
332
333   if (rr->tl.y > mainr.tl.y)
334     REQUIRE_RECTANGLE(rr->tl.x,rr->tl.y-1, rr->br.x,rr->tl.y-1, "+");
335   if (rr->br.y < mainr.tl.y)
336     REQUIRE_RECTANGLE(rr->tl.x,rr->br.y+1, rr->br.x,rr->br.y+1, "+");
337 }
338
339 static void find_table_entry(Rect commod, int colno, Rect *cellr) {
340   cellr->tl.y= commod.tl.y;
341   cellr->br.y= commod.br.y;
342   cellr->tl.x= !colno ? commod.tl.x : colrightx[colno-1]+2;
343   cellr->br.x=                        colrightx[colno];
344   debug_rect("cell", colno, *cellr);
345   require_rectangle_r(*cellr, " o", __LINE__);
346 }
347
348 static void ocr_rectangle(Rect r, const OcrCellType ct, FILE *tsv_output) {
349   OcrResultGlyph *results, *res;
350
351   int w= r.br.x - r.tl.x + 1;
352   Pixcol cols[w+1];
353   int x,y;
354   for (x=0; x<w; x++) {
355     Pixcol cx, rv;
356     for (y=0, cx=0, rv=1; y<text_h; y++, rv<<=1) {
357       Point here= { x+r.tl.x, y+r.tl.y };
358       int pixel= get_p(here);
359       switch (pixel) {
360       case ' ':           break;
361       case 'o': cx |= rv; break;
362       default:
363         MUST(!"wrong pixel",
364              MC(pixel);MP(here);MSB(ocr_celltype_name(ct));MR(r); );
365       }
366     }
367     cols[x]= cx;
368   }
369   cols[w]= 0;
370
371   results= ocr(rd,ct,w,cols);
372   for (res=results; res->s; res++)
373     fputs(res->s,tsv_output);
374 }
375
376 void analyse(FILE *tsv_output) {
377   Rect thisr, entryr;
378   int page, tryrect, colno;
379
380   for (page=0; page<npages; page++) {
381     find_structure(page_images[page], 0);
382
383     if (!rd)
384       rd= ocr_init(text_h);
385
386     for (tryrect= +cim->h; tryrect >= -cim->h; tryrect--) {
387       find_commodity(tryrect, &thisr);
388       if (thisr.tl.x < 0)
389         continue;
390       debug_rect("commod",tryrect, thisr);
391
392       const char *tab= "";
393       for (colno=0; colno<columns; colno++) {
394         find_table_entry(thisr,colno,&entryr);
395         fputs(tab, tsv_output);
396         ocr_rectangle(entryr,
397                       colno<TEXT_COLUMNS
398                       ? &ocr_celltype_text
399                       : &ocr_celltype_number,
400                       tsv_output);
401         tab= "\t";
402       }
403       fputs("\n", tsv_output);
404       sysassert(!ferror(tsv_output));
405       sysassert(!fflush(tsv_output));
406     }
407   }
408 }