Code

From trunk
[inkscape.git] / src / live_effects / lpe-sketch.cpp
1 #define INKSCAPE_LPE_SKETCH_CPP
2 /** \file
3  * LPE <sketch> implementation
4  */
5 /*
6  * Authors:
7  *   Johan Engelen
8 *
9 * Copyright (C) Johan Engelen 2007 <j.b.c.engelen@utwente.nl>
10  *
11  * Released under GNU GPL, read the file 'COPYING' for more information
12  */
14 #include "live_effects/lpe-sketch.h"
16 // You might need to include other 2geom files. You can add them here:
17 #include <2geom/path.h>
18 #include <2geom/sbasis.h>
19 #include <2geom/sbasis-geometric.h>
20 #include <2geom/bezier-to-sbasis.h>
21 #include <2geom/sbasis-to-bezier.h>
22 #include <2geom/d2.h>
23 #include <2geom/sbasis-math.h>
24 #include <2geom/piecewise.h>
25 #include <2geom/crossing.h>
26 #include <2geom/path-intersection.h>
28 namespace Inkscape {
29 namespace LivePathEffect {
31 LPESketch::LPESketch(LivePathEffectObject *lpeobject) :
32     Effect(lpeobject),
33     // initialise your parameters here:
34     //testpointA(_("Test Point A"), _("Test A"), "ptA", &wr, this, Geom::Point(100,100)),
35     nbiter_approxstrokes(_("Strokes"), _("Draw that many approximating strokes"), "nbiter_approxstrokes", &wr, this, 5),
36     strokelength(_("Max stroke length"), 
37                  _("Maximum length of approximating strokes"), "strokelength", &wr, this, 100.),
38     strokelength_rdm(_("Stroke length variation"), 
39                      _("Random variation of stroke length (relative to maximum length)"), "strokelength_rdm", &wr, this, .3),
40     strokeoverlap(_("Max. overlap"), 
41                   _("How much successive strokes should overlap (relative to maximum length)"), "strokeoverlap", &wr, this, .3),
42     strokeoverlap_rdm(_("Overlap variation"), 
43                       _("Random variation of overlap (relative to maximum overlap)"), "strokeoverlap_rdm", &wr, this, .3),
44     ends_tolerance(_("Max. end tolerance"), 
45                    _("Maximum distance between ends of original and approximating paths (relative to maximum length)"), "ends_tolerance", &wr, this, .1),
46     parallel_offset(_("Parallel offset"), 
47                     _("Average distance from approximating path to original path"), "parallel_offset", &wr, this, 5.),
48     tremble_size(_("Max. tremble"), 
49                  _("Maximum tremble magnitude"), "tremble_size", &wr, this, 5.),
50     tremble_frequency(_("Tremble frequency"), 
51                       _("Average number of tremble periods in an approximating stroke"), "tremble_frequency", &wr, this, 1.),
52     nbtangents(_("Construction lines"), 
53                _("How many construction lines (tangents) to draw"), "nbtangents", &wr, this, 5),
54     tgtscale(_("Scale"), 
55              _("Scale factor relating curvature and length of construction lines (try 5*offset)"), "tgtscale", &wr, this, 10.0),
56     tgtlength(_("Max. length"), _("Maximum length of construction lines"), "tgtlength", &wr, this, 100.0),
57     tgtlength_rdm(_("Length variation"), _("Random variation of the length of construction lines"), "tgtlength_rdm", &wr, this, .3)
58 {
59     // register all your parameters here, so Inkscape knows which parameters this effect has:
60     //Add some comment in the UI:  *warning* the precise output of this effect might change in future releases!
61     //convert to path if you want to keep exact output unchanged in future releases...
62     //registerParameter( dynamic_cast<Parameter *>(&testpointA) );
63     registerParameter( dynamic_cast<Parameter *>(&nbiter_approxstrokes) );
64     registerParameter( dynamic_cast<Parameter *>(&strokelength) );
65     registerParameter( dynamic_cast<Parameter *>(&strokelength_rdm) );
66     registerParameter( dynamic_cast<Parameter *>(&strokeoverlap) );
67     registerParameter( dynamic_cast<Parameter *>(&strokeoverlap_rdm) );
68     registerParameter( dynamic_cast<Parameter *>(&ends_tolerance) );
69     registerParameter( dynamic_cast<Parameter *>(&parallel_offset) );
70     registerParameter( dynamic_cast<Parameter *>(&tremble_size) );
71     registerParameter( dynamic_cast<Parameter *>(&tremble_frequency) );
72     registerParameter( dynamic_cast<Parameter *>(&nbtangents) );
73     registerParameter( dynamic_cast<Parameter *>(&tgtscale) );
74     registerParameter( dynamic_cast<Parameter *>(&tgtlength) );
75     registerParameter( dynamic_cast<Parameter *>(&tgtlength_rdm) );
78     nbiter_approxstrokes.param_make_integer();
79     nbiter_approxstrokes.param_set_range(0, NR_HUGE);
80     strokelength.param_set_range(1, NR_HUGE);
81     strokelength.param_set_increments(1., 5.);
82     strokelength_rdm.param_set_range(0, 1.);
83     strokeoverlap.param_set_range(0, 1.);
84     strokeoverlap.param_set_increments(0.1, 0.30);
85     ends_tolerance.param_set_range(0., 1.);
86     parallel_offset.param_set_range(0, NR_HUGE);
87     tremble_frequency.param_set_range(0.01, 100.);
88     tremble_frequency.param_set_increments(.5, 1.5);
89     strokeoverlap_rdm.param_set_range(0, 1.);
91     nbtangents.param_make_integer();
92     nbtangents.param_set_range(0, NR_HUGE);
93     tgtscale.param_set_range(0, NR_HUGE);
94     tgtscale.param_set_increments(.1, .5);
95     tgtlength.param_set_range(0, NR_HUGE);
96     tgtlength.param_set_increments(1., 5.);
97     tgtlength_rdm.param_set_range(0, 1.);
98 }
100 LPESketch::~LPESketch()
105 /*
106 Geom::Piecewise<Geom::D2<Geom::SBasis> >
107 addLinearEnds (Geom::Piecewise<Geom::D2<Geom::SBasis> > & m){
108     using namespace Geom;
109     Piecewise<D2<SBasis> > output;
110     Piecewise<D2<SBasis> > start;
111     Piecewise<D2<SBasis> > end;
112     double x,y,vx,vy;
114     x  = m.segs.front()[0].at0();
115     y  = m.segs.front()[1].at0();
116     vx = m.segs.front()[0][1][0]+Tri(m.segs.front()[0][0]);
117     vy = m.segs.front()[1][1][0]+Tri(m.segs.front()[1][0]);
118     start = Piecewise<D2<SBasis> >(D2<SBasis>(Linear (x-vx,x),Linear (y-vy,y)));
119     start.offsetDomain(m.cuts.front()-1.);
121     x  = m.segs.back()[0].at1();
122     y  = m.segs.back()[1].at1();
123     vx = -m.segs.back()[0][1][1]+Tri(m.segs.back()[0][0]);;
124     vy = -m.segs.back()[1][1][1]+Tri(m.segs.back()[1][0]);;
125     end = Piecewise<D2<SBasis> >(D2<SBasis>(Linear (x,x+vx),Linear (y,y+vy)));
126     //end.offsetDomain(m.cuts.back());
128     output = start;
129     output.concat(m);
130     output.concat(end);
131     return output;
133 */
137 //This returns a random perturbation. Notice the domain is [s0,s0+first multiple of period>s1]...
138 Geom::Piecewise<Geom::D2<Geom::SBasis> > 
139 LPESketch::computePerturbation (double s0, double s1){
140     using namespace Geom;
141     Piecewise<D2<SBasis> >res;
142     
143     //global offset for this stroke.
144     double offsetX = parallel_offset-parallel_offset.get_value();
145     double offsetY = parallel_offset-parallel_offset.get_value();
146     Point A,dA,B,dB,offset = Point(offsetX,offsetY);
147     //start point A
148     for (unsigned dim=0; dim<2; dim++){
149         A[dim]  = offset[dim] + 2*tremble_size-tremble_size.get_value();
150         dA[dim] = 2*tremble_size-tremble_size.get_value();
151     }
152     //compute howmany deg 3 sbasis to concat according to frequency.
153     unsigned count = unsigned((s1-s0)/strokelength*tremble_frequency)+1; 
154     for (unsigned i=0; i<count; i++){
155         D2<SBasis> perturb = D2<SBasis>();
156         for (unsigned dim=0; dim<2; dim++){
157             B[dim] = offset[dim] + 2*tremble_size-tremble_size.get_value();
158             perturb[dim].push_back(Linear(A[dim],B[dim]));
159             dA[dim] = dA[dim]-B[dim]+A[dim];
160             dB[dim] = 2*tremble_size-tremble_size.get_value();
161             perturb[dim].push_back(Linear(dA[dim],dB[dim]));
162         }
163         A = B;
164         dA = B-A-dB;
165         res.concat(Piecewise<D2<SBasis> >(perturb));
166     }
167     res.setDomain(Interval(s0,s0+count*strokelength/tremble_frequency));
168     return res;
172 // Main effect body...
173 Geom::Piecewise<Geom::D2<Geom::SBasis> >
174 LPESketch::doEffect_pwd2 (Geom::Piecewise<Geom::D2<Geom::SBasis> > const & pwd2_in)
176     using namespace Geom;
177     //If the input path is empty, do nothing.
178     //Note: this happens when duplicating a 3d box... dunno why.
179     if (pwd2_in.size()==0) return pwd2_in;
181     Piecewise<D2<SBasis> > output;
183     // some variables for futur use (for construction lines; compute arclength only once...)
184     // notations will be : t = path time, s = distance from start along the path.
185     Piecewise<SBasis> pathlength;
186     double total_length = 0;
188     //TODO: split Construction Lines/Approximated Strokes into two separate effects?
190     //----- Approximated Strokes.
191     std::vector<Piecewise<D2<SBasis> > > pieces_in = split_at_discontinuities (pwd2_in);
193     //work separately on each component.
194     for (unsigned pieceidx = 0; pieceidx < pieces_in.size(); pieceidx++){
196         Piecewise<D2<SBasis> > piece = pieces_in[pieceidx];
197         Piecewise<SBasis> piecelength = arcLengthSb(piece,.1);
198         double piece_total_length = piecelength.segs.back().at1()-piecelength.segs.front().at0();
199         pathlength.concat(piecelength + total_length);
200         total_length += piece_total_length;
201         
203         //TODO: better check this on the Geom::Path.
204         bool closed = piece.segs.front().at0() == piece.segs.back().at1(); 
205         if (closed){ 
206             piece.concat(piece);
207             piecelength.concat(piecelength+piece_total_length);
208         }
210         for (unsigned i = 0; i<nbiter_approxstrokes; i++){
211             //Basic steps: 
212             //- Choose a rdm seg [s0,s1], find coresponding [t0,t1], 
213             //- Pick a rdm perturbation delta(s), collect 'piece(t)+delta(s(t))' over [t0,t1] into output.
215             // pick a point where to start the stroke (s0 = dist from start).
216             double s1=0.,s0 = ends_tolerance*strokelength+0.0001;//the root finder might miss 0.  
217             double t1, t0;
218             double s0_initial = s0;
219             bool done = false;// was the end of the component reached?
221             while (!done){
222                 // if the start point is already too far... do nothing. (this should not happen!)
223                 if (!closed && s1>piece_total_length - ends_tolerance.get_value()*strokelength) break;
224                 if ( closed && s0>piece_total_length + s0_initial) break;
226                 std::vector<double> times;  
227                 times = roots(piecelength-s0);  
228                 t0 = times.at(0);//there should be one and only one solution!!
229                 
230                 // pick a new end point (s1 = s0 + strokelength).
231                 s1 = s0 + strokelength*(1-strokelength_rdm);
232                 // don't let it go beyond the end of the orgiginal path.
233                 // TODO/FIXME: this might result in short strokes near the end...
234                 if (!closed && s1>piece_total_length-ends_tolerance.get_value()*strokelength){
235                     done = true;
236                     //!!the root solver might miss s1==piece_total_length...
237                     if (s1>piece_total_length){s1 = piece_total_length - ends_tolerance*strokelength-0.0001;}
238                 }
239                 if (closed && s1>piece_total_length + s0_initial){
240                     done = true;
241                     if (closed && s1>2*piece_total_length){
242                         s1 = 2*piece_total_length - strokeoverlap*(1-strokeoverlap_rdm)*strokelength-0.0001;
243                     }
244                 }
245                 times = roots(piecelength-s1);  
246                 if (times.size()==0) break;//we should not be there.
247                 t1 = times[0];
248                 
249                 //pick a rdm perturbation, and collect the perturbed piece into output.
250                 Piecewise<D2<SBasis> > pwperturb = computePerturbation(s0,s1);
251                 pwperturb = compose(pwperturb,portion(piecelength,t0,t1));
252                 output.concat(portion(piece,t0,t1)+pwperturb);
253                 
254                 //step points: s0 = s1 - overlap.
255                 //TODO: make sure this has to end?
256                 s0 = s1 - strokeoverlap*(1-strokeoverlap_rdm)*(s1-s0);
257             }
258         }
259     }
262     //----- Construction lines.
263     //TODO: choose places according to curvature?.
265     //at this point we should have:
266     //pathlength = arcLengthSb(pwd2_in,.1);
267     //total_length = pathlength.segs.back().at1()-pathlength.segs.front().at0();
268     Piecewise<D2<SBasis> > m = pwd2_in;
269     Piecewise<D2<SBasis> > v = derivative(pwd2_in);
270     Piecewise<D2<SBasis> > a = derivative(v);
271     for (unsigned i=0; i<nbtangents; i++){
272         // pick a point where to draw a tangent (s = dist from start along path).
273         double s = total_length * ( i + tgtlength_rdm ) / (nbtangents+1.);
274         std::vector<double> times;  
275         times = roots(pathlength-s);
276         double t = times.at(0);//there should be one and only one solution!
277         Point m_t = m(t), v_t = v(t), a_t = a(t);
278         //Compute tgt length according to curvature (not exceeding tgtlength) so that  
279         //  dist to origninal curve ~ 4 * (parallel_offset+tremble_size).
280         //TODO: put this 4 as a parameter in the UI...
281         //TODO: what if with v=0?
282         double l = tgtlength*(1-tgtlength_rdm)/v_t.length();
283         double r = pow(v_t.length(),3)/cross(a_t,v_t);
284         r = sqrt((2*fabs(r)-tgtscale)*tgtscale)/v_t.length();
285         l=(r<l)?r:l;
286         //collect the tgt segment into output.
287         D2<SBasis> tgt = D2<SBasis>();
288         for (unsigned dim=0; dim<2; dim++){
289             tgt[dim] = SBasis(Linear(m_t[dim]-v_t[dim]*l, m_t[dim]+v_t[dim]*l));
290         }
291         output.concat(Piecewise<D2<SBasis> >(tgt));
292     }
293     return output;
296 void
297 LPESketch::doBeforeEffect (SPLPEItem *lpeitem)
299     //init random parameters.
300     parallel_offset.resetRandomizer();
301     strokelength_rdm.resetRandomizer();
302     strokeoverlap_rdm.resetRandomizer();
303     ends_tolerance.resetRandomizer();
304     tremble_size.resetRandomizer();
305     tgtlength_rdm.resetRandomizer();
308 /* ######################## */
310 } //namespace LivePathEffect (setq default-directory "c:/Documents And Settings/jf/Mes Documents/InkscapeSVN")
311 } /* namespace Inkscape */
313 /*
314   Local Variables:
315   mode:c++
316   c-file-style:"stroustrup"
317   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
318   indent-tabs-mode:nil
319   fill-column:99
320   End:
321 */
322 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :