li_recognizer.c 56 KB

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