chiark / gitweb /
Fix remote invocation
[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 const 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 DEBUG_DEFINE_DEBUGF(struct)
36
37 #define START_MAIN {200,100}
38 #define MIN_COLUMNS         6
39 #define INTERESTING_COLUMNS 7
40 #define TEXT_COLUMNS        2
41 #define MAX_COLUMNS         7
42
43 static Rect mainr = { START_MAIN,START_MAIN };
44 static int commbasey, comminty;
45 static int colrightx[INTERESTING_COLUMNS];
46 static int text_h=-1, columns=-1;
47 static OcrReader *rd;
48
49 char *archipelago, *island;
50
51 #define OTHERCOORD_x y
52 #define OTHERCOORD_y x
53
54 const CanonColourInfo canoncolourinfos[]= {
55   { 0x475A5E, '*' }, /* edge */
56   { 0x2C5F7A, '*' }, /* edge just under box heading shadow */
57   { 0xC5C7AE, '*' }, /* blank area of partial commodities list */
58   { 0x6B828C, '*' }, /* background of ship status meter area */
59   { 0x934405, '*' }, /* border of ship meter area */
60   { 0x7D9094, '+' }, /* interbox */
61
62   { 0xBDC5BF, ' ' }, /* background - pale  Sugar cane, etc. */
63   { 0xADB5AF, ' ' }, /* background - dark                   */
64   { 0xC7E1C3, ' ' }, /* background - pale  Swill, etc.      */
65   { 0xB5CFB1, ' ' }, /* background - dark                   */
66   { 0xD6CEB0, ' ' }, /* background - pale  Madder, etc.     */
67   { 0xC8C0A2, ' ' }, /* background - dark                   */
68   { 0xE0E1D3, ' ' }, /* background - pale  Lorandite, etc.  */
69   { 0xD0D1C3, ' ' }, /* background - dark                   */
70   { 0xE5E6C1, ' ' }, /* background - pale  Cloth            */
71   { 0xD7D8B3, ' ' }, /* background - dark                   */
72   { 0xEDDED9, ' ' }, /* background - pale  Dye              */
73   { 0xDACBC6, ' ' }, /* background - dark                   */
74   { 0xD3DEDF, ' ' }, /* background - pale  Paint            */
75   { 0xC5D0D1, ' ' }, /* background - dark                   */
76   { 0xDCD1CF, ' ' }, /* background - pale  Enamel           */
77   { 0xCEC3C1, ' ' }, /* background - dark                   */
78   { 0xF3F6F5, ' ' }, /* background - pale  fruit            */
79   { 0xE2E7E5, ' ' }, /* background - dark                   */
80
81   { 0x000000, 'o' }, /* foreground */
82   { 0xD4B356, ' ' }, /* background (cursor) */
83   { 0xFFFFFF, 'o' }, /* foreground (cursor) */
84
85   { 0x5B93BF, '_' }, /* selector dropdown background */
86   { 0xD7C94F, 'X' }, /* selector dropdown foreground */
87   { 0,0 }
88 };
89
90
91 static void mustfail1(const char *file, int line, const char *what) {
92   fprintf(stderr,
93           "\n\n"
94           "Unable to figure out contents of YPP client display.\n"
95           " Check that your client is logged in has the correct display.\n"
96           " If that isn't the problem, please report this as a fault.\n\n"
97           "Technical details:"
98           " %s:%d: requirement failed:\n"
99           " %s\n",
100           file, line, what);
101 }
102 static void mustfail2(void) NORET;
103 static void mustfail2(void) {
104   fprintf(stderr, "\n\nGiving up.\n");
105   exit(8);
106 }
107
108 #define MUST(x, ifnot) do{                      \
109     if (!(x)) {                                 \
110       mustfail1(__FILE__,__LINE__,#x);          \
111       ifnot;                                    \
112       mustfail2();                              \
113     }                                           \
114   }while(0)
115
116 #define MP(v) fprintf(stderr," %s=%d,%d",#v,(v).x,(v).y)
117 #define MI(v) fprintf(stderr," %s=%d",   #v,(v))
118 #define MC(v) fprintf(stderr," %s='%c'", #v,(v))
119 #define MS(v) fprintf(stderr," %s=\"%s\"", #v,(v))
120 #define MSB(v) fprintf(stderr," %s", (v))
121 #define MR(v) fprintf(stderr," %s=%d,%d..%d,%d",\
122                       #v,(v).tl.x,(v).tl.y,(v).br.x,(v).br.y)
123
124
125 #define REQUIRE_RECTANGLE(tlx,tly,brx,bry,ok) \
126  require_rectangle(tlx, tly, brx, bry, ok, __LINE__);
127
128 static void require_rectangle(int tlx, int tly, int brx, int bry,
129                               const char *ok, int lineno) {
130   Point p;
131   for (p.x=tlx; p.x<=brx; p.x++)
132     for (p.y=tly; p.y<=bry; p.y++) {
133       int c= get_p(p);
134       MUST( strchr(ok,c), ({
135              Rect rm={{tlx,tly},{brx,bry}};
136              MI(lineno),MR(rm);MP(p);MS(ok);
137       }));
138     }
139 }
140 static void require_rectangle_r(Rect rr, const char *ok, int lineno) {
141   require_rectangle(rr.tl.x,rr.tl.y, rr.br.x,rr.br.y, ok, lineno);
142 }
143
144 static void debug_rect(const char *what, int whati, Rect rr) {
145   if (!DEBUGP(rect)) return;
146   int y,w;
147   fprintf(debug, "%s %d: %d,%d..%d,%d:\n", what, whati,
148           rr.tl.x,rr.tl.y, rr.br.x,rr.br.y);
149   w= rr.br.x - rr.tl.x + 1;
150   for (y=rr.tl.y; y<=rr.br.y; y++) {
151     fprintf(debug, "%4d%*s|", y, rr.tl.x,"");
152     fwrite(cim->d + y*cim->w + rr.tl.x, 1, w, debug);
153     fputc('|',debug);
154     fputc('\n',debug);
155   }
156   debug_flush();
157 }
158
159 #define WALK_UNTIL(point,coord,increm,last,edge)                        \
160   for (;;) {                                                            \
161     if ((point).coord == (last)+(increm)) break;                        \
162     if (get_p((point)) == (edge)) { (point).coord -= (increm); break; } \
163     (point).coord += (increm);                                          \
164   }
165
166 #define WALK_UNTIL_MUST(point,coord,increm,last,edge)   \
167   do {                                                  \
168     WALK_UNTIL(point,coord,increm,last,edge);           \
169     MUST( (point).coord != (last)+(increm),             \
170           MP(point); MI(increm); MI(last); MC(edge);    \
171           );                                            \
172   }while(0)
173
174 #define ADJUST_BOX(search,insidechrs,want, lim,LIMIT_MUST, TLBR,XY,increm) \
175   for (;;) {                                                               \
176     LIMIT_MUST( (search).tl.XY != (search).br.XY &&                        \
177                 (search).tl.XY != (lim),                                   \
178                 MR((search));MSB(#TLBR);MSB(#XY) );                        \
179     int got=0;                                                             \
180     Point p=(search).tl;                                                   \
181     for (p.XY=(search).TLBR.XY;                                            \
182          p.OTHERCOORD_##XY <= (search).br.OTHERCOORD_##XY;                 \
183          p.OTHERCOORD_##XY++)                                              \
184       got += !!strchr(insidechrs, get_p(p));                               \
185     if (got >= (want))                                                     \
186       break;                                                               \
187     (search).TLBR.XY += increm;                                            \
188   }
189
190 void find_structure(const CanonImage *im, int *max_relevant_y_r) {
191   cim= im;
192   
193   Rect whole = { {0,0}, {cim->w-1,cim->h-1} };
194
195   if (DEBUGP(rect)) {
196     int xscaleunit, y,x;
197     for (y=0, xscaleunit=1; y<4; y++, xscaleunit*=10) {
198       fprintf(debug,"     ");
199       for (x=0; x<=cim->w; x++) {
200         if (x % xscaleunit) fputc(' ',debug);
201         else fprintf(debug,"%d",(x / xscaleunit)%10);
202       }
203       fputc('\n',debug);
204     }
205   }
206
207   WALK_UNTIL_MUST(mainr.tl, x,-1, whole.tl.x, '*');
208   WALK_UNTIL_MUST(mainr.tl, y,-1, whole.tl.y, '*');
209   WALK_UNTIL_MUST(mainr.br, x,+1, whole.br.x, '*');
210   WALK_UNTIL_MUST(mainr.br, y,+1, whole.br.y, '*');
211
212   REQUIRE_RECTANGLE(mainr.tl.x-1, mainr.tl.y, mainr.tl.x-1, mainr.br.y, "*");
213   REQUIRE_RECTANGLE(mainr.br.x+1, mainr.tl.y, mainr.br.x+1, mainr.br.y, "*");
214   REQUIRE_RECTANGLE(mainr.tl.x, mainr.tl.y-1, mainr.br.x, mainr.tl.y-1, "*");
215   REQUIRE_RECTANGLE(mainr.tl.x, mainr.br.y+1, mainr.br.x, mainr.br.y+1, "*");
216
217 #define CHECK_STRIP_BORDER(tlbr,xy,increm)              \
218   do {                                                  \
219     Point csb_p;                                        \
220     Rect csb_r;                                         \
221     csb_p= mainr.tl;                                    \
222     csb_p.xy= mainr.tlbr.xy;                            \
223     if (get_p(csb_p)=='+') {                            \
224       csb_r= mainr;                                     \
225       csb_r.tl.xy= csb_p.xy;                            \
226       csb_r.br.xy= csb_p.xy;                            \
227       require_rectangle_r(csb_r, "+", __LINE__);        \
228       mainr.tlbr.xy += increm;                          \
229     }                                                   \
230   } while(0)
231
232   debug_rect("mainr",0, mainr);
233
234   CHECK_STRIP_BORDER(tl,x,+1);
235   CHECK_STRIP_BORDER(tl,y,+1);
236   CHECK_STRIP_BORDER(br,x,-1);
237   CHECK_STRIP_BORDER(br,y,-1);
238
239   debug_rect("mainr",1, mainr);
240
241   Point up = START_MAIN;
242   WALK_UNTIL_MUST(up, y,-1, mainr.tl.y, '+');
243
244   Point down = START_MAIN;
245   down.y++;
246   WALK_UNTIL_MUST(down, y,+1, mainr.br.y, '+');
247
248   commbasey= up.y;
249   comminty= down.y - up.y + 2;
250
251   Point across= { mainr.tl.x, commbasey };
252   int colno=0;
253   for (;;) {
254     MUST( get_p(across) != '+', MI(colno);MP(across);MR(mainr);MI(commbasey) );
255     WALK_UNTIL(across, x,+1, mainr.br.x, '+');
256     MUST( colno < MAX_COLUMNS, MP(across);MR(mainr);MI(commbasey); );
257     int colrx= across.x;
258     if (colrx > mainr.br.x) colrx= mainr.br.x;
259     if (colno < INTERESTING_COLUMNS)
260       colrightx[colno]= colrx;
261       
262     colno++;
263     
264     if (across.x >= mainr.br.x-1)
265       break;
266
267     across.x++;
268     REQUIRE_RECTANGLE(across.x,mainr.tl.y, across.x,mainr.br.y, "+");
269     across.x++;
270   }
271   MUST( colno >= MIN_COLUMNS, MI(colno);MR(mainr);MP(across); );
272
273 #define SET_ONCE(var,val) do{                                           \
274     int v= (val);                                                       \
275     if ((var)==-1) (var)= v;                                            \
276     else MUST( (var) == v, MSB(#var);MI((var));MI(v);MR(mainr); );      \
277   }while(0)
278
279   SET_ONCE(columns, colno);
280   SET_ONCE(text_h, comminty - 1);
281   if (max_relevant_y_r)
282     SET_ONCE(*max_relevant_y_r, mainr.br.y + 10);
283 }                   
284
285 void check_correct_commodities(void) {
286   Rect search= { { 50,39 }, { 130,59 } };
287
288   ADJUST_BOX(search,"_",10, cim->h, MUST, tl,y,+1);
289   ADJUST_BOX(search,"_",10, 0,      MUST, br,y,-1);
290
291   debug_rect("commodselr",1, search);
292
293   static const char *all[]= {
294     "   ___________________________________   ",
295     "  ________X____X__X____________________  ",
296     " ________ X___ X_ X_____XXXXXXXXXXX_____ ",
297     "_________X_X__ X_ X______XXXXXXXXX_______",
298     "________ X X__ X_ X_______XXXXXXX________",
299     "________X_ _X_ X_ X________XXXXX_________",
300     "_______ X__ X_ X_ X_________XXX__________",
301     "_______XXXXXXX X_ X__________X___________",
302     " _____ X     X X_ X______________________",
303     "  ____X_____ _XX_ X______________________",
304     "   __ _______  __ ______________________ ",
305   };
306
307   static int allh= sizeof(all)/sizeof(all[0]);
308   const int allw= strlen(all[0]);
309
310   int alloffy, alloffx;
311   for (alloffy=0; alloffy < search.br.y; alloffy++) {
312     if (alloffy+allh-1 < search.tl.y) continue;
313     for (alloffx=search.tl.x; alloffx+allw-1 <= search.br.x; alloffx++) {
314       int good=0, bad=0;
315       int x,y;
316       for (x=0; x<allw; x++)
317         for (y=0; y<allh; y++) {
318           int want= all[y][x];
319           if (want==' ') continue;
320           if (get(alloffx+x, alloffy+y) == want)
321             good++;
322           else
323             bad++;
324         }
325       debugf("CHECKCOMMOD alloff=%d,%d good=%d bad=%d\n",
326              alloffx,alloffy, good,bad);
327       if (good > 20*bad)
328         goto all_found;
329     }
330   }
331   fatal("Commodities selector not set to `All'.");
332
333  all_found:;
334 }
335
336 CanonImage *alloc_canon_image(int w, int h) {
337   CanonImage *im= mmalloc(sizeof(CanonImage) + w*h);
338   im->w= w;
339   im->h= h;
340   memset(im->d,'?',w*h);
341   return im;
342 }
343
344 static void file_read_image_ppm(FILE *f) {
345   struct pam inpam;
346   unsigned char rgb_buf[3];
347   CanonImage *im;
348   RgbImage *ri=0;
349
350   pnm_readpaminit(f, &inpam, sizeof(inpam));
351   if (!(inpam.maxval == 255 &&
352         inpam.bytes_per_sample == 1 &&
353         inpam.format == RPPM_FORMAT))
354     fatal("PNM screenshot(s) file must be 8bpp 1 byte per sample RGB");
355
356   if (!npages)
357     page0_rgbimage= ri= alloc_rgb_image(inpam.width, inpam.height);
358
359   CANONICALISE_IMAGE(im, inpam.width, inpam.height, {
360     int r= fread(&rgb_buf,1,3,f);
361     sysassert(!ferror(f));
362     if (r!=3) fatal("PNM screenshot(s) file ends unexpectedly");
363
364     rgb=
365         ((unsigned long)rgb_buf[0]<<16) |
366         ((unsigned long)rgb_buf[1]<<8) |
367                        (rgb_buf[2]);
368
369     if (ri)
370       CANONIMG_ALSO_STORERGB(ri);
371   });
372
373   sysassert(!ferror(screenshot_file));
374
375   if (!(npages < MAX_PAGES))
376     fatal("Too many images in screenshots file; max is %d.\n", MAX_PAGES);
377
378   page_images[npages++]= im;
379 }
380
381 void read_one_screenshot(void) {
382   progress("reading screenshot...");
383   file_read_image_ppm(screenshot_file);
384   progress_log("read screenshot.");
385 }
386
387 void read_screenshots(void) {
388   struct stat stab;
389   
390   sysassert(! fstat(fileno(screenshot_file), &stab) );
391   
392   for (;;) {
393     if (S_ISREG(stab.st_mode)) {
394       long pos= ftell(screenshot_file);
395       if (pos == stab.st_size) break;
396     } else {
397       int c= fgetc(screenshot_file);
398       if (c==EOF) break;
399       ungetc(c, screenshot_file);
400     }
401     progress("reading screenshot %d...",npages);
402     file_read_image_ppm(screenshot_file);
403   }
404   sysassert(!ferror(screenshot_file));
405   progress_log("read %d screenshots.",npages);
406 }
407
408 static void find_commodity(int offset, Rect *rr) {
409   /* rr->tl.x==-1 if offset out of range */
410   rr->tl.y= commbasey - offset*comminty;
411   rr->br.y= rr->tl.y + comminty-2;
412   if (rr->tl.y < mainr.tl.y || rr->br.y > mainr.br.y) { rr->tl.x=-1; return; }
413   
414   rr->tl.x= mainr.tl.x;
415   rr->br.x= mainr.br.x;
416
417   if (rr->tl.y > mainr.tl.y)
418     REQUIRE_RECTANGLE(rr->tl.x,rr->tl.y-1, rr->br.x,rr->tl.y-1, "+");
419   if (rr->br.y < mainr.tl.y)
420     REQUIRE_RECTANGLE(rr->tl.x,rr->br.y+1, rr->br.x,rr->br.y+1, "+");
421 }
422
423 static void find_table_entry(Rect commod, int colno, Rect *cellr) {
424   cellr->tl.y= commod.tl.y;
425   cellr->br.y= commod.br.y;
426   cellr->tl.x= !colno ? commod.tl.x : colrightx[colno-1]+2;
427   cellr->br.x=                        colrightx[colno];
428   debug_rect("cell", colno, *cellr);
429   require_rectangle_r(*cellr, " o", __LINE__);
430 }
431
432 static void ocr_rectangle(Rect r, const OcrCellType ct, FILE *tsv_output) {
433   OcrResultGlyph *results, *res;
434
435   int w= r.br.x - r.tl.x + 1;
436   Pixcol cols[w+1];
437   int x,y;
438   for (x=0; x<w; x++) {
439     Pixcol cx, rv;
440     for (y=0, cx=0, rv=1; y<text_h; y++, rv<<=1) {
441       Point here= { x+r.tl.x, y+r.tl.y };
442       int pixel= get_p(here);
443       switch (pixel) {
444       case ' ':           break;
445       case 'o': cx |= rv; break;
446       default:
447         MUST(!"wrong pixel",
448              MC(pixel);MP(here);MSB(ocr_celltype_name(ct));MR(r); );
449       }
450     }
451     cols[x]= cx;
452   }
453   cols[w]= 0;
454
455   results= ocr(rd,ct,w,cols);
456   for (res=results; res->s; res++)
457     fputs(res->s,tsv_output);
458 }
459
460 void analyse(FILE *tsv_output) {
461   Rect thisr, entryr;
462   int page, tryrect, colno;
463
464   for (page=0; page<npages; page++) {
465     find_structure(page_images[page], 0);
466
467     if (!page)
468       check_correct_commodities();
469
470     if (!rd)
471       rd= ocr_init(text_h);
472
473     progress("Scanning page %d...",page);
474
475     for (tryrect= +cim->h; tryrect >= -cim->h; tryrect--) {
476       find_commodity(tryrect, &thisr);
477       if (thisr.tl.x < 0)
478         continue;
479       debug_rect("commod",tryrect, thisr);
480
481       const char *tab= "";
482       for (colno=0; colno<columns; colno++) {
483         find_table_entry(thisr,colno,&entryr);
484         fputs(tab, tsv_output);
485         ocr_rectangle(entryr,
486                       colno<TEXT_COLUMNS
487                       ? &ocr_celltype_text
488                       : &ocr_celltype_number,
489                       tsv_output);
490         tab= "\t";
491       }
492       fputs("\n", tsv_output);
493       sysassert(!ferror(tsv_output));
494       sysassert(!fflush(tsv_output));
495     }
496   }
497   progress("Commodity table scan complete.");
498 }
499
500 //static Rect islandnamer;
501
502 void find_islandname(void) {
503   Rect sunshiner;
504   char sunshine[MAXIMGIDENT], archisland[MAXIMGIDENT];
505
506   RgbImage *ri= alloc_rgb_image(page0_rgbimage->w, page0_rgbimage->h);
507   const unsigned char *srcp;
508   unsigned char *destp, *endp;
509   for (srcp=page0_rgbimage->data, destp=ri->data,
510          endp= ri->data + 3 * ri->w * ri->h;
511        destp < endp;
512        srcp++, destp++) {
513     unsigned char c= *srcp & 0xf0;
514     *destp= c | (c>>4);
515   }
516
517   cim= page_images[0];
518   
519   sunshiner.tl.x= cim->w - 1034 +  885;
520   sunshiner.br.x= cim->w - 1034 + 1020;
521   sunshiner.tl.y= 227;
522   sunshiner.br.y= 228;
523
524   ADJUST_BOX(sunshiner,"o*",30, 100,MUST, tl,y,-1);
525   ADJUST_BOX(sunshiner,"o*",30, 100,MUST, br,y,+1);
526   debug_rect("sunshiner",0, sunshiner);
527
528   MUST(sunshiner.br.y - sunshiner.tl.y > 20, MR(sunshiner));
529   sunshiner.br.y--;
530
531   ADJUST_BOX(sunshiner,"o",20, (cim->w - 1034 + 700), MUST, tl,x,-1);
532   ADJUST_BOX(sunshiner,"o",20,  cim->w,               MUST, br,x,+1);
533   debug_rect("sunshiner",1, sunshiner);
534
535   identify_rgbimage(ri, sunshiner, sunshine, "sunshine widget");
536   
537   if (!memcmp(sunshine,"Ship ",5)) {
538     Rect islandnamer;
539     
540     islandnamer.tl.x= cim->w - 1034 +  885;
541     islandnamer.br.x= cim->w - 1034 + 1020;
542     islandnamer.tl.y=                 128;
543     islandnamer.br.y=                 156;
544
545     ADJUST_BOX(islandnamer,"o",5, 0,      MUST, tl,y,+1);
546     ADJUST_BOX(islandnamer,"o",5, cim->h, MUST, br,y,-1);
547
548     debug_rect("islandnamer",0, islandnamer);
549 //    int larger_islandnamebry= islandnamer.tl.y + 25;
550 //    MUST(islandnamer.br.y < larger_islandnamebry,
551 //       MR(islandnamer);MI(larger_islandnamebry));
552 //    islandnamer.br.y = larger_islandnamebry;
553     debug_rect("islandnamer",1, islandnamer);
554
555     int x,y,i;
556     for (x=islandnamer.tl.x; x<=islandnamer.br.x; x++)
557       for (y=islandnamer.tl.y; y<=islandnamer.br.y; y++) {
558         if (RI_PIXEL(ri,x,y)[0] < 0x40) {
559           for (i=0; i<3; i++) {
560             RI_PIXEL(ri,x,y)[i]= 0;
561           }
562         }
563       }
564
565     identify_rgbimage(ri, islandnamer, archisland, "island");
566   } else {
567     assert(!"not vessel");
568   }
569
570   char *delim= strstr(archisland," - ");
571   assert(delim);
572   archipelago= masprintf("%.*s", delim-archisland, archisland);
573   island= masprintf("%s", delim+3);
574
575   free(ri);
576 }