Code

Avoid crash by uninitialized perspectives.
[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::area_enlarge(NRRectL &bbox, NRArenaItem const *item) const {
227     for (int i = 0 ; i < _primitive_count ; i++) {
228         if (_primitive[i]) _primitive[i]->area_enlarge(bbox, item->ctm);
229     }
230 /*
231   TODO: something. See images at the bottom of filters.svg with medium-low
232   filtering quality.
234     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
235     FilterQuality const filterquality = (FilterQuality)prefs->getInt("/options/filterquality/value");
237     if (_x_pixels <= 0 && (filterquality == FILTER_QUALITY_BEST ||
238                            filterquality == FILTER_QUALITY_BETTER)) {
239         return;
240     }
242     Geom::Rect item_bbox;
243     Geom::OptRect maybe_bbox = get_item_bbox(item);
244     if (maybe_bbox.isEmpty()) {
245         // Code below needs a bounding box
246         return;
247     }
248     item_bbox = *maybe_bbox;
250     std::pair<double,double> res_low
251         = _filter_resolution(item_bbox, item->ctm, filterquality);
252     //std::pair<double,double> res_full
253     //    = _filter_resolution(item_bbox, item->ctm, FILTER_QUALITY_BEST);
254     double pixels_per_block = fmax(item_bbox.width() / res_low.first,
255                                    item_bbox.height() / res_low.second);
256     bbox.x0 -= (int)pixels_per_block;
257     bbox.x1 += (int)pixels_per_block;
258     bbox.y0 -= (int)pixels_per_block;
259     bbox.y1 += (int)pixels_per_block;
260 */
263 void Filter::bbox_enlarge(NRRectL &bbox) {
264     // Modifying empty bounding boxes confuses rest of the renderer, so
265     // let's not do that.
266     if (bbox.x0 > bbox.x1 || bbox.y0 > bbox.y1) return;
268     /* TODO: this is wrong. Should use bounding box in user coordinates
269      * and find its extents in display coordinates. */
270     Geom::Point min(bbox.x0, bbox.y0);
271     Geom::Point max(bbox.x1, bbox.y1);
272     Geom::Rect tmp_bbox(min, max);
274     Geom::Rect enlarged = filter_effect_area(tmp_bbox);
276     bbox.x0 = (NR::ICoord)enlarged.min()[X];
277     bbox.y0 = (NR::ICoord)enlarged.min()[Y];
278     bbox.x1 = (NR::ICoord)enlarged.max()[X];
279     bbox.y1 = (NR::ICoord)enlarged.max()[Y];
282 Geom::Rect Filter::filter_effect_area(Geom::Rect const &bbox)
284     Geom::Point minp, maxp;
285     double len_x = bbox.max()[X] - bbox.min()[X];
286     double len_y = bbox.max()[Y] - bbox.min()[Y];
287     /* TODO: fetch somehow the object ex and em lengths */
288     _region_x.update(12, 6, len_x);
289     _region_y.update(12, 6, len_y);
290     _region_width.update(12, 6, len_x);
291     _region_height.update(12, 6, len_y);
292     if (_filter_units == SP_FILTER_UNITS_OBJECTBOUNDINGBOX) {
293         if (_region_x.unit == SVGLength::PERCENT) {
294             minp[X] = bbox.min()[X] + _region_x.computed;
295         } else {
296             minp[X] = bbox.min()[X] + _region_x.computed * len_x;
297         }
298         if (_region_width.unit == SVGLength::PERCENT) {
299             maxp[X] = minp[X] + _region_width.computed;
300         } else {
301             maxp[X] = minp[X] + _region_width.computed * len_x;
302         }
304         if (_region_y.unit == SVGLength::PERCENT) {
305             minp[Y] = bbox.min()[Y] + _region_y.computed;
306         } else {
307             minp[Y] = bbox.min()[Y] + _region_y.computed * len_y;
308         }
309         if (_region_height.unit == SVGLength::PERCENT) {
310             maxp[Y] = minp[Y] + _region_height.computed;
311         } else {
312             maxp[Y] = minp[Y] + _region_height.computed * len_y;
313         }
314     } else if (_filter_units == SP_FILTER_UNITS_USERSPACEONUSE) {
315         /* TODO: make sure bbox and fe region are in same coordinate system */
316         minp[X] = _region_x.computed;
317         maxp[X] = minp[X] + _region_width.computed;
318         minp[Y] = _region_y.computed;
319         maxp[Y] = minp[Y] + _region_height.computed;
320     } else {
321         g_warning("Error in Inkscape::Filters::Filter::bbox_enlarge: unrecognized value of _filter_units");
322     }
323     Geom::Rect area(minp, maxp);
324     return area;
327 /* Constructor table holds pointers to static methods returning filter
328  * primitives. This table is indexed with FilterPrimitiveType, so that
329  * for example method in _constructor[NR_FILTER_GAUSSIANBLUR]
330  * returns a filter object of type Inkscape::Filters::FilterGaussian.
331  */
332 typedef FilterPrimitive*(*FilterConstructor)();
333 static FilterConstructor _constructor[NR_FILTER_ENDPRIMITIVETYPE];
335 void Filter::_create_constructor_table()
337     // Constructor table won't change in run-time, so no need to recreate
338     static bool created = false;
339     if(created) return;
341 /* Some filter classes are not implemented yet.
342    Some of them still have only boilerplate code.*/
343     _constructor[NR_FILTER_BLEND] = &FilterBlend::create;
344     _constructor[NR_FILTER_COLORMATRIX] = &FilterColorMatrix::create;
345     _constructor[NR_FILTER_COMPONENTTRANSFER] = &FilterComponentTransfer::create;
346     _constructor[NR_FILTER_COMPOSITE] = &FilterComposite::create;
347     _constructor[NR_FILTER_CONVOLVEMATRIX] = &FilterConvolveMatrix::create;
348     _constructor[NR_FILTER_DIFFUSELIGHTING] = &FilterDiffuseLighting::create;
349     _constructor[NR_FILTER_DISPLACEMENTMAP] = &FilterDisplacementMap::create;
350     _constructor[NR_FILTER_FLOOD] = &FilterFlood::create;
351     _constructor[NR_FILTER_GAUSSIANBLUR] = &FilterGaussian::create;
352     _constructor[NR_FILTER_IMAGE] = &FilterImage::create;
353     _constructor[NR_FILTER_MERGE] = &FilterMerge::create;
354     _constructor[NR_FILTER_MORPHOLOGY] = &FilterMorphology::create;
355     _constructor[NR_FILTER_OFFSET] = &FilterOffset::create;
356     _constructor[NR_FILTER_SPECULARLIGHTING] = &FilterSpecularLighting::create;
357     _constructor[NR_FILTER_TILE] = &FilterTile::create;
358     _constructor[NR_FILTER_TURBULENCE] = &FilterTurbulence::create;
359     created = true;
362 /** Helper method for enlarging table of filter primitives. When new
363  * primitives are added, but we have no space for them, this function
364  * makes some more space.
365  */
366 void Filter::_enlarge_primitive_table() {
367     FilterPrimitive **new_tbl = new FilterPrimitive*[_primitive_table_size * 2];
368     for (int i = 0 ; i < _primitive_count ; i++) {
369         new_tbl[i] = _primitive[i];
370     }
371     _primitive_table_size *= 2;
372     for (int i = _primitive_count ; i < _primitive_table_size ; i++) {
373         new_tbl[i] = NULL;
374     }
375     if(_primitive != NULL) {
376         delete[] _primitive;
377     } else {
378         g_warning("oh oh");
379     }
380     _primitive = new_tbl;
383 int Filter::add_primitive(FilterPrimitiveType type)
385     _create_constructor_table();
387     // Check that we can create a new filter of specified type
388     if (type < 0 || type >= NR_FILTER_ENDPRIMITIVETYPE)
389         return -1;
390     if (!_constructor[type]) return -1;
391     FilterPrimitive *created = _constructor[type]();
393     // If there is no space for new filter primitive, enlarge the table
394     if (_primitive_count >= _primitive_table_size) {
395         _enlarge_primitive_table();
396     }
398     _primitive[_primitive_count] = created;
399     int handle = _primitive_count;
400     _primitive_count++;
401     return handle;
404 int Filter::replace_primitive(int target, FilterPrimitiveType type)
406     _create_constructor_table();
408     // Check that target is valid primitive inside this filter
409     if (target < 0) return -1;
410     if (target >= _primitive_count) return -1;
411     if (!_primitive[target]) return -1;
413     // Check that we can create a new filter of specified type
414     if (type < 0 || type >= NR_FILTER_ENDPRIMITIVETYPE)
415         return -1;
416     if (!_constructor[type]) return -1;
417     FilterPrimitive *created = _constructor[type]();
419     // If there is no space for new filter primitive, enlarge the table
420     if (_primitive_count >= _primitive_table_size) {
421         _enlarge_primitive_table();
422     }
424     delete _primitive[target];
425     _primitive[target] = created;
426     return target;
429 FilterPrimitive *Filter::get_primitive(int handle) {
430     if (handle < 0 || handle >= _primitive_count) return NULL;
431     return _primitive[handle];
434 void Filter::clear_primitives()
436     for (int i = 0 ; i < _primitive_count ; i++) {
437         if (_primitive[i]) delete _primitive[i];
438     }
439     _primitive_count = 0;
442 void Filter::set_x(SVGLength const &length)
444   if (length._set)
445       _region_x = length;
447 void Filter::set_y(SVGLength const &length)
449   if (length._set)
450       _region_y = length;
452 void Filter::set_width(SVGLength const &length)
454   if (length._set)
455       _region_width = length;
457 void Filter::set_height(SVGLength const &length)
459   if (length._set)
460       _region_height = length;
463 void Filter::set_resolution(double const pixels) {
464     if (pixels > 0) {
465         _x_pixels = pixels;
466         _y_pixels = pixels;
467     }
470 void Filter::set_resolution(double const x_pixels, double const y_pixels) {
471     if (x_pixels >= 0 && y_pixels >= 0) {
472         _x_pixels = x_pixels;
473         _y_pixels = y_pixels;
474     }
477 void Filter::reset_resolution() {
478     _x_pixels = -1;
479     _y_pixels = -1;
482 int Filter::_resolution_limit(FilterQuality const quality) const {
483     int limit = -1;
484     switch (quality) {
485         case FILTER_QUALITY_WORST:
486             limit = 32;
487             break;
488         case FILTER_QUALITY_WORSE:
489             limit = 64;
490             break;
491         case FILTER_QUALITY_NORMAL:
492             limit = 256;
493             break;
494         case FILTER_QUALITY_BETTER:
495         case FILTER_QUALITY_BEST:
496         default:
497             break;
498     }
499     return limit;
502 std::pair<double,double> Filter::_filter_resolution(
503     Geom::Rect const &area, Geom::Matrix const &trans,
504     FilterQuality const filterquality) const
506     std::pair<double,double> resolution;
507     if (_x_pixels > 0) {
508         double y_len;
509         if (_y_pixels > 0) {
510             y_len = _y_pixels;
511         } else {
512             y_len = (_x_pixels * (area.max()[Y] - area.min()[Y]))
513                 / (area.max()[X] - area.min()[X]);
514         }
515         resolution.first = _x_pixels;
516         resolution.second = y_len;
517     } else {
518         Geom::Point origo = area.min();
519         origo *= trans;
520         Geom::Point max_i(area.max()[X], area.min()[Y]);
521         max_i *= trans;
522         Geom::Point max_j(area.min()[X], area.max()[Y]);
523         max_j *= trans;
524         double i_len = sqrt((origo[X] - max_i[X]) * (origo[X] - max_i[X])
525                             + (origo[Y] - max_i[Y]) * (origo[Y] - max_i[Y]));
526         double j_len = sqrt((origo[X] - max_j[X]) * (origo[X] - max_j[X])
527                             + (origo[Y] - max_j[Y]) * (origo[Y] - max_j[Y]));
528         int limit = _resolution_limit(filterquality);
529         if (limit > 0 && (i_len > limit || j_len > limit)) {
530             double aspect_ratio = i_len / j_len;
531             if (i_len > j_len) {
532                 i_len = limit;
533                 j_len = i_len / aspect_ratio;
534             }
535             else {
536                 j_len = limit;
537                 i_len = j_len * aspect_ratio;
538             }
539         }
540         resolution.first = i_len;
541         resolution.second = j_len;
542     }
543     return resolution;
546 } /* namespace Filters */
547 } /* namespace Inkscape */
549 /*
550   Local Variables:
551   mode:c++
552   c-file-style:"stroustrup"
553   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
554   indent-tabs-mode:nil
555   fill-column:99
556   End:
557 */
558 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :