Code

f09573eb4694e5d4eb7c17b365d5596c692ef26e
[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 Niko Kiirala
10  *
11  * Released under GNU GPL, read the file 'COPYING' for more information
12  */
14 #include <glib.h>
15 #include <cmath>
17 #include "display/nr-filter.h"
18 #include "display/nr-filter-primitive.h"
19 #include "display/nr-filter-slot.h"
20 #include "display/nr-filter-types.h"
21 #include "display/pixblock-scaler.h"
22 #include "display/pixblock-transform.h"
24 #include "display/nr-filter-blend.h"
25 #include "display/nr-filter-composite.h"
26 #include "display/nr-filter-convolve-matrix.h"
27 #include "display/nr-filter-diffuselighting.h"
28 #include "display/nr-filter-displacement-map.h"
29 #include "display/nr-filter-gaussian.h"
30 #include "display/nr-filter-image.h"
31 #include "display/nr-filter-offset.h"
32 #include "display/nr-filter-specularlighting.h"
33 #include "display/nr-filter-turbulence.h"
35 #include "display/nr-arena-item.h"
36 #include "libnr/nr-pixblock.h"
37 #include "libnr/nr-blit.h"
38 #include "libnr/nr-matrix.h"
39 #include "libnr/nr-scale.h"
40 #include "svg/svg-length.h"
41 #include "sp-filter-units.h"
42 #if defined (SOLARIS_2_8)
43 #include "round.h"
44 using Inkscape::round;
45 #endif 
47 __attribute__ ((const))
48 inline static int _max4(const double a, const double b,
49                         const double c, const double d) {
50     double ret = a;
51     if (b > ret) ret = b;
52     if (c > ret) ret = c;
53     if (d > ret) ret = d;
54     return (int)round(ret);
55 }
57 __attribute__ ((const))
58 inline static int _min4(const double a, const double b,
59                         const double c, const double d) {
60     double ret = a;
61     if (b < ret) ret = b;
62     if (c < ret) ret = c;
63     if (d < ret) ret = d;
64     return (int)round(ret);
65 }
67 namespace NR {
69 Filter::Filter()
70 {
71     _primitive_count = 0;
72     _primitive_table_size = 1;
73     _primitive = new FilterPrimitive*[1];
74     _primitive[0] = NULL;
75     //_primitive_count = 1;
76     //_primitive[0] = new FilterGaussian;
77     _common_init();
78 }
80 Filter::Filter(int n)
81 {
82     _primitive_count = 0;
83     _primitive_table_size = n;
84     _primitive = new FilterPrimitive*[n];
85     for ( int i = 0 ; i < n ; i++ ) {
86         _primitive[i] = NULL;
87     }
88     _common_init();
89 }
91 void Filter::_common_init() {
92     _slot_count = 1;
93     // Having "not set" here as value means the output of last filter
94     // primitive will be used as output of this filter
95     _output_slot = NR_FILTER_SLOT_NOT_SET;
97     // These are the default values for filter region,
98     // as specified in SVG standard
99     // NB: SVGLength.set takes prescaled percent values: -.10 means -10%
100     _region_x.set(SVGLength::PERCENT, -.10, 0);
101     _region_y.set(SVGLength::PERCENT, -.10, 0);
102     _region_width.set(SVGLength::PERCENT, 1.20, 0);
103     _region_height.set(SVGLength::PERCENT, 1.20, 0);
105     // Filter resolution, negative value here stands for "automatic"
106     _x_pixels = -1.0;
107     _y_pixels = -1.0;
109     _filter_units = SP_FILTER_UNITS_OBJECTBOUNDINGBOX;
110     _primitive_units = SP_FILTER_UNITS_USERSPACEONUSE;
113 Filter::~Filter()
115     clear_primitives();
116     delete[] _primitive;
120 int Filter::render(NRArenaItem const *item, NRPixBlock *pb)
122     if(!_primitive[0]) { // if there are no primitives, do nothing
123        return 0; 
124     }
126     Matrix trans = *item->ctm;
127     Matrix paraller_trans = trans;
128     bool notparaller = false;
129     FilterSlot slot(_slot_count, item);
130     NRPixBlock *in = new NRPixBlock;
132     // If filter effects region is not paraller to viewport,
133     // we must first undo the rotation / shear.
134     // It will be redone after filtering.
135     // If there is only rotation and uniform scaling (zoom), let's skip this,
136     // as it will not make a difference with gaussian blur.
137     if ((fabs(trans[1]) > 1e-6 || fabs(trans[2]) > 1e-6) &&
138         !(fabs(trans[0] - trans[3]) < 1e-6 && fabs(trans[1] + trans[2]) < 1e-6)) {
139         notparaller = true;
141         // TODO: if filter resolution is specified, scaling should be set
142         // according to that
143         double scaling_factor = sqrt(trans.expansionX() * trans.expansionX() +
144                                      trans.expansionY() * trans.expansionY());
145         scale scaling(scaling_factor, scaling_factor);
146         scale scaling_inv(1.0 / scaling_factor, 1.0 / scaling_factor);
147         trans *= scaling_inv;
148         paraller_trans.set_identity();
149         paraller_trans *= scaling;
151         Matrix itrans = trans.inverse();
152         int x0 = pb->area.x0;
153         int y0 = pb->area.y0;
154         int x1 = pb->area.x1;
155         int y1 = pb->area.y1;
156         int min_x = _min4(itrans[0] * x0 + itrans[2] * y0 + itrans[4],
157                           itrans[0] * x0 + itrans[2] * y1 + itrans[4],
158                           itrans[0] * x1 + itrans[2] * y0 + itrans[4],
159                           itrans[0] * x1 + itrans[2] * y1 + itrans[4]);
160         int max_x = _max4(itrans[0] * x0 + itrans[2] * y0 + itrans[4],
161                           itrans[0] * x0 + itrans[2] * y1 + itrans[4],
162                           itrans[0] * x1 + itrans[2] * y0 + itrans[4],
163                           itrans[0] * x1 + itrans[2] * y1 + itrans[4]);
164         int min_y = _min4(itrans[1] * x0 + itrans[3] * y0 + itrans[5],
165                           itrans[1] * x0 + itrans[3] * y1 + itrans[5],
166                           itrans[1] * x1 + itrans[3] * y0 + itrans[5],
167                           itrans[1] * x1 + itrans[3] * y1 + itrans[5]);
168         int max_y = _max4(itrans[1] * x0 + itrans[3] * y0 + itrans[5],
169                           itrans[1] * x0 + itrans[3] * y1 + itrans[5],
170                           itrans[1] * x1 + itrans[3] * y0 + itrans[5],
171                           itrans[1] * x1 + itrans[3] * y1 + itrans[5]);
172         
173         nr_pixblock_setup_fast(in, pb->mode,
174                                min_x, min_y,
175                                max_x, max_y, true);
176         if (in->size != NR_PIXBLOCK_SIZE_TINY && in->data.px == NULL) // memory allocation failed
177             return 0;
178         transform_nearest(in, pb, itrans);
179     } else if (_x_pixels >= 0) {
180         // If filter resolution is not set to automatic, we should
181         // scale the input image to correct resolution
182         /* If filter resolution is zero, the object should not be rendered */
183         if (_x_pixels == 0 || _y_pixels == 0) {
184             int size = (pb->area.x1 - pb->area.x0)
185                 * (pb->area.y1 - pb->area.y0)
186                 * NR_PIXBLOCK_BPP(pb);
187             memset(NR_PIXBLOCK_PX(pb), 0, size);
188             return 0;
189         }
190         // Resolution is specified as pixel length of our internal buffer.
191         // Though, we might not be rendering the whole object at time,
192         // so we need to calculate the correct pixel size
193         int x_len = (int)round(((pb->area.x1 - pb->area.x0) * _x_pixels) / (item->bbox.x1 - item->bbox.x0));
194         if (x_len < 1) x_len = 1;
195         // If y-resolution is also set, count y-area in the same way as x-area
196         // Otherwise, make y-area so, that aspect ratio of input pixblock and
197         // internal pixblock are the same.
198         int y_len;
199         if (_y_pixels > 0) {
200             y_len = (int)round(((pb->area.y1 - pb->area.y0) * _y_pixels) / (item->bbox.y1 - item->bbox.y0));
201         } else {
202             y_len = (int)round((x_len * (pb->area.y1 - pb->area.y0)) / (double)(pb->area.x1 - pb->area.x0));
203         }
204         if (y_len < 1) y_len = 1;
205         nr_pixblock_setup_fast(in, pb->mode, 0, 0, x_len, y_len, true);
206         if (in->size != NR_PIXBLOCK_SIZE_TINY && in->data.px == NULL) // memory allocation failed
207             return 0;
208         scale_bicubic(in, pb);
209         scale res_scaling(x_len / (double)(pb->area.x1 - pb->area.x0),
210                           y_len / (double)(pb->area.y1 - pb->area.y0));
211         paraller_trans *= res_scaling;
212     } else {
213         // If filter resolution is automatic, just make copy of input image
214         nr_pixblock_setup_fast(in, pb->mode,
215                                pb->area.x0, pb->area.y0,
216                                pb->area.x1, pb->area.y1, true);
217         if (in->size != NR_PIXBLOCK_SIZE_TINY && in->data.px == NULL) // memory allocation failed
218             return 0;
219         nr_blit_pixblock_pixblock(in, pb);
220     }
221     in->empty = FALSE;
222     slot.set(NR_FILTER_SOURCEGRAPHIC, in);
223     in = NULL; // in is now handled by FilterSlot, we should not touch it
225     for (int i = 0 ; i < _primitive_count ; i++) {
226         _primitive[i]->render(slot, paraller_trans);
227     }
228     NRPixBlock *out = slot.get(_output_slot);
230     // Clear the pixblock, where the output will be put
231     // -> the original image does not show through
232     int size = (pb->area.x1 - pb->area.x0)
233         * (pb->area.y1 - pb->area.y0)
234         * NR_PIXBLOCK_BPP(pb);
235     memset(NR_PIXBLOCK_PX(pb), 0, size);
237     if (notparaller) {
238         transform_nearest(pb, out, trans);
239     } else if (_x_pixels < 0) {
240         // If the filter resolution is automatic, just copy our final image
241         // to output pixblock, otherwise use bicubic scaling
242         nr_blit_pixblock_pixblock(pb, out);
243     } else {
244         scale_bicubic(pb, out);
245     }
247     // Take note of the amount of used image slots
248     // -> next time this filter is rendered, we can reserve enough slots
249     // immediately
250     _slot_count = slot.get_slot_count();
251     return 0;
254 void Filter::area_enlarge(NRRectL &bbox, Matrix const &m) {
255     for (int i = 0 ; i < _primitive_count ; i++) {
256         if (_primitive[i]) _primitive[i]->area_enlarge(bbox, m);
257     }
260 void Filter::bbox_enlarge(NRRectL &bbox)
262     int len_x = bbox.x1 - bbox.x0;
263     int len_y = bbox.y1 - bbox.y0;
264     /* TODO: fetch somehow the object ex and em lengths */
265     _region_x.update(12, 6, len_x);
266     _region_y.update(12, 6, len_y);
267     _region_width.update(12, 6, len_x);
268     _region_height.update(12, 6, len_y);
269     if (_filter_units == SP_FILTER_UNITS_OBJECTBOUNDINGBOX) {
270         if (_region_x.unit == SVGLength::PERCENT) {
271             bbox.x0 += (ICoord)_region_x.computed;
272         } else {
273             bbox.x0 += (ICoord)(_region_x.computed * len_x);
274         }
275         if (_region_width.unit == SVGLength::PERCENT) {
276             bbox.x1 = bbox.x0 + (ICoord)_region_width.computed;
277         } else {
278             bbox.x1 = bbox.x0 + (ICoord)(_region_width.computed * len_x);
279         }
281         if (_region_y.unit == SVGLength::PERCENT) {
282             bbox.y0 += (ICoord)_region_y.computed;
283         } else {
284             bbox.y0 += (ICoord)(_region_y.computed * len_y);
285         }
286         if (_region_height.unit == SVGLength::PERCENT) {
287             bbox.y1 = bbox.y0 + (ICoord)_region_height.computed;
288         } else {
289             bbox.y1 = bbox.y0 + (ICoord)(_region_height.computed * len_y);
290         }
291     } else if (_filter_units == SP_FILTER_UNITS_USERSPACEONUSE) {
292         /* TODO: make sure bbox and fe region are in same coordinate system */
293         bbox.x0 = (ICoord) _region_x.computed;
294         bbox.x1 = bbox.x0 + (ICoord) _region_width.computed;
295         bbox.y0 = (ICoord) _region_y.computed;
296         bbox.y1 = bbox.y0 + (ICoord) _region_height.computed;
297     } else {
298         g_warning("Error in NR::Filter::bbox_enlarge: unrecognized value of _filter_units");
299     }
302 /* Constructor table holds pointers to static methods returning filter
303  * primitives. This table is indexed with FilterPrimitiveType, so that
304  * for example method in _constructor[NR_FILTER_GAUSSIANBLUR]
305  * returns a filter object of type NR::FilterGaussian.
306  */
307 typedef FilterPrimitive*(*FilterConstructor)();
308 static FilterConstructor _constructor[NR_FILTER_ENDPRIMITIVETYPE];
310 void Filter::_create_constructor_table()
312     // Constructor table won't change in run-time, so no need to recreate
313     static bool created = false;
314     if(created) return;
316 /* Some filter classes are not implemented yet.
317    Filters with constructors appearing in this table are not necessarilly already implemented.
318    Some of them still have only boilerplate-code.*/
319     _constructor[NR_FILTER_BLEND] = &FilterBlend::create;
320     _constructor[NR_FILTER_COLORMATRIX] = NULL;
321     _constructor[NR_FILTER_COMPONENTTRANSFER] = NULL;
322     _constructor[NR_FILTER_COMPOSITE] = &FilterComposite::create;
323     _constructor[NR_FILTER_CONVOLVEMATRIX] = &FilterConvolveMatrix::create;
324     _constructor[NR_FILTER_DIFFUSELIGHTING] = &FilterDiffuseLighting::create;
325     _constructor[NR_FILTER_DISPLACEMENTMAP] = &FilterDisplacementMap::create;
326     _constructor[NR_FILTER_FLOOD] = NULL;
327     _constructor[NR_FILTER_GAUSSIANBLUR] = &FilterGaussian::create;
328     _constructor[NR_FILTER_IMAGE] = &FilterImage::create;
329     _constructor[NR_FILTER_MERGE] = NULL;
330     _constructor[NR_FILTER_MORPHOLOGY] = NULL;
331     _constructor[NR_FILTER_OFFSET] = &FilterOffset::create;
332     _constructor[NR_FILTER_SPECULARLIGHTING] = &FilterSpecularLighting::create;
333     _constructor[NR_FILTER_TILE] = NULL;
334     _constructor[NR_FILTER_TURBULENCE] = &FilterTurbulence::create;
335     created = true;
338 /** Helper method for enlarging table of filter primitives. When new
339  * primitives are added, but we have no space for them, this function
340  * makes some more space.
341  */
342 void Filter::_enlarge_primitive_table() {
343     FilterPrimitive **new_tbl = new FilterPrimitive*[_primitive_table_size * 2];
344     for (int i = 0 ; i < _primitive_count ; i++) {
345         new_tbl[i] = _primitive[i];
346     }
347     _primitive_table_size *= 2;
348     for (int i = _primitive_count ; i < _primitive_table_size ; i++) {
349         new_tbl[i] = NULL;
350     }
351     delete[] _primitive;
352     _primitive = new_tbl;
355 int Filter::add_primitive(FilterPrimitiveType type)
357     _create_constructor_table();
359     // Check that we can create a new filter of specified type
360     if (type < 0 || type >= NR_FILTER_ENDPRIMITIVETYPE)
361         return -1;
362     if (!_constructor[type]) return -1;
363     FilterPrimitive *created = _constructor[type]();
365     // If there is no space for new filter primitive, enlarge the table
366     if (_primitive_count >= _primitive_table_size) {
367         _enlarge_primitive_table();
368     }
370     _primitive[_primitive_count] = created;
371     int handle = _primitive_count;
372     _primitive_count++;
373     return handle;
376 int Filter::replace_primitive(int target, FilterPrimitiveType type)
378     _create_constructor_table();
380     // Check that target is valid primitive inside this filter
381     if (target < 0) return -1;
382     if (target >= _primitive_count) return -1;
383     if (!_primitive[target]) return -1;
385     // Check that we can create a new filter of specified type
386     if (type < 0 || type >= NR_FILTER_ENDPRIMITIVETYPE)
387         return -1;
388     if (!_constructor[type]) return -1;
389     FilterPrimitive *created = _constructor[type]();
391     // If there is no space for new filter primitive, enlarge the table
392     if (_primitive_count >= _primitive_table_size) {
393         _enlarge_primitive_table();
394     }
396     delete _primitive[target];
397     _primitive[target] = created;
398     return target;
401 FilterPrimitive *Filter::get_primitive(int handle) {
402     if (handle < 0 || handle >= _primitive_count) return NULL;
403     return _primitive[handle];
406 void Filter::clear_primitives()
408     for (int i = 0 ; i < _primitive_count ; i++) {
409         if (_primitive[i]) delete _primitive[i];
410     }
411     _primitive_count = 0;
414 void Filter::set_x(SVGLength const &length)
415
416   if (length._set)
417       _region_x = length;
419 void Filter::set_y(SVGLength const &length)
421   if (length._set)
422       _region_y = length;
424 void Filter::set_width(SVGLength const &length)
426   if (length._set)
427       _region_width = length;
429 void Filter::set_height(SVGLength const &length)
430
431   if (length._set)
432       _region_height = length;
435 void Filter::set_resolution(double const pixels) {
436     if (pixels > 0) {
437         _x_pixels = pixels;
438         _y_pixels = pixels;
439     }
442 void Filter::set_resolution(double const x_pixels, double const y_pixels) {
443     if (x_pixels >= 0 && y_pixels >= 0) {
444         _x_pixels = x_pixels;
445         _y_pixels = y_pixels;
446     }
449 void Filter::reset_resolution() {
450     _x_pixels = -1;
451     _y_pixels = -1;
454 } /* namespace NR */
456 /*
457   Local Variables:
458   mode:c++
459   c-file-style:"stroustrup"
460   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
461   indent-tabs-mode:nil
462   fill-column:99
463   End:
464 */
465 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :