summaryrefslogtreecommitdiffstats
path: root/kjsembed/plugins/imagefx_plugin.cpp
blob: ba2181cc498208f2db64b3b5655d003a7f435531 (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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
// -*- c++ -*-

/*
 *  Copyright (C) 2003, Ian Reinhart Geiser <geiseri@kde.org>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library 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
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public License
 *  along with this library; see the file COPYING.LIB.  If not, write to
 *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301, USA.
 */

#include <kdebug.h>
#include <kglobal.h>
#include <kjsembed/jsopaqueproxy.h>
#include <kjsembed/jsbinding.h>
#include <kjsembed/jsfactory.h>
#include <kjsembed/jsfactory_imp.h>
#include <kjsembed/kjsembedpart.h>
#include <kjsembed/customobject_imp.h>
#include <tqvariant.h>
#include <tqbrush.h>

#include "imagefx_plugin.h"

namespace KJSEmbed {
namespace Bindings {


ImageFXLoader::ImageFXLoader( TQObject *parent, const char *name, const TQStringList &args ) :
	JSBindingPlugin(parent, name, args)
{
}

KJS::Object ImageFXLoader::createBinding(KJSEmbedPart */*jspart*/, KJS::ExecState *exec, const KJS::List &/*args*/) const
{
	kdDebug() << "Loading a ImageFX object" << endl;
	JSOpaqueProxy *prx = new JSOpaqueProxy(  (int*)0, "ImageFX" );

	KJS::Object proxyObj(prx);
	ImageFX::addBindings( exec, proxyObj );
	return proxyObj;
}

ImageFX::ImageFX( KJS::ExecState *exec, int id )
    : JSProxyImp(exec), mid(id)
{
}

ImageFX::~ImageFX()
{
}

void ImageFX::addBindings( KJS::ExecState *exec, KJS::Object &object ) {

    kdDebug() << "ImageFX::addBindings()" << endl;
    JSOpaqueProxy *op = JSProxy::toOpaqueProxy( object.imp() );
    if ( !op ) {
        kdWarning() << "ImageFX::addBindings() failed, not a JSOpaqueProxy" << endl;
        return;
    }

    if ( op->typeName() != "ImageFX" ) {
	kdWarning() << "ImageFX::addBindings() failed, type is " << op->typeName() << endl;
	return;
    }

    JSProxy::MethodTable methods[] = {
	{ Methodgradient, "gradient" },
	{ MethodunbalancedGradient, "unbalancedGradient" },
	{ MethodblendColor, "blendColor" },
	{ MethodblendImage, "blendImage" },
	{ MethodcomputeDestinationRect, "computeDestinationRect" },
	{ MethodchannelIntensity, "channelIntensity" },
	{ Methodfade, "fade" },
	{ Methodflatten, "flatten" },
	{ Methodhash, "hash" },
	{ Methodintensity, "intensity" },
	{ Methodmodulate, "modulate" },
	{ MethodtoGray, "toGray" },
	{ Methoddesaturate, "desaturate" },
	{ Methoddither, "dither" },
	{ MethodselectedImage, "selectedImage" },
	{ MethodcontrastHSV, "contrastHSV" },
	{ Methodnormalize, "normalize" },
	{ Methodequalize, "equalize" },
	{ Methodthreshold, "threshold" },
	{ Methodsolarize, "solarize" },
	{ Methodemboss, "emboss" },
	{ Methoddespeckle, "despeckle" },
	{ Methodcharcoal, "charcoal" },
	{ Methodcharcoal2, "charcoal2" },
	{ Methodrotate, "rotate" },
	{ Methodsample, "sample" },
	{ MethodaddNoise, "addNoise" },
	{ Methodblur, "blur" },
	{ Methodedge, "edge" },
	{ Methodimplode, "implode" },
	{ MethodoilPaintConvolve, "oilPaintConvolve" },
	{ MethodoilPaint, "MethodoilPaint" },
	{ Methodsharpen, "sharpen" },
	{ Methodsharpen2, "sharpen2" },
	{ Methodspread, "spread" },
	{ Methodshade, "shade" },
	{ Methodswirl, "swirl" },
	{ Methodwave, "wave" },
	{ Methodcontrast, "contrast" },
	{ MethodbumpMap, "bumpmap" },
	{ 0, 0 }
    };

    int idx = 0;
    do {
        ImageFX *meth = new ImageFX( exec, methods[idx].id );
        object.put( exec , methods[idx].name, KJS::Object(meth) );
        ++idx;
    } while( methods[idx].id );

    //
    // Define the enum constants
    //
    struct EnumValue {
	const char *id;
	int val;
    };

    EnumValue enums[] = {
	// GradiantType
	{ "VerticalGradient", 0 },
	{ "HorizontalGradient", 1 },
	{ "DiagonalGradient", 2 },
	{ "CrossDiagonalGradient", 3 },
	{ "PyramidGradient", 4 },
	{ "RectangleGradient", 5 },
	{ "PipeCrossGradient", 6 },
	{ "EllipticGradient", 7 },
	// RGBComponent
	{ "Red", 0 },
	{ "Green", 1 },
	{ "Blue", 2 },
	{ "Gray", 3 },
	{ "All", 4 },
        // Lighting
	{ "NorthLite", 0 },
	{ "NWLite", 1 },
	{ "WestLite", 2 },
	{ "SWLite", 3 },
	{ "SouthLite", 4 },
	{ "SELite", 5 },
	{ "EastLite", 6 },
	{ "NELite", 7 },
        // ModulationType
	{ "Intensity", 0 },
	{ "Saturation", 1 },
	{ "HueShift", 2 },
	{ "Contrast", 3 },
        // NoiseType
	{ "UniformNoise", 0 },
	{ "GaussianNoise", 1 },
	{ "MultiplicativeGaussianNoise", 2 },
	{ "ImpulseNoise", 3 },
	{ "LaplacianNoise", 4 },
	{ "PoissonNoise", 5 },
        // RotateDirection
	{ "Rotate90", 0 },
	{ "Rotate180", 1 },
	{ "Rotate270", 2 },
	// BumpmapType
	{ "Linear", 0},
	{ "Spherical", 1},
	{ "Sinuosidal", 2},
	{ 0, 0 }
    };

    int enumidx = 0;
    do {
        object.put( exec, enums[enumidx].id, KJS::Number(enums[enumidx].val), KJS::ReadOnly );
        ++enumidx;
    } while( enums[enumidx].id );
}

KJS::Value ImageFX::call( KJS::ExecState *exec, KJS::Object &self, const KJS::List &args ) {

    kdDebug() << "ImageFX::call() " << mid << endl;
    JSOpaqueProxy *op = JSProxy::toOpaqueProxy( self.imp() );
    if ( !op ) {
        kdWarning() << "ImageFX::call() failed, not a JSOpaqueProxy" << endl;
        return KJS::Value();
    }

    if ( op->typeName() != "ImageFX" ) {
	kdWarning() << "ImageFX::call() failed, type is " << op->typeName() << endl;
	return KJS::Value();
    }


    KJS::Value retValue = KJS::Value();
    switch ( mid ) {
    case Methodgradient: {
            TQSize size = extractQSize(exec, args, 0);
            TQColor ca = extractQColor(exec, args, 1);
            TQColor cb = extractQColor(exec, args, 2);
            int type = extractInt( exec, args, 3);
            int ncols = extractInt( exec, args, 4);
	    TQImage img = KImageEffect::gradient(size, ca, cb, (KImageEffect::GradientType)type, ncols);
	    retValue = convertToValue(exec, img);
            break;
        }
    case MethodunbalancedGradient: {
            TQSize size = extractQSize(exec, args, 0);
            TQColor ca = extractQColor(exec, args, 1);
            TQColor cb = extractQColor(exec, args, 2);
            int type = extractInt( exec, args, 3);
            int xfactor = extractInt( exec, args, 4);
            int yfactor = extractInt( exec, args, 5);
            int ncols = extractInt( exec, args, 6);
            TQImage img = KImageEffect::unbalancedGradient(size, ca, cb, (KImageEffect::GradientType)type, xfactor, yfactor, ncols);
	    retValue = convertToValue(exec, img);
            break;
        }
    case MethodblendColor: {
            TQColor clr = extractQColor(exec, args, 0);
	    TQImage dst = extractQImage(exec, args, 1);
            float opacity = (float)extractDouble(exec, args, 2);
	    TQImage img = KImageEffect::blend(clr, dst, opacity);
	    retValue = convertToValue(exec, img);
            break;
        }
    case MethodblendImage: {
            TQImage src = extractQImage(exec, args, 0);
	    TQImage dst = extractQImage(exec, args, 1);
            float opacity = (float)extractDouble(exec, args, 2);
	    TQImage img = KImageEffect::blend(src, dst, opacity);
	    retValue = convertToValue(exec, img);
            break;
        }
    case MethodcomputeDestinationRect: {
            TQSize lowerSize = extractQSize(exec, args, 0);
            int disposition = extractInt(exec, args, 1);
	    TQImage upper = extractQImage(exec, args, 2);
	    TQRect rect = KImageEffect::computeDestinationRect(lowerSize,  (KImageEffect::Disposition) disposition, upper);
            retValue = convertToValue(exec, rect);
	    break;
        }
    case MethodchannelIntensity: {
    	    TQImage image = extractQImage(exec, args, 0);
            float percent = (float)extractDouble(exec, args, 1);
            int channel = extractInt(exec, args, 2);
	    TQImage img = KImageEffect::channelIntensity(image, percent, (KImageEffect::RGBComponent)channel);
            retValue = convertToValue(exec, img);
	    break;
        }
    case Methodfade: {
            TQImage image = extractQImage(exec, args, 0);
            float val = (float)extractDouble(exec, args, 1);
            TQColor color = extractQColor(exec, args, 2);
	    TQImage img = KImageEffect::fade(image, val, color);
            retValue = convertToValue(exec, img);
            break;
        }
    case Methodflatten: {
            TQImage image = extractQImage(exec, args, 0);
	    TQColor ca = extractQColor(exec, args, 1);
            TQColor cb = extractQColor(exec, args, 2);
            int ncols = extractInt(exec, args, 3);
	    TQImage img = KImageEffect::flatten(image, ca, cb, ncols);
            retValue = convertToValue(exec, img);
            break;
        }
    case Methodhash: {

            TQImage image = extractQImage(exec, args, 0);
	    int lite  = extractInt(exec, args, 1);
            int spacing = extractInt(exec, args, 2);
	    TQImage img = KImageEffect::hash(image, (KImageEffect::Lighting)lite, spacing);
            retValue = convertToValue(exec, img);
            break;
        }
    case Methodintensity: {

	    TQImage image = extractQImage(exec, args, 0);
	    float percent = (float)extractDouble(exec, args, 1);
            TQImage img = KImageEffect::intensity(image, percent);
	    retValue = convertToValue(exec, img);
            break;
        }
    case Methodmodulate: {
            TQImage image = extractQImage(exec, args, 0);
	    TQImage modImage = extractQImage(exec, args, 0);
            bool reverse = extractBool(exec, args, 1);
            int type = extractInt(exec, args, 2);
            int factor = extractInt(exec, args, 3);
            int channel = extractInt(exec, args, 4);
	    TQImage img = KImageEffect::modulate(image, modImage, reverse, (KImageEffect::ModulationType)type, factor, (KImageEffect::RGBComponent)channel);
            retValue = convertToValue(exec, img);
            break;
        }

    case MethodtoGray: {
            TQImage image = extractQImage(exec, args, 0);
	    bool fast = extractBool(exec, args, 1);
            TQImage img = KImageEffect::toGray(image, fast);
	    retValue = convertToValue(exec, img);
            break;
        }
    case Methoddesaturate: {
            TQImage image = extractQImage(exec, args, 0);
	    float desat = (float)extractDouble(exec, args, 1);
            TQImage img = KImageEffect::desaturate(image, desat);
	    retValue = convertToValue(exec, img);
            break;
        }
    case Methoddither: {

            //dither( palette, size)
            break;
        }
    case MethodselectedImage: {

            TQImage image = extractQImage(exec, args, 0);
	    TQColor col = extractQColor(exec, args, 1);
            TQImage img = KImageEffect::selectedImage(image, col);
	    retValue = convertToValue(exec, img);
            break;
        }
    case MethodcontrastHSV: {
	    TQImage image = extractQImage(exec, args, 0);
	    bool sharpen = extractBool(exec, args, 1);
            KImageEffect::contrastHSV(image, sharpen);
	    retValue = convertToValue(exec, image);
            break;
        }
    case Methodnormalize: {
            TQImage image = extractQImage(exec, args, 0);
            KImageEffect::normalize(image);
	    retValue = convertToValue(exec, image);
            break;
        }
    case Methodequalize: {
            TQImage image = extractQImage(exec, args, 0);
            KImageEffect::equalize(image);
	    retValue = convertToValue(exec, image);
            break;
        }
    case Methodthreshold: {
            TQImage image = extractQImage(exec, args, 0);
	    uint value = extractUInt(exec, args, 1);
            KImageEffect::threshold(image, value);
	    retValue = convertToValue(exec, image);
            break;
        }
    case Methodsolarize: {
            TQImage image = extractQImage(exec, args, 0);
            double factor = extractDouble(exec, args, 1);
            KImageEffect::solarize(image, factor);
	    retValue = convertToValue(exec, image);
            break;
        }
    case Methodemboss: {
            TQImage image = extractQImage(exec, args, 0);
	    double radius = extractDouble(exec, args, 1);
            double sigma = extractDouble(exec, args, 2);
            TQImage img = KImageEffect::emboss(image, radius, sigma);
	    retValue = convertToValue(exec, img);
            break;
        }
    case Methoddespeckle: {
            TQImage image = extractQImage(exec, args, 0);
	    TQImage img = KImageEffect::despeckle(image);
	    retValue = convertToValue(exec, img);
            break;
        }
    case Methodcharcoal: {
            TQImage image = extractQImage(exec, args, 0);
	    double factor = extractDouble(exec, args, 1);
            TQImage img = KImageEffect::charcoal( image, factor);
	    retValue = convertToValue(exec, img);
            break;
        }
    case Methodcharcoal2: {
            TQImage image = extractQImage(exec, args, 0);
	    double radius = extractDouble(exec, args, 1);
            double sigma = extractDouble(exec, args, 2);
            TQImage img = KImageEffect::charcoal(image, radius, sigma);
	    retValue = convertToValue(exec, img);
            break;
        }
    case Methodrotate: {
            TQImage image = extractQImage(exec, args, 0);
	    int r = extractInt(exec, args, 1);
            TQImage img = KImageEffect::rotate(image, (KImageEffect::RotateDirection) r);
	    retValue = convertToValue(exec, img);
            break;
        }
    case Methodsample: {
            TQImage image = extractQImage(exec, args, 0);
            int width = extractInt(exec, args, 1);
            int height = extractInt(exec, args, 2);
            TQImage img = KImageEffect::sample(image, width, height);
	    retValue = convertToValue(exec, img);
            break;
        }
    case MethodaddNoise: {
            TQImage image = extractQImage(exec, args, 0);
            int type = extractInt(exec, args, 1);
            TQImage img = KImageEffect::addNoise(image, (KImageEffect::NoiseType) type);
	    retValue = convertToValue(exec, img);
            break;
        }
    case Methodblur: {
            TQImage image = extractQImage(exec, args, 0);
	    double radius = extractDouble(exec, args, 1);
            double sigma = extractDouble(exec, args, 2);
            TQImage img = KImageEffect::blur(image, radius, sigma);
	    retValue = convertToValue(exec, img);
            break;
        }
    case Methodedge: {
            TQImage image = extractQImage(exec, args, 0);
	    double radius = extractDouble(exec, args, 1);
            TQImage img = KImageEffect::edge(image, radius);
            retValue = convertToValue(exec, img);
	    break;
        }
    case Methodimplode: {
            TQImage image = extractQImage(exec, args, 0);
	    double factor = extractDouble(exec, args, 1);
            uint background = extractUInt(exec, args, 2);
            TQImage img = KImageEffect::implode(image, factor, background);
            retValue = convertToValue(exec, img);
	    break;
        }
    case MethodoilPaintConvolve: {
            TQImage image = extractQImage(exec, args, 0);
	    double radius = extractDouble(exec, args, 1);
            TQImage img = KImageEffect::oilPaintConvolve(image, radius);
	    retValue = convertToValue(exec, img);
            break;
        }
    case MethodoilPaint: {
            TQImage image = extractQImage(exec, args, 0);
            int radius = extractInt(exec, args, 1);
            TQImage img = KImageEffect::oilPaint(image, radius);
	    retValue = convertToValue(exec, img);
            break;
        }


    case Methodsharpen: {
            TQImage image = extractQImage(exec, args, 0);
	    double factor = extractDouble(exec, args, 1);
            TQImage img = KImageEffect::sharpen(image, factor);
	    retValue = convertToValue(exec, img);
            break;
        }
    case Methodsharpen2: {
            TQImage image = extractQImage(exec, args, 0);
	    double radius = extractDouble(exec, args, 1);
            double sigma = extractDouble(exec, args, 2);
            TQImage img = KImageEffect::sharpen(image, radius, sigma);
	    retValue = convertToValue(exec, img);
            break;
        }
    case Methodspread: {
            TQImage image = extractQImage(exec, args, 0);
	    uint amount = extractUInt(exec, args, 1);
            TQImage img = KImageEffect::spread(image, amount);
            retValue = convertToValue(exec, img);
	    break;
        }
    case Methodshade: {
            TQImage image = extractQImage(exec, args, 0);
	    bool color_shading = extractBool(exec, args, 1);
            double azimuth = extractDouble(exec, args, 2);
            double elevation = extractDouble(exec, args, 3);
            TQImage img = KImageEffect::shade(image, color_shading, azimuth, elevation);
            retValue = convertToValue(exec, img);
	    break;
        }
    case Methodswirl: {
            TQImage image = extractQImage(exec, args, 0);
	    double degrees  = extractDouble(exec, args, 1);
            uint background = extractUInt(exec, args, 2);
            TQImage img = KImageEffect::swirl(image, degrees, background);
            retValue = convertToValue(exec, img);
	    break;
        }
    case Methodwave: {
            TQImage image = extractQImage(exec, args, 0);
	    double amplitude  = extractDouble(exec, args, 1);
            double frequency  = extractDouble(exec, args, 2);
            uint background = extractUInt(exec, args, 3);
            TQImage img = KImageEffect::wave(image, amplitude, frequency, background);
            retValue = convertToValue(exec, img);
	    break;
        }
    case Methodcontrast: {
            TQImage image = extractQImage(exec, args, 0);
	    int c = extractInt(exec, args, 1);
            TQImage img = KImageEffect::contrast(image, c);
            retValue = convertToValue(exec, img);
	    break;
        }
    case MethodbumpMap: {
        TQImage mask = extractQImage(exec, args, 0);
        TQImage img = bumpmap(img,
	                                        mask,
						extractDouble(exec, args, 1),
						extractDouble(exec, args, 2),
						extractInt(exec, args, 3),
						extractInt(exec, args, 4),
						extractInt(exec, args, 5),
						extractInt(exec, args, 6),
						extractInt(exec, args, 7),
						extractBool(exec, args, 8),
						extractBool(exec, args, 9),
						(BumpmapType) extractInt(exec, args, 10),
						extractBool(exec, args, 11));

	retValue = convertToValue(exec, img);
	break;
    }
    default:
        kdWarning() << "ImageFX has no method " << mid << endl;
        break;
    }

    return retValue;
}

/***********************************************************************
 * Here's a pretty fast bumpmap implementation.
 * NOTE: remind me to move it to KImageEffects after 3.2.
 */
#define DegreesToRadians(x) ((x)*M_PI/180.0)
#define MOD(x, y) ((x) < 0 ? ((y) - 1 - ((y) - 1 - (x)) % (y)) : (x) % (y))

/**
 * NOTE: kclamp needs to be moved to kglobals.h along kmin and kmax
 */
#define KCLAMP(x,low,high) kClamp(x,low,high)
template<class T>
inline const T& kClamp( const T& x, const T& low, const T& high )
{
    if ( x < low )
        return low;
    else if ( x > high )
        return high;
    else
        return x;
}

static inline unsigned int intensityValue( unsigned int color ) {
    return (unsigned int)( (0.299*qRed( color ) +
                            0.587*qGreen( color ) +
                            0.1140000000000001*qBlue( color ) ) );
}

struct BumpmapParams {
    BumpmapParams( double bm_azimuth, double bm_elevation,
                   int bm_depth, BumpmapType bm_type,
                   bool invert ) {
         /* Convert to radians */
        double azimuth = DegreesToRadians( bm_azimuth );
        double elevation = DegreesToRadians( bm_elevation );

        /* Calculate the light vector */
        lx = (int)( cos(azimuth) * cos(elevation) * 255.0 );
        ly = (int)( sin(azimuth) * cos(elevation) * 255.0 );
        int lz         = (int)( sin(elevation) * 255.0 );

        /* Calculate constant Z component of surface normal */
        int nz  = (6 * 255) / bm_depth;
        nz2     = nz * nz;
        nzlz    = nz * lz;

        /* Optimize for vertical normals */
        background = lz;

        /* Calculate darkness compensation factor */
        compensation = sin(elevation);

        /* Create look-up table for map type */
        for (int i = 0; i < 256; i++)
        {
            double n = 0;
            switch (bm_type)
            {
            case Spherical:
                n = i / 255.0 - 1.0;
                lut[i] = (int) (255.0 * sqrt(1.0 - n * n) + 0.5);
                break;

            case Sinuosidal:
                n = i / 255.0;
                lut[i] = (int) (255.0 * (sin((-M_PI / 2.0) + M_PI * n) + 1.0) /
                                        2.0 + 0.5);
                break;

            case Linear:
            default:
                lut[i] = i;
            }

            if (invert)
                lut[i] = 255 - lut[i];
        }
    }
    int lx,  ly;
    int nz2, nzlz;
    int background;
    double compensation;
    uchar lut[256];
};


static void bumpmap_convert_row( uint *row,
                                 int    width,
                                 int    bpp,
                                 int    has_alpha,
                                 uchar *lut,
                                 int waterlevel )
{
  uint *p;

  p = row;

  has_alpha = has_alpha ? 1 : 0;

  if (bpp >= 3)
      for (; width; width--)
      {
          if (has_alpha) {
              unsigned int idx = (unsigned int)(intensityValue( *row ) + 0.5);
              *p++ = lut[(unsigned int) ( waterlevel +
                                          ( ( idx -
                                              waterlevel) * qBlue( *row )) / 255.0 )];
          } else {
              unsigned int idx = (unsigned int)(intensityValue( *row ) + 0.5);
              *p++ = lut[idx];
          }

          ++row;
      }
}

static void bumpmap_row( uint           *src,
                         uint           *dest,
                         int              width,
                         int              bpp,
                         int              has_alpha,
                         uint           *bm_row1,
                         uint           *bm_row2,
                         uint           *bm_row3,
                         int              bm_width,
                         int              bm_xofs,
                         bool          tiled,
                         bool          row_in_bumpmap,
                         int           ambient,
                         bool          compensate,
                         BumpmapParams *params )
{
    int xofs1, xofs2, xofs3;
    int shade;
    int ndotl;
    int nx, ny;
    int x;
    int pbpp;
    int tmp;

    if (has_alpha)
        pbpp = bpp - 1;
    else
        pbpp = bpp;

    tmp = bm_xofs;
    xofs2 = MOD(tmp, bm_width);

    for (x = 0; x < width; x++)
    {
        /* Calculate surface normal from bump map */

        if (tiled || (row_in_bumpmap &&
                      x >= - tmp && x < - tmp + bm_width)) {
            if (tiled) {
                xofs1 = MOD(xofs2 - 1, bm_width);
                xofs3 = MOD(xofs2 + 1, bm_width);
	    } else {
                xofs1 = KCLAMP(xofs2 - 1, 0, bm_width - 1);
                xofs3 = KCLAMP(xofs2 + 1, 0, bm_width - 1);
	    }
            nx = (bm_row1[xofs1] + bm_row2[xofs1] + bm_row3[xofs1] -
                  bm_row1[xofs3] - bm_row2[xofs3] - bm_row3[xofs3]);
            ny = (bm_row3[xofs1] + bm_row3[xofs2] + bm_row3[xofs3] -
                  bm_row1[xofs1] - bm_row1[xofs2] - bm_row1[xofs3]);
	} else {
            nx = ny = 0;
        }

      /* Shade */

        if ((nx == 0) && (ny == 0))
            shade = params->background;
        else {
            ndotl = nx * params->lx + ny * params->ly + params->nzlz;

            if (ndotl < 0)
                shade = (int)( params->compensation * ambient );
            else {
                shade = (int)( ndotl / sqrt(nx * nx + ny * ny + params->nz2) );

                shade = (int)( shade + KMAX(0.0, (255 * params->compensation - shade)) *
                               ambient / 255 );
	    }
	}

        /* Paint */

        /**
         * NOTE: if we want to work with non-32bit images the alpha handling would
         * also change
         */
        if (compensate) {
            int red = (int)((qRed( *src ) * shade) / (params->compensation * 255));
            int green = (int)((qGreen( *src ) * shade) / (params->compensation * 255));
            int blue = (int)((qBlue( *src ) * shade) / (params->compensation * 255));
            int alpha = (int)((qAlpha( *src ) * shade) / (params->compensation * 255));
            ++src;
            *dest++ = qRgba( red, green, blue, alpha );
        } else {
            int red = qRed( *src ) * shade / 255;
            int green = qGreen( *src ) * shade / 255;
            int blue = qBlue( *src ) * shade / 255;
            int alpha = qAlpha( *src ) * shade / 255;
            ++src;
            *dest++ = qRgba( red, green, blue, alpha );
        }

        /* Next pixel */

        if (++xofs2 == bm_width)
            xofs2 = 0;
    }
}

/**
 * A bumpmapping algorithm.
 *
 * @param img the image you want bumpmap
 * @param map the map used
 * @param azimuth azimuth
 * @param elevation elevation
 * @param depth depth (not the depth of the image, but of the map)
 * @param xofs X offset
 * @param yofs Y offset
 * @param waterlevel level that full transparency should represent
 * @param ambient ambient lighting factor
 * @param compensate compensate for darkening
 * @param invert invert bumpmap
 * @param type type of the bumpmap
 *
 * @return The destination image (dst) containing the result.
 * @author Zack Rusin <zack@kde.org>
 */
TQImage ImageFX::bumpmap(TQImage &img, TQImage &map, double azimuth, double elevation,
               int depth, int xofs, int yofs, int waterlevel,
               int ambient, bool compensate, bool invert,
               BumpmapType type, bool tiled)
{
    TQImage dst;

    if ( img.depth() != 32 || img.depth() != 32 ) {
        qWarning( "Bump-mapping effect works only with 32 bit images");
        return dst;
    }

    dst.create( img.width(), img.height(), img.depth() );
    int bm_width  = map.width();
    int bm_height = map.height();
    int bm_bpp = map.depth();
    int bm_has_alpha = map.hasAlphaBuffer();

    int yofs1, yofs2, yofs3;

    if ( tiled ) {
        yofs2 = MOD( yofs, bm_height );
        yofs1 = MOD( yofs2 - 1, bm_height);
        yofs3 = MOD( yofs2 + 1, bm_height);
    } else {
        yofs1 = 0;
        yofs2 = 0;
        yofs3 = KCLAMP( yofs2+1, 0, bm_height - 1 );
    }

    BumpmapParams params( azimuth, elevation, depth, type, invert );

    uint* bm_row1 = (unsigned int*)map.scanLine( yofs1 );
    uint* bm_row2 = (unsigned int*)map.scanLine( yofs2 );
    uint* bm_row3 = (unsigned int*)map.scanLine( yofs3 );

    bumpmap_convert_row( bm_row1, bm_width, bm_bpp, bm_has_alpha, params.lut, waterlevel );
    bumpmap_convert_row( bm_row2, bm_width, bm_bpp, bm_has_alpha, params.lut, waterlevel );
    bumpmap_convert_row( bm_row3, bm_width, bm_bpp, bm_has_alpha, params.lut, waterlevel );

    for (int y = 0; y < img.height(); ++y)
    {
        int row_in_bumpmap = (y >= - yofs && y < - yofs + bm_height);

        uint* src_row = (unsigned int*)img.scanLine( y );
        uint* dest_row = (unsigned int*)dst.scanLine( y );

        bumpmap_row( src_row, dest_row, img.width(), img.depth(), img.hasAlphaBuffer(),
                     bm_row1, bm_row2, bm_row3, bm_width, xofs,
                     tiled,
                     row_in_bumpmap, ambient, compensate,
                     &params );

        /* Next line */

        if (tiled || row_in_bumpmap)
	{
            uint* bm_tmprow = bm_row1;
            bm_row1   = bm_row2;
            bm_row2   = bm_row3;
            bm_row3   = bm_tmprow;

            if (++yofs2 == bm_height)
                yofs2 = 0;

            if (tiled)
                yofs3 = MOD(yofs2 + 1, bm_height);
            else
                yofs3 = KCLAMP(yofs2 + 1, 0, bm_height - 1);

            bm_row3 = (unsigned int*)map.scanLine( yofs3 );
            bumpmap_convert_row( bm_row3, bm_width, bm_bpp, bm_has_alpha,
                                 params.lut, waterlevel );
	}
    }
    return dst;
}


} // namespace KJSEmbed::Bindings
} // namespace KJSEmbed

#include <kgenericfactory.h>
typedef KGenericFactory<KJSEmbed::Bindings::ImageFXLoader> ImageFXLoaderFactory;
K_EXPORT_COMPONENT_FACTORY( libimagefxplugin, ImageFXLoaderFactory( "ImageFXLoader" ) )