Debian Codegraph @

cuneiform_src/Kern/lns32/src/extrlns.cpp

raw
1 /*
2 Copyright (c) 1993-2008, Cognitive Technologies
3 All rights reserved.
4
5 Разрешается повторное распространение и использование как в виде исходного кода,
6 так и в двоичной форме, с изменениями или без, при соблюдении следующих условий:
7
8 * При повторном распространении исходного кода должны оставаться указанное
9 выше уведомление об авторском праве, этот список условий и последующий
10 отказ от гарантий.
11 * При повторном распространении двоичного кода в документации и/или в
12 других материалах, поставляемых при распространении, должны сохраняться
13 указанная выше информация об авторском праве, этот список условий и
14 последующий отказ от гарантий.
15 * Ни название Cognitive Technologies, ни имена ее сотрудников не могут
16 быть использованы в качестве средства поддержки и/или продвижения
17 продуктов, основанных на этом ПО, без предварительного письменного
18 разрешения.
19
20 ЭТА ПРОГРАММА ПРЕДОСТАВЛЕНА ВЛАДЕЛЬЦАМИ АВТОРСКИХ ПРАВ И/ИЛИ ДРУГИМИ ЛИЦАМИ "КАК
21 ОНА ЕСТЬ" БЕЗ КАКОГО-ЛИБО ВИДА ГАРАНТИЙ, ВЫРАЖЕННЫХ ЯВНО ИЛИ ПОДРАЗУМЕВАЕМЫХ,
22 ВКЛЮЧАЯ ГАРАНТИИ КОММЕРЧЕСКОЙ ЦЕННОСТИ И ПРИГОДНОСТИ ДЛЯ КОНКРЕТНОЙ ЦЕЛИ, НО НЕ
23 ОГРАНИЧИВАЯСЬ ИМИ. НИ ВЛАДЕЛЕЦ АВТОРСКИХ ПРАВ И НИ ОДНО ДРУГОЕ ЛИЦО, КОТОРОЕ
24 МОЖЕТ ИЗМЕНЯТЬ И/ИЛИ ПОВТОРНО РАСПРОСТРАНЯТЬ ПРОГРАММУ, НИ В КОЕМ СЛУЧАЕ НЕ
25 НЕСЁТ ОТВЕТСТВЕННОСТИ, ВКЛЮЧАЯ ЛЮБЫЕ ОБЩИЕ, СЛУЧАЙНЫЕ, СПЕЦИАЛЬНЫЕ ИЛИ
26 ПОСЛЕДОВАВШИЕ УБЫТКИ, СВЯЗАННЫЕ С ИСПОЛЬЗОВАНИЕМ ИЛИ ПОНЕСЕННЫЕ ВСЛЕДСТВИЕ
27 НЕВОЗМОЖНОСТИ ИСПОЛЬЗОВАНИЯ ПРОГРАММЫ (ВКЛЮЧАЯ ПОТЕРИ ДАННЫХ, ИЛИ ДАННЫЕ,
28 СТАВШИЕ НЕГОДНЫМИ, ИЛИ УБЫТКИ И/ИЛИ ПОТЕРИ ДОХОДОВ, ПОНЕСЕННЫЕ ИЗ-ЗА ДЕЙСТВИЙ
29 ТРЕТЬИХ ЛИЦ И/ИЛИ ОТКАЗА ПРОГРАММЫ РАБОТАТЬ СОВМЕСТНО С ДРУГИМИ ПРОГРАММАМИ,
30 НО НЕ ОГРАНИЧИВАЯСЬ ЭТИМИ СЛУЧАЯМИ), НО НЕ ОГРАНИЧИВАЯСЬ ИМИ, ДАЖЕ ЕСЛИ ТАКОЙ
31 ВЛАДЕЛЕЦ ИЛИ ДРУГОЕ ЛИЦО БЫЛИ ИЗВЕЩЕНЫ О ВОЗМОЖНОСТИ ТАКИХ УБЫТКОВ И ПОТЕРЬ.
32
33 Redistribution and use in source and binary forms, with or without modification,
34 are permitted provided that the following conditions are met:
35
36 * Redistributions of source code must retain the above copyright notice,
37 this list of conditions and the following disclaimer.
38 * Redistributions in binary form must reproduce the above copyright notice,
39 this list of conditions and the following disclaimer in the documentation
40 and/or other materials provided with the distribution.
41 * Neither the name of the Cognitive Technologies nor the names of its
42 contributors may be used to endorse or promote products derived from this
43 software without specific prior written permission.
44
45 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
46 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
47 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
48 DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
49 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
51 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
52 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
53 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
54 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
55 */
56
57 #include <math.h>
58 #include "lnslang.h"
59
60 #ifndef __LNS_H
61 # include "lns.h"
62 #endif
63
64 #ifndef __EXTRLNS_H
65 # include "extrlns.h"
66 #endif
67
68 #ifndef __SBAMBUK_H
69 # include "sbambuk.h"
70 #endif
71 #ifndef __RBAMBUK_H
72 # include "rbambuk.h"
73 #endif
74 #ifndef __LBAMBUK_H
75 # include "lbambuk.h"
76 #endif
77 #ifndef __PARALINE_H
78 # include "paraline.h"
79 #endif
80
81 #ifndef __SWEEPER_H
82 # include "sweeper.h"
83 #endif
84
85 #include "lns_skew1024.h"
86
87 #include "decl.h"
88
89 Bool cdecl ExtrLinesIsOk(void);
90 /* Implementation ************************/
91 static THVSegBambuk * hvSB = NULL;
92 static TRasterBambuk * hRB = NULL;
93 static TLinesBambuk * hLB = NULL;
94 static TRasterBambuk * vRB = NULL;
95 static TLinesBambuk * vLB = NULL;
96 /*****************************************/
97
98 #include "rombabble.h"
99 //*******************Rom********************
100 RomBubble* Rptr = NULL;
101 RomBubble* Rptr2 = NULL;
102 RomBubble* Rptr3 = NULL;
103 CRomBabble* RBlockFirst = NULL;
104 CRomBabble* RBlockCurrent = NULL;
105 CRomBabble* RBlockPrev = NULL;
106 int Romi = 0;
107 //******************************************
108
109
110
111 //#define DELETE_PTR(ptr) if (ptr != NULL) { ::delete ptr; ptr = NULL; };
112 #define DELETE_PTR(ptr) if (ptr != NULL) { delete ptr; ptr = NULL; };
113 static void _destroy_lines(void)
114 {
115 DELETE_PTR( hvSB );
116 DELETE_PTR( hRB );
117 DELETE_PTR( hLB );
118 DELETE_PTR( vRB );
119 DELETE_PTR( vLB );
120 }
121
122 void ExtrLinesInitLNS(void)
123 { _destroy_lines();
124 //*******************Rom********************
125 RBlockCurrent = new CRomBabble;
126 RBlockFirst = RBlockCurrent;
127 RBlockPrev = NULL;
128 Rptr = new RomBubble;
129 Rptr->next = NULL; //*************Rom 17.11.98 16:30
130 Rptr2 = NULL;
131 Rptr3 = Rptr;
132 Romi =0 ;
133 //******************************************
134
135 }
136
137 void ExtrLinesDoneLNS(void)
138 { _destroy_lines();
139 DELETE_PTR( Rptr );
140 Rptr2 = Rptr3 = NULL;
141 Romi = 0;
142 RBlockPrev = RBlockCurrent = RBlockFirst;
143 while ( RBlockCurrent != NULL )
144 {
145 RBlockCurrent = RBlockPrev->next;
146 delete(RBlockPrev);
147 RBlockPrev = RBlockCurrent;
148 }
149 }
150
151 static void _squeezeIfTooMany( int32_t & hor_len, int32_t & ver_len,
152 int32_t & hor_cnt, int32_t & ver_cnt
153 )
154 {
155 int32_t max_cnt = 0xFFF0 / sizeof( LineInfo );
156 while (TRUE)
157 {
158 ExtrLinesGetCount( hor_len, ver_len, hor_cnt, ver_cnt );
159 if (hor_cnt <= max_cnt && ver_cnt <= max_cnt )
160 break;
161 if (hor_cnt > max_cnt)
162 hor_len++;
163 if (ver_cnt > max_cnt)
164 ver_len++;
165 };
166 }
167
168 //******************************* Rom 8-2-99 **************
169 static void FillFragmentsCount( int32_t hnd, Bool hor, int16_t* cnt, uchar* quality)
170 {
171 int16_t Romii;
172 int16_t SpacesLength, TotalLength;
173 TLinesBambuk* lb = hor ? hLB : vLB;
174
175 TLineInfo & li = lb->linesRoot[hnd];
176 BEntry lbe = li.linesBambukEntry;
177 BHandle h = lb->firstEntryMember( lbe );
178 TLineFragment lf;
179 Romii = 0;
180
181 if (hor)
182 TotalLength = abs(li.lineAsIs.start.x-li.lineAsIs.end.x);
183 else
184 TotalLength = abs(li.lineAsIs.start.y-li.lineAsIs.end.y);
185
186
187 SpacesLength = TotalLength;
188 if (TotalLength <=0)
189 return;
190 while ( h !=NULLBHandle )
191 {
192 lf = (*lb)[h];
193 SpacesLength -= hor ?
194 abs(lf.fragmentAsIs.start.x-lf.fragmentAsIs.end.x) :
195 abs(lf.fragmentAsIs.start.y-lf.fragmentAsIs.end.y);
196
197 SpacesLength=abs(SpacesLength);
198 Romii++;
199 h = lb->nextMember(h);
200 }
201 *cnt = Romii;
202 *quality = ((TotalLength-SpacesLength)*255)/TotalLength;
203 }
204
205 //**********************************************************
206 #define LOG_TIME
207 #ifdef LOG_TIME
208 #define CONSOLE(str) OutputDebugString(str)
209 #include "xtimer.h"
210 #endif
211
212 #include "hliner.h"
213
214 Err16 ExtrLinesUnderTigerStatic( int32_t hor_len, int32_t ver_len,
215 int32_t &hor_cnt, int32_t &ver_cnt )
216 {
217 #ifdef LOG_TIME
218 XTimer t("Lines Extraction");
219 #endif
220
221 int err_code = ER_NONE;
222 int i=0;
223
224 TigerReader tg_rdr;
225
226 HLiner_Setup(&tg_rdr);
227
228 if (!tg_rdr.isOk())
229 { assert(0); return tg_rdr.errCode; };
230
231 _destroy_lines();
232 int AddX = tg_rdr.wAddX;
233 int AddY = tg_rdr.wAddY;
234 /* I. build segments bambuk */
235 hvSB = new THVSegBambuk( tg_rdr );
236 if (hvSB == NULL) {
237 err_code = ER_NOMEMORY;
238 goto ErrorExit;
239 };
240 if (!hvSB->isOk())
241 {
242 err_code = hvSB->errCode;
243 goto ErrorExit;
244 };
245
246 /* II. make horisontal lines */
247 /* build H rasters */
248 hRB = new TRasterBambuk( &(hvSB->hBambuk),
249 (BHandle) MAX_H_DASHES_COUNT, // members
250 (BEntry) MAX_H_RASTERS_COUNT // entries
251 );
252 if (hRB == NULL) {
253 err_code = ER_NOMEMORY;
254 goto ErrorExit;
255 };
256 if (!hRB->isOk()) {
257 err_code = ER_NOMEMORY;
258 goto ErrorExit;
259 };
260
261 /* build H lines */
262
263 HLiner_Analyze();
264
265 hLB = new TLinesBambuk( hRB,
266 &(hvSB->hBambuk),
267 (BEntry) MAX_H_LINES_COUNT,
268 FALSE // not vertical
269 );
270 if (hLB == NULL) {
271 err_code = ER_NOMEMORY;
272 goto ErrorExit;
273 };
274
275 if (!hLB->isOk()) {
276 err_code = ER_NOMEMORY;
277 goto ErrorExit;
278 };
279 *((TXYDim*)hLB) = *((TXYDim*)hvSB); // 11-05-93 07:24pm
280
281 /* III. make vertical lines */
282 /* build V rasters */
283 vRB = new TRasterBambuk( &(hvSB->vBambuk),
284 (BHandle) MAX_V_DASHES_COUNT, // members
285 (BEntry) MAX_V_RASTERS_COUNT // entries
286 );
287 if (vRB == NULL) {
288 err_code = ER_NOMEMORY;
289 goto ErrorExit;
290 };
291 if (!vRB->isOk()) {
292 err_code = ER_NOMEMORY;
293 goto ErrorExit;
294 };
295
296 /* build V lines */
297 vLB = new TLinesBambuk( vRB,
298 &(hvSB->vBambuk),
299 (BEntry) MAX_V_LINES_COUNT,
300 TRUE // is vertical
301 );
302 if (vLB == NULL) {
303 err_code = ER_NOMEMORY;
304 goto ErrorExit;
305 };
306 if (!vLB->isOk()) {
307 err_code = ER_NOMEMORY;
308 goto ErrorExit;
309 };
310 *((TXYDim*)vLB) = *((TXYDim*)hvSB); // 11-05-93 07:24pm
311 ////////////////
312 Bool AnalyzeFragments( TLinesBambuk& hLB, TLinesBambuk& vLB);
313 Bool AnalyzeFragmentsII( TLinesBambuk& hLB, TLinesBambuk& vLB);
314
315 if (!AnalyzeFragments( *hLB, *vLB))
316 {
317 err_code = ER_NOMEMORY;
318 goto ErrorExit;
319 }
320
321 if (!AnalyzeFragmentsII( *hLB, *vLB))
322 {
323 err_code = ER_NOMEMORY;
324 goto ErrorExit;
325 }
326
327 if (!hLB->linkHFragments())
328 {
329 err_code = ER_NOMEMORY;
330 goto ErrorExit;
331 }
332
333 if (!vLB->linkVFragments())
334 {
335 err_code = ER_NOMEMORY;
336 goto ErrorExit;
337 }
338 /////////////////
339 /* IV. Make diff... */
340 for ( i = 0; i < hLB->linesCount; i++)
341 {
342 Point32 & p1 = hLB->linesRoot[i].lineAsIs.end;
343 p1.x += AddX; p1.y += AddY;
344 Point32 & p2 = hLB->linesRoot[i].lineAsIs.start;
345 p2.x += AddX; p2.y += AddY;
346 };
347
348 for ( i = 0; i < vLB->linesCount; i++)
349 {
350 Point32 & p1 = vLB->linesRoot[i].lineAsIs.end;
351 p1.x += AddX; p1.y += AddY;
352 Point32 & p2 = vLB->linesRoot[i].lineAsIs.start;
353 p2.x += AddX; p2.y += AddY;
354 };
355 /* IV. Send counts... */
356
357
358 //=========== 10-19-95 06:46pm, Basil ====================
359 _squeezeIfTooMany( hor_len, ver_len, hor_cnt, ver_cnt );
360 //============================================================
361
362
363 return ER_NONE; // Normal exit
364
365 ErrorExit :
366 _destroy_lines();
367
368 return err_code; // Bad exit
369 }
370
371 Bool ExtrLinesGetCount( int32_t hor_len, int32_t ver_len,
372 int32_t &hor_cnt, int32_t &ver_cnt
373 )
374 {
375
376 if (hLB == NULL) return WRONG();
377 if (vLB == NULL) return WRONG();
378 if (!hLB->isOk()) return WRONG();
379 if (!vLB->isOk()) return WRONG();
380
381 hor_cnt = 0;
382 int i(0);
383 for (i = 0; i < hLB->linesCount; i++)
384 { if ( (hLB->linesRoot[i].lineAsIs.end.x -
385 hLB->linesRoot[i].lineAsIs.start.x
386 ) > hor_len
387 ) hor_cnt++;
388 };
389 ver_cnt = 0;
390 for (i = 0; i < vLB->linesCount; i++)
391 { if ( (vLB->linesRoot[i].lineAsIs.end.y -
392 vLB->linesRoot[i].lineAsIs.start.y
393 ) > ver_len
394 ) ver_cnt++;
395 };
396 return TRUE;
397 }
398
399 static void LCpy( Point16& dst, Point32& src )
400 {
401 dst.x=(int16_t)(src.x);
402 dst.y=(int16_t)(src.y);
403 }
404
405
406 Bool ExtrLinesGetInfo( LinesTotalInfo * lti,
407 int32_t hor_len, int32_t ver_len,
408 int32_t &hor_cnt, int32_t &ver_cnt
409 )
410 {
411 int16_t cnt;//******************Rom
412 uchar Quality;//******************Rom
413
414 if (hLB == NULL) return WRONG();
415 if (vLB == NULL) return WRONG();
416 if (!hLB->isOk()) return WRONG();
417 if (!vLB->isOk()) return WRONG();
418
419 int32_t max_cnt = 0xFFF0 / sizeof( LineInfo );
420 _squeezeIfTooMany( hor_len, ver_len, hor_cnt, ver_cnt );
421
422 int i(0);
423 hor_cnt = 0;
424 for (i = 0; i < hLB->linesCount; i++)
425 { if ( (hLB->linesRoot[i].lineAsIs.end.x -
426 hLB->linesRoot[i].lineAsIs.start.x
427 ) > hor_len
428 )
429 {
430 if (hor_cnt >= lti->Hor.Cnt)
431 return WRONG();
432 LineInfo& li = lti->Hor.Lns[hor_cnt];
433 FillFragmentsCount( i, TRUE, &cnt, &Quality);
434 LCpy( li.A, hLB->linesRoot[i].lineAsIs.start );
435 LCpy( li.B, hLB->linesRoot[i].lineAsIs.end );
436 li.Thickness = ( hLB->linesRoot[i].lineAsIs.width10 + 5 ) / 10;
437 //li.A = hLB->linesRoot[i].lineAsIs.start;
438 //li.B = hLB->linesRoot[i].lineAsIs.end;
439 li.ExtrDllHnd = i;
440 li.Extractor = LI_LNSDLL;
441 li.Flags = hLB->linesRoot[i].lineAsIs.flags; //******************Rom
442 li.Anew = li.A;//******Rom
443 li.Bnew = li.B;//******Rom
444 li.SegCnt = cnt; //******** Rom 8-2-99
445 li.Quality = Quality; //******* Rom 23-2-99
446 hor_cnt++;
447 assert( hor_cnt <= max_cnt );
448 };
449 };
450 ver_cnt = 0;
451 for (i = 0; i < vLB->linesCount; i++)
452 { if ( (vLB->linesRoot[i].lineAsIs.end.y -
453 vLB->linesRoot[i].lineAsIs.start.y
454 ) > ver_len
455 )
456 {
457 if (ver_cnt >= lti->Ver.Cnt)
458 return WRONG();
459 LineInfo& li = lti->Ver.Lns[ver_cnt];
460 FillFragmentsCount( i, FALSE, &cnt, &Quality);
461 LCpy( li.A, vLB->linesRoot[i].lineAsIs.start );
462 LCpy( li.B, vLB->linesRoot[i].lineAsIs.end );
463 li.Thickness = ( vLB->linesRoot[i].lineAsIs.width10 + 5 ) / 10;
464 //li.A = vLB->linesRoot[i].lineAsIs.start;
465 //li.B = vLB->linesRoot[i].lineAsIs.end;
466 li.ExtrDllHnd = i;
467 li.Extractor = LI_LNSDLL;
468 li.Flags = vLB->linesRoot[i].lineAsIs.flags; //******************Rom
469 li.Anew = li.A;//******Rom
470 li.Bnew = li.B;//******Rom
471 li.SegCnt = cnt; //******** Rom 8-2-99
472 li.Quality = Quality; //******* Rom 23-2-99
473 ver_cnt++;
474 assert( ver_cnt <= max_cnt );
475 };
476 };
477
478 lti->ImgResolution.y = hvSB->yres;
479 lti->ImgResolution.x = hvSB->xres;
480
481 lti->ImgSize.y = hvSB->height();
482 lti->ImgSize.x = hvSB->width();
483
484 if (hLB->averagePhi != 1. && vLB->averagePhi != 1.)
485 lti->Skew1024 = (int)(512 * (hLB->averagePhi + vLB->averagePhi));
486 else
487 {
488 lti->Skew1024=0;
489 if (hLB->averagePhi != 1.)
490 lti->Skew1024 = (int)(1024 * hLB->averagePhi);
491 else if (vLB->averagePhi != 1.)
492 lti->Skew1024 = (int)(1024 * vLB->averagePhi);
493 }
494
495 int skew = lti->Skew1024;
496 for (i = 0; i < hor_cnt; i++)
497 {
498 LineInfo& li = lti->Hor.Lns[i];
499 li.Ar = li.A; Deskew(li.Ar, skew);
500 li.Br = li.B; Deskew(li.Br, skew);
501 };
502 for (i = 0; i < ver_cnt; i++)
503 {
504 LineInfo& li = lti->Ver.Lns[i];
505 li.Ar = li.A; Deskew(li.Ar, skew);
506 li.Br = li.B; Deskew(li.Br, skew);
507 };
508
509 return TRUE;
510 }
511
512 Bool ExtrLinesIsOk(void)
513 {
514 if ((hvSB == NULL) || (!hvSB->isOk())) return WRONG();
515 if ((hRB == NULL) || (!hRB->isOk() )) return WRONG();
516 if ((hLB == NULL) || (!hLB->isOk() )) return WRONG();
517 if ((vRB == NULL) || (!vRB->isOk() )) return WRONG();
518 if ((vLB == NULL) || (!vLB->isOk() )) return WRONG();
519
520 return TRUE;
521 }
522
523 static Bool _PreSwp( LnsInfoArray& larr, Bool hor )
524 {
525 if (larr.Cnt == 0) return TRUE;
526 if (larr.Lns == NULL) return WRONG();
527
528 TLinesBambuk* lb = hor ? hLB : vLB;
529 if (lb == NULL) return WRONG();
530 TRasterBambuk* rb = hor ? hRB : vRB;
531 if (rb == NULL) return WRONG();
532 TSegBambuk* sb = hor ? &(hvSB->hBambuk) : &(hvSB->vBambuk);
533 if (sb == NULL) return WRONG();
534
535 int32_t root_len = lb->linesRoot.volume();
536 for ( int i =0; i<larr.Cnt; i++ )
537 {
538 if ((larr.Lns[i].Flags & LI_COVERED) != 0)
539 {
540 LineInfo & cover = larr.Lns[larr.Lns[i].IndCover];
541 if (!(cover.Flags & LI_SWEEP))
542 continue; // if not must be sweepped - do nothing here;
543 }
544 else if ((larr.Lns[i].Flags & LI_SWEEP) == 0)
545 { continue; // if not must be sweepped - do nothing here;
546 }
547
548 if (larr.Lns[i].Extractor != LI_LNSDLL)
549 { continue; // if not extracted by this - do nothing here;
550 }
551
552 // if here - this is noise line; let's delete it from bambuks!
553
554 //******************Rom****************
555 int32_t RightX = larr.Lns[i].B.x; // set restrictions for case of sweeping
556 int32_t LeftX = larr.Lns[i].A.x; // not whole line; initially - full line
557 int32_t TopY = larr.Lns[i].A.y;
558 int32_t BottomY = larr.Lns[i].A.y;
559
560 if(larr.Lns[i].A.y>larr.Lns[i].B.y)
561 {
562 BottomY = larr.Lns[i].B.y;
563 }
564 else
565 {
566 TopY = larr.Lns[i].B.y;
567 }
568 //*************************************
569
570
571 if (larr.Lns[i].Flags & LI_NOTWHOLE) // correct restriction if not whole line should be sweeped
572 {
573 if ( larr.Lns[i].Anew.x > larr.Lns[i].A.x)
574 {
575 if (larr.Lns[i].Anew.x > larr.Lns[i].B.x) larr.Lns[i].Anew.x = larr.Lns[i].A.x;
576 LeftX = larr.Lns[i].Anew.x;
577 }
578 if ( larr.Lns[i].Anew.y > larr.Lns[i].A.y)
579 {
580 if (larr.Lns[i].Anew.y > TopY) larr.Lns[i].Anew.y = larr.Lns[i].A.y;
581 BottomY = larr.Lns[i].Anew.y;
582 }
583 if ( larr.Lns[i].Bnew.x < larr.Lns[i].B.x)
584 {
585 if (larr.Lns[i].Bnew.x < larr.Lns[i].A.x) larr.Lns[i].Bnew.x = larr.Lns[i].B.x;
586 RightX = larr.Lns[i].Bnew.x;
587 }
588 if ( larr.Lns[i].Bnew.y < larr.Lns[i].B.y)
589 {
590 if (larr.Lns[i].Bnew.y < BottomY) larr.Lns[i].Bnew.y = larr.Lns[i].B.y;
591 TopY = larr.Lns[i].Bnew.y;
592 }
593 }
594 //*************************************
595 ////////////////////
596 int32_t hnd = larr.Lns[i].ExtrDllHnd;
597 if (hnd >= root_len ) return WRONG();
598 TLineInfo & li = lb->linesRoot[hnd];
599 BEntry lbe = li.linesBambukEntry;
600 BHandle h = lb->firstEntryMember( lbe );
601 while ( h !=NULLBHandle )
602 {
603 TLineFragment& lf = (*lb)[h];
604
605 if (lf.fragmentAsIs.flags & LF_HLINER)
606 {
607 h = lb->nextMember(h);
608 continue;
609 }
610
611 BEntry rbe = lf.rasterBambukEntry;
612 BHandle hr = rb->firstEntryMember( rbe );
613 #ifndef NO_17FEB99 // prepear to detect touching letters
614 int frag_width[4000]; // width by len distribution
615
616 // compute real left and right fragment's bounds
617 int frag_left=0xffff; int frag_right = 0;
618 while ( hr != NULLBHandle )
619 {
620 TDash& dash = (*rb)[hr];
621 BHandle sh = dash.firstSegHandle;
622 while ( sh != NULLBHandle )
623 {
624 TBlackSeg& bs = (*sb)[sh];
625 frag_left = MIN( frag_left, bs.left );
626 frag_right = MAX( frag_right, bs.right );
627 sh = bs.nLower;
628 }
629 hr = rb->nextMember(hr);
630 }
631 hr = rb->firstEntryMember( rbe );
632
633 int frag_len = frag_right-frag_left+1;
634 int frag_base =frag_left;
635
636 double ave_frag_width = 2.0; // default, for any
637
638 // avoid sweep short fragments at the bound of line
639 // cos probably part of letters:
640 #ifndef SHORT_FRAGMENTS_ARE_TESTED_TO_BE_NOT_PART_OF_LETTER
641 if ( hor &&
642 frag_len < 50 && // short fragment
643 ( lf.fragmentAsIs.end.x == li.lineAsIs.end.x // at the end of line
644 ||lf.fragmentAsIs.start.x == li.lineAsIs.start.x
645 )
646 )
647 { // skip it, don't sweep.
648 h = lb->nextMember(h);
649 continue;
650 }
651 #endif // SHORT_FRAGMENTS_ARE_TESTED_TO_BE_NOT_PART_OF_LETTER
652
653 // accumulate width distribution
654 if (hor && frag_len > 0 && frag_len*sizeof(frag_width[0]) < sizeof(frag_width))
655 {
656 memset(frag_width, 0, frag_len*sizeof(frag_width[0]));
657 while ( hr != NULLBHandle )
658 {
659 TDash& dash = (*rb)[hr];
660 BHandle sh = dash.firstSegHandle;
661 while ( sh != NULLBHandle )
662 {
663 TBlackSeg& bs = (*sb)[sh];
664 frag_width[ bs.left -frag_base]++;
665 frag_width[ bs.right-frag_base]--;
666 sh = bs.nLower;
667 }
668 hr = rb->nextMember(hr);
669 }
670 int sum_pel = 0;
671 for (int i=1;i<frag_len; i++)
672 {
673 frag_width[i] += frag_width[i-1];
674 sum_pel += frag_width[i];
675 }
676 ave_frag_width = sum_pel / frag_len;
677
678 hr = rb->firstEntryMember( rbe ); // reset hr
679 }
680 #endif // NO_17FEB99
681
682
683 // start main loop of presweeping:
684 while ( hr != NULLBHandle )
685 {
686 TDash& dash = (*rb)[hr];
687 Romi = 0;
688 BHandle sh = dash.firstSegHandle;
689 while ( sh != NULLBHandle )
690 {
691 TBlackSeg& bs = (*sb)[sh];
692 if (hor)
693 {
694 #ifndef NO_17FEB99 // prepear to detect touching letters:
695 // keep short segment if local jump of width > 1.5 pel
696 if (!(bs.right - bs.left < 24 && // short interval and width jump > 1.5 pel
697 ( double(frag_width[(bs.left+bs.right)/2 - frag_base]) > ave_frag_width + 1.5
698 ||double(frag_width[bs.left+4 - frag_base]) > ave_frag_width + 1.5
699 ||double(frag_width[bs.right-4 - frag_base]) > ave_frag_width + 1.5
700 )
701 ) )
702 #endif
703 if ( (bs.right > LeftX) && (bs.left < RightX) )
704 {
705 if (bs.left < LeftX-5) bs.left = LeftX;
706 if (bs.right > RightX+5) bs.right = RightX;
707 int xx = bs.left;
708 bs.left = bs.right;
709 bs.right = xx;
710 }
711 // swap segment to indicate it's SWEEPABILITY
712 }
713 //*********************Rom**********************
714 else
715 {
716 if ( (bs.right > BottomY) && (bs.left < TopY) )
717 {
718 if (bs.left < BottomY-5) bs.left = BottomY;
719 if (bs.right > TopY+5) bs.right = TopY;
720 if(RBlockCurrent->Current >= RBlockCurrent->Max)
721 {
722 RBlockPrev = RBlockCurrent;
723 RBlockCurrent = new CRomBabble;
724 RBlockPrev->next = RBlockCurrent;
725 }
726 Rptr2 = &RBlockCurrent->Data[RBlockCurrent->Current];
727 Rptr2->Begin = bs.left;
728 Rptr2->End = bs.right+4;
729 Rptr2->Column = dash.firstSegEntry+Romi;
730 RBlockCurrent->Current++;
731 Rptr2->next = NULL;
732 Rptr3->next = Rptr2;
733 Rptr3 = Rptr3->next;
734 }
735 Romi++;
736 }
737 //**********************************************
738 sh = bs.nLower;
739 }
740 hr = rb->nextMember(hr);
741 }
742
743 h = lb->nextMember(h);
744 }
745 }
746 return TRUE;
747 }
748 Bool ExtractEvents(CLINE_handle hCLINE, LinesTotalInfo *lti)
749 {
750
751 Bool hor;//горизонтальный - вертикальный
752 LnsInfoArray larr;
753 CLINE_handle hLine, hEvent, hInterval;//хэндлы
754 DEvent Event;//структура для дэшей
755 DInterval Interval;//структура для интервалов
756 CPDLine pLine;//указатель на структуру для линии
757 int count_lines = 0;
758 Bool first_ver = 1;
759 for( hLine = CLINE_GetFirstLine(hCLINE); hLine; hLine=CLINE_GetNextLine(hLine) )
760 {//цикл по всем линиям в контейнере ( и гор. и верт. )
761
762 pLine=CLINE_GetLineData(hLine);//указатель по хэндлу
763
764 if(!pLine)//проверка на вшивость
765 continue;
766 if( pLine->Dir == LD_Horiz )//определение какая линия, горизонтальная или вертикальная
767 {
768 hor = TRUE;
769 larr = lti->Hor;// взяли структуру гори. линии а ля Lns32
770 }
771 else
772 {
773 if( first_ver )
774 {
775 first_ver = 0;
776 count_lines = 0;
777 }
778
779 hor = FALSE;
780 larr = lti->Ver;// взяли структуру верт. линии а ля Lns32
781 }
782 // проверим готовность структур данных ( кусок извлечен из _preSwp() )
783 TLinesBambuk* lb = hor ? hLB : vLB;
784 if (lb == NULL) return WRONG(); // false
785 TRasterBambuk* rb = hor ? hRB : vRB;
786 if (rb == NULL) return WRONG();
787 TSegBambuk* sb = hor ? &(hvSB->hBambuk) : &(hvSB->vBambuk);
788 int32_t root_len = lb->linesRoot.volume();
789 if (sb == NULL) return WRONG();
790
791 //вот это главная проблема. Здесь на руках имеем линия а ля Контейнер CLINE, как узнать
792 //какая линия а ля Lns32 ей соответствует?????
793
794 //int i = from_pLine_to_larr_index(pLine); // pLine->??
795
796 //TLineInfo& li = larr[i]; // взяли описатель i-й линии
797 /* Возможен нулевой хэндл !
798 while( larr.Lns[count_lines].ExtrDllHnd == 0 )
799 {
800 count_lines++;
801 }
802 */
803 if (larr.Lns[count_lines].Extractor != LI_LNSDLL)
804 {
805 //int u = 0;
806 continue; // не из LNSDLL Пришлось закоментировать!!!
807 }
808
809
810 int32_t hnd = larr.Lns[count_lines].ExtrDllHnd; /// начинаем проход по линии Lns[i]
811 count_lines++;
812 /*
813 if( hnd == 0 )
814 return WRONG();
815 */
816 if (hnd >= root_len ) return WRONG();
817 TLineInfo & li = lb->linesRoot[hnd];
818 BEntry lbe = li.linesBambukEntry; /// линия - набор фрагментов, каждый из которых является компонентой связности (КС)
819
820
821
822 BHandle h = lb->firstEntryMember( lbe ); /// берем первый фрагмент
823
824 while ( h !=NULLBHandle ) /// цикл по фрагментам линии
825 {
826 TLineFragment& lf = (*lb)[h]; /// описатель фрагмента линии
827
828 if (lf.fragmentAsIs.flags & LF_HLINER) /// этот кусок линии был выделен другим алгоритмом
829 {
830 h = lb->nextMember(h);
831 continue;
832 }
833
834 BEntry rbe = lf.rasterBambukEntry; /// вход в список эвентов - 'Dash'
835 BHandle hr = rb->firstEntryMember( rbe ); /// номер первого эвент
836 while ( hr != NULLBHandle ) /// по всем эвентам
837 {
838 TDash& dash = (*rb)[hr]; /// взяли дэш (=эвент)
839 hEvent = CLINE_AddNewEvent( hLine ); // создали эвент
840 BHandle sh = dash.firstSegHandle;
841 while ( sh != NULLBHandle ) /// пошли по его списку интервалов
842 {
843 TBlackSeg& bs = (*sb)[sh];///взяли интервал
844 hInterval = CLINE_AddNewEventInv( hEvent );
845 Interval.Pos = bs.left;//наполняем структуру
846 Interval.Lent = bs.right-bs.left+1;//наполняем структуру
847 CLINE_SetEventInvData( hInterval, &Interval );//откладываем в контейнер интервал ( сегмент )
848 sh = bs.nLower;
849 }
850 Event.Hori = pLine->Dir == LD_Horiz;//hor;//pLine->Dir;//наполняем структуру
851 Event.Increase = TRUE;//наполняем структуру
852 Event.Lev_0 = dash.firstSegEntry; /// начинается с этой строки изображения
853 Event.Width = 0;
854
855 CLINE_SetEventData( hEvent, &Event );//откладываем в контейнер эвент ( дэш )
856 hr = rb->nextMember(hr); // переходим к следующему дэшу
857 }
858 h = lb->nextMember(h);
859 } // конец цикла по фрагментам линии
860 } // конец цикла по hLINE
861
862
863 return TRUE;
864 }
865
866 Bool ExtrLinesPrepearToSweep( LinesTotalInfo * lti )
867 {
868 if (lti==NULL) return WRONG();
869 //Rptr = GetRomptr();
870 if (lti->Hor.Cnt > 0)
871 {
872 if (lti->Hor.Lns==NULL) return WRONG();
873 if (!_PreSwp( lti->Hor, TRUE ))
874 return WRONG();
875 }
876 //***************************Rom**********************
877 if (lti->Ver.Cnt > 0)
878 {
879 if (lti->Ver.Lns==NULL) return WRONG();
880 if (!_PreSwp( lti->Ver, FALSE ))
881 return WRONG();
882 }
883
884 SortList ( Rptr );
885 SetRomptr ( Rptr );
886 //****************************************************
887
888
889 InitSweeperData( hvSB );
890 return TRUE;
891 }
892
893 //**********************Rom***************
894 Bool SortList ( RomBubble* rptr)
895 {
896 Bool IsOk = TRUE;
897 Bool Unsorted = TRUE;
898 RomBubble* Rptr0=NULL;
899 RomBubble* Rptr1=NULL;
900 RomBubble* Rptr2=NULL;
901
902 while (( Unsorted ) && (Rptr->next!=NULL))
903 {
904 Rptr0 = Rptr;
905 Rptr1 = Rptr->next;
906 Unsorted = FALSE;
907 while (Rptr1->next != NULL )
908 {
909 if(Rptr1->Begin > Rptr1->next->Begin)
910 {
911 Rptr2 = Rptr1->next;
912 Rptr1->next = Rptr1->next->next;
913 Rptr2->next = Rptr1;
914 Rptr1 = Rptr2;
915 Rptr0->next = Rptr2;
916 Unsorted = TRUE;
917 }
918 else
919 {
920 Rptr0 = Rptr1;
921 Rptr1 = Rptr1->next;
922 }
923 }
924 }
925
926 return IsOk;
927 }
928