Code

remove 2geom transition code
[inkscape.git] / src / pencil-context.cpp
1 /** \file
2  * Pencil event context implementation.
3  */
5 /*
6  * Authors:
7  *   Lauris Kaplinski <lauris@kaplinski.com>
8  *   bulia byak <buliabyak@users.sf.net>
9  *
10  * Copyright (C) 2000 Lauris Kaplinski
11  * Copyright (C) 2000-2001 Ximian, Inc.
12  * Copyright (C) 2002 Lauris Kaplinski
13  * Copyright (C) 2004 Monash University
14  *
15  * Released under GNU GPL, read the file 'COPYING' for more information
16  */
18 #include <gdk/gdkkeysyms.h>
20 #include "pencil-context.h"
21 #include "desktop.h"
22 #include "desktop-handles.h"
23 #include "selection.h"
24 #include "selection-chemistry.h"
25 #include "draw-anchor.h"
26 #include "message-stack.h"
27 #include "message-context.h"
28 #include "modifier-fns.h"
29 #include "sp-path.h"
30 #include "preferences.h"
31 #include "snap.h"
32 #include "pixmaps/cursor-pencil.xpm"
33 #include <2geom/sbasis-to-bezier.h>
34 #include <2geom/bezier-utils.h>
35 #include "display/canvas-bpath.h"
36 #include <glibmm/i18n.h>
37 #include "libnr/in-svg-plane.h"
38 #include "context-fns.h"
39 #include "sp-namedview.h"
40 #include "xml/repr.h"
41 #include "document.h"
42 #include "desktop-style.h"
43 #include "macros.h"
44 #include "display/curve.h"
46 static void sp_pencil_context_class_init(SPPencilContextClass *klass);
47 static void sp_pencil_context_init(SPPencilContext *pc);
48 static void sp_pencil_context_setup(SPEventContext *ec);
49 static void sp_pencil_context_dispose(GObject *object);
51 static gint sp_pencil_context_root_handler(SPEventContext *event_context, GdkEvent *event);
52 static gint pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent);
53 static gint pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent);
54 static gint pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent);
55 static gint pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state);
56 static gint pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const state);
58 static void spdc_set_startpoint(SPPencilContext *pc, Geom::Point const p);
59 static void spdc_set_endpoint(SPPencilContext *pc, Geom::Point const p);
60 static void spdc_finish_endpoint(SPPencilContext *pc);
61 static void spdc_add_freehand_point(SPPencilContext *pc, Geom::Point p, guint state);
62 static void fit_and_split(SPPencilContext *pc);
63 static void interpolate(SPPencilContext *pc);
64 static void sketch_interpolate(SPPencilContext *pc);
66 static SPDrawContextClass *pencil_parent_class;
67 static Geom::Point pencil_drag_origin_w(0, 0);
68 static bool pencil_within_tolerance = false;
70 /**
71  * Register SPPencilContext class with Gdk and return its type number.
72  */
73 GType
74 sp_pencil_context_get_type()
75 {
76     static GType type = 0;
77     if (!type) {
78         GTypeInfo info = {
79             sizeof(SPPencilContextClass),
80             NULL, NULL,
81             (GClassInitFunc) sp_pencil_context_class_init,
82             NULL, NULL,
83             sizeof(SPPencilContext),
84             4,
85             (GInstanceInitFunc) sp_pencil_context_init,
86             NULL,   /* value_table */
87         };
88         type = g_type_register_static(SP_TYPE_DRAW_CONTEXT, "SPPencilContext", &info, (GTypeFlags)0);
89     }
90     return type;
91 }
93 /**
94  * Initialize SPPencilContext vtable.
95  */
96 static void
97 sp_pencil_context_class_init(SPPencilContextClass *klass)
98 {
99     GObjectClass *object_class;
100     SPEventContextClass *event_context_class;
102     object_class = (GObjectClass *) klass;
103     event_context_class = (SPEventContextClass *) klass;
105     pencil_parent_class = (SPDrawContextClass*)g_type_class_peek_parent(klass);
107     object_class->dispose = sp_pencil_context_dispose;
109     event_context_class->setup = sp_pencil_context_setup;
110     event_context_class->root_handler = sp_pencil_context_root_handler;
113 /**
114  * Callback to initialize SPPencilContext object.
115  */
116 static void
117 sp_pencil_context_init(SPPencilContext *pc)
119     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
121     event_context->cursor_shape = cursor_pencil_xpm;
122     event_context->hot_x = 4;
123     event_context->hot_y = 4;
125     pc->npoints = 0;
126     pc->state = SP_PENCIL_CONTEXT_IDLE;
127     pc->req_tangent = Geom::Point(0, 0);
129     // since SPPencilContext is not properly constructed...
130     pc->sketch_interpolation = Geom::Piecewise<Geom::D2<Geom::SBasis> >();
131     pc->sketch_n = 0;
134 /**
135  * Callback to setup SPPencilContext object.
136  */
137 static void
138 sp_pencil_context_setup(SPEventContext *ec)
140     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
141     if (prefs->getBool("/tools/freehand/pencil/selcue")) {
142         ec->enableSelectionCue();
143     }
145     if (((SPEventContextClass *) pencil_parent_class)->setup) {
146         ((SPEventContextClass *) pencil_parent_class)->setup(ec);
147     }
149     SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
150     pc->is_drawing = false;
152     pc->anchor_statusbar = false;
155 static void
156 sp_pencil_context_dispose(GObject *object)
158     G_OBJECT_CLASS(pencil_parent_class)->dispose(object);
161 /** Snaps new node relative to the previous node. */
162 static void
163 spdc_endpoint_snap(SPPencilContext const *pc, Geom::Point &p, guint const state)
165     if ((state & GDK_CONTROL_MASK)) { //CTRL enables constrained snapping
166         spdc_endpoint_snap_rotation(pc, p, pc->p[0], state);
167     } else {
168         if (!(state & GDK_SHIFT_MASK)) { //SHIFT disables all snapping, except the angular snapping above
169                                          //After all, the user explicitely asked for angular snapping by
170                                          //pressing CTRL
171             spdc_endpoint_snap_free(pc, p, state);
172         }
173     }
176 /**
177  * Callback for handling all pencil context events.
178  */
179 gint
180 sp_pencil_context_root_handler(SPEventContext *const ec, GdkEvent *event)
182     SPPencilContext *const pc = SP_PENCIL_CONTEXT(ec);
184     gint ret = FALSE;
186     switch (event->type) {
187         case GDK_BUTTON_PRESS:
188             ret = pencil_handle_button_press(pc, event->button);
189             break;
191         case GDK_MOTION_NOTIFY:
192             ret = pencil_handle_motion_notify(pc, event->motion);
193             break;
195         case GDK_BUTTON_RELEASE:
196             ret = pencil_handle_button_release(pc, event->button);
197             break;
199         case GDK_KEY_PRESS:
200             ret = pencil_handle_key_press(pc, get_group0_keyval (&event->key), event->key.state);
201             break;
203         case GDK_KEY_RELEASE:
204             ret = pencil_handle_key_release(pc, get_group0_keyval (&event->key), event->key.state);
205             break;
207         default:
208             break;
209     }
211     if (!ret) {
212         gint (*const parent_root_handler)(SPEventContext *, GdkEvent *)
213             = ((SPEventContextClass *) pencil_parent_class)->root_handler;
214         if (parent_root_handler) {
215             ret = parent_root_handler(ec, event);
216         }
217     }
219     return ret;
222 static gint
223 pencil_handle_button_press(SPPencilContext *const pc, GdkEventButton const &bevent)
225     gint ret = FALSE;
226     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
227     if ( bevent.button == 1  && !event_context->space_panning) {
229         SPDrawContext *dc = SP_DRAW_CONTEXT (pc);
230         SPDesktop *desktop = SP_EVENT_CONTEXT_DESKTOP(dc);
231         Inkscape::Selection *selection = sp_desktop_selection(desktop);
233         if (Inkscape::have_viable_layer(desktop, dc->_message_context) == false) {
234             return TRUE;
235         }
237         Geom::Point const button_w(bevent.x, bevent.y);
239         /* Find desktop coordinates */
240         Geom::Point p = pc->desktop->w2d(button_w);
242         /* Test whether we hit any anchor. */
243         SPDrawAnchor *anchor = spdc_test_inside(pc, button_w);
245         pencil_drag_origin_w = Geom::Point(bevent.x,bevent.y);
246         pencil_within_tolerance = true;
248         switch (pc->state) {
249             case SP_PENCIL_CONTEXT_ADDLINE:
250                 /* Current segment will be finished with release */
251                 ret = TRUE;
252                 break;
253             default:
254                 /* Set first point of sequence */
255                 if (bevent.state & GDK_CONTROL_MASK) {
256                     spdc_create_single_dot(event_context, p, "/tools/freehand/pencil", bevent.state);
257                     ret = true;
258                     break;
259                 }
260                 if (anchor) {
261                     p = anchor->dp;
262                     desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Continuing selected path"));
263                 } else {
265                     if (!(bevent.state & GDK_SHIFT_MASK)) {
267                         // This is the first click of a new curve; deselect item so that
268                         // this curve is not combined with it (unless it is drawn from its
269                         // anchor, which is handled by the sibling branch above)
270                         selection->clear();
271                         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Creating new path"));
272                         SnapManager &m = desktop->namedview->snap_manager;
273                         m.setup(desktop);
274                         Inkscape::SnappedPoint const s = m.freeSnap(Inkscape::SnapPreferences::SNAPPOINT_NODE, p);
275                         if (s.getSnapped()) {
276                                 s.getPoint(p);
277                                 pc->prev_snap_was_succesful = true;
278                         } else {
279                                 pc->prev_snap_was_succesful = false;
280                         }
281                     } else if (selection->singleItem() && SP_IS_PATH(selection->singleItem())) {
282                         desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Appending to selected path"));
283                     }
284                 }
285                 pc->sa = anchor;
286                 spdc_set_startpoint(pc, p);
287                 ret = TRUE;
288                 break;
289         }
291         pc->is_drawing = true;
292     }
293     return ret;
296 static gint
297 pencil_handle_motion_notify(SPPencilContext *const pc, GdkEventMotion const &mevent)
299     if ((mevent.state & GDK_CONTROL_MASK) && (mevent.state & GDK_BUTTON1_MASK)) {
300         // mouse was accidentally moved during Ctrl+click;
301         // ignore the motion and create a single point
302         pc->is_drawing = false;
303         return TRUE;
304     }
305     gint ret = FALSE;
306     SPDesktop *const dt = pc->desktop;
308     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
309     if (event_context->space_panning || mevent.state & GDK_BUTTON2_MASK || mevent.state & GDK_BUTTON3_MASK) {
310         // allow scrolling
311         return FALSE;
312     }
314     if ( ( mevent.state & GDK_BUTTON1_MASK ) && !pc->grab && pc->is_drawing) {
315         /* Grab mouse, so release will not pass unnoticed */
316         pc->grab = SP_CANVAS_ITEM(dt->acetate);
317         sp_canvas_item_grab(pc->grab, ( GDK_KEY_PRESS_MASK | GDK_BUTTON_PRESS_MASK   |
318                                         GDK_BUTTON_RELEASE_MASK |
319                                         GDK_POINTER_MOTION_MASK  ),
320                             NULL, mevent.time);
321     }
323     /* Find desktop coordinates */
324     Geom::Point p = dt->w2d(Geom::Point(mevent.x, mevent.y));
326     /* Test whether we hit any anchor. */
327     SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(mevent.x, mevent.y));
329     if (pencil_within_tolerance) {
330         Inkscape::Preferences *prefs = Inkscape::Preferences::get();
331         gint const tolerance = prefs->getIntLimited("/options/dragtolerance/value", 0, 0, 100);
332         if ( Geom::LInfty( Geom::Point(mevent.x,mevent.y) - pencil_drag_origin_w ) < tolerance ) {
333             return FALSE;   // Do not drag if we're within tolerance from origin.
334         }
335     }
337     // Once the user has moved farther than tolerance from the original location
338     // (indicating they intend to move the object, not click), then always process the
339     // motion notify coordinates as given (no snapping back to origin)
340     pencil_within_tolerance = false;
342     switch (pc->state) {
343         case SP_PENCIL_CONTEXT_ADDLINE:
344             /* Set red endpoint */
345             if (anchor) {
346                 p = anchor->dp;
347             } else {
348                 Geom::Point ptnr(p);
349                 spdc_endpoint_snap(pc, ptnr, mevent.state);
350                 p = ptnr;
351             }
352             spdc_set_endpoint(pc, p);
353             ret = TRUE;
354             break;
355         default:
356             /* We may be idle or already freehand */
357             if ( mevent.state & GDK_BUTTON1_MASK && pc->is_drawing ) {
358                 pc->state = SP_PENCIL_CONTEXT_FREEHAND;
359                 if ( !pc->sa && !pc->green_anchor ) {
360                     /* Create green anchor */
361                     pc->green_anchor = sp_draw_anchor_new(pc, pc->green_curve, TRUE, pc->p[0]);
362                 }
363                 /** \todo
364                  * fixme: I am not sure whether we want to snap to anchors
365                  * in middle of freehand (Lauris)
366                  */
367                 SnapManager &m = dt->namedview->snap_manager;
368                 
369                 if (anchor) {
370                     p = anchor->dp;
371                 } else if ((mevent.state & GDK_SHIFT_MASK) == 0) {
372                     m.setup(dt);
373                     Inkscape::SnappedPoint const s = m.freeSnap(Inkscape::SnapPreferences::SNAPPOINT_NODE, p);
374                     if (s.getSnapped()) {
375                         s.getPoint(p);
376                         pc->prev_snap_was_succesful = true;
377                     } else {
378                         pc->prev_snap_was_succesful = false;
379                     }
380                 }
381                 if ( pc->npoints != 0) { // buttonpress may have happened before we entered draw context!
382                         if (!(pc->prev_snap_was_succesful && m.snapprefs.getSnapPostponedGlobally())) {
383                             // When snapping is enabled but temporarily on hold because the mouse is moving 
384                         // fast, then we don't want to add nodes off-grid
385                         spdc_add_freehand_point(pc, p, mevent.state);
386                             ret = TRUE;
387                         }
388                 }
390                 if (anchor && !pc->anchor_statusbar) {
391                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Release</b> here to close and finish the path."));
392                     pc->anchor_statusbar = true;
393                 } else if (!anchor && pc->anchor_statusbar) {
394                     pc->_message_context->clear();
395                     pc->anchor_statusbar = false;
396                 } else if (!anchor) {
397                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("Drawing a freehand path"));
398                 }
400             } else {
401                 if (anchor && !pc->anchor_statusbar) {
402                     pc->_message_context->set(Inkscape::NORMAL_MESSAGE, _("<b>Drag</b> to continue the path from this point."));
403                     pc->anchor_statusbar = true;
404                 } else if (!anchor && pc->anchor_statusbar) {
405                     pc->_message_context->clear();
406                     pc->anchor_statusbar = false;
407                 }
408             }
409             break;
410     }
411     return ret;
414 static gint
415 pencil_handle_button_release(SPPencilContext *const pc, GdkEventButton const &revent)
417     gint ret = FALSE;
419     SPEventContext *event_context = SP_EVENT_CONTEXT(pc);
420     if ( revent.button == 1 && pc->is_drawing && !event_context->space_panning) {
421         SPDesktop *const dt = pc->desktop;
423         pc->is_drawing = false;
425         /* Find desktop coordinates */
426         Geom::Point p = dt->w2d(Geom::Point(revent.x, revent.y));
428         /* Test whether we hit any anchor. */
429         SPDrawAnchor *anchor = spdc_test_inside(pc, Geom::Point(revent.x,
430                                                               revent.y));
432         switch (pc->state) {
433             case SP_PENCIL_CONTEXT_IDLE:
434                 /* Releasing button in idle mode means single click */
435                 /* We have already set up start point/anchor in button_press */
436                 if (!(revent.state & GDK_CONTROL_MASK)) {
437                     // Ctrl+click creates a single point so only set context in ADDLINE mode when Ctrl isn't pressed
438                     pc->state = SP_PENCIL_CONTEXT_ADDLINE;
439                 }
440                 ret = TRUE;
441                 break;
442             case SP_PENCIL_CONTEXT_ADDLINE:
443                 /* Finish segment now */
444                 if (anchor) {
445                     p = anchor->dp;
446                 } else {
447                     spdc_endpoint_snap(pc, p, revent.state);
448                 }
449                 pc->ea = anchor;
450                 spdc_set_endpoint(pc, p);
451                 spdc_finish_endpoint(pc);
452                 pc->state = SP_PENCIL_CONTEXT_IDLE;
453                 ret = TRUE;
454                 break;
455             case SP_PENCIL_CONTEXT_FREEHAND:
456                 if (revent.state & GDK_MOD1_MASK) {
457                     /* sketch mode: interpolate the sketched path and improve the current output path with the new interpolation. don't finish sketch */
458                     if (anchor) {
459                         p = anchor->dp;
460                     }
461                     pc->ea = anchor;
463                     if (pc->green_anchor) {
464                         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
465                     }
467                     sketch_interpolate(pc);
469                     pc->state = SP_PENCIL_CONTEXT_SKETCH;
470                 } else {
471                     /* Finish segment now */
472                     /// \todo fixme: Clean up what follows (Lauris)
473                     if (anchor) {
474                         p = anchor->dp;
475                     }
476                     pc->ea = anchor;
477                     /* Write curves to object */
479                     dt->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand"));
481                     interpolate(pc);
482                     spdc_concat_colors_and_flush(pc, FALSE);
483                     pc->sa = NULL;
484                     pc->ea = NULL;
485                     if (pc->green_anchor) {
486                         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
487                     }
488                     pc->state = SP_PENCIL_CONTEXT_IDLE;
489                 }
490                 ret = TRUE;
491                 break;
492             case SP_PENCIL_CONTEXT_SKETCH:
493             default:
494                 break;
495         }
497         if (pc->grab) {
498             /* Release grab now */
499             sp_canvas_item_ungrab(pc->grab, revent.time);
500             pc->grab = NULL;
501         }
503         ret = TRUE;
504     }
505     return ret;
508 static void
509 pencil_cancel (SPPencilContext *const pc) 
511     if (pc->grab) {
512         /* Release grab now */
513         sp_canvas_item_ungrab(pc->grab, 0);
514         pc->grab = NULL;
515     }
517     pc->is_drawing = false;
519     pc->state = SP_PENCIL_CONTEXT_IDLE;
521     pc->red_curve->reset();
522     sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
523     while (pc->green_bpaths) {
524         gtk_object_destroy(GTK_OBJECT(pc->green_bpaths->data));
525         pc->green_bpaths = g_slist_remove(pc->green_bpaths, pc->green_bpaths->data);
526     }
527     pc->green_curve->reset();
528     if (pc->green_anchor) {
529         pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
530     }
532     pc->_message_context->clear();
533     pc->_message_context->flash(Inkscape::NORMAL_MESSAGE, _("Drawing cancelled"));
535     sp_canvas_end_forced_full_redraws(pc->desktop->canvas);
538 static gint
539 pencil_handle_key_press(SPPencilContext *const pc, guint const keyval, guint const state)
541     gint ret = FALSE;
542     switch (keyval) {
543         case GDK_Up:
544         case GDK_Down:
545         case GDK_KP_Up:
546         case GDK_KP_Down:
547             // Prevent the zoom field from activation.
548             if (!mod_ctrl_only(state)) {
549                 ret = TRUE;
550             }
551             break;
552         case GDK_Escape:
553             if (pc->npoints != 0) {
554                 // if drawing, cancel, otherwise pass it up for deselecting
555                 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
556                     pencil_cancel (pc);
557                     ret = TRUE;
558                 }
559             }
560             break;
561         case GDK_z:
562         case GDK_Z:
563             if (mod_ctrl_only(state) && pc->npoints != 0) {
564                 // if drawing, cancel, otherwise pass it up for undo
565                 if (pc->state != SP_PENCIL_CONTEXT_IDLE) {
566                     pencil_cancel (pc);
567                     ret = TRUE;
568                 }
569             }
570             break;
571         case GDK_g:
572         case GDK_G:
573             if (mod_shift_only(state)) {
574                 sp_selection_to_guides(SP_EVENT_CONTEXT(pc)->desktop);
575                 ret = true;
576             }
577             break;
578         case GDK_Alt_L:
579         case GDK_Alt_R:
580         case GDK_Meta_L:
581         case GDK_Meta_R:
582             if (pc->state == SP_PENCIL_CONTEXT_IDLE) {
583                 pc->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("<b>Sketch mode</b>: holding <b>Alt</b> interpolates between sketched paths. Release <b>Alt</b> to finalize."));
584             }
585             break;
586         default:
587             break;
588     }
589     return ret;
592 static gint
593 pencil_handle_key_release(SPPencilContext *const pc, guint const keyval, guint const /*state*/)
595     gint ret = FALSE;
596     switch (keyval) {
597         case GDK_Alt_L:
598         case GDK_Alt_R:
599         case GDK_Meta_L:
600         case GDK_Meta_R:
601             if (pc->state == SP_PENCIL_CONTEXT_SKETCH) {
602                 spdc_concat_colors_and_flush(pc, FALSE);
603                 pc->sketch_n = 0;
604                 pc->sa = NULL;
605                 pc->ea = NULL;
606                 if (pc->green_anchor) {
607                     pc->green_anchor = sp_draw_anchor_destroy(pc->green_anchor);
608                 }
609                 pc->state = SP_PENCIL_CONTEXT_IDLE;
610                 pc->desktop->messageStack()->flash(Inkscape::NORMAL_MESSAGE, _("Finishing freehand sketch"));
611                 ret = TRUE;
612             }
613             break;
614         default:
615             break;
616     }
617     return ret;
620 /**
621  * Reset points and set new starting point.
622  */
623 static void
624 spdc_set_startpoint(SPPencilContext *const pc, Geom::Point const p)
626     pc->npoints = 0;
627     pc->red_curve_is_valid = false;
628     if (in_svg_plane(p)) {
629         pc->p[pc->npoints++] = p;
630     }
633 /**
634  * Change moving endpoint position.
635  * <ul>
636  * <li>Ctrl constrains to moving to H/V direction, snapping in given direction.
637  * <li>Otherwise we snap freely to whatever attractors are available.
638  * </ul>
639  *
640  * Number of points is (re)set to 2 always, 2nd point is modified.
641  * We change RED curve.
642  */
643 static void
644 spdc_set_endpoint(SPPencilContext *const pc, Geom::Point const p)
646     if (pc->npoints == 0) {
647         return;
648         /* May occur if first point wasn't in SVG plane (e.g. weird w2d transform, perhaps from bad
649          * zoom setting).
650          */
651     }
652     g_return_if_fail( pc->npoints > 0 );
654     pc->red_curve->reset();
655     if ( ( p == pc->p[0] )
656          || !in_svg_plane(p) )
657     {
658         pc->npoints = 1;
659     } else {
660         pc->p[1] = p;
661         pc->npoints = 2;
663         pc->red_curve->moveto(pc->p[0]);
664         pc->red_curve->lineto(pc->p[1]);
665         pc->red_curve_is_valid = true;
667         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
668     }
671 /**
672  * Finalize addline.
673  *
674  * \todo
675  * fixme: I'd like remove red reset from concat colors (lauris).
676  * Still not sure, how it will make most sense.
677  */
678 static void
679 spdc_finish_endpoint(SPPencilContext *const pc)
681     if ( ( pc->red_curve->is_empty() )
682          || ( *(pc->red_curve->first_point()) == *(pc->red_curve->second_point())   ) )
683     {
684         pc->red_curve->reset();
685         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), NULL);
686     } else {
687         /* Write curves to object. */
688         spdc_concat_colors_and_flush(pc, FALSE);
689         pc->sa = NULL;
690         pc->ea = NULL;
691     }
695 static void
696 spdc_add_freehand_point(SPPencilContext *pc, Geom::Point p, guint /*state*/)
698     g_assert( pc->npoints > 0 );
699     g_return_if_fail(unsigned(pc->npoints) < G_N_ELEMENTS(pc->p));
701     if ( ( p != pc->p[ pc->npoints - 1 ] )
702          && in_svg_plane(p) )
703     {
704         pc->ps.push_back(p);
705         pc->p[pc->npoints++] = p;
706         fit_and_split(pc);
707     }
710 static inline double
711 square(double const x)
713     return x * x;
716 static void
717 interpolate(SPPencilContext *pc)
720     g_assert( pc->ps.size() > 1 );
722     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
723     double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
724     double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() * 
725                                                tol) * exp(0.2*tol - 2);
727     g_assert(is_zero(pc->req_tangent)
728              || is_unit_vector(pc->req_tangent));
729     Geom::Point const tHatEnd(0, 0);
731     guint n_points  = pc->ps.size();
732     pc->green_curve->reset();
733     pc->red_curve->reset();
734     pc->red_curve_is_valid = false;
736     Geom::Point * b = g_new(Geom::Point, 4*n_points);
737     Geom::Point * points = g_new(Geom::Point, 4*n_points);
738     for (unsigned int i = 0; i < pc->ps.size(); i++) { 
739         points[i] = pc->ps[i];
740     }
742     // worst case gives us a segment per point
743     int max_segs = 4*n_points;
745     int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
746                                              tolerance_sq, max_segs);
748     if ( n_segs > 0)
749     {
750         /* Fit and draw and reset state */
751         pc->green_curve->moveto(b[0]);
752         for (int c = 0; c < n_segs; c++) { 
753             pc->green_curve->curveto(b[4*c+1], b[4*c+2], b[4*c+3]);
754         }
755         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
757         /* Fit and draw and copy last point */
758         g_assert(!pc->green_curve->is_empty());
760         /* Set up direction of next curve. */
761         {
762             Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
763             g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
764             pc->p[0] = last_seg->finalPoint();
765             pc->npoints = 1;
766             Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
767             pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
768                                 ? Geom::Point(0, 0)
769                                 : Geom::unit_vector(req_vec) );
770         }
771     }
772     g_free(b);
773     g_free(points);
774     pc->ps.clear();
778 /* interpolates the sketched curve and tweaks the current sketch interpolation*/
779 static void
780 sketch_interpolate(SPPencilContext *pc)
782     g_assert( pc->ps.size() > 1 );
784     Inkscape::Preferences *prefs = Inkscape::Preferences::get();
785     double const tol = prefs->getDoubleLimited("/tools/freehand/pencil/tolerance", 10.0, 1.0, 100.0) * 0.4;
786     double const tolerance_sq = 0.02 * square( pc->desktop->w2d().descrim() * 
787                                                tol) * exp(0.2*tol - 2);
789     bool average_all_sketches = prefs->getBool("/tools/freehand/pencil/average_all_sketches", true);
791     g_assert(is_zero(pc->req_tangent)
792              || is_unit_vector(pc->req_tangent));
793     Geom::Point const tHatEnd(0, 0);
795     guint n_points  = pc->ps.size();
796     pc->red_curve->reset();
797     pc->red_curve_is_valid = false;
799     Geom::Point * b = g_new(Geom::Point, 4*n_points);
800     Geom::Point * points = g_new(Geom::Point, 4*n_points);
801     for (unsigned i = 0; i < pc->ps.size(); i++) { 
802         points[i] = pc->ps[i];
803     }
805     // worst case gives us a segment per point
806     int max_segs = 4*n_points;
808     int const n_segs = Geom::bezier_fit_cubic_r(b, points, n_points,
809                                              tolerance_sq, max_segs);
811     if ( n_segs > 0)
812     {
813         Geom::Path fit(b[0]);
814         for (int c = 0; c < n_segs; c++) { 
815             fit.appendNew<Geom::CubicBezier>(b[4*c+1], b[4*c+2], b[4*c+3]);
816         }
817         Geom::Piecewise<Geom::D2<Geom::SBasis> > fit_pwd2 = fit.toPwSb();
819         double t =0.;
820         if ( pc->sketch_n > 0 ) {
821             if (average_all_sketches) {
822                 // Average = (sum of all) / n
823                 //         = (sum of all + new one) / n+1
824                 //         = ((old average)*n + new one) / n+1
825                 t = pc->sketch_n / (pc->sketch_n + 1.);
826             } else {
827                 t = 0.5;
828             }
829         }
830         pc->sketch_interpolation = Geom::lerp(fit_pwd2, pc->sketch_interpolation, t);
831         pc->sketch_n++;
833         pc->green_curve->reset();
834         pc->green_curve->set_pathvector(Geom::path_from_piecewise(pc->sketch_interpolation, 0.01));
835         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->green_curve);
837         /* Fit and draw and copy last point */
838         g_assert(!pc->green_curve->is_empty());
840         /* Set up direction of next curve. */
841         {
842             Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->green_curve->last_segment());
843             g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
844             pc->p[0] = last_seg->finalPoint();
845             pc->npoints = 1;
846             Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
847             pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
848                                 ? Geom::Point(0, 0)
849                                 : Geom::unit_vector(req_vec) );
850         }
851     }
852     g_free(b);
853     g_free(points);
854     pc->ps.clear();
857 static void
858 fit_and_split(SPPencilContext *pc)
860     g_assert( pc->npoints > 1 );
862     double const tolerance_sq = 0;
864     Geom::Point b[4];
865     g_assert(is_zero(pc->req_tangent)
866              || is_unit_vector(pc->req_tangent));
867     Geom::Point const tHatEnd(0, 0);
868     int const n_segs = Geom::bezier_fit_cubic_full(b, NULL, pc->p, pc->npoints,
869                                                 pc->req_tangent, tHatEnd, 
870                                                 tolerance_sq, 1);
871     if ( n_segs > 0
872          && unsigned(pc->npoints) < G_N_ELEMENTS(pc->p) )
873     {
874         /* Fit and draw and reset state */
875         pc->red_curve->reset();
876         pc->red_curve->moveto(b[0]);
877         pc->red_curve->curveto(b[1], b[2], b[3]);
878         sp_canvas_bpath_set_bpath(SP_CANVAS_BPATH(pc->red_bpath), pc->red_curve);
879         pc->red_curve_is_valid = true;
880     } else {
881         /* Fit and draw and copy last point */
883         g_assert(!pc->red_curve->is_empty());
885         /* Set up direction of next curve. */
886         {
887             Geom::CubicBezier const * last_seg = dynamic_cast<Geom::CubicBezier const *>(pc->red_curve->last_segment());
888             g_assert( last_seg );      // Relevance: validity of (*last_seg)[2]
889             pc->p[0] = last_seg->finalPoint();
890             pc->npoints = 1;
891             Geom::Point const req_vec( pc->p[0] - (*last_seg)[2] );
892             pc->req_tangent = ( ( Geom::is_zero(req_vec) || !in_svg_plane(req_vec) )
893                                 ? Geom::Point(0, 0)
894                                 : Geom::unit_vector(req_vec) );
895         }
897         pc->green_curve->append_continuous(pc->red_curve, 0.0625);
898         SPCurve *curve = pc->red_curve->copy();
900         /// \todo fixme:
901         SPCanvasItem *cshape = sp_canvas_bpath_new(sp_desktop_sketch(pc->desktop), curve);
902         curve->unref();
903         sp_canvas_bpath_set_stroke(SP_CANVAS_BPATH(cshape), pc->green_color, 1.0, SP_STROKE_LINEJOIN_MITER, SP_STROKE_LINECAP_BUTT);
905         pc->green_bpaths = g_slist_prepend(pc->green_bpaths, cshape);
907         pc->red_curve_is_valid = false;
908     }
912 /*
913   Local Variables:
914   mode:c++
915   c-file-style:"stroustrup"
916   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
917   indent-tabs-mode:nil
918   fill-column:99
919   End:
920 */
921 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :