/*
 *  libpipi       Pathetic image processing interface library
 *  Copyright (c) 2004-2008 Sam Hocevar <sam@zoy.org>
 *                All Rights Reserved
 *
 *  $Id$
 *
 *  This library is free software. It comes without any warranty, to
 *  the extent permitted by applicable law. You can redistribute it
 *  and/or modify it under the terms of the Do What The Fuck You Want
 *  To Public License, Version 2, as published by Sam Hocevar. See
 *  http://sam.zoy.org/wtfpl/COPYING for more details.
 */

/*
 * wave.c: wave and warping effects
 */

#include "config.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>

#include "pipi.h"
#include "pipi_internals.h"

pipi_image_t *pipi_wave(pipi_image_t *src, double freq, double phase,
                        double theta, double xamp, double yamp)
{
    pipi_image_t *dst;
    pipi_pixels_t *srcp, *dstp;
    float *srcdata, *dstdata;
    double sint, cost;
    int x, y, w, h, i, gray;

    w = src->w;
    h = src->h;

    gray = (src->last_modified == PIPI_PIXELS_Y_F32);

    srcp = gray ? pipi_get_pixels(src, PIPI_PIXELS_Y_F32)
                : pipi_get_pixels(src, PIPI_PIXELS_RGBA_F32);
    srcdata = (float *)srcp->pixels;

    dst = pipi_new(w, h);
    dstp = gray ? pipi_get_pixels(dst, PIPI_PIXELS_Y_F32)
                : pipi_get_pixels(dst, PIPI_PIXELS_RGBA_F32);
    dstdata = (float *)dstp->pixels;

    sint = sin(theta);
    cost = cos(theta);

    for(y = 0; y < h; y++)
    {
        for(x = 0; x < w; x++)
        {
            double t = cost * (x - w / 2) + sint * (y - h / 2);
            double step = sin(t * freq + phase);
            double dx = xamp * step;
            double dy = yamp * step;

            int x2 = x + dx;
            int y2 = y + dy;

            if(x2 < 0) x2 = 0;
            else if(x2 >= w) x2 = w - 1;

            if(y2 < 0) y2 = 0;
            else if(y2 >= h) y2 = h - 1;

            if(gray)
            {
                dstdata[y * w + x] = srcdata[y2 * w + x2];
            }
            else
            {
                for(i = 0; i < 4; i++)
                {
                    dstdata[4 * (y * w + x) + i]
                        = srcdata[4 * (y2 * w + x2) + i];
                }
            }
        }
    }

    return dst;
}