summaryrefslogtreecommitdiffstats
path: root/chalk/plugins/filters/cubismfilter/kis_cubism_filter.cpp
blob: 1eb2984efa42acf6e015153561d1b4c7f7eee6b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
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
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
306
307
308
309
310
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
/*
 * This file is part of Chalk
 *
 * Copyright (c) 2005 Michael Thaler <michael.thaler@physik.tu-muenchen.de>
 *
 * ported from Gimp, Copyright (C) 1997 Eiichi Takamori <taka@ma1.seikyou.ne.jp>
 * original pixelize.c for GIMP 0.54 by Tracy Scott
 *
 *  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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include <stdlib.h>
#include <time.h>
#include <vector>

#include <tqpoint.h>
#include <tqspinbox.h>

#include <tdelocale.h>
#include <kiconloader.h>
#include <kinstance.h>
#include <tdemessagebox.h>
#include <kstandarddirs.h>
#include <tdetempfile.h>
#include <kdebug.h>
#include <kgenericfactory.h>
#include <knuminput.h>

#include <kis_painter.h>
#include <kis_meta_registry.h>
#include <kis_colorspace_factory_registry.h>
#include <kis_doc.h>
#include <kis_image.h>
#include <kis_iterators_pixel.h>
#include <kis_layer.h>
#include <kis_filter_registry.h>
#include <kis_global.h>
#include <kis_types.h>
#include <kis_progress_display_interface.h>
#include <kis_vec.h>

#include "kis_multi_integer_filter_widget.h"
#include "kis_cubism_filter.h"
#include "kis_polygon.h"
#include "kis_point.h"

#define RANDOMNESS       5
#define SUPERSAMPLE      4
#define CLAMP(x,l,u) ((x)<(l)?(l):((x)>(u)?(u):(x)))
#define SQR(x) ((x) * (x))

KisCubismFilter::KisCubismFilter() : KisFilter(id(), "artistic", i18n("&Cubism..."))
{
}

bool KisCubismFilter::workWith(KisColorSpace* /*cs*/)
{
    return true;
}


void KisCubismFilter::process(KisPaintDeviceSP src, KisPaintDeviceSP dst,
                               KisFilterConfiguration* configuration, const TQRect& rect)
{
    Q_ASSERT(src);
    Q_ASSERT(dst);
    Q_ASSERT(configuration);
    
    //read the filter configuration values from the KisFilterConfiguration object
    TQ_UINT32 tileSize = ((KisCubismFilterConfiguration*)configuration)->tileSize();
    TQ_UINT32 tileSaturation = ((KisCubismFilterConfiguration*)configuration)->tileSaturation();

    KisColorSpace * cs = src->colorSpace();
    TQString id = cs->id().id();

    if (id == "RGBA" || id == "GRAY" || id == "CMYK") {
        cubism(src, dst, rect, tileSize, tileSaturation);
    }
    else {
        if (src->image()) src->image()->lock();
    
        KisPaintDeviceSP dev = new KisPaintDevice(KisMetaRegistry::instance()->csRegistry()->getRGB8(), "temporary");
        KisPainter gc(dev);
        gc.bitBlt(0, 0, COMPOSITE_COPY, src, rect.x(), rect.y(), rect.width(), rect.height());
        gc.end();
        
        kdDebug() << src->colorSpace()->id().id() << endl;
        cubism(dev, dev, TQRect(0, 0, rect.width(), rect.height()), tileSize, tileSaturation);

        gc.begin(dst);
        gc.bitBlt(rect.x(), rect.y(), COMPOSITE_COPY, dev, 0, 0, rect.width(), rect.height());
        gc.end();      
        if (src->image()) src->image()->unlock();
    
        kdDebug() << src->colorSpace()->id().id() << endl;
    }
}

void KisCubismFilter::randomizeIndices (TQ_INT32 count, TQ_INT32* indices)
{
        TQ_INT32 index1, index2;
        TQ_INT32 tmp;

        //initialize random number generator with time
        srand(static_cast<unsigned int>(time(0)));

        for (TQ_INT32 i = 0; i < count * RANDOMNESS; i++)
        {
                index1 = randomIntNumber(0, count);
                index2 = randomIntNumber(0, count);
                tmp = indices[index1];
                indices[index1] = indices[index2];
                indices[index2] = tmp;
        }
}

TQ_INT32 KisCubismFilter::randomIntNumber(TQ_INT32 lowestNumber, TQ_INT32 highestNumber)
{
        if(lowestNumber > highestNumber)
        {
                TQ_INT32 temp = lowestNumber;
                lowestNumber = highestNumber;
                highestNumber = temp;
        }

        return lowestNumber + (( highestNumber - lowestNumber ) * rand() )/ RAND_MAX;
}

double KisCubismFilter::randomDoubleNumber(double lowestNumber, double highestNumber)
{
        if(lowestNumber > highestNumber)
        {
                double temp = lowestNumber;
                lowestNumber = highestNumber;
                highestNumber = temp;
        }

        double range = highestNumber - lowestNumber;
        return lowestNumber + range * rand() / (double)RAND_MAX;
}

double KisCubismFilter::calcAlphaBlend (double* vec, double  oneOverDist, double  x, double  y)
{

        if ( oneOverDist==0 )
            return 1.0;
        else
        {
            double r = (vec[0] * x + vec[1] * y) * oneOverDist;
            if (r < 0.2)
                r = 0.2;
            else if (r > 1.0)
                r = 1.0;
            return r;
        }
}

void KisCubismFilter::convertSegment (TQ_INT32 x1, TQ_INT32 y1, TQ_INT32 x2, TQ_INT32  y2, TQ_INT32 offset, TQ_INT32* min, TQ_INT32* max, TQ_INT32 xmin, TQ_INT32 xmax)
{
        if (y1 > y2)
        {
                TQ_INT32 tmp = y2; y2 = y1; y1 = tmp;
                tmp = x2; x2 = x1; x1 = tmp;
        }
        TQ_INT32 ydiff = (y2 - y1);

        if (ydiff)
        {
                double xinc = static_cast<double>(x2 - x1) / static_cast<double>(ydiff);
                double xstart = x1 + 0.5 * xinc;
                for (TQ_INT32 y = y1 ; y < y2; y++)
                {
                    if(xstart >= xmin && xstart <= xmax)
                    {
                        if (xstart < min[y - offset])
                        {
                            min[y-offset] = (int)xstart;
                        }
                        if (xstart > max[y - offset])
                        {
                            max[y-offset] = (int)xstart;
                        }
                        xstart += xinc;
                    }
                }
        }
}

#define USE_READABLE_BUT_SLOW_CODE

void KisCubismFilter::fillPolyColor (KisPaintDeviceSP src, KisPaintDeviceSP dst, KisPolygon* poly, const TQ_UINT8* col, TQ_UINT8* /*s*/, TQRect rect)
{
        TQ_INT32         val;
        TQ_INT32         alpha;
        TQ_UINT8         buf[4];
        TQ_INT32         x, y;
        double          xx, yy;
        double          vec[2];
        TQ_INT32         x1 = rect.left(), y1 = rect.top(), x2 = rect.right(), y2 = rect.bottom();
//         TQ_INT32         selWidth, selHeight;
        TQ_INT32         *vals, *valsIter, *valsEnd;
        TQ_INT32         b;
        TQ_INT32         xs, ys, xe, ye;


        TQ_INT32 sx = (TQ_INT32) (*poly)[0].x();
        TQ_INT32 sy = (TQ_INT32) (*poly)[0].y();
        TQ_INT32 ex = (TQ_INT32) (*poly)[1].x();
        TQ_INT32 ey = (TQ_INT32) (*poly)[1].y();

        double dist = sqrt (SQR (ex - sx) + SQR (ey - sy));
        double oneOverDist = 0.0;
        if (dist > 0.0)
        {
                double oneOverDist = 1/dist;
                vec[0] = (ex - sx) * oneOverDist;
                vec[1] = (ey - sy) * oneOverDist;
        }

        TQ_INT32 pixelSize = src->pixelSize();
        //get the extents of the polygon
        double dMinX, dMinY, dMaxX, dMaxY;
        poly->extents (dMinX, dMinY, dMaxX, dMaxY);
        TQ_INT32 minX = static_cast<TQ_INT32>(dMinX);
        TQ_INT32 minY = static_cast<TQ_INT32>(dMinY);
        TQ_INT32 maxX = static_cast<TQ_INT32>(dMaxX);
        TQ_INT32 maxY = static_cast<TQ_INT32>(dMaxY);
        TQ_INT32 sizeX = (maxX - minX) * SUPERSAMPLE;
        TQ_INT32 sizeY = (maxY - minY) * SUPERSAMPLE;

        TQ_INT32 *minScanlines = new TQ_INT32[sizeY];
        TQ_INT32 *minScanlinesIter = minScanlines;
        TQ_INT32 *maxScanlines = new TQ_INT32[sizeY];
        TQ_INT32 *maxScanlinesIter = maxScanlines;

        for (TQ_INT32 i = 0; i < sizeY; i++)
        {
            minScanlines[i] = maxX * SUPERSAMPLE;
            maxScanlines[i] = minX * SUPERSAMPLE;
        }

        if ( poly->numberOfPoints() )
        {
                TQ_INT32 polyNpts = poly->numberOfPoints();

                xs = static_cast<TQ_INT32>((*poly)[polyNpts-1].x());
                ys = static_cast<TQ_INT32>((*poly)[polyNpts-1].y());
                xe = static_cast<TQ_INT32>((*poly)[0].x());
                ye = static_cast<TQ_INT32>((*poly)[0].y());

                xs *= SUPERSAMPLE;
                ys *= SUPERSAMPLE;
                xe *= SUPERSAMPLE;
                ye *= SUPERSAMPLE;

                convertSegment (xs, ys, xe, ye, minY * SUPERSAMPLE, minScanlines, maxScanlines, minX* SUPERSAMPLE, maxX* SUPERSAMPLE);

                KisPolygon::iterator it;

                for ( it = poly->begin(); it != poly->end(); )
                {
                        xs = static_cast<TQ_INT32>((*it).x());
                        ys = static_cast<TQ_INT32>((*it).y());
                        ++it;
                        
                        if( it != poly->end() )
                        {
                            xe = static_cast<TQ_INT32>((*it).x());
                            ye = static_cast<TQ_INT32>((*it).y());

                            xs *= SUPERSAMPLE;
                            ys *= SUPERSAMPLE;
                            xe *= SUPERSAMPLE;
                            ye *= SUPERSAMPLE;

                            convertSegment (xs, ys, xe, ye, minY * SUPERSAMPLE, minScanlines, maxScanlines, minX* SUPERSAMPLE, maxX* SUPERSAMPLE);
                        }
                }
        }

        vals = new TQ_INT32[sizeX];
//         x1 = minX; x2 = maxX; y1 = minY; y2 = maxY;
        for (TQ_INT32 i = 0; i < sizeY; i++, minScanlinesIter++, maxScanlinesIter++)
        {
                if (! (i % SUPERSAMPLE))
                {
                        memset (vals, 0, sizeof( TQ_INT32 ) * sizeX);
                }

                yy = static_cast<double>(i) / static_cast<double>(SUPERSAMPLE) + minY;

                for (TQ_INT32 j = *minScanlinesIter; j < *maxScanlinesIter; j++)
                {
                        x = j - minX * SUPERSAMPLE;
                        vals[x] += 255;
                }

                if (! ((i + 1) % SUPERSAMPLE))
                {
                        y = (i / SUPERSAMPLE) + minY;
                        if (y >= y1 && y <= y2)
                        {
                                for (TQ_INT32 j = 0; j < sizeX; j += SUPERSAMPLE)
                                {
                                        x = (j / SUPERSAMPLE) + minX;

                                        if (x >= x1 && x <= x2)
                                        {
                                                for (val = 0, valsIter = &vals[j], valsEnd = &valsIter[SUPERSAMPLE]; valsIter < valsEnd; valsIter++)
                                                {
                                                        val += *valsIter;
                                                }
                                                val /= SQR(SUPERSAMPLE);

                                                if (val > 0)
                                                {
                                                        xx = static_cast<double>(j) / static_cast<double>(SUPERSAMPLE) + minX;
                                                        alpha = static_cast<TQ_INT32>(val * calcAlphaBlend (vec, oneOverDist, xx - sx, yy - sy));

//                                                         KisRectIteratorPixel srcIt = src->createRectIterator(x,y,1,1, false);
//                                                         const TQ_UINT8* srcPixel = srcIt.oldRawData();
//                                                         memcpy( buf, srcPixel, sizeof(TQ_UINT8) * pixelSize );
                                                        src->readBytes(buf, x, y, 1, 1);
                                                #ifndef USE_READABLE_BUT_SLOW_CODE
                                                        TQ_UINT8 *bufIter = buf;
                                                        const TQ_UINT8 *colIter = col;
                                                        TQ_UINT8 *bufEnd = buf+pixelSize;

                                                        for(; bufIter < bufEnd; bufIter++, colIter++)
                                                        *bufIter = (static_cast<TQ_UINT8>(*colIter * alpha)
                                                                        + (static_cast<TQ_UINT8>(*bufIter)
                                                                        * (256 - alpha))) >> 8;
                                                #else  //original, pre-ECL code
                                                        for (b = 0; b < pixelSize; b++)
                                                        {
                                                            buf[b] = ((col[b] * alpha) + (buf[b] * (255 - alpha))) / 255;
                                                        }
                                                #endif
                                                        
                                                        dst->writeBytes(buf, x, y, 1, 1);
                                                }
                                        }
                                }
                        }
                }
        }
    delete[] vals;
    delete[] minScanlines;
    delete[] maxScanlines;
}

void KisCubismFilter::cubism(KisPaintDeviceSP src, KisPaintDeviceSP dst, const TQRect& rect, TQ_UINT32 tileSize, TQ_UINT32 tileSaturation)
{
    Q_ASSERT(src);
    Q_ASSERT(dst);
    
        //fill the destination image with the background color (black for now)
        KisRectIteratorPixel dstIt = dst->createRectIterator(rect.x(), rect.y(), rect.width(), rect.height(), true );
        TQ_INT32 depth = src->colorSpace()->nColorChannels();
        while( ! dstIt.isDone() )
        {
                for( TQ_INT32 i = 0; i < depth; i++)
                {
                        dstIt.rawData()[i] = 0;
                }
                ++dstIt;
        }

        //compute number of rows and columns
        TQ_INT32 cols = ( rect.width() + tileSize - 1) / tileSize;
        TQ_INT32 rows = ( rect.height() + tileSize - 1) / tileSize;
        TQ_INT32 numTiles = (rows + 1) * (cols + 1);

        setProgressTotalSteps(numTiles);
        setProgressStage(i18n("Applying cubism filter..."),0);

        TQ_INT32* randomIndices = new TQ_INT32[numTiles];
        for (TQ_INT32 i = 0; i < numTiles; i++)
        {
                randomIndices[i] = i;
        }
        randomizeIndices (numTiles, randomIndices);

        TQ_INT32 count = 0;
        TQ_INT32 i, j, ix, iy;
        double x, y, width, height, theta;
        KisPolygon *poly = new KisPolygon();
        TQ_INT32 pixelSize = src->pixelSize();
        const TQ_UINT8 *srcPixel /*= new TQ_UINT8[ pixelSize ]*/;
        TQ_UINT8 *dstPixel = 0;
        while (count < numTiles)
        {
                i = randomIndices[count] / (cols + 1);
                j = randomIndices[count] % (cols + 1);
                x = j * tileSize + (tileSize / 4.0) - randomDoubleNumber(0, tileSize/2.0) + rect.x();
                y = i * tileSize + (tileSize / 4.0) - randomDoubleNumber(0, tileSize/2.0) + rect.y();
                width = (tileSize + randomDoubleNumber(0, tileSize / 4.0) - tileSize / 8.0) * tileSaturation;
                height = (tileSize + randomDoubleNumber (0, tileSize / 4.0) - tileSize / 8.0) * tileSaturation;
                theta = randomDoubleNumber(0, 2*M_PI);
                poly->clear();
                poly->addPoint( -width / 2.0, -height / 2.0 );
                poly->addPoint( width / 2.0, -height / 2.0 );
                poly->addPoint( width / 2.0, height / 2.0 );
                poly->addPoint( -width / 2.0, height / 2.0 );
                poly->rotate( theta );
                poly->translate ( x, y );
                //  bounds check on x, y
                ix = (TQ_INT32) CLAMP (x, rect.x(), rect.x() + rect.width() - 1);
                iy = (TQ_INT32) CLAMP (y, rect.y(), rect.y() + rect.height() - 1);

                //read the pixel at ix, iy
                KisRectIteratorPixel srcIt = src->createRectIterator(ix,iy,1,1, false);
                srcPixel = srcIt.oldRawData();
                if (srcPixel[pixelSize - 1])
                {
                    fillPolyColor (src, dst, poly, srcPixel, dstPixel, rect);
                }
                count++;
                if ((count % 5) == 0) setProgress(count);
        }
        setProgressDone();
}

KisFilterConfigWidget * KisCubismFilter::createConfigurationWidget(TQWidget* parent, KisPaintDeviceSP /*dev*/)
{
    vKisIntegerWidgetParam param;
    param.push_back( KisIntegerWidgetParam( 2, 40, 10, i18n("Tile size"), "tileSize" ) );
    param.push_back( KisIntegerWidgetParam( 2, 40, 10, i18n("Tile saturation"), "tileSaturation" ) );
    return new KisMultiIntegerFilterWidget(parent, id().id().ascii(), id().id().ascii(), param );
}

KisFilterConfiguration* KisCubismFilter::configuration(TQWidget* nwidget)
{
    KisMultiIntegerFilterWidget* widget = (KisMultiIntegerFilterWidget*) nwidget;
    if( widget == 0 )
    {
        return new KisCubismFilterConfiguration( 10, 10);
    } else {
        return new KisCubismFilterConfiguration( widget->valueAt( 0 ), widget->valueAt( 1 ) );
    }
}