chiark / gitweb /
8141feb3db461c60099841db25d3a4954d018dec
[ypp-sc-tools.main.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   { 0x7D9094, '+' }, /* interbox */
51
52   { 0xBDC5BF, ' ' }, /* background - pale  Sugar cane, etc. */
53   { 0xADB5AF, ' ' }, /* background - dark                   */
54   { 0xC7E1C3, ' ' }, /* background - pale  Swill, etc.      */
55   { 0xB5CFB1, ' ' }, /* background - dark                   */
56   { 0xD6CEB0, ' ' }, /* background - pale  Madder, etc.     */
57   { 0xC8C0A2, ' ' }, /* background - dark                   */
58   { 0xE0E1D3, ' ' }, /* background - pale  Lorandite, etc.  */
59   { 0xD0D1C3, ' ' }, /* background - dark                   */
60   { 0xE5E6C1, ' ' }, /* background - pale  Cloth            */
61   { 0xD7D8B3, ' ' }, /* background - dark                   */
62   { 0xEDDED9, ' ' }, /* background - pale  Dye              */
63   { 0xDACBC6, ' ' }, /* background - dark                   */
64   { 0xD3DEDF, ' ' }, /* background - pale  Paint            */
65   { 0xC5D0D1, ' ' }, /* background - dark                   */
66   { 0xDCD1CF, ' ' }, /* background - pale  Enamel           */
67   { 0xCEC3C1, ' ' }, /* background - dark                   */
68   { 0xF3F6F5, ' ' }, /* background - pale  fruit            */
69   { 0xE2E7E5, ' ' }, /* background - dark                   */
70
71   { 0x000000, 'o' }, /* foreground */
72   { 0xD4B356, ' ' }, /* background (cursor) */
73   { 0xFFFFFF, 'o' }, /* foreground (cursor) */
74
75   { 0x5B93BF, '_' }, /* selector dropdown background */
76   { 0xD7C94F, 'X' }, /* selector dropdown foreground */
77   { 0,0 }
78 };
79
80
81 static void mustfail1(const char *file, int line, const char *what) {
82   fprintf(stderr,
83           "\n\n"
84           "Unable to figure out contents YPP client display.\n"
85           " Check that your client is logged in has the correct display.\n"
86           " If that isn't the problem, please report this as a fault.\n\n"
87           "Technical details:"
88           " %s:%d: requirement failed: %s\n",
89           file, line, what);
90 }
91 static void mustfail2(void) NORET;
92 static void mustfail2(void) {
93   fprintf(stderr, "\n\nGiving up.\n");
94   exit(8);
95 }
96
97 #define MUST(x, ifnot) do{                      \
98     if (!(x)) {                                 \
99       mustfail1(__FILE__,__LINE__,#x);          \
100       ifnot;                                    \
101       mustfail2();                              \
102     }                                           \
103   }while(0)
104
105 #define MP(v) fprintf(stderr," %s=%d,%d",#v,(v).x,(v).y)
106 #define MI(v) fprintf(stderr," %s=%d",   #v,(v))
107 #define MC(v) fprintf(stderr," %s='%c'", #v,(v))
108 #define MS(v) fprintf(stderr," %s=\"%s\"", #v,(v))
109 #define MSB(v) fprintf(stderr," %s", (v))
110 #define MR(v) fprintf(stderr," %s=%d,%d..%d,%d",\
111                       #v,(v).tl.x,(v).tl.y,(v).br.x,(v).br.y)
112
113
114 static void require_rectangle(int tlx, int tly, int brx, int bry,
115                               const char *ok) {
116   Point p;
117   for (p.x=tlx; p.x<=brx; p.x++)
118     for (p.y=tly; p.y<=bry; p.y++) {
119       int c= get_p(p);
120       MUST( strchr(ok,c), ({
121              Rect rm={{tlx,tly},{brx,bry}};
122              MR(rm);MP(p);MS(ok);
123       }));
124     }
125 }
126 static void require_rectangle_r(Rect rr, const char *ok) {
127   require_rectangle(rr.tl.x,rr.tl.y, rr.br.x,rr.br.y, ok);
128 }
129
130 static void debug_rect(const char *what, int whati, Rect rr) {
131   if (!DEBUGP(rect)) return;
132   int y,w;
133   fprintf(debug, "%s %d: %d,%d..%d,%d:\n", what, whati,
134           rr.tl.x,rr.tl.y, rr.br.x,rr.br.y);
135   w= rr.br.x - rr.tl.x + 1;
136   for (y=rr.tl.y; y<=rr.br.y; y++) {
137     fprintf(debug, "%4d%*s|", y, rr.tl.x,"");
138     fwrite(cim->d + y*cim->w + rr.tl.x, 1, w, debug);
139     fputc('|',debug);
140     fputc('\n',debug);
141   }
142   debug_flush();
143 }
144
145 #define WALK_UNTIL(point,coord,increm,last,edge)                        \
146   for (;;) {                                                            \
147     if ((point).coord == (last)+(increm)) break;                        \
148     if (get_p((point)) == (edge)) { (point).coord -= (increm); break; } \
149     (point).coord += (increm);                                          \
150   }
151
152 #define WALK_UNTIL_MUST(point,coord,increm,last,edge)   \
153   do {                                                  \
154     WALK_UNTIL(point,coord,increm,last,edge);           \
155     MUST( (point).coord != (last)+(increm),             \
156           MP(point); MI(increm); MI(last); MC(edge);    \
157           );                                            \
158   }while(0)
159
160 void find_structure(CanonImage *im) {
161   cim= im;
162   
163   Rect whole = { {0,0}, {cim->w-1,cim->h-1} };
164
165   WALK_UNTIL_MUST(mainr.tl, x,-1, whole.tl.x, '*');
166   WALK_UNTIL_MUST(mainr.tl, y,-1, whole.tl.y, '*');
167   WALK_UNTIL_MUST(mainr.br, x,+1, whole.br.x, '*');
168   WALK_UNTIL_MUST(mainr.br, y,+1, whole.br.y, '*');
169
170   require_rectangle(mainr.tl.x-1, mainr.tl.y, mainr.tl.x-1, mainr.br.y, "*");
171   require_rectangle(mainr.br.x+1, mainr.tl.y, mainr.br.x+1, mainr.br.y, "*");
172   require_rectangle(mainr.tl.x, mainr.tl.y-1, mainr.br.x, mainr.tl.y-1, "*");
173   require_rectangle(mainr.tl.x, mainr.br.y+1, mainr.br.x, mainr.br.y+1, "*");
174
175 #define CHECK_STRIP_BORDER(tlbr,xy,increm)      \
176   do {                                          \
177     Point csb_p;                                \
178     Rect csb_r;                                 \
179     csb_p= mainr.tl;                            \
180     csb_p.xy= mainr.tlbr.xy;                    \
181     if (get_p(csb_p)=='+') {                    \
182       csb_r= mainr;                             \
183       csb_r.tl.xy= csb_p.xy;                    \
184       csb_r.br.xy= csb_p.xy;                    \
185       require_rectangle_r(csb_r, "+");          \
186       mainr.tlbr.xy += increm;                  \
187     }                                           \
188   } while(0)
189
190   debug_rect("mainr",0, mainr);
191
192   CHECK_STRIP_BORDER(tl,x,+1);
193   CHECK_STRIP_BORDER(tl,y,+1);
194   CHECK_STRIP_BORDER(br,x,-1);
195   CHECK_STRIP_BORDER(br,y,-1);
196
197   debug_rect("mainr",1, mainr);
198
199   Point up = START_MAIN;
200   WALK_UNTIL_MUST(up, y,-1, mainr.tl.y, '+');
201
202   Point down = START_MAIN;
203   down.y++;
204   WALK_UNTIL_MUST(down, y,+1, mainr.br.y, '+');
205
206   if (DEBUGP(rect)) {
207     int xscaleunit, y,x;
208     for (y=0, xscaleunit=1; y<4; y++, xscaleunit*=10) {
209       fprintf(debug,"     ");
210       for (x=0; x<=cim->w; x++) {
211         if (x % xscaleunit) fputc(' ',debug);
212         else fprintf(debug,"%d",(x / xscaleunit)%10);
213       }
214       fputc('\n',debug);
215     }
216   }
217
218   commbasey= up.y;
219   comminty= down.y - up.y + 2;
220
221   Point across= { mainr.tl.x, commbasey };
222   int colno=0;
223   for (;;) {
224     MUST( get_p(across) != '+', MI(colno);MP(across);MR(mainr);MI(commbasey) );
225     WALK_UNTIL(across, x,+1, mainr.br.x, '+');
226     MUST( colno < MAX_COLUMNS, MP(across);MR(mainr);MI(commbasey); );
227     int colrx= across.x;
228     if (colrx > mainr.br.x) colrx= mainr.br.x;
229     if (colno < INTERESTING_COLUMNS)
230       colrightx[colno]= colrx;
231       
232     colno++;
233     
234     if (across.x >= mainr.br.x-1)
235       break;
236
237     across.x++;
238     require_rectangle(across.x,mainr.tl.y, across.x,mainr.br.y, "+");
239     across.x++;
240   }
241   MUST( colno >= MIN_COLUMNS, MI(colno);MR(mainr);MP(across); );
242
243 #define SET_ONCE(var,val) do{                                           \
244     int v= (val);                                                       \
245     if ((var)==-1) (var)= v;                                            \
246     else MUST( (var) == v, MSB(#var);MI((var));MI(v);MR(mainr); );      \
247   }while(0)
248
249   SET_ONCE(columns, colno);
250   SET_ONCE(text_h, comminty - 1);
251 }                   
252
253 CanonImage *alloc_canon_image(int w, int h) {
254   CanonImage *im= mmalloc(sizeof(CanonImage) + w*h);
255   im->w= w;
256   im->h= h;
257   memset(im->d,'?',w*h);
258   return im;
259 }
260
261 static void file_read_image_ppm(FILE *f) {
262   struct pam inpam;
263   unsigned char rgb_buf[3];
264   CanonImage *im;
265
266   pnm_readpaminit(f, &inpam, sizeof(inpam));
267   if (!(inpam.maxval == 255 &&
268         inpam.bytes_per_sample == 1 &&
269         inpam.format == RPPM_FORMAT))
270     fatal("PNM screenshot(s) file must be 8bpp 1 byte per sample RGB");
271
272   CANONICALISE_IMAGE(im, inpam.width, inpam.height, {
273     int r= fread(&rgb_buf,1,3,f);
274     sysassert(!ferror(f));
275     if (r!=3) fatal("PNM screenshot(s) file ends unexpectedly");
276
277     rgb=
278         ((unsigned long)rgb_buf[0]<<16) |
279         ((unsigned long)rgb_buf[1]<<8) |
280                        (rgb_buf[2]);
281   });
282
283   sysassert(!ferror(screenshots_file));
284
285   if (!(npages < MAX_PAGES))
286     fatal("Too many images in screenshots file; max is %d.\n", MAX_PAGES);
287
288   page_images[npages++]= im;
289 }
290
291 void read_one_screenshot(void) {
292   progress("reading screenshot...");
293   file_read_image_ppm(screenshots_file);
294   progress_log("read screenshot.");
295 }
296
297 void read_screenshots(void) {
298   struct stat stab;
299   
300   sysassert(! fstat(fileno(screenshots_file), &stab) );
301   
302   for (;;) {
303     if (S_ISREG(stab.st_mode)) {
304       long pos= ftell(screenshots_file);
305       if (pos == stab.st_size) break;
306     } else {
307       int c= fgetc(screenshots_file);
308       if (c==EOF) break;
309       ungetc(c, screenshots_file);
310     }
311     progress("reading screenshot %d...",npages);
312     file_read_image_ppm(screenshots_file);
313   }
314   sysassert(!ferror(screenshots_file));
315   progress_log("read %d screenshots.",npages);
316 }
317
318 static void find_commodity(int offset, Rect *rr) {
319   /* rr->tl.x==-1 if offset out of range */
320   rr->tl.y= commbasey - offset*comminty;
321   rr->br.y= rr->tl.y + comminty-2;
322   if (rr->tl.y < mainr.tl.y || rr->br.y > mainr.br.y) { rr->tl.x=-1; return; }
323   
324   rr->tl.x= mainr.tl.x;
325   rr->br.x= mainr.br.x;
326
327   if (rr->tl.y > mainr.tl.y)
328     require_rectangle(rr->tl.x,rr->tl.y-1, rr->br.x,rr->tl.y-1, "+");
329   if (rr->br.y < mainr.tl.y)
330     require_rectangle(rr->tl.x,rr->br.y+1, rr->br.x,rr->br.y+1, "+");
331 }
332
333 static void find_table_entry(Rect commod, int colno, Rect *cellr) {
334   cellr->tl.y= commod.tl.y;
335   cellr->br.y= commod.br.y;
336   cellr->tl.x= !colno ? commod.tl.x : colrightx[colno-1]+2;
337   cellr->br.x=                        colrightx[colno];
338   debug_rect("cell", colno, *cellr);
339   require_rectangle_r(*cellr, " o");
340 }
341
342 static void ocr_rectangle(Rect r, const OcrCellType ct, FILE *tsv_output) {
343   OcrResultGlyph *results, *res;
344
345   int w= r.br.x - r.tl.x + 1;
346   Pixcol cols[w+1];
347   int x,y;
348   for (x=0; x<w; x++) {
349     Pixcol cx, rv;
350     for (y=0, cx=0, rv=1; y<text_h; y++, rv<<=1) {
351       Point here= { x+r.tl.x, y+r.tl.y };
352       int pixel= get_p(here);
353       switch (pixel) {
354       case ' ':           break;
355       case 'o': cx |= rv; break;
356       default:
357         MUST(!"wrong pixel",
358              MC(pixel);MP(here);MSB(ocr_celltype_name(ct));MR(r); );
359       }
360     }
361     cols[x]= cx;
362   }
363   cols[w]= 0;
364
365   results= ocr(rd,ct,w,cols);
366   for (res=results; res->s; res++)
367     fputs(res->s,tsv_output);
368 }
369
370 void analyse(FILE *tsv_output) {
371   Rect thisr, entryr;
372   int page, tryrect, colno;
373
374   for (page=0; page<npages; page++) {
375     find_structure(page_images[page]);
376
377     if (!rd)
378       rd= ocr_init(text_h);
379
380     for (tryrect= +cim->h; tryrect >= -cim->h; tryrect--) {
381       find_commodity(tryrect, &thisr);
382       if (thisr.tl.x < 0)
383         continue;
384       debug_rect("commod",tryrect, thisr);
385
386       const char *tab= "";
387       for (colno=0; colno<columns; colno++) {
388         find_table_entry(thisr,colno,&entryr);
389         fputs(tab, tsv_output);
390         ocr_rectangle(entryr,
391                       colno<TEXT_COLUMNS
392                       ? &ocr_celltype_text
393                       : &ocr_celltype_number,
394                       tsv_output);
395         tab= "\t";
396       }
397       fputs("\n", tsv_output);
398       sysassert(!ferror(tsv_output));
399       sysassert(!fflush(tsv_output));
400     }
401   }
402 }