Code

8a22778a130566eaa57233496c5b2e7429f27fc1
[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-gaussian.h"
25 #include "display/nr-filter-blend.h"
26 #include "display/nr-filter-offset.h"
27 #include "display/nr-filter-composite.h"
28 #include "display/nr-filter-diffuselighting.h"
29 #include "display/nr-filter-specularlighting.h"
31 #include "display/nr-arena-item.h"
32 #include "libnr/nr-pixblock.h"
33 #include "libnr/nr-blit.h"
34 #include "libnr/nr-matrix.h"
35 #include "libnr/nr-scale.h"
36 #include "svg/svg-length.h"
37 #include "sp-filter-units.h"
38 #if defined (SOLARIS_2_8)
39 #include "round.h"
40 using Inkscape::round;
41 #endif 
43 __attribute__ ((const))
44 inline static int _max4(const double a, const double b,
45                         const double c, const double d) {
46     double ret = a;
47     if (b > ret) ret = b;
48     if (c > ret) ret = c;
49     if (d > ret) ret = d;
50     return (int)round(ret);
51 }
53 __attribute__ ((const))
54 inline static int _min4(const double a, const double b,
55                         const double c, const double d) {
56     double ret = a;
57     if (b < ret) ret = b;
58     if (c < ret) ret = c;
59     if (d < ret) ret = d;
60     return (int)round(ret);
61 }
63 namespace NR {
65 Filter::Filter()
66 {
67     _primitive_count = 0;
68     _primitive_table_size = 1;
69     _primitive = new FilterPrimitive*[1];
70     _primitive[0] = NULL;
71     //_primitive_count = 1;
72     //_primitive[0] = new FilterGaussian;
73     _common_init();
74 }
76 Filter::Filter(int n)
77 {
78     _primitive_count = 0;
79     _primitive_table_size = n;
80     _primitive = new FilterPrimitive*[n];
81     for ( int i = 0 ; i < n ; i++ ) {
82         _primitive[i] = NULL;
83     }
84     _common_init();
85 }
87 void Filter::_common_init() {
88     _slot_count = 1;
89     // Having "not set" here as value means the output of last filter
90     // primitive will be used as output of this filter
91     _output_slot = NR_FILTER_SLOT_NOT_SET;
93     // These are the default values for filter region,
94     // as specified in SVG standard
95     // NB: SVGLength.set takes prescaled percent values: -.10 means -10%
96     _region_x.set(SVGLength::PERCENT, -.10, 0);
97     _region_y.set(SVGLength::PERCENT, -.10, 0);
98     _region_width.set(SVGLength::PERCENT, 1.20, 0);
99     _region_height.set(SVGLength::PERCENT, 1.20, 0);
101     // Filter resolution, negative value here stands for "automatic"
102     _x_pixels = -1.0;
103     _y_pixels = -1.0;
105     _filter_units = SP_FILTER_UNITS_OBJECTBOUNDINGBOX;
106     _primitive_units = SP_FILTER_UNITS_USERSPACEONUSE;
109 Filter::~Filter()
111     clear_primitives();
112     delete[] _primitive;
116 int Filter::render(NRArenaItem const *item, NRPixBlock *pb)
118     if(!_primitive[0]) { // if there are no primitives, do nothing
119        return 0; 
120     }
122     Matrix trans = *item->ctm;
123     Matrix paraller_trans = trans;
124     bool notparaller = false;
125     FilterSlot slot(_slot_count, item);
126     NRPixBlock *in = new NRPixBlock;
128     // If filter effects region is not paraller to viewport,
129     // we must first undo the rotation / shear.
130     // It will be redone after filtering.
131     // If there is only rotation and uniform scaling (zoom), let's skip this,
132     // as it will not make a difference with gaussian blur.
133     if ((fabs(trans[1]) > 1e-6 || fabs(trans[2]) > 1e-6) &&
134         !(fabs(trans[0] - trans[3]) < 1e-6 && fabs(trans[1] + trans[2]) < 1e-6)) {
135         notparaller = true;
137         // TODO: if filter resolution is specified, scaling should be set
138         // according to that
139         double scaling_factor = sqrt(trans.expansionX() * trans.expansionX() +
140                                      trans.expansionY() * trans.expansionY());
141         scale scaling(scaling_factor, scaling_factor);
142         scale scaling_inv(1.0 / scaling_factor, 1.0 / scaling_factor);
143         trans *= scaling_inv;
144         paraller_trans.set_identity();
145         paraller_trans *= scaling;
147         Matrix itrans = trans.inverse();
148         int x0 = pb->area.x0;
149         int y0 = pb->area.y0;
150         int x1 = pb->area.x1;
151         int y1 = pb->area.y1;
152         int min_x = _min4(itrans[0] * x0 + itrans[2] * y0 + itrans[4],
153                           itrans[0] * x0 + itrans[2] * y1 + itrans[4],
154                           itrans[0] * x1 + itrans[2] * y0 + itrans[4],
155                           itrans[0] * x1 + itrans[2] * y1 + itrans[4]);
156         int max_x = _max4(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 min_y = _min4(itrans[1] * x0 + itrans[3] * y0 + itrans[5],
161                           itrans[1] * x0 + itrans[3] * y1 + itrans[5],
162                           itrans[1] * x1 + itrans[3] * y0 + itrans[5],
163                           itrans[1] * x1 + itrans[3] * y1 + itrans[5]);
164         int max_y = _max4(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         
169         nr_pixblock_setup_fast(in, pb->mode,
170                                min_x, min_y,
171                                max_x, max_y, true);
172         if (in->size != NR_PIXBLOCK_SIZE_TINY && in->data.px == NULL) // memory allocation failed
173             return 0;
174         transform_nearest(in, pb, itrans);
175     } else if (_x_pixels >= 0) {
176         // If filter resolution is not set to automatic, we should
177         // scale the input image to correct resolution
178         /* If filter resolution is zero, the object should not be rendered */
179         if (_x_pixels == 0 || _y_pixels == 0) {
180             int size = (pb->area.x1 - pb->area.x0)
181                 * (pb->area.y1 - pb->area.y0)
182                 * NR_PIXBLOCK_BPP(pb);
183             memset(NR_PIXBLOCK_PX(pb), 0, size);
184             return 0;
185         }
186         // Resolution is specified as pixel length of our internal buffer.
187         // Though, we might not be rendering the whole object at time,
188         // so we need to calculate the correct pixel size
189         int x_len = (int)round(((pb->area.x1 - pb->area.x0) * _x_pixels) / (item->bbox.x1 - item->bbox.x0));
190         if (x_len < 1) x_len = 1;
191         // If y-resolution is also set, count y-area in the same way as x-area
192         // Otherwise, make y-area so, that aspect ratio of input pixblock and
193         // internal pixblock are the same.
194         int y_len;
195         if (_y_pixels > 0) {
196             y_len = (int)round(((pb->area.y1 - pb->area.y0) * _y_pixels) / (item->bbox.y1 - item->bbox.y0));
197         } else {
198             y_len = (int)round((x_len * (pb->area.y1 - pb->area.y0)) / (double)(pb->area.x1 - pb->area.x0));
199         }
200         if (y_len < 1) y_len = 1;
201         nr_pixblock_setup_fast(in, pb->mode, 0, 0, x_len, y_len, true);
202         if (in->size != NR_PIXBLOCK_SIZE_TINY && in->data.px == NULL) // memory allocation failed
203             return 0;
204         scale_bicubic(in, pb);
205         scale res_scaling(x_len / (double)(pb->area.x1 - pb->area.x0),
206                           y_len / (double)(pb->area.y1 - pb->area.y0));
207         paraller_trans *= res_scaling;
208     } else {
209         // If filter resolution is automatic, just make copy of input image
210         nr_pixblock_setup_fast(in, pb->mode,
211                                pb->area.x0, pb->area.y0,
212                                pb->area.x1, pb->area.y1, true);
213         if (in->size != NR_PIXBLOCK_SIZE_TINY && in->data.px == NULL) // memory allocation failed
214             return 0;
215         nr_blit_pixblock_pixblock(in, pb);
216     }
217     in->empty = FALSE;
218     slot.set(NR_FILTER_SOURCEGRAPHIC, in);
219     in = NULL; // in is now handled by FilterSlot, we should not touch it
221     for (int i = 0 ; i < _primitive_count ; i++) {
222         _primitive[i]->render(slot, paraller_trans);
223     }
224     NRPixBlock *out = slot.get(_output_slot);
226     // Clear the pixblock, where the output will be put
227     // -> the original image does not show through
228     int size = (pb->area.x1 - pb->area.x0)
229         * (pb->area.y1 - pb->area.y0)
230         * NR_PIXBLOCK_BPP(pb);
231     memset(NR_PIXBLOCK_PX(pb), 0, size);
233     if (notparaller) {
234         transform_nearest(pb, out, trans);
235     } else if (_x_pixels < 0) {
236         // If the filter resolution is automatic, just copy our final image
237         // to output pixblock, otherwise use bicubic scaling
238         nr_blit_pixblock_pixblock(pb, out);
239     } else {
240         scale_bicubic(pb, out);
241     }
243     // Take note of the amount of used image slots
244     // -> next time this filter is rendered, we can reserve enough slots
245     // immediately
246     _slot_count = slot.get_slot_count();
247     return 0;
250 void Filter::area_enlarge(NRRectL &bbox, Matrix const &m) {
251     for (int i = 0 ; i < _primitive_count ; i++) {
252         if (_primitive[i]) _primitive[i]->area_enlarge(bbox, m);
253     }
256 void Filter::bbox_enlarge(NRRectL &bbox)
258     int len_x = bbox.x1 - bbox.x0;
259     int len_y = bbox.y1 - bbox.y0;
260     /* TODO: fetch somehow the object ex and em lengths */
261     _region_x.update(12, 6, len_x);
262     _region_y.update(12, 6, len_y);
263     _region_width.update(12, 6, len_x);
264     _region_height.update(12, 6, len_y);
265     if (_filter_units == SP_FILTER_UNITS_OBJECTBOUNDINGBOX) {
266         if (_region_x.unit == SVGLength::PERCENT) {
267             bbox.x0 += (ICoord)_region_x.computed;
268         } else {
269             bbox.x0 += (ICoord)(_region_x.computed * len_x);
270         }
271         if (_region_width.unit == SVGLength::PERCENT) {
272             bbox.x1 = bbox.x0 + (ICoord)_region_width.computed;
273         } else {
274             bbox.x1 = bbox.x0 + (ICoord)(_region_width.computed * len_x);
275         }
277         if (_region_y.unit == SVGLength::PERCENT) {
278             bbox.y0 += (ICoord)_region_y.computed;
279         } else {
280             bbox.y0 += (ICoord)(_region_y.computed * len_y);
281         }
282         if (_region_height.unit == SVGLength::PERCENT) {
283             bbox.y1 = bbox.y0 + (ICoord)_region_height.computed;
284         } else {
285             bbox.y1 = bbox.y0 + (ICoord)(_region_height.computed * len_y);
286         }
287     } else if (_filter_units == SP_FILTER_UNITS_USERSPACEONUSE) {
288         /* TODO: make sure bbox and fe region are in same coordinate system */
289         bbox.x0 = (ICoord) _region_x.computed;
290         bbox.x1 = bbox.x0 + (ICoord) _region_width.computed;
291         bbox.y0 = (ICoord) _region_y.computed;
292         bbox.y1 = bbox.y0 + (ICoord) _region_height.computed;
293     } else {
294         g_warning("Error in NR::Filter::bbox_enlarge: unrecognized value of _filter_units");
295     }
298 /* Constructor table holds pointers to static methods returning filter
299  * primitives. This table is indexed with FilterPrimitiveType, so that
300  * for example method in _constructor[NR_FILTER_GAUSSIANBLUR]
301  * returns a filter object of type NR::FilterGaussian.
302  */
303 typedef FilterPrimitive*(*FilterConstructor)();
304 static FilterConstructor _constructor[NR_FILTER_ENDPRIMITIVETYPE];
306 void Filter::_create_constructor_table()
308     // Constructor table won't change in run-time, so no need to recreate
309     static bool created = false;
310     if(created) return;
312     /* Filter effects not yet implemented are set to NULL */
313     _constructor[NR_FILTER_BLEND] = &FilterBlend::create;
314     _constructor[NR_FILTER_COLORMATRIX] = NULL;
315     _constructor[NR_FILTER_COMPONENTTRANSFER] = NULL;
316     _constructor[NR_FILTER_COMPOSITE] = &FilterComposite::create;
317     _constructor[NR_FILTER_CONVOLVEMATRIX] = NULL;
318     _constructor[NR_FILTER_DIFFUSELIGHTING] = &FilterDiffuseLighting::create;
319     _constructor[NR_FILTER_DISPLACEMENTMAP] = NULL;
320     _constructor[NR_FILTER_FLOOD] = NULL;
321     _constructor[NR_FILTER_GAUSSIANBLUR] = &FilterGaussian::create;
322     _constructor[NR_FILTER_IMAGE] = NULL;
323     _constructor[NR_FILTER_MERGE] = NULL;
324     _constructor[NR_FILTER_MORPHOLOGY] = NULL;
325     _constructor[NR_FILTER_OFFSET] = &FilterOffset::create;
326     _constructor[NR_FILTER_SPECULARLIGHTING] = &FilterSpecularLighting::create;
327     _constructor[NR_FILTER_TILE] = NULL;
328     _constructor[NR_FILTER_TURBULENCE] = NULL;
329     created = true;
332 /** Helper method for enlarging table of filter primitives. When new
333  * primitives are added, but we have no space for them, this function
334  * makes some more space.
335  */
336 void Filter::_enlarge_primitive_table() {
337     FilterPrimitive **new_tbl = new FilterPrimitive*[_primitive_table_size * 2];
338     for (int i = 0 ; i < _primitive_count ; i++) {
339         new_tbl[i] = _primitive[i];
340     }
341     _primitive_table_size *= 2;
342     for (int i = _primitive_count ; i < _primitive_table_size ; i++) {
343         new_tbl[i] = NULL;
344     }
345     delete[] _primitive;
346     _primitive = new_tbl;
349 int Filter::add_primitive(FilterPrimitiveType type)
351     _create_constructor_table();
353     // Check that we can create a new filter of specified type
354     if (type < 0 || type >= NR_FILTER_ENDPRIMITIVETYPE)
355         return -1;
356     if (!_constructor[type]) return -1;
357     FilterPrimitive *created = _constructor[type]();
359     // If there is no space for new filter primitive, enlarge the table
360     if (_primitive_count >= _primitive_table_size) {
361         _enlarge_primitive_table();
362     }
364     _primitive[_primitive_count] = created;
365     int handle = _primitive_count;
366     _primitive_count++;
367     return handle;
370 int Filter::replace_primitive(int target, FilterPrimitiveType type)
372     _create_constructor_table();
374     // Check that target is valid primitive inside this filter
375     if (target < 0) return -1;
376     if (target >= _primitive_count) return -1;
377     if (!_primitive[target]) return -1;
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     delete _primitive[target];
391     _primitive[target] = created;
392     return target;
395 FilterPrimitive *Filter::get_primitive(int handle) {
396     if (handle < 0 || handle >= _primitive_count) return NULL;
397     return _primitive[handle];
400 void Filter::clear_primitives()
402     for (int i = 0 ; i < _primitive_count ; i++) {
403         if (_primitive[i]) delete _primitive[i];
404     }
405     _primitive_count = 0;
408 void Filter::set_x(SVGLength &length)
409
410   if (length._set)
411       _region_x = length;
413 void Filter::set_y(SVGLength &length)
415   if (length._set)
416       _region_y = length;
418 void Filter::set_width(SVGLength &length)
420   if (length._set)
421       _region_width = length;
423 void Filter::set_height(SVGLength &length)
424
425   if (length._set)
426       _region_height = length;
429 } /* namespace NR */
431 /*
432   Local Variables:
433   mode:c++
434   c-file-style:"stroustrup"
435   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
436   indent-tabs-mode:nil
437   fill-column:99
438   End:
439 */
440 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :