newsprint.c 18.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
/* This file is an image processing operation for GEGL
 *
 * GEGL is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * GEGL 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
14
 * License along with GEGL; if not, see <https://www.gnu.org/licenses/>.
15 16 17 18 19 20 21 22 23
 *
 * Copyright 2017 Øyvind Kolås <pippin@gimp.org>
 */

#include "config.h"
#include <glib/gi18n-lib.h>

#ifdef GEGL_PROPERTIES

24 25 26 27
enum_start (gegl_newsprint_pattern)
  enum_value (GEGL_NEWSPRINT_PATTERN_LINE,     "line",     N_("Line"))
  enum_value (GEGL_NEWSPRINT_PATTERN_CIRCLE,   "circle",   N_("Circle"))
  enum_value (GEGL_NEWSPRINT_PATTERN_DIAMOND,  "diamond",  N_("Diamond"))
28
  enum_value (GEGL_NEWSPRINT_PATTERN_PSCIRCLE, "pssquare", N_("PSSquare (or Euclidian) dot"))
29 30 31
  enum_value (GEGL_NEWSPRINT_PATTERN_CROSS,    "cross",    N_("Orthogonal Lines"))
enum_end (GeglNewsprintPattern)

32
enum_start (gegl_newsprint_color_model)
33 34 35 36
  enum_value (GEGL_NEWSPRINT_COLOR_MODEL_WHITE_ON_BLACK, "white-on-black", N_("White on Black"))
  enum_value (GEGL_NEWSPRINT_COLOR_MODEL_BLACK_ON_WHITE, "black-on-white", N_("Black on White"))
  enum_value (GEGL_NEWSPRINT_COLOR_MODEL_RGB,  "rgb",      N_("RGB"))
  enum_value (GEGL_NEWSPRINT_COLOR_MODEL_CMYK, "cmyk",     N_("CMYK"))
37 38 39
enum_end (GeglNewsprintColorModel)

property_enum (color_model, _("Color Model"),
40
              GeglNewsprintColorModel, gegl_newsprint_color_model, GEGL_NEWSPRINT_COLOR_MODEL_BLACK_ON_WHITE)
41
              description (_("How many inks to use just black, rg, rgb (additive), or cmyk"))
42

43
property_enum (pattern, _("Pattern"),
44
              GeglNewsprintPattern, gegl_newsprint_pattern, GEGL_NEWSPRINT_PATTERN_LINE)
45
              description (_("Halftoning/dot pattern to use"))
46

47
property_double (period, _("Period"), 12.0)
48
                 value_range (0.0, 200.0)
49
                 description (_("The number of pixels across one repetition of a base pattern at base resolution."))
50

51
property_double (turbulence, _("Turbulence"), 0.0)
52
                 value_range (0.0, 1.0)  // rename to wave-pinch or period-pinch?
53
                 description (_("Color saturation dependent compression of period"))
54

55
property_double (blocksize, _("Blocksize"), -1.0)
56
                 value_range (-1.0, 64.0)
57
                 description (_("Number of periods per tile, this tiling avoids high frequency anomaly that angle boost causes"))
58

59
property_double (angleboost, _("Angle Boost"), 0.0)
60
                 value_range (0.0, 4.0)
61
                 description (_("Multiplication factor for desired rotation of the local space for texture, the way this is computed makes it weak for desaturated colors and possibly stronger where there is color."))
62

63
property_double (twist, _("Black and green angle"), 75.0)
64 65
                 value_range (-180.0, 180.0)
                 ui_meta ("unit", "degree")
66
                 ui_meta ("direction", "ccw")
67
                 description (_("Angle offset for patterns"))
68 69 70 71 72 73 74
                 ui_meta ("label", "[color-model {white-on-black,"
                                   "              black-on-white} : bw-label,"
                                   " color-model {rgb}            : rgb-label,"
                                   " color-model {cmyk}           : cmyk-label]")
                 ui_meta ("bw-label",   _("Angle"))
                 ui_meta ("rgb-label",  _("Green angle"))
                 ui_meta ("cmyk-label", _("Black angle"))
75

76
property_double (twist2, _("Red and cyan angle"), 15.0)
77 78
                 value_range (-180.0, 180.0)
                 ui_meta ("unit", "degree")
79
                 ui_meta ("direction", "ccw")
80 81 82 83 84
                 ui_meta ("visible", "color-model {rgb, cmyk}")
                 ui_meta ("label", "[color-model {rgb}  : rgb-label,"
                                   " color-model {cmyk} : cmyk-label]")
                 ui_meta ("rgb-label",  _("Red angle"))
                 ui_meta ("cmyk-label", _("Cyan angle"))
85

86
property_double (twist3, _("Blue and magenta angle"), 45.0)
87 88
                 value_range (-180.0, 180.0)
                 ui_meta ("unit", "degree")
89
                 ui_meta ("direction", "ccw")
90 91 92 93 94
                 ui_meta ("visible", "color-model {rgb, cmyk}")
                 ui_meta ("label", "[color-model {rgb}  : rgb-label,"
                                   " color-model {cmyk} : cmyk-label]")
                 ui_meta ("rgb-label",  _("Blue angle"))
                 ui_meta ("cmyk-label", _("Magenta angle"))
95

96
property_double (twist4, _("Yellow angle"), 0.0)
97 98
                 value_range (-180.0, 180.0)
                 ui_meta ("unit", "degree")
99
                 ui_meta ("direction", "ccw")
100
                 ui_meta ("visible", "color-model {cmyk}")
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

#else

#define GEGL_OP_POINT_FILTER
#define GEGL_OP_NAME     newsprint
#define GEGL_OP_C_SOURCE newsprint.c

#include "gegl-op.h"

#include <math.h>

static inline float dmodf(float x, float y)
{
  return x - y * floorf(x/y);
}

#define fmodf dmodf

/* for details and more liberal licensing of the following function, see
   https://pippin.gimp.org/spachrotyzer/ */

static
float spachrotyze (
    float x,
    float y,
    float part_white,
    float offset,
    float hue,
    int   pattern,
130
    float period,
131 132 133 134 135
    float turbulence,
    float blocksize,
    float angleboost,
    float twist)
{
136
  int max_aa_samples = 16;
137 138
  float acc = 0.0;

139
  float angle  = 3.1415 / 2- ((hue * angleboost) + twist);
140

141 142
  float width  = (period * (1.0 - turbulence) +
                 (period * offset) * turbulence);
143

144 145
  float vec0 = cosf (angle);
  float vec1 = sinf (angle);
146

147 148 149 150 151 152
  float xi = 0.5;
  float yi = 0.2;
  int count = 0;
  int in = 0;
  float old_acc = 0.0;

153 154 155
  x += period * 2;
  y += period * 2;

156
  for (int i = 0; i < max_aa_samples ; i++)
157
  {
158 159 160 161
    xi = fmodf (xi + 0.618033988749854, 1.0);
    yi = fmodf (yi + (0.618033988749854/1.61235), 1.0);

    old_acc = acc;
162
    {
163 164 165
      float u = fmodf (x + xi - 0.5 * width, blocksize * width);
      float v = fmodf (y + yi - 0.5 * width, blocksize * width);

166 167 168 169 170 171 172 173 174
      float w = vec0 * u + vec1 * v;
      float q = vec1 * u - vec0 * v;

      float wperiod = fmodf (w, width);
      float wphase  = (wperiod / width) * 2.0 - 1.0;

      float qperiod = fmodf (q, width);
      float qphase  = (qperiod / width) * 2.0 - 1.0;

175 176
      if (pattern == 0)       /* line */
      {
177
        if (fabsf (wphase) < part_white)
178
          in ++;
179
      }
180 181
      else if (pattern == 1) /* dot */
      {
182 183
        if (qphase * qphase + wphase * wphase <
          part_white * part_white * 2.0)
184
          in ++;
185
      }
186 187
      else if (pattern == 2) /* diamond */
      {
188
        if ((fabsf(wphase) + fabsf(qphase))/2.0 < part_white )
189
          in++;
190
      }
191 192
      else if (pattern == 3) /* dot-to-diamond-to-dot */
      {
193 194 195 196
          float ax = fabsf (wphase ) ;
          float ay = fabsf (qphase ) ;
          float v = 0.0;

197
          if  (ax + ay > 1.0)
198
          {
199 200 201
            ay = 1.0 - ay;
            ax = 1.0 - ax;
            v = 2.0 - sqrtf (ay * ay + ax * ax);
202 203 204
          }
          else
          {
205
            v = sqrtf (ay * ay + ax * ax);
206 207 208
          }
          v/=2.0;
          if (v < part_white)
209
            in++;
210 211
      }
      else if (pattern == 4) /* cross */
212
      {
213 214 215 216
        float part_white2 = powf (part_white, 2.0);
        if (fabsf (wphase) < part_white2 ||
            fabsf (qphase) < part_white2)
          in++;
217
      }
218 219 220 221 222 223 224
      count ++;

      acc = in * 1.0/ count;
      if (i > 3 &&
          fabs (acc - old_acc) < 0.23)
        break;
      old_acc = acc;
225
    }
226

227 228 229
  }
  return acc;
}
230 231 232 233 234 235

static inline double degrees_to_radians (double degrees)
{
  return degrees * (2 * G_PI / 360.0);
}

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
#if 0
-- threshold filter

level = 0.5

for y=0, height-1 do
	for x=0, width-1 do
		ax = (x / width) * 2 - 1
		ay = (y / height) * 2 - 1
		if ax < 0 then ax = -ax end
		if ay < 0 then ay = -ay end
		v = ax * ay

		if false then
		if ax + ay > 1.0 then
		  ax = 1.0 - ax
		  ay = 1.0 - ay
	  --  v = (2.0 - math.sqrt((1.0-ay) * (1.0-ay) + (1.0-ax) * (1.0-ax)))/2
          v = (math.sqrt(ax * ax + ay * ay)/2)

		else
          v = 1.0-math.sqrt(ax * ax + ay * ay)/2
		end
		end
		set_value (x,y,v)
	end
	progress (y/height)
end

#endif

267

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
static gboolean
process (GeglOperation       *operation,
         void                *in_buf,
         void                *out_buf,
         glong                n_pixels,
         const GeglRectangle *roi,
         gint                 level)
{
  GeglProperties *o = GEGL_PROPERTIES (operation);
  gfloat     *in_pixel = in_buf;
  gfloat     *out_pixel = out_buf;

  gint        x = roi->x; /* initial x         */
  gint        y = roi->y; /* and y coordinates */
  gfloat blocksize = o->blocksize;
  if (blocksize < 0.0)
    blocksize = 819200.0;

286
  switch (o->color_model)
287
  {
288
    case GEGL_NEWSPRINT_COLOR_MODEL_WHITE_ON_BLACK:
289 290 291 292 293 294
       while (n_pixels--)
         {
           float luminance  = in_pixel[1];
           float chroma     = fabs(in_pixel[0]-in_pixel[1]);
           float angle      = fabs(in_pixel[2]-in_pixel[1]);

295 296 297 298 299 300 301 302 303 304 305
           float gray = spachrotyze (x, y,
                                    luminance, chroma, angle,
                                    o->pattern,
                                    o->period / (1.0*(1<<level)),
                                    o->turbulence,
                                    blocksize,
                                    o->angleboost,
                                    degrees_to_radians (o->twist));

           for (int c = 0; c < 3; c++)
             out_pixel[c] = gray;
306
           out_pixel[3] = 1.0;
307

308 309 310
           out_pixel += 4;
           in_pixel  += 4;

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
           /* update x and y coordinates */
           x++; if (x>=roi->x + roi->width) { x=roi->x; y++; }
         }
       break;
    case GEGL_NEWSPRINT_COLOR_MODEL_BLACK_ON_WHITE:
       while (n_pixels--)
         {
           float luminance  = in_pixel[1];
           float chroma     = fabs(in_pixel[0]-in_pixel[1]);
           float angle      = fabs(in_pixel[2]-in_pixel[1]);

           float gray = 1.0-spachrotyze (x, y,
                                    1.0-luminance, chroma, angle,
                                    o->pattern,
                                    o->period / (1.0*(1<<level)),
                                    o->turbulence,
                                    blocksize,
                                    o->angleboost,
                                    degrees_to_radians (o->twist));

           for (int c = 0; c < 3; c++)
             out_pixel[c] = gray;
           out_pixel[3] = 1.0;

           out_pixel += 4;
           in_pixel  += 4;

338 339 340 341
           /* update x and y coordinates */
           x++; if (x>=roi->x + roi->width) { x=roi->x; y++; }
         }
       break;
342
    case GEGL_NEWSPRINT_COLOR_MODEL_RGB:
343 344 345 346 347
       while (n_pixels--)
         {
           float pinch = fabs(in_pixel[0]-in_pixel[1]);
           float angle = fabs(in_pixel[2]-in_pixel[1]);

348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
           out_pixel[0] = spachrotyze (x, y,
                                       in_pixel[0], pinch, angle,
                                       o->pattern,
                                       o->period / (1.0*(1<<level)),
                                       o->turbulence,
                                       blocksize,
                                       o->angleboost,
                                       degrees_to_radians (o->twist2));

           out_pixel[1] = spachrotyze (x, y,
                                       in_pixel[1], pinch, angle,
                                       o->pattern,
                                       o->period / (1.0*(1<<level)),
                                       o->turbulence,
                                       blocksize,
                                       o->angleboost,
                                       degrees_to_radians (o->twist));

           out_pixel[2] = spachrotyze (x, y,
367 368
                                   in_pixel[2], pinch, angle,
                                   o->pattern,
369
                                   o->period / (1.0*(1<<level)),
370 371 372
                                   o->turbulence,
                                   blocksize,
                                   o->angleboost,
373
                                   degrees_to_radians (o->twist3));
374
           out_pixel[3] = 1.0;
375

376
           out_pixel += 4;
377 378 379 380 381 382
           in_pixel  += 4;

           /* update x and y coordinates */
           x++; if (x>=roi->x + roi->width) { x=roi->x; y++; }
         }
       break;
383
    case GEGL_NEWSPRINT_COLOR_MODEL_CMYK:
384 385 386 387
       while (n_pixels--)
         {
           float pinch = fabs(in_pixel[0]-in_pixel[1]);
           float angle = fabs(in_pixel[2]-in_pixel[1]);
388 389
           float c = 1.0  - in_pixel[0];
           float m = 1.0  - in_pixel[1];
390 391
           float iy = 1.0 - in_pixel[2];
           float k = 1.0;
392

393 394 395 396
           if (c < k) k = c;
           if (m < k) k = m;
           if (y < k) k = y;

397
           k = k * 0.40; /* black pull out */
398 399 400 401 402 403 404 405 406 407 408 409

           if (k < 1.0)
           {
             c = (c - k) / (1.0 - k);
             m = (m - k) / (1.0 - k);
             iy = (iy - k) / (1.0 - k);
           }
           else /* wont happen with 0.40 pullout */
           {
             c = m = iy = 1.0;
           }

410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
           c = spachrotyze (x, y,
                            c, pinch, angle,
                            o->pattern,
                            o->period / (1.0*(1<<level)),
                            o->turbulence,
                            blocksize,
                            o->angleboost,
                            degrees_to_radians (o->twist2));

           m = spachrotyze (x, y,
                            m, pinch, angle,
                            o->pattern,
                            o->period / (1.0*(1<<level)),
                            o->turbulence,
                            blocksize,
                            o->angleboost,
                            degrees_to_radians (o->twist3));
427

428 429 430 431 432 433 434 435
           iy = spachrotyze (x, y,
                             iy, pinch, angle,
                             o->pattern,
                             o->period / (1.0*(1<<level)),
                             o->turbulence,
                             blocksize,
                             o->angleboost,
                             degrees_to_radians (o->twist4));
436

437 438
           k = spachrotyze (x, y,
                            k, pinch, angle,
439
                            o->pattern,
440
                            o->period / (1.0*(1<<level)),
441 442 443
                            o->turbulence,
                            blocksize,
                            o->angleboost,
444
                            degrees_to_radians (o->twist));
445 446 447 448 449 450 451 452 453 454 455 456 457

           if (k < 1.0) {
             c = c * (1.0 - k) + k;
             m = m * (1.0 - k) + k;
             iy= iy* (1.0 - k) + k;
           } else {
             c = 1.0; iy = 1.0; m = 1.0;
           }
           out_pixel[0] = 1.0 - c;
           out_pixel[1] = 1.0 - m;
           out_pixel[2] = 1.0 - iy;
           out_pixel[3] = in_pixel[3];
           out_pixel += 4;
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
           in_pixel  += 4;

           /* update x and y coordinates */
           x++; if (x>=roi->x + roi->width) { x=roi->x; y++; }
         }
       break;
  }

  return  TRUE;
}

#if 0
#include "opencl/gegl-cl.h"
#include "opencl/spachrotyze.cl.h"

static GeglClRunData *cl_data = NULL;

/* OpenCL processing function */
static gboolean
cl_process (GeglOperation       *op,
            cl_mem               in_tex,
            cl_mem               out_tex,
            size_t               global_worksize,
            const GeglRectangle *roi,
            int                  level)
{
  const size_t  gbl_size[2] = {roi->width, roi->height};
  const size_t  gbl_offs[2] = {roi->x, roi->y};

  GeglProperties   *o  = GEGL_PROPERTIES (op);
  cl_int cl_err = 0;

  if (!cl_data)
    {
      const char *kernel_name[] = {"gegl_spachrotyzer", NULL};
      cl_data = gegl_cl_compile_and_build (spachrotyzer_cl_source, kernel_name);
    }

  if (!cl_data)
  {
    g_warning ("cl fail\n");
    CL_CHECK;
    return 1;
  }

  cl_err = gegl_clSetKernelArg(cl_data->kernel[0], 0, sizeof(cl_mem),   (void*)&in_tex);
  CL_CHECK;
  cl_err = gegl_clSetKernelArg(cl_data->kernel[0], 1, sizeof(cl_mem),   (void*)&out_tex);
  CL_CHECK;
  cl_err = gegl_clSetKernelArg(cl_data->kernel[0], 2, sizeof(cl_int),   (void*)&o->pattern);
  CL_CHECK;
509
  cl_err = gegl_clSetKernelArg(cl_data->kernel[0], 3, sizeof(cl_float), (void*)&o->period);
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
  CL_CHECK;
  cl_err = gegl_clSetKernelArg(cl_data->kernel[0], 4, sizeof(cl_float), (void*)&o->turbulence);
  CL_CHECK;
  cl_err = gegl_clSetKernelArg(cl_data->kernel[0], 5, sizeof(cl_float), (void*)&o->blocksize);
  CL_CHECK;
  cl_err = gegl_clSetKernelArg(cl_data->kernel[0], 6, sizeof(cl_float), (void*)&o->angleboost);
  CL_CHECK;
  cl_err = gegl_clSetKernelArg(cl_data->kernel[0], 7, sizeof(cl_float), (void*)&o->twist);
  CL_CHECK;

  cl_err = gegl_clEnqueueNDRangeKernel(gegl_cl_get_command_queue (),
                                        cl_data->kernel[0], 2,
                                        gbl_offs, gbl_size, NULL,
                                        0, NULL, NULL);
  CL_CHECK;

  return FALSE;

error:
  return TRUE;
}
#endif

static void
gegl_op_class_init (GeglOpClass *klass)
{
  GeglOperationClass            *operation_class;
  GeglOperationPointFilterClass *point_filter_class;

  operation_class = GEGL_OPERATION_CLASS (klass);
  point_filter_class = GEGL_OPERATION_POINT_FILTER_CLASS (klass);

  point_filter_class->process = process;
#if 0
  point_filter_class->cl_process = cl_process;
  operation_class->opencl_support = TRUE;
#endif

  gegl_operation_class_set_keys (operation_class,
    "name",               "gegl:newsprint",
550
    "title",              _("Newsprint"),
551 552
    "position-dependent", "true",
    "categories" ,        "render",
553
    "reference-hash",     "f680e099d412e28dfa26f9b19e34109f",
554
    "description",        _("Digital halftoning with optional modulations. "),
555
    "reference-chain",    "load path=images/standard-input.png newsprint period=6.0 pattern=pssquare color-model=cmyk",
556 557 558 559 560
    "position-dependent", "true",
    NULL);
}

#endif