lens-distortion.c 14.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* 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
 * License along with GEGL; if not, see <http://www.gnu.org/licenses/>.
 *
16 17
 * Lens plug-in - adjust for lens distortion
 *
18
 * Copyright (C) 1995 Spencer Kimball and Peter Mattis
19
 * Copyright (C) 2001-2005 David Hodson <hodsond@acm.org>
20
 * Copyright (C) 2008 Aurimas Juška <aurisj@svn.gnome.org>
21 22
 * Copyright (C) 2011 Robert Sasu <sasu.robert@gmail.com>
 * Copyright (C) 2013 Téo Mazars <teo.mazars@ensimag.fr>
23 24 25 26 27 28 29 30
 *
 * Many thanks for Lars Clausen for the original inspiration,
 *   useful discussion, optimisation and improvements.
 */

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

31 32
#ifdef GEGL_PROPERTIES

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
property_double (main, _("Main"), 0.0)
    description (_("Amount of second-order distortion"))
    value_range (-100.0, 100.0)

property_double (edge, _("Edge"), 0.0)
    description (_("Amount of fourth-order distortion"))
    value_range (-100.0, 100.0)

property_double (zoom, _("Zoom"), 0.0)
    description (_("Rescale overall image size"))
    value_range (-100, 100.0)

property_double (x_shift, _("Shift X"), 0.0)
    description (_("Effect centre offset in X"))
    value_range (-100.0, 100.0)

property_double (y_shift, _("Shift Y"), 0.0)
    description (_("Effect centre offset in Y"))
    value_range (-100.0, 100.0)

property_double (brighten, _("Brighten"), 0.0)
    description (_("Adjust brightness in corners"))
    value_range (-100.0, 100.0)

property_color  (background, _("Background color"), "white")
58

59 60
#else

61
#define GEGL_OP_FILTER
62
#define GEGL_OP_C_SOURCE lens-distortion.c
63

64
#include "gegl-op.h"
65
#include <math.h>
66 67 68 69 70 71 72 73 74 75 76
#include <stdio.h>

#define SQR(x) ((x)*(x))

#define MIN3(x,y,z) (MIN (MIN ((x),(y)),(z)))

#define MAX3(x,y,z) (MAX (MAX ((x),(y)),(z)))

#define MAX_WH     1024
#define CHUNK_SIZE 512

77

78 79 80 81 82 83 84 85 86
typedef struct
{
  gdouble centre_x;
  gdouble centre_y;
  gdouble mult_sq;
  gdouble mult_qd;
  gdouble rescale;
  gdouble brighten;
  gdouble norm;
87 88
} LensValues;

89

90
static void
91 92
reorder (gdouble *low,
         gdouble *high)
93
{
94 95 96 97 98 99 100
  gdouble temp;

  if (*low < *high) return;

  temp = *low;
  *low = *high;
  *high = temp;
101 102
}

103
static LensValues
104 105
lens_setup_calc (GeglProperties *o,
                 GeglRectangle   boundary)
106
{
107
  LensValues lens;
108

109 110 111 112 113 114 115
  lens.norm     = 4.0 / (SQR (boundary.width) + SQR (boundary.height));
  lens.centre_x = boundary.width  * (100.0 + o->x_shift) / 200.0;
  lens.centre_y = boundary.height * (100.0 + o->y_shift) / 200.0;
  lens.mult_sq  = o->main / 200.0;
  lens.mult_qd  = o->edge / 200.0;
  lens.rescale  = pow (2.0, - o->zoom / 100.0);
  lens.brighten = - o->brighten / 10.0;
116

117
  return lens;
118 119
}

120 121 122 123 124 125 126
static void
lens_get_source_coord (gdouble     i,
                       gdouble     j,
                       gdouble    *x,
                       gdouble    *y,
                       gdouble    *mag,
                       LensValues *lens)
127
{
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
  gdouble radius_sq, off_x, off_y, radius_mult;

  off_x = i - lens->centre_x;
  off_y = j - lens->centre_y;

  radius_sq = SQR (off_x) + SQR (off_y);

  radius_sq *= lens->norm;

  radius_mult = radius_sq * lens->mult_sq + SQR (radius_sq) * lens->mult_qd;

  *mag = radius_mult;

  radius_mult = lens->rescale * (1.0 + radius_mult);

  *x = lens->centre_x + radius_mult * off_x;
  *y = lens->centre_y + radius_mult * off_y;
145 146
}

147 148 149 150 151
/* FIXME: not 100% bullet proof */
static GeglRectangle
get_required (GeglRectangle       *boundary,
              const GeglRectangle *roi,
              GeglOperation       *operation)
152
{
153

154 155 156 157 158
  GeglProperties *o;
  GeglRectangle   area;
  LensValues      lens;
  gdouble         x1, y1, x2, y2, x3, y3, x4, y4, mag;
  gint            x, y, width, height;
159

160
  o = GEGL_PROPERTIES (operation);
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

  lens = lens_setup_calc (o, *boundary);

  x = roi->x;
  y = roi->y;
  width = roi->width;
  height = roi->height;

  lens_get_source_coord (x,         y,          &x1, &y1, &mag, &lens);
  lens_get_source_coord (x + width, y,          &x2, &y2, &mag, &lens);
  lens_get_source_coord (x,         y + height, &x3, &y3, &mag, &lens);
  lens_get_source_coord (x + width, y + height, &x4, &y4, &mag, &lens);

  /* This is ugly, and happens
   * with a crazy set of parameters */
  reorder (&x1, &x2);
  reorder (&x3, &x4);

  reorder (&y1, &y3);
  reorder (&y2, &y4);

  if (lens.centre_y > y && lens.centre_y < y + height)
    {
      gdouble x5, y5, x6, y6;

      lens_get_source_coord (x,         lens.centre_y, &x5, &y5, &mag, &lens);
      lens_get_source_coord (x + width, lens.centre_y, &x6, &y6, &mag, &lens);

      reorder (&x5, &x6);

      area.x = floor (MIN3 (x1, x3, x5)) - 1;
      area.width = ceil (MAX3 (x2, x4, x6)) + 3 - area.x;
    }
  else
    {
      area.x = floor (MIN (x1, x3)) - 1;
      area.width = ceil (MAX (x2, x4)) + 3 - area.x;
    }

  if (lens.centre_x > x && lens.centre_x < x + width)
    {
      gdouble x5, y5, x6, y6;

      lens_get_source_coord (lens.centre_x, y,          &x5, &y5, &mag, &lens);
      lens_get_source_coord (lens.centre_x, y + height, &x6, &y6, &mag, &lens);

      reorder (&y5, &y6);

      area.y = floor (MIN3 (y1, y2, y5)) - 1;
      area.height = ceil (MAX3 (y3, y4, y6)) + 3 - area.y;
    }
  else
    {
      area.y = floor (MIN (y1, y2)) - 1;
      area.height = ceil (MAX (y3, y4)) + 3 - area.y;
    }

  return area;
219 220 221
}

static void
222 223 224
clamp_area (GeglRectangle *area,
            gdouble        center_x,
            gdouble        center_y)
225
{
226 227 228 229 230 231 232 233 234
  if (center_x <= area->x || area->width < 1)
    {
      area->width = CLAMP (area->width, 1, MAX_WH);
    }
  else
    {
      area->x += area->width - CLAMP (area->width, 1, MAX_WH);
      area->width = CLAMP (area->width, 1, MAX_WH);
    }
235

236 237 238 239 240 241 242 243 244 245
  if (center_y <= area->y || area->height < 1)
    {
      area->height = CLAMP (area->height, 1, MAX_WH);
    }
  else
    {
      area->y += area->height - CLAMP (area->height, 1, MAX_WH);
      area->height = CLAMP (area->height, 1, MAX_WH);
    }
}
246

247 248 249 250 251 252
static GeglRectangle
get_required_for_output (GeglOperation       *operation,
                         const gchar         *input_pad,
                         const GeglRectangle *roi)
{
  GeglRectangle *boundary;
253

254
  boundary = gegl_operation_source_get_bounding_box (operation, "input");
255

256 257
  if (strcmp (input_pad, "input") || !boundary)
    return *GEGL_RECTANGLE (0, 0, 0, 0);
258

259 260
  return get_required (boundary, roi, operation);
}
261

262 263 264 265 266
static void
prepare (GeglOperation *operation)
{
  gegl_operation_set_format (operation, "input", babl_format ("RGBA float"));
  gegl_operation_set_format (operation, "output", babl_format ("RGBA float"));
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
}

/*
 * Catmull-Rom cubic interpolation
 *
 * equally spaced points p0, p1, p2, p3
 * interpolate 0 <= u < 1 between p1 and p2
 *
 * (1 u u^2 u^3) (  0.0  1.0  0.0  0.0 ) (p0)
 *               ( -0.5  0.0  0.5  0.0 ) (p1)
 *               (  1.0 -2.5  2.0 -0.5 ) (p2)
 *               ( -0.5  1.5 -1.5  0.5 ) (p3)
 *
 */

static void
lens_cubic_interpolate (gfloat  *src,
                        gfloat  *dst,
                        gdouble  dx,
                        gdouble  dy,
                        gdouble  brighten)
{
  gfloat um1, u, up1, up2;
  gfloat vm1, v, vp1, vp2;
  gint   c, row_stride = 16;
  gfloat verts[16];

  um1 = ((-0.5 * dx + 1.0) * dx - 0.5) * dx;
  u = (1.5 * dx - 2.5) * dx * dx + 1.0;
  up1 = ((-1.5 * dx + 2.0) * dx + 0.5) * dx;
  up2 = (0.5 * dx - 0.5) * dx * dx;

  vm1 = ((-0.5 * dy + 1.0) * dy - 0.5) * dy;
  v = (1.5 * dy - 2.5) * dy * dy + 1.0;
  vp1 = ((-1.5 * dy + 2.0) * dy + 0.5) * dy;
  vp2 = (0.5 * dy - 0.5) * dy * dy;

  for (c = 0; c < 4 * 4; ++c)
    {
306 307
      verts[c] = vm1 * src[c] + v * src[c + row_stride] +
        vp1 * src[c + row_stride * 2] + vp2 * src[ c + row_stride * 3];
308 309 310 311 312 313
    }

  for (c = 0; c < 4; ++c)
    {
      gfloat result;

314 315
      result = um1 * verts[c] + u * verts[c + 4] +
        up1 * verts[c + 4 * 2] + up2 * verts[c + 4 * 3];
316

317 318
      if (c != 3)
        result *= brighten;
319 320 321 322 323 324 325 326 327 328 329

      dst[c] = CLAMP (result, 0.0, 1.0);
    }
}

static void
lens_distort_func (gfloat              *src_buf,
                   gfloat              *dst_buf,
                   const GeglRectangle *extended,
                   const GeglRectangle *result,
                   const GeglRectangle *boundary,
330
                   LensValues          *lens,
331 332
                   gint                 xx,
                   gint                 yy,
333
                   GeglBuffer          *input,
334 335
                   gfloat              *background,
                   gint                 level)
336
{
337 338 339 340 341
  gdouble sx, sy, mag;
  gdouble brighten;
  gfloat  pixel_buffer [16 * 4], temp[4];
  gdouble dx, dy;
  gint    x_int, y_int, x = 0, y = 0, offset = 0;
342

343
  temp[0] = temp[1] = temp[2] = temp[3] = 0.0;
344

345
  lens_get_source_coord ((gdouble) xx, (gdouble) yy, &sx, &sy, &mag, lens);
346

347 348
  /* pseudo gamma transformation, since the input is scRGB */
  brighten = pow (MAX (1.0 + mag * lens->brighten, 0.0), 2.4);
349

350 351
  x_int = floor (sx);
  dx = sx - x_int;
352

353 354
  y_int = floor (sy);
  dy = sy - y_int;
355

356 357 358 359 360 361
  for (y = y_int - 1; y <= y_int + 2; y++)
    {
      for (x = x_int - 1; x <= x_int + 2; x++)
        {
          gint b;

362 363
          if (x < boundary->x || x >= (boundary->x + boundary->width) ||
              y < boundary->y || y >= (boundary->y + boundary->height))
364
            {
365
              for (b = 0; b < 4; b++)
366
                pixel_buffer[offset++] = background[b];
367
            }
368
          else
369
            {
370

371 372 373 374 375 376 377 378 379 380 381 382
              if (x >= extended->x && x < (extended->x + extended->width) &&
                  y >= extended->y && y < (extended->y + extended->height))
                {
                  gint src_off;
                  src_off = (y - extended->y) * extended->width * 4 +
                    (x - extended->x) * 4;

                  for (b = 0; b < 4; b++)
                    temp[b] = src_buf[src_off++];
                }
              else
                {
383
                  gegl_buffer_sample_at_level (input, x, y, NULL, temp,
384
                                      babl_format ("RGBA float"),
385
                                      level,
386 387 388
                                      GEGL_SAMPLER_LINEAR,
                                      GEGL_ABYSS_CLAMP);
                }
389

390 391 392
              for (b = 0; b < 4; b++)
                pixel_buffer[offset++] = temp[b];
            }
393 394
        }
    }
395 396 397 398

  lens_cubic_interpolate (pixel_buffer, temp, dx, dy, brighten);

  offset = (yy - result->y) * result->width * 4 + (xx - result->x) * 4;
399 400

  for (x = 0; x < 4; x++)
401
    dst_buf[offset++] = temp[x];
402 403 404 405 406 407
}

static gboolean
process (GeglOperation       *operation,
         GeglBuffer          *input,
         GeglBuffer          *output,
408 409
         const GeglRectangle *result,
         gint                 level)
410
{
411 412 413 414 415 416
  GeglProperties *o = GEGL_PROPERTIES (operation);
  LensValues      lens;
  GeglRectangle   boundary;
  gint            i, j;
  gfloat         *src_buf, *dst_buf;
  gfloat          background[4];
417 418 419

  boundary = *gegl_operation_source_get_bounding_box (operation, "input");
  lens     =  lens_setup_calc (o, boundary);
420

421 422
  src_buf = g_new0 (gfloat, SQR (MAX_WH) * 4);
  dst_buf = g_new0 (gfloat, SQR (CHUNK_SIZE) * 4);
423

424 425
  gegl_color_get_pixel (o->background, babl_format ("RGBA float"), background);

426 427 428 429 430 431
  for (j = 0; (j-1) * CHUNK_SIZE < result->height; j++)
    for (i = 0; (i-1) * CHUNK_SIZE < result->width; i++)
      {
        GeglRectangle chunked_result;
        GeglRectangle area;
        gint          x, y;
432

433 434 435
        chunked_result = *GEGL_RECTANGLE (result->x + i * CHUNK_SIZE,
                                          result->y + j * CHUNK_SIZE,
                                          CHUNK_SIZE, CHUNK_SIZE);
436

437
        gegl_rectangle_intersect (&chunked_result, &chunked_result, result);
438

439 440
        if (chunked_result.width < 1  || chunked_result.height < 1)
          continue;
441

442
        area = get_required (&boundary, &chunked_result, operation);
443

444 445 446 447 448 449 450 451 452
        clamp_area (&area, lens.centre_x, lens.centre_y);

        gegl_buffer_get (input, &area, 1.0, babl_format ("RGBA float"), src_buf,
                         GEGL_AUTO_ROWSTRIDE, GEGL_ABYSS_CLAMP);

        for (y = chunked_result.y; y < chunked_result.y + chunked_result.height; y++)
          for (x = chunked_result.x; x < chunked_result.x + chunked_result.width; x++)
            {
              lens_distort_func (src_buf, dst_buf, &area, &chunked_result, &boundary,
453
                                 &lens, x, y, input, background, level);
454 455 456 457 458
            }

        gegl_buffer_set (output, &chunked_result, 0, babl_format ("RGBA float"),
                         dst_buf, GEGL_AUTO_ROWSTRIDE);
      }
459 460 461 462 463 464 465 466

  g_free (dst_buf);
  g_free (src_buf);

  return TRUE;
}

static void
467
gegl_op_class_init (GeglOpClass *klass)
468 469 470
{
  GeglOperationClass       *operation_class;
  GeglOperationFilterClass *filter_class;
471 472
  gchar                    *composition =
    "<?xml version='1.0' encoding='UTF-8'?>"
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
    "<gegl>"
    "<node operation='gegl:lens-distortion'>"
    "  <params>"
    "    <param name='main'>100</param>"
    "    <param name='zoom'>20</param>"
    "    <param name='edge'>100</param>"
    "    <param name='x-shift'>20</param>"
    "    <param name='y-shift'>20</param>"
    "  </params>"
    "</node>"
    "<node operation='gegl:load'>"
    "  <params>"
    "    <param name='path'>standard-input.png</param>"
    "  </params>"
    "</node>"
    "</gegl>";
489 490 491 492

  operation_class = GEGL_OPERATION_CLASS (klass);
  filter_class    = GEGL_OPERATION_FILTER_CLASS (klass);

493
  operation_class->prepare                 = prepare;
494 495
  operation_class->get_required_for_output = get_required_for_output;

496 497
  filter_class->process                    = process;

498
  gegl_operation_class_set_keys (operation_class,
499
    "name",                  "gegl:lens-distortion",
500
    "title",                 _("Lens Distortion"),
501 502
    "categories",            "blur",
    "position-dependent",    "true",
503
    "license",               "GPL3+",
504
    "reference-composition", composition,
505
    "description", _("Corrects barrel or pincushion lens distortion."),
506
    NULL);
507 508 509
}

#endif