ddnet/src/tools/dilate.cpp

104 lines
2.1 KiB
C++
Raw Normal View History

2011-03-17 16:38:21 +00:00
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include <base/system.h>
#include <base/math.h>
#include <pnglite.h>
2011-03-17 16:38:21 +00:00
typedef struct
{
unsigned char r, g, b, a;
} CPixel;
static void Dilate(int w, int h, CPixel *pSrc, CPixel *pDest)
{
int ix, iy;
const int xo[] = {0, -1, 1, 0};
const int yo[] = {-1, 0, 0, 1};
2011-03-17 16:38:21 +00:00
int m = 0;
for(int y = 0; y < h; y++)
{
for(int x = 0; x < w; x++, m++)
{
pDest[m] = pSrc[m];
if(pSrc[m].a)
continue;
2011-03-17 16:38:21 +00:00
for(int c = 0; c < 4; c++)
{
ix = clamp(x + xo[c], 0, w-1);
iy = clamp(y + yo[c], 0, h-1);
int k = iy*w+ix;
if(pSrc[k].a)
{
pDest[m] = pSrc[k];
pDest[m].a = 255;
break;
}
}
}
}
}
static void CopyAlpha(int w, int h, CPixel *pSrc, CPixel *pDest)
{
int m = 0;
for(int y = 0; y < h; y++)
for(int x = 0; x < w; x++, m++)
pDest[m].a = pSrc[m].a;
}
2011-07-11 09:26:41 +00:00
int DilateFile(const char *pFileName)
2011-03-17 16:38:21 +00:00
{
png_t Png;
CPixel *pBuffer[3] = {0,0,0};
2011-03-17 16:38:21 +00:00
png_init(0, 0);
2011-07-11 09:26:41 +00:00
png_open_file(&Png, pFileName);
2011-03-17 16:38:21 +00:00
if(Png.color_type != PNG_TRUECOLOR_ALPHA)
{
2011-07-11 09:26:41 +00:00
dbg_msg("dilate", "%s: not an RGBA image", pFileName);
return 1;
2011-03-17 16:38:21 +00:00
}
2011-03-17 16:38:21 +00:00
pBuffer[0] = (CPixel*)mem_alloc(Png.width*Png.height*sizeof(CPixel), 1);
pBuffer[1] = (CPixel*)mem_alloc(Png.width*Png.height*sizeof(CPixel), 1);
pBuffer[2] = (CPixel*)mem_alloc(Png.width*Png.height*sizeof(CPixel), 1);
png_get_data(&Png, (unsigned char *)pBuffer[0]);
png_close_file(&Png);
2011-03-17 16:38:21 +00:00
int w = Png.width;
int h = Png.height;
2011-03-17 16:38:21 +00:00
Dilate(w, h, pBuffer[0], pBuffer[1]);
for(int i = 0; i < 5; i++)
{
Dilate(w, h, pBuffer[1], pBuffer[2]);
Dilate(w, h, pBuffer[2], pBuffer[1]);
}
2011-03-17 16:38:21 +00:00
CopyAlpha(w, h, pBuffer[0], pBuffer[1]);
2011-03-17 16:38:21 +00:00
// save here
2011-07-11 09:26:41 +00:00
png_open_file_write(&Png, pFileName);
2011-03-17 16:38:21 +00:00
png_set_data(&Png, w, h, 8, PNG_TRUECOLOR_ALPHA, (unsigned char *)pBuffer[1]);
png_close_file(&Png);
2011-03-17 16:38:21 +00:00
return 0;
}
int main(int argc, const char **argv)
{
dbg_logger_stdout();
if(argc == 1)
{
dbg_msg("usage", "%s FILE1 [ FILE2... ]", argv[0]);
return -1;
}
2011-08-11 08:59:14 +00:00
2011-07-11 09:26:41 +00:00
for(int i = 1; i < argc; i++)
DilateFile(argv[i]);
return 0;
}