Code

3b19ff69ba6f996ac0a91e2b34183f876be8c50b
[inkscape.git] / 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.h"
43 #include "display/nr-arena-item.h"
44 #include "libnr/nr-pixblock.h"
45 #include "libnr/nr-blit.h"
46 #include <2geom/matrix.h>
47 #include <2geom/rect.h>
48 #include "svg/svg-length.h"
49 #include "sp-filter-units.h"
50 #include "preferences.h"
52 #if defined (SOLARIS) && (SOLARIS == 8)
53 #include "round.h"
54 using Inkscape::round;
55 #endif
57 namespace Inkscape {
58 namespace Filters {
60 using Geom::X;
61 using Geom::Y;
63 static Geom::OptRect get_item_bbox(NRArenaItem const *item) {
64     Geom::Rect item_bbox;
65     if (item->item_bbox) {
66         item_bbox = *(item->item_bbox);
67     } else {
68         // Bounding box might not exist, so create a dummy one.
69         Geom::Point zero(0, 0);
70         item_bbox = Geom::Rect(zero, zero);
71     }
72     if (item_bbox.min()[X] > item_bbox.max()[X]
73         || item_bbox.min()[Y] > item_bbox.max()[Y])
74     {
75         // In case of negative-size bbox, return an empty OptRect
76         return Geom::OptRect();
77     }
78     return Geom::OptRect(item_bbox);
79 }
81 Filter::Filter()
82 {
83     _primitive_count = 0;
84     _primitive_table_size = 1;
85     _primitive = new FilterPrimitive*[1];
86     _primitive[0] = NULL;
87     //_primitive_count = 1;
88     //_primitive[0] = new FilterGaussian;
89     _common_init();
90 }
92 Filter::Filter(int n)
93 {
94     _primitive_count = 0;
95     _primitive_table_size = (n > 0) ? n : 1;    // we guarantee there is at least 1(one) filter slot
96     _primitive = new FilterPrimitive*[_primitive_table_size];
97     for ( int i = 0 ; i < _primitive_table_size ; i++ ) {
98         _primitive[i] = NULL;
99     }
100     _common_init();
103 void Filter::_common_init() {
104     _slot_count = 1;
105     // Having "not set" here as value means the output of last filter
106     // primitive will be used as output of this filter
107     _output_slot = NR_FILTER_SLOT_NOT_SET;
109     // These are the default values for filter region,
110     // as specified in SVG standard
111     // NB: SVGLength.set takes prescaled percent values: -.10 means -10%
112     _region_x.set(SVGLength::PERCENT, -.10, 0);
113     _region_y.set(SVGLength::PERCENT, -.10, 0);
114     _region_width.set(SVGLength::PERCENT, 1.20, 0);
115     _region_height.set(SVGLength::PERCENT, 1.20, 0);
117     // Filter resolution, negative value here stands for "automatic"
118     _x_pixels = -1.0;
119     _y_pixels = -1.0;
121     _filter_units = SP_FILTER_UNITS_OBJECTBOUNDINGBOX;
122     _primitive_units = SP_FILTER_UNITS_USERSPACEONUSE;
125 Filter::~Filter()
127     clear_primitives();
128     delete[] _primitive;
132 int Filter::render(NRArenaItem const *item, NRPixBlock *pb)
134     if (!_primitive[0]) {
135         // TODO: Should clear the input buffer instead of just returning
136        return 1;
137     }
139     FilterQuality const filterquality = (FilterQuality)item->arena->filterquality;
140     int const blurquality = item->arena->blurquality;
142     Geom::Matrix trans = item->ctm;
143     FilterSlot slot(_slot_count, item);
144     slot.set_quality(filterquality);
145     slot.set_blurquality(blurquality);
147     Geom::Rect item_bbox;
148     {
149         Geom::OptRect maybe_bbox = get_item_bbox(item);
150         if (maybe_bbox.isEmpty()) {
151             // Code below needs a bounding box
152             return 1;
153         }
154         item_bbox = *maybe_bbox;
155     }
157     Geom::Rect filter_area = filter_effect_area(item_bbox);
158     if (item_bbox.hasZeroArea()) {
159         // It's no use to try and filter an empty object.
160         return 1;
161     }
163     FilterUnits units(_filter_units, _primitive_units);
164     units.set_ctm(trans);
165     units.set_item_bbox(item_bbox);
166     units.set_filter_area(filter_area);
168     // TODO: with filterRes of 0x0 should return an empty image
169     std::pair<double,double> resolution
170         = _filter_resolution(filter_area, trans, filterquality);
171     if(!(resolution.first > 0 && resolution.second > 0))
172         return 1;
173     units.set_resolution(resolution.first, resolution.second);
174     if (_x_pixels > 0) {
175         units.set_automatic_resolution(false);
176     }
177     else {
178         units.set_automatic_resolution(true);
179     }
181     units.set_paraller(false);
182     for (int i = 0 ; i < _primitive_count ; i++) {
183         if (_primitive[i]->get_input_traits() & TRAIT_PARALLER) {
184             units.set_paraller(true);
185             break;
186         }
187     }
189     slot.set_units(units);
191     NRPixBlock *in = new NRPixBlock;
192     nr_pixblock_setup_fast(in, pb->mode, pb->area.x0, pb->area.y0,
193                            pb->area.x1, pb->area.y1, true);
194     if (in->size != NR_PIXBLOCK_SIZE_TINY && in->data.px == NULL) {
195         g_warning("Inkscape::Filters::Filter::render: failed to reserve temporary buffer");
196         return 0;
197     }
198     nr_blit_pixblock_pixblock(in, pb);
199     in->empty = FALSE;
200     slot.set(NR_FILTER_SOURCEGRAPHIC, in);
202     // Check that we are rendering a non-empty area
203     in = slot.get(NR_FILTER_SOURCEGRAPHIC);
204     if (in->area.x1 - in->area.x0 <= 0 || in->area.y1 - in->area.y0 <= 0) {
205         if (in->area.x1 - in->area.x0 < 0 || in->area.y1 - in->area.y0 < 0) {
206             g_warning("Inkscape::Filters::Filter::render: negative area! (%d, %d) (%d, %d)",
207                       in->area.x0, in->area.y0, in->area.x1, in->area.y1);
208         }
209         return 0;
210     }
211     in = NULL; // in is now handled by FilterSlot, we should not touch it
213     for (int i = 0 ; i < _primitive_count ; i++) {
214         _primitive[i]->render(slot, units);
215     }
217     slot.get_final(_output_slot, pb);
219     // Take note of the amount of used image slots
220     // -> next time this filter is rendered, we can reserve enough slots
221     // immediately
222     _slot_count = slot.get_slot_count();
223     return 0;
226 void Filter::set_filter_units(SPFilterUnits unit) {
227     _filter_units = unit;
230 void Filter::set_primitive_units(SPFilterUnits unit) {
231     _primitive_units = unit;
234 void Filter::area_enlarge(NRRectL &bbox, NRArenaItem const *item) const {
235     for (int i = 0 ; i < _primitive_count ; i++) {
236         if (_primitive[i]) _primitive[i]->area_enlarge(bbox, item->ctm);
237     }
238 /*
239   TODO: something. See images at the bottom of filters.svg with medium-low
240   filtering quality.
242     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
243     FilterQuality const filterquality = (FilterQuality)prefs->getInt("/options/filterquality/value");
245     if (_x_pixels <= 0 && (filterquality == FILTER_QUALITY_BEST ||
246                            filterquality == FILTER_QUALITY_BETTER)) {
247         return;
248     }
250     Geom::Rect item_bbox;
251     Geom::OptRect maybe_bbox = get_item_bbox(item);
252     if (maybe_bbox.isEmpty()) {
253         // Code below needs a bounding box
254         return;
255     }
256     item_bbox = *maybe_bbox;
258     std::pair<double,double> res_low
259         = _filter_resolution(item_bbox, item->ctm, filterquality);
260     //std::pair<double,double> res_full
261     //    = _filter_resolution(item_bbox, item->ctm, FILTER_QUALITY_BEST);
262     double pixels_per_block = fmax(item_bbox.width() / res_low.first,
263                                    item_bbox.height() / res_low.second);
264     bbox.x0 -= (int)pixels_per_block;
265     bbox.x1 += (int)pixels_per_block;
266     bbox.y0 -= (int)pixels_per_block;
267     bbox.y1 += (int)pixels_per_block;
268 */
271 void Filter::bbox_enlarge(NRRectL &bbox) {
272     // Modifying empty bounding boxes confuses rest of the renderer, so
273     // let's not do that.
274     if (bbox.x0 > bbox.x1 || bbox.y0 > bbox.y1) return;
276     /* TODO: this is wrong. Should use bounding box in user coordinates
277      * and find its extents in display coordinates. */
278     Geom::Point min(bbox.x0, bbox.y0);
279     Geom::Point max(bbox.x1, bbox.y1);
280     Geom::Rect tmp_bbox(min, max);
282     Geom::Rect enlarged = filter_effect_area(tmp_bbox);
284     bbox.x0 = (NR::ICoord)enlarged.min()[X];
285     bbox.y0 = (NR::ICoord)enlarged.min()[Y];
286     bbox.x1 = (NR::ICoord)enlarged.max()[X];
287     bbox.y1 = (NR::ICoord)enlarged.max()[Y];
290 Geom::Rect Filter::filter_effect_area(Geom::Rect const &bbox)
292     Geom::Point minp, maxp;
293     double len_x = bbox.max()[X] - bbox.min()[X];
294     double len_y = bbox.max()[Y] - bbox.min()[Y];
295     /* TODO: fetch somehow the object ex and em lengths */
296     _region_x.update(12, 6, len_x);
297     _region_y.update(12, 6, len_y);
298     _region_width.update(12, 6, len_x);
299     _region_height.update(12, 6, len_y);
300     if (_filter_units == SP_FILTER_UNITS_OBJECTBOUNDINGBOX) {
301         if (_region_x.unit == SVGLength::PERCENT) {
302             minp[X] = bbox.min()[X] + _region_x.computed;
303         } else {
304             minp[X] = bbox.min()[X] + _region_x.computed * len_x;
305         }
306         if (_region_width.unit == SVGLength::PERCENT) {
307             maxp[X] = minp[X] + _region_width.computed;
308         } else {
309             maxp[X] = minp[X] + _region_width.computed * len_x;
310         }
312         if (_region_y.unit == SVGLength::PERCENT) {
313             minp[Y] = bbox.min()[Y] + _region_y.computed;
314         } else {
315             minp[Y] = bbox.min()[Y] + _region_y.computed * len_y;
316         }
317         if (_region_height.unit == SVGLength::PERCENT) {
318             maxp[Y] = minp[Y] + _region_height.computed;
319         } else {
320             maxp[Y] = minp[Y] + _region_height.computed * len_y;
321         }
322     } else if (_filter_units == SP_FILTER_UNITS_USERSPACEONUSE) {
323         /* TODO: make sure bbox and fe region are in same coordinate system */
324         minp[X] = _region_x.computed;
325         maxp[X] = minp[X] + _region_width.computed;
326         minp[Y] = _region_y.computed;
327         maxp[Y] = minp[Y] + _region_height.computed;
328     } else {
329         g_warning("Error in Inkscape::Filters::Filter::bbox_enlarge: unrecognized value of _filter_units");
330     }
331     Geom::Rect area(minp, maxp);
332     return area;
335 /* Constructor table holds pointers to static methods returning filter
336  * primitives. This table is indexed with FilterPrimitiveType, so that
337  * for example method in _constructor[NR_FILTER_GAUSSIANBLUR]
338  * returns a filter object of type Inkscape::Filters::FilterGaussian.
339  */
340 typedef FilterPrimitive*(*FilterConstructor)();
341 static FilterConstructor _constructor[NR_FILTER_ENDPRIMITIVETYPE];
343 void Filter::_create_constructor_table()
345     // Constructor table won't change in run-time, so no need to recreate
346     static bool created = false;
347     if(created) return;
349 /* Some filter classes are not implemented yet.
350    Some of them still have only boilerplate code.*/
351     _constructor[NR_FILTER_BLEND] = &FilterBlend::create;
352     _constructor[NR_FILTER_COLORMATRIX] = &FilterColorMatrix::create;
353     _constructor[NR_FILTER_COMPONENTTRANSFER] = &FilterComponentTransfer::create;
354     _constructor[NR_FILTER_COMPOSITE] = &FilterComposite::create;
355     _constructor[NR_FILTER_CONVOLVEMATRIX] = &FilterConvolveMatrix::create;
356     _constructor[NR_FILTER_DIFFUSELIGHTING] = &FilterDiffuseLighting::create;
357     _constructor[NR_FILTER_DISPLACEMENTMAP] = &FilterDisplacementMap::create;
358     _constructor[NR_FILTER_FLOOD] = &FilterFlood::create;
359     _constructor[NR_FILTER_GAUSSIANBLUR] = &FilterGaussian::create;
360     _constructor[NR_FILTER_IMAGE] = &FilterImage::create;
361     _constructor[NR_FILTER_MERGE] = &FilterMerge::create;
362     _constructor[NR_FILTER_MORPHOLOGY] = &FilterMorphology::create;
363     _constructor[NR_FILTER_OFFSET] = &FilterOffset::create;
364     _constructor[NR_FILTER_SPECULARLIGHTING] = &FilterSpecularLighting::create;
365     _constructor[NR_FILTER_TILE] = &FilterTile::create;
366     _constructor[NR_FILTER_TURBULENCE] = &FilterTurbulence::create;
367     created = true;
370 /** Helper method for enlarging table of filter primitives. When new
371  * primitives are added, but we have no space for them, this function
372  * makes some more space.
373  */
374 void Filter::_enlarge_primitive_table() {
375     FilterPrimitive **new_tbl = new FilterPrimitive*[_primitive_table_size * 2];
376     for (int i = 0 ; i < _primitive_count ; i++) {
377         new_tbl[i] = _primitive[i];
378     }
379     _primitive_table_size *= 2;
380     for (int i = _primitive_count ; i < _primitive_table_size ; i++) {
381         new_tbl[i] = NULL;
382     }
383     if(_primitive != NULL) {
384         delete[] _primitive;
385     } else {
386         g_warning("oh oh");
387     }
388     _primitive = new_tbl;
391 int Filter::add_primitive(FilterPrimitiveType type)
393     _create_constructor_table();
395     // Check that we can create a new filter of specified type
396     if (type < 0 || type >= NR_FILTER_ENDPRIMITIVETYPE)
397         return -1;
398     if (!_constructor[type]) return -1;
399     FilterPrimitive *created = _constructor[type]();
401     // If there is no space for new filter primitive, enlarge the table
402     if (_primitive_count >= _primitive_table_size) {
403         _enlarge_primitive_table();
404     }
406     _primitive[_primitive_count] = created;
407     int handle = _primitive_count;
408     _primitive_count++;
409     return handle;
412 int Filter::replace_primitive(int target, FilterPrimitiveType type)
414     _create_constructor_table();
416     // Check that target is valid primitive inside this filter
417     if (target < 0) return -1;
418     if (target >= _primitive_count) return -1;
419     if (!_primitive[target]) return -1;
421     // Check that we can create a new filter of specified type
422     if (type < 0 || type >= NR_FILTER_ENDPRIMITIVETYPE)
423         return -1;
424     if (!_constructor[type]) return -1;
425     FilterPrimitive *created = _constructor[type]();
427     // If there is no space for new filter primitive, enlarge the table
428     if (_primitive_count >= _primitive_table_size) {
429         _enlarge_primitive_table();
430     }
432     delete _primitive[target];
433     _primitive[target] = created;
434     return target;
437 FilterPrimitive *Filter::get_primitive(int handle) {
438     if (handle < 0 || handle >= _primitive_count) return NULL;
439     return _primitive[handle];
442 void Filter::clear_primitives()
444     for (int i = 0 ; i < _primitive_count ; i++) {
445         if (_primitive[i]) delete _primitive[i];
446     }
447     _primitive_count = 0;
450 void Filter::set_x(SVGLength const &length)
452   if (length._set)
453       _region_x = length;
455 void Filter::set_y(SVGLength const &length)
457   if (length._set)
458       _region_y = length;
460 void Filter::set_width(SVGLength const &length)
462   if (length._set)
463       _region_width = length;
465 void Filter::set_height(SVGLength const &length)
467   if (length._set)
468       _region_height = length;
471 void Filter::set_resolution(double const pixels) {
472     if (pixels > 0) {
473         _x_pixels = pixels;
474         _y_pixels = pixels;
475     }
478 void Filter::set_resolution(double const x_pixels, double const y_pixels) {
479     if (x_pixels >= 0 && y_pixels >= 0) {
480         _x_pixels = x_pixels;
481         _y_pixels = y_pixels;
482     }
485 void Filter::reset_resolution() {
486     _x_pixels = -1;
487     _y_pixels = -1;
490 int Filter::_resolution_limit(FilterQuality const quality) const {
491     int limit = -1;
492     switch (quality) {
493         case FILTER_QUALITY_WORST:
494             limit = 32;
495             break;
496         case FILTER_QUALITY_WORSE:
497             limit = 64;
498             break;
499         case FILTER_QUALITY_NORMAL:
500             limit = 256;
501             break;
502         case FILTER_QUALITY_BETTER:
503         case FILTER_QUALITY_BEST:
504         default:
505             break;
506     }
507     return limit;
510 std::pair<double,double> Filter::_filter_resolution(
511     Geom::Rect const &area, Geom::Matrix const &trans,
512     FilterQuality const filterquality) const
514     std::pair<double,double> resolution;
515     if (_x_pixels > 0) {
516         double y_len;
517         if (_y_pixels > 0) {
518             y_len = _y_pixels;
519         } else {
520             y_len = (_x_pixels * (area.max()[Y] - area.min()[Y]))
521                 / (area.max()[X] - area.min()[X]);
522         }
523         resolution.first = _x_pixels;
524         resolution.second = y_len;
525     } else {
526         Geom::Point origo = area.min();
527         origo *= trans;
528         Geom::Point max_i(area.max()[X], area.min()[Y]);
529         max_i *= trans;
530         Geom::Point max_j(area.min()[X], area.max()[Y]);
531         max_j *= trans;
532         double i_len = sqrt((origo[X] - max_i[X]) * (origo[X] - max_i[X])
533                             + (origo[Y] - max_i[Y]) * (origo[Y] - max_i[Y]));
534         double j_len = sqrt((origo[X] - max_j[X]) * (origo[X] - max_j[X])
535                             + (origo[Y] - max_j[Y]) * (origo[Y] - max_j[Y]));
536         int limit = _resolution_limit(filterquality);
537         if (limit > 0 && (i_len > limit || j_len > limit)) {
538             double aspect_ratio = i_len / j_len;
539             if (i_len > j_len) {
540                 i_len = limit;
541                 j_len = i_len / aspect_ratio;
542             }
543             else {
544                 j_len = limit;
545                 i_len = j_len * aspect_ratio;
546             }
547         }
548         resolution.first = i_len;
549         resolution.second = j_len;
550     }
551     return resolution;
554 } /* namespace Filters */
555 } /* namespace Inkscape */
557 /*
558   Local Variables:
559   mode:c++
560   c-file-style:"stroustrup"
561   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
562   indent-tabs-mode:nil
563   fill-column:99
564   End:
565 */
566 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :