summaryrefslogtreecommitdiffstats
path: root/chalk/plugins/paintops/defaultpaintops/kis_duplicateop.cc
blob: 556a77751e0737d9b73bb509df93b901ec83f858 (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
/*
 *  Copyright (c) 2002 Patrick Julien <freak@codepimps.org>
 *  Copyright (c) 2004 Boudewijn Rempt <boud@valdyas.org>
 *  Copyright (c) 2004 Clarence Dang <dang@kde.org>
 *  Copyright (c) 2004 Adrian Page <adrian@pagenet.plus.com>
 *  Copyright (c) 2004-2006 Cyrille Berger <cberger@cberger.net>
 *
 *  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 "kis_duplicateop.h"

#include <tqrect.h>

#include <kdebug.h>

#include "kis_brush.h"
#include "kis_global.h"
#include "kis_paint_device.h"
#include "kis_layer.h"
#include "kis_painter.h"
#include "kis_types.h"
#include "kis_meta_registry.h"
#include "kis_colorspace_factory_registry.h"
#include "kis_paintop.h"
#include "kis_iterators_pixel.h"
#include "kis_selection.h"
#include "kis_perspective_grid.h"
#include "kis_random_sub_accessor.h"

KisPaintOp * KisDuplicateOpFactory::createOp(const KisPaintOpSettings */*settings*/, KisPainter * painter)
{
    KisPaintOp * op = new KisDuplicateOp(painter);
    TQ_CHECK_PTR(op);
    return op;
}


KisDuplicateOp::KisDuplicateOp(KisPainter * painter)
    : super(painter)
    , m_target(0)
    , m_srcdev(0)
{
}

KisDuplicateOp::~KisDuplicateOp()
{
}

double KisDuplicateOp::minimizeEnergy(const double* m, double* sol, int w, int h)
{
    int rowstride = 3*w;
    double err = 0;
    memcpy(sol, m, 3* sizeof(double) * w);
    m+=rowstride;
    sol+=rowstride;
    for ( int i = 1; i < h - 1; i++)
    {
        memcpy(sol, m, 3* sizeof(double));
        m+=3; sol+=3;
        for ( int j = 3; j < rowstride-3; j++)
        {
            double tmp = *sol;
            *sol = ( ( *(m - 3 ) + *(m + 3) + *(m - rowstride ) + *(m + rowstride )) + 2 * *m ) /6;
            double diff = *sol - tmp;
            err += diff*diff;
            m ++; sol ++;
        }
        memcpy(sol, m, 3* sizeof(double));
        m+=3; sol+=3;
}
    memcpy(sol, m, 3* sizeof(double) * w);
    return err;
}


void KisDuplicateOp::paintAt(const KisPoint &pos, const KisPaintInformation& info)
{
    if (!m_painter) return;

    bool heal = m_painter->duplicateHealing();
//     int healradius = m_painter->duplicateHealingRadius();

    KisPaintDeviceSP device = m_painter->device();
    if (m_source) device = m_source;
    if (!device) return;

    KisBrush * brush = m_painter->brush();
    if (!brush) return;
    if (! brush->canPaintFor(info) )
        return;

    KisPoint hotSpot = brush->hotSpot(info);
    KisPoint pt = pos - hotSpot;

    // Split the coordinates into integer plus fractional parts. The integer
    // is where the dab will be positioned and the fractional part determines
    // the sub-pixel positioning.
    TQ_INT32 x;
    double xFraction;
    TQ_INT32 y;
    double yFraction;

    splitCoordinate(pt.x(), &x, &xFraction);
    splitCoordinate(pt.y(), &y, &yFraction);
    xFraction = yFraction = 0.0;

    KisPaintDeviceSP dab = 0;

    if (brush->brushType() == IMAGE ||
        brush->brushType() == PIPE_IMAGE) {
        dab = brush->image(device->colorSpace(), info, xFraction, yFraction);
        dab->convertTo(KisMetaRegistry::instance()->csRegistry()->getAlpha8());
    }
    else {
        KisAlphaMaskSP mask = brush->mask(info, xFraction, yFraction);
        dab = computeDab(mask, KisMetaRegistry::instance()->csRegistry()->getAlpha8());
    }

    m_painter->setPressure(info.pressure);

    KisPoint srcPointF = pt - m_painter->duplicateOffset();
    TQPoint srcPoint = TQPoint(x - static_cast<TQ_INT32>(m_painter->duplicateOffset().x()),
                             y - static_cast<TQ_INT32>(m_painter->duplicateOffset().y()));


    TQ_INT32 sw = dab->extent().width();
    TQ_INT32 sh = dab->extent().height();

    if (srcPoint.x() < 0 )
        srcPoint.setX(0);

    if( srcPoint.y() < 0)
        srcPoint.setY(0);
    if( !(m_srcdev && m_srcdev->colorSpace() != device->colorSpace()) )
    {
        m_srcdev = new KisPaintDevice(device->colorSpace(), "duplicate source dev");
        m_target = new KisPaintDevice(device->colorSpace(), "duplicate target dev");
    }
    TQ_CHECK_PTR(m_srcdev);

    // Perspective correction ?
    KisPainter copyPainter(m_srcdev);
    if(m_painter->duplicatePerspectiveCorrection())
    {
        double startM[3][3];
        double endM[3][3];
        for(int i = 0; i < 3; i++)
        {
            for(int j = 0; j < 3; j++)
            {
                startM[i][j] = 0.;
                endM[i][j] = 0.;
            }
            startM[i][i] = 1.;
            endM[i][i] = 1.;
        }
        // First look for the grid corresponding to the start point
        KisSubPerspectiveGrid* subGridStart = *device->image()->perspectiveGrid()->begin();//device->image()->perspectiveGrid()->gridAt(KisPoint(srcPoint.x() +hotSpot.x(),srcPoint.y() +hotSpot.y()));
        TQRect r = TQRect(0,0, device->image()->width(), device->image()->height());

#if 1
        if(subGridStart)
        {
//             kdDebug() << "fgrid" << endl;
//             kdDebug() << *subGridStart->topLeft() << " " << *subGridStart->topRight() << " " << *subGridStart->bottomLeft() << " " <<  *subGridStart->bottomRight() << endl;
            double* b = KisPerspectiveMath::computeMatrixTransfoFromPerspective( r, *subGridStart->topLeft(), *subGridStart->topRight(), *subGridStart->bottomLeft(), *subGridStart->bottomRight());
            for(int i = 0; i < 3; i++)
            {
                for(int j = 0; j < 3; j++)
                {
//                     kdDebug() << "sol[" << 3*i+j << "]=" << b[3*i+j] << endl;
                    startM[i][j] = b[3*i+j];
                }
            }

        }
#endif
#if 1
        // Second look for the grid corresponding to the end point
        KisSubPerspectiveGrid* subGridEnd = *device->image()->perspectiveGrid()->begin();// device->image()->perspectiveGrid()->gridAt(pos);
        if(subGridEnd)
        {
//             kdDebug() << "second grid" << endl;
            double* b = KisPerspectiveMath::computeMatrixTransfoToPerspective(*subGridEnd->topLeft(), *subGridEnd->topRight(), *subGridEnd->bottomLeft(), *subGridEnd->bottomRight(), r);
            for(int i = 0; i < 3; i++)
            {
                for(int j = 0; j < 3; j++)
                {
//                     kdDebug() << "sol[" << 3*i+j << "]=" << b[3*i+j] << endl;
                    endM[i][j] = b[3*i+j];
                }
            }
        }
#endif
//         kdDebug()<< " oouuuuh" << srcPointF << KisPerspectiveMath::matProd(startM,  KisPerspectiveMath::matProd(endM, srcPointF ) ) << KisPerspectiveMath::matProd(endM,  KisPerspectiveMath::matProd(startM, srcPointF ) );

        // Compute the translation in the perspective transformation space:
        KisPoint positionStartPaintingT = KisPerspectiveMath::matProd(endM, m_painter->duplicateStart() );
        KisPoint duplicateStartPoisitionT = KisPerspectiveMath::matProd(endM, m_painter->duplicateStart() - m_painter->duplicateOffset() );
        KisPoint translat = duplicateStartPoisitionT - positionStartPaintingT;
        KisRectIteratorPixel dstIt = m_srcdev->createRectIterator(0, 0, sw, sh, true);
        KisRandomSubAccessorPixel srcAcc = device->createRandomSubAccessor();
        //Action
        while(!dstIt.isDone())
        {
            if(dstIt.isSelected())
            {
                KisPoint p =  KisPerspectiveMath::matProd(startM, KisPerspectiveMath::matProd(endM, KisPoint(dstIt.x() + x, dstIt.y() + y) ) + translat );
                srcAcc.moveTo( p );
                srcAcc.sampledOldRawData( dstIt.rawData() );
            }
            ++dstIt;
        }


    } else {
        // Or, copy the source data on the temporary device:
        copyPainter.bitBlt(0, 0, COMPOSITE_COPY, device, srcPoint.x(), srcPoint.y(), sw, sh);
        copyPainter.end();
    }

    // heal ?

    if(heal)
    {
        TQ_UINT16 dataDevice[4];
        TQ_UINT16 dataSrcDev[4];
        TQMemArray<double> matrix ( 3 * sw * sh );
        // First divide
        KisColorSpace* deviceCs = device->colorSpace();
        KisHLineIteratorPixel deviceIt = device->createHLineIterator(x, y, sw, false );
        KisHLineIteratorPixel srcDevIt = m_srcdev->createHLineIterator(0, 0, sw, true );
        double* matrixIt = &matrix[0];
        for(int j = 0; j < sh; j++)
        {
            for(int i= 0; !srcDevIt.isDone(); i++)
            {
                deviceCs->toLabA16(deviceIt.rawData(), (TQ_UINT8*)dataDevice, 1);
                deviceCs->toLabA16(srcDevIt.rawData(), (TQ_UINT8*)dataSrcDev, 1);
                // Division
                for( int k = 0; k < 3; k++)
                {
                    matrixIt[k] = dataDevice[k] / (double)TQMAX(dataSrcDev [k], 1);
                }
                ++deviceIt;
                ++srcDevIt;
                matrixIt +=3;
            }
            deviceIt.nextRow();
            srcDevIt.nextRow();
        }
        // Minimize energy
        {
            int iter = 0;
            double err;
            TQMemArray<double> solution ( 3 * sw * sh );
            do {
                err = minimizeEnergy(&matrix[0], &solution[0],sw,sh);
                memcpy (&matrix[0], &solution[0], sw * sh * 3 * sizeof(double));
                iter++;
            } while( err < 0.00001 && iter < 100);
        }

        // Finaly multiply
        deviceIt = device->createHLineIterator(x, y, sw, false );
        srcDevIt = m_srcdev->createHLineIterator(0, 0, sw, true );
        matrixIt = &matrix[0];
        for(int j = 0; j < sh; j++)
        {
            for(int i= 0; !srcDevIt.isDone(); i++)
            {
                deviceCs->toLabA16(deviceIt.rawData(), (TQ_UINT8*)dataDevice, 1);
                deviceCs->toLabA16(srcDevIt.rawData(), (TQ_UINT8*)dataSrcDev, 1);
                // Multiplication
                for( int k = 0; k < 3; k++)
                {
                    dataSrcDev[k] = (int)CLAMP( matrixIt[k] * TQMAX( dataSrcDev[k], 1), 0, 65535 );
                }
                deviceCs->fromLabA16((TQ_UINT8*)dataSrcDev, srcDevIt.rawData(), 1);
                ++deviceIt;
                ++srcDevIt;
                matrixIt +=3;
            }
            deviceIt.nextRow();
            srcDevIt.nextRow();
        }
    }


    // Add the dab as selection to the srcdev
//     KisPainter copySelection(srcdev->selection().data());
//     copySelection.bitBlt(0, 0, COMPOSITE_OVER, dab, 0, 0, sw, sh);
//     copySelection.end();

    // copy the srcdev onto a new device, after applying the dab selection
    copyPainter.begin(m_target);

    copyPainter.bltMask(0, 0, COMPOSITE_OVER, m_srcdev, dab,
                             OPACITY_OPAQUE, 0, 0, sw, sh);
    copyPainter.end();

    TQRect dabRect = TQRect(0, 0, brush->maskWidth(info), brush->maskHeight(info));
    TQRect dstRect = TQRect(x, y, dabRect.width(), dabRect.height());

    KisImage * image = device->image();

    if (image != 0) {
        dstRect &= image->bounds();
    }

    if (dstRect.isNull() || dstRect.isEmpty() || !dstRect.isValid()) return;

    TQ_INT32 sx = dstRect.x() - x;
    TQ_INT32 sy = dstRect.y() - y;
    sw = dstRect.width();
    sh = dstRect.height();

    if (m_source->hasSelection()) {
        m_painter->bltSelection(dstRect.x(), dstRect.y(), m_painter->compositeOp(), m_target,
                                m_source->selection(), m_painter->opacity(), sx, sy, sw, sh);
    }
    else {
        m_painter->bitBlt(dstRect.x(), dstRect.y(), m_painter->compositeOp(), m_target, m_painter->opacity(), sx, sy, sw, sh);
    }


    m_painter->addDirtyRect(dstRect);
}