/* The GIMP -- an image manipulation program
 * Copyright (C) 1995-2001 Spencer Kimball, Peter Mattis, and others
 *
 * 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.
 *
 * 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
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include "config.h"

#include <glib-object.h>
    
#include "base-types.h"

#include "pixel-region.h"
#include "pixel-cache.h"
#include "tile-manager.h"
#include "tile.h"

void 
pixel_cache_init (PixelCache  *pc,
                  TileManager *tm,
                  guchar       bg[MAX_CHANNELS])
{
  int i;

  for (i=0; i<MAX_CHANNELS; i++)
      pc->bg[i] = bg[i];

  pc->tm  = tm;
  pc->tile= NULL;
  pc->num = -1;
  pc->bpp = tile_manager_bpp(tm);

  pc->width  = tile_manager_width(tm);
  pc->height = tile_manager_height(tm);  
}

void 
pixel_cache_clear (PixelCache *pc)
{
  if (pc->tile)
    {
      tile_release(pc->tile,FALSE);
      pc->tile=NULL;
    }
}

void
pixel_cache_get (PixelCache *pc,
        gint x, 
        gint y, 
        guchar color[MAX_CHANNELS])
{
    gint num;
    gint i;

    if ( x >= 0 && y >= 0 && x < pc->width && y < pc->height )
      {
        num = tile_manager_get_tile_num (pc->tm, x, y);

        if (num != pc->num)
          {
            if (pc->tile)
              {
                tile_release(pc->tile,FALSE);
                pc->tile=NULL;
              }

            pc->num=num;
            pc->tile=tile_manager_get (pc->tm, num, TRUE, FALSE);
          }

        if(pc->tile)
          {
            gpointer data;
            data = tile_data_pointer (pc->tile, 
                                      (x) % TILE_WIDTH, (y) % TILE_HEIGHT);
            memcpy(color, data, pc->bpp);
            return;
          }
      }

    for (i=0; i<MAX_CHANNELS; i++)
        color[i] = pc->bg[i];

}
