File: SGEngine.cpp

package info (click to toggle)
yudit 3.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 18,472 kB
  • sloc: cpp: 76,344; perl: 5,630; makefile: 989; ansic: 823; sh: 441
file content (1357 lines) | stat: -rw-r--r-- 32,733 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
/** 
 *  Yudit Unicode Editor Source File
 *
 *  GNU Copyright (C) 1997-2023  Gaspar Sinai <gaspar@yudit.org>  
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License, version 2,
 *  dated June 1991. See file COPYYING for details.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

// #########################################################################
// This code is obsolete. 
// It was developed for the 2.x.x series of Yudit in year 2000
// and was replaced in 2023 (Yudit-3.0.9) with SRasterizer.
// This class is only kept here to do performance comparison tests.
// #########################################################################
 
#define SS_MAKKA true
#include "swindow/SGEngine.h"
#include "swindow/SImage.h"
#include "stoolkit/SBinHashtable.h"
#include "stoolkit/SProperties.h"
#include "math.h"


static bool cacheOn=true;

typedef SBinHashtable<SImage*> SEImageCache;
static SEImageCache imageCache;

static unsigned int cacheSize = 100;
static unsigned int cacheCount = 0;

#define SS_MITER_ALLOW 2
#define FILL_REPLAY_LINEWIDTH  0.5 
#define STROKE_REPLAY_LINEWIDTH 0.25

static void clearImageCache();

/**
 * After this size things won't be cached.
 */
void
SGEngine::setCacheSize(unsigned int size)
{
  cacheSize = size;
}

/**
 * turn on/off the cache and clear it
 */
void
SGEngine::setCacheOn (bool on)
{
  cacheOn=on;
  clearImageCache();
}
/**
 * @author: Gaspar Sinai <gaspar@yudit.org>
 * @version: 2000-04-23
 * This is the abstract widget toolkit package
 */

/**
 * This class is meant to be the base class of canvases
 * @param windingrule is true if nonzero winding areas should
 * be filled instead of nonzero intersects.
 */
SGEngine::SGEngine(bool windingrule)
{
  SS_Matrix2D m;
  matrix.append (m);
  setup (1.0);
  winding = windingrule;
}

SGEngine::~SGEngine ()
{
    for (unsigned int i=0; i<images.size(); i++) {
        delete images[i];
    }
    images.clear();
}

/** 
 * start a new path.
 * @param _pen is the pen to draw with. it controls oversampling.
 * by experience the best and most efficient pen is size 1.0
 * that give you a 2x2 oversampling.
 * @param _lw is the linewidth
 */
void
SGEngine::_newpath (double _lw)
{
  pathNow.clear();
  pathVector.clear();
  setup (_lw);
  unfinished =false;
}

/**
 * set up scanning parameters
 * By experience the best pen is the 0.5-pen
 */
void
SGEngine::setup(double linewidth)
{
  minx = 0.0;
  miny = 0.0;
  maxx = 0.0;
  maxy = 0.0;
  unfinished = false;
  undelta = 0.0;
  unx = 0.0;
  uny = 0.0;
  if (linewidth > 2.0)
  {
    scancount = 1;
    oversample = 1;
    epsylon = 1;
  }
  else
  {
    scancount = 2;
    if (linewidth <= 0.125)
    {
      oversample = 5;
      epsylon = 0.125;
    }
    else if (linewidth <= 0.25)
    {
      oversample = 4;
      epsylon = 0.25;
    }
    else if (linewidth <= 0.5)
    {
      oversample = 3;
      epsylon = 0.5;
    }
    else
    {
      oversample = 2;
      epsylon = 0.5;
    }
  }
  //colors = scancount * (oversample * oversample) +1;
  //colors = (oversample * oversample) +1;
  colors = (oversample * oversample) +1;
}

void
SGEngine::_moveto (double _x, double _y)
{
  if (unfinished)
  {
    linetoInternal (unx, uny);
    unfinished = false;
  }

  SS_Matrix2D m = matrix[matrix.size()-1];
  double x = m.x0 * _x + m.y0 * _y + m.t0;
  double y = m.x1 * _x + m.y1 * _y + m.t1;

  if (pathVector.size()==0 && pathNow.size()==0)
  {
    minx=x ; miny=y;
    maxx=x ; maxy=y;
  }
  if (pathNow.size())
  {
    pathVector.append (pathNow);
  }
  pathNow.clear();
  pathNow.append(x);
  pathNow.append(y);
  if (x < minx) minx=x;
  if (x > maxx) maxx=x;
  if (y < miny) miny=y;
  if (y > maxy) maxy=y;
}

void
SGEngine::_lineto (double _x, double _y)
{
  SS_Matrix2D m = matrix[matrix.size()-1];
  double x = m.x0 * _x + m.y0 * _y + m.t0;
  double y = m.x1 * _x + m.y1 * _y + m.t1;

  double px0 = pathNow[pathNow.size()-2];
  double py0 = pathNow[pathNow.size()-1];
  double d2 = (x - px0) * (x - px0) + (y - py0) * (y - py0);

  if (d2<epsylon)
  {
    if (!unfinished || ((unfinished && undelta < d2) || SS_MAKKA))
    {
      undelta = d2;
      unx = x;
      uny = y;
      unfinished = true;
    }
  }
  else
  {
    linetoInternal (x, y);
    unfinished=false;
  }
}

/**
 * Cubic bezier curve. first two points are the control points 
 * last point is the endpoint. Statring point is on the stack.
 */
void
SGEngine::_curveto (double _x0, double _y0, double _x1, double _y1, 
  double _x2, double _y2)
{
  SS_Matrix2D m = matrix[matrix.size()-1];
  double x0 = m.x0 * _x0 + m.y0 * _y0 + m.t0;
  double y0 = m.x1 * _x0 + m.y1 * _y0 + m.t1;

  double x1 = m.x0 * _x1 + m.y0 * _y1 + m.t0;
  double y1 = m.x1 * _x1 + m.y1 * _y1 + m.t1;

  double x2 = m.x0 * _x2 + m.y0 * _y2 + m.t0;
  double y2 = m.x1 * _x2 + m.y1 * _y2 + m.t1;

  /* If the area is less than one we draw the lines */
  double px0 = pathNow[pathNow.size()-2];
  double py0 = pathNow[pathNow.size()-1];
  curvetoInternal (px0, py0, x0, y0, x1, y1, x2, y2, 0);
}
void
SGEngine::_closepath()
{
  SS_Matrix2D m = matrix[matrix.size()-1];
  if (unfinished)
  {
    linetoInternal (unx, uny);
    unfinished = false;
  }
  if (pathNow.size () < 2) return;
  double x0 = pathNow[0];
  double y0 = pathNow[1];
  pathNow.append(x0);
  pathNow.append(y0);
  if (pathNow.size()) pathVector.append (pathNow);
  pathNow.clear();
}

/**
 * TODO: This routine is not yet implemented
 */
SImage*
SGEngine::_stroke(int _x, int _y, unsigned int  _width, 
unsigned int  _height, const SPen& pen)
{
/*
  if (unfinished)
  {
    linetoInternal (unx, uny);
    unfinished = false;
  }
*/
  if (_height == 0 || _width == 0) {
    return 0;
  }
//fprintf (stderr, "HEIGHT=%d\n", _height);
  bool offScreen = false;
#if 0
  if (unfinished)
  {
    linetoInternal (unx, uny);
    unfinished = false;
  }
#endif
  unsigned int lines = 0;
  for (unsigned int a=0; a<pathVector.size(); a++)
    for (unsigned int b=0; b+3<pathVector[a].size(); b=b+2) lines++;
  if (lines==0) return 0;
    

  // Mitter can be bad.
  double cminx =  minx - pen.getLineWidth() * SS_MITER_ALLOW ;
  if (int (cminx) < _x) 
  {
    cminx = double (_x);
    offScreen = true;
  }
  double cminy =  miny - pen.getLineWidth() * SS_MITER_ALLOW ;
  if (int (cminy) < _y) 
  {
    cminy = double (_y);
    offScreen = true;
  }

  int origoX=(int) cminx;
  int origoY=(int) cminy;

  // FIXME : this should be same for fill (x)
  double cmaxx = maxx+1.0 + pen.getLineWidth() * SS_MITER_ALLOW ;
  if (cmaxx > double (int(cminx) + int(_width)))
  {
    cmaxx = double (int(cminx) + int(_width));
    offScreen = true;
  }

  double cmaxy = maxy+1.0 + pen.getLineWidth() * SS_MITER_ALLOW ;
  if (cmaxy > double (int(cminy) + int (_height)))
  {
    cmaxy = double (int(cminy)+ int(_height));
    offScreen = true;
  }

  int cwidth = (int) cmaxx - (int) origoX;
  int cheight = (int) cmaxy - (int) origoY;
  unsigned int width = (cwidth < 0) ? 1 : cwidth;
  unsigned int height = (cheight < 0) ? 1 : cheight;

  if (height == 0 || width == 0) return 0;
  if (cwidth < 0 || cheight < 0)
  {
    offScreen = true;
  }

/*
  fprintf (stderr, "XXXXX width=%u height=%u origo=%d,%d\n",
    width, height, origoX, origoY);
*/

  unsigned int i;
  unsigned int imageSize = width *height;

  SS_WORD32 *image = new SS_WORD32[imageSize];
  CHECK_NEW (image);
  memset (image, 0, imageSize * sizeof (SS_WORD32));

  for (unsigned int i=0; i<pathVector.size(); i++)
  {
    for (unsigned int j=0; j+3<pathVector[i].size(); j=j+2)
    {
      const double* v0 = &pathVector[i].array()[j];
      
      strokeScan (image,  width, height, v0, 
        j+5 < pathVector[i].size(), origoX, origoY, pen, true);
/*
      double x0 = pathVector[i][j];
      double y0 = pathVector[i][j+1];
      double x1 = pathVector[i][j+2];
      double y1 = pathVector[i][j+3];
*/
    }
 }
  for (i=0; i<imageSize; i++)
  {
    SS_WORD32 bits = image[i];
    SS_WORD32 cnt = 0;
    while (bits)
    {
      if (bits&1) cnt++;
      bits = bits >> 1;
    }
    /* count how many bits we have */
    image[i] = cnt;
  }
 
  /**
   * copy the resulting image
   */
  SImage* im = new SImage (image, colors, origoX, 
        origoY, width, height);
  CHECK_NEW (im);
  im->px = (int)newpathX;
  im->py = (int)newpathY;
  im->offScreen = offScreen;
  return im;
}

void
SGEngine::strokeScan (SS_WORD32 *image, int width, int height, 
   const double* vectors, bool join, double origoX, double origoY,
  const SPen& pen, bool horizontal) 
  {
    double dirX = vectors[2] - vectors[0];
    double dirY = vectors[3] - vectors[1];
    // 90 degrees
    double length = sqrt (dirX*dirX + dirY*dirY);
    if (length < epsylon/100.0) {
        return;
    } 

    double penw = pen.getLineWidth() ;
 //   length, oversample, dirX, dirY);
    // Unit vector
/*
    double dir90UnitX = -dirY / length;
    double dir90UnitY = dirX / length;
*/

    // Other direction

    double unitX = dirX / length;
    double unitY = dirY / length;
    double inc = 0.5 / oversample;
    double penr2 = (penw/2) * (penw/2);

    for (double t0 = 0.0; t0<=length; t0=t0+inc) {
        double x0 = vectors[0] + t0  * unitX; 
        double y0 = vectors[1] + t0  * unitY; 
        for (double tx =-penw/2.0; tx<=penw/2.0; tx=tx+inc) {
            for (double ty =-penw/2.0; ty<=penw/2.0; ty=ty+inc) {
                double x = x0 + tx;
                double y = y0 + ty;
                int indXOver = (int) ((x-(double)origoX) * (double)oversample);
                int indYOver = (int) ((y-(double)origoY) * (double)oversample);
                if (tx*tx + ty*ty > penr2) continue;
                int indX = indXOver/oversample;
                int indY = indYOver/oversample;

                int bit = ((indXOver % oversample) * oversample) 
                    + (indYOver % oversample);

                if (indX < 0 || indY < 0) continue;              
                if (indX >= width || indY >= height) continue;              
                image[indX + indY * width] |= (1 << bit);
            }
        }
    }
}


SImage*
SGEngine::_fill(int _x, int _y, unsigned int _width, unsigned int _height)
{
  if (_height == 0 || _width == 0) return 0;
//fprintf (stderr, "HEIGHT=%d\n", _height);
  bool offScreen = false;
  if (unfinished)
  {
    linetoInternal (unx, uny);
    unfinished = false;
  }
  unsigned int lines = 0;
  for (unsigned int a=0; a<pathVector.size(); a++)
    for (unsigned b=0; b+3<pathVector[a].size(); b=b+2) lines++;
  if (lines==0) return 0;

  /* Set clipping here */
  double cminx =  minx;
  if (int (minx) < _x) 
  {
    cminx = double (_x);
    offScreen = true;
  }
  double cminy =  miny;
  if (int (miny) < _y) 
  {
    cminy = double (_y);
    offScreen = true;
  }

  int origoX=oversample * (int) cminx;
  int origoY=oversample * (int) cminy;

  double cmaxx = maxx+1.0;
  if (maxx > double (int(cminx) + int(_width)))
  {
    cmaxx = double (int(cminx) + int(_width));
    offScreen = true;
  }

  double cmaxy = maxy+1.0;
  if (maxy > double (int(cminy) + int (_height)))
  {
    cmaxy = double (int(cminy)+ int(_height));
    offScreen = true;
  }

  int cwidth = oversample * (int)  cmaxx - (int) origoX;
  int cheight = oversample * (int) cmaxy - (int) origoY;

  unsigned int width = (cwidth < 0) ? oversample : cwidth;
  unsigned int height = (cheight < 0) ? oversample : cheight;

//  fprintf (stderr, "miny=%g maxy=%g origoY=%d cmaxy=%g cminy=%g cheight=%d height=%d _height=%d\n",
//      miny, maxy, origoY, cmaxy, cminy, cheight, height, _height);

  if (height == 0 || width == 0) return 0;

  if (cwidth < 0 || cheight < 0)
  {
    offScreen = true;
  }

  unsigned int i;
  unsigned int imageSize = width/oversample *height/oversample;

  SS_WORD32 *image = new SS_WORD32[imageSize];
  CHECK_NEW (image);
  memset (image, 0, imageSize * sizeof (SS_WORD32));
 
  /**
   * scan the lines horizontally 
   */ 
  SS_InterSection** scanHoriz = new SS_InterSection* [height];
  CHECK_NEW (scanHoriz);

  for (i=0; i<height; i++)
  {
    scanHoriz[i] = new SS_InterSection();
    CHECK_NEW (scanHoriz[i]);
  }
  scan (scanHoriz, origoX, origoY, (int) height, false);
  render (image, scanHoriz, width, height, false); 
  for (i=0; i<height; i++)
  {
    delete scanHoriz[i];
    scanHoriz[i] = 0;
  }
  delete[] scanHoriz;

  /**
   * scan the lines vertically 
   */ 
  if (scancount > 0)
  {
    SS_InterSection** scanVert = new SS_InterSection* [width];
    CHECK_NEW (scanVert);
    for (i=0; i<width; i++)
    {
      scanVert[i] = new SS_InterSection();
      CHECK_NEW (scanVert[i]);
    }
    scan (scanVert, origoY, origoX, (int) width, true);
    render (image, scanVert, height, width, true); 

    for (i=0; i<width; i++)
    {
      delete scanVert[i];
      scanVert[i] = 0;
    }
    delete[] scanVert;
  }
  for (i=0; i<imageSize; i++)
  {
    SS_WORD32 bits = image[i];
    SS_WORD32 cnt = 0;
    while (bits)
    {
      if (bits&1) cnt++;
      bits = bits >> 1;
    }
    /* count how many bits we have */
    image[i] = cnt;
  }
  /**
   * copy the resulting image
   */
  SImage* im = new SImage (image, colors, origoX/oversample, 
        origoY/oversample, width/oversample, height/oversample);
  CHECK_NEW (im);
  im->offScreen = offScreen;
  return im;
}

void
SGEngine::_pushmatrix()
{
  if (matrix.size() > 10) {
    fprintf (stderr, "pushpmatrix size-%u\n", matrix.size());
    return;
  }
  SS_Matrix2D m = matrix[matrix.size()-1];
  matrix.append (m);
}

void
SGEngine::_popmatrix()
{
//  fprintf (stderr, "Popmatrix size-%u\n", matrix.size());
  if (matrix.size())
  {
    matrix.truncate(matrix.size()-1);
  }
}

/**
 * TODO: not implemented 
 */
void
SGEngine::_rotate (double angle)
{
  SS_Matrix2D m = matrix[matrix.size()-1];
  m.rotate (angle);
  popmatrix ();
  matrix.append (m);
}

/**
 * immaediate action.
 */
void
SGEngine::_scale (double x, double y)
{
  SS_Matrix2D m = matrix[matrix.size()-1];
  m.scale (x, y);
  popmatrix ();
  matrix.append (m);
}

void
SGEngine::_translate (double x, double y)
{
  SS_Matrix2D m = matrix[matrix.size()-1];
  m.translate (x, y);
  popmatrix ();
  matrix.append (m);
}


/**
 * The following section contains the guts of the engine: the rendering
 */

/**
 * This routine is called when no coordnate transform is needed
 */
void
SGEngine::curvetoInternal (double x0, double y0, double x1, 
  double y1, double x2, double y2, double x3, double y3, int rec)
{
  /* http://www.cs.wpi.edu/~matt/courses/cs563/talks/curves.html */
  double dist2 = (x3 - x0) * (x3 - x0) + (y3 - y0) * (y3 - y0);

  // Tune this. 1.0 should be fine.
  if (dist2 < 1.0)
  {
    if (unfinished)
    {
      double px0 = pathNow[pathNow.size()-2];
      double py0 = pathNow[pathNow.size()-1];
      double d2 = (x3 - px0) * (x3 - px0) + (y3 - py0) * (y3 - py0);
      if (d2 > epsylon)
      {
        linetoInternal (x3, y3);
        unfinished = false;
      }
      else
      {
        if (undelta < d2 || SS_MAKKA)
        {
          undelta = d2;
          unx = x3;
          uny = y3;
        }
      }
    }
    else
    {
      unfinished = true;
      unx = x3;
      uny = y3;
    }
    return;
  }

  /* divide it up into two sub-sections */
  double qx0 = x0; double qy0 = y0;

  double qx1 = (x0 + x1)/2.0;
  double qy1 = (y0 + y1)/2.0;

  double qx2 = qx1/2.0 + (x1 + x2) / 4.0;
  double qy2 = qy1/2.0 + (y1 + y2) / 4.0;

  double rx3 = x3;
  double ry3 = y3;

  double rx2 = (x2 + x3) / 2.0;
  double ry2 = (y2 + y3) / 2.0; 

  double rx1 = (x1 + x2) / 4.0 + rx2 / 2.0;
  double ry1 = (y1 + y2) / 4.0 + ry2 / 2.0;

  double qx3 = (qx2 + rx1) / 2.0;
  double qy3 = (qy2 + ry1) / 2.0;

  double rx0 = qx3;
  double ry0 = qy3; 
 
  curvetoInternal (qx0, qy0, qx1, qy1, qx2, qy2, qx3, qy3, rec);
  curvetoInternal (rx0, ry0, rx1, ry1, rx2, ry2, rx3, ry3, rec);
}


/**
 * This routine is called when no coordnate transform is needed
 */
void
SGEngine::linetoInternal (double x, double y)
{
  pathNow.append(x);
  pathNow.append(y);
  if (x < minx) minx=x;
  if (x > maxx) maxx=x;
  if (y < miny) miny=y;
  if (y > maxy) maxy=y;
}

/**
 * can the curves into the buffer
 * If winding is true use the non-zero winding rule rather that
 * intersect rule.
 * @param inter in the allocated  and initialisez intersection array
 * @param offsetx is the offset in internal buffer
 * @param offsety is the offset in scanline.
 * @parm height is the height of the internal buffer 
 * @param xy is 0 if x is x y is y 1 vice versa.
 */
void
SGEngine::scan (SS_InterSection** intersBuff, 
  int ox, int oy, int height, bool swap)
{
  if (winding)
  {
    scanWinding (intersBuff, ox, oy, height, swap);
  }
  else
  {
    scanCrosses (intersBuff, ox, oy, height, swap);
  }
}

/**
 * Scan the curves into the buffer using nonzero winding rule.
 * @param inter in the allocated  and initialisez intersection array
 * @param offsetx is the offset in internal buffer
 * @param offsety is the offset in scanline.
 * @parm height is the height of the internal buffer 
 * @param xy is 0 if x is x y is y 1 vice versa.
 */
void
SGEngine::scanWinding (SS_InterSection** intersBuff, 
  int ox, int oy, int height, bool swap)
{
  int* crossBuff = new int[height];
  CHECK_NEW (crossBuff);

  double is;
  double diff;

  unsigned int swapindx = (swap) ? 1 : 0;
  unsigned int swapindy = (swap) ? 0 : 1;
  /* all paths */
  unsigned int i;
  unsigned int j;
  SS_InterSection** clockwise = new SS_InterSection*[(unsigned int)height];
  CHECK_NEW (clockwise);
  for (i=0; i<(unsigned int)height; i++)
  {
    clockwise[i] = new SS_InterSection();
    CHECK_NEW (clockwise[i]);
  }
  for (i=0; i<pathVector.size(); i++)
  {
    memset (crossBuff, 0, height * sizeof (int));
    /* one path */
    for (j=0; j+3<pathVector[i].size(); j=j+2)
    {
      bool lastone = (j+3+2>=pathVector[i].size());
      /* Blur the image by half a grid to get a better contour */
      double x0 = pathVector[i][j+swapindx] * (double) oversample  
           + 0.5 - (double) ox ;
      double y0 = pathVector[i][j+swapindy] * (double) oversample 
           + 0.5 - (double) oy ;
      double x1 = pathVector[i][j+swapindx+2] * (double) oversample
           + 0.5 - (double) ox ;
      double y1 = pathVector[i][j+swapindy+2] * (double) oversample 
           + 0.5 - (double) oy ;

      int from = (int) y0;
      int to = (int) y1;
      int increment = (y0 > y1) ? -1 : 1;

      if (increment > 0)
      {
        if (from >= height || to < 0)
        {
          continue;
        }
        if (from < 0) from = 0;
        if (to >= height) to  = height-1;
        diff = y1 - y0;
      }
      else
      {
        if (to >= height || from < 0)
        {
          continue;
        }
        if (to < 0) to = 0;
        if (from >= height) from  = height-1;
        diff = y0 - y1;
      }
      /* scan betbeen  y0..y1 */
      for (int k=from; ; k+=increment)
      {
         double cline = double (k);
         bool crosses  = (increment > 0) 
               ? (cline >= y0 && cline < y1) 
               : (cline >= y1 && cline < y0);

         int lastCross = crossBuff[k];
         if (lastCross == 0)
         {
           lastCross =  -increment;
         }

         if (increment * lastCross > 0 || !crosses)
         {
            if (k==to) break;
            continue;
         }
         crossBuff[k] = increment;

         if (diff < 0.1)
         {
           is = x0;
         }
         else
         {
           is = x0 + (x1 - x0) * (cline - y0) / (y1-y0);
         }
         unsigned int pos = intersBuff[k]->appendSorted ((int)is);
         clockwise[k]->insert (pos, increment);
         /*
          * This happened if we got inside/out it all wrong
          * Mainly happens when we get a straight line first and we
          * think is is positive.
          */
         if (lastone && (intersBuff[k]->size() & 1)!=0)
         {
           intersBuff[k]->remove (0);
           clockwise[k]->remove (0);
         }
         if (k==to) break;
      }
    }
  }
  
  for (i=0; i<(unsigned int)height; i++)
  {
    int swinding = 0;
    for (j=0; j<intersBuff[i]->size(); )
    {
      int oldwin = swinding;
      swinding += clockwise[i]->peek(j);
      if (oldwin==0 || swinding==0)
      {
         j++; continue;
      }
      /* remove the ones that don't go from/to zero */
      intersBuff[i]->remove (j);
      clockwise[i]->remove (j);
    }
    delete clockwise[i];
    clockwise[i] = 0;
  }
  delete[] crossBuff;
  delete[] clockwise;
}

/**
 * Scan the curves into the buffer using crosses rule
 * @param inter in the allocated  and initialisez intersection array
 * @param offsetx is the offset in internal buffer
 * @param offsety is the offset in scanline.
 * @parm height is the height of the internal buffer 
 * @param xy is 0 if x is x y is y 1 vice versa.
 */
void
SGEngine::scanCrosses (SS_InterSection** intersBuff, 
  int ox, int oy, int height, bool swap)
{
  int* crossBuff = new int[height];
  CHECK_NEW (crossBuff);

  double is;
  double diff;

  unsigned int swapindx = (swap) ? 1 : 0;
  unsigned int swapindy = (swap) ? 0 : 1;
  /* all paths */
  for (unsigned int i=0; i<pathVector.size(); i++)
  {
    memset (crossBuff, 0, height * sizeof (int));
    /* one path */
    for (unsigned j=0; j+3<pathVector[i].size(); j=j+2)
    {
      bool lastone = (j+3+2>=pathVector[i].size());
      /* Blur the image by half a grid to get a better contour */
      double x0 = pathVector[i][j+swapindx] * (double) oversample  
           + 0.5 - (double) ox ;
      double y0 = pathVector[i][j+swapindy] * (double) oversample 
           + 0.5 - (double) oy ;
      double x1 = pathVector[i][j+swapindx+2] * (double) oversample
           + 0.5 - (double) ox ;
      double y1 = pathVector[i][j+swapindy+2] * (double) oversample 
           + 0.5 - (double) oy ;

      int from = (int) y0;
      int to = (int) y1;
      int increment = (y0 > y1) ? -1 : 1;

      if (increment > 0)
      {
        if (from >= height || to < 0)
        {
          continue;
        }
        if (from < 0) from = 0;
        if (to >= height) to  = height-1;
        diff = y1 - y0;
      }
      else
      {
        if (to >= height || from < 0)
        {
          continue;
        }
        if (to < 0) to = 0;
        if (from >= height) from  = height-1;
        diff = y0 - y1;
      }
      /* scan betbeen  y0..y1 */
      for (int k=from; ; k+=increment)
      {
         double cline = double (k);
         bool crosses  = (increment > 0) 
               ? (cline >= y0 && cline < y1) 
               : (cline >= y1 && cline < y0);

         int lastCross = crossBuff[k];
         if (lastCross == 0)
         {
           lastCross =  -increment;
         }

         if (increment * lastCross > 0 || !crosses)
         {
            if (k==to) break;
            continue;
         }
         crossBuff[k] = increment;

         if (diff < 0.1)
         {
           is = x0;
         }
         else
         {
           is = x0 + (x1 - x0) * (cline - y0) / (y1-y0);
         }
         intersBuff[k]->appendSorted ((int)is);
         /*
          * This happened if we got inside/out it all wrong
          * Mainly happens when we get a straight line first and we
          * think is is positive.
          */
         if (lastone && (intersBuff[k]->size() & 1)!=0)
         {
           intersBuff[k]->remove (0);
         }
         if (k==to) break;
      }
    }
  }
  delete[] crossBuff;
}

void
SGEngine::render (SS_WORD32* image, SS_InterSection** intersBuff, 
 unsigned int width, unsigned int height, bool swap)
{
  int first;
  int next;

  /* These are the array increments x, y */
  int muxx = (swap) ?  1 : width/oversample;
  int muxy = (swap) ?  height/oversample : 1;

  //for (unsigned i=0; i<height; i=i+SD_OVERSAMPLE)
  SS_WORD32 ovs2 = oversample * oversample;
  for (unsigned i=0; i<height; i++)
  {
    //for (unsigned int j=0; j<SD_OVERSAMPLE; j++)
    {
      int lastx = -1;
      if (intersBuff[i]->size() == 0) continue;

      for (unsigned int k=0; k+1<intersBuff[i]->size(); k=k+2)
      {
        first = intersBuff[i]->peek (k);
        next =  intersBuff[i]->peek (k+1);

        if (first < 0) first = 0;
        if (lastx < first)  lastx=first; 
        if (next+1 >= (int) width) next = ((int) width)-1;

        while (lastx<=next)
        {
           SS_WORD32 ind = muxy*(lastx/oversample) + muxx*((i)/oversample);
           SS_WORD32 mask = (swap) 
                   ? 1 << (((i) + oversample * lastx) % ovs2)
                   : 1 << (((i) * oversample + lastx) % ovs2);
           SS_WORD32 vle = image[ind];
           vle = vle | mask;
           image[ind] = vle;
           lastx++;
        }
      }
    }
  }
}

/**
 * create a new path.
 * if an image exists that has the same id, it will be
 * moved to x, y and returned.  You should delete the image
 * aftwerwards. 
 *
 * IMPORTANT: it is the creator of the id that actually
 * is responsible of distinguishing different penWidth values.
 *
 * If the image with id is not in cache, it will return 0.
 * @param id is the unique id of the image.
 * @param x is the x offset
 * @param y is the y offset
 */
bool
SGEngine::beginImage (int x, int y, const SString& id)
{
  primitive.clear();
  pathVector.clear();
  for (unsigned int i=0; i<images.size(); i++) {
        delete images[i];
  }
  images.clear();
  newpathID = id;
  newpathX = x;
  newpathY = y;
  /* with a bit of a luck we have it in the cache */
  if (id.size() && imageCache.get (id) != 0)
  {
    return true;
  }
  return false;
}

SImage*
SGEngine::endImage () {
    primitive.clear();
    pathVector.clear();
    SImage* ret = (SImage*) imageCache.get (newpathID);
    if (ret)
    {
        SImage * im = new SImage(*ret);
        im->setOrigoX (im->getOrigoX() + (int)newpathX - im->px);
        im->setOrigoY (im->getOrigoY() + (int)newpathY - im->py);
        return im;
    }
    if (images.size() == 0) return 0;
    // FIXME: merge all images.
    SImage currentLayer (*images[0]);
    delete images[0];
    for (unsigned int i=1; i<images.size(); i++) {
        currentLayer = currentLayer.addLayer ((*images[i]));
        delete images[i];
    } 
    images.clear();
    ret = new SImage (currentLayer);
    if (ret->offScreen)
    {
        //fprintf (stderr, "refuse to put off screen image into the cache\n");
    }

    ret->compress ();
    if (cacheOn && !ret->offScreen && newpathID.size() > 0) 
    {
        cacheCount++;
        if (cacheCount > cacheSize)
        {
            fprintf (stderr, "SGEngine:: clearing cache (%u elements)\n",cacheCount);
            clearImageCache();
            cacheCount = 1;
        }
// makka
        imageCache.put (newpathID, new SImage (*ret));
    //fprintf (stderr, "putting screen image %*.*s into the cache\n",
     //      SSARGS(newpathID));
    }
    return ret;
}

void
SGEngine::newpath ()
{
  pathVector.clear();
  /* take a first hand look. */
  SGPrimitive p;
  p.newpath();
  primitive.append (p);
}

/**
 * Stroke and fill resets the machinesry and returns the rendered image
 * @param x is the x corner
 * @param x is the y corner
 * @param width is the desired width
 * @param height is the desired height
 * @param lw is the lineWidth (if value is less than zero - subpixel *) 
 */
void 
SGEngine::stroke(int x, int y, unsigned int width, unsigned int height, 
  const SPen& pen)
{
  //double lw = pen.getLineWidth();
  SGPrimitive p; 
  p.stroke(x, y, width, height);
  primitive.append (p);
  _replay(STROKE_REPLAY_LINEWIDTH);
  if (unfinished)
  {
    linetoInternal (unx, uny);
    unfinished = false;
  }
  if (pathNow.size()) pathVector.append (pathNow);
  pathNow.clear();

  SImage* ret = _stroke (x, y, width, height, pen);
  if (ret) {
    SImage colsi = ret->colorize(pen.getForeground());
    delete ret;
    ret = new SImage(colsi);
    images.append (ret);
  }
}

void
SGEngine::fill (int x, int y, unsigned int width, unsigned int height, 
  const SPen& pen)
{
  double lw = pen.getLineWidth();
  SImage* si = fillInternal (x, y, width, height, lw);
  //fprintf  (stderr, "Image Layer appended %lx\n", (unsigned long) ret);
  if (si) {
    SImage colsi = si->colorize(pen.getForeground());
    delete si;
    si = new SImage(colsi);
    images.append (si);
  }
}

/**
 * Stroke and fill resets the machinesry and returns the rendered image
 * @param x is the x corner
 * @param x is the y corner
 * @param width is the desired width
 * @param height is the desired height
 * @return the resulting image. Put it in the cache with 'newpathID' if
 * newpathID is not "" and the image is not off the screen.
 */
SImage* 
SGEngine::fillInternal (int x, int y, unsigned int width, unsigned int height, 
  double lw)
{
  SGPrimitive p; p.fill (x, y, width, height); primitive.append (p);

  if (newpathID.size()==0)
  {
    //fprintf (stderr, "screen image %*.*s cacheOn=%d\n",
     //      SSARGS(newpathID), (int)cacheOn);
    _replay(FILL_REPLAY_LINEWIDTH);
    SImage* ret = _fill (x, y, width, height);
    pathVector.clear();
    return ret;
  }

  /*--------- no luck with cached image. -------------*/    
  _replay(FILL_REPLAY_LINEWIDTH);
  SImage *ii = _fill (x, y, width, height);
  if (ii==0) return 0;

  ii->px = (int)newpathX;
  ii->py = (int)newpathY;

//fprintf (stderr, "created one with newpathX=%d, newpathY=%d\n",
 //  (int)newpathX, (int)newpathY);
  pathVector.clear();
  return ii;
}

/**
 * Go through the primitives and replay them
 */
void 
SGEngine::_replay (double lineWidth)
{
  for (unsigned int i=0; i<primitive.size(); i++)
  {
    SGPrimitive p (primitive[i]);
    switch (p.type)
    {
    case SGPrimitive::CURVETO:
      _curveto (p.params[0], p.params[1],
             p.params[2], p.params[3], 
             p.params[4], p.params[5]);
      break;
    case SGPrimitive::NEWPATH:
      _newpath (lineWidth);
      unfinished =false;
      break;
    case SGPrimitive::MOVETO:
      _moveto (p.params[0], p.params[1]);
      break;
    case SGPrimitive::LINETO:
      _lineto (p.params[0], p.params[1]);
      break;
    case SGPrimitive::TRANSLATE:
      _translate (p.params[0], p.params[1]);
      break;
    case SGPrimitive::SCALE:
      _scale (p.params[0], p.params[1]);
      break;
    case SGPrimitive::CLOSEPATH:
      _closepath ();
      break;
    case SGPrimitive::PUSHMATRIX:
      _pushmatrix ();
      break;
    case SGPrimitive::POPMATRIX:
      _popmatrix ();
      break;
    case SGPrimitive::ROTATE:
      _rotate (p.params[0]);
      break;
    default:
      break;
    }
  }
}


void
SGEngine::moveto (double x, double y)
{
  SGPrimitive p; p.moveto(x,y);
  primitive.append (p);
}

void
SGEngine::lineto (double x, double y)
{
  SGPrimitive p; p.lineto(x,y);
  primitive.append (p);
}

void
SGEngine::curveto (double x0, double y0, double x1, double y1, double x2, double y2)
{
  SGPrimitive p; p.curveto(x0,y0,x1,y1,x2,y2);
  primitive.append (p);
}

void
SGEngine::closepath()
{
  SGPrimitive p; p.closepath();
  primitive.append (p);
}


void
SGEngine::pushmatrix()
{
  // need this because scale is not a primitive...
  _pushmatrix();
  SGPrimitive p; p.pushmatrix();
  primitive.append (p);
}

void
SGEngine::popmatrix()
{
  // need this because scale is not a primitive...
  _popmatrix();
  SGPrimitive p; p.popmatrix();
  primitive.append (p);
}

void
SGEngine::scale (double x, double y)
{
  _scale (x,y);
  //SGPrimitive p; p.scale(x,y);
  //primitive.append (p);
}

void
SGEngine::translate (double x, double y)
{
   _translate (x, y);

  //SGPrimitive p; p.translate(x,y);
  //primitive.append (p);
}

void
SGEngine::rotate (double angle)
{
   _rotate (angle);
  //SGPrimitive p; p.rotate(angle);
  //primitive.append (p);
}

/**
 * This routine is not supposed to be used extensively. This is
 * to check the current matrix.
 */
SS_Matrix2D
SGEngine::getCurrentMatrix() const
{
  return SS_Matrix2D(matrix[matrix.size()-1]);
}

static void clearImageCache() {
    for (unsigned int i=0; i<imageCache.size(); i++)
    {
        for (unsigned int j=0; j<imageCache.size(i); j++)
        {
            SImage* e = imageCache.get (i, j);
            if (e != 0) delete e;
        }
    }
    imageCache.clear ();
    cacheCount = 0;
}