forked from mypaint/mypaint
/
pyramidfill.cpp
1745 lines (1583 loc) · 51.8 KB
/
pyramidfill.cpp
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
/* This file is part of MyPaint.
* Copyright (C) 2017 by dothiko<dothiko@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include "pyramidfill.hpp"
#include "pyramidworkers.hpp"
#include "common.hpp"
#include "fix15.hpp"
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#define NO_IMPORT_ARRAY
#include <numpy/arrayobject.h>
#include <mypaint-tiled-surface.h>
#include <math.h>
#include <glib.h>
#define TILE_SIZE MYPAINT_TILE_SIZE
//// Struct definition
//-----------------------------------------------------------------------------
//// Function definition
// XXX borrowed from `_floodfill_color_match` of lib/fill.cpp. almost same.
static inline fix15_t
floodfill_color_match(const fix15_short_t c1_premult[4],
const fix15_short_t c2_premult[4],
const fix15_t tolerance)
{
const fix15_short_t c1_a = c1_premult[3];
fix15_short_t c1[] = {
fix15_short_clamp(c1_a <= 0 ? 0 : fix15_div(c1_premult[0], c1_a)),
fix15_short_clamp(c1_a <= 0 ? 0 : fix15_div(c1_premult[1], c1_a)),
fix15_short_clamp(c1_a <= 0 ? 0 : fix15_div(c1_premult[2], c1_a)),
fix15_short_clamp(c1_a),
};
const fix15_short_t c2_a = c2_premult[3];
fix15_short_t c2[] = {
fix15_short_clamp(c2_a <= 0 ? 0 : fix15_div(c2_premult[0], c2_a)),
fix15_short_clamp(c2_a <= 0 ? 0 : fix15_div(c2_premult[1], c2_a)),
fix15_short_clamp(c2_a <= 0 ? 0 : fix15_div(c2_premult[2], c2_a)),
fix15_short_clamp(c2_a),
};
// Calculate the raw distance
fix15_t dist = 0;
for (int i=0; i<4; ++i) {
fix15_t n = (c1[i] > c2[i]) ? (c1[i] - c2[i]) : (c2[i] - c1[i]);
if (n > dist)
dist = n;
}
/*
* // Alternatively, could use
* fix15_t sumsqdiffs = 0;
* for (int i=0; i<4; ++i) {
* fix15_t n = (c1[i] > c2[i]) ? (c1[i] - c2[i]) : (c2[i] - c1[i]);
* n >>= 2; // quarter, to avoid a fixed maths sqrt() overflow
* sumsqdiffs += fix15_mul(n, n);
* }
* dist = fix15_sqrt(sumsqdiffs) << 1; // [0.0 .. 0.5], doubled
* // but the MAX()-based metric will a) be more GIMP-like and b) not
* // lose those two bits of precision.
*/
// Compare with adjustable tolerance of mismatches.
static const fix15_t onepointfive = fix15_one + fix15_halve(fix15_one);
if (tolerance > 0) {
dist = fix15_div(dist, tolerance);
if (dist > onepointfive) { // aa < 0, but avoid underflow
return 0;
}
else {
fix15_t aa = onepointfive - dist;
if (aa < fix15_halve(fix15_one))
return fix15_short_clamp(fix15_double(aa));
else
return fix15_one;
}
}
else {
if (dist > tolerance)
return 0;
else
return fix15_one;
}
}
#ifdef HEAVY_DEBUG
// To share same check code
void
assert_tile(PyArrayObject* array) {
assert(PyArray_Check(array));
// We need to check/assert mypaint color tile with this function,
// so we MUST use TILE_SIZE here, explicitly.
assert(PyArray_DIM(array, 0) == TILE_SIZE);
assert(PyArray_DIM(array, 1) == TILE_SIZE);
assert(PyArray_DIM(array, 2) == 4);
assert(PyArray_TYPE(array) == NPY_UINT16);
assert(PyArray_ISCARRAY(array));
}
#endif
//-----------------------------------------------------------------------------
//// Class definition
//
// FYC, Base worker classes are defined at lib/profilldefine.hpp
// And most of derived worker classes are defined at lib/pyramidworkers.hpp
//----------------------------------------------------------------------------
/// KernelWorker
//// Shared empty tile related.
Flagtile *KernelWorker::m_shared_empty = NULL;
Flagtile*
KernelWorker::get_shared_empty()
{
if (m_shared_empty == NULL)
m_shared_empty = new Flagtile(PIXEL_EMPTY);
return m_shared_empty;
}
bool
KernelWorker::sync_shared_empty(const int level)
{
if (!m_shared_empty->is_filled_with(level, PIXEL_EMPTY)) {
m_shared_empty = NULL;
return true;
}
return false;
}
// Call this from FlagtileSurface destructor.
void
KernelWorker::free_shared_empty()
{
delete m_shared_empty;
m_shared_empty = NULL;
}
void
KernelWorker::set_target_level(const int level)
{
#ifdef HEAVY_DEBUG
assert(level >= 0);
assert(level <= MAX_PYRAMID);
#endif
m_level = level;
}
// We can enumerate kernel window(surrounding) 4 pixels with for-loop
// by these offset, in the order of
//
// TOP, RIGHT, BOTTOM, LEFT (i.e. clockwise).
//
// Derived from WalkingKernel(especially AntialiasWalker) depends
// the order of this offsets.
// DO NOT CHANGE THIS ORDER.
const int KernelWorker::xoffset[] = { 0, 1, 0, -1};
const int KernelWorker::yoffset[] = {-1, 0, 1, 0};
// Wrapper method to get pixel with direction.
uint8_t
KernelWorker::get_pixel_with_direction(const int sx, const int sy,
const int direction)
{
return m_surf->get_pixel(
m_level,
sx + xoffset[direction],
sy + yoffset[direction]
);
}
//--------------------------------------
//// WalkingKernel class
// Rotate to right.
// This is used when we missed wall at right-hand.
void
WalkingKernel::rotate_left()
{
// We need update current direction
// before call rotation handler.
m_cur_dir = get_hand_dir(m_cur_dir);
on_rotate_cb(false);
}
// Rotate to left.
// This is used when we face `wall`
void
WalkingKernel::rotate_right()
{
// We need update current direction
// before call rotation handler
m_cur_dir = get_reversed_hand_dir(m_cur_dir);
m_right_rotate_cnt++;
on_rotate_cb(true);
}
bool
WalkingKernel::forward()
{
uint8_t pix;
// see front.
pix = get_front_pixel();
if (is_wall_pixel(pix)) {
// Face to wall.
// Now, we must turn left.
// With this turn, this kernel draws antialias line or
// initialize internal status of this object.
rotate_right();
if (m_right_rotate_cnt >= 4)
return false; // Exit from infnite loop of 1px hole!
}
else {
// Then, forward.
int nx = m_x + xoffset[m_cur_dir];
int ny = m_y + yoffset[m_cur_dir];
// Refreshing clockwise counter.
// Algorithm from
// https://stackoverflow.com/questions/1165647/how-to-determine-if-a-list-of-polygon-points-are-in-clockwise-order
// XXX CAUTION: mypaint uses inverted Cartesian coordinate system,
// so the result is also inverted.
// when m_clockwise_cnt is negative or zero, that area should be clockwise.
m_clockwise_cnt += (nx - m_x) * (ny + m_y);
m_x = nx;
m_y = ny;
m_step++;
m_right_rotate_cnt = 0;
if (m_x == m_ox && m_y == m_oy) {
return false; // Walking end!!
}
on_new_pixel();
}
return true;
}
// Walk single step.
// when end walking, return false.
bool
WalkingKernel::proceed()
{
if (!is_wall_pixel(get_hand_pixel())) {
// Right hand of kernel misses the wall.
// Couldn't forward.
rotate_left();
}
return forward();
}
void
WalkingKernel::walk(const int sx, const int sy, const int direction)
{
#ifdef HEAVY_DEBUG
unsigned int cnt = 0;
#endif
m_ox = sx;
m_oy = sy;
m_x = sx;
m_y = sy;
m_step = 1;
m_right_rotate_cnt = 0;
m_clockwise_cnt = 0;
m_cur_dir = direction;
// walk into staring point pixel.
on_new_pixel();
while (proceed()) {
#ifdef HEAVY_DEBUG
cnt++;
// `Walking over 100 million pixel` cannot happen.
// It would be infinite loop bug.
assert(cnt < 100000000);
#endif
}
}
//--------------------------------------
//// Flagtile
const int
Flagtile::m_buf_offsets[MAX_PYRAMID+1] = {
// pyramid level 0: 64x64(TILE_SIZE * TILE_SIZE), start from 0.
0,
PYRAMID_BUF_SIZE(0),
Flagtile::m_buf_offsets[1] + PYRAMID_BUF_SIZE(1),
Flagtile::m_buf_offsets[2] + PYRAMID_BUF_SIZE(2),
Flagtile::m_buf_offsets[3] + PYRAMID_BUF_SIZE(3),
Flagtile::m_buf_offsets[4] + PYRAMID_BUF_SIZE(4)
};
Flagtile::Flagtile(const int initial_value)
: m_npbuf(NULL),
m_statflag(0)
{
m_buf = new uint8_t[FLAGTILE_BUF_SIZE];
fill(initial_value);
}
Flagtile::~Flagtile()
{
if (m_npbuf != NULL)
Py_DECREF(m_npbuf);
delete[] m_buf;
}
void
Flagtile::propagate_upward_single(const int targ_level)
{
#ifdef HEAVY_DEBUG
assert(targ_level >= 1);
#endif
int c_size = PYRAMID_TILE_SIZE(targ_level);
int b_level = targ_level - 1;
// XXX To maximize parallel processing effeciency,
// not using omp here.
// It is done at FlagtileSurface::propagate_upward.
for (int y=0; y < c_size; y++) {
for (int x=0; x < c_size; x++) {
// The pyramid level beneath is always
// double sized of current level.
int bbx = x << 1;
int bby = y << 1;
uint8_t new_pixel = PIXEL_EMPTY;
// process chunk of pixels, like `pooling`
for (int by=0; by < 2; by++) {
for (int bx=0; bx < 2; bx++) {
uint8_t pix = get(b_level, bbx+bx, bby+by) & PIXEL_MASK;
switch(pix) {
case PIXEL_CONTOUR:
case PIXEL_OVERWRAP:
// Prior to every other pixels.
new_pixel = PIXEL_CONTOUR;
goto exit_pixel_loop;
case PIXEL_AREA:
new_pixel = PIXEL_AREA;
break;
case PIXEL_RESERVE:
if (new_pixel == PIXEL_EMPTY)
new_pixel = PIXEL_RESERVE;
break;
}
}
}
exit_pixel_loop:
if (new_pixel != PIXEL_EMPTY) {
replace(
targ_level,
x, y,
new_pixel
);
}
}
}// Tile processing end
}
void
Flagtile::propagate_upward(const int max_level)
{
#ifdef HEAVY_DEBUG
assert(max_level >= 1);
assert(max_level <= MAX_PYRAMID);
#endif
if (is_filled_with(0, PIXEL_INVALID))
return; // There is nothing to do for empty tile.
// In this stage, when the all of level-0 pixels are filled with same value
// , but it might not be filled above level 0.
// So, ensure the filled pixels such case.
if (is_filled_with(0, PIXEL_AREA)) {
if (get(max_level, 0, 0) != PIXEL_AREA)
fill(PIXEL_AREA);
}
else if (is_filled_with(0, PIXEL_CONTOUR)) {
if (get(max_level, 0, 0) != PIXEL_CONTOUR)
fill(PIXEL_CONTOUR);
}
else if (is_filled_with(0, PIXEL_OUTSIDE)) {
if (get(max_level, 0, 0) != PIXEL_OUTSIDE)
fill(PIXEL_OUTSIDE);
}
else {
for(int i=1;i <= max_level; i++) {
propagate_upward_single(i);
}
}
}
/**
* @convert_from_color
* convert color-tile into flagtile.
*
* @param tolerance Color-space tolerance of fillable area.
* @param alpha_threshold Fillable pixel threshould, in alpha component.
* @param limit_within_opaque If true, generate contour pixel even transparent pixel.
*
* Convert color-tile into flagtile, to decide contour pixel.
* With a certain brush preset, freehand tool would draw almost invisible strokes
* even no stylus pressure is applied.
* It is difficult to reject such pixels with `tolerance` option.
* So, in addition to `tolerance`, use this parameter.
* Practically, alpha_threshold value is enough around 0.03.
*/
void
Flagtile::convert_from_color(PyObject *py_src_tile,
const int targ_r,
const int targ_g,
const int targ_b,
const int targ_a,
const double tolerance,
const double alpha_threshold,
const bool limit_within_opaque)
{
PyArrayObject *array = (PyArrayObject*)py_src_tile;
#ifdef HEAVY_DEBUG
assert_tile(array);
#endif
const unsigned int xstride = PyArray_STRIDE(array, 1) / sizeof(fix15_short_t);
const unsigned int ystride = PyArray_STRIDE(array, 0) / sizeof(fix15_short_t);
fix15_short_t *bptr = (fix15_short_t*)PyArray_BYTES(array);
const fix15_short_t targ[4] = {
fix15_short_clamp(targ_r),
fix15_short_clamp(targ_g),
fix15_short_clamp(targ_b),
fix15_short_clamp(targ_a)
};
fix15_t f15_tolerance = (fix15_t)(tolerance * (double)fix15_one);
fix15_t f15_threshold = (fix15_t)(alpha_threshold * (double)fix15_one);
#pragma omp parallel for
for(int y=0; y<TILE_SIZE; y++) {
fix15_short_t *cptr = bptr + y * ystride;
for(int x=0; x<TILE_SIZE; x++) {
uint8_t pix = get(0, x, y);
fix15_t alpha = (fix15_t)cptr[3];
if (!limit_within_opaque || alpha > 0) {
// Only some `basic pixel` (not PIXEL_EMPTY,
// such as PIXEL_AREA or PIXEL_OUTSIDE)
// should be convertable.
if (pix != PIXEL_EMPTY && alpha >= f15_threshold) {
fix15_t match = floodfill_color_match(
targ, cptr,
f15_tolerance
);
if (match == 0) {
replace(0, x, y, PIXEL_CONTOUR);
}
}
}
/*
else {
// Code reaches here when
// limit_within_opaque is true and current pixel
// is completely transparent.
if (pix != PIXEL_EMPTY) {
replace(0, x, y, PIXEL_EMPTY);
}
}*/
cptr += xstride;
}
}
}
/**
* @convert_to_color
* convert Flagtile to mypaint colortile.
*
* @param py_targ_tile Mypaint colortile(numpy array of uint8)
* @param r,g,b Target pixel color, to be converted from flag.
* @param pixel Value of Flagtile pixel to be converted into mypaint tile.
*
* Convert Flagtile pixel into Mypaint color tile.
* Parameter r,g,b is pixel color. They are floating point value,
* from 0.0 to 1.0.
* This method would also render anti-aliasing pixels into mypaint colortile.
*
* For this method, array of py_targ_tile should be empty(Zero-filled).
* Actual pixel composition against target layer surface is done by
* lib.mypaintlib.combine_tile later.
*/
void
Flagtile::convert_to_color(PyObject *py_targ_tile,
const double r, const double g, const double b,
const int pixel)
{
PyArrayObject *array = (PyArrayObject*)py_targ_tile;
#ifdef HEAVY_DEBUG
assert_tile(array);
#endif
const unsigned int xstride = PyArray_STRIDE(array, 1) / sizeof(fix15_short_t);
const unsigned int ystride = PyArray_STRIDE(array, 0) / sizeof(fix15_short_t);
fix15_short_t *cptr = (fix15_short_t*)PyArray_BYTES(array);
// Premult color pixel array.
fix15_short_t cols[4];
cols[0] = fix15_short_clamp(r * fix15_one);
cols[1] = fix15_short_clamp(g * fix15_one);
cols[2] = fix15_short_clamp(b * fix15_one);
cols[3] = fix15_one;
// Completely filled tile can be filled with memcpy.
// In this stage, we can know it from level 0 pixel count.
if (is_filled_with(0, pixel)) {
fix15_short_t *dptr = cptr;
// Build one line
for(int x=0; x<TILE_SIZE; x++) {
dptr[0] = cols[0];
dptr[1] = cols[1];
dptr[2] = cols[2];
dptr[3] = cols[3];
dptr += xstride;
}
// Just copy that completed line.
int y=1;
while(y < TILE_SIZE) {
dptr = cptr + y * ystride;
memcpy(dptr, cptr, sizeof(fix15_short_t) * 4 * TILE_SIZE * y);
y <<= 1;
}
return;
}
// Converting pyramid level 0 pixel into color tile.
#pragma omp parallel for
for(int y=0; y<TILE_SIZE; y++) {
fix15_short_t *dptr = cptr + y * ystride;
for(int x=0; x<TILE_SIZE; x++) {
uint8_t pix = get(0, x, y);
// At first, We need to check anti-aliasing flag of pixel.
// Anti-aliasing pixel is not compatible
// with another PIXEL_* values.
if ((pix & FLAG_AA) != 0) {
double alpha = get_aa_double_value(pix & AA_MASK);
fix15_short_t cur_alpha = fix15_short_clamp((alpha * fix15_one));
dptr[0] = fix15_short_clamp(r * cur_alpha);
dptr[1] = fix15_short_clamp(g * cur_alpha);
dptr[2] = fix15_short_clamp(b * cur_alpha);
dptr[3] = cur_alpha;
}
else if ((pix & PIXEL_MASK) == pixel) {
dptr[0] = cols[0];
dptr[1] = cols[1];
dptr[2] = cols[2];
dptr[3] = cols[3];
}
dptr += xstride;
}
}
}
/**
* @convert_from_transparency
* convert mypaint colortile to Flagtile, only using alpha pixel value.
*
* @param alpha_threshold Alpha component threshold of target pixel.
* @param pixel_value Replacing pixel value, where colortile alpha pixel exceeds alpha_threshold.
* @param overwrap_value If a pixel has already non-PIXEL_EMPTY value, place this value.
*
* Convert(replace) Mypaint colortile pixels into Flagtile pixels.
* A pixel which has larger alpha value than alpha_threshold is converted to
* pixel_value.
* Also, if there is already non-PIXEL_EMPTY(initial value of Flagtile), that pixel
* To disable overwrap_value, just assign same value with pixel_value.
*/
void
Flagtile::convert_from_transparency(PyObject *py_src_tile,
const double alpha_threshold,
const int pixel_value,
const int overwrap_value)
{
PyArrayObject *array = (PyArrayObject*)py_src_tile;
#ifdef HEAVY_DEBUG
assert_tile(array);
assert(pixel_value <= PIXEL_MASK);
assert(overwrap_value <= PIXEL_MASK);
#endif
const unsigned int xstride = PyArray_STRIDE(array, 1) / sizeof(fix15_short_t);
const unsigned int ystride = PyArray_STRIDE(array, 0) / sizeof(fix15_short_t);
fix15_short_t *cptr_base = (fix15_short_t*)PyArray_BYTES(array);
fix15_short_t threshold = (fix15_short_t)(alpha_threshold * fix15_one);
// Converting pyramid level 0 pixel into color tile.
#pragma omp parallel for
for(int y=0; y<TILE_SIZE; y++) {
fix15_short_t *cptr = cptr_base + y * ystride;
for(int x=0; x<TILE_SIZE; x++) {
if (cptr[3] > threshold) {
if (pixel_value != overwrap_value
&& get(0, x, y) != PIXEL_EMPTY)
replace(0, x, y, (uint8_t)overwrap_value);
else
replace(0, x, y, (uint8_t)pixel_value);
}
cptr += xstride;
}
}
}
void
Flagtile::fill(const uint8_t val)
{
#ifdef HEAVY_DEBUG
assert((val & PIXEL_MASK) == val); // There is no any flag for pixel,
// and also it is not special pixel value.
assert(val <= PIXEL_MASK);
#endif
// Fill only equal and above of assigned level.
memset(m_buf, val, FLAGTILE_BUF_SIZE);
memset(m_pixcnt, 0, sizeof(uint16_t) * PIXEL_MAX * (MAX_PYRAMID + 1));
for(int l=0; l <= MAX_PYRAMID; l++) {
int tile_size = PYRAMID_TILE_SIZE(l);
m_pixcnt[l][val & PIXEL_MASK] = tile_size * tile_size;
}
}
/**
* @to_nparray
* Get internal m_buf buffer as numpy.array
*
* @param readonly Swear that requested object is used as read-only.
* @return numpy array object.
*
* You can get and manipulate m_buf buffer pixel, via numpy API.
* That numpy array is just `view`, and you must discard(or just
* stop using) view-object before this Flagtile instance is released.
*
* Also, you can `swear` that view is used as readonly object.
* Although, actually you are still enable to change numpy-buffer flag and
* write change its contents, do not do it.
*
* Use this method carefully.
*/
PyObject*
Flagtile::lock(const bool readonly)
{
#ifdef HEAVY_DEBUG
assert(m_npbuf == NULL);
#endif
npy_intp dim = FLAGTILE_BUF_SIZE;
m_npbuf = PyArray_SimpleNewFromData(1, &dim, NPY_UINT8, m_buf);
Py_INCREF(m_npbuf);
if (readonly) {
PyArray_CLEARFLAGS((PyArrayObject*)m_npbuf, NPY_ARRAY_WRITEABLE);
}
else {
m_statflag |= COUNT_DIRTY;
}
return m_npbuf;
}
/**
* @unlock
* Return the right of use numpy.array, which came from lock method.
*
* @param nparray The numpy array object, which is generated by lock method.
* @return True when that array object is released.
*
* You MUST call this method if you get a numpy.array object with lock method.
* Use this method carefully.
*/
void
Flagtile::unlock(PyObject *nparray)
{
// Assert strictly, even not in HEAVY_DEBUG.
assert(nparray == m_npbuf);
if (!PyArray_ISWRITEABLE((PyArrayObject*)m_npbuf)) {
// View object might be changed to writable one.
// Force counting flag.
m_statflag |= COUNT_DIRTY;
}
Py_DECREF(m_npbuf);
m_npbuf = NULL;
}
//--------------------------------------
//// FlagtileSurface class.
// psuedo surface object.
// This manages Flagtile objects.
// Default constructor for derive class. actually, do not use.
FlagtileSurface::FlagtileSurface()
: m_tiles(NULL)
{
#ifdef HEAVY_DEBUG
// These are actually `static assert`.
// We MUST exactly compare them with
// MYPAINT_TILE_SIZE, not other macros such as `N` or `TILE_SIZE`.
assert((1 << TILE_LOG) == MYPAINT_TILE_SIZE); // for Flagtile
assert(sizeof(uint64_t) == (MYPAINT_TILE_SIZE/8)); // for EdgeQueue
#endif
}
FlagtileSurface::~FlagtileSurface()
{
for(int i=0; i<m_width*m_height; i++) {
delete m_tiles[i];
}
delete[] m_tiles;
KernelWorker::free_shared_empty();
#ifdef HEAVY_DEBUG
printf("FlagtileSurface destructor called.\n");
#endif
}
//// Internal methods
/**
* @generate_tileptr_buf
* Generate(allocate) tile pointer array buffer.
* Very important method.
*
* @details
* All parameters are in tile-unit.
* ox and oy are the origin point of this surface, in mypaint document(model).
* They are used to converting node positions of mypaint coordinate into
* Flagtilesurface local coodinate.
*
* m_width and m_height are minimum dimension of this surface.
*/
void
FlagtileSurface::generate_tileptr_buf(const int ox, const int oy,
const int w, const int h)
{
#ifdef HEAVY_DEBUG
assert(m_tiles == NULL);
assert(w >= 1);
assert(h >= 1);
#endif
// Make Surface size larger than requested
// by 1 tile for each direction.
// Also, make origin 1 tile smaller.
// Because, Dilation might exceed surface border.
m_ox = ox - 1;
m_oy = oy - 1;
m_width = w + 2;
m_height = h + 2;
m_tiles = new Flagtile*[m_width * m_height];
memset(
m_tiles,
0,
m_width * m_height * sizeof(Flagtile*)
);
}
/**
* @flood_fill
* Do `Flood fill` from
*
* @param level Target pyramid level to doing flood-fill
* @param sx,sy Flood-fill starting point, in pyramid level coordinate.
*
* Call step method of worker for each flood-fill point.
* Algorithm is copied/conveted from fill.cpp, but in this class
* we do not need to access `real` color pixels of mypaint surface.
* So we can complete flood-fill operation only in this class,
* without returning python seed tuples.
*/
void
FlagtileSurface::flood_fill(const int sx, const int sy, Filler* w)
{
const int level = w->get_target_level();
int tile_size = PYRAMID_TILE_SIZE(level);
int tx = sx / tile_size;
int ty = sy / tile_size;
bool request = (w->match(PIXEL_EMPTY));
if (tx < 0 && ty < 0 && tx >= get_width() && ty >= get_height()) {
return;
}
GQueue *queue = g_queue_new();
BorderQueue *q = new BorderQueue(
tx, ty, sx%tile_size, sy%tile_size
);
g_queue_push_tail(queue, q);
while (! g_queue_is_empty(queue)) {
q = (BorderQueue*)g_queue_pop_head(queue);
tx = q->get_tx();
ty = q->get_ty();
#ifdef HEAVY_DEBUG
assert(q != NULL);
assert(tx >= 0 && ty >= 0 && tx < get_width() && ty < get_height());
#endif
Flagtile *t = get_tile(tx, ty, request);
if (t != NULL) {
if (flagtile_flood_fill(t, q, w)) {
for(int i=0; i < 4; i++) {
if (! q->is_empty_queue(i)) {
int ntx = BorderQueue::adjust_tx(tx, i);
int nty = BorderQueue::adjust_ty(ty, i);
if(ntx >= 0 && nty >= 0 && ntx < get_width() && nty < get_height()) {
BorderQueue *nq = new BorderQueue(i, q, ntx, nty);
g_queue_push_tail(queue, nq);
}
}
}
}
}
delete q;
}
g_queue_free(queue);
}
/**
* @filter_tiles
* Internal method of tile pixel iteration.
*
* @param level The target pyramid level.
*
* This internal method is to iterate all pixels to worker classes.
*/
void
FlagtileSurface::filter_tiles(KernelWorker *w)
{
int level = w->get_target_level();
int tile_size = PYRAMID_TILE_SIZE(level);
// This loop would trigger worker-object, which might
// also refer/write pixels all over the FlagtileSurface.
// Furthermore, This method utilize shared-empty tile
// for workers can access even NULL tile area, generate
// new tile on demand seamlessly, without requesting it.
//
// Therefore, we cannot use OpemMP here.
for(int ty=0; ty<m_height; ty++) {
for(int tx=0; tx<m_width; tx++) {
// Get tile.
Flagtile *t = get_tile(tx, ty, false);
bool use_shared = (t==NULL);
if (use_shared)
t = KernelWorker::get_shared_empty();
int bx = tx * tile_size;
int by = ty * tile_size;
if (w->start(t, bx, by)) {
// iterate tile pixel.
for (int y=0; y<tile_size; y++) {
for (int x=0; x<tile_size; x++) {
w->step(t, x, y, bx+x, by+y);
}
}
// iterate tile pixel end.
// As a default, the `end` method
// of KernelWorker would set
// DIRTY stat flag for the tile.
w->end(t);
}
if (use_shared) {
if(KernelWorker::sync_shared_empty(level)) {
m_tiles[get_tile_index(tx, ty)] = t;
}
}
}
}
}
#ifdef _OPENMP
/**
* @filter_tiles_mp
* Internal method of tile pixel iteration, OpenMP enabled version.
*
* @param level The target pyramid level.
*
* This internal method is to iterate all pixels to worker classes.
*
* Different from original filter_tiles, this cannot use
* shared-empty tile. (i.e. NULL empty tile should not be targetted.)
* Also, worker should not change global pixel.
* So very limited worker can use this method.
* Use carefully.
*/
void
FlagtileSurface::filter_tiles_mp(KernelWorker *w)
{
int tile_size = PYRAMID_TILE_SIZE(w->get_target_level());
#pragma omp parallel for
for(int ty=0; ty<m_height; ty++) {
for(int tx=0; tx<m_width; tx++) {
// Get tile.
Flagtile *t = get_tile(tx, ty, false);
int bx = tx * tile_size;
int by = ty * tile_size;
if (t != NULL && w->start(t, bx, by)) {
// iterate tile pixel.
for (int y=0; y<tile_size; y++) {
for (int x=0; x<tile_size; x++) {
w->step(t, x, y, bx+x, by+y);
}
}
// iterate tile pixel end.
// As a default, the `end` method
// of KernelWorker would set
// DIRTY stat flag for the tile.
w->end(t);
}
}
}
}
#endif
/// propagate related.
/**
* @propagate_upward
* The function to build(finalize) propagating pixel seeds.
*
* As first, we would convert color tiles into each Flagtiles
* at pyramid-level 0.
* And register such tiles into FlagtileSurface,
* Then, call this method to `propagate` pixel upward and create
* pyramid level.
* `propagate` of this functionality is simular to so called
* `max pooling`.
*
* Before this method called, polygon rendering(with FLAG_AREA)
* should be completed.
*/
void
FlagtileSurface::propagate_upward(const int max_level)
{
#ifdef HEAVY_DEBUG
assert(max_level <= MAX_PYRAMID);
#endif
#pragma omp parallel for
for(int ty=0; ty<m_height; ty++) {
for(int tx=0; tx<m_width; tx++) {
Flagtile *t = get_tile(tx, ty, false);
if (t == NULL) {
continue;
}
t->propagate_upward(max_level);
}
}
}
/**
* @propagate_downwards
* The interface method of doing downward-propagation of
* decided pixels.
*
* @detail
* With propagation of this method, we can reshape target filling area
* progressively into downward pyramid-level.
* Actual pixel manipulation(deciding the filling area) is done in
* PropagateKernel class.
*/
void
FlagtileSurface::propagate_downward(const int level, const bool expand_outside)
{
#ifdef HEAVY_DEBUG
assert(level > 0);
assert(level <= MAX_PYRAMID);
#endif
PropagateKernel k(this, expand_outside);
k.set_target_level(level);
#ifdef _OPENMP
filter_tiles_mp((KernelWorker*)&k); // This worker is parallelizable.
#else