Code

updated spanish.nsh and inkscape.nsi to reflect latest file-changes
[inkscape.git] / trunk / src / display / nr-filter.cpp
1 #define __NR_FILTER_CPP__
3 /*
4  * SVG filters rendering
5  *
6  * Author:
7  *   Niko Kiirala <niko@kiirala.com>
8  *
9  * Copyright (C) 2006-2008 Niko Kiirala
10  *
11  * Released under GNU GPL, read the file 'COPYING' for more information
12  */
14 #include <glib.h>
15 #include <cmath>
16 #include <cstring>
17 #include <string>
19 #include "display/nr-filter.h"
20 #include "display/nr-filter-primitive.h"
21 #include "display/nr-filter-slot.h"
22 #include "display/nr-filter-types.h"
23 #include "display/nr-filter-units.h"
25 #include "display/nr-filter-blend.h"
26 #include "display/nr-filter-composite.h"
27 #include "display/nr-filter-convolve-matrix.h"
28 #include "display/nr-filter-colormatrix.h"
29 #include "display/nr-filter-component-transfer.h"
30 #include "display/nr-filter-diffuselighting.h"
31 #include "display/nr-filter-displacement-map.h"
32 #include "display/nr-filter-flood.h"
33 #include "display/nr-filter-gaussian.h"
34 #include "display/nr-filter-image.h"
35 #include "display/nr-filter-merge.h"
36 #include "display/nr-filter-morphology.h"
37 #include "display/nr-filter-offset.h"
38 #include "display/nr-filter-specularlighting.h"
39 #include "display/nr-filter-tile.h"
40 #include "display/nr-filter-turbulence.h"
42 #include "display/nr-arena-item.h"
43 #include "libnr/nr-pixblock.h"
44 #include "libnr/nr-blit.h"
45 #include <2geom/matrix.h>
46 #include <2geom/rect.h>
47 #include "svg/svg-length.h"
48 #include "sp-filter-units.h"
49 #include "preferences.h"
51 #if defined (SOLARIS) && (SOLARIS == 8)
52 #include "round.h"
53 using Inkscape::round;
54 #endif 
56 namespace Inkscape {
57 namespace Filters {
59 using Geom::X;
60 using Geom::Y;
62 static Geom::OptRect get_item_bbox(NRArenaItem const *item) {
63     Geom::Rect item_bbox;
64     if (item->item_bbox) {
65         item_bbox = *(item->item_bbox);
66     } else {
67         // Bounding box might not exist, so create a dummy one.
68         Geom::Point zero(0, 0);
69         item_bbox = Geom::Rect(zero, zero);
70     }
71     if (item_bbox.min()[X] > item_bbox.max()[X]
72         || item_bbox.min()[Y] > item_bbox.max()[Y])
73     {
74         // In case of negative-size bbox, return an empty OptRect
75         return Geom::OptRect();
76     }
77     return Geom::OptRect(item_bbox);
78 }
80 Filter::Filter()
81 {
82     _primitive_count = 0;
83     _primitive_table_size = 1;
84     _primitive = new FilterPrimitive*[1];
85     _primitive[0] = NULL;
86     //_primitive_count = 1;
87     //_primitive[0] = new FilterGaussian;
88     _common_init();
89 }
91 Filter::Filter(int n)
92 {
93     _primitive_count = 0;
94     _primitive_table_size = n;
95     _primitive = new FilterPrimitive*[n];
96     for ( int i = 0 ; i < n ; i++ ) {
97         _primitive[i] = NULL;
98     }
99     _common_init();
102 void Filter::_common_init() {
103     _slot_count = 1;
104     // Having "not set" here as value means the output of last filter
105     // primitive will be used as output of this filter
106     _output_slot = NR_FILTER_SLOT_NOT_SET;
108     // These are the default values for filter region,
109     // as specified in SVG standard
110     // NB: SVGLength.set takes prescaled percent values: -.10 means -10%
111     _region_x.set(SVGLength::PERCENT, -.10, 0);
112     _region_y.set(SVGLength::PERCENT, -.10, 0);
113     _region_width.set(SVGLength::PERCENT, 1.20, 0);
114     _region_height.set(SVGLength::PERCENT, 1.20, 0);
116     // Filter resolution, negative value here stands for "automatic"
117     _x_pixels = -1.0;
118     _y_pixels = -1.0;
120     _filter_units = SP_FILTER_UNITS_OBJECTBOUNDINGBOX;
121     _primitive_units = SP_FILTER_UNITS_USERSPACEONUSE;
124 Filter::~Filter()
126     clear_primitives();
127     delete[] _primitive;
131 int Filter::render(NRArenaItem const *item, NRPixBlock *pb)
133     if (!_primitive[0]) {
134         // TODO: Should clear the input buffer instead of just returning
135        return 1; 
136     }
138     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
139     FilterQuality const filterquality = (FilterQuality)prefs->getInt("/options/filterquality/value");
141     Geom::Matrix trans = item->ctm;
142     FilterSlot slot(_slot_count, item);
143     slot.set_quality(filterquality);
145     Geom::Rect item_bbox;
146     {
147         Geom::OptRect maybe_bbox = get_item_bbox(item);
148         if (maybe_bbox.isEmpty()) {
149             // Code below needs a bounding box
150             return 1;
151         }
152         item_bbox = *maybe_bbox;
153     }
155     Geom::Rect filter_area = filter_effect_area(item_bbox);
156     if (item_bbox.hasZeroArea()) {
157         // It's no use to try and filter an empty object.
158         return 1;
159     }
160         
161     FilterUnits units(_filter_units, _primitive_units);
162     units.set_ctm(trans);
163     units.set_item_bbox(item_bbox);
164     units.set_filter_area(filter_area);
166     // TODO: with filterRes of 0x0 should return an empty image
167     std::pair<double,double> resolution
168         = _filter_resolution(filter_area, trans, filterquality);
169     units.set_resolution(resolution.first, resolution.second);
170     if (_x_pixels > 0) {
171         units.set_automatic_resolution(false);
172     }
173     else {
174         units.set_automatic_resolution(true);
175     }
177     units.set_paraller(false);
178     for (int i = 0 ; i < _primitive_count ; i++) {
179         if (_primitive[i]->get_input_traits() & TRAIT_PARALLER) {
180             units.set_paraller(true);
181             break;
182         }
183     }
185     slot.set_units(units);
187     NRPixBlock *in = new NRPixBlock;
188     nr_pixblock_setup_fast(in, pb->mode, pb->area.x0, pb->area.y0,
189                            pb->area.x1, pb->area.y1, true);
190     if (in->size != NR_PIXBLOCK_SIZE_TINY && in->data.px == NULL) {
191         g_warning("Inkscape::Filters::Filter::render: failed to reserve temporary buffer");
192         return 0;
193     }
194     nr_blit_pixblock_pixblock(in, pb);
195     in->empty = FALSE;
196     slot.set(NR_FILTER_SOURCEGRAPHIC, in);
198     // Check that we are rendering a non-empty area
199     in = slot.get(NR_FILTER_SOURCEGRAPHIC);
200     if (in->area.x1 - in->area.x0 <= 0 || in->area.y1 - in->area.y0 <= 0) {
201         if (in->area.x1 - in->area.x0 < 0 || in->area.y1 - in->area.y0 < 0) {
202             g_warning("Inkscape::Filters::Filter::render: negative area! (%d, %d) (%d, %d)",
203                       in->area.x0, in->area.y0, in->area.x1, in->area.y1);
204         }
205         return 0;
206     }
207     in = NULL; // in is now handled by FilterSlot, we should not touch it
209     for (int i = 0 ; i < _primitive_count ; i++) {
210         _primitive[i]->render(slot, units);
211     }
213     slot.get_final(_output_slot, pb);
215     // Take note of the amount of used image slots
216     // -> next time this filter is rendered, we can reserve enough slots
217     // immediately
218     _slot_count = slot.get_slot_count();
219     return 0;
222 void Filter::area_enlarge(NRRectL &bbox, NRArenaItem const *item) const {
223     for (int i = 0 ; i < _primitive_count ; i++) {
224         if (_primitive[i]) _primitive[i]->area_enlarge(bbox, item->ctm);
225     }
226 /*
227   TODO: something. See images at the bottom of filters.svg with medium-low
228   filtering quality.
230     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
231     FilterQuality const filterquality = (FilterQuality)prefs->getInt("/options/filterquality/value");
233     if (_x_pixels <= 0 && (filterquality == FILTER_QUALITY_BEST ||
234                            filterquality == FILTER_QUALITY_BETTER)) {
235         return;
236     }
238     Geom::Rect item_bbox;
239     Geom::OptRect maybe_bbox = get_item_bbox(item);
240     if (maybe_bbox.isEmpty()) {
241         // Code below needs a bounding box
242         return;
243     }
244     item_bbox = *maybe_bbox;
246     std::pair<double,double> res_low
247         = _filter_resolution(item_bbox, item->ctm, filterquality);
248     //std::pair<double,double> res_full
249     //    = _filter_resolution(item_bbox, item->ctm, FILTER_QUALITY_BEST);
250     double pixels_per_block = fmax(item_bbox.width() / res_low.first,
251                                    item_bbox.height() / res_low.second);
252     bbox.x0 -= (int)pixels_per_block;
253     bbox.x1 += (int)pixels_per_block;
254     bbox.y0 -= (int)pixels_per_block;
255     bbox.y1 += (int)pixels_per_block;
256 */
259 void Filter::bbox_enlarge(NRRectL &bbox) {
260     // Modifying empty bounding boxes confuses rest of the renderer, so
261     // let's not do that.
262     if (bbox.x0 > bbox.x1 || bbox.y0 > bbox.y1) return;
264     /* TODO: this is wrong. Should use bounding box in user coordinates
265      * and find its extents in display coordinates. */
266     Geom::Point min(bbox.x0, bbox.y0);
267     Geom::Point max(bbox.x1, bbox.y1);
268     Geom::Rect tmp_bbox(min, max);
270     Geom::Rect enlarged = filter_effect_area(tmp_bbox);
272     bbox.x0 = (NR::ICoord)enlarged.min()[X];
273     bbox.y0 = (NR::ICoord)enlarged.min()[Y];
274     bbox.x1 = (NR::ICoord)enlarged.max()[X];
275     bbox.y1 = (NR::ICoord)enlarged.max()[Y];
278 Geom::Rect Filter::filter_effect_area(Geom::Rect const &bbox)
280     Geom::Point minp, maxp;
281     double len_x = bbox.max()[X] - bbox.min()[X];
282     double len_y = bbox.max()[Y] - bbox.min()[Y];
283     /* TODO: fetch somehow the object ex and em lengths */
284     _region_x.update(12, 6, len_x);
285     _region_y.update(12, 6, len_y);
286     _region_width.update(12, 6, len_x);
287     _region_height.update(12, 6, len_y);
288     if (_filter_units == SP_FILTER_UNITS_OBJECTBOUNDINGBOX) {
289         if (_region_x.unit == SVGLength::PERCENT) {
290             minp[X] = bbox.min()[X] + _region_x.computed;
291         } else {
292             minp[X] = bbox.min()[X] + _region_x.computed * len_x;
293         }
294         if (_region_width.unit == SVGLength::PERCENT) {
295             maxp[X] = minp[X] + _region_width.computed;
296         } else {
297             maxp[X] = minp[X] + _region_width.computed * len_x;
298         }
300         if (_region_y.unit == SVGLength::PERCENT) {
301             minp[Y] = bbox.min()[Y] + _region_y.computed;
302         } else {
303             minp[Y] = bbox.min()[Y] + _region_y.computed * len_y;
304         }
305         if (_region_height.unit == SVGLength::PERCENT) {
306             maxp[Y] = minp[Y] + _region_height.computed;
307         } else {
308             maxp[Y] = minp[Y] + _region_height.computed * len_y;
309         }
310     } else if (_filter_units == SP_FILTER_UNITS_USERSPACEONUSE) {
311         /* TODO: make sure bbox and fe region are in same coordinate system */
312         minp[X] = _region_x.computed;
313         maxp[X] = minp[X] + _region_width.computed;
314         minp[Y] = _region_y.computed;
315         maxp[Y] = minp[Y] + _region_height.computed;
316     } else {
317         g_warning("Error in Inkscape::Filters::Filter::bbox_enlarge: unrecognized value of _filter_units");
318     }
319     Geom::Rect area(minp, maxp);
320     return area;
323 /* Constructor table holds pointers to static methods returning filter
324  * primitives. This table is indexed with FilterPrimitiveType, so that
325  * for example method in _constructor[NR_FILTER_GAUSSIANBLUR]
326  * returns a filter object of type Inkscape::Filters::FilterGaussian.
327  */
328 typedef FilterPrimitive*(*FilterConstructor)();
329 static FilterConstructor _constructor[NR_FILTER_ENDPRIMITIVETYPE];
331 void Filter::_create_constructor_table()
333     // Constructor table won't change in run-time, so no need to recreate
334     static bool created = false;
335     if(created) return;
337 /* Some filter classes are not implemented yet.
338    Some of them still have only boilerplate code.*/
339     _constructor[NR_FILTER_BLEND] = &FilterBlend::create;
340     _constructor[NR_FILTER_COLORMATRIX] = &FilterColorMatrix::create;
341     _constructor[NR_FILTER_COMPONENTTRANSFER] = &FilterComponentTransfer::create;
342     _constructor[NR_FILTER_COMPOSITE] = &FilterComposite::create;
343     _constructor[NR_FILTER_CONVOLVEMATRIX] = &FilterConvolveMatrix::create;
344     _constructor[NR_FILTER_DIFFUSELIGHTING] = &FilterDiffuseLighting::create;
345     _constructor[NR_FILTER_DISPLACEMENTMAP] = &FilterDisplacementMap::create;
346     _constructor[NR_FILTER_FLOOD] = &FilterFlood::create;
347     _constructor[NR_FILTER_GAUSSIANBLUR] = &FilterGaussian::create;
348     _constructor[NR_FILTER_IMAGE] = &FilterImage::create;
349     _constructor[NR_FILTER_MERGE] = &FilterMerge::create;
350     _constructor[NR_FILTER_MORPHOLOGY] = &FilterMorphology::create;
351     _constructor[NR_FILTER_OFFSET] = &FilterOffset::create;
352     _constructor[NR_FILTER_SPECULARLIGHTING] = &FilterSpecularLighting::create;
353     _constructor[NR_FILTER_TILE] = &FilterTile::create;
354     _constructor[NR_FILTER_TURBULENCE] = &FilterTurbulence::create;
355     created = true;
358 /** Helper method for enlarging table of filter primitives. When new
359  * primitives are added, but we have no space for them, this function
360  * makes some more space.
361  */
362 void Filter::_enlarge_primitive_table() {
363     FilterPrimitive **new_tbl = new FilterPrimitive*[_primitive_table_size * 2];
364     for (int i = 0 ; i < _primitive_count ; i++) {
365         new_tbl[i] = _primitive[i];
366     }
367     _primitive_table_size *= 2;
368     for (int i = _primitive_count ; i < _primitive_table_size ; i++) {
369         new_tbl[i] = NULL;
370     }
371     delete[] _primitive;
372     _primitive = new_tbl;
375 int Filter::add_primitive(FilterPrimitiveType type)
377     _create_constructor_table();
379     // Check that we can create a new filter of specified type
380     if (type < 0 || type >= NR_FILTER_ENDPRIMITIVETYPE)
381         return -1;
382     if (!_constructor[type]) return -1;
383     FilterPrimitive *created = _constructor[type]();
385     // If there is no space for new filter primitive, enlarge the table
386     if (_primitive_count >= _primitive_table_size) {
387         _enlarge_primitive_table();
388     }
390     _primitive[_primitive_count] = created;
391     int handle = _primitive_count;
392     _primitive_count++;
393     return handle;
396 int Filter::replace_primitive(int target, FilterPrimitiveType type)
398     _create_constructor_table();
400     // Check that target is valid primitive inside this filter
401     if (target < 0) return -1;
402     if (target >= _primitive_count) return -1;
403     if (!_primitive[target]) return -1;
405     // Check that we can create a new filter of specified type
406     if (type < 0 || type >= NR_FILTER_ENDPRIMITIVETYPE)
407         return -1;
408     if (!_constructor[type]) return -1;
409     FilterPrimitive *created = _constructor[type]();
411     // If there is no space for new filter primitive, enlarge the table
412     if (_primitive_count >= _primitive_table_size) {
413         _enlarge_primitive_table();
414     }
416     delete _primitive[target];
417     _primitive[target] = created;
418     return target;
421 FilterPrimitive *Filter::get_primitive(int handle) {
422     if (handle < 0 || handle >= _primitive_count) return NULL;
423     return _primitive[handle];
426 void Filter::clear_primitives()
428     for (int i = 0 ; i < _primitive_count ; i++) {
429         if (_primitive[i]) delete _primitive[i];
430     }
431     _primitive_count = 0;
434 void Filter::set_x(SVGLength const &length)
435
436   if (length._set)
437       _region_x = length;
439 void Filter::set_y(SVGLength const &length)
441   if (length._set)
442       _region_y = length;
444 void Filter::set_width(SVGLength const &length)
446   if (length._set)
447       _region_width = length;
449 void Filter::set_height(SVGLength const &length)
450
451   if (length._set)
452       _region_height = length;
455 void Filter::set_resolution(double const pixels) {
456     if (pixels > 0) {
457         _x_pixels = pixels;
458         _y_pixels = pixels;
459     }
462 void Filter::set_resolution(double const x_pixels, double const y_pixels) {
463     if (x_pixels >= 0 && y_pixels >= 0) {
464         _x_pixels = x_pixels;
465         _y_pixels = y_pixels;
466     }
469 void Filter::reset_resolution() {
470     _x_pixels = -1;
471     _y_pixels = -1;
474 int Filter::_resolution_limit(FilterQuality const quality) const {
475     int limit = -1;
476     switch (quality) {
477         case FILTER_QUALITY_WORST:
478             limit = 32;
479             break;
480         case FILTER_QUALITY_WORSE:
481             limit = 64;
482             break;
483         case FILTER_QUALITY_NORMAL:
484             limit = 256;
485             break;
486         case FILTER_QUALITY_BETTER:
487         case FILTER_QUALITY_BEST:
488         default:
489             break;
490     }
491     return limit;
494 std::pair<double,double> Filter::_filter_resolution(
495     Geom::Rect const &area, Geom::Matrix const &trans,
496     FilterQuality const filterquality) const
498     std::pair<double,double> resolution;
499     if (_x_pixels > 0) {
500         double y_len;
501         if (_y_pixels > 0) {
502             y_len = _y_pixels;
503         } else {
504             y_len = (_x_pixels * (area.max()[Y] - area.min()[Y]))
505                 / (area.max()[X] - area.min()[X]);
506         }
507         resolution.first = _x_pixels;
508         resolution.second = y_len;
509     } else {
510         Geom::Point origo = area.min();
511         origo *= trans;
512         Geom::Point max_i(area.max()[X], area.min()[Y]);
513         max_i *= trans;
514         Geom::Point max_j(area.min()[X], area.max()[Y]);
515         max_j *= trans;
516         double i_len = sqrt((origo[X] - max_i[X]) * (origo[X] - max_i[X])
517                             + (origo[Y] - max_i[Y]) * (origo[Y] - max_i[Y]));
518         double j_len = sqrt((origo[X] - max_j[X]) * (origo[X] - max_j[X])
519                             + (origo[Y] - max_j[Y]) * (origo[Y] - max_j[Y]));
520         int limit = _resolution_limit(filterquality);
521         if (limit > 0 && (i_len > limit || j_len > limit)) {
522             double aspect_ratio = i_len / j_len;
523             if (i_len > j_len) {
524                 i_len = limit;
525                 j_len = i_len / aspect_ratio;
526             }
527             else {
528                 j_len = limit;
529                 i_len = j_len * aspect_ratio;
530             }
531         }
532         resolution.first = i_len;
533         resolution.second = j_len;
534     }
535     return resolution;
538 } /* namespace Filters */
539 } /* namespace Inkscape */
541 /*
542   Local Variables:
543   mode:c++
544   c-file-style:"stroustrup"
545   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
546   indent-tabs-mode:nil
547   fill-column:99
548   End:
549 */
550 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :