li_recognizer.c 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. /*
  10. * li_recognizer.c
  11. *
  12. * Copyright 2000 Compaq Computer Corporation.
  13. * Copying or modifying this code for any purpose is permitted,
  14. * provided that this copyright notice is preserved in its entirety
  15. * in all copies or modifications.
  16. * COMPAQ COMPUTER CORPORATION MAKES NO WARRANTIES, EXPRESSED OR
  17. * IMPLIED, AS TO THE USEFULNESS OR CORRECTNESS OF THIS CODE OR
  18. *
  19. *
  20. * Adapted from cmu_recognizer.c by Jay Kistler.
  21. *
  22. * Where is the CMU copyright???? Gotta track it down - Jim Gettys
  23. *
  24. * Credit to Dean Rubine, Jim Kempf, and Ari Rapkin.
  25. */
  26. #include <u.h>
  27. #include <libc.h>
  28. #include <stdio.h>
  29. #include <draw.h>
  30. #include <scribble.h>
  31. #include "scribbleimpl.h"
  32. #include "hre_internal.h"
  33. #include "li_recognizer_internal.h"
  34. int lidebug = 0;
  35. #define LI_MAGIC 0xACCBADDD
  36. #define CHECK_LI_MAGIC(_a) \
  37. ((_a) != nil && ((li_recognizer*)(_a))->li_magic == LI_MAGIC)
  38. static void lialg_initialize(rClassifier *);
  39. static int lialg_read_classifier_digest(rClassifier *);
  40. static int lialg_canonicalize_examples(rClassifier *);
  41. static char *lialg_recognize_stroke(rClassifier *, point_list *);
  42. static void lialg_compute_lpf_parameters(void);
  43. char* li_err_msg = nil;
  44. #define bcopy(s1,s2,n) memmove(s2,s1,n)
  45. /*Freeing classifier*/
  46. static void
  47. free_rClassifier(rClassifier* rc);
  48. /*
  49. * Point List Support
  50. */
  51. static point_list*
  52. add_example(point_list* l,int npts,pen_point* pts)
  53. {
  54. pen_point* lpts = mallocz(npts*sizeof(pen_point), 1);
  55. point_list *p = malloc(sizeof(point_list));
  56. p->npts = npts;
  57. p->pts = lpts;
  58. p->next = l; /*Order doesn't matter, so we stick on end.*/
  59. /*Copy points.*/
  60. bcopy(pts, lpts, npts * sizeof(pen_point));
  61. return(p);
  62. }
  63. static void
  64. delete_examples(point_list* l)
  65. {
  66. point_list* p;
  67. for( ; l != nil; l = p ) {
  68. p = l->next;
  69. free(l->pts);
  70. free(l);
  71. }
  72. }
  73. /*
  74. * Local functions
  75. */
  76. /*
  77. * recognize_internal-Form Vector, use Classifier to classify, return char.
  78. */
  79. static char*
  80. recognize_internal(rClassifier* rec, Stroke* str, int* i)
  81. {
  82. char *res;
  83. point_list *stroke;
  84. stroke = add_example(nil, str->npts, str->pts);
  85. if (stroke == nil) return(nil);
  86. res = lialg_recognize_stroke(rec, stroke);
  87. delete_examples(stroke);
  88. return(res);
  89. }
  90. /*
  91. * file_path-Construct pathname, check for proper extension.
  92. */
  93. static int
  94. file_path(char* dir,char* filename,char* pathname)
  95. {
  96. char* dot;
  97. /*Check for proper extension on file name.*/
  98. dot = strrchr(filename,'.');
  99. if( dot == nil ) {
  100. return(-1);
  101. }
  102. /*Determine whether a gesture or character classifier.*/
  103. if( strcmp(dot,LI_CLASSIFIER_EXTENSION) != 0 ) {
  104. return(-1);
  105. }
  106. /*Concatenate directory and filename into pathname.*/
  107. strcpy(pathname,dir);
  108. strcat(pathname,"/");
  109. strcat(pathname,filename);
  110. return(0);
  111. }
  112. /*read_classifier_points-Read points so classifier can be extended.*/
  113. static int
  114. read_classifier_points(FILE* fd,int nclss,point_list** ex,char** cnames)
  115. {
  116. int i,j,k;
  117. char buf[BUFSIZ];
  118. int nex = 0;
  119. char* names[MAXSCLASSES];
  120. point_list* examples[MAXSCLASSES];
  121. pen_point* pts;
  122. int npts;
  123. /*Initialize*/
  124. for( i = 0; i < MAXSCLASSES; i++ ) {
  125. names[i] = nil;
  126. examples[i] = nil;
  127. }
  128. /*Go thru classes.*/
  129. for( k = 0; k < nclss; k++ ) {
  130. /*Read class name and number of examples.*/
  131. if( fscanf(fd,"%d %s",&nex,buf) != 2 )
  132. goto unallocate;
  133. /*Save class name*/
  134. names[k] = strdup(buf);
  135. /*Read examples.*/
  136. for( i = 0; i < nex; i++ ) {
  137. /*Read number of points.*/
  138. if( fscanf(fd,"%d",&npts) != 1 )
  139. goto unallocate; /*Boy would I like exceptions!*/
  140. /*Allocate array for points.*/
  141. if( (pts = mallocz(npts*sizeof(pen_point), 1)) == nil )
  142. goto unallocate;
  143. /*Read in points.*/
  144. for( j = 0; j < npts; j++ ) {
  145. int x,y;
  146. if( fscanf(fd,"%d %d",&x,&y) != 2 ) {
  147. delete_pen_point_array(pts);
  148. goto unallocate;
  149. }
  150. pts[j].Point = Pt(x, y);
  151. }
  152. /*Add example*/
  153. if( (examples[k] = add_example(examples[k],npts,pts)) == nil ) {
  154. delete_pen_point_array(pts);
  155. goto unallocate;
  156. }
  157. delete_pen_point_array(pts);
  158. }
  159. }
  160. /* ari -- end of list of classes */
  161. /* fprint(2, "]\n"); */
  162. /*Transfer to recognizer.*/
  163. bcopy(examples,ex,sizeof(examples));
  164. bcopy(names,cnames,sizeof(names));
  165. return(0);
  166. /*Error. Deallocate memory and return.*/
  167. unallocate:
  168. for( ; k >= 0; k-- ) {
  169. delete_examples(examples[k]);
  170. free(names[k]);
  171. }
  172. return(-1);
  173. }
  174. /*read_classifier-Read a classifier file.*/
  175. static int read_classifier(FILE* fd,rClassifier* rc)
  176. {
  177. li_err_msg = nil;
  178. /*Read in classifier file.*/
  179. if(fscanf(fd, "%d", &rc->nclasses) != 1)
  180. return -1;
  181. /*Read in the example points, so classifier can be extended.*/
  182. if( read_classifier_points(fd,rc->nclasses,rc->ex,rc->cnames) != 0 )
  183. return -1;
  184. return(0);
  185. }
  186. /*
  187. * Extension Functions
  188. */
  189. /* getClasses and clearState are by Ari */
  190. static int
  191. recognizer_getClasses (recognizer r, char ***list, int *nc)
  192. {
  193. int i, nclasses;
  194. li_recognizer* rec;
  195. char **ret;
  196. rec = (li_recognizer*)r->recognizer_specific;
  197. /*Check for LI recognizer.*/
  198. if( !CHECK_LI_MAGIC(rec) ) {
  199. li_err_msg = "Not a LI recognizer";
  200. return(-1);
  201. }
  202. *nc = nclasses = rec->li_rc.nclasses;
  203. ret = malloc(nclasses*sizeof(char*));
  204. for (i = 0; i < nclasses; i++)
  205. ret[i] = rec->li_rc.cnames[i]; /* only the 1st char of the cname */
  206. *list = ret;
  207. return 0;
  208. }
  209. static int
  210. recognizer_clearState (recognizer r)
  211. {
  212. /*This operation isn't supported by the LI recognizer.*/
  213. li_err_msg = "Clearing state is not supported by the LI recognizer";
  214. return(-1);
  215. }
  216. static bool isa_li(recognizer r)
  217. { return(CHECK_LI_MAGIC(r)); }
  218. static int
  219. recognizer_train(recognizer r, rc* rc, uint u, Stroke* s, rec_element* re, bool b)
  220. {
  221. /*This operation isn't supported by the LI recognizer.*/
  222. li_err_msg = "Training is not supported by the LI recognizer";
  223. return(-1);
  224. }
  225. int
  226. li_recognizer_get_example (recognizer r,
  227. int class,
  228. int instance,
  229. char **name,
  230. pen_point **points,
  231. int *npts)
  232. {
  233. li_recognizer *rec = (li_recognizer*)r->recognizer_specific;
  234. int nclasses = rec->li_rc.nclasses;
  235. point_list *pl;
  236. if( !CHECK_LI_MAGIC(rec) ) {
  237. li_err_msg = "Not a LI recognizer";
  238. return(-1);
  239. }
  240. if (class > nclasses)
  241. return -1;
  242. pl = rec->li_rc.canonex[class];
  243. while (instance && pl)
  244. {
  245. pl = pl->next;
  246. instance--;
  247. }
  248. if (!pl)
  249. return -1;
  250. *name = rec->li_rc.cnames[class];
  251. *points = pl->pts;
  252. *npts = pl->npts;
  253. return pl->npts; /* I hope [sjm] */
  254. }
  255. /*
  256. * API Functions
  257. */
  258. /*li_recognizer_load-Load a classifier file.*/
  259. static int li_recognizer_load(recognizer r, char* dir, char* filename)
  260. {
  261. FILE *fd;
  262. char* pathname;
  263. li_recognizer* rec;
  264. rClassifier* rc;
  265. rec = (li_recognizer*)r->recognizer_specific;
  266. /*Make sure recognizer's OK*/
  267. if( !CHECK_LI_MAGIC(rec) ) {
  268. li_err_msg = "Not a LI recognizer";
  269. return(-1);
  270. }
  271. rc = &(rec->li_rc);
  272. /*Check parameters.*/
  273. if( filename == nil ) {
  274. li_err_msg = "Invalid parameters";
  275. return(-1);
  276. }
  277. /*We let the directory be null.*/
  278. if( dir == nil || (int)strlen(dir) <= 0 ) {
  279. dir = ".";
  280. }
  281. if(0)fprint(2, "dir = %s, filename = %s\n",
  282. dir, filename);
  283. /*Make full pathname and check filename*/
  284. pathname = malloc((strlen(dir) + strlen(filename) + 2)*sizeof(char));
  285. if( file_path(dir, filename, pathname) == -1 ) {
  286. free(pathname);
  287. li_err_msg = "Not a LI recognizer classifier file";
  288. return -1;
  289. }
  290. /* Try to short-circuit the full classifier-file processing. */
  291. rc->file_name = pathname;
  292. if (lialg_read_classifier_digest(rc) == 0)
  293. return(0);
  294. rc->file_name = nil;
  295. /*Open the file*/
  296. if( (fd = fopen(pathname,"r")) == nil ) {
  297. li_err_msg = "Can't open classifier file";
  298. if(0)fprint(2, "Can't open %s.\n", pathname);
  299. free(pathname);
  300. return(-1);
  301. }
  302. /*If rClassifier is OK, then delete it first.*/
  303. if( rc->file_name != nil ) {
  304. free_rClassifier(rc);
  305. }
  306. /*Read classifier.*/
  307. if( read_classifier(fd,rc) < 0 ) {
  308. free(pathname);
  309. return(-1);
  310. }
  311. /*Close file.*/
  312. fclose(fd);
  313. /*Add classifier name.*/
  314. rc->file_name = pathname;
  315. /* Canonicalize examples. */
  316. if (lialg_canonicalize_examples(rc) != 0) {
  317. free(pathname);
  318. rc->file_name = nil;
  319. return -1;
  320. }
  321. return(0);
  322. }
  323. /*li_recognizer_save-Save a classifier file.*/
  324. static int li_recognizer_save(recognizer r, char* c, char* d)
  325. {
  326. /*This operation isn't supported by the LI recognizer.*/
  327. li_err_msg = "Saving is not supported by the LI recognizer";
  328. return -1;
  329. }
  330. static wordset
  331. li_recognizer_load_dictionary(recognizer r, char* c, char* d)
  332. {
  333. /*This operation isn't supported by the LI recognizer.*/
  334. li_err_msg = "Dictionaries are not supported by the LI recognizer";
  335. return nil;
  336. }
  337. static int
  338. li_recognizer_save_dictionary(recognizer r, char* c, char* d, wordset w)
  339. {
  340. /*This operation isn't supported by the LI recognizer.*/
  341. li_err_msg = "Dictionaries are not supported by the LI recognizer";
  342. return -1;
  343. }
  344. static int
  345. li_recognizer_free_dictionary(recognizer r, wordset w)
  346. {
  347. /*This operation isn't supported by the LI recognizer.*/
  348. li_err_msg = "Dictionaries are not supported by the LI recognizer";
  349. return -1;
  350. }
  351. static int
  352. li_recognizer_add_to_dictionary(recognizer r, letterset* l, wordset w)
  353. {
  354. /*This operation isn't supported by the LI recognizer.*/
  355. li_err_msg = "Dictionaries are not supported by the LI recognizer";
  356. return -1;
  357. }
  358. static int
  359. li_recognizer_delete_from_dictionary(recognizer r, letterset* l, wordset w)
  360. {
  361. /*This operation isn't supported by the LI recognizer.*/
  362. li_err_msg = "Dictionaries are not supported by the LI recognizer";
  363. return -1;
  364. }
  365. static char*
  366. li_recognizer_error(recognizer rec)
  367. {
  368. char* ret = li_err_msg;
  369. /*Check for LI recognizer.*/
  370. if( !CHECK_LI_MAGIC(rec->recognizer_specific) ) {
  371. li_err_msg = "Not a LI recognizer";
  372. return nil;
  373. }
  374. li_err_msg = nil;
  375. return ret;
  376. }
  377. static int
  378. li_recognizer_clear(recognizer r, bool b)
  379. {
  380. li_recognizer* rec;
  381. rec = (li_recognizer*)r->recognizer_specific;
  382. /*Check for LI recognizer.*/
  383. if( !CHECK_LI_MAGIC(rec) ) {
  384. li_err_msg = "Not a LI recognizer";
  385. return 0;
  386. }
  387. return 0;
  388. }
  389. static int
  390. li_recognizer_set_context(recognizer r, rc* rc)
  391. {
  392. /*This operation isn't supported by the LI recognizer.*/
  393. li_err_msg = "Contexts are not supported by the LI recognizer";
  394. return -1;
  395. }
  396. static rc*
  397. li_recognizer_get_context(recognizer r)
  398. {
  399. /*This operation isn't supported by the LI recognizer.*/
  400. li_err_msg = "Contexts are not supported by the LI recognizer";
  401. return nil;
  402. }
  403. static int
  404. li_recognizer_get_buffer(recognizer r, uint* u, Stroke** s)
  405. {
  406. /*This operation isn't supported by the LI recognizer.*/
  407. li_err_msg = "Buffer get/set are not supported by the LI recognizer";
  408. return -1;
  409. }
  410. static int
  411. li_recognizer_set_buffer(recognizer r, uint u, Stroke* s)
  412. {
  413. /*This operation isn't supported by the LI recognizer.*/
  414. li_err_msg = "Buffer get/set are not supported by the LI recognizer";
  415. return -1;
  416. }
  417. static int
  418. li_recognizer_translate(recognizer r, uint ncs, Stroke* tps, bool b, int* nret, rec_alternative** ret)
  419. {
  420. char* clss;
  421. li_recognizer* rec;
  422. int conf;
  423. rClassifier* rc;
  424. rec = (li_recognizer*)r->recognizer_specific;
  425. *nret = 0;
  426. *ret = nil;
  427. /*Check for LI recognizer.*/
  428. if( !CHECK_LI_MAGIC(rec) ) {
  429. li_err_msg = "Not a LI recognizer";
  430. return(-1);
  431. }
  432. rc = &(rec->li_rc);
  433. /*Check for valid parameters.*/
  434. if (ncs < 1) {
  435. li_err_msg = "Invalid parameters: ncs";
  436. return(-1);
  437. }
  438. if( tps == nil) {
  439. li_err_msg = "Invalid parameters: tps";
  440. return(-1);
  441. }
  442. if( nret == nil) {
  443. li_err_msg = "Invalid parameters: nret";
  444. return(-1);
  445. }
  446. if( ret == nil) {
  447. li_err_msg = "Invalid parameters: ret";
  448. return(-1);
  449. }
  450. /*
  451. * Go through the stroke array and recognize. Since this is a single
  452. * stroke recognizer, each stroke is treated as a separate
  453. * character or gesture. We allow only characters or gestures
  454. * to be recognized at one time, since otherwise, handling
  455. * the display of segmentation would be difficult.
  456. */
  457. clss = recognize_internal(rc,tps,&conf);
  458. if (clss == nil) {
  459. *nret = 1;
  460. return(0);
  461. }
  462. /*Return values.*/
  463. *nret = 1;
  464. return(*clss);
  465. }
  466. static rec_fn*
  467. li_recognizer_get_extension_functions(recognizer rec)
  468. {
  469. rec_fn* ret;
  470. /*Check for LI recognizer.*/
  471. if( !CHECK_LI_MAGIC(rec->recognizer_specific) ) {
  472. li_err_msg = "Not a LI recognizer";
  473. return(nil);
  474. }
  475. ret = make_rec_fn_array(LI_NUM_EX_FNS);
  476. /* ari -- clearState & getClasses are mine */
  477. ret[LI_GET_CLASSES] = (rec_fn)recognizer_getClasses;
  478. ret[LI_CLEAR] = (rec_fn)recognizer_clearState;
  479. ret[LI_ISA_LI] = (rec_fn)isa_li;
  480. ret[LI_TRAIN] = (rec_fn)recognizer_train;
  481. return(ret);
  482. }
  483. static char**
  484. li_recognizer_get_gesture_names(recognizer r)
  485. {
  486. /*This operation isn't supported by the LI recognizer.*/
  487. li_err_msg = "Gestures are not supported by the LI recognizer";
  488. return nil;
  489. }
  490. static xgesture
  491. li_recognizer_set_gesture_action(recognizer r, char* c, xgesture x, void* v)
  492. {
  493. /*This operation isn't supported by the LI recognizer.*/
  494. li_err_msg = "Gestures are not supported by the LI recognizer";
  495. return nil;
  496. }
  497. /*
  498. * Exported Functions
  499. */
  500. /*RECOGNIZER_INITIALIZE-Initialize the recognizer.*/
  501. /* note from ari: this expands via pre-processor to
  502. *
  503. * recognizer __recognizer_internal_initialize(rec_info* ri)
  504. */
  505. RECOGNIZER_INITIALIZE(ri)
  506. {
  507. recognizer r;
  508. li_recognizer* rec;
  509. int i;
  510. /*Check that locale matches.*/
  511. if( strcmp(ri->ri_locale,LI_SUPPORTED_LOCALE) != 0 ) {
  512. li_err_msg = "Not a supported locale";
  513. /* fprint(2, "Locale error.\n");*/
  514. return(nil);
  515. }
  516. /*
  517. * Check that character sets match. Note that this is only approximate,
  518. * since the classifier file will have more information.
  519. */
  520. if( ri->ri_subset != nil ) {
  521. for(i = 0; ri->ri_subset[i] != nil; i++ ) {
  522. if( strcmp(ri->ri_subset[i],UPPERCASE) != 0 &&
  523. strcmp(ri->ri_subset[i],LOWERCASE) != 0 &&
  524. strcmp(ri->ri_subset[i],DIGITS) != 0 &&
  525. strcmp(ri->ri_subset[i],GESTURE) != 0 ) {
  526. li_err_msg = "Not a supported character set";
  527. /* fprint(2, "charset error.\n"); */
  528. return(nil);
  529. }
  530. }
  531. }
  532. /* ari */
  533. r = make_recognizer(ri);
  534. /* fprint(2, "past make_recognizer.\n"); */
  535. if( r == nil ) {
  536. li_err_msg = "Can't allocate storage";
  537. return(nil);
  538. }
  539. /*Make a LI recognizer structure.*/
  540. /* rec = (li_recognizer*)safe_malloc(sizeof(li_recognizer))) == nil ); */
  541. rec = malloc(sizeof(li_recognizer));
  542. r->recognizer_specific = rec;
  543. rec->li_rc.file_name = nil;
  544. rec->li_rc.nclasses = 0;
  545. /*Initialize the recognizer struct.*/
  546. r->recognizer_load_state = li_recognizer_load;
  547. r->recognizer_save_state = li_recognizer_save;
  548. r->recognizer_load_dictionary = li_recognizer_load_dictionary;
  549. r->recognizer_save_dictionary = li_recognizer_save_dictionary;
  550. r->recognizer_free_dictionary = li_recognizer_free_dictionary;
  551. r->recognizer_add_to_dictionary = li_recognizer_add_to_dictionary;
  552. r->recognizer_delete_from_dictionary = li_recognizer_delete_from_dictionary;
  553. r->recognizer_error = li_recognizer_error;
  554. r->recognizer_translate = li_recognizer_translate;
  555. r->recognizer_get_context = li_recognizer_get_context;
  556. r->recognizer_set_context = li_recognizer_set_context;
  557. r->recognizer_get_buffer = li_recognizer_get_buffer;
  558. r->recognizer_set_buffer = li_recognizer_set_buffer;
  559. r->recognizer_clear = li_recognizer_clear;
  560. r->recognizer_get_extension_functions =
  561. li_recognizer_get_extension_functions;
  562. r->recognizer_get_gesture_names = li_recognizer_get_gesture_names;
  563. r->recognizer_set_gesture_action =
  564. li_recognizer_set_gesture_action;
  565. /*Initialize LI Magic Number.*/
  566. rec->li_magic = LI_MAGIC;
  567. /*Initialize rClassifier.*/
  568. rec->li_rc.file_name = nil;
  569. for( i = 0; i < MAXSCLASSES; i++ ) {
  570. rec->li_rc.ex[i] = nil;
  571. rec->li_rc.cnames[i] = nil;
  572. }
  573. lialg_initialize(&rec->li_rc);
  574. /*Get rid of error message. Not needed here.*/
  575. li_err_msg = nil;
  576. return(r);
  577. }
  578. /*free_rClassifier-Free the rClassifier.*/
  579. static void
  580. free_rClassifier(rClassifier* rc)
  581. {
  582. int i;
  583. if( rc->file_name != nil) {
  584. free(rc->file_name);
  585. }
  586. for( i = 0; rc->ex[i] != nil; i++) {
  587. delete_examples(rc->ex[i]);
  588. free(rc->cnames[i]);
  589. }
  590. }
  591. /*RECOGNIZER_FINALIZE-Deallocate the recognizer, finalize.*/
  592. RECOGNIZER_FINALIZE(r)
  593. {
  594. li_recognizer* rec = (li_recognizer*)r->recognizer_specific;
  595. /*Make sure this is a li_recognizer first*/
  596. if( !CHECK_LI_MAGIC(rec) ) {
  597. li_err_msg = "Not a LI recognizer";
  598. return(-1);
  599. }
  600. /*Deallocate rClassifier resources.*/
  601. free_rClassifier(&(rec->li_rc));
  602. /*Deallocate the li_recognizer struct.*/
  603. free(rec);
  604. /*Deallocate the recognizer*/
  605. delete_recognizer(r);
  606. return(0);
  607. }
  608. /* **************************************************
  609. Implementation of the Li/Yeung recognition algorithm
  610. ************************************************** */
  611. #define WORST_SCORE 0x7fffffff
  612. /* Dynamic programming parameters */
  613. #define DP_BAND 3
  614. #define MIN_SIM 0
  615. #define MAX_DIST 0x7fffffff
  616. #define SIM_THLD 60 /* x 100 */
  617. #define DIST_THLD 3200 /* x 100 */
  618. /* Low-pass filter parameters -- empirically derived */
  619. #define LP_FILTER_WIDTH 6
  620. #define LP_FILTER_ITERS 8
  621. #define LP_FILTER_THLD 250 /* x 100 */
  622. #define LP_FILTER_MIN 5
  623. /* Pseudo-extrema parameters -- empirically derived */
  624. #define PE_AL_THLD 1500 /* x 100 */
  625. #define PE_ATCR_THLD 135 /* x 100 */
  626. /* Contour-angle derivation parameters */
  627. #define T_ONE 1
  628. #define T_TWO 20
  629. /* Pre-processing and canonicalization parameters */
  630. #define CANONICAL_X 108
  631. #define CANONICAL_Y 128
  632. #define DIST_SQ_THRESHOLD (3*3) /* copied from fv.h */
  633. #define NCANONICAL 50
  634. /* Tap-handling parameters */
  635. #define TAP_CHAR "."
  636. #define TAP_TIME_THLD 150 /* msec */
  637. #define TAP_DIST_THLD 75 /* dx * dx + dy * dy */
  638. #define TAP_PATHLEN 1000 /* x 100 */
  639. /* region types */
  640. #define RGN_CONVEX 0
  641. #define RGN_CONCAVE 1
  642. #define RGN_PLAIN 2
  643. #define RGN_PSEUDO 3
  644. typedef struct RegionList {
  645. int start;
  646. int end;
  647. int type;
  648. struct RegionList *next;
  649. } region_list;
  650. /* direction-code table; indexed by dx, dy */
  651. static int lialg_dctbl[3][3] = {{1, 0, 7}, {2, 0x7FFFFFFF, 6}, {3, 4, 5}};
  652. /* low-pass filter weights */
  653. static int lialg_lpfwts[2 * LP_FILTER_WIDTH + 1];
  654. static int lialg_lpfconst = -1;
  655. static int lialg_preprocess_stroke(point_list *);
  656. static point_list *lialg_compute_dominant_points(point_list *);
  657. static point_list *lialg_interpolate_points(point_list *);
  658. static void lialg_bresline(pen_point *, pen_point *, point_list *, int *);
  659. static void lialg_compute_chain_code(point_list *);
  660. static void lialg_compute_unit_chain_code(point_list *);
  661. static region_list *lialg_compute_regions(point_list *);
  662. static point_list *lialg_compute_dompts(point_list *, region_list *);
  663. static int *lialg_compute_contour_angle_set(point_list *, region_list *);
  664. static void lialg_score_stroke(point_list *, point_list *, int *, int *);
  665. static int lialg_compute_similarity(point_list *, point_list *);
  666. static int lialg_compute_distance(point_list *, point_list *);
  667. static int lialg_read_classifier_digest(rClassifier *);
  668. static int lialg_canonicalize_examples(rClassifier *);
  669. static int lialg_canonicalize_example_stroke(point_list *);
  670. static int lialg_compute_equipoints(point_list *);
  671. static int lialg_compute_pathlen(point_list *);
  672. static int lialg_compute_pathlen_subset(point_list *, int, int);
  673. static int lialg_filter_points(point_list *);
  674. static int lialg_translate_points(point_list *, int, int, int, int);
  675. static void lialg_get_bounding_box(point_list *, int *, int *, int *, int *);
  676. static void lialg_compute_lpf_parameters();
  677. static int isqrt(int);
  678. static int likeatan(int, int);
  679. static int quadr(int);
  680. /*************************************************************
  681. Core routines for the Li/Yeung recognition algorithm
  682. *************************************************************/
  683. static void lialg_initialize(rClassifier *rec) {
  684. int i;
  685. /* Initialize the dompts arrays. */
  686. for (i = 0; i < MAXSCLASSES; i++) {
  687. rec->dompts[i] = nil;
  688. }
  689. }
  690. /*
  691. * Main recognition routine -- called by HRE API.
  692. */
  693. static char *lialg_recognize_stroke(rClassifier *rec, point_list *stroke) {
  694. int i;
  695. char *name = nil;
  696. point_list *input_dompts = nil;
  697. char *best_name = nil;
  698. int best_score = WORST_SCORE;
  699. char *curr_name;
  700. point_list *curr_dompts;
  701. /* (void)gettimeofday(&stv, nil);*/
  702. if (stroke->npts < 1) goto done;
  703. /* Check for tap. */
  704. /* First thing is to filter out ``close points.'' */
  705. if (lialg_filter_points(stroke) != 0) return(nil);
  706. /* Unfortunately, we don't have the actual time that each point */
  707. /* was recorded (i.e., dt is invalid). Hence, we have to use a */
  708. /* heuristic based on total distance and the number of points. */
  709. if (stroke->npts == 1 || lialg_compute_pathlen(stroke) < TAP_PATHLEN)
  710. return(TAP_CHAR);
  711. /* Pre-process input stroke. */
  712. if (lialg_preprocess_stroke(stroke) != 0) goto done;
  713. /* Compute its dominant points. */
  714. input_dompts = lialg_compute_dominant_points(stroke);
  715. if (input_dompts == nil) goto done;
  716. /* Score input stroke against every class in classifier. */
  717. for (i = 0, curr_name = rec->cnames[i], curr_dompts = rec->dompts[i];
  718. i < MAXSCLASSES && curr_name != nil && curr_dompts != nil;
  719. i++, curr_name = rec->cnames[i], curr_dompts = rec->dompts[i]) {
  720. int sim;
  721. int dist;
  722. int curr_score;
  723. lialg_score_stroke(input_dompts, curr_dompts, &sim, &dist);
  724. curr_score = dist;
  725. if (lidebug && curr_score < DIST_THLD)
  726. fprint(2, "(%s, %d, %d) ", curr_name, sim, dist);
  727. /* Is it the best so far? */
  728. if (curr_score < best_score && curr_score <= DIST_THLD) {
  729. best_score = curr_score;
  730. best_name = curr_name;
  731. }
  732. }
  733. if (lidebug)
  734. fprint(2, "\n");
  735. /* No errors. */
  736. name = best_name;
  737. done:
  738. delete_examples(input_dompts);
  739. return(name);
  740. }
  741. static int lialg_preprocess_stroke(point_list *points) {
  742. int minx, miny, maxx, maxy, xrange, yrange, scale, xoff, yoff;
  743. /* Filter out points that are too close. */
  744. /* We did this earlier, when we checked for a tap. */
  745. /*
  746. if (lialg_filter_points(points) != 0) return(-1);
  747. */
  748. /* assert(points->npts > 0);*/
  749. /* Scale up to avoid conversion errors. */
  750. lialg_get_bounding_box(points, &minx, &miny, &maxx, &maxy);
  751. xrange = maxx - minx;
  752. yrange = maxy - miny;
  753. scale = ( ((100 * xrange + CANONICAL_X / 2) / CANONICAL_X) >
  754. ((100 * yrange + CANONICAL_Y / 2) / CANONICAL_Y))
  755. ? (100 * CANONICAL_X + xrange / 2) / xrange
  756. : (100 * CANONICAL_Y + yrange / 2) / yrange;
  757. if (lialg_translate_points(points, minx, miny, scale, scale) != 0)
  758. return(-1);
  759. /* Center the stroke. */
  760. lialg_get_bounding_box(points, &minx, &miny, &maxx, &maxy);
  761. xrange = maxx - minx;
  762. yrange = maxy - miny;
  763. xoff = -((CANONICAL_X - xrange + 1) / 2);
  764. yoff = -((CANONICAL_Y - yrange + 1) / 2);
  765. if (lialg_translate_points(points, xoff, yoff, 100, 100) != 0) return(-1);
  766. /* Store the x and y ranges in the point list. */
  767. xrange = maxx - minx;
  768. yrange = maxy - miny;
  769. points->xrange = xrange;
  770. points->yrange = yrange;
  771. if (lidebug) {
  772. int i;
  773. fprint(2, "After pre-processing: %d %d %d %d\n",
  774. minx, miny, maxx, maxy);
  775. for (i = 0; i < points->npts; i++)
  776. fprint(2, " (%P)\n", points->pts[i].Point);
  777. fflush(stderr);
  778. }
  779. return(0);
  780. }
  781. static point_list *lialg_compute_dominant_points(point_list *points) {
  782. point_list *ipts;
  783. region_list *regions;
  784. point_list *dpts;
  785. /* Interpolate points. */
  786. ipts = lialg_interpolate_points(points);
  787. if (ipts == nil) return(nil);
  788. if (lidebug) {
  789. int j;
  790. fprint(2, "After interpolation: %d ipts\n", ipts->npts);
  791. for (j = 0; j < ipts->npts; j++) {
  792. fprint(2, " (%P), %lu\n", ipts->pts[j].Point, ipts->pts[j].chaincode);
  793. }
  794. fflush(stderr);
  795. }
  796. /* Compute regions. */
  797. regions = lialg_compute_regions(ipts);
  798. /* assert(regions != nil);*/
  799. /* Compute dominant points. */
  800. dpts = lialg_compute_dompts(ipts, regions);
  801. if (lidebug) {
  802. int j;
  803. fprint(2, "Dominant points: ");
  804. for (j = 0; j < dpts->npts; j++) {
  805. fprint(2, "%P (%lu) ", dpts->pts[j].Point, dpts->pts[j].chaincode);
  806. }
  807. fprint(2, "\n");
  808. fflush(stderr);
  809. }
  810. /* Delete region data structure. */
  811. {
  812. region_list *curr, *next;
  813. for (curr = regions; curr != nil; ) {
  814. next = curr->next;
  815. free(curr);
  816. curr = next;
  817. }
  818. }
  819. delete_examples(ipts);
  820. return(dpts);
  821. }
  822. /* Input points are assumed to be integer-valued! */
  823. static point_list *lialg_interpolate_points(point_list *points) {
  824. int i, j;
  825. int maxpts;
  826. point_list *newpts;
  827. /* Compute an upper-bound on the number of interpolated points. */
  828. maxpts = 0;
  829. for (i = 0; i < (points->npts - 1); i++) {
  830. pen_point *pta = &(points->pts[i]);
  831. pen_point *ptb = &(points->pts[i+1]);
  832. maxpts += abs(pta->x - ptb->x) + abs(pta->y - ptb->y);
  833. }
  834. /* Allocate an array of the requisite size. */
  835. maxpts += points->npts;
  836. /* newpts = (point_list *)safe_malloc(sizeof(point_list)); */
  837. newpts = malloc(sizeof(point_list));
  838. newpts->pts = mallocz(maxpts*sizeof(pen_point), 1);
  839. if (newpts->pts == nil) {
  840. free(newpts);
  841. return(nil);
  842. }
  843. newpts->npts = maxpts;
  844. newpts->next = nil;
  845. /* Interpolate each of the segments. */
  846. j = 0;
  847. for (i = 0; i < (points->npts - 1); i++) {
  848. pen_point *startpt = &(points->pts[i]);
  849. pen_point *endpt = &(points->pts[i+1]);
  850. lialg_bresline(startpt, endpt, newpts, &j);
  851. j--; /* end point gets recorded as start point of next segment! */
  852. }
  853. /* Add-in last point. */
  854. newpts->pts[j++] = points->pts[points->npts - 1];
  855. newpts->npts = j;
  856. /* Compute the chain code for P (the list of points). */
  857. lialg_compute_unit_chain_code(newpts);
  858. return(newpts);
  859. }
  860. /* This implementation is due to Kenny Hoff. */
  861. static void lialg_bresline(pen_point *startpt, pen_point *endpt,
  862. point_list *newpts, int *j) {
  863. int Ax, Ay, Bx, By, dX, dY, Xincr, Yincr;
  864. Ax = startpt->x;
  865. Ay = startpt->y;
  866. Bx = endpt->x;
  867. By = endpt->y;
  868. /* INITIALIZE THE COMPONENTS OF THE ALGORITHM THAT ARE NOT AFFECTED */
  869. /* BY THE SLOPE OR DIRECTION OF THE LINE */
  870. dX = abs(Bx-Ax); /* store the change in X and Y of the line endpoints */
  871. dY = abs(By-Ay);
  872. /* DETERMINE "DIRECTIONS" TO INCREMENT X AND Y (REGARDLESS OF DECISION) */
  873. if (Ax > Bx) { Xincr=-1; } else { Xincr=1; } /* which direction in X? */
  874. if (Ay > By) { Yincr=-1; } else { Yincr=1; } /* which direction in Y? */
  875. /* DETERMINE INDEPENDENT VARIABLE (ONE THAT ALWAYS INCREMENTS BY 1 (OR -1) ) */
  876. /* AND INITIATE APPROPRIATE LINE DRAWING ROUTINE (BASED ON FIRST OCTANT */
  877. /* ALWAYS). THE X AND Y'S MAY BE FLIPPED IF Y IS THE INDEPENDENT VARIABLE. */
  878. if (dX >= dY) { /* if X is the independent variable */
  879. int dPr = dY<<1; /* amount to increment decision if right is chosen (always) */
  880. int dPru = dPr - (dX<<1); /* amount to increment decision if up is chosen */
  881. int P = dPr - dX; /* decision variable start value */
  882. /* process each point in the line one at a time (just use dX) */
  883. for (; dX>=0; dX--) {
  884. newpts->pts[*j].x = Ax;
  885. newpts->pts[*j].y = Ay;
  886. (*j)++;
  887. if (P > 0) { /* is the pixel going right AND up? */
  888. Ax+=Xincr; /* increment independent variable */
  889. Ay+=Yincr; /* increment dependent variable */
  890. P+=dPru; /* increment decision (for up) */
  891. } else { /* is the pixel just going right? */
  892. Ax+=Xincr; /* increment independent variable */
  893. P+=dPr; /* increment decision (for right) */
  894. }
  895. }
  896. } else { /* if Y is the independent variable */
  897. int dPr = dX<<1; /* amount to increment decision if right is chosen (always) */
  898. int dPru = dPr - (dY<<1); /* amount to increment decision if up is chosen */
  899. int P = dPr - dY; /* decision variable start value */
  900. /* process each point in the line one at a time (just use dY) */
  901. for (; dY>=0; dY--) {
  902. newpts->pts[*j].x = Ax;
  903. newpts->pts[*j].y = Ay;
  904. (*j)++;
  905. if (P > 0) { /* is the pixel going up AND right? */
  906. Ax+=Xincr; /* increment dependent variable */
  907. Ay+=Yincr; /* increment independent variable */
  908. P+=dPru; /* increment decision (for up) */
  909. } else { /* is the pixel just going up? */
  910. Ay+=Yincr; /* increment independent variable */
  911. P+=dPr; /* increment decision (for right) */
  912. }
  913. }
  914. }
  915. }
  916. static void lialg_compute_chain_code(point_list *pts) {
  917. int i;
  918. for (i = 0; i < (pts->npts - 1); i++) {
  919. pen_point *startpt = &(pts->pts[i]);
  920. pen_point *endpt = &(pts->pts[i+1]);
  921. int dx = endpt->x - startpt->x;
  922. int dy = endpt->y - startpt->y;
  923. int tmp = quadr(likeatan(dy, dx));
  924. int dircode = (12 - tmp) % 8;
  925. startpt->chaincode = dircode;
  926. }
  927. }
  928. static void lialg_compute_unit_chain_code(point_list *pts) {
  929. int i;
  930. for (i = 0; i < (pts->npts - 1); i++) {
  931. pen_point *startpt = &(pts->pts[i]);
  932. pen_point *endpt = &(pts->pts[i+1]);
  933. int dx = endpt->x - startpt->x;
  934. int dy = endpt->y - startpt->y;
  935. int dircode = lialg_dctbl[dx+1][dy+1];
  936. startpt->chaincode = dircode;
  937. }
  938. }
  939. static region_list *lialg_compute_regions(point_list *pts) {
  940. region_list *regions;
  941. region_list *curr_reg;
  942. int *R[2 + LP_FILTER_ITERS];
  943. int *junk;
  944. int *curr, *next;
  945. int i, j;
  946. /* Initialize low-pass filter parameters if necessary. */
  947. if (lialg_lpfconst == -1)
  948. lialg_compute_lpf_parameters();
  949. /* Allocate a 2 x pts->npts array for use in computing the (filtered) Angle set, A_n. */
  950. junk = malloc((2 + LP_FILTER_ITERS) * pts->npts*sizeof(int));
  951. for (i = 0; i < (2 + LP_FILTER_ITERS); i++)
  952. R[i] = junk + (i * pts->npts);
  953. curr = R[0];
  954. /* Compute the Angle set, A, in the first element of array R. */
  955. /* Values in R are in degrees, x 100. */
  956. curr[0] = 18000; /* a_0 */
  957. for (i = 1; i < (pts->npts - 1); i++) {
  958. int d_i = pts->pts[i].chaincode;
  959. int d_iminusone = pts->pts[i-1].chaincode;
  960. int a_i;
  961. if (d_iminusone < d_i)
  962. d_iminusone += 8;
  963. a_i = (d_iminusone - d_i) % 8;
  964. /* convert to degrees, x 100 */
  965. curr[i] = ((12 - a_i) % 8) * 45 * 100;
  966. }
  967. curr[pts->npts - 1] = 18000; /* a_L-1 */
  968. /* Perform a number of filtering iterations. */
  969. next = R[1];
  970. for (j = 0; j < LP_FILTER_ITERS; j++, curr = R[j], next = R[j+1]) {
  971. for (i = 0; i < pts->npts; i++) {
  972. int k;
  973. next[i] = 0;
  974. for (k = i - LP_FILTER_WIDTH; k <= i + LP_FILTER_WIDTH; k++) {
  975. int oldval = (k < 0 || k >= pts->npts) ? 18000 : curr[k];
  976. next[i] += oldval * lialg_lpfwts[k - (i - LP_FILTER_WIDTH)]; /* overflow? */
  977. }
  978. next[i] /= lialg_lpfconst;
  979. }
  980. }
  981. /* Do final thresholding around PI. */
  982. /* curr and next are set-up correctly at end of previous loop! */
  983. for (i = 0; i < pts->npts; i++)
  984. next[i] = (abs(curr[i] - 18000) < LP_FILTER_THLD) ? 18000 : curr[i];
  985. curr = next;
  986. /* Debugging. */
  987. if (lidebug > 1) {
  988. for (i = 0; i < pts->npts; i++) {
  989. fprint(2, "%3d: (%P) %lu ",
  990. i, pts->pts[i].Point, pts->pts[i].chaincode);
  991. for (j = 0; j < 2 + LP_FILTER_ITERS; j++)
  992. fprint(2, "%d ", R[j][i]);
  993. fprint(2, "\n");
  994. }
  995. }
  996. /* Do the region segmentation. */
  997. {
  998. int start, end;
  999. int currtype;
  1000. #define RGN_TYPE(val) (((val)==18000)?RGN_PLAIN:((val)<18000?RGN_CONCAVE:RGN_CONVEX))
  1001. start = 0;
  1002. currtype = RGN_TYPE(curr[0]);
  1003. regions = malloc(sizeof(region_list));
  1004. curr_reg = regions;
  1005. curr_reg->start = start;
  1006. curr_reg->end = 0;
  1007. curr_reg->type = currtype;
  1008. curr_reg->next = nil;
  1009. for (i = 1; i < pts->npts; i++) {
  1010. int nexttype = RGN_TYPE(curr[i]);
  1011. if (nexttype != currtype) {
  1012. region_list *next_reg;
  1013. end = i - 1;
  1014. curr_reg->end = end;
  1015. if (lidebug > 1)
  1016. fprint(2, " (%d, %d), %d\n", start, end, currtype);
  1017. start = i;
  1018. currtype = nexttype;
  1019. next_reg = malloc(sizeof(region_list));
  1020. next_reg->start = start;
  1021. next_reg->end = 0;
  1022. next_reg->type = nexttype;
  1023. next_reg->next = nil;
  1024. curr_reg->next = next_reg;
  1025. curr_reg = next_reg;
  1026. }
  1027. }
  1028. end = i - 1;
  1029. curr_reg->end = end;
  1030. if (lidebug > 1)
  1031. fprint(2, " (%d, %d), %d\n", start, end, currtype);
  1032. /* Filter out convex/concave regions that are too short. */
  1033. for (curr_reg = regions; curr_reg; curr_reg = curr_reg->next)
  1034. if (curr_reg->type == RGN_PLAIN) {
  1035. region_list *next_reg;
  1036. for (next_reg = curr_reg->next;
  1037. next_reg != nil &&
  1038. (next_reg->end - next_reg->start) < LP_FILTER_MIN;
  1039. next_reg = curr_reg->next) {
  1040. /* next_reg must not be plain, and it must be followed by a plain */
  1041. /* assert(next_reg->type != RGN_PLAIN); */
  1042. /* assert(next_reg->next != nil && (next_reg->next)->type == RGN_PLAIN); */
  1043. curr_reg->next = (next_reg->next)->next;
  1044. curr_reg->end = (next_reg->next)->end;
  1045. free(next_reg->next);
  1046. free(next_reg);
  1047. }
  1048. }
  1049. /* Add-in pseudo-extremes. */
  1050. {
  1051. region_list *tmp, *prev_reg;
  1052. tmp = regions;
  1053. regions = nil;
  1054. prev_reg = nil;
  1055. for (curr_reg = tmp; curr_reg; curr_reg = curr_reg->next) {
  1056. if (curr_reg->type == RGN_PLAIN) {
  1057. int arclen = lialg_compute_pathlen_subset(pts,
  1058. curr_reg->start,
  1059. curr_reg->end);
  1060. int dx = pts->pts[curr_reg->end].x -
  1061. pts->pts[curr_reg->start].x;
  1062. int dy = pts->pts[curr_reg->end].y -
  1063. pts->pts[curr_reg->start].y;
  1064. int chordlen = isqrt(10000 * (dx * dx + dy * dy));
  1065. int atcr = (chordlen == 0) ? 0 : (100 * arclen + chordlen / 2) / chordlen;
  1066. if (lidebug)
  1067. fprint(2, "%d, %d, %d\n", arclen, chordlen, atcr);
  1068. /* Split region if necessary. */
  1069. if (arclen >= PE_AL_THLD && atcr >= PE_ATCR_THLD) {
  1070. int mid = curr_reg->start + (curr_reg->end - curr_reg->start) / 2;
  1071. int end = curr_reg->end;
  1072. region_list *saved_next = curr_reg->next;
  1073. curr_reg->end = mid - 1;
  1074. if (prev_reg == nil)
  1075. regions = curr_reg;
  1076. else
  1077. prev_reg->next = curr_reg;
  1078. prev_reg = curr_reg;
  1079. /* curr_reg = (region_list *)safe_malloc(sizeof(region_list));*/
  1080. curr_reg = malloc(sizeof(region_list));
  1081. curr_reg->start = mid;
  1082. curr_reg->end = mid;
  1083. curr_reg->type = RGN_PSEUDO;
  1084. curr_reg->next = nil;
  1085. prev_reg->next = curr_reg;
  1086. prev_reg = curr_reg;
  1087. /* curr_reg = (region_list *)malloc(sizeof(region_list)); */
  1088. curr_reg = malloc(sizeof(region_list));
  1089. curr_reg->start = mid + 1;
  1090. curr_reg->end = end;
  1091. curr_reg->type = RGN_PLAIN;
  1092. curr_reg->next = nil;
  1093. prev_reg->next = curr_reg;
  1094. prev_reg = curr_reg;
  1095. curr_reg->next = saved_next;
  1096. continue;
  1097. }
  1098. }
  1099. if (prev_reg == nil)
  1100. regions = curr_reg;
  1101. else
  1102. prev_reg->next = curr_reg;
  1103. prev_reg = curr_reg;
  1104. }
  1105. }
  1106. }
  1107. free(junk);
  1108. return(regions);
  1109. }
  1110. static point_list *lialg_compute_dompts(point_list *pts, region_list *regions) {
  1111. point_list *dpts;
  1112. int ndpts;
  1113. int *cas;
  1114. int nonplain;
  1115. region_list *r;
  1116. region_list *curr;
  1117. int dp;
  1118. int previx;
  1119. int currix;
  1120. /* Compute contour angle set. */
  1121. cas = lialg_compute_contour_angle_set(pts, regions);
  1122. /* Dominant points include: start_pt, end_pt, extrema_of_non_plain_regions, midpts of the preceding. */
  1123. nonplain = 0;
  1124. for (r = regions; r != nil; r = r->next)
  1125. if (r->type != RGN_PLAIN)
  1126. nonplain++;
  1127. ndpts = 2 * (2 + nonplain) - 1;
  1128. /* dpts = (point_list *)safe_malloc(sizeof(point_list)); */
  1129. dpts = malloc(sizeof(point_list));
  1130. dpts->pts = mallocz(ndpts*sizeof(pen_point), 1);
  1131. if (dpts->pts == nil) {
  1132. free(dpts);
  1133. return(nil);
  1134. }
  1135. dpts->npts = ndpts;
  1136. dpts->next = nil;
  1137. /* Pick out dominant points. */
  1138. /* Record start point. */
  1139. dp = 0;
  1140. previx = 0;
  1141. dpts->pts[dp++] = pts->pts[previx];
  1142. for (curr = regions; curr != nil; curr = curr->next)
  1143. if (curr->type != RGN_PLAIN) {
  1144. int max_v = 0;
  1145. int min_v = 0x7fffffff; /* maxint */
  1146. int max_ix = -1;
  1147. int min_ix = -1;
  1148. int i;
  1149. for (i = curr->start; i <= curr->end; i++) {
  1150. int v = cas[i];
  1151. if (v > max_v) { max_v = v; max_ix = i; }
  1152. if (v < min_v) { min_v = v; min_ix = i; }
  1153. if (lidebug > 1)
  1154. fprint(2, " %d\n", v);
  1155. }
  1156. currix = (curr->type == RGN_CONVEX ? max_ix : min_ix);
  1157. /* Record midpoint. */
  1158. dpts->pts[dp++] = pts->pts[previx + (currix - previx) / 2];
  1159. /* Record extreme point. */
  1160. dpts->pts[dp++] = pts->pts[currix];
  1161. previx = currix;
  1162. }
  1163. /* Record last mid-point and end point. */
  1164. currix = pts->npts - 1;
  1165. dpts->pts[dp++] = pts->pts[previx + (currix - previx) / 2];
  1166. dpts->pts[dp] = pts->pts[currix];
  1167. /* Compute chain-code. */
  1168. lialg_compute_chain_code(dpts);
  1169. free(cas);
  1170. return(dpts);
  1171. }
  1172. static int *lialg_compute_contour_angle_set(point_list *pts,
  1173. region_list *regions) {
  1174. int *V;
  1175. region_list *curr_reg;
  1176. int i;
  1177. V = malloc(pts->npts*sizeof(int));
  1178. V[0] = 18000;
  1179. for (curr_reg = regions; curr_reg != nil; curr_reg = curr_reg->next) {
  1180. for (i = curr_reg->start; i <= curr_reg->end; i++) {
  1181. if (curr_reg->type == RGN_PLAIN) {
  1182. V[i] = 18000;
  1183. } else {
  1184. /* For now, simply choose the mid-point. */
  1185. int isMidPt = i == (curr_reg->start +
  1186. (curr_reg->end - curr_reg->start) / 2);
  1187. V[i] = (curr_reg->type == RGN_CONVEX)
  1188. ? (isMidPt ? 18000 : 0)
  1189. : (isMidPt ? 0 : 18000);
  1190. }
  1191. }
  1192. }
  1193. V[pts->npts - 1] = 18000;
  1194. return(V);
  1195. }
  1196. /*
  1197. * First compute the similarity between the two strings.
  1198. * If it's above a threshold, compute the distance between
  1199. * the two and return it as the ``score.''
  1200. * Otherwise, return the constant WORST_SCORE.
  1201. *
  1202. */
  1203. static void lialg_score_stroke(point_list *input_dompts, point_list *curr_dompts, int *sim, int *dist) {
  1204. *sim = MIN_SIM;
  1205. *dist = MAX_DIST;
  1206. *sim = lialg_compute_similarity(input_dompts, curr_dompts);
  1207. if (*sim < SIM_THLD) goto done;
  1208. *dist = lialg_compute_distance(input_dompts, curr_dompts);
  1209. done:
  1210. if (lidebug)
  1211. fprint(2, "%d, %d\n", *sim, *dist);
  1212. }
  1213. static int lialg_compute_similarity(point_list *input_dompts, point_list *curr_dompts) {
  1214. int sim;
  1215. point_list *A, *B;
  1216. int N, M;
  1217. int **G;
  1218. int *junk;
  1219. int i, j;
  1220. /* A is the longer sequence, length N. */
  1221. /* B is the shorter sequence, length M. */
  1222. if (input_dompts->npts >= curr_dompts->npts) {
  1223. A = input_dompts;
  1224. N = input_dompts->npts;
  1225. B = curr_dompts;
  1226. M = curr_dompts->npts;
  1227. } else {
  1228. A = curr_dompts;
  1229. N = curr_dompts->npts;
  1230. B = input_dompts;
  1231. M = input_dompts->npts;
  1232. }
  1233. /* Allocate and initialize the Gain matrix, G. */
  1234. /* The size of G is M x (N + 1). */
  1235. /* Note that row 0 is unused. */
  1236. /* Similarities are x 10. */
  1237. G = malloc(M*sizeof(int *));
  1238. junk = malloc(M * (N + 1) * sizeof(int));
  1239. for (i = 0; i < M; i++)
  1240. G[i] = junk + (i * (N + 1));
  1241. for (i = 1; i < M; i++) {
  1242. int bval = B->pts[i-1].chaincode;
  1243. /* Source column. */
  1244. G[i][0] = 0;
  1245. for (j = 1; j < N; j++) {
  1246. int aval = A->pts[j-1].chaincode;
  1247. int diff = abs(bval - aval);
  1248. if (diff > 4) diff = 8 - diff;
  1249. G[i][j] = (diff == 0)
  1250. ? 10
  1251. : (diff == 1)
  1252. ? 6
  1253. : 0;
  1254. }
  1255. /* Sink column. */
  1256. G[i][N] = 0;
  1257. }
  1258. /* Do the DP algorithm. */
  1259. /* Proceed in column order, from highest column to the lowest. */
  1260. /* Within each column, proceed from the highest row to the lowest. */
  1261. /* Skip the highest column. */
  1262. for (j = N - 1; j >= 0; j--)
  1263. for (i = M - 1; i > 0; i--) {
  1264. int max = G[i][j + 1];
  1265. if (i < (M - 1)) {
  1266. int tmp = G[i + 1][j + 1];
  1267. if (tmp > max) max = tmp;
  1268. }
  1269. G[i][j] += max;
  1270. }
  1271. sim = (10 * G[1][0] + (N - 1) / 2) / (N - 1);
  1272. if (G != nil)
  1273. free(G);
  1274. if (junk != nil)
  1275. free(junk);
  1276. return(sim);
  1277. }
  1278. static int lialg_compute_distance(point_list *input_dompts,
  1279. point_list *curr_dompts) {
  1280. int dist;
  1281. point_list *A, *B;
  1282. int N, M;
  1283. int **C;
  1284. int *junk;
  1285. int *BE;
  1286. int *TE;
  1287. int i, j;
  1288. /* A is the longer sequence, length N. */
  1289. /* B is the shorter sequence, length M. */
  1290. if (input_dompts->npts >= curr_dompts->npts) {
  1291. A = input_dompts;
  1292. N = input_dompts->npts;
  1293. B = curr_dompts;
  1294. M = curr_dompts->npts;
  1295. }
  1296. else {
  1297. A = curr_dompts;
  1298. N = curr_dompts->npts;
  1299. B = input_dompts;
  1300. M = input_dompts->npts;
  1301. }
  1302. /* Construct the helper vectors, BE and TE, which say for each column */
  1303. /* what are the ``bottom'' and ``top'' rows of interest. */
  1304. BE = malloc((N + 1)*sizeof(int));
  1305. TE = malloc((N + 1)*sizeof(int));
  1306. for (j = 1; j <= N; j++) {
  1307. int bot, top;
  1308. bot = j + (M - DP_BAND);
  1309. if (bot > M) bot = M;
  1310. BE[j] = bot;
  1311. top = j - (N - DP_BAND);
  1312. if (top < 1) top = 1;
  1313. TE[j] = top;
  1314. }
  1315. /* Allocate and initialize the Cost matrix, C. */
  1316. /* The size of C is (M + 1) x (N + 1). */
  1317. /* Note that row and column 0 are unused. */
  1318. /* Costs are x 100. */
  1319. /* C = (int **)safe_malloc((M + 1) * sizeof(int *)); */
  1320. C = malloc((M + 1)*sizeof( int *));
  1321. junk = malloc((M + 1) * (N + 1)*sizeof(int));
  1322. for (i = 0; i <= M; i++)
  1323. C[i] = junk + (i * (N + 1));
  1324. for (i = 1; i <= M; i++) {
  1325. int bx = B->pts[i-1].x;
  1326. int by = B->pts[i-1].y;
  1327. for (j = 1; j <= N; j++) {
  1328. int ax = A->pts[j-1].x;
  1329. int ay = A->pts[j-1].y;
  1330. int dx = bx - ax;
  1331. int dy = by - ay;
  1332. int dist = isqrt(10000 * (dx * dx + dy * dy));
  1333. C[i][j] = dist;
  1334. }
  1335. }
  1336. /* Do the DP algorithm. */
  1337. /* Proceed in column order, from highest column to the lowest. */
  1338. /* Within each column, proceed from the highest row to the lowest. */
  1339. for (j = N; j > 0; j--)
  1340. for (i = M; i > 0; i--) {
  1341. int min = MAX_DIST;
  1342. if (i > BE[j] || i < TE[j] || (j == N && i == M))
  1343. continue;
  1344. if (j < N) {
  1345. if (i >= TE[j+1]) {
  1346. int tmp = C[i][j+1];
  1347. if (tmp < min)
  1348. min = tmp;
  1349. }
  1350. if (i < M) {
  1351. int tmp = C[i+1][j+1];
  1352. if (tmp < min)
  1353. min = tmp;
  1354. }
  1355. }
  1356. if (i < BE[j]) {
  1357. int tmp = C[i+1][j];
  1358. if (tmp < min) min = tmp;
  1359. }
  1360. C[i][j] += min;
  1361. }
  1362. dist = (C[1][1] + N / 2) / N;
  1363. if (C != nil) free(C);
  1364. if (junk != nil) free(junk);
  1365. if (BE != nil) free(BE);
  1366. if (TE != nil) free(TE);
  1367. return(dist);
  1368. }
  1369. /*************************************************************
  1370. Digest-processing routines
  1371. *************************************************************/
  1372. static int lialg_read_classifier_digest(rClassifier *rec) {
  1373. int nclasses;
  1374. FILE *fp;
  1375. /* Try to open the corresponding digest file. */
  1376. {
  1377. char *clx_path;
  1378. char *dot;
  1379. /* Get a copy of the filename, with some room on the end. */
  1380. /* clx_path = safe_malloc(strlen(rec->file_name) + 5); */
  1381. clx_path = malloc((strlen(rec->file_name) + 5) *sizeof(char));
  1382. strcpy(clx_path, rec->file_name);
  1383. /* Truncate the path after the last dot. */
  1384. dot = strrchr(clx_path, '.');
  1385. if (dot == nil) { free(clx_path); return(-1); }
  1386. *(dot + 1) = 0;
  1387. /* Append the classifier-digest extension. */
  1388. strcat(clx_path, "clx");
  1389. fp = fopen(clx_path, "r");
  1390. if (fp == nil) {
  1391. free(clx_path);
  1392. return(-1);
  1393. }
  1394. free(clx_path);
  1395. }
  1396. /* Read-in the name and dominant points for each class. */
  1397. for (nclasses = 0; !feof(fp); nclasses++) {
  1398. point_list *dpts = nil;
  1399. char class[BUFSIZ];
  1400. int npts;
  1401. int j;
  1402. if (fscanf(fp, "%s %d", class, &npts) != 2) {
  1403. if (feof(fp)) break;
  1404. goto failed;
  1405. }
  1406. rec->cnames[nclasses] = strdup(class);
  1407. /* Allocate a dominant-points list. */
  1408. /* dpts = (point_list *)safe_malloc(sizeof(point_list)); */
  1409. dpts = malloc(sizeof(point_list));
  1410. dpts->pts = mallocz(npts*sizeof(pen_point), 1);
  1411. if (dpts->pts == nil) goto failed;
  1412. dpts->npts = npts;
  1413. dpts->next = nil;
  1414. /* Read in each point. */
  1415. for (j = 0; j < npts; j++) {
  1416. int x, y;
  1417. if (fscanf(fp, "%d %d", &x, &y) != 2) goto failed;
  1418. dpts->pts[j].x = x;
  1419. dpts->pts[j].y = y;
  1420. }
  1421. /* Compute the chain-code. */
  1422. lialg_compute_chain_code(dpts);
  1423. /* Store the list in the rec data structure. */
  1424. rec->dompts[nclasses] = dpts;
  1425. continue;
  1426. failed:
  1427. fprint(2, "read_classifier_digest failed...\n");
  1428. for (; nclasses >= 0; nclasses--) {
  1429. if (rec->cnames[nclasses] != nil) {
  1430. free(rec->cnames[nclasses]);
  1431. rec->cnames[nclasses] = nil;
  1432. }
  1433. if (rec->dompts[nclasses] != nil) {
  1434. delete_examples(rec->dompts[nclasses]);
  1435. rec->dompts[nclasses] = nil;
  1436. }
  1437. }
  1438. if (dpts != nil)
  1439. delete_examples(dpts);
  1440. fclose(fp);
  1441. return(-1);
  1442. }
  1443. fclose(fp);
  1444. return(0);
  1445. }
  1446. /*************************************************************
  1447. Canonicalization routines
  1448. *************************************************************/
  1449. static int lialg_canonicalize_examples(rClassifier *rec) {
  1450. int i;
  1451. int nclasses;
  1452. if (lidebug) {
  1453. fprint(2, "lialg_canonicalize_examples working on %s\n",
  1454. rec->file_name);
  1455. }
  1456. /* Initialize canonical-example arrays. */
  1457. for (i = 0; i < MAXSCLASSES; i++) {
  1458. rec->canonex[i] = nil;
  1459. }
  1460. /* Figure out number of classes. */
  1461. for (nclasses = 0;
  1462. nclasses < MAXSCLASSES && rec->cnames[nclasses] != nil;
  1463. nclasses++)
  1464. ;
  1465. /* Canonicalize the examples for each class. */
  1466. for (i = 0; i < nclasses; i++) {
  1467. int j, k;
  1468. int nex;
  1469. point_list *pts, *tmp, *avg;
  1470. int maxxrange, maxyrange;
  1471. int minx, miny, maxx, maxy;
  1472. int avgxrange, avgyrange, avgxoff, avgyoff, avgscale;
  1473. if (lidebug) {
  1474. fprint(2, "lialg_canonicalize_examples working on class %s\n",
  1475. rec->cnames[i]);
  1476. }
  1477. /* Make a copy of the examples. */
  1478. pts = nil;
  1479. tmp = rec->ex[i];
  1480. for (nex = 0; tmp != nil; nex++, tmp = tmp->next) {
  1481. if ((pts = add_example(pts, tmp->npts, tmp->pts)) == nil) {
  1482. delete_examples(pts);
  1483. return(-1);
  1484. }
  1485. }
  1486. /* Canonicalize each example, and derive the max x and y ranges. */
  1487. maxxrange = 0;
  1488. maxyrange = 0;
  1489. for (j = 0, tmp = pts; j < nex; j++, tmp = tmp->next) {
  1490. if (lialg_canonicalize_example_stroke(tmp) != 0) {
  1491. if (lidebug) {
  1492. fprint(2, "lialg_canonicalize_example_stroke returned error\n");
  1493. }
  1494. return(-1);
  1495. }
  1496. if (tmp->xrange > maxxrange) maxxrange = tmp->xrange;
  1497. if (tmp->yrange > maxyrange) maxyrange = tmp->yrange;
  1498. }
  1499. /* Normalize max ranges. */
  1500. if (((100 * maxxrange + CANONICAL_X / 2) / CANONICAL_X) >
  1501. ((100 * maxyrange + CANONICAL_Y / 2) / CANONICAL_Y)) {
  1502. maxyrange = (maxyrange * CANONICAL_X + maxxrange / 2) / maxxrange;
  1503. maxxrange = CANONICAL_X;
  1504. }
  1505. else {
  1506. maxxrange = (maxxrange * CANONICAL_Y + maxyrange / 2) / maxyrange;
  1507. maxyrange = CANONICAL_Y;
  1508. }
  1509. /* Re-scale each example to max ranges. */
  1510. for (j = 0, tmp = pts; j < nex; j++, tmp = tmp->next) {
  1511. int scalex = (tmp->xrange == 0) ? 100 : (100 * maxxrange + tmp->xrange / 2) / tmp->xrange;
  1512. int scaley = (tmp->yrange == 0) ? 100 : (100 * maxyrange + tmp->yrange / 2) / tmp->yrange;
  1513. if (lialg_translate_points(tmp, 0, 0, scalex, scaley) != 0) {
  1514. delete_examples(pts);
  1515. return(-1);
  1516. }
  1517. }
  1518. /* Average the examples; leave average in first example. */
  1519. avg = pts; /* careful aliasing!! */
  1520. for (k = 0; k < NCANONICAL; k++) {
  1521. int xsum = 0;
  1522. int ysum = 0;
  1523. for (j = 0, tmp = pts; j < nex; j++, tmp = tmp->next) {
  1524. xsum += tmp->pts[k].x;
  1525. ysum += tmp->pts[k].y;
  1526. }
  1527. avg->pts[k].x = (xsum + j / 2) / j;
  1528. avg->pts[k].y = (ysum + j / 2) / j;
  1529. }
  1530. /* Compute BB of averaged stroke and re-scale. */
  1531. lialg_get_bounding_box(avg, &minx, &miny, &maxx, &maxy);
  1532. avgxrange = maxx - minx;
  1533. avgyrange = maxy - miny;
  1534. avgscale = (((100 * avgxrange + CANONICAL_X / 2) / CANONICAL_X) >
  1535. ((100 * avgyrange + CANONICAL_Y / 2) / CANONICAL_Y))
  1536. ? (100 * CANONICAL_X + avgxrange / 2) / avgxrange
  1537. : (100 * CANONICAL_Y + avgyrange / 2) / avgyrange;
  1538. if (lialg_translate_points(avg, minx, miny, avgscale, avgscale) != 0) {
  1539. delete_examples(pts);
  1540. return(-1);
  1541. }
  1542. /* Re-compute the x and y ranges and center the stroke. */
  1543. lialg_get_bounding_box(avg, &minx, &miny, &maxx, &maxy);
  1544. avgxrange = maxx - minx;
  1545. avgyrange = maxy - miny;
  1546. avgxoff = -((CANONICAL_X - avgxrange + 1) / 2);
  1547. avgyoff = -((CANONICAL_Y - avgyrange + 1) / 2);
  1548. if (lialg_translate_points(avg, avgxoff, avgyoff, 100, 100) != 0) {
  1549. delete_examples(pts);
  1550. return(-1);
  1551. }
  1552. /* Create a point list to serve as the ``canonical representation. */
  1553. if ((rec->canonex[i] = add_example(nil, avg->npts, avg->pts)) == nil) {
  1554. delete_examples(pts);
  1555. return(-1);
  1556. }
  1557. (rec->canonex[i])->xrange = maxx - minx;
  1558. (rec->canonex[i])->yrange = maxy - miny;
  1559. if (lidebug) {
  1560. fprint(2, "%s, avgpts = %d\n", rec->cnames[i], avg->npts);
  1561. for (j = 0; j < avg->npts; j++) {
  1562. fprint(2, " (%P)\n", avg->pts[j].Point);
  1563. }
  1564. }
  1565. /* Compute dominant points of canonical representation. */
  1566. rec->dompts[i] = lialg_compute_dominant_points(avg);
  1567. /* Clean up. */
  1568. delete_examples(pts);
  1569. }
  1570. /* Sanity check. */
  1571. for (i = 0; i < nclasses; i++) {
  1572. char *best_name = lialg_recognize_stroke(rec, rec->canonex[i]);
  1573. if (best_name != rec->cnames[i])
  1574. fprint(2, "%s, best = %s\n", rec->cnames[i], best_name);
  1575. }
  1576. return(0);
  1577. }
  1578. static int lialg_canonicalize_example_stroke(point_list *points) {
  1579. int minx, miny, maxx, maxy, xrange, yrange, scale;
  1580. /* Filter out points that are too close. */
  1581. if (lialg_filter_points(points) != 0) return(-1);
  1582. /* Must be at least two points! */
  1583. if (points->npts < 2) {
  1584. if (lidebug) {
  1585. fprint(2, "lialg_canonicalize_example_stroke: npts=%d\n",
  1586. points->npts);
  1587. }
  1588. return(-1);
  1589. }
  1590. /* Scale up to avoid conversion errors. */
  1591. lialg_get_bounding_box(points, &minx, &miny, &maxx, &maxy);
  1592. xrange = maxx - minx;
  1593. yrange = maxy - miny;
  1594. scale = (((100 * xrange + CANONICAL_X / 2) / CANONICAL_X) >
  1595. ((100 * yrange + CANONICAL_Y / 2) / CANONICAL_Y))
  1596. ? (100 * CANONICAL_X + xrange / 2) / xrange
  1597. : (100 * CANONICAL_Y + yrange / 2) / yrange;
  1598. if (lialg_translate_points(points, minx, miny, scale, scale) != 0) {
  1599. if (lidebug) {
  1600. fprint(2, "lialg_translate_points (minx=%d,miny=%d,scale=%d) returned error\n", minx, miny, scale);
  1601. }
  1602. return(-1);
  1603. }
  1604. /* Compute an equivalent stroke with equi-distant points. */
  1605. if (lialg_compute_equipoints(points) != 0) return(-1);
  1606. /* Re-translate the points to the origin. */
  1607. lialg_get_bounding_box(points, &minx, &miny, &maxx, &maxy);
  1608. if (lialg_translate_points(points, minx, miny, 100, 100) != 0) {
  1609. if (lidebug) {
  1610. fprint(2, "lialg_translate_points (minx=%d,miny=%d) returned error\n", minx, miny);
  1611. }
  1612. return(-1);
  1613. }
  1614. /* Store the x and y ranges in the point list. */
  1615. xrange = maxx - minx;
  1616. yrange = maxy - miny;
  1617. points->xrange = xrange;
  1618. points->yrange = yrange;
  1619. if (lidebug) {
  1620. int i;
  1621. fprint(2, "Canonicalized: %d, %d, %d, %d\n", minx, miny, maxx, maxy);
  1622. for (i = 0; i < points->npts; i++)
  1623. fprint(2, " (%P)\n", points->pts[i].Point);
  1624. fflush(stderr);
  1625. }
  1626. return(0);
  1627. }
  1628. static int lialg_compute_equipoints(point_list *points) {
  1629. pen_point *equipoints = mallocz(NCANONICAL*sizeof(pen_point), 1);
  1630. int nequipoints = 0;
  1631. int pathlen = lialg_compute_pathlen(points);
  1632. int equidist = (pathlen + (NCANONICAL - 1) / 2) / (NCANONICAL - 1);
  1633. int i;
  1634. int dist_since_last_eqpt;
  1635. int remaining_seglen;
  1636. int dist_to_next_eqpt;
  1637. if (equipoints == nil) {
  1638. fprint(2, "can't allocate memory in lialg_compute_equipoints");
  1639. return(-1);
  1640. }
  1641. if (lidebug) {
  1642. fprint(2, "compute_equipoints: npts = %d, pathlen = %d, equidist = %d\n",
  1643. points->npts, pathlen, equidist);
  1644. fflush(stderr);
  1645. }
  1646. /* First original point is an equipoint. */
  1647. equipoints[0] = points->pts[0];
  1648. nequipoints++;
  1649. dist_since_last_eqpt = 0;
  1650. for (i = 1; i < points->npts; i++) {
  1651. int dx1 = points->pts[i].x - points->pts[i-1].x;
  1652. int dy1 = points->pts[i].y - points->pts[i-1].y;
  1653. int endx = 100 * points->pts[i-1].x;
  1654. int endy = 100 * points->pts[i-1].y;
  1655. remaining_seglen = isqrt(10000 * (dx1 * dx1 + dy1 * dy1));
  1656. dist_to_next_eqpt = equidist - dist_since_last_eqpt;
  1657. while (remaining_seglen >= dist_to_next_eqpt) {
  1658. if (dx1 == 0) {
  1659. /* x-coordinate stays the same */
  1660. if (dy1 >= 0)
  1661. endy += dist_to_next_eqpt;
  1662. else
  1663. endy -= dist_to_next_eqpt;
  1664. }
  1665. else {
  1666. int slope = (100 * dy1 + dx1 / 2) / dx1;
  1667. int tmp = isqrt(10000 + slope * slope);
  1668. int dx = (100 * dist_to_next_eqpt + tmp / 2) / tmp;
  1669. int dy = (slope * dx + 50) / 100;
  1670. if (dy < 0) dy = -dy;
  1671. if (dx1 >= 0)
  1672. endx += dx;
  1673. else
  1674. endx -= dx;
  1675. if (dy1 >= 0)
  1676. endy += dy;
  1677. else
  1678. endy -= dy;
  1679. }
  1680. equipoints[nequipoints].x = (endx + 50) / 100;
  1681. equipoints[nequipoints].y = (endy + 50) / 100;
  1682. nequipoints++;
  1683. /* assert(nequipoints <= NCANONICAL);*/
  1684. dist_since_last_eqpt = 0;
  1685. remaining_seglen -= dist_to_next_eqpt;
  1686. dist_to_next_eqpt = equidist;
  1687. }
  1688. dist_since_last_eqpt += remaining_seglen;
  1689. }
  1690. /* Take care of last equipoint. */
  1691. if (nequipoints == NCANONICAL) {
  1692. /* Good. */
  1693. } else if (nequipoints == (NCANONICAL - 1)) {
  1694. /* Make last original point the last equipoint. */
  1695. equipoints[nequipoints] = points->pts[points->npts - 1];
  1696. } else {
  1697. if (lidebug) {
  1698. fprint(2,"lialg_compute_equipoints: nequipoints = %d\n",
  1699. nequipoints);
  1700. }
  1701. /* assert(false);*/
  1702. return(-1);
  1703. }
  1704. points->npts = NCANONICAL;
  1705. delete_pen_point_array(points->pts);
  1706. points->pts = equipoints;
  1707. return(0);
  1708. }
  1709. /*************************************************************
  1710. Utility routines
  1711. *************************************************************/
  1712. /* Result is x 100. */
  1713. static int lialg_compute_pathlen(point_list *points) {
  1714. return(lialg_compute_pathlen_subset(points, 0, points->npts - 1));
  1715. }
  1716. /* Result is x 100. */
  1717. static int lialg_compute_pathlen_subset(point_list *points,
  1718. int start, int end) {
  1719. int pathlen;
  1720. int i;
  1721. pathlen = 0;
  1722. for (i = start + 1; i <= end; i++) {
  1723. int dx = points->pts[i].x - points->pts[i-1].x;
  1724. int dy = points->pts[i].y - points->pts[i-1].y;
  1725. int dist = isqrt(10000 * (dx * dx + dy * dy));
  1726. pathlen += dist;
  1727. }
  1728. return(pathlen);
  1729. }
  1730. /* Note that this does NOT update points->xrange and points->yrange! */
  1731. static int lialg_filter_points(point_list *points) {
  1732. int filtered_npts;
  1733. pen_point *filtered_pts = mallocz(points->npts*sizeof(pen_point), 1);
  1734. int i;
  1735. if (filtered_pts == nil) {
  1736. fprint(2, "can't allocate memory in lialg_filter_points");
  1737. return(-1);
  1738. }
  1739. filtered_pts[0] = points->pts[0];
  1740. filtered_npts = 1;
  1741. for (i = 1; i < points->npts; i++) {
  1742. int j = filtered_npts - 1;
  1743. int dx = points->pts[i].x - filtered_pts[j].x;
  1744. int dy = points->pts[i].y - filtered_pts[j].y;
  1745. int magsq = dx * dx + dy * dy;
  1746. if (magsq >= DIST_SQ_THRESHOLD) {
  1747. filtered_pts[filtered_npts] = points->pts[i];
  1748. filtered_npts++;
  1749. }
  1750. }
  1751. points->npts = filtered_npts;
  1752. delete_pen_point_array(points->pts);
  1753. points->pts = filtered_pts;
  1754. return(0);
  1755. }
  1756. /* scalex and scaley are x 100. */
  1757. /* Note that this does NOT update points->xrange and points->yrange! */
  1758. static int lialg_translate_points(point_list *points,
  1759. int minx, int miny,
  1760. int scalex, int scaley) {
  1761. int i;
  1762. for (i = 0; i < points->npts; i++) {
  1763. points->pts[i].x = ((points->pts[i].x - minx) * scalex + 50) / 100;
  1764. points->pts[i].y = ((points->pts[i].y - miny) * scaley + 50) / 100;
  1765. }
  1766. return(0);
  1767. }
  1768. static void lialg_get_bounding_box(point_list *points,
  1769. int *pminx, int *pminy,
  1770. int *pmaxx, int *pmaxy) {
  1771. int minx, miny, maxx, maxy;
  1772. int i;
  1773. minx = maxx = points->pts[0].x;
  1774. miny = maxy = points->pts[0].y;
  1775. for (i = 1; i < points->npts; i++) {
  1776. pen_point *pt = &(points->pts[i]);
  1777. if (pt->x < minx) minx = pt->x;
  1778. else if (pt->x > maxx) maxx = pt->x;
  1779. if (pt->y < miny) miny = pt->y;
  1780. else if (pt->y > maxy) maxy = pt->y;
  1781. }
  1782. *pminx = minx;
  1783. *pminy = miny;
  1784. *pmaxx = maxx;
  1785. *pmaxy = maxy;
  1786. }
  1787. int wtvals[] = {100, 104, 117, 143, 189, 271, 422};
  1788. static void lialg_compute_lpf_parameters(void) {
  1789. int i;
  1790. for (i = LP_FILTER_WIDTH; i >= 0; i--) {
  1791. // double x = 0.04 * (i * i);
  1792. // double tmp = 100.0 * exp(x);
  1793. // int wt = floor((double)tmp);
  1794. int wt = wtvals[i];
  1795. lialg_lpfwts[LP_FILTER_WIDTH - i] = wt;
  1796. lialg_lpfwts[LP_FILTER_WIDTH + i] = wt;
  1797. }
  1798. lialg_lpfconst = 0;
  1799. for (i = 0; i < (2 * LP_FILTER_WIDTH + 1); i++) {
  1800. lialg_lpfconst += lialg_lpfwts[i];
  1801. }
  1802. }
  1803. /* Code from Joseph Hall (jnhall@sat.mot.com). */
  1804. static int isqrt(int n) {
  1805. register int i;
  1806. register int32_t k0, k1, nn;
  1807. for (nn = i = n, k0 = 2; i > 0; i >>= 2, k0 <<= 1)
  1808. ;
  1809. nn <<= 2;
  1810. for (;;) {
  1811. k1 = (nn / k0 + k0) >> 1;
  1812. if (((k0 ^ k1) & ~1) == 0)
  1813. break;
  1814. k0 = k1;
  1815. }
  1816. return (int) ((k1 + 1) >> 1);
  1817. }
  1818. /* Helper routines from Mark Hayter. */
  1819. static int likeatan(int tantop, int tanbot) {
  1820. int t;
  1821. /* Use tan(theta)=top/bot --> order for t */
  1822. /* t in range 0..0x40000 */
  1823. if ((tantop == 0) && (tanbot == 0))
  1824. t = 0;
  1825. else
  1826. {
  1827. t = (tantop << 16) / (abs(tantop) + abs(tanbot));
  1828. if (tanbot < 0)
  1829. t = 0x20000 - t;
  1830. else
  1831. if (tantop < 0) t = 0x40000 + t;
  1832. }
  1833. return t;
  1834. }
  1835. static int quadr(int t) {
  1836. return (8 - (((t + 0x4000) >> 15) & 7)) & 7;
  1837. }