gimppickable-contiguous-region.c 34.4 KB
Newer Older
1
/* GIMP - The GNU Image Manipulation Program
2 3
 * Copyright (C) 1995 Spencer Kimball and Peter Mattis
 *
4
 * This program is free software: you can redistribute it and/or modify
5
 * it under the terms of the GNU General Public License as published by
6
 * the Free Software Foundation; either version 3 of the License, or
7 8 9 10 11 12 13 14
 * (at your option) any later version.
 *
 * 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
15
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
16 17 18 19
 */

#include "config.h"

20 21
#include <stdlib.h>

22
#include <cairo.h>
23
#define GEGL_ITERATOR2_API
24
#include <gegl.h>
25
#include <gdk-pixbuf/gdk-pixbuf.h>
26 27

#include "libgimpcolor/gimpcolor.h"
28
#include "libgimpmath/gimpmath.h"
29 30 31

#include "core-types.h"

32 33
#include "gegl/gimp-babl.h"

34
#include "gimp-parallel.h"
35
#include "gimp-utils.h" /* GIMP_TIMER */
36
#include "gimpasync.h"
37
#include "gimplineart.h"
38
#include "gimppickable.h"
39
#include "gimppickable-contiguous-region.h"
40 41


42 43 44 45 46 47 48 49
typedef struct
{
  GeglBuffer *buffer;
  gboolean    select_transparent;
  gfloat      stroke_threshold;
} LineArtData;


50 51
/*  local function prototypes  */

52 53 54 55
static const Babl * choose_format         (GeglBuffer          *buffer,
                                           GimpSelectCriterion  select_criterion,
                                           gint                *n_components,
                                           gboolean            *has_alpha);
56 57
static gfloat   pixel_difference          (const gfloat        *col1,
                                           const gfloat        *col2,
58
                                           gboolean             antialias,
59 60
                                           gfloat               threshold,
                                           gint                 n_components,
61 62 63
                                           gboolean             has_alpha,
                                           gboolean             select_transparent,
                                           GimpSelectCriterion  select_criterion);
64 65 66 67 68 69 70 71 72 73 74 75 76
static void     push_segment              (GQueue              *segment_queue,
                                           gint                 y,
                                           gint                 old_y,
                                           gint                 start,
                                           gint                 end,
                                           gint                 new_y,
                                           gint                 new_start,
                                           gint                 new_end);
static void     pop_segment               (GQueue              *segment_queue,
                                           gint                *y,
                                           gint                *old_y,
                                           gint                *start,
                                           gint                *end);
77
static gboolean find_contiguous_segment   (const gfloat        *col,
78
                                           GeglBuffer          *src_buffer,
79
                                           GeglSampler         *src_sampler,
80 81
                                           GeglBuffer          *mask_buffer,
                                           const Babl          *src_format,
82
                                           const Babl          *mask_format,
83
                                           gint                 n_components,
84
                                           gboolean             has_alpha,
85
                                           gint                 width,
86 87 88
                                           gboolean             select_transparent,
                                           GimpSelectCriterion  select_criterion,
                                           gboolean             antialias,
89
                                           gfloat               threshold,
90 91
                                           gint                 initial_x,
                                           gint                 initial_y,
92
                                           gint                *start,
93 94 95
                                           gint                *end,
                                           gfloat              *row);
static void     find_contiguous_region    (GeglBuffer          *src_buffer,
96 97
                                           GeglBuffer          *mask_buffer,
                                           const Babl          *format,
98 99
                                           gint                 n_components,
                                           gboolean             has_alpha,
100 101 102
                                           gboolean             select_transparent,
                                           GimpSelectCriterion  select_criterion,
                                           gboolean             antialias,
103
                                           gfloat               threshold,
104
                                           gboolean             diagonal_neighbors,
105 106
                                           gint                 x,
                                           gint                 y,
107
                                           const gfloat        *col);
108

109 110 111 112 113
static LineArtData * line_art_data_new    (GeglBuffer          *buffer,
                                           gboolean             select_transparent,
                                           gfloat               stroke_threshold);
static void          line_art_data_free   (LineArtData         *data);

114 115 116

/*  public functions  */

117 118 119
static void
gimp_pickable_contiguous_region_prepare_line_art_async_func (GimpAsync   *async,
                                                             LineArtData *data)
120 121 122
{
  GeglBuffer *lineart;
  gboolean    has_alpha;
123
  gboolean    select_transparent = FALSE;
124

125
  has_alpha = babl_format_has_alpha (gegl_buffer_get_format (data->buffer));
126

127
  if (has_alpha)
128
    {
129
      if (data->select_transparent)
130 131 132 133 134 135
        {
          /*  don't select transparent regions if there are no fully
           *  transparent pixels.
           */
          GeglBufferIterator *gi;

136 137
          gi = gegl_buffer_iterator_new (data->buffer, NULL, 0,
                                         babl_format ("A u8"),
138 139 140 141 142 143
                                         GEGL_ACCESS_READ, GEGL_ABYSS_NONE, 3);
          while (gegl_buffer_iterator_next (gi))
            {
              guint8 *p = (guint8*) gi->items[0].data;
              gint    k;

144 145 146 147 148 149 150 151 152 153 154
              if (gimp_async_is_canceled (async))
                {
                  gegl_buffer_iterator_stop (gi);

                  gimp_async_abort (async);

                  line_art_data_free (data);

                  return;
                }

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
              for (k = 0; k < gi->length; k++)
                {
                  if (! *p)
                    {
                      select_transparent = TRUE;
                      break;
                    }
                  p++;
                }
              if (select_transparent)
                break;
            }
          if (select_transparent)
            gegl_buffer_iterator_stop (gi);
        }
    }

  /* For smart selection, we generate a binarized image with close
   * regions, then run a composite selection with no threshold on
   * this intermediate buffer.
   */
  GIMP_TIMER_START();

178
  lineart = gimp_lineart_close (data->buffer,
179
                                select_transparent,
180
                                data->stroke_threshold,
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
                                /*minimal_lineart_area,*/
                                5,
                                /*normal_estimate_mask_size,*/
                                5,
                                /*end_point_rate,*/
                                0.85,
                                /*spline_max_length,*/
                                60,
                                /*spline_max_angle,*/
                                90.0,
                                /*end_point_connectivity,*/
                                2,
                                /*spline_roundness,*/
                                1.0,
                                /*allow_self_intersections,*/
                                TRUE,
                                /*created_regions_significant_area,*/
                                4,
                                /*created_regions_minimum_area,*/
                                100,
                                /*small_segments_from_spline_sources,*/
                                TRUE,
                                /*segments_max_length*/
                                20);

  GIMP_TIMER_END("close line-art");

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
  gimp_async_finish_full (async, lineart, g_object_unref);

  line_art_data_free (data);
}

GeglBuffer *
gimp_pickable_contiguous_region_prepare_line_art (GimpPickable *pickable,
                                                  gboolean      select_transparent,
                                                  gfloat        stroke_threshold)
{
  GimpAsync   *async;
  LineArtData *data;
  GeglBuffer  *lineart;

  g_return_val_if_fail (GIMP_IS_PICKABLE (pickable), NULL);

  gimp_pickable_flush (pickable);

  async = gimp_async_new ();
  data  = line_art_data_new (gimp_pickable_get_buffer (pickable),
                             select_transparent,
                             stroke_threshold);

  gimp_pickable_contiguous_region_prepare_line_art_async_func (async, data);

  lineart = g_object_ref (gimp_async_get_result (async));

  g_object_unref (async);

237 238 239
  return lineart;
}

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
GimpAsync *
gimp_pickable_contiguous_region_prepare_line_art_async (GimpPickable *pickable,
                                                        gboolean      select_transparent,
                                                        gfloat        stroke_threshold,
                                                        gint          priority)
{
  GeglBuffer  *buffer;
  GimpAsync   *async;
  LineArtData *data;

  g_return_val_if_fail (GIMP_IS_PICKABLE (pickable), NULL);

  gimp_pickable_flush (pickable);

  buffer = gegl_buffer_dup (gimp_pickable_get_buffer (pickable));

  data  = line_art_data_new (buffer,
                             select_transparent,
                             stroke_threshold);

  g_object_unref (buffer);

  async = gimp_parallel_run_async_full (
    priority,
    (GimpParallelRunAsyncFunc)
      gimp_pickable_contiguous_region_prepare_line_art_async_func,
    data,
    (GDestroyNotify) line_art_data_free);

  return async;
}

272
GeglBuffer *
273
gimp_pickable_contiguous_region_by_seed (GimpPickable        *pickable,
274
                                         GeglBuffer          *line_art,
275 276 277 278
                                         gboolean             antialias,
                                         gfloat               threshold,
                                         gboolean             select_transparent,
                                         GimpSelectCriterion  select_criterion,
279
                                         gboolean             diagonal_neighbors,
280
                                         gfloat               stroke_threshold,
281 282
                                         gint                 x,
                                         gint                 y)
283
{
284 285 286 287 288 289 290
  GeglBuffer    *src_buffer;
  GeglBuffer    *mask_buffer;
  const Babl    *format;
  GeglRectangle  extent;
  gint           n_components;
  gboolean       has_alpha;
  gfloat         start_col[MAX_CHANNELS];
291
  gfloat         flag           = 2.0;
292
  gboolean       smart_line_art = FALSE;
293
  gboolean       free_line_art  = FALSE;
294 295

  g_return_val_if_fail (GIMP_IS_PICKABLE (pickable), NULL);
296

297
  if (select_criterion == GIMP_SELECT_CRITERION_LINE_ART)
298
    {
299
      if (line_art == NULL)
300
        {
301 302 303
          /* It is much better experience to pre-compute the line art,
           * but it may not be always possible (for instance when
           * selecting/filling through a PDB call).
304
           */
305
          line_art      = gimp_pickable_contiguous_region_prepare_line_art (pickable, select_transparent,
306
                                                                            stroke_threshold);
307
          free_line_art = TRUE;
308
        }
309

310 311
      src_buffer = line_art;

312
      smart_line_art     = TRUE;
313 314 315 316 317
      antialias          = FALSE;
      threshold          = 0.0;
      select_transparent = FALSE;
      select_criterion   = GIMP_SELECT_CRITERION_COMPOSITE;
      diagonal_neighbors = FALSE;
318 319 320 321 322

      format = choose_format (src_buffer, select_criterion,
                              &n_components, &has_alpha);
      gegl_buffer_sample (src_buffer, x, y, NULL, start_col, format,
                          GEGL_SAMPLER_NEAREST, GEGL_ABYSS_NONE);
323 324 325 326 327
    }
  else
    {
      gimp_pickable_flush (pickable);
      src_buffer = gimp_pickable_get_buffer (pickable);
328

329 330 331 332 333
      format = choose_format (src_buffer, select_criterion,
                              &n_components, &has_alpha);
      gegl_buffer_sample (src_buffer, x, y, NULL, start_col, format,
                          GEGL_SAMPLER_NEAREST, GEGL_ABYSS_NONE);

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
      if (has_alpha)
        {
          if (select_transparent)
            {
              /*  don't select transparent regions if the start pixel isn't
               *  fully transparent
               */
              if (start_col[n_components - 1] > 0)
                select_transparent = FALSE;
            }
        }
      else
        {
          select_transparent = FALSE;
        }
349 350
    }

351
  extent = *gegl_buffer_get_extent (src_buffer);
352

353
  mask_buffer = gegl_buffer_new (&extent, babl_format ("Y float"));
354

355 356 357 358 359 360 361 362 363 364 365 366
  if (smart_line_art && start_col[0])
    {
      /* As a special exception, if you fill over a line art pixel, only
       * fill the pixel and exit
       */
      start_col[0] = 1.0;
      gegl_buffer_set (mask_buffer, GEGL_RECTANGLE (x, y, 1, 1),
                       0, babl_format ("Y float"), start_col,
                       GEGL_AUTO_ROWSTRIDE);
      smart_line_art = FALSE;
    }
  else if (x >= extent.x && x < (extent.x + extent.width) &&
367 368 369 370 371 372 373
      y >= extent.y && y < (extent.y + extent.height))
    {
      GIMP_TIMER_START();

      find_contiguous_region (src_buffer, mask_buffer,
                              format, n_components, has_alpha,
                              select_transparent, select_criterion,
374
                              antialias, threshold, diagonal_neighbors,
375
                              x, y, start_col);
376

377 378
      GIMP_TIMER_END("foo");
    }
379 380 381 382 383 384 385 386 387 388 389

  if (smart_line_art)
    {
      /* The last step of the line art algorithm is to make sure that
       * selections does not leave "holes" between its borders and the
       * line arts, while not stepping over as well.
       * To achieve this, I label differently the selection and the rest
       * and leave the stroke pixels unlabelled, then I let these
       * unknown pixels be labelled by flooding through watershed.
       */
      GeglBufferIterator *gi;
390
      GeglBuffer         *priomap;
391 392 393 394 395 396 397
      GeglNode           *graph;
      GeglNode           *input;
      GeglNode           *aux;
      GeglNode           *op;

      GIMP_TIMER_START();

398 399 400
      /* Flag the mask on the line art and create a priority map. */
      priomap = gegl_buffer_new (gegl_buffer_get_extent (mask_buffer),
                                 babl_format ("Y u8"));
401

402
      gi = gegl_buffer_iterator_new (src_buffer, NULL, 0, NULL,
403
                                     GEGL_ACCESS_READ, GEGL_ABYSS_NONE, 3);
404 405 406
      gegl_buffer_iterator_add (gi, mask_buffer, NULL, 0,
                                babl_format ("Y float"),
                                GEGL_ACCESS_READWRITE, GEGL_ABYSS_NONE);
407 408 409
      gegl_buffer_iterator_add (gi, priomap, NULL, 0,
                                babl_format ("Y u8"),
                                GEGL_ACCESS_WRITE, GEGL_ABYSS_NONE);
410 411 412

      while (gegl_buffer_iterator_next (gi))
        {
413 414 415
          guchar *lineart = (guchar*) gi->items[0].data;
          gfloat *mask    = (gfloat*) gi->items[1].data;
          guint8 *prio    = (guint8*) gi->items[2].data;
416 417 418 419
          gint    k;

          for (k = 0; k < gi->length; k++)
            {
420 421 422 423 424 425 426 427 428 429
              if (*lineart)
                {
                  *prio = 1;
                  if (! *mask)
                    *mask = flag;
                }
              else
                {
                  *prio = 0;
                }
430 431
              lineart++;
              mask++;
432
              prio++;
433 434 435 436
            }
        }

      /* Watershed the line art. */
437 438 439
      graph = gegl_node_new ();
      input = gegl_node_new_child (graph,
                                   "operation", "gegl:buffer-source",
440
                                   "buffer", mask_buffer,
441 442 443
                                   NULL);
      aux = gegl_node_new_child (graph,
                                 "operation", "gegl:buffer-source",
444
                                 "buffer", priomap,
445 446 447
                                 NULL);
      op  = gegl_node_new_child (graph,
                                 "operation", "gegl:watershed-transform",
448 449
                                 "flag-component", 0,
                                 "flag", &flag,
450 451 452 453 454
                                 NULL);
      gegl_node_connect_to (input, "output",
                            op, "input");
      gegl_node_connect_to (aux, "output",
                            op, "aux");
455
      gegl_node_blit_buffer (op, mask_buffer, NULL, 0, GEGL_ABYSS_NONE);
456
      g_object_unref (graph);
457
      g_object_unref (priomap);
458 459 460

      GIMP_TIMER_END("watershed line art");
    }
461 462
  if (free_line_art)
    g_object_unref (src_buffer);
463

464
  return mask_buffer;
465 466
}

467
GeglBuffer *
468 469 470 471 472 473
gimp_pickable_contiguous_region_by_color (GimpPickable        *pickable,
                                          gboolean             antialias,
                                          gfloat               threshold,
                                          gboolean             select_transparent,
                                          GimpSelectCriterion  select_criterion,
                                          const GimpRGB       *color)
474
{
475
  /*  Scan over the pickable's active layer, finding pixels within the
Sven Neumann's avatar
Sven Neumann committed
476 477
   *  specified threshold from the given R, G, & B values.  If
   *  antialiasing is on, use the same antialiasing scheme as in
478
   *  fuzzy_select.  Modify the pickable's mask to reflect the
Sven Neumann's avatar
Sven Neumann committed
479
   *  additional selection
480
   */
481 482 483
  GeglBufferIterator *iter;
  GeglBuffer         *src_buffer;
  GeglBuffer         *mask_buffer;
484 485
  const Babl         *format;
  gint                n_components;
486
  gboolean            has_alpha;
487
  gfloat              start_col[MAX_CHANNELS];
488

489
  g_return_val_if_fail (GIMP_IS_PICKABLE (pickable), NULL);
490 491
  g_return_val_if_fail (color != NULL, NULL);

492 493
  gimp_pickable_flush (pickable);

494
  src_buffer = gimp_pickable_get_buffer (pickable);
495

496 497 498 499
  format = choose_format (src_buffer, select_criterion,
                          &n_components, &has_alpha);

  gimp_rgba_get_pixel (color, format, start_col);
500

501
  if (has_alpha)
502 503 504
    {
      if (select_transparent)
        {
505
          /*  don't select transparency if "color" isn't fully transparent
506
           */
507
          if (start_col[n_components - 1] > 0.0)
508 509 510 511 512 513 514 515
            select_transparent = FALSE;
        }
    }
  else
    {
      select_transparent = FALSE;
    }

516 517
  mask_buffer = gegl_buffer_new (gegl_buffer_get_extent (src_buffer),
                                 babl_format ("Y float"));
518

519 520
  iter = gegl_buffer_iterator_new (src_buffer,
                                   NULL, 0, format,
521
                                   GEGL_ACCESS_READ, GEGL_ABYSS_NONE, 2);
522

523
  gegl_buffer_iterator_add (iter, mask_buffer,
524
                            NULL, 0, babl_format ("Y float"),
525
                            GEGL_ACCESS_WRITE, GEGL_ABYSS_NONE);
Sven Neumann's avatar
Sven Neumann committed
526

527
  while (gegl_buffer_iterator_next (iter))
Sven Neumann's avatar
Sven Neumann committed
528
    {
529 530
      const gfloat *src   = iter->items[0].data;
      gfloat       *dest  = iter->items[1].data;
531
      gint          count = iter->length;
Sven Neumann's avatar
Sven Neumann committed
532

533
      while (count--)
Sven Neumann's avatar
Sven Neumann committed
534 535
        {
          /*  Find how closely the colors match  */
536
          *dest = pixel_difference (start_col, src,
537 538
                                    antialias,
                                    threshold,
539
                                    n_components,
540 541 542 543
                                    has_alpha,
                                    select_transparent,
                                    select_criterion);

544
          src  += n_components;
545
          dest += 1;
Sven Neumann's avatar
Sven Neumann committed
546 547
        }
    }
548

549
  return mask_buffer;
Sven Neumann's avatar
Sven Neumann committed
550 551
}

552 553 554

/*  private functions  */

555 556 557 558 559 560 561 562 563 564 565 566 567 568
static const Babl *
choose_format (GeglBuffer          *buffer,
               GimpSelectCriterion  select_criterion,
               gint                *n_components,
               gboolean            *has_alpha)
{
  const Babl *format = gegl_buffer_get_format (buffer);

  *has_alpha = babl_format_has_alpha (format);

  switch (select_criterion)
    {
    case GIMP_SELECT_CRITERION_COMPOSITE:
      if (babl_format_is_palette (format))
569
        format = babl_format ("R'G'B'A float");
570 571
      else
        format = gimp_babl_format (gimp_babl_format_get_base_type (format),
572 573 574
                                   GIMP_PRECISION_FLOAT_NON_LINEAR,
                                   *has_alpha,
                                   NULL);
575 576 577 578 579
      break;

    case GIMP_SELECT_CRITERION_R:
    case GIMP_SELECT_CRITERION_G:
    case GIMP_SELECT_CRITERION_B:
580
    case GIMP_SELECT_CRITERION_A:
581
      format = babl_format ("R'G'B'A float");
582 583 584 585 586 587 588 589
      break;

    case GIMP_SELECT_CRITERION_H:
    case GIMP_SELECT_CRITERION_S:
    case GIMP_SELECT_CRITERION_V:
      format = babl_format ("HSVA float");
      break;

590
    case GIMP_SELECT_CRITERION_LCH_L:
591 592 593
      format = babl_format ("CIE L alpha float");
      break;

594 595 596 597 598
    case GIMP_SELECT_CRITERION_LCH_C:
    case GIMP_SELECT_CRITERION_LCH_H:
      format = babl_format ("CIE LCH(ab) alpha float");
      break;

599
    case GIMP_SELECT_CRITERION_LINE_ART:
600
      format = babl_format ("Y'A float");
601 602
      break;

603 604 605 606 607 608 609 610 611 612
    default:
      g_return_val_if_reached (NULL);
      break;
    }

  *n_components = babl_format_get_n_components (format);

  return format;
}

613 614 615
static gfloat
pixel_difference (const gfloat        *col1,
                  const gfloat        *col2,
616
                  gboolean             antialias,
617 618
                  gfloat               threshold,
                  gint                 n_components,
619 620 621
                  gboolean             has_alpha,
                  gboolean             select_transparent,
                  GimpSelectCriterion  select_criterion)
622
{
623
  gfloat max = 0.0;
624 625

  /*  if there is an alpha channel, never select transparent regions  */
626 627
  if (! select_transparent && has_alpha && col2[n_components - 1] == 0.0)
    return 0.0;
628

629
  if (select_transparent && has_alpha)
630
    {
631
      max = fabs (col1[n_components - 1] - col2[n_components - 1]);
632 633 634
    }
  else
    {
635 636
      gfloat diff;
      gint   b;
637 638

      if (has_alpha)
639
        n_components--;
640

641
      switch (select_criterion)
642
        {
643
        case GIMP_SELECT_CRITERION_COMPOSITE:
644
          for (b = 0; b < n_components; b++)
645
            {
646
              diff = fabs (col1[b] - col2[b]);
647 648 649 650 651 652
              if (diff > max)
                max = diff;
            }
          break;

        case GIMP_SELECT_CRITERION_R:
653
          max = fabs (col1[0] - col2[0]);
654 655 656
          break;

        case GIMP_SELECT_CRITERION_G:
657
          max = fabs (col1[1] - col2[1]);
658 659 660
          break;

        case GIMP_SELECT_CRITERION_B:
661
          max = fabs (col1[2] - col2[2]);
662 663
          break;

664 665 666 667
        case GIMP_SELECT_CRITERION_A:
          max = fabs (col1[3] - col2[3]);
          break;

668
        case GIMP_SELECT_CRITERION_H:
669 670
          max = fabs (col1[0] - col2[0]);
          max = MIN (max, 1.0 - max);
671 672 673
          break;

        case GIMP_SELECT_CRITERION_S:
674
          max = fabs (col1[1] - col2[1]);
675 676 677
          break;

        case GIMP_SELECT_CRITERION_V:
678
          max = fabs (col1[2] - col2[2]);
679
          break;
680 681 682 683 684 685 686 687 688 689 690 691 692

        case GIMP_SELECT_CRITERION_LCH_L:
          max = fabs (col1[0] - col2[0]) / 100.0;
          break;

        case GIMP_SELECT_CRITERION_LCH_C:
          max = fabs (col1[1] - col2[1]) / 100.0;
          break;

        case GIMP_SELECT_CRITERION_LCH_H:
          max = fabs (col1[2] - col2[2]) / 360.0;
          max = MIN (max, 1.0 - max);
          break;
693 694 695 696

        case GIMP_SELECT_CRITERION_LINE_ART:
          /* Smart selection is handled before. */
          g_return_val_if_reached (0.0);
697
        }
698 699
    }

700
  if (antialias && threshold > 0.0)
701
    {
702
      gfloat aa = 1.5 - (max / threshold);
703

704
      if (aa <= 0.0)
705
        return 0.0;
706
      else if (aa < 0.5)
707
        return aa * 2.0;
708
      else
709
        return 1.0;
710 711 712 713
    }
  else
    {
      if (max > threshold)
714
        return 0.0;
715
      else
716
        return 1.0;
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
static void
push_segment (GQueue *segment_queue,
              gint    y,
              gint    old_y,
              gint    start,
              gint    end,
              gint    new_y,
              gint    new_start,
              gint    new_end)
{
  /* To avoid excessive memory allocation (y, old_y, start, end) tuples are
   * stored in interleaved format:
   *
   * [y1] [old_y1] [start1] [end1] [y2] [old_y2] [start2] [end2]
   */

  if (new_y != old_y)
    {
      /* If the new segment's y-coordinate is different than the old (source)
       * segment's y-coordinate, push the entire segment.
       */
      g_queue_push_tail (segment_queue, GINT_TO_POINTER (new_y));
      g_queue_push_tail (segment_queue, GINT_TO_POINTER (y));
      g_queue_push_tail (segment_queue, GINT_TO_POINTER (new_start));
      g_queue_push_tail (segment_queue, GINT_TO_POINTER (new_end));
    }
  else
    {
      /* Otherwise, only push the set-difference between the new segment and
       * the source segment (since we've already scanned the source segment.)
       * Note that the `+ 1` and `- 1` terms of the end/start coordinates below
       * are only necessary when `diagonal_neighbors` is on (and otherwise make
       * the segments slightly larger than necessary), but, meh...
       */
      if (new_start < start)
        {
          g_queue_push_tail (segment_queue, GINT_TO_POINTER (new_y));
          g_queue_push_tail (segment_queue, GINT_TO_POINTER (y));
          g_queue_push_tail (segment_queue, GINT_TO_POINTER (new_start));
          g_queue_push_tail (segment_queue, GINT_TO_POINTER (start + 1));
        }

      if (new_end > end)
        {
          g_queue_push_tail (segment_queue, GINT_TO_POINTER (new_y));
          g_queue_push_tail (segment_queue, GINT_TO_POINTER (y));
          g_queue_push_tail (segment_queue, GINT_TO_POINTER (end - 1));
          g_queue_push_tail (segment_queue, GINT_TO_POINTER (new_end));
        }
    }
}

static void
pop_segment (GQueue *segment_queue,
             gint   *y,
             gint   *old_y,
             gint   *start,
             gint   *end)
{
  *y     = GPOINTER_TO_INT (g_queue_pop_head (segment_queue));
  *old_y = GPOINTER_TO_INT (g_queue_pop_head (segment_queue));
  *start = GPOINTER_TO_INT (g_queue_pop_head (segment_queue));
  *end   = GPOINTER_TO_INT (g_queue_pop_head (segment_queue));
}

785
/* #define FETCH_ROW 1 */
786

787
static gboolean
788
find_contiguous_segment (const gfloat        *col,
789
                         GeglBuffer          *src_buffer,
790
                         GeglSampler         *src_sampler,
791
                         GeglBuffer          *mask_buffer,
792 793
                         const Babl          *src_format,
                         const Babl          *mask_format,
794
                         gint                 n_components,
795
                         gboolean             has_alpha,
796
                         gint                 width,
797 798 799
                         gboolean             select_transparent,
                         GimpSelectCriterion  select_criterion,
                         gboolean             antialias,
800
                         gfloat               threshold,
801 802
                         gint                 initial_x,
                         gint                 initial_y,
803
                         gint                *start,
804 805
                         gint                *end,
                         gfloat              *row)
806
{
807 808 809 810 811 812
  gfloat *s;
  gfloat  mask_row[width];
  gfloat  diff;

#ifdef FETCH_ROW
  gegl_buffer_get (src_buffer, GEGL_RECTANGLE (0, initial_y, width, 1), 1.0,
813
                   src_format,
814 815 816 817
                   row, GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_NONE);
  s = row + initial_x * n_components;
#else
  s = g_alloca (n_components * sizeof (gfloat));
818

819 820
  gegl_sampler_get (src_sampler,
                    initial_x, initial_y, NULL, s, GEGL_ABYSS_NONE);
821
#endif
822

823
  diff = pixel_difference (col, s, antialias, threshold,
824
                           n_components, has_alpha, select_transparent,
825
                           select_criterion);
826

827
  /* check the starting pixel */
828
  if (! diff)
829 830 831
    return FALSE;

  mask_row[initial_x] = diff;
832

833
  *start = initial_x - 1;
834 835 836
#ifdef FETCH_ROW
  s = row + *start * n_components;
#endif
837

838
  while (*start >= 0)
839
    {
840
#ifndef FETCH_ROW
841 842
      gegl_sampler_get (src_sampler,
                        *start, initial_y, NULL, s, GEGL_ABYSS_NONE);
843
#endif
844

845
      diff = pixel_difference (col, s, antialias, threshold,
846
                               n_components, has_alpha, select_transparent,
847
                               select_criterion);
848 849
      if (diff == 0.0)
        break;
850

851
      mask_row[*start] = diff;
852

853
      (*start)--;
854
#ifdef FETCH_ROW
855
      s -= n_components;
856
#endif
857 858
    }

859
  *end = initial_x + 1;
860 861 862
#ifdef FETCH_ROW
  s = row + *end * n_components;
#endif
863

864
  while (*end < width)
865
    {
866
#ifndef FETCH_ROW
867 868
      gegl_sampler_get (src_sampler,
                        *end, initial_y, NULL, s, GEGL_ABYSS_NONE);
869
#endif
870

871
      diff = pixel_difference (col, s, antialias, threshold,
872
                               n_components, has_alpha, select_transparent,
873
                               select_criterion);
874 875
      if (diff == 0.0)
        break;
876

877
      mask_row[*end] = diff;
878

879
      (*end)++;
880
#ifdef FETCH_ROW
881
      s += n_components;
882
#endif
883 884
    }

885 886 887
  gegl_buffer_set (mask_buffer, GEGL_RECTANGLE (*start + 1, initial_y,
                                                *end - *start - 1, 1),
                   0, mask_format, &mask_row[*start + 1],
888 889
                   GEGL_AUTO_ROWSTRIDE);

890 891 892 893
  return TRUE;
}

static void
894 895 896 897 898 899 900 901 902
find_contiguous_region (GeglBuffer          *src_buffer,
                        GeglBuffer          *mask_buffer,
                        const Babl          *format,
                        gint                 n_components,
                        gboolean             has_alpha,
                        gboolean             select_transparent,
                        GimpSelectCriterion  select_criterion,
                        gboolean             antialias,
                        gfloat               threshold,
903
                        gboolean             diagonal_neighbors,
904 905 906
                        gint                 x,
                        gint                 y,
                        const gfloat        *col)
907
{
908 909 910 911 912 913 914
  const Babl  *mask_format = babl_format ("Y float");
  GeglSampler *src_sampler;
  gint         old_y;
  gint         start, end;
  gint         new_start, new_end;
  GQueue      *segment_queue;
  gfloat      *row = NULL;
915 916 917 918

#ifdef FETCH_ROW
  row = g_new (gfloat, gegl_buffer_get_width (src_buffer) * n_components);
#endif
919

920
  src_sampler = gegl_buffer_sampler_new (src_buffer,
921 922
                                          format, GEGL_SAMPLER_NEAREST);

923
  segment_queue = g_queue_new ();
924

925 926 927
  push_segment (segment_queue,
                y, /* dummy values: */ -1, 0, 0,
                y, x - 1, x + 1);
928

929 930
  do
    {
931 932
      pop_segment (segment_queue,
                   &y, &old_y, &start, &end);
933

934 935
      for (x = start + 1; x < end; x++)
        {
936 937
          gfloat val;

938 939 940
          gegl_buffer_get (mask_buffer, GEGL_RECTANGLE (x, y, 1, 1), 1.0,
                           mask_format, &val, GEGL_AUTO_ROWSTRIDE,
                           GEGL_ABYSS_NONE);
941

942
          if (val != 0.0)
943 944 945 946 947 948 949 950
            {
              /* If the current pixel is selected, then we've already visited
               * the next pixel.  (Note that we assume that the maximal image
               * width is sufficiently low that `x` won't overflow.)
               */
              x++;
              continue;
            }
951

952 953
          if (! find_contiguous_segment (col,
                                         src_buffer, src_sampler, mask_buffer,
954
                                         format, mask_format,
955 956
                                         n_components,
                                         has_alpha,
957
                                         gegl_buffer_get_width (src_buffer),
958
                                         select_transparent, select_criterion,
959
                                         antialias, threshold, x, y,
960 961
                                         &new_start, &new_end,
                                         row))
962
            continue;
963

964 965 966 967 968 969 970 971
          /* We can skip directly to `new_end + 1` on the next iteration, since
           * we've just selected all pixels in the range `[x, new_end)`, and
           * the pixel at `new_end` is above threshold.  (Note that we assume
           * that the maximal image width is sufficiently low that `x` won't
           * overflow.)
           */
          x = new_end;

972 973 974 975 976 977 978 979 980
          if (diagonal_neighbors)
            {
              if (new_start >= 0)
                new_start--;

              if (new_end < gegl_buffer_get_width (src_buffer))
                new_end++;
            }

981
          if (y + 1 < gegl_buffer_get_height (src_buffer))
982
            {
983 984 985
              push_segment (segment_queue,
                            y, old_y, start, end,
                            y + 1, new_start, new_end);
986
            }
987

988
          if (y - 1 >= 0)
989
            {
990 991 992
              push_segment (segment_queue,
                            y, old_y, start, end,
                            y - 1, new_start, new_end);
993
            }
994

995
        }
996
    }
997
  while (! g_queue_is_empty (segment_queue));
998

999
  g_queue_free (segment_queue);
1000

1001 1002
  g_object_unref (src_sampler);

1003 1004 1005
#ifdef FETCH_ROW
  g_free (row);
#endif
1006
}
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028

static LineArtData *
line_art_data_new (GeglBuffer *buffer,
                   gboolean    select_transparent,
                   gfloat      stroke_threshold)
{
  LineArtData *data = g_slice_new (LineArtData);

  data->buffer             = g_object_ref (buffer);
  data->select_transparent = select_transparent;
  data->stroke_threshold   = stroke_threshold;

  return data;
}

static void
line_art_data_free (LineArtData *data)
{
  g_object_unref (data->buffer);

  g_slice_free (LineArtData, data);
}