forked from AngusJohnson/Image32
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImg32.Draw.pas
2234 lines (2034 loc) · 68.5 KB
/
Img32.Draw.pas
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
unit Img32.Draw;
(*******************************************************************************
* Author : Angus Johnson *
* Version : 4.4 *
* Date : 12 March 2023 *
* Website : http://www.angusj.com *
* Copyright : Angus Johnson 2019-2023 *
* *
* Purpose : Polygon renderer for TImage32 *
* *
* License : Use, modification & distribution is subject to *
* Boost Software License Ver 1 *
* http://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************)
interface
{$I Img32.inc}
{.$DEFINE MemCheck} //for debugging only (adds a minimal cost to performance)
uses
SysUtils, Classes, Types, Math, Img32, Img32.Vector;
type
TFillRule = Img32.Vector.TFillRule;
// TGradientColor: used internally by both
// TLinearGradientRenderer and TRadialGradientRenderer
TGradientColor = record
offset: double;
color: TColor32;
end;
TArrayOfGradientColor = array of TGradientColor;
TGradientFillStyle = (gfsClamp, gfsMirror, gfsRepeat);
// TBoundsProc: Function template for TCustomRenderer.
TBoundsProc = function(dist, colorsCnt: integer): integer;
TBoundsProcD = function(dist: double; colorsCnt: integer): integer;
TImage32ChangeProc = procedure of object;
// TCustomRenderer: can accommodate pixels of any size
TCustomRenderer = class {$IFDEF ABSTRACT_CLASSES} abstract {$ENDIF}
private
fImgWidth : integer;
fImgHeight : integer;
fImgBase : Pointer;
fCurrY : integer;
fCurrLinePtr : Pointer;
fPixelSize : integer;
fChangeProc : TImage32ChangeProc;
protected
procedure NotifyChange;
function Initialize(imgBase: Pointer;
imgWidth, imgHeight, pixelSize: integer): Boolean; overload; virtual;
function Initialize(targetImage: TImage32): Boolean; overload; virtual;
function GetDstPixel(x,y: integer): Pointer;
// RenderProc: x & y refer to pixel coords in the destination image and
// where x1 is the start (and left) and x2 is the end of the render
procedure RenderProc(x1, x2, y: integer; alpha: PByte); virtual; abstract;
property ImgWidth: integer read fImgWidth;
property ImgHeight: integer read fImgHeight;
property ImgBase: Pointer read fImgBase;
property PixelSize: integer read fPixelSize;
end;
TColorRenderer = class(TCustomRenderer)
private
fAlpha: Byte;
fColor: TColor32;
protected
procedure RenderProc(x1, x2, y: integer; alpha: PByte); override;
function Initialize(targetImage: TImage32): Boolean; override;
public
constructor Create(color: TColor32 = clNone32);
procedure SetColor(value: TColor32);
end;
TAliasedColorRenderer = class(TCustomRenderer)
private
fColor: TColor32;
protected
function Initialize(targetImage: TImage32): Boolean; override;
procedure RenderProc(x1, x2, y: integer; alpha: PByte); override;
public
constructor Create(color: TColor32 = clNone32);
end;
TEraseRenderer = class(TCustomRenderer)
protected
procedure RenderProc(x1, x2, y: integer; alpha: PByte); override;
end;
TInverseRenderer = class(TCustomRenderer)
protected
procedure RenderProc(x1, x2, y: integer; alpha: PByte); override;
end;
TImageRenderer = class(TCustomRenderer)
private
fImage : TImage32;
fOffset : TPoint;
fBrushPixel : PARGB;
fLastYY : integer;
fMirrorY : Boolean;
fBoundsProc : TBoundsProc;
function GetFirstBrushPixel(x, y: integer): PARGB;
protected
procedure RenderProc(x1, x2, y: integer; alpha: PByte); override;
function Initialize(targetImage: TImage32): Boolean; override;
public
constructor Create(tileFillStyle: TTileFillStyle = tfsRepeat;
brushImage: TImage32 = nil);
destructor Destroy; override;
procedure SetTileFillStyle(value: TTileFillStyle);
property Image: TImage32 read fImage;
property Offset: TPoint read fOffset write fOffset;
end;
// TCustomGradientRenderer is also an abstract class
TCustomGradientRenderer = class(TCustomRenderer)
private
fBoundsProc : TBoundsProc;
fGradientColors : TArrayOfGradientColor;
protected
fColors : TArrayOfColor32;
fColorsCnt : integer;
procedure SetGradientFillStyle(value: TGradientFillStyle); virtual;
public
constructor Create;
procedure SetParameters(startColor, endColor: TColor32;
gradFillStyle: TGradientFillStyle = gfsClamp); virtual;
procedure InsertColorStop(offsetFrac: double; color: TColor32);
procedure Clear;
end;
TLinearGradientRenderer = class(TCustomGradientRenderer)
private
fStartPt : TPointD;
fEndPt : TPointD;
fPerpendicOffsets: TArrayOfInteger;
fIsVert : Boolean;
protected
procedure RenderProc(x1, x2, y: integer; alpha: PByte); override;
function Initialize(targetImage: TImage32): Boolean; override;
public
procedure SetParameters(const startPt, endPt: TPointD;
startColor, endColor: TColor32;
gradFillStyle: TGradientFillStyle = gfsClamp); reintroduce;
end;
TRadialGradientRenderer = class(TCustomGradientRenderer)
private
fCenterPt : TPointD;
fScaleX : double;
fScaleY : double;
fColors : TArrayOfColor32;
protected
procedure RenderProc(x1, x2, y: integer; alpha: PByte); override;
function Initialize(targetImage: TImage32): Boolean; override;
public
procedure SetParameters(const focalRect: TRect;
innerColor, outerColor: TColor32;
gradientFillStyle: TGradientFillStyle = gfsClamp); reintroduce;
end;
TSvgRadialGradientRenderer = class(TCustomGradientRenderer)
private
fA, fB : double;
fAA, fBB : double;
fCenterPt : TPointD;
fFocusPt : TPointD;
fBoundsProcD : TBoundsProcD;
protected
procedure RenderProc(x1, x2, y: integer; alpha: PByte); override;
function Initialize(targetImage: TImage32): Boolean; override;
public
procedure SetParameters(const ellipseRect: TRect;
const focus: TPoint; innerColor, outerColor: TColor32;
gradientFillStyle: TGradientFillStyle = gfsClamp); reintroduce;
end;
// Barycentric rendering colorizes inside triangles
TBarycentricRenderer = class(TCustomRenderer)
private
a: TPointD;
c1, c2, c3: TARGB;
v0, v1: TPointD;
d00, d01, d11, invDenom: double;
function GetColor(const pt: TPointD): TColor32;
protected
procedure RenderProc(x1, x2, y: integer; alpha: PByte); override;
public
procedure SetParameters(const a, b, c: TPointD; c1, c2, c3: TColor32);
end;
// /////////////////////////////////////////////////////////////////////////
// DRAWING FUNCTIONS
// /////////////////////////////////////////////////////////////////////////
procedure DrawPoint(img: TImage32; const pt: TPointD;
radius: double; color: TColor32); overload;
procedure DrawPoint(img: TImage32; const pt: TPointD;
radius: double; renderer: TCustomRenderer); overload;
procedure DrawPoint(img: TImage32; const points: TPathD;
radius: double; color: TColor32); overload;
procedure DrawPoint(img: TImage32; const paths: TPathsD;
radius: double; color: TColor32); overload;
procedure DrawInvertedPoint(img: TImage32; const pt: TPointD; radius: double);
procedure DrawLine(img: TImage32;
const pt1, pt2: TPointD; lineWidth: double; color: TColor32); overload;
procedure DrawLine(img: TImage32;
const line: TPathD; lineWidth: double; color: TColor32;
endStyle: TEndStyle; joinStyle: TJoinStyle = jsAuto;
miterLimit: double = 2); overload;
procedure DrawLine(img: TImage32;
const line: TPathD; lineWidth: double; renderer: TCustomRenderer;
endStyle: TEndStyle; joinStyle: TJoinStyle = jsAuto;
miterLimit: double = 2); overload;
procedure DrawLine(img: TImage32; const lines: TPathsD;
lineWidth: double; color: TColor32;
endStyle: TEndStyle; joinStyle: TJoinStyle = jsAuto;
miterLimit: double = 2); overload;
procedure DrawLine(img: TImage32; const lines: TPathsD;
lineWidth: double; renderer: TCustomRenderer;
endStyle: TEndStyle; joinStyle: TJoinStyle = jsAuto;
miterLimit: double = 2); overload;
procedure DrawInvertedLine(img: TImage32;
const line: TPathD; lineWidth: double;
endStyle: TEndStyle; joinStyle: TJoinStyle = jsAuto); overload;
procedure DrawInvertedLine(img: TImage32;
const lines: TPathsD; lineWidth: double;
endStyle: TEndStyle; joinStyle: TJoinStyle = jsAuto); overload;
procedure DrawDashedLine(img: TImage32; const line: TPathD;
dashPattern: TArrayOfInteger; patternOffset: PDouble;
lineWidth: double; color: TColor32;
endStyle: TEndStyle; joinStyle: TJoinStyle = jsAuto); overload;
procedure DrawDashedLine(img: TImage32; const lines: TPathsD;
dashPattern: TArrayOfInteger; patternOffset: PDouble;
lineWidth: double; color: TColor32; endStyle: TEndStyle;
joinStyle: TJoinStyle = jsAuto); overload;
procedure DrawDashedLine(img: TImage32; const line: TPathD;
dashPattern: TArrayOfInteger; patternOffset: PDouble;
lineWidth: double; renderer: TCustomRenderer; endStyle: TEndStyle;
joinStyle: TJoinStyle = jsAuto); overload;
procedure DrawDashedLine(img: TImage32; const lines: TPathsD;
dashPattern: TArrayOfInteger; patternOffset: PDouble;
lineWidth: double; renderer: TCustomRenderer;
endStyle: TEndStyle; joinStyle: TJoinStyle = jsAuto); overload;
procedure DrawInvertedDashedLine(img: TImage32;
const line: TPathD; dashPattern: TArrayOfInteger;
patternOffset: PDouble; lineWidth: double; endStyle: TEndStyle;
joinStyle: TJoinStyle = jsAuto); overload;
procedure DrawInvertedDashedLine(img: TImage32;
const lines: TPathsD; dashPattern: TArrayOfInteger;
patternOffset: PDouble; lineWidth: double;
endStyle: TEndStyle; joinStyle: TJoinStyle = jsAuto); overload;
procedure DrawPolygon(img: TImage32; const polygon: TPathD;
fillRule: TFillRule; color: TColor32); overload;
procedure DrawPolygon(img: TImage32; const polygon: TPathD;
fillRule: TFillRule; renderer: TCustomRenderer); overload;
procedure DrawPolygon(img: TImage32; const polygons: TPathsD;
fillRule: TFillRule; color: TColor32); overload;
procedure DrawPolygon(img: TImage32; const polygons: TPathsD;
fillRule: TFillRule; renderer: TCustomRenderer); overload;
procedure DrawInvertedPolygon(img: TImage32; const polygon: TPathD;
fillRule: TFillRule); overload;
procedure DrawInvertedPolygon(img: TImage32; const polygons: TPathsD;
fillRule: TFillRule); overload;
// 'Clear Type' text rendering is quite useful for low resolution
// displays (96 ppi). However it's of little to no benefit on higher
// resolution displays and becomes unnecessary overhead. See also:
// https://en.wikipedia.org/wiki/Subpixel_rendering
// https://www.grc.com/ctwhat.htm
// https://www.grc.com/cttech.htm
procedure DrawPolygon_ClearType(img: TImage32; const polygons: TPathsD;
fillRule: TFillRule; color: TColor32; backColor: TColor32 = clWhite32);
// /////////////////////////////////////////////////////////////////////////
// MISCELLANEOUS FUNCTIONS
// /////////////////////////////////////////////////////////////////////////
procedure ErasePolygon(img: TImage32; const polygon: TPathD;
fillRule: TFillRule); overload;
procedure ErasePolygon(img: TImage32; const polygons: TPathsD;
fillRule: TFillRule); overload;
// Both DrawBoolMask and DrawAlphaMask require
// 'mask' length to equal 'img' width * height
procedure DrawBoolMask(img: TImage32;
const mask: TArrayOfByte; color: TColor32 = clBlack32);
procedure DrawAlphaMask(img: TImage32;
const mask: TArrayOfByte; color: TColor32 = clBlack32);
procedure Rasterize(const paths: TPathsD;
const clipRec: TRect; fillRule: TFillRule; renderer: TCustomRenderer);
implementation
{$IFDEF MemCheck}
resourcestring
sMemCheckError = 'Img32.Draw: Memory allocation error';
{$ENDIF}
type
// A horizontal scanline contains any number of line fragments. A fragment
// can be a number of pixels wide but it can't be more than one pixel high.
// TFragment = record
// botX, topX, dy, dydx: double; // ie x at bottom and top of scanline
// end;
TScanLine = record
Y: integer;
minX, maxX: integer;
fragCnt: integer;
{$IFDEF MemCheck} total: integer; {$ENDIF}
fragOffset: integer;
end;
PScanline = ^TScanline;
TArrayOfScanline = array of TScanline;
// ------------------------------------------------------------------------------
// ApplyClearType (see DrawPolygon_ClearType below)
// ------------------------------------------------------------------------------
type
PArgbs = ^TArgbs;
TArgbs = array [0.. (Maxint div SizeOf(TARGB)) -1] of TARGB;
procedure ApplyClearType(img: TImage32; textColor: TColor32 = clBlack32;
bkColor: TColor32 = clWhite32);
const
centerWeighting = 5; //0 <= centerWeighting <= 25
var
h, w: integer;
src, dst: PARGB;
srcArr: PArgbs;
fgColor: TARGB absolute textColor;
bgColor: TARGB absolute bkColor;
diff_R, diff_G, diff_B: integer;
bg8_R, bg8_G, bg8_B: integer;
rowBuffer: TArrayOfARGB;
primeTbl, nearTbl, FarTbl: PByteArray;
begin
// Precondition: the background to text drawn onto 'img' must be transparent
// 85 + (2 * 57) + (2 * 28) == 255
primeTbl := PByteArray(@MulTable[85 + centerWeighting *2]);
nearTbl := PByteArray(@MulTable[57]);
farTbl := PByteArray(@MulTable[28 - centerWeighting]);
SetLength(rowBuffer, img.Width +4);
for h := 0 to img.Height -1 do
begin
// each row of the image is copied into a temporary buffer ...
// noting that while 'dst' (img.Pixels) is initially the source
// it will later be destination (during image compression).
dst := PARGB(@img.Pixels[h * img.Width]);
src := PARGB(@rowBuffer[2]);
Move(dst^, src^, img.Width * SizeOf(TColor32));
srcArr := PArgbs(rowBuffer);
// using this buffer compress the image ...
w := 2;
while w < img.Width do
begin
dst.R := primeTbl[srcArr[w].A] +
nearTbl[srcArr[w-1].A] + farTbl[srcArr[w-2].A] +
nearTbl[srcArr[w+1].A] + farTbl[srcArr[w+2].A];
inc(w);
dst.G := primeTbl[srcArr[w].A] +
nearTbl[srcArr[w-1].A] + farTbl[srcArr[w-2].A] +
nearTbl[srcArr[w+1].A] + farTbl[srcArr[w+2].A];
inc(w);
dst.B := primeTbl[srcArr[w].A] +
nearTbl[srcArr[w-1].A] + farTbl[srcArr[w-2].A] +
nearTbl[srcArr[w+1].A] + farTbl[srcArr[w+2].A];
inc(w);
dst.A := 255;
inc(dst);
end;
end;
// Following compression the right 2/3 of the image is redundant
img.Crop(Types.Rect(0,0, img.Width div 3, img.Height));
// currently text is white and the background is black
// so blend in the text and background colors ...
diff_R := fgColor.R - bgColor.R;
diff_G := fgColor.G - bgColor.G;
diff_B := fgColor.B - bgColor.B;
bg8_R := bgColor.R shl 8;
bg8_G := bgColor.G shl 8;
bg8_B := bgColor.B shl 8;
dst := PARGB(img.PixelBase);
for h := 0 to img.Width * img.Height -1 do
begin
if dst.R = 0 then
dst.Color := bkColor
else
begin
// blend front (text) and background colors ...
dst.R := (bg8_R + diff_R * dst.R) shr 8;
dst.G := (bg8_G + diff_G * dst.G) shr 8;
dst.B := (bg8_B + diff_B * dst.B) shr 8;
end;
inc(dst);
end;
end;
// ------------------------------------------------------------------------------
// Other miscellaneous functions
// ------------------------------------------------------------------------------
// //__Trunc: An efficient Trunc() algorithm (ie rounds toward zero)
// function __Trunc(val: double): integer; {$IFDEF INLINE} inline; {$ENDIF}
// var
// exp: integer;
// i64: UInt64 absolute val;
// begin
// //https://en.wikipedia.org/wiki/Double-precision_floating-point_format
// Result := 0;
// if i64 = 0 then Exit;
// exp := Integer(Cardinal(i64 shr 52) and $7FF) - 1023;
// //nb: when exp == 1024 then val == INF or NAN.
// if exp < 0 then
// Exit
// else if exp > 52 then
// Result := ((i64 and $1FFFFFFFFFFFFF) shl (exp - 52)) or (UInt64(1) shl exp)
// else
// Result := ((i64 and $1FFFFFFFFFFFFF) shr (52 - exp)) or (UInt64(1) shl exp);
// if val < 0 then Result := -Result;
// end;
// ------------------------------------------------------------------------------
function ClampByte(val: double): byte; {$IFDEF INLINE} inline; {$ENDIF}
begin
if val < 0 then result := 0
else if val > 255 then result := 255
else result := Round(val);
end;
// ------------------------------------------------------------------------------
function GetPixel(current: PARGB; delta: integer): PARGB;
{$IFDEF INLINE} inline; {$ENDIF}
begin
Result := current;
inc(Result, delta);
end;
// ------------------------------------------------------------------------------
function ReverseColors(const colors: TArrayOfGradientColor): TArrayOfGradientColor;
var
i, highI: integer;
begin
highI := High(colors);
SetLength(result, highI +1);
for i := 0 to highI do
begin
result[i].color := colors[highI -i].color;
result[i].offset := 1 - colors[highI -i].offset;
end;
end;
// ------------------------------------------------------------------------------
procedure SwapColors(var color1, color2: TColor32);
var
c: TColor32;
begin
c := color1;
color1 := color2;
color2 := c;
end;
// ------------------------------------------------------------------------------
procedure SwapPoints(var point1, point2: TPoint); overload;
var
pt: TPoint;
begin
pt := point1;
point1 := point2;
point2 := pt;
end;
// ------------------------------------------------------------------------------
procedure SwapPoints(var point1, point2: TPointD); overload;
var
pt: TPointD;
begin
pt := point1;
point1 := point2;
point2 := pt;
end;
// ------------------------------------------------------------------------------
function ClampQ(q, endQ: integer): integer;
begin
if q < 0 then result := 0
else if q >= endQ then result := endQ -1
else result := q;
end;
// ------------------------------------------------------------------------------
function ClampD(d: double; colorCnt: integer): integer;
begin
dec(colorCnt);
if d < 0 then result := 0
else if d >= 1 then result := colorCnt
else result := Round(d * colorCnt);
end;
// ------------------------------------------------------------------------------
function MirrorQ(q, endQ: integer): integer;
begin
result := q mod endQ;
if (result < 0) then result := -result;
if Odd(q div endQ) then
result := (endQ -1) - result;
end;
// ------------------------------------------------------------------------------
function MirrorD(d: double; colorCnt: integer): integer;
begin
dec(colorCnt);
if Odd(Round(d)) then
result := Round((1 - frac(d)) * colorCnt) else
result := Round(frac(d) * colorCnt);
end;
// ------------------------------------------------------------------------------
function RepeatQ(q, endQ: integer): integer;
begin
if (q < 0) or (q >= endQ) then
begin
endQ := Abs(endQ);
result := q mod endQ;
if result < 0 then inc(result, endQ);
end
else result := q;
end;
// ------------------------------------------------------------------------------
function SoftRptQ(q, endQ: integer): integer;
begin
if (q < 0) then
result := endQ + (q mod endQ) else
result := (q mod endQ);
if result = 0 then result := endQ div 2;
end;
// ------------------------------------------------------------------------------
function RepeatD(d: double; colorCnt: integer): integer;
begin
dec(colorCnt);
if (d < 0) then
result := Round((1 + frac(d)) * colorCnt) else
result := Round(frac(d) * colorCnt);
end;
// ------------------------------------------------------------------------------
function BlendColorUsingMask(bgColor, fgColor: TColor32; mask: Byte): TColor32;
var
bg: TARGB absolute bgColor;
fg: TARGB absolute fgColor;
res: TARGB absolute Result;
R, invR: PByteArray;
begin
if fg.A = 0 then
begin
Result := bgColor;
res.A := MulBytes(res.A, not mask);
end
else if bg.A = 0 then
begin
Result := fgColor;
res.A := MulBytes(res.A, mask);
end
else if (mask = 0) then
Result := bgColor
else if (mask = 255) then
Result := fgColor
else
begin
R := PByteArray(@MulTable[mask]);
InvR := PByteArray(@MulTable[not mask]);
res.A := R[fg.A] + InvR[bg.A];
res.R := R[fg.R] + InvR[bg.R];
res.G := R[fg.G] + InvR[bg.G];
res.B := R[fg.B] + InvR[bg.B];
end;
end;
// ------------------------------------------------------------------------------
// MakeColorGradient: using the supplied array of TGradientColor,
// create an array of TColor32 of the specified length
function MakeColorGradient(const gradColors: TArrayOfGradientColor;
len: integer): TArrayOfColor32;
var
i,j, lenC: integer;
dist, offset1, offset2, step, pos: double;
color1, color2: TColor32;
begin
lenC := length(gradColors);
if (len = 0) or (lenC < 2) then Exit;
SetLength(result, len);
color2 := gradColors[0].color;
result[0] := color2;
if len = 1 then Exit;
step := 1/(len-1);
pos := step;
offset2 := 0;
i := 1; j := 1;
repeat
offset1 := offset2;
offset2 := gradColors[i].offset;
dist := offset2 - offset1;
color1 := color2;
color2 := gradColors[i].color;
while (pos <= dist) and (j < len) do
begin
result[j] := BlendColorUsingMask(color1, color2, Round(pos/dist * 255));
inc(j);
pos := pos + step;
end;
pos := pos - dist;
inc(i);
until i = lenC;
if j < len then result[j] := result[j-1];
end;
// ------------------------------------------------------------------------------
// Rasterize() support functions
// ------------------------------------------------------------------------------
procedure AllocateScanlines(const polygons: TPathsD;
var scanlines: TArrayOfScanline; out fragments: PDouble; clipBottom, clipRight: integer);
var
i,j, highI, highJ: integer;
y1, y2: integer;
fragOff: Cardinal;
psl: PScanline;
begin
// first count how often each edge intersects with each horizontal scanline
for i := 0 to high(polygons) do
begin
highJ := high(polygons[i]);
if highJ < 2 then continue;
y1 := Round(polygons[i][highJ].Y);
for j := 0 to highJ do
begin
y2 := Round(polygons[i][j].Y);
if y1 < y2 then
begin
// descending (but ignore edges outside the clipping range)
if (y2 >= 0) and (y1 <= clipBottom) then
begin
if (y1 > 0) then
dec(scanlines[y1 -1].fragCnt);
if y2 >= clipBottom then
inc(scanlines[clipBottom].fragCnt) else
inc(scanlines[y2].fragCnt);
end;
end else
begin
// ascending (but ignore edges outside the clipping range)
if (y1 >= 0) and (y2 <= clipBottom) then
begin
if (y2 > 0) then
dec(scanlines[y2 -1].fragCnt);
if y1 >= clipBottom then
inc(scanlines[clipBottom].fragCnt) else
inc(scanlines[y1].fragCnt);
end;
end;
y1 := y2;
end;
end;
// convert 'count' accumulators into real counts and allocate storage
j := 0;
fragOff := 0;
highI := high(scanlines);
psl := @scanlines[highI];
// 'fragments' is a pointer and not a dynamic array because
// dynamic arrays are zero initialized (hence slower than GetMem).
for i := highI downto 0 do
begin
inc(j, psl.fragCnt); // nb: psl.fragCnt may be < 0 here!
if j > 0 then
begin
psl.fragOffset := fragOff;
inc(fragOff, j * 4); // 4 doubles are needed for each fragment
end else
psl.fragOffset := -1;
{$IFDEF MemCheck} psl.total := j; {$ENDIF}
psl.fragCnt := 0; // reset for later
psl.minX := clipRight;
psl.maxX := 0;
psl.Y := i;
dec(psl);
end;
// allocate fragments as a single block of memory
GetMem(fragments, fragOff * sizeOf(Double));
end;
// ------------------------------------------------------------------------------
procedure SplitEdgeIntoFragments(const pt1, pt2: TPointD;
const scanlines: TArrayOfScanline; fragments: PDouble; const clipRec: TRect);
var
x,y, dx,dy, absDx, dydx, dxdy: double;
i, scanlineY, maxY, maxX: integer;
psl: PScanLine;
pFrag: PDouble;
bot, top: TPointD;
begin
dy := pt1.Y - pt2.Y;
dx := pt2.X - pt1.X;
RectWidthHeight(clipRec, maxX, maxY);
absDx := abs(dx);
if dy > 0 then
begin
// ASCENDING EDGE (+VE WINDING DIR)
if dy < 0.0001 then Exit; //ignore near horizontals
bot := pt1; top := pt2;
// exclude edges that are completely outside the top or bottom clip region
if (top.Y >= maxY) or (bot.Y <= 0) then Exit;
end else
begin
// DESCENDING EDGE (-VE WINDING DIR)
if dy > -0.0001 then Exit; //ignore near horizontals
bot := pt2; top := pt1;
// exclude edges that are completely outside the top or bottom clip region
if (top.Y >= maxY) or (bot.Y <= 0) then Exit;
end;
if absDx < 0.000001 then
begin
// VERTICAL EDGE
top.X := bot.X; //this circumvents v. rare rounding issues.
// exclude vertical edges that are outside the right clip region
// but still update maxX for each scanline the edge passes
if bot.X > maxX then
begin
for i := Min(maxY, Round(bot.Y)) downto Max(0, Round(top.Y)) do
scanlines[i].maxX := maxX;
Exit;
end;
dxdy := 0;
if dy > 0 then dydx := 1 else dydx := -1;
end else
begin
dxdy := dx/dy;
dydx := dy/absDx;
end;
// TRIM EDGES THAT CROSS CLIPPING BOUNDARIES (EXCEPT THE LEFT BOUNDARY)
if bot.X >= maxX then
begin
if top.X >= maxX then
begin
for i := Min(maxY, Round(bot.Y)) downto Max(0, Round(top.Y)) do
scanlines[i].maxX := maxX;
Exit;
end;
// here the edge must be oriented bottom-right to top-left
y := bot.Y - (bot.X - maxX) * Abs(dydx);
for i := Min(maxY, Round(bot.Y)) downto Max(0, Round(y)) do
scanlines[i].maxX := maxX;
bot.Y := y;
if bot.Y <= 0 then Exit;
bot.X := maxX;
end
else if top.X > maxX then
begin
// here the edge must be oriented bottom-left to top-right
y := top.Y + (top.X - maxX) * Abs(dydx);
for i := Min(maxY, Round(y)) downto Max(0, Round(top.Y)) do
scanlines[i].maxX := maxX;
top.Y := y;
if top.Y >= maxY then Exit;
top.X := maxX;
end;
if bot.Y > maxY then
begin
bot.X := bot.X + dxdy * (bot.Y - maxY);
if (bot.X > maxX) then Exit; //nb: no clipping on the left
bot.Y := maxY;
end;
if top.Y < 0 then
begin
top.X := top.X + (dxdy * top.Y);
if (top.X > maxX) then Exit; //nb: no clipping on the left
top.Y := 0;
end;
// SPLIT THE EDGE INTO MULTIPLE SCANLINE FRAGMENTS
scanlineY := Round(bot.Y);
if bot.Y = scanlineY then dec(scanlineY);
// at the lower-most extent of the edge 'split' the first fragment
if scanlineY < 0 then Exit;
psl := @scanlines[scanlineY];
if psl.fragOffset < 0 then Exit; //a very rare event
{$IFDEF MemCheck}
if psl.fragCnt = psl.total then raise Exception.Create(sMemCheckError);
{$ENDIF}
pFrag := fragments;
inc(pFrag, psl.fragOffset + psl.fragCnt * 4);
inc(psl.fragCnt);
pFrag^ := bot.X; inc(pFrag);
if scanlineY <= top.Y then
begin
// the whole edge is within 1 scanline
pFrag^ := top.X; inc(pFrag);
pFrag^ := bot.Y - top.Y; inc(pFrag);
pFrag^ := dydx;
Exit;
end;
x := bot.X + (bot.Y - scanlineY) * dxdy;
pFrag^ := x; inc(pFrag);
pFrag^ := bot.Y - scanlineY; inc(pFrag);
pFrag^ := dydx;
// 'split' subsequent fragments until the top fragment
dec(psl);
while psl.Y > top.Y do
begin
{$IFDEF MemCheck}
if psl.fragCnt = psl.total then raise Exception.Create(sMemCheckError);
{$ENDIF}
pFrag := fragments;
inc(pFrag, psl.fragOffset + psl.fragCnt * 4);
inc(psl.fragCnt);
pFrag^ := x; inc(pFrag);
x := x + dxdy;
pFrag^ := x; inc(pFrag);
pFrag^ := 1; inc(pFrag);
pFrag^ := dydx;
dec(psl);
end;
// and finally the top fragment
{$IFDEF MemCheck}
if psl.fragCnt = psl.total then raise Exception.Create(sMemCheckError);
{$ENDIF}
pFrag := fragments;
inc(pFrag, psl.fragOffset + psl.fragCnt * 4);
inc(psl.fragCnt);
pFrag^ := x; inc(pFrag);
pFrag^ := top.X; inc(pFrag);
pFrag^ := psl.Y + 1 - top.Y; inc(pFrag);
pFrag^ := dydx;
end;
// ------------------------------------------------------------------------------
procedure InitializeScanlines(var polygons: TPathsD;
const scanlines: TArrayOfScanline; fragments: PDouble; const clipRec: TRect);
var
i,j, highJ: integer;
pt1, pt2: PPointD;
begin
for i := 0 to high(polygons) do
begin
highJ := high(polygons[i]);
if highJ < 2 then continue;
pt1 := @polygons[i][highJ];
pt2 := @polygons[i][0];
for j := 0 to highJ do
begin
SplitEdgeIntoFragments(pt1^, pt2^, scanlines, fragments, clipRec);
pt1 := pt2;
inc(pt2);
end;
end;
end;
// ------------------------------------------------------------------------------
procedure ProcessScanlineFragments(var scanline: TScanLine;
fragments: PDouble; var buffer: TArrayOfDouble);
var
i,j, leftXi,rightXi: integer;
fracX, yy, q, windDir: double;
left, right, dy, dydx: double;
pd, frag: PDouble;
begin
frag := fragments;
inc(frag, scanline.fragOffset);
for i := 1 to scanline.fragCnt do
begin
left := frag^; inc(frag); //botX
right := frag^; inc(frag); //topX
dy := frag^; inc(frag);
dydx := frag^; inc(frag);
// converting botX & topX to left & right simplifies code
if {botX > topX} left > right then
begin
q := left;
left := right;
right := q;
end;
leftXi := Max(0, Round(left));
rightXi := Max(0, Round(right));
if (leftXi = rightXi) then
begin
if dydx < 0 then windDir := -1.0 else windDir := 1.0;
// the fragment is only one pixel wide
if leftXi < scanline.minX then
scanline.minX := leftXi;
if rightXi > scanline.maxX then
scanline.maxX := rightXi;
pd := @buffer[leftXi];
if (left <= 0) then
begin
pd^ := pd^ + dy * windDir;
end else
begin
q := (left + right) * 0.5 - leftXi;
pd^ := pd^ + (1-q) * dy * windDir;
inc(pd);
pd^ := pd^ + q * dy * windDir;
end;
end else
begin
if leftXi < scanline.minX then
scanline.minX := leftXi;
if rightXi > scanline.maxX then
scanline.maxX := rightXi;
pd := @buffer[leftXi];
// left pixel
fracX := leftXi + 1 - left;
yy := dydx * fracX;
q := fracX * yy * 0.5;
pd^ := pd^ + q;
q := yy - q;
inc(pd);
// middle pixels
for j := leftXi +1 to rightXi -1 do
begin
pd^ := pd^ + q + dydx * 0.5;
q := dydx * 0.5;
inc(pd);
end;
// right pixel
fracX := right - rightXi;
yy := fracX * dydx;
pd^ := pd^ + q + (1 - fracX * 0.5) * yy;
inc(pd);
// overflow
pd^ := pd^ + fracX * 0.5 * yy;
end;
end;
end;
// ------------------------------------------------------------------------------
{$IFNDEF TROUNDINGMODE}
type
TRoundingMode = {$IFNDEF FPC}Math.{$ENDIF}TFPURoundingMode;
{$ENDIF}
procedure Rasterize(const paths: TPathsD; const clipRec: TRect;
fillRule: TFillRule; renderer: TCustomRenderer);
var
i,j, xli,xri, maxW, maxH, aa: integer;
clipRec2: TRect;
paths2: TPathsD;
accum: double;
windingAccum: TArrayOfDouble;
byteBuffer: TArrayOfByte;
scanlines: TArrayOfScanline;
fragments: PDouble;
scanline: PScanline;
savedRoundMode: TRoundingMode;
begin
// See also https://nothings.org/gamedev/rasterize/
if not assigned(renderer) then Exit;
Types.IntersectRect(clipRec2, clipRec, GetBounds(paths));
if IsEmptyRect(clipRec2) then Exit;